1
0
Fork 0

feat(intelligence): add undiscovered faction state with read masking

Factions gain a discovered checkbox plus a read-time mask so players see
the entry (UNDISCOVERED card, classified detail stub) without its name,
description, standing, relationships, campaigns or cover image.

The mask runs in the Factions afterRead hook, so every reader path is
covered: pages, REST, and populated relationships. Readers holding the new
factions:view-undiscovered permission or system:admin-access see the real
record; admin panel reads are exempt so a masked edit form can never write
the placeholder name back over a record.
This commit is contained in:
Jason Fraley 2026-11-18 09:19:57 -05:00
parent 4264431e4d
commit 1d45c3fee1
21 changed files with 46635 additions and 280 deletions

View file

@ -124,6 +124,7 @@ export default async function CampaignDetailPage({ params }: CampaignDetailPageP
where: { associatedCampaigns: { equals: campaign.id } },
limit: 100,
depth: 0,
user,
select: { name: true, type: true, description: true },
}),
]);

View file

@ -9,6 +9,7 @@ import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintex
import {
ArrowLeftIcon,
ChevronRightIcon,
EyeOffIcon,
FlagIcon,
LandmarkIcon,
ScaleIcon,
@ -18,6 +19,10 @@ import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { MissionCard } from "@/components/frontend/intelligence/MissionCard";
import { getCurrencyConfig } from "@/lib/banking";
import { CurrencyAmount } from "@/components/frontend/banking/CurrencyAmount";
import {
canViewUndiscoveredFactions,
UNDISCOVERED_FACTION_SUMMARY,
} from "@/lib/intelligence/factionDiscovery";
interface FactionDetailPageProps {
params: Promise<{ id: string }>;
@ -84,6 +89,7 @@ export default async function FactionDetailPage({ params }: FactionDetailPagePro
collection: "factions",
id: Number(id),
depth: 2,
user,
})
.catch(() => null);
@ -91,6 +97,12 @@ export default async function FactionDetailPage({ params }: FactionDetailPagePro
notFound();
}
// Undiscovered factions arrive masked from the Factions afterRead hook unless
// the reader is cleared for them. Render the classified stub and skip every
// related lookup in that case.
const redacted =
faction.discovered === false && !(await canViewUndiscoveredFactions(payload, user));
const coverImage =
typeof faction.coverImage === "object" && faction.coverImage !== null
? (faction.coverImage as Media)
@ -100,63 +112,71 @@ export default async function FactionDetailPage({ params }: FactionDetailPagePro
const descriptionText = faction.description
? convertLexicalToPlaintext({ data: faction.description })
: null;
const heroSubtitle =
descriptionText && descriptionText.length > 240
const heroSubtitle = redacted
? UNDISCOVERED_FACTION_SUMMARY
: descriptionText && descriptionText.length > 240
? descriptionText.slice(0, 240) + "…"
: (descriptionText ?? faction.name);
const reputation = faction.reputation ?? 0;
// Bank account for this faction
const bankRes = await payload
.find({
collection: "bank-accounts",
where: {
and: [{ ownerFaction: { equals: faction.id } }, { accountType: { equals: "faction" } }],
},
depth: 1,
limit: 1,
})
.catch(() => ({ docs: [] }));
const bankRes = redacted
? { docs: [] as unknown[] }
: await payload
.find({
collection: "bank-accounts",
where: {
and: [{ ownerFaction: { equals: faction.id } }, { accountType: { equals: "faction" } }],
},
depth: 1,
limit: 1,
})
.catch(() => ({ docs: [] }));
const bankAccount = (bankRes.docs[0] as BankAccount | undefined) ?? null;
// Currency emblem/label is shared across all accounts (from Game Rules), so
// the bank balance renders the same emblem the banking surfaces show.
const currencyConfig = await getCurrencyConfig(payload);
// Missions involving this faction
const missionsRes = await payload
.find({
collection: "missions",
where: { "factionsInvolved.faction": { equals: faction.id } },
sort: "-classification.startDateTime",
limit: 100,
depth: 1,
user,
overrideAccess: false,
select: {
name: true,
codeName: true,
summary: true,
operationType: true,
ownershipAndStatus: true,
classification: true,
missionRoles: true,
coverImage: true,
},
})
.catch(() => ({ docs: [] as Mission[] }));
const missionsRes = redacted
? { docs: [] as Mission[] }
: await payload
.find({
collection: "missions",
where: { "factionsInvolved.faction": { equals: faction.id } },
sort: "-classification.startDateTime",
limit: 100,
depth: 1,
user,
overrideAccess: false,
select: {
name: true,
codeName: true,
summary: true,
operationType: true,
ownershipAndStatus: true,
classification: true,
missionRoles: true,
coverImage: true,
},
})
.catch(() => ({ docs: [] as Mission[] }));
const missions = missionsRes.docs as Mission[];
// Associated campaigns (faction.associatedCampaigns is populated at depth 2)
const campaigns =
faction.associatedCampaigns?.filter(
(c): c is Campaign => typeof c === "object" && c !== null,
) ?? [];
const campaigns = redacted
? []
: (faction.associatedCampaigns?.filter(
(c): c is Campaign => typeof c === "object" && c !== null,
) ?? []);
// Relationships (targetFaction populated at depth 2)
const relationships = (faction.relationships ?? []).filter(
(r) => typeof r.targetFaction === "object" && r.targetFaction !== null,
);
const relationships = redacted
? []
: (faction.relationships ?? []).filter(
(r) => typeof r.targetFaction === "object" && r.targetFaction !== null,
);
return (
<div className="flex flex-col">
@ -189,11 +209,13 @@ export default async function FactionDetailPage({ params }: FactionDetailPagePro
>
{typeLabels[faction.type] ?? faction.type}
</span>
<span
className={`rounded-md border border-white/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-wider backdrop-blur-sm ${reputationTone(reputation)}`}
>
{reputationLabel(reputation)} · {reputation >= 0 ? `+${reputation}` : reputation}
</span>
{!redacted && (
<span
className={`rounded-md border border-white/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-wider backdrop-blur-sm ${reputationTone(reputation)}`}
>
{reputationLabel(reputation)} · {reputation >= 0 ? `+${reputation}` : reputation}
</span>
)}
</div>
<div className="absolute inset-0 flex flex-col items-center justify-center p-6 md:p-10 lg:p-12 text-center">
@ -204,236 +226,266 @@ export default async function FactionDetailPage({ params }: FactionDetailPagePro
{faction.name}
</h1>
<p className="mt-3 max-w-3xl text-lg leading-relaxed text-white/80">{heroSubtitle}</p>
<div className="mt-6 flex items-center gap-2 text-sm text-white/70">
<ShieldIcon className="size-4 text-white/60" />
<span>{typeLabels[faction.type] ?? faction.type}</span>
{faction.playableFaction && (
<>
<span className="text-white/30">·</span>
<span>Playable</span>
</>
)}
{faction.startingFaction && (
<>
<span className="text-white/30">·</span>
<span>Starting</span>
</>
)}
</div>
{redacted ? (
<div className="mt-6 flex items-center gap-2 text-sm text-white/70">
<EyeOffIcon className="size-4 text-white/60" />
<span>No intelligence available</span>
</div>
) : (
<div className="mt-6 flex items-center gap-2 text-sm text-white/70">
<ShieldIcon className="size-4 text-white/60" />
<span>{typeLabels[faction.type] ?? faction.type}</span>
{faction.playableFaction && (
<>
<span className="text-white/30">·</span>
<span>Playable</span>
</>
)}
{faction.startingFaction && (
<>
<span className="text-white/30">·</span>
<span>Starting</span>
</>
)}
</div>
)}
</div>
</header>
<div className="p-5 flex flex-col gap-6 max-w-[96rem] mx-auto w-full">
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
{/* ── Main Content (2/3) ──────────────────────────── */}
<div className="xl:col-span-2 flex flex-col gap-6">
{faction.description && (
<Item variant="outline">
<ItemHeader>
<ItemTitle>Description</ItemTitle>
</ItemHeader>
<ItemContent className="prose-invert prose-sm max-w-none [&_p]:mb-2 [&_ul]:list-disc [&_ul]:ml-4 [&_ol]:list-decimal [&_ol]:ml-4 [&_strong]:text-foreground [&_em]:italic">
<RichText data={faction.description} />
</ItemContent>
</Item>
)}
{redacted ? (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<EyeOffIcon className="size-4 text-muted-foreground" />
<ItemTitle>No Intelligence Available</ItemTitle>
</div>
<span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
Classification: Unknown
</span>
</ItemHeader>
<ItemContent>
<p className="text-sm text-muted-foreground">
Nothing is known about this faction. No description, standing, relationships,
finances or campaign activity has been recorded yet.
</p>
</ItemContent>
</Item>
) : (
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
{/* ── Main Content (2/3) ──────────────────────────── */}
<div className="xl:col-span-2 flex flex-col gap-6">
{faction.description && (
<Item variant="outline">
<ItemHeader>
<ItemTitle>Description</ItemTitle>
</ItemHeader>
<ItemContent className="prose-invert prose-sm max-w-none [&_p]:mb-2 [&_ul]:list-disc [&_ul]:ml-4 [&_ol]:list-decimal [&_ol]:ml-4 [&_strong]:text-foreground [&_em]:italic">
<RichText data={faction.description} />
</ItemContent>
</Item>
)}
{relationships.length > 0 && (
{relationships.length > 0 && (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ScaleIcon className="size-4 text-muted-foreground" />
<ItemTitle>Relationships</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-3">
{relationships.map((r) => {
const target = r.targetFaction as Faction;
const value = r.value;
const tone = relationshipTone(value);
const barWidth = Math.min(Math.abs(value), 100);
return (
<Link
key={r.id ?? target.id}
href={`/intelligence/factions/${target.id}`}
className="flex flex-col gap-1 rounded-md border border-border/50 p-3 transition-colors hover:border-primary/40 hover:bg-muted/30"
>
<div className="flex items-center justify-between gap-2">
<Link
href={`/intelligence/factions/${target.id}`}
className="flex items-center gap-2 py-1 text-sm font-medium hover:text-primary transition-colors"
>
<ShieldIcon className="size-4 text-muted-foreground" />
<span>{target.name}</span>
</Link>
<span className={`text-xs font-mono ${tone.text}`}>
{value >= 0 ? `+${value}` : value} · {tone.label}
</span>
</div>
<div className="relative h-1.5 w-full overflow-hidden rounded-full bg-muted">
<div
className={`absolute top-0 h-full ${tone.bar}`}
style={{
left: value < 0 ? "50%" : `${50 - barWidth / 2}%`,
width: `${barWidth / 2}%`,
}}
/>
<div className="absolute left-1/2 top-0 h-full w-px bg-border" />
</div>
{r.notes && (
<p className="text-xs text-muted-foreground mt-1">{r.notes}</p>
)}
</Link>
);
})}
</div>
</ItemContent>
</Item>
)}
{missions.length > 0 && (
<section className="flex flex-col gap-3">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Missions
</h2>
<span className="text-xs text-muted-foreground">
{missions.length} mission{missions.length !== 1 ? "s" : ""}
</span>
</div>
<div className="flex flex-col gap-2">
{missions.map((mission) => (
<MissionCard key={mission.id} mission={mission} showFullDetails={false} />
))}
</div>
</section>
)}
</div>
{/* ── Right Sidebar (1/3) ─────────────────────────── */}
<div className="flex flex-col gap-4">
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ScaleIcon className="size-4 text-muted-foreground" />
<ItemTitle>Relationships</ItemTitle>
<ItemTitle>Standing</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-3">
{relationships.map((r) => {
const target = r.targetFaction as Faction;
const value = r.value;
const tone = relationshipTone(value);
const barWidth = Math.min(Math.abs(value), 100);
return (
<Link
key={r.id ?? target.id}
href={`/intelligence/factions/${target.id}`}
className="flex flex-col gap-1 rounded-md border border-border/50 p-3 transition-colors hover:border-primary/40 hover:bg-muted/30"
>
<div className="flex items-center justify-between gap-2">
<Link
href={`/intelligence/factions/${target.id}`}
className="flex items-center gap-2 py-1 text-sm font-medium hover:text-primary transition-colors"
>
<ShieldIcon className="size-4 text-muted-foreground" />
<span>{target.name}</span>
</Link>
<span className={`text-xs font-mono ${tone.text}`}>
{value >= 0 ? `+${value}` : value} · {tone.label}
</span>
</div>
<div className="relative h-1.5 w-full overflow-hidden rounded-full bg-muted">
<div
className={`absolute top-0 h-full ${tone.bar}`}
style={{
left: value < 0 ? "50%" : `${50 - barWidth / 2}%`,
width: `${barWidth / 2}%`,
}}
/>
<div className="absolute left-1/2 top-0 h-full w-px bg-border" />
</div>
{r.notes && (
<p className="text-xs text-muted-foreground mt-1">{r.notes}</p>
)}
</Link>
);
})}
</div>
</ItemContent>
</Item>
)}
{missions.length > 0 && (
<section className="flex flex-col gap-3">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Missions
</h2>
<span className="text-xs text-muted-foreground">
{missions.length} mission{missions.length !== 1 ? "s" : ""}
</span>
</div>
<div className="flex flex-col gap-2">
{missions.map((mission) => (
<MissionCard key={mission.id} mission={mission} showFullDetails={false} />
))}
</div>
</section>
)}
</div>
{/* ── Right Sidebar (1/3) ─────────────────────────── */}
<div className="flex flex-col gap-4">
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ScaleIcon className="size-4 text-muted-foreground" />
<ItemTitle>Standing</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Reputation</span>
<span className={`font-mono ${reputationTone(reputation).split(" ")[1]}`}>
{reputation >= 0 ? `+${reputation}` : reputation}
</span>
</div>
<div className="relative h-2 w-full overflow-hidden rounded-full bg-muted">
<div
className={`absolute top-0 h-full ${reputationTone(reputation).split(" ")[0]}`}
style={{
left:
reputation < 0
? "50%"
: `${50 - Math.min(Math.abs(reputation), 100) / 2}%`,
width: `${Math.min(Math.abs(reputation), 100) / 2}%`,
}}
/>
<div className="absolute left-1/2 top-0 h-full w-px bg-border" />
</div>
<p className="text-xs text-muted-foreground pt-1">
{reputationLabel(reputation)} standing in the world.
</p>
</div>
</ItemContent>
</Item>
{bankAccount && (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<LandmarkIcon className="size-4 text-muted-foreground" />
<ItemTitle>Bank Balance</ItemTitle>
</div>
<Link
href={`/logistics/banking/${bankAccount.id}`}
className="py-1 text-xs text-muted-foreground hover:text-primary transition-colors"
>
View
</Link>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-1">
<span className="text-lg font-semibold font-mono">
<CurrencyAmount value={bankAccount.balance ?? 0} currency={currencyConfig} />
</span>
<span className="text-xs text-muted-foreground">{bankAccount.name}</span>
{bankAccount.status !== "open" && (
<span className="text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded w-fit bg-amber-500/20 text-amber-400">
{bankAccount.status}
<div className="flex flex-col gap-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Reputation</span>
<span className={`font-mono ${reputationTone(reputation).split(" ")[1]}`}>
{reputation >= 0 ? `+${reputation}` : reputation}
</span>
)}
</div>
<div className="relative h-2 w-full overflow-hidden rounded-full bg-muted">
<div
className={`absolute top-0 h-full ${reputationTone(reputation).split(" ")[0]}`}
style={{
left:
reputation < 0
? "50%"
: `${50 - Math.min(Math.abs(reputation), 100) / 2}%`,
width: `${Math.min(Math.abs(reputation), 100) / 2}%`,
}}
/>
<div className="absolute left-1/2 top-0 h-full w-px bg-border" />
</div>
<p className="text-xs text-muted-foreground pt-1">
{reputationLabel(reputation)} standing in the world.
</p>
</div>
</ItemContent>
</Item>
)}
{campaigns.length > 0 && (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<FlagIcon className="size-4 text-muted-foreground" />
<ItemTitle>Associated Campaigns</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-1.5">
{campaigns.map((c) => {
const campaign = c as {
id: number;
name: string;
status?: string;
summary?: string;
};
return (
<Link
key={campaign.id}
href={`/intelligence/campaigns/${campaign.id}`}
className="flex items-center gap-3 p-1.5 rounded-md hover:bg-muted/50 transition-colors group"
>
<FlagIcon className="size-4 text-muted-foreground shrink-0" />
<div className="flex flex-col gap-0.5 min-w-0 flex-1">
<span className="text-sm font-medium truncate group-hover:text-primary transition-colors">
{campaign.name}
</span>
{campaign.summary && (
<span className="text-xs text-muted-foreground line-clamp-1">
{campaign.summary}
{bankAccount && (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<LandmarkIcon className="size-4 text-muted-foreground" />
<ItemTitle>Bank Balance</ItemTitle>
</div>
<Link
href={`/logistics/banking/${bankAccount.id}`}
className="py-1 text-xs text-muted-foreground hover:text-primary transition-colors"
>
View
</Link>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-1">
<span className="text-lg font-semibold font-mono">
<CurrencyAmount
value={bankAccount.balance ?? 0}
currency={currencyConfig}
/>
</span>
<span className="text-xs text-muted-foreground">{bankAccount.name}</span>
{bankAccount.status !== "open" && (
<span className="text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded w-fit bg-amber-500/20 text-amber-400">
{bankAccount.status}
</span>
)}
</div>
</ItemContent>
</Item>
)}
{campaigns.length > 0 && (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<FlagIcon className="size-4 text-muted-foreground" />
<ItemTitle>Associated Campaigns</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-1.5">
{campaigns.map((c) => {
const campaign = c as {
id: number;
name: string;
status?: string;
summary?: string;
};
return (
<Link
key={campaign.id}
href={`/intelligence/campaigns/${campaign.id}`}
className="flex items-center gap-3 p-1.5 rounded-md hover:bg-muted/50 transition-colors group"
>
<FlagIcon className="size-4 text-muted-foreground shrink-0" />
<div className="flex flex-col gap-0.5 min-w-0 flex-1">
<span className="text-sm font-medium truncate group-hover:text-primary transition-colors">
{campaign.name}
</span>
{campaign.summary && (
<span className="text-xs text-muted-foreground line-clamp-1">
{campaign.summary}
</span>
)}
</div>
{campaign.status && (
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1 py-0.5 rounded shrink-0 ${campaignStatusColors[campaign.status] ?? "bg-muted text-muted-foreground"}`}
>
{campaign.status === "inProgress"
? "In Progress"
: campaign.status === "onHold"
? "On Hold"
: campaign.status.charAt(0).toUpperCase() +
campaign.status.slice(1)}
</span>
)}
</div>
{campaign.status && (
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1 py-0.5 rounded shrink-0 ${campaignStatusColors[campaign.status] ?? "bg-muted text-muted-foreground"}`}
>
{campaign.status === "inProgress"
? "In Progress"
: campaign.status === "onHold"
? "On Hold"
: campaign.status.charAt(0).toUpperCase() +
campaign.status.slice(1)}
</span>
)}
<ChevronRightIcon className="size-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity shrink-0" />
</Link>
);
})}
</div>
</ItemContent>
</Item>
)}
<ChevronRightIcon className="size-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity shrink-0" />
</Link>
);
})}
</div>
</ItemContent>
</Item>
)}
</div>
</div>
</div>
)}
</div>
</div>
);

View file

@ -1,5 +1,6 @@
import config from "@payload-config";
import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import type { Faction } from "@/payload-types";
import { ShieldIcon } from "lucide-react";
import { FactionCard } from "@/components/frontend/intelligence/FactionCard";
@ -10,11 +11,16 @@ export const metadata = {
export default async function FactionsPage() {
const payload = await getPayload({ config });
const { user } = await payload.auth({
headers: await nextHeaders(),
canSetHeaders: false,
});
const factionsRes = await payload.find({
collection: "factions",
limit: 100,
depth: 1,
user,
});
const factions = factionsRes.docs as Faction[];

View file

@ -34,6 +34,7 @@ export default async function IntelligenceOverviewPage() {
payload.find({
collection: "factions",
limit: 100,
user,
select: { name: true, type: true },
}),
]);

View file

@ -41,6 +41,7 @@ export default async function BankingPage() {
collection: "factions",
limit: 100,
depth: 0,
user,
});
const factions = (factionsRes.docs as unknown as Faction[]).map((f) => ({
id: f.id,

View file

@ -1,5 +1,6 @@
import config from "@payload-config";
import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { Faction, GameStructure, Structure } from "@/payload-types";
import { StorageGrid } from "@/components/frontend/storage/StorageGrid";
import { Building2Icon } from "lucide-react";
@ -7,6 +8,10 @@ import { Building2Icon } from "lucide-react";
export default async function LogisticsPage() {
const payloadConfig = await config;
const payload = await getPayload({ config: payloadConfig });
const { user } = await payload.auth({
headers: await nextHeaders(),
canSetHeaders: false,
});
const structuresRes = await payload.find({
collection: "game-structures",
@ -18,6 +23,7 @@ export default async function LogisticsPage() {
collection: "factions",
depth: 0,
limit: 500,
user,
});
const structures = structuresRes.docs as unknown as (GameStructure & {

View file

@ -1,6 +1,7 @@
import config from "@payload-config";
import { getPayload } from "payload";
import Link from "next/link";
import { headers as nextHeaders } from "next/headers";
import type { Metadata } from "next";
import { Map as MapIcon, MapPinIcon } from "lucide-react";
import type { Campaign, Faction, Map as MapDoc, Media } from "@/payload-types";
@ -47,6 +48,12 @@ interface ReadoutCell {
export default async function MapPickerPage() {
const payload = await getPayload({ config: await config });
// Maps stay world-readable (overrideAccess), but the reader is still passed so
// populated factions run the discovery hook with the right clearance.
const { user } = await payload.auth({
headers: await nextHeaders(),
canSetHeaders: false,
});
const mapsRes = await payload.find({
collection: "maps",
@ -55,6 +62,7 @@ export default async function MapPickerPage() {
limit: 100,
depth: 1,
overrideAccess: true,
user,
});
const maps = mapsRes.docs.filter((map) => isWorldMapEntry(map));

View file

@ -34,6 +34,7 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
collection: "game-npcs",
id,
depth: 2,
user,
})) as unknown as GameNpc;
} catch {
notFound();

View file

@ -1,13 +1,10 @@
import config from "@payload-config";
import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import type { GameNpc } from "@/payload-types";
import { UsersIcon } from "lucide-react";
import { NpcDirectory } from "@/components/frontend/personnel/NpcDirectory";
import {
ClassificationStrip,
CornerBrackets,
DOSSIER,
} from "@/components/frontend/operations";
import { ClassificationStrip, CornerBrackets, DOSSIER } from "@/components/frontend/operations";
export const metadata = {
title: "Contacts: Polaris Task Force",
@ -15,10 +12,15 @@ export const metadata = {
export default async function ContactsPage() {
const payload = await getPayload({ config });
const { user } = await payload.auth({
headers: await nextHeaders(),
canSetHeaders: false,
});
const npcsRes = await payload.find({
collection: "game-npcs",
limit: 200,
depth: 1,
user,
});
const npcs = npcsRes.docs as unknown as GameNpc[];

View file

@ -74,6 +74,7 @@ Permission tiers and panel gates:
## Hooks with side effects
- `Factions` `afterRead`: masks undiscovered factions (name, description, standing, relationships, campaigns, cover image, playable/starting) for readers without `factions:view-undiscovered` or `system:admin-access`. Admin panel reads are exempt; see `src/lib/intelligence/factionDiscovery.ts`
- `Structures` `beforeChange`: emits `structure:resize`; blueprint "Staffing Defaults" group via `staffingFields.ts`
- `GameStructures` `afterChange`: emits storage edit events; `beforeChange` copies blueprint staffing defaults on create
- `Users` `afterChange`: maintains profile sync

View file

@ -1,5 +1,9 @@
import { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { isAdminPanelRequest, requirePermission } from "@/utils/access-control/hasPermission";
import {
canViewUndiscoveredFactions,
maskUndiscoveredFaction,
} from "@/lib/intelligence/factionDiscovery";
export const Factions: CollectionConfig = {
slug: "factions",
@ -36,6 +40,18 @@ export const Factions: CollectionConfig = {
return data;
},
],
afterRead: [
// Undiscovered factions stay readable; only their identity is masked.
// Admin panel reads are exempt: a masked edit form would write the
// placeholder name back over the record on save.
async ({ doc, req }) => {
const record = doc as unknown as { discovered?: boolean | null } | null;
if (!record || record.discovered !== false) return doc;
if (isAdminPanelRequest(req)) return doc;
if (await canViewUndiscoveredFactions(req.payload, req.user)) return doc;
return maskUndiscoveredFaction(doc);
},
],
},
fields: [
{
@ -76,6 +92,16 @@ export const Factions: CollectionConfig = {
"Player Faction = the faction our unit is currently playing as. Only one faction can carry this type at a time.",
},
},
{
name: "discovered",
type: "checkbox",
defaultValue: true,
index: true,
admin: {
description:
"Uncheck while players should not know this faction yet. The entry still appears in lists as UNDISCOVERED; name, description, standing, relationships, campaign links, cover image and the playable/starting flags are hidden from anyone without the View Undiscovered Factions permission.",
},
},
{
name: "description",
type: "richText",

View file

@ -10,13 +10,15 @@ import {
ItemTitle,
} from "@/components/ui/item";
import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintext";
import { ShieldIcon, UsersIcon } from "lucide-react";
import { EyeOffIcon, ShieldIcon, UsersIcon } from "lucide-react";
import { cn } from "@/lib/utils";
interface FactionCardProps {
faction: {
id: number;
name: string;
type: "playerFaction" | "majorFaction" | "minorFaction" | "corporation" | "special";
discovered?: boolean | null;
description?: {
root: {
type: string;
@ -72,26 +74,31 @@ function reputationLabel(rep: number): string {
}
export function FactionCard({ faction }: FactionCardProps) {
const description = faction.description
? convertLexicalToPlaintext({ data: faction.description })
: null;
// Undiscovered factions arrive masked from the collection hook; only `type`,
// `discovered` and the id survive. Render them as unknown contacts.
const undiscovered = faction.discovered === false;
const description =
!undiscovered && faction.description
? convertLexicalToPlaintext({ data: faction.description })
: null;
const truncatedDescription =
description && description.length > 150 ? description.slice(0, 150) + "…" : description;
const campaignCount = faction.associatedCampaigns?.length ?? 0;
const reputation = faction.reputation ?? 0;
const campaignCount = undiscovered ? 0 : (faction.associatedCampaigns?.length ?? 0);
const reputation = !undiscovered && faction.reputation != null ? faction.reputation : null;
return (
<Link href={`/intelligence/factions/${faction.id}`} className="block">
<Item
variant="outline"
className="cursor-pointer group transition-all duration-200 hover:scale-[1.01] hover:[box-shadow:inset_0_2px_8px_rgba(255,255,255,0.33)]"
className={cn(
"cursor-pointer group transition-all duration-200 hover:scale-[1.01] hover:[box-shadow:inset_0_2px_8px_rgba(255,255,255,0.33)]",
undiscovered && "border-dashed",
)}
>
<ItemHeader>
<div className="flex items-center gap-2">
<ItemMedia variant="icon">
<ShieldIcon />
</ItemMedia>
<ItemMedia variant="icon">{undiscovered ? <EyeOffIcon /> : <ShieldIcon />}</ItemMedia>
<ItemTitle>{faction.name}</ItemTitle>
</div>
<span
@ -106,21 +113,23 @@ export function FactionCard({ faction }: FactionCardProps) {
<p className="text-sm text-muted-foreground line-clamp-2">{truncatedDescription}</p>
)}
<div className="flex items-center gap-2 flex-wrap">
{faction.playableFaction && (
{!undiscovered && faction.playableFaction && (
<span className="text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-green-500/20 text-green-400">
Playable
</span>
)}
{faction.startingFaction && (
{!undiscovered && faction.startingFaction && (
<span className="text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-emerald-500/20 text-emerald-400">
Starting
</span>
)}
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded ${reputationTone(reputation)}`}
>
{reputationLabel(reputation)} ({reputation >= 0 ? `+${reputation}` : reputation})
</span>
{reputation !== null && (
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded ${reputationTone(reputation)}`}
>
{reputationLabel(reputation)} ({reputation >= 0 ? `+${reputation}` : reputation})
</span>
)}
{campaignCount > 0 && (
<span className="flex items-center gap-1 text-xs text-muted-foreground">
<UsersIcon className="size-3" />
@ -130,7 +139,11 @@ export function FactionCard({ faction }: FactionCardProps) {
</div>
</div>
</ItemContent>
<ItemDescription>{truncatedDescription ?? "No description provided."}</ItemDescription>
<ItemDescription>
{undiscovered
? "No intelligence available on this faction."
: (truncatedDescription ?? "No description provided.")}
</ItemDescription>
</Item>
</Link>
);

View file

@ -18,6 +18,7 @@ lib/
aim-trainer.ts # Pure aim-trainer game rules (difficulties, scoring, XP)
impersonation.ts # Admin impersonation cookie helpers
redaction.ts # Text redaction helper
intelligence/ # Mission lifecycle/reminders, briefings, faction discovery masking
versionInfo.ts # Build version display
arma-bridge/ # Arma server sync: auth, heartbeat/presence, commands, sync events
@ -71,6 +72,12 @@ base-tick script ── lib/base/tick.ts (processBaseTick: salaries, maintenance
## Key modules
### `redaction.ts`
`redactText()` replaces every non-space glyph with a block character, for spoilered copy (mission objectives, voiceover scripts).
### `intelligence/factionDiscovery.ts`
Faction discovery gate. `canViewUndiscoveredFactions(payload, user)` checks `factions:view-undiscovered` **or** `system:admin-access`; `maskUndiscoveredFaction(doc)` blanks name, description, standing, relationships, campaign links, cover image and the playable/starting flags. Consumed by the Factions `afterRead` hook, so masking applies to every reader (pages, REST, populated relationships) without per-page work. Admin panel reads are exempt so a masked edit form can never write a placeholder name back over a record.
### `storageRules.ts`
Enforcement order: **prohibited → whitelist → per-item cap**. Functions: `checkStorageDeposit`, `isResourceProhibited`, `isResourceWhitelisted`, `getResourceStorageCap`, `storageViolationMessage`. Used in structure actions, shipment creation, and arrival processing.

View file

@ -0,0 +1,49 @@
import type { Payload } from "payload";
import { hasPermission } from "@/utils/access-control/hasPermission";
/**
* Faction discovery: players have not met this faction yet.
*
* The `discovered` checkbox stays readable everywhere so each surface can render
* the unknown-contact treatment; everything that identifies the faction is
* replaced with placeholders in the Factions `afterRead` hook for readers
* without `factions:view-undiscovered` (or the superuser tier).
*/
export const UNDISCOVERED_FACTION_NAME = "UNDISCOVERED";
export const UNDISCOVERED_FACTION_SUMMARY =
"No signal intercepts, no assets on the ground, no records. This faction remains unidentified.";
type UserLike = { id: number | string; roleDocs?: unknown } | null | undefined;
/** Whether the reader may see undiscovered factions in full. */
export async function canViewUndiscoveredFactions(
payload: Payload,
user: UserLike,
): Promise<boolean> {
if (!user) return false;
const [permitted, adminTier] = await Promise.all([
hasPermission(payload, user, "factions:view-undiscovered"),
hasPermission(payload, user, "system:admin-access"),
]);
return permitted || adminTier;
}
/**
* Replace every identifying field of an undiscovered faction with a
* placeholder. `type` and `discovered` survive so cards still sort by type and
* render as unknown contacts rather than as empty records.
*/
export function maskUndiscoveredFaction<T extends object>(doc: T): T {
return {
...doc,
name: UNDISCOVERED_FACTION_NAME,
description: null,
reputation: null,
relationships: [],
playableFaction: false,
startingFaction: false,
associatedCampaigns: [],
coverImage: null,
} as T;
}

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -157,6 +157,7 @@ import * as migration_20261031_085035_add_mission_rating_sent_at_marker from './
import * as migration_20261031_090000_add_missions_discord_modlist_buffer_sent_at from './20261031_090000_add_missions_discord_modlist_buffer_sent_at';
import * as migration_20261101_210013_add_mission_command_links from './20261101_210013_add_mission_command_links';
import * as migration_20261112_171955_add_npc_dialogue_generation_provenance from './20261112_171955_add_npc_dialogue_generation_provenance';
import * as migration_20261117_212337_add_faction_discovered_field from './20261117_212337_add_faction_discovered_field';
export const migrations = [
{
@ -952,6 +953,11 @@ export const migrations = [
{
up: migration_20261112_171955_add_npc_dialogue_generation_provenance.up,
down: migration_20261112_171955_add_npc_dialogue_generation_provenance.down,
name: '20261112_171955_add_npc_dialogue_generation_provenance'
name: '20261112_171955_add_npc_dialogue_generation_provenance',
},
{
up: migration_20261117_212337_add_faction_discovered_field.up,
down: migration_20261117_212337_add_faction_discovered_field.down,
name: '20261117_212337_add_faction_discovered_field'
},
];

View file

@ -742,6 +742,7 @@ export interface Role {
| 'campaigns:manage'
| 'factions:create'
| 'factions:read'
| 'factions:view-undiscovered'
| 'factions:update'
| 'factions:delete'
| 'admin:factions:manage'
@ -2585,6 +2586,10 @@ export interface Faction {
* Player Faction = the faction our unit is currently playing as. Only one faction can carry this type at a time.
*/
type: 'playerFaction' | 'majorFaction' | 'minorFaction' | 'corporation' | 'special';
/**
* Uncheck while players should not know this faction yet. The entry still appears in lists as UNDISCOVERED; name, description, standing, relationships, campaign links, cover image and the playable/starting flags are hidden from anyone without the View Undiscovered Factions permission.
*/
discovered?: boolean | null;
description?: {
root: {
type: string;
@ -3307,6 +3312,7 @@ export interface GameEventLog {
| 'campaigns:manage'
| 'factions:create'
| 'factions:read'
| 'factions:view-undiscovered'
| 'factions:update'
| 'factions:delete'
| 'admin:factions:manage'
@ -10913,6 +10919,7 @@ export interface CampaignsSelect<T extends boolean = true> {
export interface FactionsSelect<T extends boolean = true> {
name?: T;
type?: T;
discovered?: T;
description?: T;
reputation?: T;
relationships?:

View file

@ -259,6 +259,10 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
permissions: [
{ value: "factions:create", label: "Create" },
{ value: "factions:read", label: "Read" },
{
value: "factions:view-undiscovered",
label: "View Undiscovered Factions (see factions the players have not found yet)",
},
{ value: "factions:update", label: "Update" },
{ value: "factions:delete", label: "Delete" },
{ value: "admin:factions:manage", label: "Manage Admin Page" },
@ -1004,6 +1008,7 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
"campaigns:manage",
"factions:create",
"factions:read",
"factions:view-undiscovered",
"factions:update",
"factions:delete",
"admin:factions:manage",

View file

@ -62,6 +62,7 @@ const ADMIN_PERMISSIONS: Permission[] = [
"mission-ratings:update",
"mission-ratings:delete",
"missions:read",
"factions:view-undiscovered",
"market-negotiations:read",
"market-negotiations:update",
"logistics:manage",

View file

@ -0,0 +1,273 @@
import { getTestPayload } from "../helpers/get-test-payload";
import type { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Faction, GameNpc, Role, User } from "@/payload-types";
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
import {
UNDISCOVERED_FACTION_NAME,
maskUndiscoveredFaction,
} from "@/lib/intelligence/factionDiscovery";
let payload: Payload;
const RUN = `factiondisc-${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
const DESCRIPTION = {
root: {
type: "root",
direction: null,
format: "" as const,
indent: 0,
version: 1,
children: [
{
type: "paragraph",
version: 1,
direction: null,
format: "" as const,
indent: 0,
children: [{ type: "text", version: 1, text: "Covert logistics and deniable assets." }],
},
],
},
};
describe("Faction discovery masking", () => {
const roleIds: number[] = [];
const userIds: number[] = [];
const factionIds: number[] = [];
const npcIds: number[] = [];
let reader: User;
let revealer: User;
let superUser: User;
let covertId: number;
let overtId: number;
let npcId: number;
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;
};
/** Local-API read as a real user, so collection access and afterRead hooks apply. */
const readAs = async (user: User | undefined, id: number): Promise<Faction | null> => {
const res = await payload.find({
collection: "factions",
where: { id: { equals: id } },
limit: 1,
depth: 1,
user: user as never,
overrideAccess: false,
});
return (res.docs[0] as Faction | undefined) ?? null;
};
beforeAll(async () => {
payload = await getTestPayload();
invalidatePermissionCache();
const readerRole = await makeRole("reader", { permissions: ["factions:read"] });
const revealerRole = await makeRole("revealer", {
permissions: ["factions:read", "factions:view-undiscovered"],
});
const superRole = await makeRole("super", { isSuperuser: true });
reader = await makeUser("reader", readerRole.id);
revealer = await makeUser("revealer", revealerRole.id);
superUser = await makeUser("super", superRole.id);
const overt = (await payload.create({
collection: "factions",
data: {
name: `${RUN}-Overt Combine`,
type: "corporation",
reputation: 24,
description: DESCRIPTION,
},
overrideAccess: true,
depth: 0,
})) as unknown as Faction;
factionIds.push(overt.id);
overtId = overt.id;
const covert = (await payload.create({
collection: "factions",
data: {
name: `${RUN}-Covert Directorate`,
type: "minorFaction",
discovered: false,
reputation: 64,
description: DESCRIPTION,
playableFaction: true,
startingFaction: true,
relationships: [{ targetFaction: overtId, value: -80, notes: "Black ops history" }],
associatedCampaigns: [],
},
overrideAccess: true,
depth: 0,
})) as unknown as Faction;
factionIds.push(covert.id);
covertId = covert.id;
const npc = (await payload.create({
collection: "game-npcs",
data: { name: `${RUN}-Courier`, faction: covertId },
overrideAccess: true,
depth: 0,
})) as unknown as GameNpc;
npcIds.push(npc.id);
npcId = npc.id;
invalidatePermissionCache();
}, TIMEOUT);
afterAll(async () => {
if (!payload) return;
for (const id of npcIds) {
await payload.delete({ collection: "game-npcs", id, overrideAccess: true }).catch(() => {});
}
for (const id of factionIds) {
await payload.delete({ collection: "factions", 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(() => {});
}
invalidatePermissionCache();
}, TIMEOUT);
it("masks an undiscovered faction for a plain reader", async () => {
const faction = await readAs(reader, covertId);
expect(faction).not.toBeNull();
const masked = faction as Faction;
expect(masked.name).toBe(UNDISCOVERED_FACTION_NAME);
expect(masked.description).toBeNull();
expect(masked.reputation).toBeNull();
expect(masked.relationships ?? []).toHaveLength(0);
expect(masked.playableFaction).toBe(false);
expect(masked.startingFaction).toBe(false);
expect(masked.coverImage ?? null).toBeNull();
// The type badge and the discovery flag survive so cards still render.
expect(masked.type).toBe("minorFaction");
expect(masked.discovered).toBe(false);
});
it("leaves a discovered faction untouched for the same reader", async () => {
const faction = (await readAs(reader, overtId)) as Faction;
expect(faction.name).toBe(`${RUN}-Overt Combine`);
expect(faction.reputation).toBe(24);
expect(faction.description).not.toBeNull();
});
it("shows the real record to readers holding factions:view-undiscovered", async () => {
const faction = (await readAs(revealer, covertId)) as Faction;
expect(faction.name).toBe(`${RUN}-Covert Directorate`);
expect(faction.reputation).toBe(64);
expect(faction.description).not.toBeNull();
expect(faction.relationships ?? []).toHaveLength(1);
expect(faction.playableFaction).toBe(true);
});
it("shows the real record to superusers", async () => {
const faction = (await readAs(superUser, covertId)) as Faction;
expect(faction.name).toBe(`${RUN}-Covert Directorate`);
expect(faction.reputation).toBe(64);
});
it("keeps the faction unreadable to anonymous requests", async () => {
await expect(
payload.find({
collection: "factions",
where: { id: { equals: covertId } },
limit: 1,
depth: 0,
overrideAccess: false,
}),
).rejects.toThrow(/not allowed/i);
});
it("masks the faction when it is populated through a relationship", async () => {
const asReader = await payload.find({
collection: "game-npcs",
where: { id: { equals: npcId } },
limit: 1,
depth: 1,
user: reader as never,
overrideAccess: false,
});
const readerNpc = asReader.docs[0] as GameNpc;
expect(typeof readerNpc.faction).toBe("object");
expect((readerNpc.faction as Faction).name).toBe(UNDISCOVERED_FACTION_NAME);
const asRevealer = await payload.find({
collection: "game-npcs",
where: { id: { equals: npcId } },
limit: 1,
depth: 1,
user: revealer as never,
overrideAccess: false,
});
const revealerNpc = asRevealer.docs[0] as GameNpc;
expect((revealerNpc.faction as Faction).name).toBe(`${RUN}-Covert Directorate`);
});
it("clears every identifying field in the masking helper", () => {
const masked = maskUndiscoveredFaction({
id: 42,
name: "Real Name",
type: "majorFaction",
discovered: false,
description: DESCRIPTION,
reputation: 90,
relationships: [{ id: "r1", targetFaction: 7, value: 10, notes: "n" }],
associatedCampaigns: [1, 2],
playableFaction: true,
startingFaction: true,
coverImage: 9,
});
expect(masked).toMatchObject({
id: 42,
name: UNDISCOVERED_FACTION_NAME,
type: "majorFaction",
discovered: false,
description: null,
reputation: null,
relationships: [],
associatedCampaigns: [],
playableFaction: false,
startingFaction: false,
coverImage: null,
});
});
});