/** * Paid plans for space (assets/design/shared/SPACE.md "Plans"): the seam a payment company's webhook calls, and the * plan an account holds. No payment company is wired in: the only provider is `fake`, answered only where its secret * is bound (the tests), so on dev and live `POST /v1/plans/` answers 404. What a plan does to the space * holds only under SPACE_RULES `on` (src/space.ts): `off` keeps today's cap whatever the plan. * * The one narrow interface: a provider's adapter checks its own signature, reads its own event, and hands over * [`PlanEvent`]s; [`applyPlanEvent`] lands each on the account's object, which keeps the plan (`space_plan`) and * nothing else of the payment. A plan's size is what `bought` was for: the allowance is the larger of the plan and * the free space with friends, never above 2 TB, never below what was held. */ import type { Env } from "./env.ts"; import { GB } from "./space.ts"; import { json, refuse } from "./http.ts"; import * as accountDelete from "./account_delete.ts"; /** The plans the site offers (cotton-site copy.ts "Price"), each a total, monthly. */ export const PLANS = { "10gb": 10 * GB, "100gb": 100 * GB, "1tb": 1024 * GB, "2tb": 2048 * GB } as const; export type PlanId = keyof typeof PLANS; /** After a plan ends (cancelled, or not renewed), its space still holds this long: a card that failed has time. */ export const GRACE_MS = 30 * 86_400_000; /** The ids of the last events an account took, so a provider's retry lands once. */ export const EVENTS_KEPT = 50; /** What a provider tells, made plain. */ export interface PlanEvent { /** The provider's own event id: the same id lands once. */ id: string; provider: string; /** The provider's subscription id: a plan is one subscription. */ subscription: string; /** The account's slug (`p-`), as the checkout was given it. */ account: string; /** `set`: the plan holds, paid through `paid_through`. `end`: it ended at `at`. */ kind: "set" | "end"; plan?: PlanId; /** ms: the end of the period paid for. */ paid_through?: number; /** ms: when it happened, as the provider says. An older event than the last one taken changes nothing. */ at: number; } /** The plan an account holds (`space_plan` in its object's meta). */ export interface HeldPlan { plan: PlanId; provider: string; subscription: string; paid_through: number; /** ms, once ended; null while it goes on. */ ended_at: number | null; /** ms: the newest event taken. */ at: number; /** The newest event ids taken, at most [`EVENTS_KEPT`]. */ events: string[]; } /** How the plan stands at `now`, and the space it gives. */ export interface PlanState { plan: PlanId; bytes: number; /** `active`: paid for. `grace`: ended or not renewed, its space held until `grace_until`. `ended`: gone. */ status: "active" | "grace" | "ended"; until: number; grace_until: number; } export function isPlan(value: unknown): value is PlanId { return typeof value === "string" && Object.hasOwn(PLANS, value); } /** The plan after `event`; the same plan when the event changes nothing (a retry, an older event, another plan's end). */ export function applied(held: HeldPlan | null, event: PlanEvent): HeldPlan | null { if (held?.events.includes(event.id)) return held; if (held && event.at < held.at) return { ...held, events: kept(held.events, event.id) }; if (event.kind === "set") { if (!isPlan(event.plan) || typeof event.paid_through !== "number") return held; return { plan: event.plan, provider: event.provider, subscription: event.subscription, paid_through: event.paid_through, ended_at: null, at: event.at, events: kept(held?.events ?? [], event.id) }; } // An end for a subscription the account no longer holds (it moved to another plan) ends nothing. if (!held || held.subscription !== event.subscription || held.provider !== event.provider) return held ? { ...held, events: kept(held.events, event.id) } : null; return { ...held, ended_at: event.at, at: event.at, events: kept(held.events, event.id) }; } function kept(events: string[], id: string): string[] { return [...events, id].slice(-EVENTS_KEPT); } /** The plan at `now`: active while paid for and not ended; then a grace of [`GRACE_MS`]; then ended. Nothing is erased in any. */ export function stateOf(held: HeldPlan | null, now: number): PlanState | null { if (!held) return null; const until = held.ended_at !== null ? Math.min(held.ended_at, held.paid_through) : held.paid_through; const grace_until = until + GRACE_MS; const status = now < until ? "active" : now < grace_until ? "grace" : "ended"; return { plan: held.plan, bytes: status === "ended" ? 0 : PLANS[held.plan], status, until, grace_until }; } export function parseHeld(text: string | null): HeldPlan | null { if (!text) return null; try { const held = JSON.parse(text) as HeldPlan; return isPlan(held.plan) ? held : null; } catch { return null; } } // ── providers ──────────────────────────────────────────────────────────── /** A payment company's webhook, read: its signature checked, its events made plain. Null when the signature fails. */ export interface Provider { name: string; /** Whether it is bound on this Worker (its secret set): an unbound provider answers 404. */ bound(env: Env): boolean; read(request: Request, body: string, env: Env): Promise; } async function hmacHex(secret: string, body: string): Promise { const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); const signed = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body))); return [...signed].map((b) => b.toString(16).padStart(2, "0")).join(""); } function sameText(a: string, b: string): boolean { if (a.length !== b.length) return false; let diff = 0; for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); return diff === 0; } /** * The fake provider the tests drive: `x-fake-signature` is the hex HMAC-SHA256 of the body under `PLANS_FAKE_SECRET`; * the body is `{ id, type: "subscription.active" | "subscription.renewed" | "subscription.ended", subscription, * account, plan?, paid_through?, at }` (ISO instants), the shape a real provider's adapter would make of its own. */ export const fake: Provider = { name: "fake", bound: (env) => Boolean(env.PLANS_FAKE_SECRET), async read(request, body, env) { const signature = request.headers.get("x-fake-signature") ?? ""; if (!env.PLANS_FAKE_SECRET || !sameText(signature, await hmacHex(env.PLANS_FAKE_SECRET, body))) return null; const e = JSON.parse(body) as Record; const at = Date.parse(String(e.at)); const kind = e.type === "subscription.ended" ? "end" : e.type === "subscription.active" || e.type === "subscription.renewed" ? "set" : null; if (!kind || typeof e.id !== "string" || typeof e.subscription !== "string" || typeof e.account !== "string" || !Number.isFinite(at)) return []; const event: PlanEvent = { id: e.id, provider: "fake", subscription: e.subscription, account: e.account, kind, at }; if (kind === "set") { if (!isPlan(e.plan)) return []; event.plan = e.plan; event.paid_through = Date.parse(String(e.paid_through)); if (!Number.isFinite(event.paid_through)) return []; } return [event]; }, }; export const PROVIDERS: Record = { fake }; export const PLANS_PATH = /^\/v1\/plans\/([a-z]+)$/; /** `POST /v1/plans/`: the provider's webhook. 404 where the provider is not bound; 401 on a bad signature. */ export async function webhook(request: Request, env: Env, name: string): Promise { const provider = PROVIDERS[name]; if (!provider || !provider.bound(env) || request.method !== "POST") refuse(404, "not_found", "no such route"); const body = await request.text(); let events: PlanEvent[] | null; try { events = await provider.read(request, body, env); } catch { refuse(400, "bad_request", "the event could not be read"); } if (events === null) refuse(401, "bad_signature", "the signature does not match"); const answers = []; for (const event of events) answers.push(await applyPlanEvent(env, event)); return json({ ok: true, events: answers }); } /** THE INTERFACE: one plain event landed on its account. Unknown accounts are said, never made. */ export async function applyPlanEvent(env: Env, event: PlanEvent): Promise<{ id: string; account: string; applied: boolean; plan?: PlanState | null }> { if (!/^p-[a-z0-9-]{1,40}$/.test(event.account) || (await accountDelete.marked(env, event.account))) return { id: event.id, account: event.account, applied: false }; const object = env.BUSINESS.get(env.BUSINESS.idFromName(event.account)); const plan = await object.spacePlanEvent(event); if (plan === undefined) return { id: event.id, account: event.account, applied: false }; return { id: event.id, account: event.account, applied: true, plan }; }