feat(npc-dialogue): testing-only conversations for superusers
An npc-dialogues document can be marked testing, which keeps it off the player site while letting the superuser tier walk it live. Enforced in one module, lib/npc-dialogue/visibility.ts: the offer skips the conversation, its new-message badge never appears, and every node lookup re-checks visibility. Those lookups now name their conversation. The client sends dialogue.id and the server verifies it belongs to the NPC and is visible to the reader, so a player cannot read a testing conversation's nodes by guessing an id. The old lookup took limit: 1 on the NPC's conversations with no ordering, which with a testing conversation present could read the wrong document and silently skip an effect. Tester tier is system:admin-access, not every author: an officer who can edit conversations still cannot reach a testing one on the player site. Only an explicit true hides a conversation, so rows written before the flag stay live.
This commit is contained in:
parent
36f4bf5e1a
commit
1110315214
11 changed files with 47582 additions and 64 deletions
|
|
@ -11,6 +11,7 @@ import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpol
|
||||||
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||||
import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
|
import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
|
||||||
import { markNodeRead } from "@/lib/npc-dialogue/states";
|
import { markNodeRead } from "@/lib/npc-dialogue/states";
|
||||||
|
import { canSeeTestingDialogues, loadPlayerDialogue } from "@/lib/npc-dialogue/visibility";
|
||||||
import { resolveAttachments, resolveVoiceClip } from "@/lib/npc-dialogue/attachments";
|
import { resolveAttachments, resolveVoiceClip } from "@/lib/npc-dialogue/attachments";
|
||||||
import { transcodeToMp3, MP3_MIMETYPE } from "@/lib/voiceover/transcode";
|
import { transcodeToMp3, MP3_MIMETYPE } from "@/lib/voiceover/transcode";
|
||||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||||
|
|
@ -68,20 +69,23 @@ async function authenticate() {
|
||||||
* only trigger effects an admin has authored for this conversation.
|
* only trigger effects an admin has authored for this conversation.
|
||||||
*/
|
*/
|
||||||
export async function triggerNpcDialogueEvent(
|
export async function triggerNpcDialogueEvent(
|
||||||
|
dialogueId: number,
|
||||||
npcId: number,
|
npcId: number,
|
||||||
nodeId: string,
|
nodeId: string,
|
||||||
): Promise<ActionResult> {
|
): Promise<ActionResult> {
|
||||||
try {
|
try {
|
||||||
const { payload, user } = await authenticate();
|
const { payload, user } = await authenticate();
|
||||||
|
|
||||||
const res = await payload.find({
|
// The client names the conversation it is in; the id is verified (right
|
||||||
collection: "npc-dialogues",
|
// NPC, and visible to this reader) instead of trusted, so an unreleased
|
||||||
where: { npc: { equals: npcId } },
|
// testing conversation cannot be read by guessing a node id.
|
||||||
limit: 1,
|
const dialogue = await loadPlayerDialogue(payload, {
|
||||||
depth: 0,
|
npcId,
|
||||||
overrideAccess: true,
|
dialogueId,
|
||||||
|
userId: user.id as number,
|
||||||
|
canSeeTesting: await canSeeTestingDialogues(payload, user),
|
||||||
});
|
});
|
||||||
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
const flowData = dialogue?.flowData;
|
||||||
if (!flowData || !Array.isArray(flowData.nodes)) {
|
if (!flowData || !Array.isArray(flowData.nodes)) {
|
||||||
return { success: false, error: "This contact has no conversation configured." };
|
return { success: false, error: "This contact has no conversation configured." };
|
||||||
}
|
}
|
||||||
|
|
@ -189,20 +193,23 @@ async function runEffect(
|
||||||
* authored for this conversation.
|
* authored for this conversation.
|
||||||
*/
|
*/
|
||||||
export async function evaluateNpcDialogueCondition(
|
export async function evaluateNpcDialogueCondition(
|
||||||
|
dialogueId: number,
|
||||||
npcId: number,
|
npcId: number,
|
||||||
nodeId: string,
|
nodeId: string,
|
||||||
): Promise<ActionResult<boolean>> {
|
): Promise<ActionResult<boolean>> {
|
||||||
try {
|
try {
|
||||||
const { payload, user } = await authenticate();
|
const { payload, user } = await authenticate();
|
||||||
|
|
||||||
const res = await payload.find({
|
// The client names the conversation it is in; the id is verified (right
|
||||||
collection: "npc-dialogues",
|
// NPC, and visible to this reader) instead of trusted, so an unreleased
|
||||||
where: { npc: { equals: npcId } },
|
// testing conversation cannot be read by guessing a node id.
|
||||||
limit: 1,
|
const dialogue = await loadPlayerDialogue(payload, {
|
||||||
depth: 0,
|
npcId,
|
||||||
overrideAccess: true,
|
dialogueId,
|
||||||
|
userId: user.id as number,
|
||||||
|
canSeeTesting: await canSeeTestingDialogues(payload, user),
|
||||||
});
|
});
|
||||||
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
const flowData = dialogue?.flowData;
|
||||||
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
||||||
if (!node || node.type !== "condition" || !node.data.condition) {
|
if (!node || node.type !== "condition" || !node.data.condition) {
|
||||||
// Not a condition node: nothing to branch on.
|
// Not a condition node: nothing to branch on.
|
||||||
|
|
@ -229,20 +236,23 @@ export async function evaluateNpcDialogueCondition(
|
||||||
* config for conversations an admin has not authored.
|
* config for conversations an admin has not authored.
|
||||||
*/
|
*/
|
||||||
export async function evaluateNpcDialogueChoices(
|
export async function evaluateNpcDialogueChoices(
|
||||||
|
dialogueId: number,
|
||||||
npcId: number,
|
npcId: number,
|
||||||
nodeId: string,
|
nodeId: string,
|
||||||
): Promise<ActionResult<ChoiceGate[]>> {
|
): Promise<ActionResult<ChoiceGate[]>> {
|
||||||
try {
|
try {
|
||||||
const { payload, user } = await authenticate();
|
const { payload, user } = await authenticate();
|
||||||
|
|
||||||
const res = await payload.find({
|
// The client names the conversation it is in; the id is verified (right
|
||||||
collection: "npc-dialogues",
|
// NPC, and visible to this reader) instead of trusted, so an unreleased
|
||||||
where: { npc: { equals: npcId } },
|
// testing conversation cannot be read by guessing a node id.
|
||||||
limit: 1,
|
const dialogue = await loadPlayerDialogue(payload, {
|
||||||
depth: 0,
|
npcId,
|
||||||
overrideAccess: true,
|
dialogueId,
|
||||||
|
userId: user.id as number,
|
||||||
|
canSeeTesting: await canSeeTestingDialogues(payload, user),
|
||||||
});
|
});
|
||||||
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
const flowData = dialogue?.flowData;
|
||||||
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
||||||
if (!node || node.type !== "choice") {
|
if (!node || node.type !== "choice") {
|
||||||
// Not a choice node: nothing to gate.
|
// Not a choice node: nothing to gate.
|
||||||
|
|
@ -277,20 +287,23 @@ export async function evaluateNpcDialogueChoices(
|
||||||
* references are read; substituted values are never re-scanned for tokens.
|
* references are read; substituted values are never re-scanned for tokens.
|
||||||
*/
|
*/
|
||||||
export async function resolveNpcDialogueTexts(
|
export async function resolveNpcDialogueTexts(
|
||||||
|
dialogueId: number,
|
||||||
npcId: number,
|
npcId: number,
|
||||||
nodeId: string,
|
nodeId: string,
|
||||||
): Promise<ActionResult<ResolvedNodeTexts>> {
|
): Promise<ActionResult<ResolvedNodeTexts>> {
|
||||||
try {
|
try {
|
||||||
const { payload, user } = await authenticate();
|
const { payload, user } = await authenticate();
|
||||||
|
|
||||||
const res = await payload.find({
|
// The client names the conversation it is in; the id is verified (right
|
||||||
collection: "npc-dialogues",
|
// NPC, and visible to this reader) instead of trusted, so an unreleased
|
||||||
where: { npc: { equals: npcId } },
|
// testing conversation cannot be read by guessing a node id.
|
||||||
limit: 1,
|
const dialogue = await loadPlayerDialogue(payload, {
|
||||||
depth: 0,
|
npcId,
|
||||||
overrideAccess: true,
|
dialogueId,
|
||||||
|
userId: user.id as number,
|
||||||
|
canSeeTesting: await canSeeTestingDialogues(payload, user),
|
||||||
});
|
});
|
||||||
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
const flowData = dialogue?.flowData;
|
||||||
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
||||||
if (!node) return { success: true, data: {} };
|
if (!node) return { success: true, data: {} };
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,10 @@ import { getPayload } from "payload";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { headers as nextHeaders } from "next/headers";
|
import { headers as nextHeaders } from "next/headers";
|
||||||
import type { GameNpc, MarketListing, NpcStaffing } from "@/payload-types";
|
import type { GameNpc, MarketListing, NpcStaffing } from "@/payload-types";
|
||||||
import type { FlowData } from "@/lib/npc-dialogue/dialogue";
|
import {
|
||||||
import { selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
canSeeTestingDialogues,
|
||||||
import { evaluateCondition } from "@/lib/npc-dialogue/flags";
|
loadPlayerDialogue,
|
||||||
|
} from "@/lib/npc-dialogue/visibility";
|
||||||
import { listSeenNodeIds } from "@/lib/npc-dialogue/states";
|
import { listSeenNodeIds } from "@/lib/npc-dialogue/states";
|
||||||
import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings";
|
import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings";
|
||||||
import { resolveTypewriter } from "@/lib/npc-dialogue/presentation";
|
import { resolveTypewriter } from "@/lib/npc-dialogue/presentation";
|
||||||
|
|
@ -160,7 +161,11 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
||||||
|
|
||||||
const dialogue =
|
const dialogue =
|
||||||
npc.canMessage === true
|
npc.canMessage === true
|
||||||
? await pickDialogue(payload, id, user?.id as number | undefined)
|
? await loadPlayerDialogue(payload, {
|
||||||
|
npcId: id,
|
||||||
|
userId: user?.id as number | undefined,
|
||||||
|
canSeeTesting: await canSeeTestingDialogues(payload, user),
|
||||||
|
})
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
// Server-side NEW badges: which nodes has this player already read? Empty
|
// Server-side NEW badges: which nodes has this player already read? Empty
|
||||||
|
|
@ -216,29 +221,3 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Picks the conversation to offer this player: among all of the NPC's
|
|
||||||
* conversations, the highest-priority one whose entry gate passes (ungated
|
|
||||||
* always passes). Only the winner's flowchart leaves the server, so gated
|
|
||||||
* story content never reaches a client that has not unlocked it.
|
|
||||||
*/
|
|
||||||
async function pickDialogue(
|
|
||||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
|
||||||
npcId: number,
|
|
||||||
userId: number | undefined,
|
|
||||||
) {
|
|
||||||
const res = await payload.find({
|
|
||||||
collection: "npc-dialogues",
|
|
||||||
where: { npc: { equals: npcId } },
|
|
||||||
limit: 25,
|
|
||||||
depth: 0,
|
|
||||||
});
|
|
||||||
if (res.docs.length === 0) return null;
|
|
||||||
|
|
||||||
const chosen = await selectDialogueForUser(res.docs, async (condition) => {
|
|
||||||
if (!userId) return false;
|
|
||||||
return evaluateCondition(payload, userId, condition);
|
|
||||||
});
|
|
||||||
if (!chosen) return null;
|
|
||||||
return { id: chosen.id, flowData: chosen.flowData as unknown as FlowData | undefined };
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ export const NpcDialogues: CollectionConfig = {
|
||||||
group: "Game",
|
group: "Game",
|
||||||
useAsTitle: "name",
|
useAsTitle: "name",
|
||||||
listSearchableFields: ["name"],
|
listSearchableFields: ["name"],
|
||||||
defaultColumns: ["name", "npc", "priority"],
|
defaultColumns: ["name", "npc", "priority", "testing"],
|
||||||
pagination: { defaultLimit: 50 },
|
pagination: { defaultLimit: 50 },
|
||||||
},
|
},
|
||||||
access: {
|
access: {
|
||||||
|
|
@ -49,6 +49,16 @@ export const NpcDialogues: CollectionConfig = {
|
||||||
"When a contact has several conversations, the highest-priority one whose entry gate passes is the one offered. Ties break by oldest first.",
|
"When a contact has several conversations, the highest-priority one whose entry gate passes is the one offered. Ties break by oldest first.",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "testing",
|
||||||
|
type: "checkbox",
|
||||||
|
defaultValue: false,
|
||||||
|
label: "Testing: superusers only",
|
||||||
|
admin: {
|
||||||
|
description:
|
||||||
|
"Walk this conversation on the live site without releasing it. Only the superuser tier is offered it: players never see it or its new-message badge, and it cannot be resolved by guessing its id. Untick to publish.",
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "entryGate",
|
name: "entryGate",
|
||||||
type: "group",
|
type: "group",
|
||||||
|
|
|
||||||
|
|
@ -154,6 +154,9 @@ export function NpcConversation({
|
||||||
/** One element reused for every clip: a line's audio stops when the next
|
/** One element reused for every clip: a line's audio stops when the next
|
||||||
* starts, and the browser keeps its autoplay permission for the session. */
|
* starts, and the browser keeps its autoplay permission for the session. */
|
||||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||||
|
/** This conversation's id: node lookups name it so the server can verify the
|
||||||
|
* reader is in a conversation they are allowed to see. */
|
||||||
|
const dialogueId = dialogue?.id ?? null;
|
||||||
/** Sound is on unless the player turned it off or muted this session. */
|
/** Sound is on unless the player turned it off or muted this session. */
|
||||||
const [soundOn, setSoundOn] = useState(voice);
|
const [soundOn, setSoundOn] = useState(voice);
|
||||||
const soundOnRef = useRef(soundOn);
|
const soundOnRef = useRef(soundOn);
|
||||||
|
|
@ -211,7 +214,8 @@ export function NpcConversation({
|
||||||
);
|
);
|
||||||
if (!hasGated) return;
|
if (!hasGated) return;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
void evaluateNpcDialogueChoices(Number(npc.id), activeChoiceNodeId).then((res) => {
|
if (dialogueId === null) return;
|
||||||
|
void evaluateNpcDialogueChoices(dialogueId, Number(npc.id), activeChoiceNodeId).then((res) => {
|
||||||
if (!cancelled && res.success && Array.isArray(res.data)) {
|
if (!cancelled && res.success && Array.isArray(res.data)) {
|
||||||
const gate = res.data;
|
const gate = res.data;
|
||||||
setChoiceGates((prev) => ({ ...prev, [activeChoiceNodeId]: gate }));
|
setChoiceGates((prev) => ({ ...prev, [activeChoiceNodeId]: gate }));
|
||||||
|
|
@ -252,7 +256,8 @@ export function NpcConversation({
|
||||||
(node.data.attachments?.length ?? 0) > 0 ||
|
(node.data.attachments?.length ?? 0) > 0 ||
|
||||||
node.data.voice
|
node.data.voice
|
||||||
) {
|
) {
|
||||||
const res = await resolveNpcDialogueTexts(Number(npc.id), node.id);
|
if (dialogueId === null) return;
|
||||||
|
const res = await resolveNpcDialogueTexts(dialogueId, Number(npc.id), node.id);
|
||||||
if (sessionRef.current !== token) return;
|
if (sessionRef.current !== token) return;
|
||||||
if (res.success && res.data) resolved = res.data;
|
if (res.success && res.data) resolved = res.data;
|
||||||
}
|
}
|
||||||
|
|
@ -381,7 +386,12 @@ export function NpcConversation({
|
||||||
}
|
}
|
||||||
|
|
||||||
if (current.type === "condition") {
|
if (current.type === "condition") {
|
||||||
const result = await evaluateNpcDialogueCondition(Number(npc.id), current.id);
|
if (dialogueId === null) return;
|
||||||
|
const result = await evaluateNpcDialogueCondition(
|
||||||
|
dialogueId,
|
||||||
|
Number(npc.id),
|
||||||
|
current.id,
|
||||||
|
);
|
||||||
if (sessionRef.current !== token) return;
|
if (sessionRef.current !== token) return;
|
||||||
const branch =
|
const branch =
|
||||||
result.success && result.data ? current.data.trueTarget : current.data.falseTarget;
|
result.success && result.data ? current.data.trueTarget : current.data.falseTarget;
|
||||||
|
|
@ -395,7 +405,11 @@ export function NpcConversation({
|
||||||
if (current.type === "event" && current.data.effect) {
|
if (current.type === "event" && current.data.effect) {
|
||||||
// Await the effect so flags it writes are visible to the lines
|
// Await the effect so flags it writes are visible to the lines
|
||||||
// that follow (interpolated text and later condition nodes).
|
// that follow (interpolated text and later condition nodes).
|
||||||
await triggerNpcDialogueEvent(Number(npc.id), current.id).catch(() => undefined);
|
if (dialogueId !== null) {
|
||||||
|
await triggerNpcDialogueEvent(dialogueId, Number(npc.id), current.id).catch(
|
||||||
|
() => undefined,
|
||||||
|
);
|
||||||
|
}
|
||||||
if (sessionRef.current !== token) return;
|
if (sessionRef.current !== token) return;
|
||||||
}
|
}
|
||||||
const target: string | undefined = current.data.next?.target;
|
const target: string | undefined = current.data.next?.target;
|
||||||
|
|
|
||||||
|
|
@ -84,6 +84,23 @@ Availability is double-gated: `game-npcs.canMessage` on the contact, and the
|
||||||
`entryGate` / `priority` on the dialogue document selecting which of an NPC's
|
`entryGate` / `priority` on the dialogue document selecting which of an NPC's
|
||||||
conversations is offered.
|
conversations is offered.
|
||||||
|
|
||||||
|
`testing: true` on a conversation makes it superuser-only. The flag is enforced
|
||||||
|
in one place, `visibility.ts`, which both the offer and every node lookup call:
|
||||||
|
|
||||||
|
- **Who counts as a tester**: `system:admin-access` (the built-in admin role and
|
||||||
|
superuser roles), not every author. A division officer who can edit
|
||||||
|
conversations still cannot reach a testing one on the player site.
|
||||||
|
- **Absent means live**: only an explicit `true` hides a conversation. Rows
|
||||||
|
written before the flag existed read back as null and stay visible.
|
||||||
|
- **The claim is verified, never trusted**: the conversation client sends its
|
||||||
|
`dialogue.id` and each node lookup re-checks that the id belongs to the NPC and
|
||||||
|
is visible to the reader, so a player cannot read a testing conversation's
|
||||||
|
nodes by guessing an id. Those lookups used to take `limit: 1` on the NPC's
|
||||||
|
conversations with no ordering, which with a testing conversation present could
|
||||||
|
read the wrong document and silently skip an event effect.
|
||||||
|
- **Badges follow the offer**: the NEW marker comes from the offered
|
||||||
|
conversation, so a testing conversation never advertises itself to players.
|
||||||
|
|
||||||
## Flag conditions
|
## Flag conditions
|
||||||
|
|
||||||
Leaves test a `player-flags` value for the reading player, falling back to the
|
Leaves test a `player-flags` value for the reading player, falling back to the
|
||||||
|
|
|
||||||
111
src/lib/npc-dialogue/visibility.ts
Normal file
111
src/lib/npc-dialogue/visibility.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
/**
|
||||||
|
* Which conversations a player may be offered, and which one they are in.
|
||||||
|
*
|
||||||
|
* A conversation flagged `testing` is authorable but unreleased: superusers can
|
||||||
|
* walk it on the live site, players never see it, its "new" badge, or its text.
|
||||||
|
* Both decisions (the offer, and the node lookups that follow) go through this
|
||||||
|
* module so a flag cannot be enforced on one path and forgotten on another.
|
||||||
|
*
|
||||||
|
* Server only: it reads flags and media-adjacent state through Payload.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { Payload } from "payload";
|
||||||
|
|
||||||
|
import type { FlowData } from "./dialogue";
|
||||||
|
import { evaluateCondition } from "./flags";
|
||||||
|
import { selectDialogueForUser } from "./selection";
|
||||||
|
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||||
|
|
||||||
|
/** The part of an npc-dialogues document this module reads. */
|
||||||
|
export interface TestingAwareDialogue {
|
||||||
|
testing?: boolean | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A conversation as the conversation client needs it. */
|
||||||
|
export interface PlayerDialogue {
|
||||||
|
id: number;
|
||||||
|
flowData?: FlowData;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether this player may see an unreleased conversation. */
|
||||||
|
export function dialogueVisibleTo(doc: TestingAwareDialogue, canSeeTesting: boolean): boolean {
|
||||||
|
// Anything not explicitly flagged is live, including rows written before the
|
||||||
|
// flag existed (their column predates this check and may hold null).
|
||||||
|
return canSeeTesting || doc.testing !== true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this reader belongs to the superuser tier, which is what "testing
|
||||||
|
* only" means: the built-in admin role and superuser roles, not every author.
|
||||||
|
*/
|
||||||
|
export async function canSeeTestingDialogues(
|
||||||
|
payload: Payload,
|
||||||
|
user: { id: number | string; roleDocs?: unknown } | null | undefined,
|
||||||
|
): Promise<boolean> {
|
||||||
|
return hasPermission(payload, user, "system:admin-access");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The NPC a stored relationship points at, whichever depth it was read at. */
|
||||||
|
function relatedId(value: unknown): number | null {
|
||||||
|
if (typeof value === "number") return value;
|
||||||
|
if (value && typeof value === "object" && "id" in value) {
|
||||||
|
const id = (value as { id: unknown }).id;
|
||||||
|
return typeof id === "number" ? id : null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The conversation this player is in, or null when there is none.
|
||||||
|
*
|
||||||
|
* With `dialogueId` the client is claiming an active conversation: the claim is
|
||||||
|
* verified (right NPC, visible to this reader) rather than trusted, so a player
|
||||||
|
* cannot read a superuser-only conversation's nodes by guessing an id. Without
|
||||||
|
* it, this is the offer: the highest-priority conversation whose entry gate
|
||||||
|
* passes, skipping any the reader may not see.
|
||||||
|
*/
|
||||||
|
export async function loadPlayerDialogue(
|
||||||
|
payload: Payload,
|
||||||
|
options: {
|
||||||
|
npcId: number;
|
||||||
|
userId?: number | null;
|
||||||
|
canSeeTesting: boolean;
|
||||||
|
dialogueId?: number | null;
|
||||||
|
},
|
||||||
|
): Promise<PlayerDialogue | null> {
|
||||||
|
const { npcId, userId, canSeeTesting, dialogueId } = options;
|
||||||
|
|
||||||
|
if (dialogueId) {
|
||||||
|
const doc = await payload
|
||||||
|
.findByID({
|
||||||
|
collection: "npc-dialogues",
|
||||||
|
id: dialogueId,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
disableErrors: true,
|
||||||
|
})
|
||||||
|
.catch(() => null);
|
||||||
|
if (!doc) return null;
|
||||||
|
if (relatedId(doc.npc) !== Number(npcId)) return null;
|
||||||
|
if (!dialogueVisibleTo(doc, canSeeTesting)) return null;
|
||||||
|
return { id: doc.id, flowData: doc.flowData as unknown as FlowData | undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await payload.find({
|
||||||
|
collection: "npc-dialogues",
|
||||||
|
where: { npc: { equals: npcId } },
|
||||||
|
limit: 25,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Filter in code rather than in the query: an unset `testing` column is null,
|
||||||
|
// and `<> true` on null matches nothing, which would hide every older row.
|
||||||
|
const candidates = res.docs.filter((doc) => dialogueVisibleTo(doc, canSeeTesting));
|
||||||
|
const chosen = await selectDialogueForUser(candidates, async (condition) => {
|
||||||
|
if (!userId) return false;
|
||||||
|
return evaluateCondition(payload, userId, condition);
|
||||||
|
});
|
||||||
|
if (!chosen) return null;
|
||||||
|
return { id: chosen.id, flowData: chosen.flowData as unknown as FlowData | undefined };
|
||||||
|
}
|
||||||
47142
src/migrations/20261124_232253_add_npc_dialogue_testing_flag.json
Normal file
47142
src/migrations/20261124_232253_add_npc_dialogue_testing_flag.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,11 @@
|
||||||
|
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||||
|
|
||||||
|
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||||
|
await db.execute(sql`
|
||||||
|
ALTER TABLE "npc_dialogues" ADD COLUMN "testing" boolean DEFAULT false;`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||||
|
await db.execute(sql`
|
||||||
|
ALTER TABLE "npc_dialogues" DROP COLUMN "testing";`)
|
||||||
|
}
|
||||||
|
|
@ -169,6 +169,7 @@ import * as migration_20261124_175950_add_ai_connections from './20261124_175950
|
||||||
import * as migration_20261124_223219_add_defined_condition_ops from './20261124_223219_add_defined_condition_ops';
|
import * as migration_20261124_223219_add_defined_condition_ops from './20261124_223219_add_defined_condition_ops';
|
||||||
import * as migration_20261124_223724_add_conversation_typewriter_setting from './20261124_223724_add_conversation_typewriter_setting';
|
import * as migration_20261124_223724_add_conversation_typewriter_setting from './20261124_223724_add_conversation_typewriter_setting';
|
||||||
import * as migration_20261124_225400_add_conversation_voice_preference from './20261124_225400_add_conversation_voice_preference';
|
import * as migration_20261124_225400_add_conversation_voice_preference from './20261124_225400_add_conversation_voice_preference';
|
||||||
|
import * as migration_20261124_232253_add_npc_dialogue_testing_flag from './20261124_232253_add_npc_dialogue_testing_flag';
|
||||||
|
|
||||||
export const migrations = [
|
export const migrations = [
|
||||||
{
|
{
|
||||||
|
|
@ -1024,6 +1025,11 @@ export const migrations = [
|
||||||
{
|
{
|
||||||
up: migration_20261124_225400_add_conversation_voice_preference.up,
|
up: migration_20261124_225400_add_conversation_voice_preference.up,
|
||||||
down: migration_20261124_225400_add_conversation_voice_preference.down,
|
down: migration_20261124_225400_add_conversation_voice_preference.down,
|
||||||
name: '20261124_225400_add_conversation_voice_preference'
|
name: '20261124_225400_add_conversation_voice_preference',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
up: migration_20261124_232253_add_npc_dialogue_testing_flag.up,
|
||||||
|
down: migration_20261124_232253_add_npc_dialogue_testing_flag.down,
|
||||||
|
name: '20261124_232253_add_npc_dialogue_testing_flag'
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -3038,6 +3038,10 @@ export interface NpcDialogue {
|
||||||
* When a contact has several conversations, the highest-priority one whose entry gate passes is the one offered. Ties break by oldest first.
|
* When a contact has several conversations, the highest-priority one whose entry gate passes is the one offered. Ties break by oldest first.
|
||||||
*/
|
*/
|
||||||
priority?: number | null;
|
priority?: number | null;
|
||||||
|
/**
|
||||||
|
* Walk this conversation on the live site without releasing it. Only the superuser tier is offered it: players never see it or its new-message badge, and it cannot be resolved by guessing its id. Untick to publish.
|
||||||
|
*/
|
||||||
|
testing?: boolean | null;
|
||||||
/**
|
/**
|
||||||
* Only offer this conversation to players whose flags pass this condition. Leave the key empty to always offer it (ungated conversations are the fallback).
|
* Only offer this conversation to players whose flags pass this condition. Leave the key empty to always offer it (ungated conversations are the fallback).
|
||||||
*/
|
*/
|
||||||
|
|
@ -10281,6 +10285,7 @@ export interface NpcDialoguesSelect<T extends boolean = true> {
|
||||||
name?: T;
|
name?: T;
|
||||||
npc?: T;
|
npc?: T;
|
||||||
priority?: T;
|
priority?: T;
|
||||||
|
testing?: T;
|
||||||
entryGate?:
|
entryGate?:
|
||||||
| T
|
| T
|
||||||
| {
|
| {
|
||||||
|
|
|
||||||
210
tests/int/npc-dialogue-visibility.int.spec.ts
Normal file
210
tests/int/npc-dialogue-visibility.int.spec.ts
Normal file
|
|
@ -0,0 +1,210 @@
|
||||||
|
import { getTestPayload } from "../helpers/get-test-payload";
|
||||||
|
import { Payload } from "payload";
|
||||||
|
|
||||||
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import type { Role, User } from "@/payload-types";
|
||||||
|
import {
|
||||||
|
canSeeTestingDialogues,
|
||||||
|
dialogueVisibleTo,
|
||||||
|
loadPlayerDialogue,
|
||||||
|
} from "@/lib/npc-dialogue/visibility";
|
||||||
|
|
||||||
|
let payload: Payload;
|
||||||
|
|
||||||
|
const RUN = `vis-${Date.now().toString(36)}`;
|
||||||
|
const TIMEOUT = 30_000;
|
||||||
|
|
||||||
|
const FLOW = { nodes: [], edges: [] };
|
||||||
|
|
||||||
|
describe("dialogue visibility (testing flag)", () => {
|
||||||
|
const roleIds: number[] = [];
|
||||||
|
const userIds: number[] = [];
|
||||||
|
const dialogueIds: number[] = [];
|
||||||
|
let npcId: number;
|
||||||
|
let otherNpcId: number;
|
||||||
|
let superUser: User;
|
||||||
|
let plainUser: User;
|
||||||
|
let testingId: number;
|
||||||
|
let liveId: number;
|
||||||
|
|
||||||
|
const makeRole = async (label: string, isSuperuser = false): Promise<Role> =>
|
||||||
|
(await payload.create({
|
||||||
|
collection: "roles",
|
||||||
|
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, isSuperuser },
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
})) as unknown as Role;
|
||||||
|
|
||||||
|
const makeUser = async (label: string, roleId: number): Promise<User> => {
|
||||||
|
const user = (await payload.create({
|
||||||
|
collection: "users",
|
||||||
|
data: {
|
||||||
|
username: `${RUN}-${label}`,
|
||||||
|
discordUsername: `${RUN}-${label}`,
|
||||||
|
displayName: label.toUpperCase(),
|
||||||
|
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
||||||
|
password: "Test123",
|
||||||
|
roleDocs: [roleId],
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
})) as unknown as User;
|
||||||
|
userIds.push(user.id);
|
||||||
|
return user;
|
||||||
|
};
|
||||||
|
|
||||||
|
const makeNpc = async (label: string): Promise<number> =>
|
||||||
|
(
|
||||||
|
(await payload.create({
|
||||||
|
collection: "game-npcs",
|
||||||
|
data: { name: `${RUN}-${label}`, canMessage: true },
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
})) as unknown as { id: number }
|
||||||
|
).id;
|
||||||
|
|
||||||
|
const makeDialogue = async (
|
||||||
|
label: string,
|
||||||
|
npc: number,
|
||||||
|
data: { priority: number; testing?: boolean },
|
||||||
|
): Promise<number> => {
|
||||||
|
const doc = (await payload.create({
|
||||||
|
collection: "npc-dialogues",
|
||||||
|
data: { name: `${RUN}-${label}`, npc, flowData: FLOW, ...data },
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
})) as unknown as { id: number };
|
||||||
|
dialogueIds.push(doc.id);
|
||||||
|
return doc.id;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The real path: the reader's tier decides what the claim may resolve. */
|
||||||
|
const offerTo = async (user: User, npc: number, dialogueId?: number) =>
|
||||||
|
loadPlayerDialogue(payload, {
|
||||||
|
npcId: npc,
|
||||||
|
userId: user.id,
|
||||||
|
canSeeTesting: await canSeeTestingDialogues(payload, user),
|
||||||
|
dialogueId,
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
payload = await getTestPayload();
|
||||||
|
|
||||||
|
const superRole = await makeRole("super", true);
|
||||||
|
roleIds.push(superRole.id);
|
||||||
|
const plainRole = await makeRole("plain");
|
||||||
|
roleIds.push(plainRole.id);
|
||||||
|
|
||||||
|
superUser = await makeUser("super", superRole.id);
|
||||||
|
plainUser = await makeUser("plain", plainRole.id);
|
||||||
|
|
||||||
|
npcId = await makeNpc("npc");
|
||||||
|
otherNpcId = await makeNpc("other");
|
||||||
|
testingId = await makeDialogue("testing", npcId, { priority: 10, testing: true });
|
||||||
|
liveId = await makeDialogue("live", npcId, { priority: 0 });
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (!payload) return;
|
||||||
|
for (const id of dialogueIds) {
|
||||||
|
await payload.delete({ collection: "npc-dialogues", id, overrideAccess: true }).catch(() => {});
|
||||||
|
}
|
||||||
|
for (const id of [npcId, otherNpcId]) {
|
||||||
|
if (!id) continue;
|
||||||
|
await payload.delete({ collection: "game-npcs", id, overrideAccess: true }).catch(() => {});
|
||||||
|
}
|
||||||
|
for (const id of userIds) {
|
||||||
|
const profiles = await payload
|
||||||
|
.find({
|
||||||
|
collection: "profiles",
|
||||||
|
where: { user: { equals: id } },
|
||||||
|
limit: 5,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
.catch(() => null);
|
||||||
|
for (const profile of profiles?.docs ?? []) {
|
||||||
|
await payload
|
||||||
|
.delete({ collection: "profiles", id: profile.id, overrideAccess: true })
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
||||||
|
}
|
||||||
|
for (const id of roleIds) {
|
||||||
|
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("treats only an explicit true as unreleased", () => {
|
||||||
|
expect(dialogueVisibleTo({ testing: true }, false)).toBe(false);
|
||||||
|
expect(dialogueVisibleTo({ testing: false }, false)).toBe(true);
|
||||||
|
expect(dialogueVisibleTo({}, false)).toBe(true);
|
||||||
|
// Rows written before the flag existed read back as null, not false.
|
||||||
|
expect(dialogueVisibleTo({ testing: null }, false)).toBe(true);
|
||||||
|
expect(dialogueVisibleTo({ testing: true }, true)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it(
|
||||||
|
"reserves the superuser tier, not every author",
|
||||||
|
async () => {
|
||||||
|
expect(await canSeeTestingDialogues(payload, superUser)).toBe(true);
|
||||||
|
expect(await canSeeTestingDialogues(payload, plainUser)).toBe(false);
|
||||||
|
expect(await canSeeTestingDialogues(payload, null)).toBe(false);
|
||||||
|
},
|
||||||
|
TIMEOUT,
|
||||||
|
);
|
||||||
|
|
||||||
|
it(
|
||||||
|
"offers a player the live conversation even when a testing one outranks it",
|
||||||
|
async () => {
|
||||||
|
const offered = await loadPlayerDialogue(payload, {
|
||||||
|
npcId,
|
||||||
|
userId: plainUser.id,
|
||||||
|
canSeeTesting: await canSeeTestingDialogues(payload, plainUser),
|
||||||
|
});
|
||||||
|
expect(offered?.id).toBe(liveId);
|
||||||
|
},
|
||||||
|
TIMEOUT,
|
||||||
|
);
|
||||||
|
|
||||||
|
it(
|
||||||
|
"offers a superuser the testing conversation",
|
||||||
|
async () => {
|
||||||
|
const offered = await loadPlayerDialogue(payload, {
|
||||||
|
npcId,
|
||||||
|
userId: superUser.id,
|
||||||
|
canSeeTesting: await canSeeTestingDialogues(payload, superUser),
|
||||||
|
});
|
||||||
|
expect(offered?.id).toBe(testingId);
|
||||||
|
},
|
||||||
|
TIMEOUT,
|
||||||
|
);
|
||||||
|
|
||||||
|
it(
|
||||||
|
"refuses a testing conversation named by a player, and allows a superuser",
|
||||||
|
async () => {
|
||||||
|
expect(await offerTo(plainUser, npcId, testingId)).toBeNull();
|
||||||
|
expect((await offerTo(superUser, npcId, testingId))?.id).toBe(testingId);
|
||||||
|
// A live conversation is still readable by its id for anyone.
|
||||||
|
expect((await offerTo(plainUser, npcId, liveId))?.id).toBe(liveId);
|
||||||
|
},
|
||||||
|
TIMEOUT,
|
||||||
|
);
|
||||||
|
|
||||||
|
it(
|
||||||
|
"rejects a conversation that belongs to another NPC",
|
||||||
|
async () => {
|
||||||
|
expect(await offerTo(superUser, otherNpcId, testingId)).toBeNull();
|
||||||
|
},
|
||||||
|
TIMEOUT,
|
||||||
|
);
|
||||||
|
|
||||||
|
it(
|
||||||
|
"rejects a conversation id that does not exist",
|
||||||
|
async () => {
|
||||||
|
expect(await offerTo(superUser, npcId, 2_000_000_000)).toBeNull();
|
||||||
|
},
|
||||||
|
TIMEOUT,
|
||||||
|
);
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue