Inbjudningslänkar, adressuppslag för kartregistret och närvaromärke
Böcker kan delas med en inbjudningslänk (roll, giltighetstid, en eller flera personer, bara en hash sparas). Inloggningen går tillbaka till inbjudan. Kartregistrets markeringar kan få position genom uppslag mot karttjänsten, ett i sekunden. Redigeringsformulär och listor visar vem som har något öppet för redigering. Migrering 0009. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1fd1ce78cb
commit
5c58f70bdd
34 files changed
+1610
-30
No files matched your search
@@ -0,0 +1,281 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createHash } from "node:crypto";
|
||||
import { describeDb, makeBook, makeUser, prisma, resetAll } from "../helpers/db";
|
||||
|
||||
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 { createBookInvite, joinBook, revokeBookInvite } from "@/actions/invites";
|
||||
import { bookAccess } from "@/lib/book-access";
|
||||
import { acceptInvite, createInvite, hashToken, listInvites, newToken, previewInvite, revokeInvite } from "@/lib/invites";
|
||||
|
||||
const form = (fields: Record<string, string>) => {
|
||||
const data = new FormData();
|
||||
for (const [key, value] of Object.entries(fields)) data.append(key, value);
|
||||
return data;
|
||||
};
|
||||
|
||||
async function attempt(run: () => Promise<unknown>): Promise<string> {
|
||||
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("inbjudningslänkar", () => {
|
||||
let owner: { id: string };
|
||||
let admin: { id: string };
|
||||
let editor: { id: string };
|
||||
let guest: { id: string };
|
||||
let bookId: string;
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
const asOwner = { userId: "", role: "OWNER" as const };
|
||||
const make = async (role: "EDITOR" | "VIEWER" | "ADMIN" = "EDITOR", days = 7, maxUses: number | null = 1) => {
|
||||
const result = await createInvite(bookId, { ...asOwner, userId: owner.id }, role, days, maxUses);
|
||||
if (typeof result === "string") throw new Error(result);
|
||||
return result.token;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetAll();
|
||||
owner = await makeUser("Ägare");
|
||||
admin = await makeUser("Admin");
|
||||
editor = await makeUser("Redaktör");
|
||||
guest = await makeUser("Gäst");
|
||||
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" },
|
||||
],
|
||||
});
|
||||
login.userId = owner.id;
|
||||
});
|
||||
|
||||
describe("skapa", () => {
|
||||
it("lagrar bara en hash, och länken är lång och slumpmässig", async () => {
|
||||
const token = await make();
|
||||
expect(token.length).toBeGreaterThanOrEqual(43);
|
||||
expect(newToken()).not.toBe(newToken());
|
||||
const [row] = await prisma.bookInvite.findMany();
|
||||
expect(row.tokenHash).toBe(createHash("sha256").update(token).digest("hex"));
|
||||
expect(row.tokenHash).toBe(hashToken(token));
|
||||
expect(JSON.stringify(row)).not.toContain(token);
|
||||
expect(row).toMatchObject({ bookId, role: "EDITOR", maxUses: 1, usedCount: 0, createdById: owner.id, revokedAt: null });
|
||||
expect(row.expiresAt.getTime()).toBeGreaterThan(Date.now() + 6 * DAY);
|
||||
});
|
||||
|
||||
it("följer samma regler som delning: administratörer bjuder inte in administratörer", async () => {
|
||||
const as = (userId: string, role: "OWNER" | "ADMIN" | "EDITOR" | "VIEWER") => ({ userId, role });
|
||||
expect(await createInvite(bookId, as(admin.id, "ADMIN"), "ADMIN", 7, 1)).toBe("forbidden");
|
||||
expect(typeof (await createInvite(bookId, as(admin.id, "ADMIN"), "VIEWER", 7, 1))).toBe("object");
|
||||
expect(await createInvite(bookId, as(editor.id, "EDITOR"), "VIEWER", 7, 1)).toBe("forbidden");
|
||||
expect(typeof (await createInvite(bookId, as(owner.id, "OWNER"), "ADMIN", 7, null))).toBe("object");
|
||||
});
|
||||
|
||||
it("avvisar ogiltiga giltighetstider och antal", async () => {
|
||||
const as = { userId: owner.id, role: "OWNER" as const };
|
||||
expect(await createInvite(bookId, as, "EDITOR", 3, 1)).toBe("invalid");
|
||||
expect(await createInvite(bookId, as, "EDITOR", 7, 0)).toBe("invalid");
|
||||
expect(await createInvite(bookId, as, "EDITOR", 7, 1.5)).toBe("invalid");
|
||||
expect(await createInvite(bookId, as, "EDITOR", 7, 5000)).toBe("invalid");
|
||||
expect(await prisma.bookInvite.count()).toBe(0);
|
||||
});
|
||||
|
||||
it("städar bort länkar som gått ut för länge sedan", async () => {
|
||||
await prisma.bookInvite.create({ data: { bookId, tokenHash: "gammal", role: "VIEWER", expiresAt: new Date(Date.now() - 40 * DAY) } });
|
||||
await prisma.bookInvite.create({ data: { bookId, tokenHash: "nyligen", role: "VIEWER", expiresAt: new Date(Date.now() - 2 * DAY) } });
|
||||
await make();
|
||||
expect((await prisma.bookInvite.findMany()).map((i) => i.tokenHash).sort()).not.toContain("gammal");
|
||||
expect((await prisma.bookInvite.findMany()).map((i) => i.tokenHash)).toContain("nyligen");
|
||||
});
|
||||
});
|
||||
|
||||
describe("gå med", () => {
|
||||
it("ger medlemskap med länkens roll, och räknar användningen", async () => {
|
||||
const token = await make("VIEWER", 7, null);
|
||||
expect(await acceptInvite(token, guest.id)).toEqual({ result: "joined", bookId });
|
||||
expect((await bookAccess(bookId, guest.id))?.role).toBe("VIEWER");
|
||||
expect((await prisma.bookInvite.findFirstOrThrow()).usedCount).toBe(1);
|
||||
});
|
||||
|
||||
it("en länk för en person kan inte användas av en till", async () => {
|
||||
const token = await make("EDITOR", 7, 1);
|
||||
const other = await makeUser("Annan");
|
||||
expect((await acceptInvite(token, guest.id)).result).toBe("joined");
|
||||
expect((await acceptInvite(token, other.id)).result).toBe("used");
|
||||
expect(await bookAccess(bookId, other.id)).toBeNull();
|
||||
});
|
||||
|
||||
it("av tre som försöker samtidigt med en engångslänk kommer bara en in", async () => {
|
||||
const token = await make("EDITOR", 7, 1);
|
||||
const users = await Promise.all([makeUser("A"), makeUser("B"), makeUser("C")]);
|
||||
const results = await Promise.all(users.map((u) => acceptInvite(token, u.id)));
|
||||
expect(results.filter((r) => r.result === "joined")).toHaveLength(1);
|
||||
expect(await prisma.bookMember.count({ where: { bookId, userId: { in: users.map((u) => u.id) } } })).toBe(1);
|
||||
expect((await prisma.bookInvite.findFirstOrThrow()).usedCount).toBe(1);
|
||||
});
|
||||
|
||||
it("en länk för flera räcker till så många som anges", async () => {
|
||||
const token = await make("VIEWER", 7, 2);
|
||||
const users = await Promise.all([makeUser("A"), makeUser("B"), makeUser("C")]);
|
||||
const results = await Promise.all(users.map((u) => acceptInvite(token, u.id)));
|
||||
expect(results.filter((r) => r.result === "joined")).toHaveLength(2);
|
||||
expect(results.filter((r) => r.result === "used")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("länkar utan gräns räcker så länge de gäller", async () => {
|
||||
const token = await make("VIEWER", 30, null);
|
||||
for (const name of ["A", "B", "C", "D"]) expect((await acceptInvite(token, (await makeUser(name)).id)).result).toBe("joined");
|
||||
expect((await prisma.bookInvite.findFirstOrThrow()).usedCount).toBe(4);
|
||||
});
|
||||
|
||||
it("den som redan har tillgång blir inte ändrad och räknas inte", async () => {
|
||||
const token = await make("VIEWER", 7, 1);
|
||||
expect(await acceptInvite(token, editor.id)).toEqual({ result: "already", bookId });
|
||||
expect(await acceptInvite(token, owner.id)).toEqual({ result: "already", bookId });
|
||||
expect((await bookAccess(bookId, editor.id))?.role).toBe("EDITOR");
|
||||
expect((await prisma.bookInvite.findFirstOrThrow()).usedCount).toBe(0);
|
||||
});
|
||||
|
||||
it("avvisar utgångna, indragna och okända länkar", async () => {
|
||||
const expired = await make();
|
||||
await prisma.bookInvite.updateMany({ data: { expiresAt: new Date(Date.now() - 1000) } });
|
||||
expect((await acceptInvite(expired, guest.id)).result).toBe("expired");
|
||||
|
||||
const revoked = await make();
|
||||
await prisma.bookInvite.updateMany({ where: { tokenHash: hashToken(revoked) }, data: { revokedAt: new Date() } });
|
||||
expect((await acceptInvite(revoked, guest.id)).result).toBe("revoked");
|
||||
|
||||
expect((await acceptInvite("finns-inte", guest.id)).result).toBe("not-found");
|
||||
expect((await acceptInvite("", guest.id)).result).toBe("not-found");
|
||||
expect(await bookAccess(bookId, guest.id)).toBeNull();
|
||||
});
|
||||
|
||||
it("länken slutar gälla när den som skapade den inte längre får bjuda in till rollen", async () => {
|
||||
const as = { userId: admin.id, role: "ADMIN" as const };
|
||||
const made = await createInvite(bookId, as, "EDITOR", 7, null);
|
||||
if (typeof made === "string") throw new Error(made);
|
||||
await prisma.bookMember.update({ where: { bookId_userId: { bookId, userId: admin.id } }, data: { role: "EDITOR" } });
|
||||
expect((await acceptInvite(made.token, guest.id)).result).toBe("forbidden");
|
||||
// Och när hen tagits bort helt
|
||||
await prisma.bookMember.delete({ where: { bookId_userId: { bookId, userId: admin.id } } });
|
||||
expect((await acceptInvite(made.token, guest.id)).result).toBe("forbidden");
|
||||
expect(await bookAccess(bookId, guest.id)).toBeNull();
|
||||
});
|
||||
|
||||
it("länken överlever inte att boken tas bort", async () => {
|
||||
const token = await make();
|
||||
await prisma.book.delete({ where: { id: bookId } });
|
||||
expect((await acceptInvite(token, guest.id)).result).toBe("not-found");
|
||||
});
|
||||
});
|
||||
|
||||
describe("förhandsvisning och lista", () => {
|
||||
it("visar bok, ägare och tillstånd utan att använda länken", async () => {
|
||||
const token = await make("EDITOR", 7, 1);
|
||||
const preview = await previewInvite(token);
|
||||
expect(preview.state).toBe("ok");
|
||||
expect(preview.invite?.book).toMatchObject({ title: "Delad bok", owner: { name: "Ägare" } });
|
||||
expect((await prisma.bookInvite.findFirstOrThrow()).usedCount).toBe(0);
|
||||
expect((await previewInvite("nej")).state).toBe("not-found");
|
||||
await acceptInvite(token, guest.id);
|
||||
expect((await previewInvite(token)).state).toBe("used");
|
||||
});
|
||||
|
||||
it("listar bara länkar som går att använda, med vem som skapade dem", async () => {
|
||||
await make("EDITOR", 7, 1);
|
||||
const spent = await make("VIEWER", 7, 1);
|
||||
await acceptInvite(spent, guest.id);
|
||||
const gone = await make("VIEWER", 1, null);
|
||||
await prisma.bookInvite.updateMany({ where: { tokenHash: hashToken(gone) }, data: { revokedAt: new Date() } });
|
||||
const list = await listInvites(bookId);
|
||||
expect(list).toHaveLength(1);
|
||||
expect(list[0]).toMatchObject({ role: "EDITOR", creator: "Ägare", usedCount: 0 });
|
||||
expect(list[0]).not.toHaveProperty("token");
|
||||
});
|
||||
|
||||
it("dra tillbaka: bara de roller man själv får hantera, och den som gått med behåller sin tillgång", async () => {
|
||||
const token = await make("ADMIN", 7, null);
|
||||
const [invite] = await prisma.bookInvite.findMany();
|
||||
expect(await revokeInvite(bookId, "ADMIN", invite.id)).toBe("forbidden");
|
||||
expect(await revokeInvite(bookId, "OWNER", "finns-inte")).toBe("not-found");
|
||||
await acceptInvite(token, guest.id);
|
||||
expect(await revokeInvite(bookId, "OWNER", invite.id)).toBe("ok");
|
||||
expect((await acceptInvite(token, (await makeUser("Sen")).id)).result).toBe("revoked");
|
||||
expect(await bookAccess(bookId, guest.id)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("åtgärderna", () => {
|
||||
it("administratörer skapar länkar, redaktörer och obehöriga får 404", async () => {
|
||||
login.userId = admin.id;
|
||||
const ok = await createBookInvite({ bookId, role: "VIEWER", days: 7, multiple: false });
|
||||
expect(ok).toHaveProperty("token");
|
||||
expect(await createBookInvite({ bookId, role: "ADMIN", days: 7, multiple: false })).toEqual({ error: "forbidden" });
|
||||
expect(await createBookInvite({ bookId, role: "SUPER", days: 7, multiple: false })).toEqual({ error: "invalid" });
|
||||
expect(await createBookInvite({ bookId, role: "VIEWER", days: 5, multiple: false })).toEqual({ error: "invalid" });
|
||||
|
||||
for (const user of [editor, guest]) {
|
||||
login.userId = user.id;
|
||||
expect(await attempt(() => createBookInvite({ bookId, role: "VIEWER", days: 7, multiple: false }))).toBe("NOT_FOUND");
|
||||
}
|
||||
});
|
||||
|
||||
it("länken skapas för en person om inte flera valts", async () => {
|
||||
await createBookInvite({ bookId, role: "EDITOR", days: 1, multiple: false });
|
||||
await createBookInvite({ bookId, role: "EDITOR", days: 30, multiple: true });
|
||||
const rows = await prisma.bookInvite.findMany({ orderBy: { createdAt: "asc" } });
|
||||
expect(rows.map((r) => r.maxUses)).toEqual([1, null]);
|
||||
});
|
||||
|
||||
it("gå med skickar till boken, eller visar varför det inte gick", async () => {
|
||||
const token = await make("EDITOR", 7, 1);
|
||||
login.userId = guest.id;
|
||||
expect(await attempt(() => joinBook(form({ token })))).toBe(`REDIRECT:/books/${bookId}`);
|
||||
expect((await bookAccess(bookId, guest.id))?.role).toBe("EDITOR");
|
||||
|
||||
const other = await makeUser("Sen");
|
||||
login.userId = other.id;
|
||||
expect(await attempt(() => joinBook(form({ token })))).toBe(`REDIRECT:/invite/${token}?result=used`);
|
||||
expect(await attempt(() => joinBook(form({ token: "fel" })))).toBe("REDIRECT:/invite/fel?result=not-found");
|
||||
});
|
||||
|
||||
it("dra tillbaka kräver administratör", async () => {
|
||||
await make("EDITOR", 7, null);
|
||||
const [invite] = await prisma.bookInvite.findMany();
|
||||
login.userId = editor.id;
|
||||
expect(await attempt(() => revokeBookInvite(form({ bookId, inviteId: invite.id })))).toBe("NOT_FOUND");
|
||||
login.userId = admin.id;
|
||||
await revokeBookInvite(form({ bookId, inviteId: invite.id }));
|
||||
expect((await prisma.bookInvite.findFirstOrThrow()).revokedAt).not.toBeNull();
|
||||
});
|
||||
|
||||
it("kan inte dra tillbaka en länk i en annan bok", async () => {
|
||||
const otherBook = await makeBook(guest.id, "Annans");
|
||||
const foreign = await createInvite(otherBook.id, { userId: guest.id, role: "OWNER" }, "VIEWER", 7, null);
|
||||
if (typeof foreign === "string") throw new Error(foreign);
|
||||
const [row] = await prisma.bookInvite.findMany({ where: { bookId: otherBook.id } });
|
||||
await revokeBookInvite(form({ bookId, inviteId: row.id }));
|
||||
expect((await prisma.bookInvite.findUniqueOrThrow({ where: { id: row.id } })).revokedAt).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user