Branchwell

Become a Pro / website · becomeapro.ai / src / app / api / account / account-route.test.ts

Raw 3.9 KB on f63bc385c0fa362af985bfb576a8b5aa2a3df60f
1import { readFileSync } from "node:fs";
2import { convertV4MiniflareOptions, Miniflare } from "miniflare";
3import { accountStore, d1AccountStore } from "@/lib/account-store";
4import { sessionUser, type AccountUser } from "@/lib/session-server";
5import { GET, POST } from "./[section]/route";
6
7jest.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: jest.fn() }));
8jest.mock("@/lib/session-server", () => ({ sessionUser: jest.fn() }));
9jest.mock("@/lib/account-store", () => ({
10 ...jest.requireActual("@/lib/account-store"),
11 accountStore: jest.fn(),
12}));
13
14const url = "https://becomeapro.ai/api/account/";
15const ownerId = "owner";
16const otherId = "other";
17const lesson = "electrical/how-circuits-work";
18const context = (section: string) => ({ params: Promise.resolve({ section }) });
19const user = (id: string): AccountUser => ({
20 id,
21 name: "Test user",
22 email: id + "@example.test",
23 emailVerified: true,
24 createdAt: new Date("2026-11-25T00:00:00.000Z"),
25 updatedAt: new Date("2026-11-25T00:00:00.000Z"),
26});
27
28let runtime: Miniflare;
29let db: Awaited<ReturnType<Miniflare["getD1Database"]>>;
30
31beforeAll(async () => {
32 runtime = new Miniflare(convertV4MiniflareOptions({
33 modules: true,
34 script: "export default { fetch() { return new Response(); } }",
35 compatibilityDate: "2026-07-30",
36 d1Databases: ["ACCOUNTS_DB"],
37 }));
38 db = await runtime.getD1Database("ACCOUNTS_DB");
39 const schema = ["0001_accounts.sql"].map((file) => readFileSync(`d1/migrations/${file}`, "utf-8")).join(";");
40 const statements = schema.split(";").map((sql) => sql.replace(/^--.*$/gm, "").trim()).filter(Boolean);
41 await db.batch(statements.map((sql) => db.prepare(sql)));
42 jest.mocked(accountStore).mockImplementation((current) => d1AccountStore(db, current));
43});
44
45afterAll(async () => { await runtime?.dispose(); });
46
47function asUser(id: string | null) {
48 jest.mocked(sessionUser).mockResolvedValue(id ? user(id) : null);
49}
50
51function change(section: string, body: object, origin = "https://becomeapro.ai") {
52 return POST(new Request(url + section, {
53 method: "POST", body: JSON.stringify(body), headers: { origin },
54 }), context(section));
55}
56
57function read(section: string) {
58 return GET(new Request(url + section), context(section));
59}
60
61test("account routes refuse anonymous reads and cross-origin writes", async () => {
62 asUser(null);
63 const result = await read("saved");
64 expect(result.status).toBe(401);
65 expect(result.headers.get("Cache-Control")).toBe("private, no-store");
66 asUser(ownerId);
67 expect((await change("saved", { key: lesson, saved: true }, "https://example.invalid")).status).toBe(403);
68});
69
70test("D1 preserves account isolation, idempotent saves, and lesson activity", async () => {
71 asUser(ownerId);
72 expect((await change("saved", { key: lesson, saved: true, user_id: otherId })).status).toBe(200);
73 expect((await change("saved", { key: lesson, saved: true })).status).toBe(200);
74 expect(await (await read("saved")).json()).toEqual({ data: [lesson] });
75 expect((await change("progress", { keys: [lesson], completed: true })).status).toBe(200);
76 expect((await change("view", { key: lesson })).status).toBe(200);
77 expect((await change("view", { key: lesson })).status).toBe(200);
78 expect(await (await read("progress")).json()).toEqual({ data: [lesson] });
79 expect(await db.prepare("SELECT view_count, first_viewed_at FROM tutorial_activity WHERE user_id = ?")
80 .bind(ownerId).first()).toMatchObject({ view_count: 2, first_viewed_at: expect.any(String) });
81
82 asUser(otherId);
83 expect((await change("saved", { key: lesson, saved: false, user_id: ownerId })).status).toBe(200);
84 expect(await (await read("saved")).json()).toEqual({ data: [] });
85 expect(await (await read("progress")).json()).toEqual({ data: [] });
86 asUser(ownerId);
87 expect(await (await read("saved")).json()).toEqual({ data: [lesson] });
88 expect((await change("progress", { keys: [lesson], completed: false })).status).toBe(200);
89 expect(await (await read("progress")).json()).toEqual({ data: [] });
90});
91