// @vitest-environment node // jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and // the global Uint8Array come from different realms, so signing throws a TypeError. import { getFieldsToSign, getPayload, jwtSign, Payload } from "payload"; import config from "@/payload.config"; import { randomUUID } from "node:crypto"; import { NextRequest } from "next/server"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import type { Role, User } from "@/payload-types"; import type { Permission } from "@/permissions"; import { GET } from "@/app/api/notifications/inbox/route"; import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions"; let payload: Payload; const RUN = `ntfinbox-${Date.now().toString(36)}`; const TIMEOUT = 30_000; /** Build a GET against the inbox route, optionally authenticated + scoped. */ function request(token?: string, scope?: "all" | "mine"): NextRequest { const headers = new Headers(); if (token) headers.set("cookie", `payload-token=${token}`); const url = new URL("http://localhost/api/notifications/inbox"); url.searchParams.set("limit", "12"); url.searchParams.set("sort", "-createdAt"); if (scope) url.searchParams.set("scope", scope); return new NextRequest(url, { headers }); } /** * Mint a payload-token JWT for a user, mirroring the impersonation route: * persist a session on the user doc, then sign with that session's sid. */ async function mintToken(userId: number): Promise { const collection = payload.collections.users.config; const user = await payload.findByID({ collection: "users", id: userId, depth: 0, overrideAccess: true, }); const sid = randomUUID(); const now = new Date(); const expiresAt = new Date(now.getTime() + collection.auth.tokenExpiration * 1000); const sessions = (user.sessions ?? []).filter( (session) => new Date(session.expiresAt).getTime() > now.getTime(), ); sessions.push({ id: sid, createdAt: now.toISOString(), expiresAt: expiresAt.toISOString() }); await payload.update({ collection: "users", id: userId, data: { sessions }, overrideAccess: true, }); const { token } = await jwtSign({ fieldsToSign: getFieldsToSign({ collectionConfig: collection, email: user.email ?? "", sid, user, }), secret: payload.secret, tokenExpiration: collection.auth.tokenExpiration, }); return token; } interface InboxBody { notifications?: Array<{ id: number; isMine?: boolean; ownerName?: string }>; canViewOthers?: boolean; scope?: "all" | "mine"; } describe("notifications inbox scope toggle", () => { const roleIds: number[] = []; const userIds: number[] = []; const notifIds: number[] = []; let adminToken: string; let plainToken: string; let adminNotifId: number; let plainNotifId: number; const makeRole = async (label: string, permissions: Permission[]): Promise => { const role = (await payload.create({ collection: "roles", data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, permissions }, overrideAccess: true, depth: 0, })) as unknown as Role; roleIds.push(role.id); return role; }; const makeUser = async (label: string, roleId: number): Promise => { const user = (await payload.create({ collection: "users", data: { username: `${RUN}-${label}`, discordUsername: `${RUN}-${label}`, displayName: label.toUpperCase(), steamId: `7656119${Math.floor(Math.random() * 1e9)}`, password: "Test123", roleDocs: [roleId], }, overrideAccess: true, depth: 0, })) as unknown as User; userIds.push(user.id); return user; }; const createNotification = async (userId: number): Promise => { const doc = await payload.create({ collection: "user-notifications", data: { user: userId, type: "test:inbox-scope", title: `${RUN} ${userId}`, message: "test", read: false, }, overrideAccess: true, depth: 0, }); notifIds.push(doc.id as number); return doc.id as number; }; beforeAll(async () => { const payloadConfig = await config; payload = await getPayload({ config: payloadConfig }); invalidatePermissionCache(); // The read-all tier is exactly `system:admin-access` (mirrors the collection // access rule); a plain role (no permissions) only ever sees its own rows. const adminRole = await makeRole("admin", ["system:admin-access"]); const plainRole = await makeRole("plain", []); const admin = await makeUser("admin", adminRole.id); const plain = await makeUser("plain", plainRole.id); adminNotifId = await createNotification(admin.id); plainNotifId = await createNotification(plain.id); adminToken = await mintToken(admin.id); plainToken = await mintToken(plain.id); invalidatePermissionCache(); }, TIMEOUT); afterAll(async () => { if (!payload) return; for (const id of notifIds) { await payload.delete({ collection: "user-notifications", id, overrideAccess: true }).catch( () => {}, ); } for (const id of userIds) { await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {}); } for (const id of roleIds) { await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {}); } }); it("rejects unauthenticated callers", async () => { const res = await GET(request()); expect(res.status).toBe(401); }, TIMEOUT); it("admin scope=all sees both users' notifications and is told it can view others", async () => { const res = await GET(request(adminToken, "all")); expect(res.status).toBe(200); const body = (await res.json()) as InboxBody; expect(body.canViewOthers).toBe(true); expect(body.scope).toBe("all"); const ids = (body.notifications ?? []).map((n) => n.id); expect(ids).toContain(adminNotifId); expect(ids).toContain(plainNotifId); const foreign = (body.notifications ?? []).find((n) => n.id === plainNotifId); expect(foreign?.isMine).toBe(false); }, TIMEOUT); it("admin scope=mine narrows to just their own notifications", async () => { const res = await GET(request(adminToken, "mine")); expect(res.status).toBe(200); const body = (await res.json()) as InboxBody; expect(body.canViewOthers).toBe(true); expect(body.scope).toBe("mine"); const ids = (body.notifications ?? []).map((n) => n.id); expect(ids).toContain(adminNotifId); expect(ids).not.toContain(plainNotifId); }, TIMEOUT); it("plain user cannot view others and stays scoped to their own regardless of scope", async () => { const res = await GET(request(plainToken, "all")); expect(res.status).toBe(200); const body = (await res.json()) as InboxBody; expect(body.canViewOthers).toBe(false); // Requested "all" but the server forces "mine" for a non-oversight caller. expect(body.scope).toBe("mine"); const ids = (body.notifications ?? []).map((n) => n.id); expect(ids).toContain(plainNotifId); expect(ids).not.toContain(adminNotifId); }, TIMEOUT); });