Stage 3 of the int-suite speedup (gate G2 showed Vitest 4's pool scheduler only reuses worker processes between isolate:false tasks, so per-file fork spawning made clone+boot costs unavoidable at stage 2): - config: workers branch runs pool=forks with isolate:false, cap 8 via VITEST_MAX_FORKS, node default env (jsdom docblocks on DOM specs), failure-marker reporter, and idempotent setupFiles chain - vitest-worker-setup: one template clone PER FORK PROCESS named by pid (VITEST_WORKER_ID churns per task, which silently re-cloned per file); DATABASE_URI repoint + TEST_PG_POOL_MAX=8 (measured hook deadlocks at 3) - vitest.setup: once-per-process serial test URI markers; afterEach useRealTimers guard (restoreAllMocks omitted: it resurrects vi.mock module factories mid-file); logging absorber for fire-and-forget event writes that reject after their spec's cleanup deleted fixture users - helpers/get-test-payload.ts: memoized Payload boot shared across files in a fork; codemod converted all 91 self-booting specs mechanically - pinned opt-outs (own boot + comments): game-structures-labor-route, mission-reminder, notification-inbox-scope (jwtSign writes leak into the shared instance's auth state across files) - promotion-nominations: create the superuser before its rank ladder so the Users-hook Recruit rank gets leading orderable tokens (its top-of-ladder guard needs Col to remain ladder-max on fresh clones); operation-economy: itemType-scope the market-state assertion (asset and resource ids collide as bare integers under per-fork databases) Gate G3: 5 consecutive full green runs (149/149 files), warm wall 53-65s vs 598s baseline (~10x), zero clone residue after green runs. Vitest 4 note: globalTeardown config no longer exists; teardown returns from globalSetup.
221 lines
7.3 KiB
TypeScript
221 lines
7.3 KiB
TypeScript
|
|
// 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.
|
|
//
|
|
// Pinned to its own payload boot (stage-3 straggler policy): this spec's
|
|
// signed-token auth writes into the shared memoized instance's auth state and
|
|
// leaks "You must be logged in." drift into later files on the same fork.
|
|
|
|
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<string> {
|
|
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<Role> => {
|
|
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<User> => {
|
|
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<number> => {
|
|
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);
|
|
});
|