Under 10-12 concurrent users the app queued behind itself: every SSE game-event/profile-update made each client run router.refresh(), i.e. a full layout + page render at ~15-25 queries, and a mission completion emitted one XP event per attendee row. Measured against production, no single query is slow and the DB is small, so this targets render count and per-render query count instead of indexes. Fewer renders per event: - GameTickRealtime: 250ms coalescing window -> 1s, hidden tabs skip the render and refresh once when shown again. - Delete OperationsRealtimeRefresher (5 routes) and the duplicate useGameTick refreshers in ProductionPanel/SlotsPanel; the global subscriber already refreshes those routes. - Presence heartbeats no longer broadcast (was O(N^2) per channel every 15s for a lastSeen no surface renders). - NavCore links opt out of prefetch: the layout is force-dynamic with no loading.tsx, so ~35 prefetched links per tab were 35 server renders. Fewer queries per render: - Qualification flags go through one cached, single-flight profile read instead of one query per auth check; invalidated on profile writes. - Dedupe DIVISION_ADMIN_QUALIFICATIONS (5 identical lookups -> 1). - Anchor the permission cache on globalThis so route bundles share it. - Minigame registry: real TTL cache plus invalidation on write. - New cachedConfig TTL cache for the shims/game-rules globals, with invalidation hooks; bank-account existence check stops hydrating. - pg pool max 10 -> 20 (node-postgres default throttled concurrent renders). Hot-path per-item work: - Contribution grant sweep: one status write per batch, one bucket write and one name lookup per user, one existence query per source collection instead of ~5 queries per entry. - Notifications bell: coalesced refetch, hidden-tab skip; mark-all-read filters by the actor instead of scanning 100 foreign unread rows. - Polling loops (shipments, ledger, mission reminders, chip bank) pause while the tab is hidden.
218 lines
8.6 KiB
TypeScript
218 lines
8.6 KiB
TypeScript
import type {
|
|
Access,
|
|
AccessArgs,
|
|
AccessResult,
|
|
CollectionBeforeChangeHook,
|
|
Payload,
|
|
PayloadRequest,
|
|
} from "payload";
|
|
import type { Permission } from "@/permissions";
|
|
import {
|
|
canAccessAdminPanel as canAccessAdminPanelByPermissions,
|
|
hasPermission,
|
|
isAdminPanelRequest,
|
|
requireAdminPageAccess,
|
|
} from "@/utils/access-control/hasPermission";
|
|
import { hasIntelligenceQualification } from "@/utils/access-control/hasIntelligenceQualification";
|
|
import { hasLogisticsQualification } from "@/utils/access-control/hasLogisticsQualification";
|
|
|
|
/**
|
|
* Division-scoped access control.
|
|
*
|
|
* Division membership is established by the two qualification helpers:
|
|
* - Intelligence: `hasIntelligenceQualification` (intel-domain RBAC permissions
|
|
* or the "intelligence" profile qualification)
|
|
* - Logistics: `hasLogisticsQualification` (logistics-domain RBAC permissions
|
|
* or a "logistics" profile qualification)
|
|
*
|
|
* Explicit RBAC permissions always still work on their own - these helpers are
|
|
* a union (permission OR qualification OR superuser), never a replacement.
|
|
*/
|
|
|
|
/**
|
|
* Collections whose admin panel is delegated to a division. Division members
|
|
* get full admin-panel access to exactly these collections (and nothing else,
|
|
* because `requireAdminPageAccess` still gates every other collection's
|
|
* admin-panel read behind `admin:<slug>:manage` permissions).
|
|
*
|
|
* NOTE: `assets`, `resources`, and `vehicles` are intentionally NOT here.
|
|
* Admin-panel access to those collections is gated solely by the
|
|
* `admin:<slug>:manage` "Manage Admin Page" permission (via
|
|
* `requireAdminPageAccess`), not by division membership. This prevents
|
|
* division members (e.g. an intelligence-officer role that also holds the
|
|
* logistics qualification) from viewing those backend pages without the
|
|
* explicit manage permission.
|
|
*/
|
|
const DIVISION_ADMIN_QUALIFICATIONS: Record<
|
|
string,
|
|
(payload: Payload, user: { id: number | string }) => Promise<boolean>
|
|
> = {
|
|
technologies: hasIntelligenceQualification,
|
|
"tech-categories": hasIntelligenceQualification,
|
|
"tech-researches": hasIntelligenceQualification,
|
|
"tech-ballots": hasIntelligenceQualification,
|
|
"tech-ballot-votes": hasIntelligenceQualification,
|
|
};
|
|
|
|
/**
|
|
* Access factory: allows users holding the explicit permission OR members of
|
|
* the Intelligence division.
|
|
*/
|
|
export function requireIntelligencePermission(permission: Permission) {
|
|
return async ({ req }: { req: PayloadRequest }): Promise<boolean> => {
|
|
if (await hasPermission(req.payload, req.user, permission)) return true;
|
|
if (!req.user) return false;
|
|
return hasIntelligenceQualification(req.payload, req.user);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Access factory: allows users holding the explicit permission OR members of
|
|
* the Logistics division.
|
|
*/
|
|
export function requireLogisticsPermission(permission: Permission) {
|
|
return async ({ req }: { req: PayloadRequest }): Promise<boolean> => {
|
|
if (await hasPermission(req.payload, req.user, permission)) return true;
|
|
if (!req.user) return false;
|
|
return hasLogisticsQualification(req.payload, req.user);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Field-level access factory for approval-gating fields (approval status,
|
|
* is-live flags, ...). Only "super users" may write them: superuser roles or
|
|
* holders of the `system:admin-access` permission (the Admin tier).
|
|
*
|
|
* Used as both `create` and `update` field access: on create the field is
|
|
* stripped from non-superuser payloads so the schema default (e.g.
|
|
* "in_progress") applies; on update attempts to change the value are ignored.
|
|
*/
|
|
export function requireApprovalPermission() {
|
|
return async ({ req }: { req: PayloadRequest }): Promise<boolean> =>
|
|
hasPermission(req.payload, req.user, "system:admin-access");
|
|
}
|
|
|
|
/**
|
|
* Field-level access factory for approval-status select fields.
|
|
*
|
|
* Anyone with the collection's update permission may set the status to
|
|
* "In Progress" or "Ready for Review". Only superusers (holders of
|
|
* `system:admin-access`) may set it to final states ("Approved",
|
|
* "Rejected", "Revision Requested").
|
|
*/
|
|
export function approvalStatusFieldAccess(collectionSlug: string) {
|
|
const fn = async ({ req, data }: { req: PayloadRequest; data?: Record<string, unknown> }): Promise<boolean> => {
|
|
const value = data?.approvalStatus as string | undefined;
|
|
const isSuperuser = await hasPermission(req.payload, req.user, "system:admin-access");
|
|
if (isSuperuser) return true;
|
|
|
|
const allowedValues = ["in_progress", "ready_for_review"];
|
|
if (!value || allowedValues.includes(value)) {
|
|
return await hasPermission(req.payload, req.user, `${collectionSlug}:update` as Permission);
|
|
}
|
|
|
|
return false;
|
|
};
|
|
|
|
return {
|
|
create: fn,
|
|
update: fn,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Approval statuses that a non-superuser edit invalidates:
|
|
* - `approved` the document is live/implemented, so an edit must be
|
|
* reviewed again before it stays live
|
|
* - `revision_requested` the author has changes to make, which is exactly the
|
|
* edit happening now
|
|
*/
|
|
const EDIT_INVALIDATED_APPROVAL_STATUSES = ["approved", "revision_requested"];
|
|
|
|
/** Statuses a non-superuser may legitimately land on while editing. */
|
|
const EDITABLE_APPROVAL_STATUSES = ["in_progress", "ready_for_review"];
|
|
|
|
/**
|
|
* Collection `beforeChange` hook factory: when a NON-superuser updates a
|
|
* document whose stored `approvalStatus` is Approved or Revision Requested,
|
|
* rewrite the status back to "In Progress" so the edit is reviewed again.
|
|
*
|
|
* A hook is required rather than field-level access for two reasons:
|
|
* - Payload field access can only *strip* a field, never rewrite its value.
|
|
* - It only sees the incoming payload, so it cannot react to a partial update
|
|
* that omits `approvalStatus` entirely (the normal case for the tech tree
|
|
* lite editor and PATCH-style edits).
|
|
*
|
|
* Rules:
|
|
* - Update only; creates keep the existing default/access behavior.
|
|
* - Superusers (holders of `system:admin-access`) are exempt.
|
|
* - System writes with no `req.user` (catalog imports, seeds, scripts using
|
|
* `overrideAccess: true`) are exempt, so automation never resets a reviewed
|
|
* document.
|
|
* - If the edit explicitly sets an editable status (In Progress, Ready for
|
|
* Review), that choice is honored instead of forcing In Progress.
|
|
*/
|
|
export function resetApprovalStatusOnEdit(): CollectionBeforeChangeHook {
|
|
return async ({ req, data, originalDoc, operation }) => {
|
|
if (operation !== "update" || !req.user || !data) return data;
|
|
|
|
const current = (originalDoc as { approvalStatus?: string } | null | undefined)?.approvalStatus;
|
|
if (!current || !EDIT_INVALIDATED_APPROVAL_STATUSES.includes(current)) return data;
|
|
|
|
if (await hasPermission(req.payload, req.user, "system:admin-access")) return data;
|
|
|
|
const incoming = data.approvalStatus as string | undefined;
|
|
if (incoming && EDITABLE_APPROVAL_STATUSES.includes(incoming)) return data;
|
|
|
|
return { ...data, approvalStatus: "in_progress" };
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Same contract as `requireAdminPageAccess`, with one addition: for the four
|
|
* division-scoped collections an admin-panel request also passes when the user
|
|
* qualifies for the owning division. Non-admin (REST/API) requests keep the
|
|
* original read access behavior unchanged.
|
|
*/
|
|
export function scopedAdminPageAccess(
|
|
collectionSlug: string,
|
|
readAccess?: Access | boolean,
|
|
): Access {
|
|
const base = requireAdminPageAccess(collectionSlug, readAccess);
|
|
const divisionCheck = DIVISION_ADMIN_QUALIFICATIONS[collectionSlug];
|
|
|
|
if (!divisionCheck) return base;
|
|
|
|
return async (args: AccessArgs): Promise<AccessResult> => {
|
|
const { req } = args;
|
|
if (req.user && isAdminPanelRequest(req)) {
|
|
try {
|
|
if (await divisionCheck(req.payload, req.user)) return true;
|
|
} catch {
|
|
// Qualification lookup failed; fall through to the permission-based
|
|
// decision instead of failing the request outright.
|
|
}
|
|
}
|
|
return base(args);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Division-aware admin panel gate: permission-based access (superuser or any
|
|
* `admin:<slug>:manage` permission) OR membership of a division that owns at
|
|
* least one admin panel collection.
|
|
*/
|
|
export async function canAccessAdminPanel(
|
|
payload: Payload,
|
|
user: { id: number | string; roleDocs?: unknown } | null | undefined,
|
|
): Promise<boolean> {
|
|
if (!user) return false;
|
|
if (await canAccessAdminPanelByPermissions(payload, user)) return true;
|
|
// Every entry in the map is currently the same predicate (intelligence owns
|
|
// all five tech collections), so dedupe the values: this was five identical
|
|
// qualification lookups per auth pass.
|
|
for (const divisionCheck of new Set(Object.values(DIVISION_ADMIN_QUALIFICATIONS))) {
|
|
if (await divisionCheck(payload, user)) return true;
|
|
}
|
|
return false;
|
|
}
|