import { beforeEach, describe, expect, it, vi } from "vitest"; import { UPLOAD_DIR, saveImageBytes } from "@/lib/files"; import { makeImage } from "../helpers/fixtures"; import { describeDb, filesIn, makeBook, makeEntity, makeEvent, makeRelation, makeUser, prisma, resetAll } from "../helpers/db"; // Här används den riktiga inloggningskontrollen (session.ts). Bara själva inloggningen, cache och // omdirigeringar ersätts, så att åtgärderna kan köras utan webbserver. const login = vi.hoisted(() => ({ userId: "" as string })); vi.mock("@/auth", () => ({ auth: async () => (login.userId ? { user: { id: login.userId } } : null) })); vi.mock("next/cache", () => ({ revalidatePath: () => undefined })); vi.mock("next/navigation", () => ({ redirect: (to: string) => { throw new Error(`REDIRECT:${to}`); }, notFound: () => { throw new Error("NOT_FOUND"); }, })); vi.mock("@/i18n/server", async () => { const core = await import("@/i18n/core"); return { getLocale: async () => "sv", getT: async () => ({ locale: "sv", t: core.makeT(core.dictionaries.sv) }) }; }); import { deleteBook, updateBook } from "@/actions/books"; import { deleteEntity, saveEntity } from "@/actions/entities"; import { addEvent } from "@/actions/events"; import { addRelation } from "@/actions/relations"; import { changeMemberRole, leaveSharedBook, removeBookMember, shareBook } from "@/actions/sharing"; import { emptyTrash, purgeTrash, restoreTrashEntity } from "@/actions/trash"; import { saveTemplate } from "@/actions/templates"; import { GET as exportBook } from "@/app/api/books/[bookId]/export/route"; import { GET as searchBook } from "@/app/api/books/[bookId]/search/route"; import { bookAccess } from "@/lib/book-access"; import { listMembers } from "@/lib/sharing"; const form = (fields: Record) => { const data = new FormData(); for (const [key, value] of Object.entries(fields)) for (const v of Array.isArray(value) ? value : [value]) data.append(key, v); return data; }; /** Kör en åtgärd. Returnerar "ok" om den gick igenom, annars vad som hände (omdirigering eller 404). */ async function attempt(run: () => Promise): Promise { try { await run(); return "ok"; } catch (error) { const message = error instanceof Error ? error.message : String(error); if (message.startsWith("REDIRECT:") || message === "NOT_FOUND") return message; throw error; } } describeDb("delning av böcker", () => { let owner: { id: string }; let admin: { id: string }; let editor: { id: string }; let viewer: { id: string }; let stranger: { id: string }; let bookId: string; const as = (user: { id: string }) => { login.userId = user.id; }; beforeEach(async () => { await resetAll(); owner = await makeUser("Ägare"); admin = await makeUser("Admin"); editor = await makeUser("Redaktör"); viewer = await makeUser("Läsare"); stranger = await makeUser("Obehörig"); bookId = (await makeBook(owner.id, "Delad bok")).id; await prisma.bookMember.createMany({ data: [ { bookId, userId: admin.id, role: "ADMIN" }, { bookId, userId: editor.id, role: "EDITOR" }, { bookId, userId: viewer.id, role: "VIEWER" }, ], }); }); describe("åtkomst", () => { it("ger rätt roll åt ägare, medlemmar och ingen alls åt andra", async () => { expect((await bookAccess(bookId, owner.id))?.role).toBe("OWNER"); expect((await bookAccess(bookId, admin.id))?.role).toBe("ADMIN"); expect((await bookAccess(bookId, editor.id))?.role).toBe("EDITOR"); expect((await bookAccess(bookId, viewer.id))?.role).toBe("VIEWER"); expect(await bookAccess(bookId, stranger.id)).toBeNull(); expect(await bookAccess("finns-inte", owner.id)).toBeNull(); }); it("boken ligger kvar hos ägaren och medlemskapet försvinner med boken eller användaren", async () => { await prisma.user.delete({ where: { id: editor.id } }); expect(await prisma.bookMember.count({ where: { bookId } })).toBe(2); await prisma.book.delete({ where: { id: bookId } }); expect(await prisma.bookMember.count()).toBe(0); }); }); describe("vad varje roll får göra", () => { const create = (name: string) => saveEntity(form({ bookId, kind: "CHARACTER", name })); it("läsare kan läsa men inte skriva", async () => { as(viewer); expect(await attempt(() => create("Ny"))).toBe("NOT_FOUND"); expect(await attempt(() => addRelation(form({ bookId, fromId: "a", toId: "b", type: "x" })))).toBe("NOT_FOUND"); expect(await attempt(() => addEvent(form({ bookId, title: "x", date: "2000" })))).toBe("NOT_FOUND"); expect(await prisma.entity.count()).toBe(0); // Läsning och export fungerar const res = await exportBook(new Request("http://x/api"), { params: Promise.resolve({ bookId }) }); expect(res.status).toBe(200); }); it("redaktörer skriver som ägaren men administrerar inte", async () => { as(editor); expect(await attempt(() => create("Anna"))).toMatch(/^REDIRECT:/); const anna = await prisma.entity.findFirstOrThrow({ where: { bookId } }); expect(anna.updatedById).toBe(editor.id); expect(await attempt(() => updateBook(form({ bookId, title: "Ny titel" })))).toBe("NOT_FOUND"); expect(await attempt(() => saveTemplate(form({ bookId, kind: "CHARACTER", fields: "[]" })))).toBe("NOT_FOUND"); expect(await attempt(() => shareBook(form({ bookId, email: "x@example.com", role: "VIEWER" })))).toBe("NOT_FOUND"); expect(await attempt(() => deleteBook(form({ bookId })))).toBe("NOT_FOUND"); expect((await prisma.book.findUniqueOrThrow({ where: { id: bookId } })).title).toBe("Delad bok"); }); it("administratörer ändrar bokens uppgifter och delar den, men tar inte bort den", async () => { as(admin); expect(await attempt(() => updateBook(form({ bookId, title: "Nytt namn" })))).toBe("ok"); expect((await prisma.book.findUniqueOrThrow({ where: { id: bookId } })).title).toBe("Nytt namn"); expect(await attempt(() => deleteBook(form({ bookId })))).toBe("NOT_FOUND"); expect(await prisma.book.count()).toBe(1); }); it("bara ägaren tar bort boken, och den hamnar i ägarens papperskorg", async () => { as(owner); expect(await attempt(() => deleteBook(form({ bookId })))).toBe("REDIRECT:/"); expect(await prisma.book.count()).toBe(0); expect(await prisma.trashItem.count({ where: { ownerId: owner.id, kind: "book" } })).toBe(1); }); it("obehöriga får 404 överallt, även för export och sök", async () => { as(stranger); expect(await attempt(() => create("Intrång"))).toBe("NOT_FOUND"); expect(await attempt(() => updateBook(form({ bookId, title: "x" })))).toBe("NOT_FOUND"); expect((await exportBook(new Request("http://x/api"), { params: Promise.resolve({ bookId }) })).status).toBe(404); expect((await searchBook(new Request("http://x/api?q=anna"), { params: Promise.resolve({ bookId }) })).status).toBe(404); }); it("sök fungerar för medlemmar", async () => { await makeEntity(bookId, "CHARACTER", "Annika"); as(viewer); const res = await searchBook(new Request("http://x/api?q=anni"), { params: Promise.resolve({ bookId }) }); expect(res.status).toBe(200); expect(((await res.json()) as { results: unknown[] }).results).toHaveLength(1); }); it("inloggning krävs", async () => { login.userId = ""; expect(await attempt(() => create("Anonym"))).toBe("REDIRECT:/login"); expect((await exportBook(new Request("http://x/api"), { params: Promise.resolve({ bookId }) })).status).toBe(401); }); }); describe("hantera delningen", () => { it("ägaren delar med e-postadress, oavsett stora och små bokstäver", async () => { const friend = await makeUser("Vän", "Vän@Example.com"); as(owner); expect(await attempt(() => shareBook(form({ bookId, email: " vän@example.COM ", role: "EDITOR" })))).toBe("REDIRECT:" + `/books/${bookId}/settings?share=ok`); expect((await prisma.bookMember.findFirstOrThrow({ where: { userId: friend.id } })).role).toBe("EDITOR"); }); it("ger tydliga svar när delningen inte går", async () => { as(owner); const share = (email: string, role = "EDITOR") => attempt(() => shareBook(form({ bookId, email, role }))); expect(await share("ingen@example.com")).toContain("share=not-found"); expect(await share("ägare@example.com")).toContain("share=owner"); expect(await share("redaktör@example.com")).toContain("share=already"); expect(await share("inte-en-adress")).toContain("share=invalid"); expect(await share("läsare@example.com", "SUPER")).toContain("share=invalid"); expect(await prisma.bookMember.count()).toBe(3); }); it("en administratör kan dela som redaktör eller läsare men inte utse administratörer", async () => { const friend = await makeUser("Vän"); as(admin); expect(await attempt(() => shareBook(form({ bookId, email: "vän@example.com", role: "ADMIN" })))).toContain("share=forbidden"); expect(await attempt(() => shareBook(form({ bookId, email: "vän@example.com", role: "VIEWER" })))).toContain("share=ok"); expect((await prisma.bookMember.findFirstOrThrow({ where: { userId: friend.id } })).role).toBe("VIEWER"); }); it("en administratör kan inte röra en annan administratör, ägaren kan", async () => { const second = await makeUser("Admin två"); await prisma.bookMember.create({ data: { bookId, userId: second.id, role: "ADMIN" } }); as(admin); expect(await attempt(() => changeMemberRole(form({ bookId, userId: second.id, role: "VIEWER" })))).toContain("share=forbidden"); expect(await attempt(() => removeBookMember(form({ bookId, userId: second.id })))).toContain("share=forbidden"); expect(await prisma.bookMember.count({ where: { userId: second.id } })).toBe(1); as(owner); expect(await attempt(() => changeMemberRole(form({ bookId, userId: second.id, role: "VIEWER" })))).toContain("share=ok"); expect(await attempt(() => removeBookMember(form({ bookId, userId: second.id })))).toContain("share=ok"); expect(await prisma.bookMember.count({ where: { userId: second.id } })).toBe(0); }); it("redaktörer och läsare kan inte hantera delningen", async () => { for (const user of [editor, viewer]) { as(user); expect(await attempt(() => removeBookMember(form({ bookId, userId: viewer.id })))).toBe("NOT_FOUND"); expect(await attempt(() => changeMemberRole(form({ bookId, userId: viewer.id, role: "ADMIN" })))).toBe("NOT_FOUND"); } expect(await prisma.bookMember.count()).toBe(3); }); it("en medlem kan lämna boken, och ägaren kan inte lämna sin egen", async () => { as(viewer); expect(await attempt(() => leaveSharedBook(form({ bookId })))).toBe("REDIRECT:/"); expect(await bookAccess(bookId, viewer.id)).toBeNull(); as(owner); await attempt(() => leaveSharedBook(form({ bookId }))); expect((await bookAccess(bookId, owner.id))?.role).toBe("OWNER"); }); it("listar ägare och medlemmar", async () => { const { owner: o, members } = await listMembers(bookId); expect(o.id).toBe(owner.id); expect(members.map((m) => [m.user.name, m.role])).toEqual([ ["Admin", "ADMIN"], ["Redaktör", "EDITOR"], ["Läsare", "VIEWER"], ]); }); it("tar bort en delning utan att röra bokens innehåll", async () => { await makeEntity(bookId, "CHARACTER", "Anna"); as(owner); await attempt(() => removeBookMember(form({ bookId, userId: editor.id }))); expect(await prisma.entity.count({ where: { bookId } })).toBe(1); }); }); describe("papperskorgen i en delad bok", () => { it("en redaktör flyttar en post dit under ägarens namn, och återställer den", async () => { const anna = await makeEntity(bookId, "CHARACTER", "Anna"); as(editor); expect(await attempt(() => deleteEntity(form({ bookId, id: anna.id })))).toMatch(/^REDIRECT:/); const item = await prisma.trashItem.findFirstOrThrow(); expect(item).toMatchObject({ ownerId: owner.id, bookId, kind: "entity" }); expect(await attempt(() => restoreTrashEntity(form({ bookId, id: item.id })))).toContain(`/entity/${anna.id}`); expect(await prisma.entity.count({ where: { id: anna.id } })).toBe(1); }); it("läsare kan inte ta bort eller återställa", async () => { const anna = await makeEntity(bookId, "CHARACTER", "Anna"); as(viewer); expect(await attempt(() => deleteEntity(form({ bookId, id: anna.id })))).toBe("NOT_FOUND"); expect(await prisma.entity.count()).toBe(1); }); it("bara administratörer rensar papperskorgen", async () => { const anna = await makeEntity(bookId, "CHARACTER", "Anna"); as(editor); await attempt(() => deleteEntity(form({ bookId, id: anna.id }))); const item = await prisma.trashItem.findFirstOrThrow(); expect(await attempt(() => purgeTrash(form({ bookId, id: item.id })))).toBe("NOT_FOUND"); expect(await attempt(() => emptyTrash(form({ bookId })))).toBe("NOT_FOUND"); expect(await prisma.trashItem.count()).toBe(1); as(admin); expect(await attempt(() => purgeTrash(form({ bookId, id: item.id })))).toBe("ok"); expect(await prisma.trashItem.count()).toBe(0); }); it("en annan boks papperskorg går inte att återställa eller rensa", async () => { const otherBook = await makeBook(stranger.id, "Annans bok"); const secret = await makeEntity(otherBook.id, "CHARACTER", "Hemlig"); const { trashEntity } = await import("@/lib/trash"); await trashEntity(stranger.id, otherBook.id, secret.id); const item = await prisma.trashItem.findFirstOrThrow(); as(editor); // Rätt bok i formuläret men en annan boks post: ingenting återställs expect(await attempt(() => restoreTrashEntity(form({ bookId, id: item.id })))).toContain("restore=failed"); expect(await attempt(() => purgeTrash(form({ bookId, id: item.id })))).toBe("NOT_FOUND"); expect(await prisma.trashItem.count()).toBe(1); expect(await prisma.entity.count({ where: { id: secret.id } })).toBe(0); }); it("borttagna böcker går bara att återställa och rensa för ägaren", async () => { as(owner); await attempt(() => deleteBook(form({ bookId }))); const item = await prisma.trashItem.findFirstOrThrow({ where: { kind: "book" } }); as(admin); await attempt(() => purgeTrash(form({ id: item.id }))); expect(await prisma.trashItem.count()).toBe(1); as(owner); await attempt(() => purgeTrash(form({ id: item.id }))); expect(await prisma.trashItem.count()).toBe(0); }); }); describe("lagring", () => { it("bilder som en redaktör laddar upp räknas på ägaren", async () => { const image = await saveImageBytes(await makeImage(60, 40, "png")); await makeEntity(bookId, "CHARACTER", "Anna", { imageFile: image }); const { userStorageBytes } = await import("@/lib/storage"); expect(await userStorageBytes(owner.id)).toBeGreaterThan(0); expect(await userStorageBytes(editor.id)).toBe(0); expect(await filesIn(UPLOAD_DIR)).toContain(image); }); }); describe("relationer och händelser skrivs av redaktörer", () => { it("sparar vem som gjorde ändringen", async () => { const a = await makeEntity(bookId, "CHARACTER", "A"); const b = await makeEntity(bookId, "CHARACTER", "B"); as(editor); await attempt(() => addEvent(form({ bookId, title: "Möte", date: "2001" }))); expect((await prisma.storyEvent.findFirstOrThrow()).updatedById).toBe(editor.id); await attempt(() => addRelation(form({ bookId, fromId: a.id, toId: b.id, type: "Vänner" }))); expect(await prisma.relation.count()).toBe(1); expect(await makeRelation(bookId, a.id, b.id)).toBeTruthy(); expect(await makeEvent(bookId, "x", "2000")).toBeTruthy(); }); }); });