import { readFileSync } from "node:fs"; import { convertV4MiniflareOptions, Miniflare } from "miniflare"; import { accountStore, d1AccountStore } from "@/lib/account-store"; import { sessionUser, type AccountUser } from "@/lib/session-server"; import { GET, POST } from "./[section]/route"; jest.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: jest.fn() })); jest.mock("@/lib/session-server", () => ({ sessionUser: jest.fn() })); jest.mock("@/lib/account-store", () => ({ ...jest.requireActual("@/lib/account-store"), accountStore: jest.fn(), })); const url = "https://becomeapro.ai/api/account/"; const ownerId = "owner"; const otherId = "other"; const lesson = "electrical/how-circuits-work"; const context = (section: string) => ({ params: Promise.resolve({ section }) }); const user = (id: string): AccountUser => ({ id, name: "Test user", email: id + "@example.test", emailVerified: true, createdAt: new Date("2026-11-25T00:00:00.000Z"), updatedAt: new Date("2026-11-25T00:00:00.000Z"), }); let runtime: Miniflare; let db: Awaited>; beforeAll(async () => { runtime = new Miniflare(convertV4MiniflareOptions({ modules: true, script: "export default { fetch() { return new Response(); } }", compatibilityDate: "2026-07-30", d1Databases: ["ACCOUNTS_DB"], })); db = await runtime.getD1Database("ACCOUNTS_DB"); const schema = ["0001_accounts.sql"].map((file) => readFileSync(`d1/migrations/${file}`, "utf-8")).join(";"); const statements = schema.split(";").map((sql) => sql.replace(/^--.*$/gm, "").trim()).filter(Boolean); await db.batch(statements.map((sql) => db.prepare(sql))); jest.mocked(accountStore).mockImplementation((current) => d1AccountStore(db, current)); }); afterAll(async () => { await runtime?.dispose(); }); function asUser(id: string | null) { jest.mocked(sessionUser).mockResolvedValue(id ? user(id) : null); } function change(section: string, body: object, origin = "https://becomeapro.ai") { return POST(new Request(url + section, { method: "POST", body: JSON.stringify(body), headers: { origin }, }), context(section)); } function read(section: string) { return GET(new Request(url + section), context(section)); } test("account routes refuse anonymous reads and cross-origin writes", async () => { asUser(null); const result = await read("saved"); expect(result.status).toBe(401); expect(result.headers.get("Cache-Control")).toBe("private, no-store"); asUser(ownerId); expect((await change("saved", { key: lesson, saved: true }, "https://example.invalid")).status).toBe(403); }); test("D1 preserves account isolation, idempotent saves, and lesson activity", async () => { asUser(ownerId); expect((await change("saved", { key: lesson, saved: true, user_id: otherId })).status).toBe(200); expect((await change("saved", { key: lesson, saved: true })).status).toBe(200); expect(await (await read("saved")).json()).toEqual({ data: [lesson] }); expect((await change("progress", { keys: [lesson], completed: true })).status).toBe(200); expect((await change("view", { key: lesson })).status).toBe(200); expect((await change("view", { key: lesson })).status).toBe(200); expect(await (await read("progress")).json()).toEqual({ data: [lesson] }); expect(await db.prepare("SELECT view_count, first_viewed_at FROM tutorial_activity WHERE user_id = ?") .bind(ownerId).first()).toMatchObject({ view_count: 2, first_viewed_at: expect.any(String) }); asUser(otherId); expect((await change("saved", { key: lesson, saved: false, user_id: ownerId })).status).toBe(200); expect(await (await read("saved")).json()).toEqual({ data: [] }); expect(await (await read("progress")).json()).toEqual({ data: [] }); asUser(ownerId); expect(await (await read("saved")).json()).toEqual({ data: [lesson] }); expect((await change("progress", { keys: [lesson], completed: false })).status).toBe(200); expect(await (await read("progress")).json()).toEqual({ data: [] }); });