feat(wiki): add private drafts with a one-way publish
Wiki pages gain a Draft flag pinned to their original creator. A draft is visible only to its creator, wiki moderators and admins: the collection's read access returns a where clause so the REST/local API filters drafts, and every frontend query ANDs the same clause (they run with overrideAccess). Publishing is one-way. A page whose stored draft is false is rejected (403) when sent draft: true, both in the service and in access.update. UI: amber DraftBanner on the detail page, a Draft chip in WikiRow, and a Draft switch in the editor that disables once the page is published.
This commit is contained in:
parent
def32f2c82
commit
b5f48de0b9
19 changed files with 550 additions and 19 deletions
|
|
@ -7,7 +7,12 @@ import { ArrowLeftIcon, PencilIcon } from "lucide-react";
|
|||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { LockdownBanner } from "@/components/frontend/wiki/LockdownBanner";
|
||||
import { WikiEditor } from "@/components/frontend/wiki/WikiEditor";
|
||||
import { listTemplates, templateMap } from "@/lib/wiki/service";
|
||||
import {
|
||||
canViewAllDrafts,
|
||||
draftVisibilityWhere,
|
||||
listTemplates,
|
||||
templateMap,
|
||||
} from "@/lib/wiki/service";
|
||||
import hasRoles from "@/utils/access-control/hasRoles";
|
||||
|
||||
export const metadata = {
|
||||
|
|
@ -43,9 +48,12 @@ export default async function EditWikiPage({
|
|||
const payload = await getPayload({ config });
|
||||
const headers = await nextHeaders();
|
||||
const { user } = await payload.auth({ headers, canSetHeaders: false });
|
||||
const draftClause = draftVisibilityWhere(user, await canViewAllDrafts(payload, user));
|
||||
const pageResult = await payload.find({
|
||||
collection: "wiki-pages",
|
||||
where: { slug: { equals: slug } },
|
||||
where: draftClause
|
||||
? { AND: [{ slug: { equals: slug } }, draftClause] }
|
||||
: { slug: { equals: slug } },
|
||||
limit: 1,
|
||||
depth: 1,
|
||||
overrideAccess: true,
|
||||
|
|
@ -104,6 +112,7 @@ export default async function EditWikiPage({
|
|||
listTemplates(payload),
|
||||
payload.find({
|
||||
collection: "wiki-pages",
|
||||
where: draftVisibilityWhere(user, await canViewAllDrafts(payload, user)) ?? {},
|
||||
sort: "title",
|
||||
limit: 200,
|
||||
depth: 0,
|
||||
|
|
@ -152,6 +161,7 @@ export default async function EditWikiPage({
|
|||
category: page.category,
|
||||
tags: page.tags ?? [],
|
||||
body: page.body,
|
||||
draft: page.draft === true,
|
||||
}}
|
||||
templates={templateMap(templates)}
|
||||
templateCssMap={templateCssMap(templates)}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import { Button } from "@/components/ui/button";
|
|||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { RevisionList, type WikiRevisionSummary } from "@/components/frontend/wiki/RevisionList";
|
||||
import { hasIntelligenceQualification } from "@/utils/access-control/hasIntelligenceQualification";
|
||||
import { canViewAllDrafts, draftVisibilityWhere } from "@/lib/wiki/service";
|
||||
|
||||
export const metadata = {
|
||||
title: "Wiki history: Polaris Task Force",
|
||||
|
|
@ -52,9 +53,12 @@ export default async function WikiHistoryPage({
|
|||
headers,
|
||||
canSetHeaders: false,
|
||||
});
|
||||
const draftClause = draftVisibilityWhere(user, await canViewAllDrafts(payload, user));
|
||||
const pageResult = await payload.find({
|
||||
collection: "wiki-pages",
|
||||
where: { slug: { equals: slug } },
|
||||
where: draftClause
|
||||
? { AND: [{ slug: { equals: slug } }, draftClause] }
|
||||
: { slug: { equals: slug } },
|
||||
limit: 1,
|
||||
depth: 1,
|
||||
overrideAccess: true,
|
||||
|
|
|
|||
|
|
@ -8,11 +8,17 @@ import { Badge } from "@/components/ui/badge";
|
|||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { LockdownBanner } from "@/components/frontend/wiki/LockdownBanner";
|
||||
import { DraftBanner } from "@/components/frontend/wiki/DraftBanner";
|
||||
import { WikiPageViewMeta } from "@/components/frontend/wiki/WikiPageViewMeta";
|
||||
import { WikiContent } from "@/components/frontend/wiki/WikiContent";
|
||||
import { WikiToolbar } from "@/components/frontend/wiki/WikiToolbar";
|
||||
import { hasIntelligenceQualification } from "@/utils/access-control/hasIntelligenceQualification";
|
||||
import { listTemplates, templateMap } from "@/lib/wiki/service";
|
||||
import {
|
||||
canViewAllDrafts,
|
||||
draftVisibilityWhere,
|
||||
listTemplates,
|
||||
templateMap,
|
||||
} from "@/lib/wiki/service";
|
||||
import { prepareMarkdown } from "@/lib/wiki/prepare";
|
||||
import { buildTemplateStyles } from "@/lib/wiki/templateCss";
|
||||
|
||||
|
|
@ -70,9 +76,12 @@ export default async function WikiDetailPage({
|
|||
canSetHeaders: false,
|
||||
});
|
||||
|
||||
const draftClause = draftVisibilityWhere(user, await canViewAllDrafts(payload, user));
|
||||
const pageResult = await payload.find({
|
||||
collection: "wiki-pages",
|
||||
where: { slug: { equals: slug } },
|
||||
where: draftClause
|
||||
? { AND: [{ slug: { equals: slug } }, draftClause] }
|
||||
: { slug: { equals: slug } },
|
||||
limit: 1,
|
||||
depth: 1,
|
||||
overrideAccess: true,
|
||||
|
|
@ -239,6 +248,8 @@ export default async function WikiDetailPage({
|
|||
|
||||
{lockdown && <LockdownBanner />}
|
||||
|
||||
{page.draft && <DraftBanner />}
|
||||
|
||||
<WikiPageViewMeta slug={page.slug} />
|
||||
|
||||
<article>
|
||||
|
|
|
|||
|
|
@ -87,6 +87,7 @@ export async function createWikiPage(input: {
|
|||
tags?: string[];
|
||||
body: string;
|
||||
summary?: string;
|
||||
draft?: boolean;
|
||||
}): Promise<ActionResult<{ id: number; slug: string; awardedXp: number }>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
|
@ -134,6 +135,7 @@ export async function updateWikiPage(input: {
|
|||
category?: string;
|
||||
tags?: string[];
|
||||
summary?: string;
|
||||
draft?: boolean;
|
||||
}): Promise<ActionResult<{ id: number; slug: string; awardedXp: number }>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
|
|
|||
|
|
@ -3,12 +3,14 @@ import { headers as nextHeaders } from "next/headers";
|
|||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { getPayload } from "payload";
|
||||
import type { Where } from "payload";
|
||||
import { ArrowLeftIcon, BookOpenIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { WikiRow } from "@/components/frontend/wiki/WikiRow";
|
||||
import { CATEGORY_META, WIKI_CATEGORIES, type WikiCategory } from "@/lib/wiki/categories";
|
||||
import { collectTagCounts, mapWikiPageToEntry } from "@/lib/wiki/indexView";
|
||||
import { canViewAllDrafts, draftVisibilityWhere } from "@/lib/wiki/service";
|
||||
|
||||
export const metadata = {
|
||||
title: "Wiki category: Polaris Task Force",
|
||||
|
|
@ -27,9 +29,16 @@ export default async function WikiCategoryPage({
|
|||
|
||||
const headers = await nextHeaders();
|
||||
const payload = await getPayload({ config });
|
||||
const { user } = await payload.auth({ headers, canSetHeaders: false });
|
||||
const draftClause = draftVisibilityWhere(user, await canViewAllDrafts(payload, user));
|
||||
const where = (
|
||||
draftClause
|
||||
? { AND: [{ category: { equals: category } }, draftClause] }
|
||||
: { category: { equals: category } }
|
||||
) as Where;
|
||||
const pagesResult = await payload.find({
|
||||
collection: "wiki-pages",
|
||||
where: { category: { equals: category } },
|
||||
where,
|
||||
sort: "-updatedAt",
|
||||
limit: 200,
|
||||
depth: 1,
|
||||
|
|
|
|||
|
|
@ -4,7 +4,12 @@ import { headers as nextHeaders } from "next/headers";
|
|||
import { getPayload } from "payload";
|
||||
import { ArrowLeftIcon, FilePlus2Icon } from "lucide-react";
|
||||
import { WikiEditor } from "@/components/frontend/wiki/WikiEditor";
|
||||
import { listTemplates, templateMap } from "@/lib/wiki/service";
|
||||
import {
|
||||
canViewAllDrafts,
|
||||
draftVisibilityWhere,
|
||||
listTemplates,
|
||||
templateMap,
|
||||
} from "@/lib/wiki/service";
|
||||
import hasRoles from "@/utils/access-control/hasRoles";
|
||||
|
||||
export const metadata = {
|
||||
|
|
@ -45,6 +50,7 @@ export default async function NewWikiPage({
|
|||
listTemplates(payload),
|
||||
payload.find({
|
||||
collection: "wiki-pages",
|
||||
where: draftVisibilityWhere(user, await canViewAllDrafts(payload, user)) ?? {},
|
||||
sort: "title",
|
||||
limit: 200,
|
||||
depth: 0,
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { getPayload } from "payload";
|
|||
import { BookOpenIcon } from "lucide-react";
|
||||
import { WikiIndex } from "@/components/frontend/wiki/WikiIndex";
|
||||
import { mapWikiPageToEntry } from "@/lib/wiki/indexView";
|
||||
import { canViewAllDrafts, draftVisibilityWhere } from "@/lib/wiki/service";
|
||||
import { hasIntelligenceQualification } from "@/utils/access-control/hasIntelligenceQualification";
|
||||
|
||||
export const metadata = {
|
||||
|
|
@ -19,9 +20,12 @@ export default async function WikiPage() {
|
|||
canSetHeaders: false,
|
||||
});
|
||||
|
||||
const canViewAll = await canViewAllDrafts(payload, user);
|
||||
const where = draftVisibilityWhere(user, canViewAll);
|
||||
const [pagesResult, isModerator] = await Promise.all([
|
||||
payload.find({
|
||||
collection: "wiki-pages",
|
||||
where: where ?? {},
|
||||
sort: "-updatedAt",
|
||||
limit: 200,
|
||||
depth: 1,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { CollectionConfig } from "payload";
|
||||
import { CollectionConfig, Where } from "payload";
|
||||
import { hasIntelligenceQualification } from "@/utils/access-control/hasIntelligenceQualification";
|
||||
import hasRoles from "@/utils/access-control/hasRoles";
|
||||
|
||||
|
|
@ -26,7 +26,20 @@ export const WikiPages: CollectionConfig = {
|
|||
pagination: { defaultLimit: 50 },
|
||||
},
|
||||
access: {
|
||||
read: ({ req }) => !!req.user,
|
||||
// Return a `where` clause (not a per-document boolean) so Payload filters
|
||||
// drafts out of `find` results for everyone except their creator, wiki
|
||||
// moderators and admins. Payload also applies it to findByID.
|
||||
read: async ({ req }) => {
|
||||
if (!req.user) return false;
|
||||
if (await hasIntelligenceQualification(req.payload, req.user)) return true;
|
||||
if (hasRoles(["admin"], req.user)) return true;
|
||||
return {
|
||||
OR: [
|
||||
{ draft: { equals: false } },
|
||||
{ draft: { equals: true }, createdBy: { equals: req.user.id } },
|
||||
],
|
||||
} as Where;
|
||||
},
|
||||
create: ({ req, data }) => {
|
||||
if (!req.user) return false;
|
||||
if (isDocumentationCategory(data?.category)) {
|
||||
|
|
@ -58,6 +71,24 @@ export const WikiPages: CollectionConfig = {
|
|||
return true;
|
||||
}
|
||||
}
|
||||
// One-way publish: a published page (draft=false) may never be set back
|
||||
// to draft. A draft may be published (draft=true -> false).
|
||||
if (data?.draft === true && typeof id === "number") {
|
||||
try {
|
||||
const existing = (await req.payload.findByID({
|
||||
collection: "wiki-pages",
|
||||
id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})) as unknown as { draft?: boolean } | null;
|
||||
if (existing && existing.draft === false) {
|
||||
return false;
|
||||
}
|
||||
} catch {
|
||||
// Unknown id: let the operation proceed and fail validation later.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
delete: async ({ req }) => {
|
||||
|
|
@ -161,5 +192,28 @@ export const WikiPages: CollectionConfig = {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "draft",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: {
|
||||
description:
|
||||
"Private to the author. Drafts are hidden from everyone except the creator, wiki moderators, and admins.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "createdBy",
|
||||
type: "relationship",
|
||||
relationTo: "users",
|
||||
admin: {
|
||||
hidden: true,
|
||||
},
|
||||
// Authorship is set once by the service layer (overrideAccess) and never
|
||||
// by a client, so nobody can reassign a draft's owner through the API.
|
||||
access: {
|
||||
create: () => false,
|
||||
update: () => false,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
|
|||
19
src/components/frontend/wiki/DraftBanner.tsx
Normal file
19
src/components/frontend/wiki/DraftBanner.tsx
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { FileTextIcon } from "lucide-react";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
|
||||
/**
|
||||
* Shown on the detail page of a draft wiki article. Drafts are private to their
|
||||
* author (plus wiki moderators and admins), so this reminds editors they are
|
||||
* still working in public and that others cannot see the page yet.
|
||||
*/
|
||||
export function DraftBanner() {
|
||||
return (
|
||||
<Alert className="border-sky-500/40 bg-sky-500/10 [&>svg]:text-sky-400">
|
||||
<FileTextIcon />
|
||||
<AlertTitle>Draft</AlertTitle>
|
||||
<AlertDescription>
|
||||
This article is a draft and only visible to you, wiki moderators, and admins.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import { toast } from "sonner";
|
|||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
|
|
@ -34,6 +35,7 @@ export interface WikiEditorInitial {
|
|||
readonly category: WikiCategory;
|
||||
readonly tags: readonly string[];
|
||||
readonly body: string;
|
||||
readonly draft: boolean;
|
||||
}
|
||||
|
||||
interface WikiEditorProps {
|
||||
|
|
@ -86,6 +88,7 @@ export function WikiEditor({
|
|||
const [tags, setTags] = useState(initial?.tags.join(", ") ?? "");
|
||||
const [summary, setSummary] = useState("");
|
||||
const [body, setBody] = useState(initial?.body ?? "");
|
||||
const [draft, setDraft] = useState(initial?.draft ?? false);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
|
||||
const [showStandards, setShowStandards] = useState(() => {
|
||||
|
|
@ -129,6 +132,7 @@ export function WikiEditor({
|
|||
category,
|
||||
tags: parsedTags,
|
||||
body,
|
||||
draft,
|
||||
...(trimmedSummary ? { summary: trimmedSummary } : {}),
|
||||
})
|
||||
: initial
|
||||
|
|
@ -138,6 +142,7 @@ export function WikiEditor({
|
|||
category,
|
||||
tags: parsedTags,
|
||||
body,
|
||||
draft,
|
||||
...(trimmedSummary ? { summary: trimmedSummary } : {}),
|
||||
})
|
||||
: { success: false, error: "This page could not be loaded for editing." };
|
||||
|
|
@ -225,6 +230,23 @@ export function WikiEditor({
|
|||
disabled={pending}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5 sm:col-span-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Label>Draft</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{mode === "create"
|
||||
? "Check to keep this page private to you until you are ready to publish it."
|
||||
: "Uncheck to publish. A published article cannot be set back to draft."}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={draft}
|
||||
onCheckedChange={(next) => setDraft(next)}
|
||||
disabled={pending || (mode === "edit" && !initial?.draft)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 items-start gap-4 lg:grid-cols-2">
|
||||
|
|
|
|||
|
|
@ -41,12 +41,19 @@ export function WikiRow({ page, tagLinkBase, activeTag = "", onTagClick }: WikiR
|
|||
return (
|
||||
<article className="relative flex flex-col gap-1 px-4 py-2.5 transition-colors hover:bg-accent/40 sm:flex-row sm:items-center sm:justify-between sm:gap-6">
|
||||
<div className="min-w-0">
|
||||
<Link
|
||||
href={`/wiki/${page.slug}`}
|
||||
className="text-sm font-medium after:absolute after:inset-0 after:content-['']"
|
||||
>
|
||||
{page.title}
|
||||
</Link>
|
||||
<div className="flex items-center gap-2">
|
||||
{page.draft && (
|
||||
<span className="inline-flex items-center rounded-sm border border-sky-500/40 bg-sky-500/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-sky-400">
|
||||
Draft
|
||||
</span>
|
||||
)}
|
||||
<Link
|
||||
href={`/wiki/${page.slug}`}
|
||||
className="text-sm font-medium after:absolute after:inset-0 after:content-['']"
|
||||
>
|
||||
{page.title}
|
||||
</Link>
|
||||
</div>
|
||||
{page.excerpt && (
|
||||
<p className="line-clamp-1 text-xs text-muted-foreground">{page.excerpt}</p>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@
|
|||
|
||||
`src/collections/wiki/`: `wiki-pages`, `wiki-revisions`, `wiki-templates`. A user-maintained field guide for campaigns, characters, places, and the stories around them. Admin group: **Wiki**.
|
||||
|
||||
- **WikiPages**: `title` (text, required), `slug` (text, required, unique + indexed, generated by the service layer from the title), `category` (select, required: Campaign/World/Lore/Characters/Plot/Media/Guides/Meta/Documentation), `tags` (text hasMany), `body` (textarea, required, markdown source), `lockdown` (checkbox, default false), `lockedBy`/`lockedAt` (→ users / date), `lastEditor` (→ users). Access: read/create/update any logged-in user EXCEPT the **Documentation** category, where create/update is restricted to admin/developer (enforced twice: collection access functions for the admin-panel/REST path AND the wiki server actions, because the service layer runs with `overrideAccess`); delete requires intelligence qualification (`hasIntelligenceQualification`). A plain user cannot escalate a page into Documentation via update either (the update access check consults the incoming category AND the stored doc's category).
|
||||
- **WikiPages**: `title` (text, required), `slug` (text, required, unique + indexed, generated by the service layer from the title), `category` (select, required: Campaign/World/Lore/Characters/Plot/Media/Guides/Meta/Documentation), `tags` (text hasMany), `body` (textarea, required, markdown source), `lockdown` (checkbox, default false), `lockedBy`/`lockedAt` (→ users / date), `lastEditor` (→ users), `draft` (checkbox, default false), `createdBy` (→ users, hidden, written only by the service: field access create/update is `false` so a client cannot reassign authorship). Access: read/create/update any logged-in user EXCEPT the **Documentation** category, where create/update is restricted to admin/developer (enforced twice: collection access functions for the admin-panel/REST path AND the wiki server actions, because the service layer runs with `overrideAccess`); delete requires intelligence qualification (`hasIntelligenceQualification`). A plain user cannot escalate a page into Documentation via update either (the update access check consults the incoming category AND the stored doc's category).
|
||||
- **Drafts**: a page with `draft: true` is private to its creator, wiki moderators (`hasIntelligenceQualification`) and admins. `access.read` returns a `where` clause (`draft=false` OR `draft=true AND createdBy=<viewer>`) rather than a boolean so the REST/local API filter drafts too; every frontend query then ANDs the same clause via `draftVisibilityWhere(user, canViewAll)` from `service.ts` (they read with `overrideAccess`). Publishing is one-way: `updatePage` throws and `access.update` returns `false` (403) when a page whose stored `draft` is `false` is sent `draft: true`. New pages default to published (`draft` unchecked); the editor's Draft switch is disabled on an already-published page. UI: amber `DraftBanner` on the detail page and a sky "Draft" chip in `WikiRow`; `WikiIndexEntry.draft` carries the flag into the index model. Tests: `tests/int/wiki-draft.int.spec.ts`. Gotcha: Payload calls `access.update` with `data` undefined on some paths, so the guard must use `data?.draft`.
|
||||
- **Documentation category**: in-depth, non-developer guides for the app's core systems (logistics and storage rules, banking, market and negotiation, shipments, base management, the map). Content lives as markdown files in `src/tools/seed/documentation/` (first H1 becomes the page title); `bun run src/tools/seed/seedDocumentation.ts` upserts them into `wiki-pages` (idempotent by slug, safe to re-run after edits). Migration `20260930_162200_add_documentation_wiki_category` adds the enum value. The wiki editor only offers Documentation in the category picker to admin/developer users; non-privileged users opening a Documentation page's edit URL get a "maintained by admins and developers" notice instead of the editor. Seeded pages have no `lastEditor`; the wiki index and detail header display **System** as the author for editor-less Documentation pages (other categories keep the "Unknown editor" fallback).
|
||||
- **WikiRevisions**: `page` (→ wiki-pages), `revisionNumber` (number, min 1), `titleSnapshot`/`contentSnapshot`, `editor` (→ users), `summary`, `type` (`create`/`edit`/`restore`), `restoredFromRevision`. Access: read logged-in; create/update/delete `false` (written internally via `overrideAccess`).
|
||||
- **WikiTemplates**: `name` (unique), `body` (textarea, snippet with `{{param}}` placeholders), `description`. Read logged-in; write admin/developer.
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ export interface WikiIndexEntry {
|
|||
readonly excerpt: string;
|
||||
readonly featured: boolean;
|
||||
readonly featuredOrder: number | null;
|
||||
readonly draft: boolean;
|
||||
}
|
||||
|
||||
export type WikiCategoryFilter = "all" | WikiCategory;
|
||||
|
|
@ -205,5 +206,6 @@ export function mapWikiPageToEntry(page: WikiPageDocument): WikiIndexEntry {
|
|||
: "Unknown editor",
|
||||
featured: page.curation?.featured === true,
|
||||
featuredOrder: page.curation?.featuredOrder ?? null,
|
||||
draft: page.draft === true,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,13 +7,53 @@
|
|||
* `Error`s on violations. Does NOT emit events — the actions layer emits.
|
||||
*/
|
||||
|
||||
import type { Payload } from "payload";
|
||||
import type { Payload, Where } from "payload";
|
||||
import type { User, WikiPage, WikiRevision, WikiTemplate } from "@/payload-types";
|
||||
import { hasIntelligenceQualification } from "@/utils/access-control/hasIntelligenceQualification";
|
||||
import hasRoles from "@/utils/access-control/hasRoles";
|
||||
import { slugify } from "./slugify";
|
||||
import type { TemplateMap } from "./templates";
|
||||
|
||||
type WikiCategory = WikiPage["category"];
|
||||
|
||||
/** The user shape Payload's auth/access callbacks hand back (User or an API key). */
|
||||
type WikiViewer = Parameters<typeof hasRoles>[1];
|
||||
|
||||
/**
|
||||
* Draft visibility model:
|
||||
* - non-drafts are visible to everyone (logged in);
|
||||
* - a draft is visible only to its creator, to wiki moderators (intel
|
||||
* qualification) and to admins.
|
||||
* `canViewAllDrafts` answers the moderator/admin half of that; callers combine
|
||||
* it with the creator check (which needs the page, not just the user).
|
||||
*/
|
||||
export async function canViewAllDrafts(
|
||||
payload: Payload,
|
||||
user: WikiViewer,
|
||||
): Promise<boolean> {
|
||||
if (!user) return false;
|
||||
return (await hasIntelligenceQualification(payload, user)) || hasRoles(["admin"], user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a `where` clause that hides drafts from viewers who are not the
|
||||
* creator / moderator / admin. Returns `undefined` when no restriction is
|
||||
* needed (moderator/admin). Callers AND this onto any existing clause.
|
||||
*/
|
||||
export function draftVisibilityWhere(
|
||||
user: WikiViewer,
|
||||
canViewAll: boolean,
|
||||
): Where | undefined {
|
||||
if (canViewAll) return undefined;
|
||||
if (!user) return { draft: { equals: false } } as Where;
|
||||
return {
|
||||
OR: [
|
||||
{ draft: { equals: false } },
|
||||
{ draft: { equals: true }, createdBy: { equals: user.id } },
|
||||
],
|
||||
} as Where;
|
||||
}
|
||||
|
||||
async function uniqueSlug(payload: Payload, base: string): Promise<string> {
|
||||
let candidate = base;
|
||||
let suffix = 2;
|
||||
|
|
@ -47,7 +87,14 @@ async function nextRevisionNumber(payload: Payload, pageId: number): Promise<num
|
|||
export async function createPage(
|
||||
payload: Payload,
|
||||
user: User,
|
||||
input: { title: string; category: string; tags?: string[]; body: string; summary?: string },
|
||||
input: {
|
||||
title: string;
|
||||
category: string;
|
||||
tags?: string[];
|
||||
body: string;
|
||||
summary?: string;
|
||||
draft?: boolean;
|
||||
},
|
||||
): Promise<WikiPage> {
|
||||
const slug = await uniqueSlug(payload, slugify(input.title));
|
||||
|
||||
|
|
@ -60,6 +107,8 @@ export async function createPage(
|
|||
tags: input.tags ?? [],
|
||||
body: input.body,
|
||||
lastEditor: user.id,
|
||||
createdBy: user.id,
|
||||
draft: input.draft ?? false,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
|
|
@ -87,12 +136,26 @@ export async function updatePage(
|
|||
payload: Payload,
|
||||
user: User,
|
||||
page: WikiPage,
|
||||
input: { title?: string; body?: string; category?: string; tags?: string[]; summary?: string },
|
||||
input: {
|
||||
title?: string;
|
||||
body?: string;
|
||||
category?: string;
|
||||
tags?: string[];
|
||||
summary?: string;
|
||||
draft?: boolean;
|
||||
},
|
||||
): Promise<WikiPage> {
|
||||
if (page.lockdown) {
|
||||
throw new Error("This page is locked and cannot be edited.");
|
||||
}
|
||||
|
||||
// One-way publish: a published page (draft=false) may never be set back to
|
||||
// draft. A draft may be published (draft=true -> false) or stay a draft.
|
||||
const nextDraft = input.draft ?? page.draft;
|
||||
if (page.draft === false && nextDraft === true) {
|
||||
throw new Error("This page has been published and cannot be set back to draft.");
|
||||
}
|
||||
|
||||
const nextTitle = input.title ?? page.title;
|
||||
const nextBody = input.body ?? page.body;
|
||||
const nextCategory = input.category ?? page.category;
|
||||
|
|
@ -128,6 +191,7 @@ export async function updatePage(
|
|||
category: nextCategory as WikiCategory,
|
||||
tags: nextTags,
|
||||
lastEditor: user.id,
|
||||
draft: nextDraft,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,31 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from "@payloadcms/db-postgres";
|
||||
|
||||
/**
|
||||
* Adds the "Draft" flag to wiki pages and pins drafts to their original
|
||||
* creator:
|
||||
* - `created_by_id` who created the page (the author a draft is private to)
|
||||
* - `draft` when true the page is private to the creator + moderators
|
||||
* + admins; a published page (draft=false) may never be set
|
||||
* back to draft (one-way publish).
|
||||
*/
|
||||
export async function up({ db, payload }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "wiki_pages" ADD COLUMN "created_by_id" integer;
|
||||
ALTER TABLE "wiki_pages" ADD COLUMN "draft" boolean DEFAULT false;
|
||||
ALTER TABLE "wiki_pages"
|
||||
ADD CONSTRAINT "wiki_pages_created_by_id_users_id_fk"
|
||||
FOREIGN KEY ("created_by_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
|
||||
CREATE INDEX "wiki_pages_created_by_idx" ON "wiki_pages" USING btree ("created_by_id");
|
||||
CREATE INDEX "wiki_pages_draft_idx" ON "wiki_pages" USING btree ("draft");
|
||||
`);
|
||||
}
|
||||
|
||||
export async function down({ db, payload }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "wiki_pages" DROP CONSTRAINT "wiki_pages_created_by_id_users_id_fk";
|
||||
ALTER TABLE "wiki_pages" DROP COLUMN "created_by_id";
|
||||
ALTER TABLE "wiki_pages" DROP COLUMN "draft";
|
||||
DROP INDEX "wiki_pages_created_by_idx";
|
||||
DROP INDEX "wiki_pages_draft_idx";
|
||||
`);
|
||||
}
|
||||
|
|
@ -158,6 +158,7 @@ import * as migration_20261031_090000_add_missions_discord_modlist_buffer_sent_a
|
|||
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';
|
||||
import * as migration_20261118_143000_add_wiki_pages_draft_and_created_by from './20261118_143000_add_wiki_pages_draft_and_created_by';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -960,4 +961,9 @@ export const migrations = [
|
|||
down: migration_20261117_212337_add_faction_discovered_field.down,
|
||||
name: '20261117_212337_add_faction_discovered_field'
|
||||
},
|
||||
{
|
||||
up: migration_20261118_143000_add_wiki_pages_draft_and_created_by.up,
|
||||
down: migration_20261118_143000_add_wiki_pages_draft_and_created_by.down,
|
||||
name: '20261118_143000_add_wiki_pages_draft_and_created_by'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -6035,6 +6035,11 @@ export interface WikiPage {
|
|||
*/
|
||||
featuredOrder?: number | null;
|
||||
};
|
||||
/**
|
||||
* Private to the author. Drafts are hidden from everyone except the creator, wiki moderators, and admins.
|
||||
*/
|
||||
draft?: boolean | null;
|
||||
createdBy?: (number | null) | User;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
|
@ -11895,6 +11900,8 @@ export interface WikiPagesSelect<T extends boolean = true> {
|
|||
featured?: T;
|
||||
featuredOrder?: T;
|
||||
};
|
||||
draft?: T;
|
||||
createdBy?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
|
|
|
|||
271
tests/int/wiki-draft.int.spec.ts
Normal file
271
tests/int/wiki-draft.int.spec.ts
Normal file
|
|
@ -0,0 +1,271 @@
|
|||
import { getTestPayload } from "../helpers/get-test-payload";
|
||||
import { Payload } from "payload";
|
||||
import type { AccessArgs } from "payload";
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import type { User, WikiPage } from "@/payload-types";
|
||||
import { WikiPages } from "@/collections/wiki/WikiPages";
|
||||
import {
|
||||
canViewAllDrafts,
|
||||
createPage,
|
||||
draftVisibilityWhere,
|
||||
updatePage,
|
||||
} from "@/lib/wiki/service";
|
||||
import { mapWikiPageToEntry } from "@/lib/wiki/indexView";
|
||||
|
||||
let payload: Payload;
|
||||
|
||||
const RUN = `wiki-draft-${Date.now().toString(36)}`;
|
||||
|
||||
/** Users cascade to profiles/bank accounts, which block deletion first. */
|
||||
const deleteUserWithRelations = async (pg: Payload, id: number): Promise<void> => {
|
||||
const accounts = await pg
|
||||
.find({
|
||||
collection: "bank-accounts",
|
||||
where: { ownerUser: { equals: id } },
|
||||
limit: 5,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
.catch(() => null);
|
||||
for (const account of accounts?.docs ?? []) {
|
||||
await pg
|
||||
.delete({ collection: "bank-accounts", id: account.id, overrideAccess: true })
|
||||
.catch(() => {});
|
||||
}
|
||||
const profiles = await pg
|
||||
.find({
|
||||
collection: "profiles",
|
||||
where: { user: { equals: id } },
|
||||
limit: 5,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
.catch(() => null);
|
||||
for (const profile of profiles?.docs ?? []) {
|
||||
await pg
|
||||
.delete({ collection: "profiles", id: profile.id, overrideAccess: true })
|
||||
.catch(() => {});
|
||||
}
|
||||
await pg.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
||||
};
|
||||
|
||||
describe("Wiki drafts", () => {
|
||||
let author: User;
|
||||
let other: User;
|
||||
let admin: User;
|
||||
const userIds: number[] = [];
|
||||
const pageIds: number[] = [];
|
||||
|
||||
const makeUser = async (label: string, roles?: Array<"user" | "admin">): Promise<User> => {
|
||||
const doc = (await payload.create({
|
||||
collection: "users",
|
||||
data: {
|
||||
username: `${RUN}-${label}`,
|
||||
discordUsername: `${RUN}-${label}`,
|
||||
displayName: `WIKI DRAFT ${label}`,
|
||||
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
||||
password: "Test123",
|
||||
...(roles ? { roles } : {}),
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as User;
|
||||
userIds.push(doc.id);
|
||||
return doc;
|
||||
};
|
||||
|
||||
/** Loads a page the way the frontend does, through access control. */
|
||||
const visibleTo = async (
|
||||
user: User,
|
||||
id: number,
|
||||
): Promise<boolean> => {
|
||||
const result = (await payload.find({
|
||||
collection: "wiki-pages",
|
||||
where: { id: { equals: id } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
user,
|
||||
overrideAccess: false,
|
||||
})) as unknown as { docs: WikiPage[] };
|
||||
return result.docs.length > 0;
|
||||
};
|
||||
|
||||
const makePage = async (
|
||||
title: string,
|
||||
draft: boolean,
|
||||
creator: User = author,
|
||||
): Promise<WikiPage> => {
|
||||
const page = await createPage(payload, creator, {
|
||||
title: `${RUN} ${title}`,
|
||||
category: "Lore",
|
||||
body: "draft body",
|
||||
draft,
|
||||
});
|
||||
pageIds.push(page.id);
|
||||
return page;
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getTestPayload();
|
||||
author = await makeUser("author", ["user"]);
|
||||
other = await makeUser("other", ["user"]);
|
||||
admin = await makeUser("admin", ["admin"]);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
for (const id of pageIds) {
|
||||
const revisions = await payload
|
||||
.find({
|
||||
collection: "wiki-revisions",
|
||||
where: { page: { equals: id } },
|
||||
limit: 500,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
.catch(() => null);
|
||||
for (const revision of revisions?.docs ?? []) {
|
||||
await payload
|
||||
.delete({ collection: "wiki-revisions", id: revision.id, overrideAccess: true })
|
||||
.catch(() => {});
|
||||
}
|
||||
await payload
|
||||
.delete({ collection: "wiki-pages", id, overrideAccess: true })
|
||||
.catch(() => {});
|
||||
}
|
||||
for (const id of userIds) {
|
||||
await deleteUserWithRelations(payload, id);
|
||||
}
|
||||
});
|
||||
|
||||
describe("service", () => {
|
||||
it("records the original creator and publishes by default", async () => {
|
||||
const page = await makePage("Default", false);
|
||||
expect(page.draft).toBe(false);
|
||||
expect(page.createdBy).toBe(author.id);
|
||||
});
|
||||
|
||||
it("creates a draft when asked, and can publish it later", async () => {
|
||||
const page = await makePage("Publishable", true);
|
||||
expect(page.draft).toBe(true);
|
||||
|
||||
const published = await updatePage(payload, author, page, { draft: false });
|
||||
expect(published.draft).toBe(false);
|
||||
// Publishing does not move authorship: the creator stays put.
|
||||
expect(published.createdBy).toBe(author.id);
|
||||
});
|
||||
|
||||
it("refuses to set a published page back to draft", async () => {
|
||||
const page = await makePage("OneWay", false);
|
||||
await expect(updatePage(payload, author, page, { draft: true })).rejects.toThrow(
|
||||
"This page has been published and cannot be set back to draft.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("visibility", () => {
|
||||
it("shows a draft to its creator but not to another member", async () => {
|
||||
const page = await makePage("Private", true);
|
||||
expect(await visibleTo(author, page.id)).toBe(true);
|
||||
expect(await visibleTo(other, page.id)).toBe(false);
|
||||
});
|
||||
|
||||
it("shows a draft to an admin", async () => {
|
||||
const page = await makePage("AdminVisible", true);
|
||||
expect(await visibleTo(admin, page.id)).toBe(true);
|
||||
});
|
||||
|
||||
it("shows a published page to everyone", async () => {
|
||||
const page = await makePage("Public", false);
|
||||
expect(await visibleTo(other, page.id)).toBe(true);
|
||||
});
|
||||
|
||||
it("hides a draft from the index query built for a plain member", async () => {
|
||||
const page = await makePage("Indexed", true);
|
||||
const where = draftVisibilityWhere(other, false);
|
||||
const result = (await payload.find({
|
||||
collection: "wiki-pages",
|
||||
where: { AND: [{ id: { equals: page.id } }, where ?? {}] },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})) as unknown as { docs: WikiPage[] };
|
||||
expect(result.docs).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("does not restrict the query for moderators/admins", async () => {
|
||||
expect(draftVisibilityWhere(admin, true)).toBeUndefined();
|
||||
expect(draftVisibilityWhere(null, false)).toEqual({ draft: { equals: false } });
|
||||
});
|
||||
|
||||
it("classifies a plain member and an admin correctly", async () => {
|
||||
expect(await canViewAllDrafts(payload, other)).toBe(false);
|
||||
expect(await canViewAllDrafts(payload, admin)).toBe(true);
|
||||
expect(await canViewAllDrafts(payload, null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("collection access", () => {
|
||||
const readAccess = async (user: User | null) => {
|
||||
const args = { req: { payload, user } } as unknown as AccessArgs;
|
||||
return (await WikiPages.access?.read?.(args)) ?? false;
|
||||
};
|
||||
|
||||
it("denies anonymous readers", async () => {
|
||||
expect(await readAccess(null)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns a draft-hiding where clause for a plain member", async () => {
|
||||
const result = await readAccess(other);
|
||||
expect(result).toEqual({
|
||||
OR: [
|
||||
{ draft: { equals: false } },
|
||||
{ draft: { equals: true }, createdBy: { equals: other.id } },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("lets an admin read everything", async () => {
|
||||
expect(await readAccess(admin)).toBe(true);
|
||||
});
|
||||
|
||||
const updateAccess = async (user: User, id: number, data: Record<string, unknown>) => {
|
||||
const args = { req: { payload, user }, id, data } as unknown as AccessArgs;
|
||||
return (await WikiPages.access?.update?.(args)) ?? false;
|
||||
};
|
||||
|
||||
it("allows publishing a draft", async () => {
|
||||
const page = await makePage("AccessPublish", true);
|
||||
expect(await updateAccess(author, page.id, { draft: false })).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses to unpublish a published page", async () => {
|
||||
const page = await makePage("AccessOneWay", false);
|
||||
expect(await updateAccess(author, page.id, { draft: true })).toBe(false);
|
||||
});
|
||||
|
||||
it("tolerates an access check with no data payload", async () => {
|
||||
// Payload calls update access without `data` on some paths; this used to
|
||||
// throw and 500 every wiki page render.
|
||||
const page = await makePage("AccessNoData", true);
|
||||
expect(await updateAccess(author, page.id, {})).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("index view model", () => {
|
||||
it("carries the draft flag through to the row model", () => {
|
||||
const base = {
|
||||
id: 1,
|
||||
title: "Draft Page",
|
||||
slug: "draft-page",
|
||||
category: "Lore",
|
||||
body: "text",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
lastEditor: null,
|
||||
draft: true,
|
||||
};
|
||||
expect(mapWikiPageToEntry(base as never).draft).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -530,6 +530,7 @@ const makeEntry = (
|
|||
excerpt: "",
|
||||
featured: false,
|
||||
featuredOrder: null,
|
||||
draft: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue