diff --git a/src/app/api/notifications/inbox/route.ts b/src/app/api/notifications/inbox/route.ts index efbaf814..22a03e3c 100644 --- a/src/app/api/notifications/inbox/route.ts +++ b/src/app/api/notifications/inbox/route.ts @@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server"; import config from "@payload-config"; import { getPayload } from "payload"; import { isPayloadUser } from "@/utils/access-control/isPayloadUser"; +import { hasPermission, isSuperuser } from "@/utils/access-control/hasPermission"; export const dynamic = "force-dynamic"; export const runtime = "nodejs"; @@ -13,9 +14,16 @@ export const runtime = "nodejs"; * (/api/user-notifications) returns, but enriches every row with WHO it is * meant for (`ownerId` + `ownerName`) and whether it belongs to the caller * (`isMine`). Staff with read-all oversight see everyone's notifications, so - * this is what lets the bell label "meant for someone else" rows. Read access - * is still scoped by the collection's own access control (own notifications for - * regular users, all for staff). + * this is what lets the bell label "meant for someone else" rows. + * + * Query: + * - `scope=all` (default) | `mine` — a caller with oversight (`canViewOthers`) + * may narrow the feed to just their own notifications. Non-staff are always + * scoped to their own, regardless of the param. The response echoes the + * effective `scope` plus `canViewOthers` so the bell can render its toggle. + * + * Read access is still scoped by the collection's own access control (own + * notifications for regular users, all for staff). */ interface NotificationRow { id: number; @@ -37,6 +45,16 @@ export async function GET(req: NextRequest) { try { const userId = Number(user.id); + + // Read-all oversight matches the collection's own read access: superusers + // and the `system:admin-access` tier. Everyone else only ever sees their own. + const canViewOthers = + (await isSuperuser(payload, user)) || + (await hasPermission(payload, user, "system:admin-access")); + + const requestedScope = req.nextUrl.searchParams.get("scope") === "mine" ? "mine" : "all"; + const scope = canViewOthers ? requestedScope : "mine"; + const res = await payload.find({ collection: "user-notifications", sort: "-createdAt", @@ -44,6 +62,9 @@ export async function GET(req: NextRequest) { depth: 1, overrideAccess: false, user, + // "Just mine" adds an explicit owner filter. When access already returns + // an ownership Where (non-staff) this simply ANDs with the same condition. + ...(scope === "mine" ? { where: { user: { equals: userId } } } : {}), }); const notifications = res.docs.map((doc) => { @@ -64,7 +85,7 @@ export async function GET(req: NextRequest) { }; }); - return NextResponse.json({ notifications }); + return NextResponse.json({ notifications, canViewOthers, scope }); } catch (error) { console.error("notifications/inbox: failed to load", error); return NextResponse.json({ error: "Failed to load notifications." }, { status: 500 }); diff --git a/src/components/frontend/notifications/NotificationsBell.tsx b/src/components/frontend/notifications/NotificationsBell.tsx index 69b8fdb2..7af59589 100644 --- a/src/components/frontend/notifications/NotificationsBell.tsx +++ b/src/components/frontend/notifications/NotificationsBell.tsx @@ -5,6 +5,7 @@ import { useRouter } from "next/navigation"; import Link from "next/link"; import { BellIcon, CheckIcon } from "lucide-react"; import { Button } from "@/components/ui/button"; +import { Switch } from "@/components/ui/switch"; import { DropdownMenu, DropdownMenuContent, @@ -52,6 +53,23 @@ function timeAgo(iso: string): string { const POLL_MS = 60_000; +/** + * Per-browser memory of whether a staff user wants the bell to show everyone's + * notifications ("all") or only their own ("mine"). Non-staff are always + * scoped to their own server-side, so the value is irrelevant to them. + */ +const SCOPE_KEY = "ptf:notifications:scope"; +type Scope = "all" | "mine"; + +function readStoredScope(): Scope { + if (typeof window === "undefined") return "all"; + try { + return window.localStorage.getItem(SCOPE_KEY) === "mine" ? "mine" : "all"; + } catch { + return "all"; + } +} + export function NotificationsBell() { const router = useRouter(); const [notifications, setNotifications] = useState([]); @@ -60,25 +78,31 @@ export function NotificationsBell() { const [error, setError] = useState(false); const [actionError, setActionError] = useState(null); const [marking, setMarking] = useState(false); + const [scope, setScope] = useState(readStoredScope); + const [canViewOthers, setCanViewOthers] = useState(false); const intervalRef = useRef | null>(null); const unreadCount = notifications.filter((n) => !n.read).length; const fetchNotifications = useCallback(async () => { try { - const res = await fetch("/api/notifications/inbox?limit=12&sort=-createdAt", { + const res = await fetch(`/api/notifications/inbox?limit=12&sort=-createdAt&scope=${scope}`, { cache: "no-store", }); if (!res.ok) throw new Error("Failed to fetch"); - const data = (await res.json()) as { notifications?: NotificationItem[] }; + const data = (await res.json()) as { + notifications?: NotificationItem[]; + canViewOthers?: boolean; + }; setNotifications(data.notifications ?? []); + setCanViewOthers(Boolean(data.canViewOthers)); setError(false); } catch { setError(true); } finally { setLoading(false); } - }, []); + }, [scope]); useEffect(() => { void fetchNotifications(); @@ -146,6 +170,16 @@ export function NotificationsBell() { } } + function handleScopeToggle(next: boolean) { + const value: Scope = next ? "all" : "mine"; + setScope(value); + try { + window.localStorage.setItem(SCOPE_KEY, value); + } catch { + // storage unavailable (private mode): the toggle still works this session + } + } + return ( @@ -177,6 +211,23 @@ export function NotificationsBell() { )} + {canViewOthers && ( +
+ + +
+ )}
{loading ? ( diff --git a/tests/int/notification-inbox-scope.int.spec.ts b/tests/int/notification-inbox-scope.int.spec.ts new file mode 100644 index 00000000..67ebc8d0 --- /dev/null +++ b/tests/int/notification-inbox-scope.int.spec.ts @@ -0,0 +1,217 @@ +// @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); +});