feat(event-log): configurable per-event visibility with permission gates
- game-event-logs gains visibility (public|restricted) + requiredPermissions (any-of gate from the permission registry); read access becomes a Where clause: public OR actor-is-me OR held permission; superusers and game-event-logs:update staff see all; admin panel gate unchanged - src/utils/event-log/visibility.ts: per-type policy map consumed by emitGameEvent, with per-emit overrides; npc:dialogue and flag:set start restricted, everything else stays public - PlayerFlags hooks emit restricted flag:set audit events on every flag write (admin edits and dialogue effects alike) - fix dashboard RecentEvents leaking events: local API find now runs as the viewer with overrideAccess false - SSE broadcast sends an opaque nudge for restricted events instead of type/actor metadata - /events table marks restricted rows with a lock badge - migration 20261007_025942_add_event_log_visibility + regenerated types - tests/int/event-log-visibility.int.spec.ts (8 cases)
This commit is contained in:
parent
b1168dcc38
commit
8cda724e21
14 changed files with 38861 additions and 24 deletions
12
AGENTS.md
12
AGENTS.md
|
|
@ -124,12 +124,14 @@ Access control helpers live in `src/utils/access-control/` (isRole, hasRoles). F
|
|||
|
||||
`src/collections/game/GameEventLogs.ts` — `game-event-logs` collection.
|
||||
|
||||
- **Schema**: `system` (boolean, default `true` — system-generated vs GM/narrative), `timestamp`, `type` (text/indexed), `message` (human-readable), `actor` (→ users), `structure` (→ game-structures), `targetCollection` (select — pick from known collections), `targetId` (number, polymorphic ref), `data` (JSON blob).
|
||||
- **Access**: any logged-in user can read/create. Update restricted to admins/developers. Delete restricted to developers.
|
||||
- **Emit**: `emitGameEvent(payload, { type, message, actor?, structure?, targetCollection?, targetId?, data? })` in `src/utils/event-log/emit.ts`. Silently catches errors (fire-and-forget). Always sets `system: true`.
|
||||
- **Schema**: `system` (boolean, default `true` — system-generated vs GM/narrative), `timestamp`, `type` (text/indexed), `message` (human-readable), `actor` (→ users), `structure` (→ game-structures), `targetCollection` (select — pick from known collections), `targetId` (number, polymorphic ref), `data` (JSON blob), `visibility` (select `public` default | `restricted`, indexed), `requiredPermissions` (select hasMany from the permission registry; any-of gate shown only when restricted).
|
||||
- **Access**: read is visibility-filtered: every logged-in user sees public events; restricted events additionally require one of their `requiredPermissions`, event-log staff (`game-event-logs:update`), superuser status, or being the actor (you always see your own events). Create: any logged-in user. Update restricted to admins/developers. Delete restricted to developers. The admin panel keeps its boolean gate (`scopedAdminPageAccess`), so event-log staff see everything there.
|
||||
- **Visibility policies**: `src/utils/event-log/visibility.ts` maps event TYPES to defaults (`EVENT_VISIBILITY_POLICIES`); `emitGameEvent` stamps documents via `resolveEventVisibility(type, override)`. Restricted today: `npc:dialogue` (gated `npc-dialogues:read` / `player-flags:read`) and `flag:set` (gated `player-flags:read`). Everything else defaults public. Callers may pass `visibility` / `requiredPermissions` per emit.
|
||||
- **Local API gotcha**: `payload.find` on `game-event-logs` defaults to `overrideAccess: true` and bypasses the filter. Consumers that must respect visibility pass `user` + `overrideAccess: false` (the dashboard RecentEvents query in `src/app/(frontend)/page.tsx` does this). REST consumers (`/events` page, `EventLedger`) are filtered automatically.
|
||||
- **Emit**: `emitGameEvent(payload, { type, message, actor?, structure?, targetCollection?, targetId?, data?, visibility?, requiredPermissions? })` in `src/utils/event-log/emit.ts`. Silently catches errors (fire-and-forget). Always sets `system: true`; stamps visibility from the policy map.
|
||||
- **Types**: `EventTypes` constants in `src/utils/event-log/eventTypes.ts` — add new event categories there without touching the collection. Using these constants gives TypeScript narrowing on the `type` field.
|
||||
- **Wiring**: Server actions in `actions.ts` emit events after successful mutations. `GameStructures` afterChange hook catches admin-panel storage edits. `Structures` beforeChange hook emits `structure:resize`.
|
||||
- **targetCollection options**: `game-structures`, `structures`, `resources`, `assets`, `vehicles`, `game-vehicles`, `game-npcs`, `npc-staffing`, `factions`, `missions`, `campaigns`, `users`, `technologies`, `maps`, `shipments`, `bank-accounts`, `bank-transactions`, `ledger-entries`, `market-listings`, `market-negotiations`, `locker-storages`, `loadouts`, `evaluations`, `tickets`, `wiki-pages`, `wiki-revisions`, `wiki-templates`, `game-servers`, `assignment-transfers`. If a new collection is added that should be a valid target, add an option here.
|
||||
- **Wiring**: Server actions in `actions.ts` emit events after successful mutations. `GameStructures` afterChange hook catches admin-panel storage edits. `Structures` beforeChange hook emits `structure:resize`. `PlayerFlags` afterChange/afterDelete hooks emit restricted `flag:set` audit events for every flag write (admin-panel edits and dialogue effects alike).
|
||||
- **targetCollection options**: `game-structures`, `structures`, `resources`, `assets`, `vehicles`, `game-vehicles`, `game-npcs`, `npc-staffing`, `factions`, `missions`, `campaigns`, `users`, `technologies`, `maps`, `shipments`, `bank-accounts`, `bank-transactions`, `ledger-entries`, `market-listings`, `market-negotiations`, `locker-storages`, `loadouts`, `evaluations`, `tickets`, `wiki-pages`, `wiki-revisions`, `wiki-templates`, `game-servers`, `assignment-transfers`, `player-flags`. If a new collection is added that should be a valid target, add an option here.
|
||||
- **Narrative events**: admins/developers can create entries manually in the Payload admin panel with `system: false` for GM-written narrative events. These are visually distinct in the UI (amber accent, book icon).
|
||||
|
||||
### UI
|
||||
|
|
|
|||
|
|
@ -160,12 +160,16 @@ export default async function HomePage() {
|
|||
coverImage: m.coverImage,
|
||||
}));
|
||||
|
||||
// Fetch recent events
|
||||
// Fetch recent events. Runs as the viewer with access control applied so
|
||||
// restricted events (dialogue effects, flag changes) stay hidden from
|
||||
// members who lack the required permissions.
|
||||
const eventsRes = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
sort: "-timestamp",
|
||||
limit: 8,
|
||||
depth: 1,
|
||||
user,
|
||||
overrideAccess: false,
|
||||
});
|
||||
|
||||
const events = eventsRes.docs.map((e) => ({
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { CollectionConfig } from "payload";
|
||||
import { CollectionConfig, type Where } from "payload";
|
||||
import { requirePermission, hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { loadUserPermissions } from "@/utils/access-control/loadUserPermissions";
|
||||
import { permissionSelectOptions } from "@/permissions";
|
||||
|
||||
const TARGET_COLLECTIONS = [
|
||||
{ label: "Game Structures", value: "game-structures" },
|
||||
|
|
@ -43,6 +45,7 @@ const TARGET_COLLECTIONS = [
|
|||
{ label: "Ribbon Submissions", value: "ribbon-submissions" },
|
||||
{ label: "Promotion Nominations", value: "promotion-nominations" },
|
||||
{ label: "Leadership Transfers", value: "leadership-transfers" },
|
||||
{ label: "Player Flags", value: "player-flags" },
|
||||
] as const;
|
||||
|
||||
export const GameEventLogs: CollectionConfig = {
|
||||
|
|
@ -50,12 +53,31 @@ export const GameEventLogs: CollectionConfig = {
|
|||
admin: {
|
||||
group: "Game",
|
||||
useAsTitle: "message",
|
||||
defaultColumns: ["timestamp", "type", "system", "message", "actor", "structure"],
|
||||
defaultColumns: ["timestamp", "type", "system", "visibility", "message", "actor", "structure"],
|
||||
listSearchableFields: ["message", "type"],
|
||||
pagination: { defaultLimit: 50 },
|
||||
},
|
||||
access: {
|
||||
read: ({ req }) => !!req.user,
|
||||
// Visibility-filtered read: every logged-in user sees public events;
|
||||
// restricted events additionally require one of their
|
||||
// `requiredPermissions`, an event-log staff permission
|
||||
// (`game-event-logs:update`), superuser status, or being the actor.
|
||||
// The admin panel bypasses this (boolean gate via scopedAdminPageAccess),
|
||||
// so event-log staff keep a full view there.
|
||||
read: async ({ req }): Promise<Where | boolean> => {
|
||||
if (!req.user) return false;
|
||||
const { permissions, isSuperuser } = await loadUserPermissions(req.payload, req.user);
|
||||
if (isSuperuser) return true;
|
||||
if (permissions.has("game-event-logs:update")) return true;
|
||||
const or: Where[] = [
|
||||
{ visibility: { equals: "public" } },
|
||||
{ actor: { equals: req.user.id } },
|
||||
];
|
||||
if (permissions.size > 0) {
|
||||
or.push({ requiredPermissions: { in: [...permissions] } });
|
||||
}
|
||||
return { or };
|
||||
},
|
||||
create: ({ req }) => !!req.user,
|
||||
update: async ({ req }) => {
|
||||
if (!req.user) return false;
|
||||
|
|
@ -75,6 +97,29 @@ export const GameEventLogs: CollectionConfig = {
|
|||
"System-generated events are created automatically. Uncheck for manual/GM narrative entries.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "visibility",
|
||||
type: "select",
|
||||
required: true,
|
||||
defaultValue: "public",
|
||||
index: true,
|
||||
options: ["public", "restricted"],
|
||||
admin: {
|
||||
description:
|
||||
"Public events are visible to every logged-in user. Restricted events additionally require one of the required permissions below (or event-log staff / superuser status; the actor always sees their own events).",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "requiredPermissions",
|
||||
type: "select",
|
||||
hasMany: true,
|
||||
options: permissionSelectOptions,
|
||||
admin: {
|
||||
condition: (_data, blockData) => blockData?.visibility === "restricted",
|
||||
description:
|
||||
"Any-of gate: a user holding ANY one of these permissions sees this event. Leave empty to hide it from everyone except event-log staff, superusers, and the actor.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "timestamp",
|
||||
type: "date",
|
||||
|
|
|
|||
|
|
@ -1,12 +1,41 @@
|
|||
import { CollectionConfig } from "payload";
|
||||
import { CollectionConfig, type PayloadRequest } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
import { flagValues } from "@/lib/npc-dialogue/flags";
|
||||
|
||||
/** Human label for a flag's owner ("global" or "@username") in audit messages. */
|
||||
async function flagOwnerLabel(
|
||||
payload: PayloadRequest["payload"],
|
||||
userRef: number | { id: number } | null | undefined,
|
||||
): Promise<string> {
|
||||
if (userRef == null) return "global";
|
||||
const userId = typeof userRef === "object" ? userRef.id : userRef;
|
||||
try {
|
||||
const target = await payload.findByID({
|
||||
collection: "users",
|
||||
id: userId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
select: { username: true },
|
||||
});
|
||||
return `@${target.username}`;
|
||||
} catch {
|
||||
return `user #${userId}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Where beforeDelete stashes the doomed doc so afterDelete can describe it. */
|
||||
interface FlagDeleteContext {
|
||||
__deletedPlayerFlag?: { key: string; owner: string; value: string };
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic flags — per-player (when `user` is set) or global (when null).
|
||||
* The lightweight state layer conversations branch on. Event nodes write
|
||||
* player flags; condition nodes read them, falling back to global if the
|
||||
* player-specific flag is absent. GMs can seed or correct both here in the
|
||||
* admin panel.
|
||||
* admin panel. Every write emits a restricted `flag:set` audit event.
|
||||
*/
|
||||
export const PlayerFlags: CollectionConfig = {
|
||||
slug: "player-flags",
|
||||
|
|
@ -98,6 +127,71 @@ export const PlayerFlags: CollectionConfig = {
|
|||
},
|
||||
},
|
||||
],
|
||||
hooks: {
|
||||
// Audit every flag write (admin-panel edits and dialogue effects alike)
|
||||
// as a restricted flag:set event; visibility comes from the policy map.
|
||||
afterChange: [
|
||||
async ({ doc, req, operation }) => {
|
||||
const owner = await flagOwnerLabel(req.payload, doc.user);
|
||||
const value = flagValues(doc).text;
|
||||
const verb = operation === "create" ? "created" : "updated";
|
||||
await emitGameEvent(req.payload, {
|
||||
type: EventTypes.FlagSet,
|
||||
message: `Flag "${doc.key}" ${verb} for ${owner}: ${value}`,
|
||||
actor: req.user ? Number(req.user.id) : undefined,
|
||||
targetCollection: "player-flags",
|
||||
targetId: doc.id,
|
||||
data: {
|
||||
operation,
|
||||
key: doc.key,
|
||||
flagType: doc.flagType,
|
||||
value,
|
||||
ownerUserId: typeof doc.user === "object" ? (doc.user?.id ?? null) : (doc.user ?? null),
|
||||
},
|
||||
});
|
||||
return doc;
|
||||
},
|
||||
],
|
||||
beforeDelete: [
|
||||
async ({ id, req }) => {
|
||||
// beforeDelete gets no doc; read it while it still exists so
|
||||
// afterDelete can describe what was removed.
|
||||
const ctx = req as PayloadRequest & FlagDeleteContext;
|
||||
try {
|
||||
const doc = await req.payload.findByID({
|
||||
collection: "player-flags",
|
||||
id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
ctx.__deletedPlayerFlag = {
|
||||
key: doc.key,
|
||||
owner: await flagOwnerLabel(req.payload, doc.user),
|
||||
value: flagValues(doc).text,
|
||||
};
|
||||
} catch {
|
||||
// Doc unreadable (already gone): afterDelete falls back to the id.
|
||||
}
|
||||
},
|
||||
],
|
||||
afterDelete: [
|
||||
async ({ id, req }) => {
|
||||
const ctx = req as PayloadRequest & FlagDeleteContext;
|
||||
const snapshot = ctx.__deletedPlayerFlag;
|
||||
await emitGameEvent(req.payload, {
|
||||
type: EventTypes.FlagSet,
|
||||
message: snapshot
|
||||
? `Flag "${snapshot.key}" deleted for ${snapshot.owner} (was: ${snapshot.value})`
|
||||
: `Flag #${id} deleted`,
|
||||
actor: req.user ? Number(req.user.id) : undefined,
|
||||
targetCollection: "player-flags",
|
||||
targetId: Number(id),
|
||||
data: { operation: "delete", key: snapshot?.key, value: snapshot?.value },
|
||||
});
|
||||
return id;
|
||||
},
|
||||
],
|
||||
},
|
||||
timestamps: true,
|
||||
indexes: [{ fields: ["user", "key"], unique: true }],
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { ChevronLeft, ChevronRight, RotateCcw, Search } from "lucide-react";
|
||||
import { ChevronLeft, ChevronRight, Lock, RotateCcw, Search } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Combobox } from "@/components/ui/combobox";
|
||||
|
|
@ -70,6 +70,7 @@ const TARGET_COLLECTION_LABELS: Record<string, string> = {
|
|||
"assignment-transfers": "Assignment Transfers",
|
||||
"voice-scripts": "Voice Scripts",
|
||||
"voice-submissions": "Voice Submissions",
|
||||
"player-flags": "Player Flags",
|
||||
};
|
||||
|
||||
const TARGET_COLLECTION_OPTIONS = Object.entries(TARGET_COLLECTION_LABELS).sort((a, b) =>
|
||||
|
|
@ -84,6 +85,7 @@ type SortDir = "desc" | "asc";
|
|||
interface EventRow {
|
||||
id: number;
|
||||
system?: boolean | null;
|
||||
visibility?: string | null;
|
||||
timestamp: string;
|
||||
type: string;
|
||||
message: string;
|
||||
|
|
@ -416,9 +418,21 @@ export default function EventLogTable() {
|
|||
{formatTimestamp(row.timestamp)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="max-w-40 truncate font-normal">
|
||||
{formatType(row.type)}
|
||||
</Badge>
|
||||
<div className="flex items-center gap-1">
|
||||
<Badge variant="outline" className="max-w-40 truncate font-normal">
|
||||
{formatType(row.type)}
|
||||
</Badge>
|
||||
{row.visibility === "restricted" && (
|
||||
<span
|
||||
className="inline-flex shrink-0 text-amber-400"
|
||||
role="img"
|
||||
aria-label="Restricted event"
|
||||
title="Restricted: visible only to staff with the required permissions and to its actor"
|
||||
>
|
||||
<Lock className="size-3" aria-hidden />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="max-w-md whitespace-normal">{row.message}</TableCell>
|
||||
<TableCell className="text-xs">{actorLabel(row.actor)}</TableCell>
|
||||
|
|
|
|||
37899
src/migrations/20261007_025942_add_event_log_visibility.json
Normal file
37899
src/migrations/20261007_025942_add_event_log_visibility.json
Normal file
File diff suppressed because it is too large
Load diff
34
src/migrations/20261007_025942_add_event_log_visibility.ts
Normal file
34
src/migrations/20261007_025942_add_event_log_visibility.ts
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -112,6 +112,7 @@ import * as migration_20261006_155244_add_global_flag_support from './20261006_1
|
|||
import * as migration_20261006_195605_add_text_flag_type from './20261006_195605_add_text_flag_type';
|
||||
import * as migration_20261006_203217_add_dialogue_entry_gate from './20261006_203217_add_dialogue_entry_gate';
|
||||
import * as migration_20261006_205845_add_flag_time_windows from './20261006_205845_add_flag_time_windows';
|
||||
import * as migration_20261007_025942_add_event_log_visibility from './20261007_025942_add_event_log_visibility';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -682,6 +683,11 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261006_205845_add_flag_time_windows.up,
|
||||
down: migration_20261006_205845_add_flag_time_windows.down,
|
||||
name: '20261006_205845_add_flag_time_windows'
|
||||
name: '20261006_205845_add_flag_time_windows',
|
||||
},
|
||||
{
|
||||
up: migration_20261007_025942_add_event_log_visibility.up,
|
||||
down: migration_20261007_025942_add_event_log_visibility.down,
|
||||
name: '20261007_025942_add_event_log_visibility'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -2610,6 +2610,357 @@ export interface GameEventLog {
|
|||
* System-generated events are created automatically. Uncheck for manual/GM narrative entries.
|
||||
*/
|
||||
system?: boolean | null;
|
||||
/**
|
||||
* Public events are visible to every logged-in user. Restricted events additionally require one of the required permissions below (or event-log staff / superuser status; the actor always sees their own events).
|
||||
*/
|
||||
visibility: 'public' | 'restricted';
|
||||
/**
|
||||
* Any-of gate: a user holding ANY one of these permissions sees this event. Leave empty to hide it from everyone except event-log staff, superusers, and the actor.
|
||||
*/
|
||||
requiredPermissions?:
|
||||
| (
|
||||
| 'system:admin-access'
|
||||
| 'media:create'
|
||||
| 'media:read'
|
||||
| 'media:update'
|
||||
| 'media:delete'
|
||||
| 'admin:media:manage'
|
||||
| 'users:create'
|
||||
| 'users:read'
|
||||
| 'users:update'
|
||||
| 'users:delete'
|
||||
| 'users:unlock'
|
||||
| 'users:assign-roles'
|
||||
| 'admin:users:manage'
|
||||
| 'roles:create'
|
||||
| 'roles:read'
|
||||
| 'roles:update'
|
||||
| 'roles:delete'
|
||||
| 'admin:roles:manage'
|
||||
| 'ranks:create'
|
||||
| 'ranks:read'
|
||||
| 'ranks:update'
|
||||
| 'ranks:delete'
|
||||
| 'admin:ranks:manage'
|
||||
| 'profiles:create'
|
||||
| 'profiles:read'
|
||||
| 'profiles:update'
|
||||
| 'profiles:delete'
|
||||
| 'admin:profiles:manage'
|
||||
| 'awards:create'
|
||||
| 'awards:read'
|
||||
| 'awards:update'
|
||||
| 'awards:delete'
|
||||
| 'admin:awards:manage'
|
||||
| 'qualifications:create'
|
||||
| 'qualifications:read'
|
||||
| 'qualifications:update'
|
||||
| 'qualifications:delete'
|
||||
| 'admin:qualifications:manage'
|
||||
| 'assignments:create'
|
||||
| 'assignments:read'
|
||||
| 'assignments:update'
|
||||
| 'assignments:delete'
|
||||
| 'admin:assignments:manage'
|
||||
| 'assignment-transfers:create'
|
||||
| 'assignment-transfers:read'
|
||||
| 'assignment-transfers:update'
|
||||
| 'assignment-transfers:delete'
|
||||
| 'admin:assignment-transfers:manage'
|
||||
| 'experience:create'
|
||||
| 'experience:read'
|
||||
| 'experience:update'
|
||||
| 'experience:delete'
|
||||
| 'admin:experience:manage'
|
||||
| 'user-notifications:create'
|
||||
| 'user-notifications:read'
|
||||
| 'user-notifications:update'
|
||||
| 'user-notifications:delete'
|
||||
| 'admin:user-notifications:manage'
|
||||
| 'evaluations:create'
|
||||
| 'evaluations:read'
|
||||
| 'evaluations:update'
|
||||
| 'evaluations:delete'
|
||||
| 'admin:evaluations:manage'
|
||||
| 'missions:create'
|
||||
| 'missions:read'
|
||||
| 'missions:update'
|
||||
| 'missions:delete'
|
||||
| 'missions:read-sensitive'
|
||||
| 'admin:missions:manage'
|
||||
| 'mission-attendances:create'
|
||||
| 'mission-attendances:read'
|
||||
| 'mission-attendances:update'
|
||||
| 'mission-attendances:delete'
|
||||
| 'admin:mission-attendances:manage'
|
||||
| 'mission-role-signups:create'
|
||||
| 'mission-role-signups:read'
|
||||
| 'mission-role-signups:update'
|
||||
| 'mission-role-signups:delete'
|
||||
| 'admin:mission-role-signups:manage'
|
||||
| 'mission-map-markers:create'
|
||||
| 'mission-map-markers:read'
|
||||
| 'mission-map-markers:update'
|
||||
| 'mission-map-markers:delete'
|
||||
| 'admin:mission-map-markers:manage'
|
||||
| 'campaigns:create'
|
||||
| 'campaigns:read'
|
||||
| 'campaigns:update'
|
||||
| 'campaigns:delete'
|
||||
| 'admin:campaigns:manage'
|
||||
| 'campaigns:manage'
|
||||
| 'factions:create'
|
||||
| 'factions:read'
|
||||
| 'factions:update'
|
||||
| 'factions:delete'
|
||||
| 'admin:factions:manage'
|
||||
| 'technologies:create'
|
||||
| 'technologies:read'
|
||||
| 'technologies:update'
|
||||
| 'technologies:delete'
|
||||
| 'admin:technologies:manage'
|
||||
| 'tech-categories:create'
|
||||
| 'tech-categories:read'
|
||||
| 'tech-categories:update'
|
||||
| 'tech-categories:delete'
|
||||
| 'admin:tech-categories:manage'
|
||||
| 'assets:create'
|
||||
| 'assets:read'
|
||||
| 'assets:update'
|
||||
| 'assets:delete'
|
||||
| 'admin:assets:manage'
|
||||
| 'resources:create'
|
||||
| 'resources:read'
|
||||
| 'resources:update'
|
||||
| 'resources:delete'
|
||||
| 'admin:resources:manage'
|
||||
| 'vehicles:create'
|
||||
| 'vehicles:read'
|
||||
| 'vehicles:update'
|
||||
| 'vehicles:delete'
|
||||
| 'admin:vehicles:manage'
|
||||
| 'structures:create'
|
||||
| 'structures:read'
|
||||
| 'structures:update'
|
||||
| 'structures:delete'
|
||||
| 'admin:structures:manage'
|
||||
| 'shipments:create'
|
||||
| 'shipments:read'
|
||||
| 'shipments:update'
|
||||
| 'shipments:delete'
|
||||
| 'admin:shipments:manage'
|
||||
| 'bank-accounts:create'
|
||||
| 'bank-accounts:read'
|
||||
| 'bank-accounts:update'
|
||||
| 'bank-accounts:delete'
|
||||
| 'admin:bank-accounts:manage'
|
||||
| 'bank-transactions:create'
|
||||
| 'bank-transactions:read'
|
||||
| 'bank-transactions:update'
|
||||
| 'bank-transactions:delete'
|
||||
| 'admin:bank-transactions:manage'
|
||||
| 'ledger-entries:create'
|
||||
| 'ledger-entries:read'
|
||||
| 'ledger-entries:update'
|
||||
| 'ledger-entries:delete'
|
||||
| 'admin:ledger-entries:manage'
|
||||
| 'locker-storages:create'
|
||||
| 'locker-storages:read'
|
||||
| 'locker-storages:update'
|
||||
| 'locker-storages:delete'
|
||||
| 'admin:locker-storages:manage'
|
||||
| 'loadouts:create'
|
||||
| 'loadouts:read'
|
||||
| 'loadouts:update'
|
||||
| 'loadouts:delete'
|
||||
| 'admin:loadouts:manage'
|
||||
| 'market-listings:create'
|
||||
| 'market-listings:read'
|
||||
| 'market-listings:update'
|
||||
| 'market-listings:delete'
|
||||
| 'admin:market-listings:manage'
|
||||
| 'market-negotiations:create'
|
||||
| 'market-negotiations:read'
|
||||
| 'market-negotiations:update'
|
||||
| 'market-negotiations:delete'
|
||||
| 'admin:market-negotiations:manage'
|
||||
| 'market-state:create'
|
||||
| 'market-state:read'
|
||||
| 'market-state:update'
|
||||
| 'market-state:delete'
|
||||
| 'admin:market-state:manage'
|
||||
| 'projects:create'
|
||||
| 'projects:read'
|
||||
| 'projects:update'
|
||||
| 'projects:delete'
|
||||
| 'admin:projects:manage'
|
||||
| 'labels:create'
|
||||
| 'labels:read'
|
||||
| 'labels:update'
|
||||
| 'labels:delete'
|
||||
| 'admin:labels:manage'
|
||||
| 'sprints:create'
|
||||
| 'sprints:read'
|
||||
| 'sprints:update'
|
||||
| 'sprints:delete'
|
||||
| 'admin:sprints:manage'
|
||||
| 'releases:create'
|
||||
| 'releases:read'
|
||||
| 'releases:update'
|
||||
| 'releases:delete'
|
||||
| 'admin:releases:manage'
|
||||
| 'tickets:create'
|
||||
| 'tickets:read'
|
||||
| 'tickets:update'
|
||||
| 'tickets:delete'
|
||||
| 'admin:tickets:manage'
|
||||
| 'ticket-votes:create'
|
||||
| 'ticket-votes:read'
|
||||
| 'ticket-votes:update'
|
||||
| 'ticket-votes:delete'
|
||||
| 'admin:ticket-votes:manage'
|
||||
| 'game-structures:create'
|
||||
| 'game-structures:read'
|
||||
| 'game-structures:update'
|
||||
| 'game-structures:delete'
|
||||
| 'admin:game-structures:manage'
|
||||
| 'game-vehicles:create'
|
||||
| 'game-vehicles:read'
|
||||
| 'game-vehicles:update'
|
||||
| 'game-vehicles:delete'
|
||||
| 'admin:game-vehicles:manage'
|
||||
| 'game-npcs:create'
|
||||
| 'game-npcs:read'
|
||||
| 'game-npcs:update'
|
||||
| 'game-npcs:delete'
|
||||
| 'admin:game-npcs:manage'
|
||||
| 'game-hard-resources:create'
|
||||
| 'game-hard-resources:read'
|
||||
| 'game-hard-resources:update'
|
||||
| 'game-hard-resources:delete'
|
||||
| 'admin:game-hard-resources:manage'
|
||||
| 'game-event-logs:create'
|
||||
| 'game-event-logs:read'
|
||||
| 'game-event-logs:update'
|
||||
| 'game-event-logs:delete'
|
||||
| 'admin:game-event-logs:manage'
|
||||
| 'maps:create'
|
||||
| 'maps:read'
|
||||
| 'maps:update'
|
||||
| 'maps:delete'
|
||||
| 'maps:place'
|
||||
| 'admin:maps:manage'
|
||||
| 'map-roads:read'
|
||||
| 'map-roads:author'
|
||||
| 'admin:map-roads:manage'
|
||||
| 'map-zones:read'
|
||||
| 'map-zones:author'
|
||||
| 'admin:map-zones:manage'
|
||||
| 'resource-nodes:read'
|
||||
| 'resource-nodes:author'
|
||||
| 'admin:resource-nodes:manage'
|
||||
| 'narrative-events:create'
|
||||
| 'narrative-events:read'
|
||||
| 'narrative-events:update'
|
||||
| 'narrative-events:delete'
|
||||
| 'admin:narrative-events:manage'
|
||||
| 'npc-dialogues:create'
|
||||
| 'npc-dialogues:read'
|
||||
| 'npc-dialogues:update'
|
||||
| 'npc-dialogues:delete'
|
||||
| 'admin:npc-dialogues:manage'
|
||||
| 'player-flags:create'
|
||||
| 'player-flags:read'
|
||||
| 'player-flags:update'
|
||||
| 'player-flags:delete'
|
||||
| 'admin:player-flags:manage'
|
||||
| 'mission-files:create'
|
||||
| 'mission-files:read'
|
||||
| 'mission-files:update'
|
||||
| 'mission-files:delete'
|
||||
| 'admin:mission-files:manage'
|
||||
| 'mod-lists:create'
|
||||
| 'mod-lists:read'
|
||||
| 'mod-lists:update'
|
||||
| 'mod-lists:delete'
|
||||
| 'admin:mod-lists:manage'
|
||||
| 'respawn-tickets:create'
|
||||
| 'respawn-tickets:read'
|
||||
| 'respawn-tickets:update'
|
||||
| 'respawn-tickets:delete'
|
||||
| 'admin:respawn-tickets:manage'
|
||||
| 'game-servers:create'
|
||||
| 'game-servers:read'
|
||||
| 'game-servers:update'
|
||||
| 'game-servers:delete'
|
||||
| 'admin:game-servers:manage'
|
||||
| 'arma-sync-events:create'
|
||||
| 'arma-sync-events:read'
|
||||
| 'arma-sync-events:update'
|
||||
| 'arma-sync-events:delete'
|
||||
| 'admin:arma-sync-events:manage'
|
||||
| 'arma-commands:create'
|
||||
| 'arma-commands:read'
|
||||
| 'arma-commands:update'
|
||||
| 'arma-commands:delete'
|
||||
| 'admin:arma-commands:manage'
|
||||
| 'operation-events:create'
|
||||
| 'operation-events:read'
|
||||
| 'operation-events:update'
|
||||
| 'operation-events:delete'
|
||||
| 'admin:operation-events:manage'
|
||||
| 'operation-effects:create'
|
||||
| 'operation-effects:read'
|
||||
| 'operation-effects:update'
|
||||
| 'operation-effects:delete'
|
||||
| 'admin:operation-effects:manage'
|
||||
| 'operation-reservations:create'
|
||||
| 'operation-reservations:read'
|
||||
| 'operation-reservations:update'
|
||||
| 'operation-reservations:delete'
|
||||
| 'admin:operation-reservations:manage'
|
||||
| 'operation-readiness:create'
|
||||
| 'operation-readiness:read'
|
||||
| 'operation-readiness:update'
|
||||
| 'operation-readiness:delete'
|
||||
| 'admin:operation-readiness:manage'
|
||||
| 'zone-pressure:create'
|
||||
| 'zone-pressure:read'
|
||||
| 'zone-pressure:update'
|
||||
| 'zone-pressure:delete'
|
||||
| 'admin:zone-pressure:manage'
|
||||
| 'announcements:create'
|
||||
| 'announcements:read'
|
||||
| 'announcements:update'
|
||||
| 'announcements:delete'
|
||||
| 'admin:announcements:manage'
|
||||
| 'forms:create'
|
||||
| 'forms:read'
|
||||
| 'forms:update'
|
||||
| 'forms:delete'
|
||||
| 'form-submissions:read'
|
||||
| 'form-submissions:delete'
|
||||
| 'admin:forms:manage'
|
||||
| 'admin:form-submissions:manage'
|
||||
| 'game-rules:read'
|
||||
| 'game-rules:update'
|
||||
| 'shims:read'
|
||||
| 'shims:update'
|
||||
| 'logistics:manage'
|
||||
| 'intelligence:manage'
|
||||
| 'profiles:intel_excerpt:update'
|
||||
| 'banking:manage'
|
||||
| 'tickets:staff'
|
||||
| 'discord:staff'
|
||||
| 'discord:announce'
|
||||
| 'custom-minefields:update'
|
||||
| 'custom-minefields:delete'
|
||||
| 'custom-minefield-scores:delete'
|
||||
| 'custom-radio-tests:update'
|
||||
| 'custom-radio-tests:delete'
|
||||
| 'custom-radio-test-scores:delete'
|
||||
)[]
|
||||
| null;
|
||||
timestamp: string;
|
||||
type: string;
|
||||
message: string;
|
||||
|
|
@ -2661,6 +3012,7 @@ export interface GameEventLog {
|
|||
| 'ribbon-submissions'
|
||||
| 'promotion-nominations'
|
||||
| 'leadership-transfers'
|
||||
| 'player-flags'
|
||||
)
|
||||
| null;
|
||||
targetId?: number | null;
|
||||
|
|
@ -7913,6 +8265,8 @@ export interface LaborClassificationsSelect<T extends boolean = true> {
|
|||
*/
|
||||
export interface GameEventLogsSelect<T extends boolean = true> {
|
||||
system?: T;
|
||||
visibility?: T;
|
||||
requiredPermissions?: T;
|
||||
timestamp?: T;
|
||||
type?: T;
|
||||
message?: T;
|
||||
|
|
|
|||
|
|
@ -40,7 +40,10 @@ Read-permission visibility check (`missions:read` / `campaigns:read` / `factions
|
|||
## Event log system
|
||||
|
||||
### Emitter: `emitGameEvent(payload, { type, message, ... })`
|
||||
Fire-and-forget create on `game-event-logs`. Always sets `system: true`. Silent error catch (no throw). Always called AFTER successful mutation in server actions.
|
||||
Fire-and-forget create on `game-event-logs`. Always sets `system: true`. Silent error catch (no throw). Always called AFTER successful mutation in server actions. Stamps `visibility` + `requiredPermissions` from the policy map (see below); callers may override per event.
|
||||
|
||||
### Visibility policies: `visibility.ts`
|
||||
`EVENT_VISIBILITY_POLICIES` maps event types to defaults (`public`, or `restricted` with an any-of `requiredPermissions` gate); `resolveEventVisibility(type, override)` merges per-emit overrides with independent fallbacks. Restricted today: `npc:dialogue`, `flag:set`. The `game-event-logs` read access turns this into a Where clause (public OR required-permission OR actor-is-me; staff/superusers see all). Local API consumers must pass `user` + `overrideAccess: false` to respect it.
|
||||
|
||||
### Event types: `EventTypes` constants (~105 types across 15+ categories)
|
||||
Defined in `eventTypes.ts`. Use these constants for TypeScript narrowing on the `type` field. Categories include: `mission:*`, `finance:*`, `market:*`, `structure:*`, `staff:*`, `logistics:*`, `bank:*`, `notification:*`, `locker:*`, `xp:*`, `ticket:*`, `wiki:*`, `minigame:*`, `attendance:*`, `system:*`.
|
||||
|
|
@ -54,6 +57,7 @@ Defined in `eventTypes.ts`. Use these constants for TypeScript narrowing on the
|
|||
| Add new RBAC permission | `src/permissions/index.ts` + use in `hasPermission` calls |
|
||||
| Add qualification gate | `access-control/hasLogisticsQualification.ts` (or create similar) |
|
||||
| Add event type constant | `event-log/eventTypes.ts` (add to `EventTypes` object) |
|
||||
| Gate an event type's visibility | `event-log/visibility.ts` (`EVENT_VISIBILITY_POLICIES`) |
|
||||
| Emit event from action | `import { emitGameEvent } from "@/utils/event-log/emit"` |
|
||||
| Check qualification in layout | Use `hasLogisticsQualification(payload, user)` |
|
||||
| Modify XP calculation | `xp/resolveLevel.ts` |
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
import type { EventType } from "./eventTypes";
|
||||
import type { EventVisibility } from "./visibility";
|
||||
import { resolveEventVisibility } from "./visibility";
|
||||
import { broadcast } from "@/lib/realtime/bus";
|
||||
import type { Permission } from "@/permissions";
|
||||
|
||||
interface GameEventInput {
|
||||
type: EventType;
|
||||
|
|
@ -47,15 +50,27 @@ interface GameEventInput {
|
|||
| "custom-radio-test-scores"
|
||||
| "ribbon-submissions"
|
||||
| "promotion-nominations"
|
||||
| "leadership-transfers";
|
||||
| "leadership-transfers"
|
||||
| "player-flags";
|
||||
targetId?: number;
|
||||
data?: Record<string, unknown>;
|
||||
/**
|
||||
* Override the per-type visibility default (see `EVENT_VISIBILITY_POLICIES`).
|
||||
* Omit to use the type's policy, which falls back to "public".
|
||||
*/
|
||||
visibility?: EventVisibility;
|
||||
/** Any-of permission gate for restricted events. See `visibility`. */
|
||||
requiredPermissions?: Permission[];
|
||||
}
|
||||
|
||||
export async function emitGameEvent(
|
||||
payload: Awaited<ReturnType<typeof import("payload").getPayload>>,
|
||||
event: GameEventInput,
|
||||
) {
|
||||
const policy = resolveEventVisibility(event.type, {
|
||||
visibility: event.visibility,
|
||||
requiredPermissions: event.requiredPermissions,
|
||||
});
|
||||
try {
|
||||
await payload.create({
|
||||
collection: "game-event-logs",
|
||||
|
|
@ -69,18 +84,29 @@ export async function emitGameEvent(
|
|||
targetCollection: event.targetCollection,
|
||||
targetId: event.targetId,
|
||||
structure: event.structure,
|
||||
visibility: policy.visibility,
|
||||
requiredPermissions: policy.requiredPermissions,
|
||||
},
|
||||
depth: 0,
|
||||
// Bins and tests run without an authenticated user; create access on
|
||||
// game-event-logs requires one, so system events would be silently dropped.
|
||||
overrideAccess: true,
|
||||
});
|
||||
broadcast("game-event", {
|
||||
type: event.type,
|
||||
actor: event.actor ?? null,
|
||||
targetCollection: event.targetCollection ?? null,
|
||||
targetId: event.targetId ?? null,
|
||||
});
|
||||
// Public events broadcast their metadata; restricted events broadcast an
|
||||
// opaque nudge so the SSE stream itself never leaks who did what. The
|
||||
// client listener ignores the payload and refetches through access-
|
||||
// filtered queries anyway.
|
||||
broadcast(
|
||||
"game-event",
|
||||
policy.visibility === "restricted"
|
||||
? { restricted: true }
|
||||
: {
|
||||
type: event.type,
|
||||
actor: event.actor ?? null,
|
||||
targetCollection: event.targetCollection ?? null,
|
||||
targetId: event.targetId ?? null,
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[EventLog] Failed to emit event:", err);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -117,6 +117,9 @@ export const EventTypes = {
|
|||
NpcGenerate: "npc:generate",
|
||||
NpcDialogue: "npc:dialogue",
|
||||
|
||||
// Flags
|
||||
FlagSet: "flag:set",
|
||||
|
||||
// Account
|
||||
AccountPasswordChange: "account:password-change",
|
||||
AccountProfileUpdate: "account:profile-update",
|
||||
|
|
|
|||
66
src/utils/event-log/visibility.ts
Normal file
66
src/utils/event-log/visibility.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
/**
|
||||
* Visibility policies for game events.
|
||||
*
|
||||
* Every `game-event-logs` document carries a `visibility` ("public" or
|
||||
* "restricted") plus an optional `requiredPermissions` list. Restricted
|
||||
* events are hidden from users who hold none of the required permissions
|
||||
* (superusers, event-log staff with `game-event-logs:update`, and the event's
|
||||
* actor always see them). The collection's read access enforces this.
|
||||
*
|
||||
* This module maps event TYPES to their default policy so emitters don't
|
||||
* repeat themselves; `emitGameEvent` stamps documents from it, and callers
|
||||
* may override per event. Pure module (type-only imports, client-safe).
|
||||
*/
|
||||
|
||||
import type { Permission } from "@/permissions";
|
||||
import { EventTypes, type EventType } from "./eventTypes";
|
||||
|
||||
export type EventVisibility = "public" | "restricted";
|
||||
|
||||
export interface EventVisibilityPolicy {
|
||||
visibility: EventVisibility;
|
||||
/**
|
||||
* Any-of gate for restricted events: a user holding ANY one of these
|
||||
* permissions sees the event. Empty on a restricted event means only
|
||||
* superusers, event-log staff, and the actor can see it.
|
||||
*/
|
||||
requiredPermissions?: Permission[];
|
||||
}
|
||||
|
||||
/** Default for every type not listed below: visible to all logged-in users. */
|
||||
export const PUBLIC_EVENT_VISIBILITY: EventVisibilityPolicy = { visibility: "public" };
|
||||
|
||||
/**
|
||||
* Per-type defaults applied by `emitGameEvent` when the caller does not
|
||||
* override. Narrative/state-leaking types belong here; routine game chatter
|
||||
* (minigame scores, Chronicle reads, market sales) stays public.
|
||||
*/
|
||||
export const EVENT_VISIBILITY_POLICIES: Partial<Record<EventType, EventVisibilityPolicy>> = {
|
||||
// Conversation effects (including flag writes triggered by dialogue) can
|
||||
// spoil narrative branches: gate them to conversation/flag authoring staff.
|
||||
[EventTypes.NpcDialogue]: {
|
||||
visibility: "restricted",
|
||||
requiredPermissions: ["npc-dialogues:read", "player-flags:read"],
|
||||
},
|
||||
// Direct player-flag edits (GM admin-panel surgery) are narrative state.
|
||||
[EventTypes.FlagSet]: {
|
||||
visibility: "restricted",
|
||||
requiredPermissions: ["player-flags:read"],
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve the effective policy for an event: per-type default, with optional
|
||||
* per-emit overrides. Each key falls back independently, so passing only a
|
||||
* `visibility` keeps the type's permission list and vice versa.
|
||||
*/
|
||||
export function resolveEventVisibility(
|
||||
type: EventType,
|
||||
override?: Partial<EventVisibilityPolicy>,
|
||||
): { visibility: EventVisibility; requiredPermissions: Permission[] } {
|
||||
const base = EVENT_VISIBILITY_POLICIES[type] ?? PUBLIC_EVENT_VISIBILITY;
|
||||
return {
|
||||
visibility: override?.visibility ?? base.visibility,
|
||||
requiredPermissions: override?.requiredPermissions ?? base.requiredPermissions ?? [],
|
||||
};
|
||||
}
|
||||
286
tests/int/event-log-visibility.int.spec.ts
Normal file
286
tests/int/event-log-visibility.int.spec.ts
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
import { getPayload, Payload, type Where } from "payload";
|
||||
import config from "@/payload.config";
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import type { GameEventLog, Role, User } from "@/payload-types";
|
||||
import { GameEventLogs } from "@/collections/game/GameEventLogs";
|
||||
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
import { resolveEventVisibility } from "@/utils/event-log/visibility";
|
||||
|
||||
let payload: Payload;
|
||||
|
||||
const RUN = `evlogvis-${Date.now().toString(36)}`;
|
||||
const TIMEOUT = 30_000;
|
||||
|
||||
describe("event visibility policies (pure)", () => {
|
||||
it("defaults unlisted types to public with no gates", () => {
|
||||
expect(resolveEventVisibility(EventTypes.MinigameFlappy)).toEqual({
|
||||
visibility: "public",
|
||||
requiredPermissions: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("restricts dialogue events to conversation/flag authoring staff", () => {
|
||||
expect(resolveEventVisibility(EventTypes.NpcDialogue)).toEqual({
|
||||
visibility: "restricted",
|
||||
requiredPermissions: ["npc-dialogues:read", "player-flags:read"],
|
||||
});
|
||||
});
|
||||
|
||||
it("restricts flag:set events to flag readers", () => {
|
||||
expect(resolveEventVisibility(EventTypes.FlagSet)).toEqual({
|
||||
visibility: "restricted",
|
||||
requiredPermissions: ["player-flags:read"],
|
||||
});
|
||||
});
|
||||
|
||||
it("applies per-emit overrides with independent fallbacks", () => {
|
||||
// Visibility override keeps the type's permission list.
|
||||
expect(
|
||||
resolveEventVisibility(EventTypes.NpcDialogue, { visibility: "public" }).visibility,
|
||||
).toBe("public");
|
||||
expect(
|
||||
resolveEventVisibility(EventTypes.NpcDialogue, { visibility: "public" })
|
||||
.requiredPermissions,
|
||||
).toContain("player-flags:read");
|
||||
// Permission override keeps the type's visibility.
|
||||
expect(
|
||||
resolveEventVisibility(EventTypes.StoryBeatRead, {
|
||||
requiredPermissions: ["missions:read"],
|
||||
}),
|
||||
).toEqual({ visibility: "public", requiredPermissions: ["missions:read"] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("event visibility enforcement (database)", () => {
|
||||
const roleIds: number[] = [];
|
||||
const userIds: number[] = [];
|
||||
const eventIds: number[] = [];
|
||||
const flagIds: number[] = [];
|
||||
|
||||
let plainUser: User;
|
||||
let gateUser: User;
|
||||
let staffUser: User;
|
||||
let superUser: User;
|
||||
|
||||
/** Ids of events created by this suite, newest first. */
|
||||
const makeRole = async (label: string, extra: Partial<Role> = {}): Promise<Role> => {
|
||||
const role = (await payload.create({
|
||||
collection: "roles",
|
||||
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, ...extra },
|
||||
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;
|
||||
};
|
||||
|
||||
/** Emit an event and remember its id for cleanup. */
|
||||
const emit = async (
|
||||
input: Parameters<typeof emitGameEvent>[1],
|
||||
): Promise<GameEventLog> => {
|
||||
await emitGameEvent(payload, input);
|
||||
const res = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
where: { message: { equals: input.message } },
|
||||
sort: "-id",
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
const doc = res.docs[0];
|
||||
expect(doc).toBeDefined();
|
||||
eventIds.push(doc.id);
|
||||
return doc;
|
||||
};
|
||||
|
||||
/** Event ids visible to `user` among the given ids (access-filtered find). */
|
||||
const visibleIds = async (user: User, ids: number[]): Promise<Set<number>> => {
|
||||
const res = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
where: { id: { in: ids } },
|
||||
limit: ids.length,
|
||||
overrideAccess: false,
|
||||
user,
|
||||
depth: 0,
|
||||
});
|
||||
return new Set(res.docs.map((d) => d.id));
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
const payloadConfig = await config;
|
||||
payload = await getPayload({ config: payloadConfig });
|
||||
|
||||
const plainRole = await makeRole("plain", { permissions: [] });
|
||||
const gateRole = await makeRole("gate", { permissions: ["player-flags:read"] });
|
||||
const staffRole = await makeRole("staff", { permissions: ["game-event-logs:update"] });
|
||||
const superRole = await makeRole("super", { isSuperuser: true });
|
||||
|
||||
plainUser = await makeUser("plain", plainRole.id);
|
||||
gateUser = await makeUser("gate", gateRole.id);
|
||||
staffUser = await makeUser("staff", staffRole.id);
|
||||
superUser = await makeUser("super", superRole.id);
|
||||
|
||||
invalidatePermissionCache();
|
||||
}, TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
if (!payload) return;
|
||||
for (const id of flagIds) {
|
||||
await payload.delete({ collection: "player-flags", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of eventIds) {
|
||||
await payload.delete({ collection: "game-event-logs", 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("emitGameEvent stamps the per-type policy onto documents", async () => {
|
||||
const publicEvent = await emit({
|
||||
type: EventTypes.MinigameFlappy,
|
||||
message: `${RUN} public score`,
|
||||
});
|
||||
expect(publicEvent.visibility).toBe("public");
|
||||
|
||||
const dialogueEvent = await emit({
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: `${RUN} dialogue effect`,
|
||||
actor: plainUser.id,
|
||||
});
|
||||
expect(dialogueEvent.visibility).toBe("restricted");
|
||||
expect(dialogueEvent.requiredPermissions).toEqual(
|
||||
expect.arrayContaining(["npc-dialogues:read", "player-flags:read"]),
|
||||
);
|
||||
|
||||
const overridden = await emit({
|
||||
type: EventTypes.FlagSet,
|
||||
message: `${RUN} flag override`,
|
||||
visibility: "public",
|
||||
});
|
||||
expect(overridden.visibility).toBe("public");
|
||||
}, TIMEOUT);
|
||||
|
||||
it("hides restricted events from members and shows them to permission holders, staff, superusers, and actors", async () => {
|
||||
const publicEvent = await emit({
|
||||
type: EventTypes.WikiPageEdit,
|
||||
message: `${RUN} filtered public`,
|
||||
});
|
||||
const restrictedForeign = await emit({
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: `${RUN} restricted foreign`,
|
||||
actor: gateUser.id,
|
||||
});
|
||||
const restrictedOwn = await emit({
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: `${RUN} restricted own`,
|
||||
actor: plainUser.id,
|
||||
});
|
||||
const ids = [publicEvent.id, restrictedForeign.id, restrictedOwn.id];
|
||||
|
||||
// Plain member: public events + their own restricted events only.
|
||||
const plainView = await visibleIds(plainUser, ids);
|
||||
expect(plainView.has(publicEvent.id)).toBe(true);
|
||||
expect(plainView.has(restrictedOwn.id)).toBe(true);
|
||||
expect(plainView.has(restrictedForeign.id)).toBe(false);
|
||||
|
||||
// player-flags:read holder satisfies the any-of gate.
|
||||
const gateView = await visibleIds(gateUser, ids);
|
||||
expect(gateView.has(restrictedForeign.id)).toBe(true);
|
||||
|
||||
// Event-log staff and superusers see everything.
|
||||
const staffView = await visibleIds(staffUser, ids);
|
||||
expect(staffView.size).toBe(ids.length);
|
||||
const superView = await visibleIds(superUser, ids);
|
||||
expect(superView.size).toBe(ids.length);
|
||||
}, TIMEOUT);
|
||||
|
||||
it("returns a Where clause for members and true for superusers from read access", async () => {
|
||||
const read = GameEventLogs.access?.read;
|
||||
expect(typeof read).toBe("function");
|
||||
const fn = read as (args: { req: unknown }) => Promise<Where | boolean>;
|
||||
|
||||
const memberClause = await fn({ req: { user: plainUser, payload } });
|
||||
expect(typeof memberClause).toBe("object");
|
||||
const or = (memberClause as Where).or;
|
||||
expect(or).toEqual(expect.arrayContaining([{ visibility: { equals: "public" } }]));
|
||||
|
||||
expect(await fn({ req: { user: superUser, payload } })).toBe(true);
|
||||
expect(await fn({ req: { user: null, payload } })).toBe(false);
|
||||
}, TIMEOUT);
|
||||
|
||||
it("emits restricted flag:set audit events for player-flag writes", async () => {
|
||||
const flag = await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { key: `${RUN}_met_informant`, flagType: "boolean", boolValue: true },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
flagIds.push(flag.id);
|
||||
|
||||
const createdEvents = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
where: { type: { equals: EventTypes.FlagSet }, targetId: { equals: flag.id } },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
expect(createdEvents.docs).toHaveLength(1);
|
||||
const created = createdEvents.docs[0];
|
||||
eventIds.push(created.id);
|
||||
expect(created.visibility).toBe("restricted");
|
||||
expect(created.requiredPermissions).toEqual(["player-flags:read"]);
|
||||
expect(created.message).toContain(`${RUN}_met_informant`);
|
||||
expect(created.message).toContain("global");
|
||||
expect(created.targetCollection).toBe("player-flags");
|
||||
|
||||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: flag.id,
|
||||
data: { boolValue: false },
|
||||
overrideAccess: true,
|
||||
});
|
||||
await payload.delete({
|
||||
collection: "player-flags",
|
||||
id: flag.id,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
const allEvents = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
where: { type: { equals: EventTypes.FlagSet }, targetId: { equals: flag.id } },
|
||||
sort: "id",
|
||||
limit: 10,
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
eventIds.push(...allEvents.docs.map((d) => d.id));
|
||||
const messages = allEvents.docs.map((d) => d.message).join(" | ");
|
||||
expect(messages).toContain("updated for global");
|
||||
expect(messages).toContain("deleted for global");
|
||||
}, TIMEOUT);
|
||||
});
|
||||
Loading…
Reference in a new issue