353 lines · 20.0 KB · TypeScriptRaw
import { SELF } from "cloudflare:test";import { resolve } from "../src/index.ts";import { beforeAll, describe, expect, it } from "vitest";import { addDays, localDate, type ActAnswer, type SyncAnswer, type WireRow } from "../src/protocol.ts";import { SHARMILA_FLAVOUR, YOGA_TABLES, YOGA_TOOLS } from "./yoga.ts";const ADMIN = { authorization: "Bearer test-admin-token" };const TODAY = localDate(new Date(), "Asia/Kolkata");interface Answer<T> { status: number; body: T;}async function call<T = Record<string, unknown>>(slug: string, method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<Answer<T>> { const res = await SELF.fetch(`https://example.test/b/${slug}${path}`, { method, headers: { "content-type": "application/json", ...headers }, body: body === undefined ? undefined : JSON.stringify(body), }); return { status: res.status, body: (await res.json()) as T };}async function signIn(slug: string, phone: string, name?: string): Promise<{ credential: string; person: { id: string; role: string } }> { const code = await call<{ challenge_id: string; fixed_code?: string; known?: boolean }>(slug, "POST", "/v1/code", { phone, device_id: `device-${phone}` }); expect(code.status, JSON.stringify(code.body)).toBe(200); expect(code.body.fixed_code, "the object never says the code; the person types the one they know").toBeUndefined(); const signed = await call<{ credential: string; person: { id: string; role: string } }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: `device-${phone}`, name, }); expect(signed.status, JSON.stringify(signed.body)).toBe(200); return signed.body;}function auth(credential: string): Record<string, string> { return { authorization: `Bearer ${credential}` };}async function act(slug: string, credential: string, act: string, args: Record<string, unknown>): Promise<Answer<ActAnswer & { code?: string; message?: string }>> { return call(slug, "POST", "/v1/act", { act, args }, auth(credential));}async function sync(slug: string, credential: string | null, since = 0): Promise<SyncAnswer> { const answer = await call<SyncAnswer>(slug, "GET", `/v1/sync?since=${since}`, undefined, credential ? auth(credential) : {}); expect(answer.status, JSON.stringify(answer.body)).toBe(200); return answer.body;}function rowsOf(rows: WireRow[], table: string): WireRow[] { return rows.filter((r) => r.table === table && !r.deleted);}/** RULE (owner, 24 Oct 2026): a business is JSON and seed data, never code — the real yoga packages install into an empty object and its rows follow. */describe("a business object running the yoga packages", () => { const slug = "studio"; const ids: Record<string, string> = {}; let owner = ""; let anita = ""; let bela = ""; beforeAll(async () => { const business = await call(slug, "PUT", "/v1/admin/business", { name: "Test Studio", currency: "INR", timezone: "Asia/Kolkata", owner_phone: "+91 90000 00001", upi_id: "studio@upi" }, ADMIN); expect(business.status, JSON.stringify(business.body)).toBe(200); const defs = await call(slug, "PUT", "/v1/admin/definitions", { tools: YOGA_TOOLS, tables: YOGA_TABLES, flavour: SHARMILA_FLAVOUR }, ADMIN); expect(defs.status, JSON.stringify(defs.body)).toBe(200); expect(defs.body.tables).toBe(YOGA_TABLES.length + 1); const seeded = await call<{ ids: Record<string, string> }>( slug, "POST", "/v1/admin/import", { rows: [ { ref: "trainer", table: "yoga_trainer", data: { name: "Sharmila", role: "Founder" } }, { ref: "flow", table: "yoga_class", data: { name: "Gentle Vinyasa", category: "daily", capacity: 2, minutes: 60 } }, { ref: "monthly", table: "yoga_offer", data: { name: "Monthly", kind: "time", valid_days: 30, price: 300000, currency: "INR" } }, { ref: "ten", table: "yoga_offer", data: { name: "Ten classes", kind: "classes", classes: 10, valid_days: 60, price: 350000, currency: "INR" } }, { ref: "today", table: "yoga_session", data: { name: "Gentle Vinyasa", class: "@flow", on: TODAY, starts: "07:00", trainer: "@trainer" } }, { ref: "yesterday", table: "yoga_session", data: { name: "Gentle Vinyasa", class: "@flow", on: addDays(TODAY, -1), starts: "07:00", trainer: "@trainer" } }, ], }, ADMIN, ); expect(seeded.status, JSON.stringify(seeded.body)).toBe(200); Object.assign(ids, seeded.body.ids); }); it("serves the definitions verbatim with the business's meta", async () => { const answer = await call<{ business: { name: string; upi_id: string }; tables: { id: string }[]; tools: { id: string }[]; etag: string }>(slug, "GET", "/v1/definitions"); expect(answer.status).toBe(200); expect(answer.body.business.name).toBe("Test Studio"); expect(answer.body.business.upi_id).toBe("studio@upi"); expect(answer.body.tables.map((t) => t.id)).toContain("yoga_booking"); expect(answer.body.tables.map((t) => t.id)).toContain("business_message"); expect(answer.body.tools.map((t) => t.id)).toContain("yoga"); expect(answer.body.etag).toMatch(/^[0-9a-f]{24}$/); }); it("never tells a caller it does not know the owner's number or the database id (AUDIT A H1); the admin is told", async () => { type Meta = { business: { owner_phone?: string | null; database_id?: string | null; upi_id?: string | null } }; const stranger = await call<Meta>(slug, "GET", "/v1/definitions"); expect(stranger.status).toBe(200); expect(stranger.body.business.owner_phone ?? null).toBeNull(); expect(stranger.body.business.database_id ?? null).toBeNull(); expect(JSON.stringify(stranger.body)).not.toContain("90000"); expect(stranger.body.business.upi_id, "the business's payment address stays public").toBe("studio@upi"); const admin = await call<Meta>(slug, "GET", "/v1/definitions", undefined, ADMIN); expect(admin.body.business.owner_phone).toBeTruthy(); }); it("a visitor reads public tables only, without owners", async () => { const snapshot = await sync(slug, null); const tables = new Set(snapshot.rows.map((r) => r.table)); expect(tables).toContain("yoga_session"); expect(tables).toContain("yoga_class"); expect(tables).toContain("yoga_offer"); expect(tables).not.toContain("yoga_member"); expect(tables).not.toContain("yoga_booking"); expect(snapshot.rows.every((r) => !("owner" in r))).toBe(true); expect(snapshot.people).toBeUndefined(); }); it("a code says whether the business knows the phone, so the phone asks a stranger's name once", async () => { const stranger = await call<{ known: boolean }>(slug, "POST", "/v1/code", { phone: "+919000000002", device_id: "device-+919000000002" }); expect(stranger.body.known).toBe(false); await signIn(slug, "+91 90000 00002", "Anita"); const again = await call<{ known: boolean }>(slug, "POST", "/v1/code", { phone: "+919000000002", device_id: "device-+919000000002" }); expect(again.body.known).toBe(true); }); it("phone and OTP sign-in makes a member with their own card; the owner's phone makes the owner", async () => { const a = await signIn(slug, "+91 90000 00002", "Anita"); anita = a.credential; expect(a.person.role).toBe("member"); const mine = await sync(slug, anita); const cards = rowsOf(mine.rows, "yoga_member"); expect(cards).toHaveLength(1); expect(cards[0]!.data.name).toBe("Anita"); expect(cards[0]!.data.phone).toBe("+919000000002"); expect(cards[0]!.owner).toBe(a.person.id); ids.anita = cards[0]!.id; const o = await signIn(slug, "+919000000001", "Sharmila"); owner = o.credential; expect(o.person.role).toBe("owner"); const everything = await sync(slug, owner); expect(everything.people?.map((p) => p.role).sort()).toEqual(["member", "owner"]); const b = await signIn(slug, "+919000000003", "Bela"); bela = b.credential; ids.bela = rowsOf((await sync(slug, bela)).rows, "yoga_member")[0]!.id; }); it("a wrong code or a code from another device is refused", async () => { const code = await call<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: "+919000000009", device_id: "d9" }); const wrong = await call<{ code: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "000000", device_id: "d9" }); expect(wrong.status).toBe(401); expect(wrong.body.code).toBe("invalid_code"); const elsewhere = await call<{ code: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "other" }); expect(elsewhere.status).toBe(401); }); it("members book until the class is full; the booking carries the session's name and day", async () => { const first = await act(slug, anita, "book", { slot: ids.today }); expect(first.status, JSON.stringify(first.body)).toBe(200); expect(first.body.made?.table).toBe("yoga_booking"); const booking = first.body.changed.find((r) => r.table === "yoga_booking")!; expect(booking.data.name).toBe("Gentle Vinyasa"); expect(booking.data.on).toBe(TODAY); expect(booking.data.member).toBe(ids.anita); expect(booking.data.quantity).toBe(1); ids.anitaBooking = booking.id; const second = await act(slug, bela, "book", { slot: ids.today }); expect(second.status, JSON.stringify(second.body)).toBe(200); ids.belaBooking = second.body.made!.id; const c = await signIn(slug, "+919000000004", "Chitra"); const full = await act(slug, c.credential, "book", { slot: ids.today }); expect(full.status).toBe(409); expect(full.body.code).toBe("full"); }); it("a member sees their own booking and not another's; staff see both", async () => { const mine = await sync(slug, anita); const bookings = rowsOf(mine.rows, "yoga_booking"); expect(bookings.map((b) => b.id)).toEqual([ids.anitaBooking]); const all = await sync(slug, owner); expect(rowsOf(all.rows, "yoga_booking").map((b) => b.id).sort()).toEqual([ids.anitaBooking, ids.belaBooking].sort()); }); it("a member cancels only their own booking, and the cursor carries the tombstone", async () => { const before = (await sync(slug, bela)).version; const notYours = await act(slug, bela, "cancel", { id: ids.anitaBooking }); expect(notYours.status).toBe(403); const cancelled = await act(slug, bela, "cancel", { id: ids.belaBooking }); expect(cancelled.status, JSON.stringify(cancelled.body)).toBe(200); expect(cancelled.body.changed[0]!.deleted).toBe(true); const since = await sync(slug, bela, before); expect(since.rows.find((r) => r.id === ids.belaBooking)?.deleted).toBe(true); // The place came back. const again = await act(slug, bela, "book", { slot: ids.today }); expect(again.status, JSON.stringify(again.body)).toBe(200); ids.belaBooking = again.body.made!.id; }); it("a member cannot book yesterday's session away by cancelling, nor run staff acts, nor write rows", async () => { const owner_booking = await act(slug, owner, "book", { slot: ids.yesterday, member: ids.anita }); expect(owner_booking.status, JSON.stringify(owner_booking.body)).toBe(200); const past = await act(slug, anita, "cancel", { id: owner_booking.body.made!.id }); expect(past.status).toBe(409); expect(past.body.code).toBe("past"); const here = await act(slug, anita, "record_act", { table: "yoga_booking", id: ids.anitaBooking, act: "here" }); expect(here.status).toBe(403); const write = await act(slug, anita, "create", { table: "yoga_expense", data: { name: "Rent", amount: 1 } }); expect(write.status).toBe(403); }); it("marking a member here needs a pack with classes left; renewing on a plan runs the plan's days", async () => { const refused = await act(slug, owner, "record_act", { table: "yoga_booking", id: ids.anitaBooking, act: "here" }); expect(refused.status, JSON.stringify(refused.body)).toBe(409); expect(refused.body.code).toBe("ledger_refused"); expect(refused.body.message).toMatch(/No pack has classes left/); const renewed = await act(slug, owner, "record_act", { table: "yoga_member", id: ids.anita, act: "renew", picked: [ids.monthly] }); expect(renewed.status, JSON.stringify(renewed.body)).toBe(200); const pack = renewed.body.changed.filter((r) => r.table === "yoga_pack").at(-1)!; expect(pack.data.bought_on).toBe(TODAY); expect(pack.data.expires).toBe(addDays(TODAY, 29)); expect(pack.data.classes ?? null).toBeNull(); expect(pack.data.plan).toBe(ids.monthly); expect(pack.owner).toBe((await sync(slug, anita)).rows.find((r) => r.id === ids.anita)!.owner); const here = await act(slug, owner, "record_act", { table: "yoga_booking", id: ids.anitaBooking, act: "here" }); expect(here.status, JSON.stringify(here.body)).toBe(200); const attendance = here.body.changed.find((r) => r.table === "yoga_attendance")!; expect(attendance.data.member).toBe(ids.anita); expect(attendance.data.booking).toBe(ids.anitaBooking); expect(attendance.data.attended_on).toBe(TODAY); expect(attendance.data.pack).toBe(pack.id); const booking = here.body.changed.find((r) => r.table === "yoga_booking" && r.id === ids.anitaBooking)!; expect(booking.data.here).toBe(true); const twice = await act(slug, owner, "record_act", { table: "yoga_booking", id: ids.anitaBooking, act: "here" }); expect(twice.status).toBe(409); expect(twice.body.code).toBe("act_not_available"); }); it("a class pack counts its classes down and a staff override records attendance without one", async () => { const renewed = await act(slug, owner, "record_act", { table: "yoga_member", id: ids.bela, act: "renew", picked: [ids.ten] }); expect(renewed.status, JSON.stringify(renewed.body)).toBe(200); const pack = renewed.body.changed.filter((r) => r.table === "yoga_pack").at(-1)!; expect(pack.data.classes).toBe(10); expect(pack.data.expires).toBe(addDays(TODAY, 59)); const here = await act(slug, owner, "record_act", { table: "yoga_booking", id: ids.belaBooking, act: "here" }); expect(here.status, JSON.stringify(here.body)).toBe(200); expect(here.body.changed.find((r) => r.table === "yoga_attendance")!.data.pack).toBe(pack.id); const d = await signIn(slug, "+919000000005", "Divya"); const divya = rowsOf((await sync(slug, d.credential)).rows, "yoga_member")[0]!.id; const walkIn = await act(slug, owner, "record_act", { table: "yoga_member", id: divya, act: "mark_attended" }); expect(walkIn.status).toBe(409); const override = await act(slug, owner, "create", { table: "yoga_attendance", data: { name: "Came", member: divya, staff_override: true } }); expect(override.status, JSON.stringify(override.body)).toBe(200); const row = override.body.changed.find((r) => r.table === "yoga_attendance")!; expect(row.data.attended_on).toBe(TODAY); expect(row.data.pack ?? null).toBeNull(); }); it("taking cash writes a payment dated today, and a member sees their own money only", async () => { const paid = await act(slug, owner, "record_act", { table: "yoga_member", id: ids.anita, act: "take_cash", picked: [300000] }); expect(paid.status, JSON.stringify(paid.body)).toBe(200); const payment = paid.body.changed.find((r) => r.table === "yoga_payment")!; expect(payment.data.amount).toBe(300000); expect(payment.data.method).toBe("cash"); expect(payment.data.currency).toBe("INR"); expect(payment.data.taken_on).toBe(TODAY); const mine = rowsOf((await sync(slug, anita)).rows, "yoga_payment"); expect(mine.map((p) => p.id)).toEqual([payment.id]); expect(rowsOf((await sync(slug, bela)).rows, "yoga_payment")).toHaveLength(0); }); it("messages go from a member to the business and from staff to a person", async () => { const sent = await act(slug, anita, "message", { text: "Can I switch to the 8am class?" }); expect(sent.status, JSON.stringify(sent.body)).toBe(200); const anitaPerson = (await call<{ person: { id: string } }>(slug, "GET", "/v1/me", undefined, auth(anita))).body.person.id; const reply = await act(slug, owner, "message", { text: "Of course, see you at 8.", person: anitaPerson }); expect(reply.status, JSON.stringify(reply.body)).toBe(200); // A pass from nothing carries a table's rows by id, so the thread is read in the order it was written. const thread = rowsOf((await sync(slug, anita)).rows, "business_message").sort((a, b) => a.version - b.version); expect(thread.map((m) => m.data.from)).toEqual(["member", "staff"]); expect(rowsOf((await sync(slug, bela)).rows, "business_message")).toHaveLength(0); }); it("the owner makes staff; staff see everything and sign-out ends a credential", async () => { const made = await act(slug, owner, "set_role", { phone: "+919000000006", role: "staff", name: "Front desk" }); expect(made.status, JSON.stringify(made.body)).toBe(200); const staff = await signIn(slug, "+919000000006"); expect(staff.person.role).toBe("staff"); const all = await sync(slug, staff.credential); expect(rowsOf(all.rows, "yoga_member").length).toBeGreaterThanOrEqual(4); const notOwner = await act(slug, staff.credential, "set_role", { phone: "+919000000007", role: "staff" }); expect(notOwner.status).toBe(403); const out = await call(slug, "POST", "/v1/sign-out", {}, auth(staff.credential)); expect(out.status).toBe(200); const after = await call<{ code: string }>(slug, "GET", "/v1/me", undefined, auth(staff.credential)); expect(after.status).toBe(401); expect(after.body.code).toBe("credential_revoked"); }); it("the export carries everything, and an un-onboarded slug answers 503", async () => { const out = await call<{ rows: WireRow[]; people: unknown[]; tables: unknown[] }>(slug, "GET", "/v1/admin/export", undefined, ADMIN); expect(out.status).toBe(200); expect(out.body.people.length).toBeGreaterThanOrEqual(6); expect(out.body.rows.some((r) => r.table === "yoga_attendance")).toBe(true); const nobody = await call<{ code: string }>(slug, "GET", "/v1/admin/export"); expect(nobody.status).toBe(403); // STRANGER BLIND 2 (24 Nov 2026): a pass where no database is says "sign in first", as a personal database says to a stranger. const empty = await call<{ code: string }>("nobody", "GET", "/v1/sync"); expect(empty.status).toBe(401); expect(empty.body.code).toBe("not_signed_in"); const reset = await call<{ version: number }>(slug, "POST", "/v1/admin/reset", undefined, ADMIN); expect(reset.status).toBe(200); const after = await call<{ rows: WireRow[]; people: unknown[] }>(slug, "GET", "/v1/admin/export", undefined, ADMIN); expect(after.body.rows.length).toBe(0); expect(after.body.people.length).toBe(0); expect((await call(slug, "GET", "/v1/definitions")).status).toBe(200); expect((await call<{ code: string }>(slug, "GET", "/v1/me", undefined, auth(owner))).status).toBe(401); }); it("names the object a host names by its first label", () => { expect(resolve(new URL("https://cotton.example.com/mcp"))).toEqual({ slug: "cotton", path: "/mcp", prefix: "" }); expect(resolve(new URL("https://Cotton.Example.com/v1/definitions"))).toEqual({ slug: "cotton", path: "/v1/definitions", prefix: "" }); expect(resolve(new URL("https://studio.cottondb.com/health"))).toEqual({ slug: "studio", path: "/health", prefix: "" }); expect(resolve(new URL("https://cotton-business.someone.workers.dev/mcp"))).toBeNull(); }); it("names the business from the hostname, and refuses an unnamed host", async () => { const byHost = await SELF.fetch("https://studio.cottondb.com/v1/definitions"); expect(byHost.status).toBe(200); const etag = byHost.headers.get("etag")!; const held = await SELF.fetch("https://studio.cottondb.com/v1/definitions", { headers: { "if-none-match": etag } }); expect(held.status, "a phone holding the definitions is told so without the body").toBe(304); const unnamed = await SELF.fetch("https://cotton-business.someone.workers.dev/v1/definitions"); expect(unnamed.status).toBe(404); const health = await SELF.fetch("https://studio.cottondb.com/health"); expect(health.status).toBe(200); });});