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://airesourcepro.com/api/account/"; const ownerId = "owner"; const otherId = "other"; const tutorial = "claude/claude-guide"; 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", "0004_ai_surveys.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://airesourcepro.com") { 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: tutorial, saved: true }, "https://example.invalid")).status).toBe(403); }); test("D1 preserves account isolation, idempotent saves, and tutorial activity", async () => { asUser(ownerId); expect((await change("saved", { key: tutorial, saved: true, user_id: otherId })).status).toBe(200); expect((await change("saved", { key: tutorial, saved: true })).status).toBe(200); expect(await (await read("saved")).json()).toEqual({ data: [tutorial] }); const profile = { goals: ["code"], tracks: ["claude"], level: "Beginner", weeklyTime: "light", format: "both" }; expect((await change("profile", { profile })).status).toBe(200); expect((await (await read("profile")).json()).data).toMatchObject(profile); expect((await change("progress", { keys: [tutorial], completed: true })).status).toBe(200); expect((await change("view", { key: tutorial })).status).toBe(200); expect((await change("view", { key: tutorial })).status).toBe(200); expect(await (await read("progress")).json()).toEqual({ data: [tutorial] }); 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: tutorial, saved: false, user_id: ownerId })).status).toBe(200); expect(await (await read("saved")).json()).toEqual({ data: [] }); expect(await (await read("profile")).json()).toEqual({ data: null }); expect(await (await read("progress")).json()).toEqual({ data: [] }); asUser(ownerId); expect(await (await read("saved")).json()).toEqual({ data: [tutorial] }); expect((await change("progress", { keys: [tutorial], completed: false })).status).toBe(200); expect(await (await read("progress")).json()).toEqual({ data: [] }); }); test("AI survey answers are validated, private to each account, editable and deletable", async () => { asUser(ownerId); expect(await (await read("survey")).json()).toEqual({ data: null }); const survey = { role: "researcher", uses: ["robotics", "drug", "other", "made-up"], usesOther: " Materials science ", tools: ["claude", "claude"], dailyHours: "3-6h", aiYears: "2-3y", depth: "fine-tune", coding: "bogus", }; expect((await change("survey", { survey, user_id: otherId })).status).toBe(200); const saved = (await (await read("survey")).json()).data; expect(saved).toMatchObject({ role: "researcher", uses: ["robotics", "drug", "other"], usesOther: "Materials science", tools: ["claude"], dailyHours: "3-6h", aiYears: "2-3y", depth: "fine-tune", updatedAt: expect.any(String), }); expect(saved.coding).toBeUndefined(); expect((await change("survey", { survey: "nope" })).status).toBe(400); asUser(otherId); expect(await (await read("survey")).json()).toEqual({ data: null }); expect((await change("survey", { survey: null })).status).toBe(200); asUser(ownerId); expect((await (await read("survey")).json()).data).toMatchObject({ role: "researcher" }); expect((await change("survey", { survey: { ...survey, role: "student" } })).status).toBe(200); expect((await (await read("survey")).json()).data).toMatchObject({ role: "student" }); expect((await change("survey", { survey: null })).status).toBe(200); expect(await (await read("survey")).json()).toEqual({ data: null }); });