Merge claude/security-b-118: plugin status written alone, access answers announced (strict in 1.19.0), drafts left out of related documents

Merged onto ee241de (the prepared 1.17.2). Conflicts kept both sides: AGENT.md rows (consent version; drafts, status, access answers), security.md sections (job queue, visitor accounts; access callbacks), src/index.ts (the jobs exports).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 12:53:59 +01:00
co-authored by Claude Opus 5.5
29 changed files with 554 additions and 48 deletions
+3
View File
@@ -1225,6 +1225,9 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Locales: no stand-in — `resolveRoute` (page route, `/md/…`, MCP `get_page`) answers `null` for a locale the site does not have (`xx`, `all`); a 404 page that is a draft is not shown (built-in view instead) | — | `isSiteLocale(payload, locale)`; verify: `curl -i <site>/md/xx` → 404 |
| Site integrations versions (when a project turns them on) are read by admins only (`readVersions`) | — | `globalOverrides: { 'site-integrations': { access: { readVersions } } }` |
| Consent version only goes up (1.17.2): a save through access control with a lower Cookies → *Consent version* is refused with a message (old consent would count again); the Local API with `overrideAccess` may still | `iapl({ cookieSettings: { allowLowerPolicyVersion: true } })` | `policyVersionNeverDown`, `buildCookieSettingsFields` (type `CookieSettingsFieldOptions`), `buildCookieSettings(options)`; verify: lower it in the panel → the error under the field |
| Drafts as related documents are left out (1.18.0): a block, menu or System pages link pointing at a page never published no longer brings its title, slug or text into the helpers' answers (`null` alone, removed from a list, `value: null` in a polymorphic one) — pages, Site settings, archive entries, the 404 page, Markdown, MCP, llms-full; a preview keeps them | `createContentHelpers({ draftRelations: 'keep' })`; `draftRelations: 'keep'` on `resolveRoute` / `getArchiveEntries` / `resolveNotFoundPage` / `collectSiteIndex` / `buildLlmsTxt` | `withoutDraftRelations`, `applyDraftRelations`, type `DraftRelations`; content.md "Drafts as related documents"; verify: a menu link to an unpublished page is gone on the site |
| Integration status written alone (1.18.0): `emailStatus` / `turnstileStatus` go through the database adapter on their own, so a visitor's form submit can no longer put back an admin's SMTP or Turnstile change saved at the same moment; the cookie list is checked again right before the scanner writes it (a row an editor saved in between stays) | — | `writeGlobalFields(payload, slug, data)` for your own bookkeeping fields (no hooks, no version); `addToCookieList` |
| Access callbacks (`cookieScanner.access`, the doctor's `access`): any truthy answer still allows in 1.18.0, but an answer that is not a boolean is reported once per option in the server log; **from 1.19.0 only `true` allows** | — | return a boolean (`({ req }) => Boolean(req.user)`); `accessAllowed(option, answer)`; security.md "Access callbacks" |
| Consent log on (since 1.17.0; Postgres / SQLite: a migration in the same deploy) | `consentLog: false`; one layout: `logEndpoint={false}` | `consentLog: { retentionDays, collectionOverrides }`; `buildConsentLogCollection` / `buildConsentLogEndpoint`, `CONSENT_LOG_PATH` |
| Global Privacy Control honoured: no banner, analytics and marketing off, no Google request also in Consent Mode `advanced`; a grant made without the signal is switched off when it appears | `gpc={false}` (doctor warns) | `gpc="ask"`; `resolveConsent`, `gpcFromHeaders`, `consentBannerScript({ gpc })` |
| "Reject" styled like "Accept all" (`equalChoice`) | `equalChoice={false}` (doctor warns) | `classNames.rejectButton` |
+2 -1
View File
@@ -56,7 +56,8 @@ Existing client sites are not gated on it; run it there as a report only.
`GET /api/ipal/doctor` is added by `iapl` and answers 404 until the site has `IAPL_DOCTOR_TOKEN` (≥ 32 characters).
Then `Authorization: Bearer <token>`; counts and states only (`usersWithout2fa`, `usersSetupClosed` = of those, blocked because the 2FA setup window has passed, `pendingCookies`, `openSignUp` = slugs of auth collections with open sign-up, `turnstile` = the recorded state of the Turnstile check, `turnstileSecretFromEnv`, `plugin`, `node`) — never a key or a name. With the same
`IAPL_DOCTOR_TOKEN` in the doctor's environment, `--url` reads it. Off: `iapl({ doctor: false })`; adapt:
`iapl({ doctor: { tokenVar, access } })`.
`iapl({ doctor: { tokenVar, access } })`. `access` returns a boolean (`({ req }) => isAdmin(req.user, req.payload)`):
since 1.18.0 any other answer is reported once in the server log, and from 1.19.0 only `true` allows.
## Env the doctor reads
+3 -1
View File
@@ -35,4 +35,6 @@ Requires the UI primitives from `../iapl-block/resources/section-code.md` (like
## Verification
The **iapl-audit** skill. By hand: a menu item added in the panel is visible right after
saving; the mobile menu works with the keyboard (Tab, Enter, Esc).
saving; the mobile menu works with the keyboard (Tab, Enter, Esc). A menu item that points at a page never
published is not shown (since 1.18.0 the helpers leave draft pages out; `createContentHelpers({ draftRelations:
'keep' })` shows it as before): publish the page and the item appears.
+27
View File
@@ -108,6 +108,33 @@ ambiguous (the same entry under many URLs), so `/a/b/c` → null.
**Slug collision:** two collections with an archive with the same slug → the first one
in the `collections` list wins. A configuration error; the router does not warn.
## Drafts as related documents (1.18.0)
A page is read at depth 2, Site settings and archive entries at depth 1, and Payload fills in every related document
whatever its status. Before 1.18.0 a block, a menu or a System pages link that pointed at a page never published
brought that page's title, slug and text into what the helpers answered (and llms-full printed it). Now the helpers
leave such a related document out, as if it did not exist:
| Shape | Becomes |
|---|---|
| a single relationship | `null` — a link resolves to nothing, a menu item drops out |
| a list of relationships | the draft is removed from it |
| a polymorphic one `{ relationTo, value }` | `value: null` |
A related document counts as a draft when it carries `_status` other than `'published'` (a never-published or
unpublished document of a collection with drafts). Documents without `_status` (collections without drafts, media)
are never touched; the document itself is judged as before (only published pages are served). Applies to
`createContentHelpers` (`getSettings`, `resolveRoute`, `getEntries`, `getNotFoundPage`, the page route, Markdown,
MCP, llms-full), `resolveRoute`, `getArchiveEntries`, `resolveNotFoundPage`, `collectSiteIndex` and
`buildLlmsTxt` / `createLlmsTxtRoute`. A preview (`draft: true`) keeps them.
- **What an existing site sees:** a menu item, a card or a link whose page was never published disappears for
visitors instead of showing a title that leads to a 404. Publish the page, or point the link elsewhere.
- **Keep the old behaviour:** `createContentHelpers({ draftRelations: 'keep' })`, or `draftRelations: 'keep'` on
`resolveRoute` / `getArchiveEntries` / `resolveNotFoundPage` / `collectSiteIndex` / `buildLlmsTxt`.
- **Building blocks:** `withoutDraftRelations(value)` (returns the same object when nothing changes, copies only
the changed path), `applyDraftRelations(value, { draft, draftRelations })`, type `DraftRelations`.
## Front-end helpers — createContentHelpers
Instead of writing cached wrappers in every project:
+1 -1
View File
@@ -259,7 +259,7 @@ All from `@intecion/ipal-kit` (server-safe), for your own admin view, a CLI or a
| `cookieScanContext(payload, plugin, req?)` | the `CookieScanContext` a scan uses |
| `parseCookieNames(input)` | the panel's text box → clean names |
| `mergeCookieReview(current, previous, next)`, `suggestionFor(finding, locales)` | the "never overwrite an edit" rule, pure |
| `addToCookieList({ payload, entry, req? })` | what accepting does: add the row or fill its empty text → `'added' \| 'filled' \| 'unchanged'`; a row with the same name or a covering pattern counts as the same cookie (`sameCookie(a, b)`) |
| `addToCookieList({ payload, entry, req? })` | what accepting does: add the row or fill its empty text → `'added' \| 'filled' \| 'unchanged'`; a row with the same name or a covering pattern counts as the same cookie (`sameCookie(a, b)`). The list is written whole: since 1.18.0 it is read again right before writing and, when an editor's save changed it since, the change is worked out again on what is there now (up to 5 times), so a row saved in between is not lost. A Cookies form left open in the panel and saved later still writes the whole list it shows (Payload's document lock warns the second editor) |
| `loadCookieApproval({ payload, locale, req? })` | the approval list → `CookieApprovalList` (`pending`, `gone`) |
| `approveCookies({ payload, ids?, unknownCategory?, addToList?, req? })` | what **Approve and add** does → `CookieApprovalResult` |
| `countPendingCookies(payload)`, `PENDING_WHERE` | how many wait / the query for them (drafts, and accepted cookies marked changed) |
+1
View File
@@ -38,6 +38,7 @@ and shared by the helpers (generateMetadata and the page share queries).
| `mcp` | — | `{ serverName, serverVersion, rateLimit, maxBatch, clientIp, isPathVisible }` for `mcpGET`/`mcpPOST` (mcp.md) |
| `pageJsonLd` | — | default `getPageJsonLd` options: `breadcrumbs`, `entryType`, `entries`, `faq`, `pageType` |
| `robots` | — | `RobotsOptions` for `robots` and `getRobots` (seo.md); `aiBotRules: [{ userAgent, access }]` = per-bot exceptions from code (the panel's rules come after them) |
| `draftRelations` | `'hide'` | related documents that are drafts are left out of what the helpers answer (1.18.0); `'keep'` as before (content.md "Drafts as related documents") |
| `settingsDepth` | `1` | depth of `getSettings`: Site settings relations arrive as documents, theirs as ids (the archive page is read separately at depth 2); `2` = every request pays for more |
| `siteJsonLd` | WebSite + Organization from Site settings | a function replaces it, `false` = none |
| `sitemapEntries` | — | `(entries) => entries` — final sitemap list: add URLs of your own routes, remove some, set `priority` |
+5
View File
@@ -37,6 +37,11 @@ The state block above it reads `GET /api/iapl/mail-relay/status` and acts throug
or at most every 10 min while an error lasts; it never throws. The same change already being written (many sends
failing at once) is written once; while every transaction place of a Postgres pool is taken
([deployment.md](./deployment.md) §4.3a) the write goes on in the background instead of holding the caller.
- **The status is written alone (1.18.0).** `updateGlobal` reads the whole document, merges and writes it whole: a
status written after a visitor's form submit put back an admin's SMTP or Turnstile change saved in the same
moment. The status field is now written through the database adapter on its own (`writeGlobalFields(payload,
slug, data)`, exported): no read of the rest, no hooks, no new version (fit for bookkeeping fields only). A global
that does not exist yet is created the usual way.
- **Changing keys in the admin panel** (Turnstile, the sending method / `smtp*`) clears that integration's old status.
- **`emailStatus.code`** of a send through the Intecion mail service is one of the `relay-…` codes (`relay-pending`,
`relay-quota`, `relay-unreachable`, …), each with a text in the editor's language — the list and what to do:
+11
View File
@@ -1265,6 +1265,17 @@ own `payload-locked-documents` (who edits which document) also runs on Payload's
plugin-wide default for it is planned for 2.0. Verify: the doctor shows no `visitor-writes` finding, and the
closed-doors spec's customer gets 403 on every write door.
## Access callbacks (`cookieScanner.access`, the doctor's `access`)
A project's callback says who may use the cookie scanner's endpoints or read the doctor's status. Today any truthy
answer lets the request in: `({ req }) => req.user` returns an account object and passes, and so does a function
that returns `'no'` or `{}`. **From the next minor version (1.19.0) only `true` allows** — like
`twoFactor.requireSetup.resetAccess` already does. Since 1.18.0 the first answer that is not a boolean is reported
once per option in the server log:
`[iapl] cookieScanner.access returned an object, not true or false. It is still read as allowed; …`.
Return a boolean: `({ req }) => Boolean(req.user)`, `({ req }) => isAdmin(req.user, req.payload)`. One function reads
every answer: `accessAllowed(option, answer)` (exported). The second factor is checked before the callback, as before.
## Turn off, override, extend
- **Stored secrets:** `secrets: { writeOnly: false }`, `secrets: { reenterOnChange: false }`; `writeOnlySecret` /
+5 -3
View File
@@ -228,6 +228,7 @@ export { pathOf } from './modules/construction/visibility.js'
export type { PathVisibility } from './modules/construction/visibility.js'
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
export {
applyDraftRelations,
archiveFieldName,
blocksToMarkdown,
buildArchivePath,
@@ -249,8 +250,9 @@ export {
resolveRoute,
SEARCH_QUERY_LIMIT,
searchContent,
withoutDraftRelations,
} from './modules/content/index.js'
export type { ArchiveEntries } from './modules/content/index.js'
export type { ArchiveEntries, DraftRelations } from './modules/content/index.js'
export type { SearchResult } from './modules/content/index.js'
// Postgres: connections kept free of transactions, work run after a commit (docs/deployment.md "Postgres: the connection pool").
export { afterCommit, defaultConnectionReserve, inWatchedTransaction, poolSize, RESERVE_ESCAPE_MS, reserveConnections, transactionsBusy, transactionWatchState, watchTransactions } from './modules/database/transactions.js'
@@ -400,7 +402,7 @@ export type { LocaleMiddlewareResult } from './modules/i18n/localeMiddleware.js'
export { buildLocalizedPath, switchLocalePath } from './modules/i18n/localizedPath.js'
export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './modules/i18n/negotiateLocale.js'
export { resolveLocalized } from './modules/i18n/resolveLocalized.js'
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js'
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus, writeGlobalFields } from './modules/integrations/index.js'
export type { IntegrationBannerTexts, IntegrationLabel, IntegrationState, IntegrationStatus } from './modules/integrations/index.js'
// Image lightbox — pure helpers (components live in /client).
export { formatLightboxCounter, LIGHTBOX_FALLBACK, LIGHTBOX_FALLBACK_PL, lightboxFallback, lightboxImage, lightboxIndex, resolveLightboxTexts } from './modules/lightbox/index.js'
@@ -498,7 +500,6 @@ export type {
TotpUser,
WithSecurityConfigOptions,
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
// Payload's job queue over HTTP: an admin with the second factor or Bearer CRON_SECRET (security.md "Payload's job queue")
export { CRON_SECRET_ENV, CRON_SECRET_MIN_LENGTH, cronSecretMatches, jobsRunAccess, jobsRunNotice, withJobsRunAccess } from './modules/security/jobsAccess.js'
@@ -578,6 +579,7 @@ export { robotsOptionsFrom, verificationFrom } from './modules/seo/index.js'
export type { AiBotRule, AiBotsPolicy, VerificationMetadata } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapIndexXml, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'
export { accessAllowed } from './modules/shared/accessAnswer.js'
export { applyCollectionOverride } from './modules/shared/collectionOverride.js'
export type { CollectionOverride } from './modules/shared/collectionOverride.js'
// Development addresses by pattern (no env): the built-in list and the matcher behind `developmentHosts`.
+2 -1
View File
@@ -7,6 +7,7 @@ import type { CookieScannerOptions, CookieStorage } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { secondFactorPassed } from '../../security/totp/secondFactor.js'
import { accessAllowed } from '../../shared/accessAnswer.js'
import { CONSENT_CATEGORIES } from '../categories.js'
import { COOKIE_REVIEW_SLUG } from './collection.js'
import { textFor } from './merge.js'
@@ -156,7 +157,7 @@ export async function approveCookies({
export function buildCookieApprovalEndpoints(options: CookieScannerOptions): Endpoint[] {
const approval = typeof options.approval === 'object' ? options.approval : {}
const allowed = async (req: PayloadRequest) =>
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req })) : userMeetsRole(req, 'editor')
return [
{
handler: async (req) => {
@@ -7,6 +7,7 @@ import type { CookieCrawlOptions, CookieScanContext, CookieScannerOptions } from
import { userMeetsRole } from '../../../access/predicates.js'
import { secondFactorPassed } from '../../../security/totp/secondFactor.js'
import { accessAllowed } from '../../../shared/accessAnswer.js'
import {
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
@@ -60,7 +61,7 @@ export function buildCookieCrawlEndpoints({
}): Endpoint[] {
const crawl: CookieCrawlOptions = typeof options.crawl === 'object' ? options.crawl : {}
const isStaff = async (req: PayloadRequest) =>
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req })) : userMeetsRole(req, 'editor')
const read = async (req: PayloadRequest) =>
(await req.payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0, overrideAccess: true, req })) as CrawlDoc
const write = (req: PayloadRequest, data: Partial<CrawlDoc>) =>
+2 -1
View File
@@ -4,6 +4,7 @@ import type { CookieIntegration, CookieScanContext, CookieScannerOptions } from
import { userMeetsRole } from '../../access/predicates.js'
import { secondFactorPassed } from '../../security/totp/secondFactor.js'
import { accessAllowed } from '../../shared/accessAnswer.js'
import { DEFAULT_COOKIE_INTEGRATIONS, integrationLabel } from './integrations.js'
import { cookieScanContext, enabledCookieIntegrations, parseCookieNames, runCookieScan } from './scan.js'
@@ -17,7 +18,7 @@ export const COOKIE_SCAN_PATH = '/ipal/cookie-scan'
*/
export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin: CookieScanContext['plugin']): Endpoint[] {
const allowed = async (req: PayloadRequest) =>
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req })) : userMeetsRole(req, 'editor')
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
// Names in the admin language of the editor who asks.
const list = (items: CookieIntegration[], req: PayloadRequest) =>
+44 -24
View File
@@ -16,6 +16,9 @@ type Row = {
type Entry = { name: string; storage?: null | string } & CookieReviewValues
/** How many times a write is worked out again when the list changed under it. */
const WRITE_ATTEMPTS = 5
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
/**
@@ -52,13 +55,12 @@ export async function addToCookieList({
const common = { slug: 'cookie-settings' as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
let result: 'added' | 'filled' | 'unchanged' = 'unchanged'
for (const [i, locale] of locales.entries()) {
const g = (await payload.findGlobal({ ...common, locale: locale as never })) as { cookies?: Row[] }
const rows = [...(g.cookies ?? [])]
/** Adds or fills the entry's row in `rows` (in place); what happened, or null when nothing changed. */
const applyEntry = (rows: Row[], i: number): 'added' | 'filled' | null => {
const locale = locales[i]
const row = rows.find((r) => Boolean(r.name?.trim()) && sameCookie(r.name!.trim(), entry.name))
let changed = false
if (!row) {
if (i > 0) {continue} // added in the default locale; Payload keeps the row in every locale
if (i > 0) {return null} // added in the default locale; Payload keeps the row in every locale
rows.push({
name: entry.name,
category: entry.category ?? 'necessary',
@@ -67,28 +69,46 @@ export async function addToCookieList({
purpose: text(entry.purpose, locale),
storage: entry.storage ?? 'cookie',
})
changed = true
result = 'added'
} else {
const fill = (key: 'duration' | 'provider' | 'purpose', value: null | string | undefined) => {
if (empty(row[key]) && !empty(value)) {
row[key] = value
changed = true
}
return 'added'
}
let changed = false
const fill = (key: 'duration' | 'provider' | 'purpose', value: null | string | undefined) => {
if (empty(row[key]) && !empty(value)) {
row[key] = value
changed = true
}
if (i === 0) {
fill('provider', entry.vendor)
// A row from before the type existed has none; the type is shared by every language.
if (empty(row.storage) && entry.storage) {
row.storage = entry.storage
changed = true
}
}
if (i === 0) {
fill('provider', entry.vendor)
// A row from before the type existed has none; the type is shared by every language.
if (empty(row.storage) && entry.storage) {
row.storage = entry.storage
changed = true
}
fill('purpose', text(entry.purpose, locale))
fill('duration', text(entry.retention, locale))
if (changed && result === 'unchanged') {result = 'filled'}
}
fill('purpose', text(entry.purpose, locale))
fill('duration', text(entry.retention, locale))
return changed ? 'filled' : null
}
// The list is written whole (Payload has no "add one row"): right before writing, it is read again, and when an
// editor's save changed it since, the change is worked out again on what is there now (owner's decision Q3,
// 1.18.0). What is left is the moment between that check and the write itself.
const read = async (locale: string | undefined) =>
[...(((await payload.findGlobal({ ...common, locale: locale as never })) as { cookies?: Row[] }).cookies ?? [])]
const same = (a: Row[], b: Row[]) => JSON.stringify(a) === JSON.stringify(b)
for (const [i, locale] of locales.entries()) {
for (let attempt = 0; ; attempt++) {
const seen = await read(locale)
const rows = structuredClone(seen)
const outcome = applyEntry(rows, i)
if (!outcome) {break}
if (attempt < WRITE_ATTEMPTS - 1 && !same(await read(locale), seen)) {continue}
await payload.updateGlobal({ ...common, data: { cookies: rows } as never, locale: locale as never })
if (outcome === 'added' || result === 'unchanged') {result = outcome}
break
}
if (changed) {await payload.updateGlobal({ ...common, data: { cookies: rows } as never, locale: locale as never })}
}
return result
}
+70
View File
@@ -0,0 +1,70 @@
/**
* Drafts as related documents (owner's decision Q5, 1.18.0).
*
* The public helpers read with `depth` (a page at 2, Site settings and archive entries at 1) and Payload fills
* in every related document whatever its status: a block, a menu or a System pages link pointing at a page that
* was never published showed that page's title and slug (and llms-full / the Markdown printed its text). Since
* 1.18.0 such a related document is left out of what the helpers answer, as if it did not exist:
* - a single relationship becomes `null` (a link to it resolves to nothing, a menu item drops out);
* - in a list of relationships it is removed;
* - in a polymorphic one (`{ relationTo, value }`) the `value` becomes `null`.
* A related document counts as a draft when it carries `_status` other than `'published'`, which is what a
* never-published (or unpublished) document of a collection with drafts holds. Documents without `_status`
* (collections without drafts, uploads) are never touched. The document itself is not judged here (the
* helpers already do), only what it points at.
*
* `draftRelations: 'keep'` (createContentHelpers, resolveRoute, getArchiveEntries, resolveNotFoundPage,
* collectSiteIndex) keeps the old behaviour. A preview (`draft: true`) keeps them too.
*/
export type DraftRelations = 'hide' | 'keep'
const isDraftDoc = (value: unknown): boolean => {
if (!value || typeof value !== 'object' || Array.isArray(value)) {return false}
const v = value as { _status?: unknown; id?: unknown }
return v.id !== undefined && typeof v._status === 'string' && v._status !== 'published'
}
/**
* The same value with every related document that is a draft left out (see above). Returns the SAME object
* when nothing needed changing; otherwise only the path to each change is copied (cached reads are not mutated).
*/
export function withoutDraftRelations<T>(value: T): T {
return walk(value, true) as T
}
function walk(value: unknown, root: boolean): unknown {
if (Array.isArray(value)) {
let changed = false
const next: unknown[] = []
for (const item of value) {
if (isDraftDoc(item)) {
changed = true
continue
}
const out = walk(item, false)
if (out !== item) {changed = true}
next.push(out)
}
return changed ? next : value
}
if (!value || typeof value !== 'object' || value instanceof Date) {return value}
if (!root && isDraftDoc(value)) {return null}
const obj = value as Record<string, unknown>
let result: null | Record<string, unknown> = null
for (const key of Object.keys(obj)) {
const item = obj[key]
// a polymorphic relationship keeps its shape: { relationTo, value: null }
const out = isDraftDoc(item) ? null : walk(item, false)
if (out !== item) {
result ??= { ...obj }
result[key] = out
}
}
return result ?? value
}
/** `withoutDraftRelations` unless the caller keeps them (`'keep'`) or reads a preview (`draft`). */
export function applyDraftRelations<T>(value: T, { draft = false, draftRelations = 'hide' }: { draft?: boolean; draftRelations?: DraftRelations } = {}): T {
return draft || draftRelations === 'keep' ? value : withoutDraftRelations(value)
}
+6 -1
View File
@@ -1,5 +1,7 @@
import type { BasePayload } from 'payload'
import { applyDraftRelations, type DraftRelations } from './draftRelations.js'
export type ArchiveEntries<T = Record<string, unknown>> = {
docs: T[]
hasNextPage: boolean
@@ -17,6 +19,8 @@ type GetArchiveEntriesArgs = {
depth?: number
/** Preview (draftMode): include unpublished entries and latest drafts. Default false. */
draft?: boolean
/** Related documents that are drafts: `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
draftRelations?: DraftRelations
locale: string
/** 1-based. Values below 1 are clamped. */
page?: number
@@ -45,6 +49,7 @@ export async function getArchiveEntries<T = Record<string, unknown>>({
collection,
depth = 1,
draft = false,
draftRelations,
locale,
page = 1,
payload,
@@ -69,7 +74,7 @@ export async function getArchiveEntries<T = Record<string, unknown>>({
})
return {
docs: result.docs as T[],
docs: applyDraftRelations(result.docs, { draft, draftRelations }) as T[],
hasNextPage: result.hasNextPage,
hasPrevPage: result.hasPrevPage,
page: result.page ?? 1,
+1
View File
@@ -2,6 +2,7 @@ export { buildArchiveFields } from './archiveFields.js'
export { blocksToMarkdown } from './blocksToMarkdown.js'
export { createMarkdownRenderer, createMarkdownRoute, markdownResponse } from './createMarkdownRenderer.js'
export { createSearchRoute } from './createSearchRoute.js'
export { applyDraftRelations, type DraftRelations, withoutDraftRelations } from './draftRelations.js'
export { getArchiveEntries } from './getArchiveEntries.js'
export type { ArchiveEntries } from './getArchiveEntries.js'
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'
+5 -1
View File
@@ -1,8 +1,11 @@
import type { BasePayload } from 'payload'
import { applyDraftRelations, type DraftRelations } from './draftRelations.js'
import { isPublishedDoc } from './resolveRoute.js'
type ResolveNotFoundPageArgs = {
/** Related documents that are drafts: `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
draftRelations?: DraftRelations
locale: string
/** Client's Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
@@ -24,6 +27,7 @@ type ResolveNotFoundPageArgs = {
* deleted page just yields null, so the 404 view can't crash the build.
*/
export async function resolveNotFoundPage({
draftRelations,
locale,
pagesSlug = 'pages',
payload,
@@ -52,7 +56,7 @@ export async function resolveNotFoundPage({
locale: locale as never,
})
// a page never published (or unpublished) is a draft: the built-in view, not its text (IAWL idea 23)
return isPublishedDoc(doc) ? (doc as Record<string, unknown>) : null
return isPublishedDoc(doc) ? applyDraftRelations(doc as Record<string, unknown>, { draftRelations }) : null
} catch (error) {
console.warn('[iapl] resolveNotFoundPage: falling back to built-in 404 view:', error)
return null
+16 -1
View File
@@ -2,6 +2,7 @@ import type { BasePayload } from 'payload'
import type { ContentOption } from './types.js'
import { applyDraftRelations, type DraftRelations } from './draftRelations.js'
import { archiveFieldName } from './types.js'
type ArchivePage = { id: number | string; slug?: unknown }
@@ -37,6 +38,11 @@ type ResolveRouteArgs = {
* requests only ever see published content.
*/
draft?: boolean
/**
* Related documents that are drafts (never published) in what the route answers: `'hide'` (default since 1.18.0)
* leaves them out — `null` for one, removed from a list — `'keep'` answers them as before. A preview keeps them.
*/
draftRelations?: DraftRelations
locale: string
/** Page number from the query string (?page=2). Defaults to 1. */
page?: number
@@ -99,7 +105,16 @@ export function isSiteLocale(payload: { config?: { localization?: unknown } }, l
return typeof locale === 'string' && localization.localeCodes.includes(locale)
}
export async function resolveRoute({
export async function resolveRoute(args: ResolveRouteArgs): Promise<null | ResolvedRoute> {
const route = await resolveRouteDocs(args)
if (!route) {return null}
const hide = <T,>(value: T) => applyDraftRelations(value, args)
return 'archive' in route && route.type === 'entry'
? { ...route, archive: hide(route.archive), doc: hide(route.doc) }
: { ...route, doc: hide(route.doc) }
}
async function resolveRouteDocs({
content,
draft = false,
locale,
+2 -1
View File
@@ -12,6 +12,7 @@ import { graphAvailable } from '../email/mailAdapter.js'
import { mailPanelState } from '../email/relay/panel.js'
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
import { accessAllowed } from '../shared/accessAnswer.js'
import { readEnv } from '../shared/envName.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { turnstileSecretFromEnv } from '../turnstile/config.js'
@@ -150,7 +151,7 @@ export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoi
const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'iapl-doctor', windowMs: 60_000 })
if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests' })}
const given = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '').trim()
const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && (await options.access({ req })) : false)
const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && accessAllowed('doctor.access', await options.access({ req })) : false)
if (!allowed) {return Response.json({ error: 'Unauthorized' }, { status: 401 })}
const status = await collectDoctorStatus(req.payload)
return Response.json(status, { headers: { 'cache-control': 'no-store' } })
+13 -4
View File
@@ -21,6 +21,7 @@ import { getConsentTexts } from '../consent/getConsentTexts.js'
import { isPathAllowed, isPathVisibleIn } from '../construction/logic.js'
import { pathOf } from '../construction/visibility.js'
import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
import { applyDraftRelations, type DraftRelations } from '../content/draftRelations.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
@@ -54,6 +55,12 @@ type CreateContentHelpersArgs = {
config: Promise<SanitizedConfig> | SanitizedConfig
/** Archive-backed collections, same value as the plugin option. */
content?: ContentOption
/**
* Related documents that are drafts (never published) in what the helpers answer — pages, Site settings (menus,
* System pages), archive entries, the 404 page, llms-full: `'hide'` (default since 1.18.0) leaves them out, as
* if they did not exist; `'keep'` answers them as before. content.md "Drafts as related documents".
*/
draftRelations?: DraftRelations
/**
* i18n config. Required only if you want the ready-made `sitemap` / `robots`
* handlers — they need the locale list to emit hreflang.
@@ -190,6 +197,7 @@ export function createContentHelpers({
baseUrl,
config,
content,
draftRelations = 'hide',
i18n,
markdown: markdownOptions,
markdownAlternate,
@@ -229,7 +237,7 @@ export function createContentHelpers({
*/
const getSettings = cache(async (locale: string) => {
const payload = await getCachedPayload()
return payload.findGlobal({ slug: settingsSlug as never, depth: settingsDepth, locale: locale as never })
return applyDraftRelations(await payload.findGlobal({ slug: settingsSlug as never, depth: settingsDepth, locale: locale as never }), { draftRelations })
})
/** What does this URL point at? Routing only — no listing data. */
@@ -243,6 +251,7 @@ export function createContentHelpers({
const settings = (await getSettings(locale)) as Record<string, unknown>
return resolveRouteRaw({
content,
draftRelations,
locale,
page,
pagesSlug,
@@ -416,7 +425,7 @@ export function createContentHelpers({
locale: locale as never,
})
// a page never published (or unpublished) is a draft: the built-in view, not its text (IAWL idea 23)
return isPublishedDoc(doc) ? (doc as Record<string, unknown>) : null
return isPublishedDoc(doc) ? applyDraftRelations(doc as Record<string, unknown>, { draftRelations }) : null
} catch {
return null // DB unreachable (container build) or page deleted — fallback view
}
@@ -431,7 +440,7 @@ export function createContentHelpers({
perPage: number,
): Promise<ArchiveEntries> => {
const payload = await getCachedPayload()
return getArchiveEntries({ collection, locale, page, payload, perPage })
return getArchiveEntries({ collection, draftRelations, locale, page, payload, perPage })
},
)
@@ -850,7 +859,7 @@ export function createContentHelpers({
return () => (value ??= make())
}
const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, draftRelations, full: true, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, isPathVisible, settingsSlug, ...markdownOptions }))
const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, isPathVisible, settingsSlug, summaryField, ...mcpOptions }))
const health = lazy(() => createHealthRoute({ collection: pagesSlug, getCachedPayload }))
+1
View File
@@ -2,6 +2,7 @@ export {
buildIntegrationStatusBanner,
buildIntegrationStatusField,
recordIntegrationStatus,
writeGlobalFields,
} from './status.js'
export type { IntegrationBannerTexts, IntegrationState, IntegrationStatus } from './status.js'
export type { IntegrationLabel } from './texts.js'
+19 -6
View File
@@ -88,6 +88,24 @@ export function buildIntegrationStatusBanner(
}
}
/**
* Writes these top-level fields of a global and nothing else (owner's decision Q3, 1.18.0). Payload's
* `updateGlobal` reads the whole document, merges the change and writes the whole result, so a status written
* after a visitor's form submit put back an admin's SMTP or Turnstile change saved in between. This writes the
* fields through the database adapter directly: no read of the rest, no merge, no hooks, no new version — fit for
* the plugin's own bookkeeping fields only. A global that does not exist yet is created the usual way.
*/
export async function writeGlobalFields(payload: BasePayload, slug: string, data: Record<string, unknown>): Promise<void> {
const db = (payload as { db?: Partial<BasePayload['db']> }).db
// a stand-in without a database adapter (a test double): the usual way
const existing = typeof db?.findGlobal === 'function' && typeof db.updateGlobal === 'function' ? await db.findGlobal({ slug, req: {} as never }) : null
if (!existing) {
await payload.updateGlobal({ slug: slug as never, context: { ipalIntegrationStatus: true }, data: data as never, depth: 0 })
return
}
await payload.db.updateGlobal({ slug, data: { ...data, updatedAt: new Date().toISOString() }, req: {} as never, returning: false })
}
/**
* Persist a status change. Never throws — a status write must not break the
* request that triggered it. The same change already being written is not
@@ -127,12 +145,7 @@ export async function recordIntegrationStatus(
}
const write = (async () => {
try {
await payload.updateGlobal({
slug: SITE_INTEGRATIONS as never,
context: { ipalIntegrationStatus: true },
data: { [field]: status } as never,
depth: 0,
})
await writeGlobalFields(payload, SITE_INTEGRATIONS, { [field]: status })
} catch (err) {
console.warn(`[iapl] could not record ${field}:`, err instanceof Error ? err.message : err)
} finally {
+5
View File
@@ -1,5 +1,6 @@
import type { BasePayload } from 'payload'
import type { DraftRelations } from '../content/draftRelations.js'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { SiteIndexEntry } from './siteIndex.js'
@@ -19,6 +20,8 @@ type BuildLlmsTxtArgs = {
* collection's own plural label. Usually the most quotable content on a site.
*/
content?: ContentOption
/** Related documents that are drafts (llms-full): `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
draftRelations?: DraftRelations
/**
* Full-content mode (llms-full.txt). When true, each page's full body is
* inlined as Markdown (via blocksToMarkdown) under its heading, so an agent
@@ -78,6 +81,7 @@ export async function buildLlmsTxt({
baseUrl,
config,
content,
draftRelations,
full = false,
include,
layoutField = 'layout',
@@ -105,6 +109,7 @@ export async function buildLlmsTxt({
config,
content,
depth: full ? 1 : 0,
draftRelations,
include,
locales,
pagesSlug,
+4
View File
@@ -1,5 +1,6 @@
import type { BasePayload } from 'payload'
import type { DraftRelations } from '../content/draftRelations.js'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { SitemapEntry } from './buildSitemapEntries.js'
@@ -33,6 +34,8 @@ export function createLlmsTxtRoute(opts: {
config: I18nConfig
/** Archive-backed collections (blog…) — listed too. Same value as the plugin option. */
content?: ContentOption
/** Related documents that are drafts (llms-full): `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
draftRelations?: DraftRelations
/** Inline every page's full Markdown (llms-full.txt). Default false. */
full?: boolean
getCachedPayload: () => Promise<BasePayload>
@@ -55,6 +58,7 @@ export function createLlmsTxtRoute(opts: {
baseUrl: opts.baseUrl,
config: opts.config,
content: opts.content,
draftRelations: opts.draftRelations,
full: opts.full,
...(allowed ? { include: (path: string) => allowed.has(normalizePath(path)) } : {}),
pagesSlug: opts.pagesSlug,
+5 -1
View File
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import { applyDraftRelations, type DraftRelations } from '../content/draftRelations.js'
import { archiveFieldName } from '../content/index.js'
import { buildLocalizedPath, getLocaleCodes, isValidLocale } from '../i18n/index.js'
import { resolveLocalized } from '../i18n/resolveLocalized.js'
@@ -39,6 +40,8 @@ export type CollectSiteIndexArgs = {
content?: ContentOption
/** Population depth of `doc`. Default 0 (1 when you render blocks with images). */
depth?: number
/** Related documents in `doc` that are drafts: `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
draftRelations?: DraftRelations
/**
* Only paths this returns true for — e.g. the pages still open while the site
* is under construction. Default: every path.
@@ -128,6 +131,7 @@ export async function collectSiteIndex({
config,
content,
depth = 0,
draftRelations,
include,
limit,
locales,
@@ -162,7 +166,7 @@ export async function collectSiteIndex({
if (collection !== pagesSlug && !prefix?.[locale]) {continue}
let docs: Row[] = []
try {
docs = await readDocs(payload, collection, { depth, limit, locale })
docs = applyDraftRelations(await readDocs(payload, collection, { depth, limit, locale }), { draftRelations })
} catch {
continue
}
+33
View File
@@ -0,0 +1,33 @@
/**
* The answer of a project's access callback (`cookieScanner.access`, the doctor's `access`), read the same way
* everywhere (owner's decision Q4, 1.18.0).
*
* Today any truthy answer lets the request in, as before: `({ req }) => req.user` returns an account object, and
* a function that returns `'no'` or `{}` lets the request in too. From the next minor version only `true` will
* allow. Until then the first answer that is not a boolean is reported once per option in the server log, so a
* project sees it before the change. (A callback needs a request to be asked, so this cannot be checked at start:
* the warning comes with the first call.)
*/
const warned = new Set<string>()
export type AccessAnswerOptions = {
/** Where to report (default `console.warn`). */
warn?: (message: string) => void
}
/** True when the request may pass; warns once per `option` when the answer is not a boolean. */
export function accessAllowed(option: string, answer: unknown, { warn = (m) => console.warn(m) }: AccessAnswerOptions = {}): boolean {
if (typeof answer !== 'boolean' && !warned.has(option)) {
warned.add(option)
const kind = answer === null ? 'null' : Array.isArray(answer) ? 'an array' : typeof answer === 'object' ? 'an object' : `a ${typeof answer}`
warn(
`[iapl] ${option} returned ${kind}, not true or false. It is still read as ${answer ? 'allowed' : 'refused'}; from the next minor version only \`true\` allows. Return a boolean, e.g. \`({ req }) => Boolean(req.user)\` (docs/security.md "Access callbacks").`,
)
}
return Boolean(answer)
}
/** For tests: forget which options were reported. */
export function resetAccessWarnings(): void {
warned.clear()
}
+52
View File
@@ -0,0 +1,52 @@
/**
* Access callbacks of a project (`cookieScanner.access`, the doctor's `access`), owner's decision Q4, 1.18.0:
* still allowed on any truthy answer, but an answer that is not a boolean is reported once per option, so a
* project sees it before the next minor version allows only `true`. Every call site goes through one function.
*/
import { readFileSync } from 'node:fs'
import { beforeEach, describe, expect, test, vi } from 'vitest'
import { accessAllowed, resetAccessWarnings } from '../src/modules/shared/accessAnswer.js'
beforeEach(() => resetAccessWarnings())
describe('accessAllowed', () => {
test('true and false are read as they are, without a word', () => {
const warn = vi.fn()
expect(accessAllowed('cookieScanner.access', true, { warn })).toBe(true)
expect(accessAllowed('cookieScanner.access', false, { warn })).toBe(false)
expect(warn).not.toHaveBeenCalled()
})
test.each([
[{ id: 1 }, true, 'an object'],
['no', true, 'a string'],
[1, true, 'a number'],
[null, false, 'null'],
[undefined, false, 'a undefined'],
])('%j is read as before (%s) and reported once', (answer, allowed, kind) => {
const warn = vi.fn()
expect(accessAllowed('doctor.access', answer, { warn })).toBe(allowed)
expect(accessAllowed('doctor.access', answer, { warn })).toBe(allowed)
expect(warn).toHaveBeenCalledTimes(1)
expect(warn.mock.calls[0][0]).toContain(`doctor.access returned ${kind}`)
expect(warn.mock.calls[0][0]).toContain('only `true` allows')
})
test('each option is reported on its own', () => {
const warn = vi.fn()
accessAllowed('doctor.access', 'x', { warn })
accessAllowed('cookieScanner.access', 'x', { warn })
expect(warn).toHaveBeenCalledTimes(2)
})
})
test('every call of a project access callback goes through accessAllowed', () => {
const sites = ['src/modules/consent/scanner/endpoint.ts', 'src/modules/consent/scanner/approval.ts', 'src/modules/consent/scanner/crawl/endpoints.ts', 'src/modules/doctor/status.ts']
for (const file of sites) {
const text = readFileSync(file, 'utf8')
const calls = text.match(/await options\.access\(\{ req \}\)/g) ?? []
expect(calls.length, file).toBeGreaterThan(0)
expect(text.match(/accessAllowed\('[\w.]+', await options\.access\(\{ req \}\)\)/g)?.length, file).toBe(calls.length)
}
})
+105
View File
@@ -0,0 +1,105 @@
/**
* Drafts as related documents (owner's decision Q5, 1.18.0): a block, a menu or a System pages link that points at a
* page never published no longer brings that page's title, slug and text into what the public helpers answer.
* `draftRelations: 'keep'` and a preview (`draft: true`) keep the old behaviour.
* Real database; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { withoutDraftRelations } from '../src/modules/content/draftRelations.js'
import { getArchiveEntries } from '../src/modules/content/getArchiveEntries.js'
import { resolveRoute } from '../src/modules/content/resolveRoute.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
vi.mock('server-only', () => ({}))
describe('withoutDraftRelations', () => {
const draft = { id: 2, _status: 'draft', title: 'Secret' }
const live = { id: 1, _status: 'published', title: 'Live' }
test('drops a draft related document: null alone, removed from a list, value null in a polymorphic one', () => {
const doc = { id: 9, _status: 'published', layout: [{ blockType: 'cards', items: [live, draft], one: draft, poly: { relationTo: 'pages', value: draft } }] }
expect(withoutDraftRelations(doc)).toEqual({ id: 9, _status: 'published', layout: [{ blockType: 'cards', items: [live], one: null, poly: { relationTo: 'pages', value: null } }] })
})
test('the document itself, ids, uploads and documents without _status are left alone; nothing is mutated', () => {
const doc = { id: 3, _status: 'draft', image: { id: 5, url: '/m.png' }, page: 2, pages: [1, 2] }
expect(withoutDraftRelations(doc)).toBe(doc)
const nested = { a: { b: draft } }
const out = withoutDraftRelations(nested)
expect(out).toEqual({ a: { b: null } })
expect(nested.a.b).toBe(draft)
})
})
describe('the public helpers on a real database', () => {
let payload: Payload
beforeAll(async () => {
const config = buildTestConfig({
collections: [
{
slug: 'pages',
access: { read: () => true },
fields: [
{ name: 'title', type: 'text' },
{ name: 'slug', type: 'text', localized: true },
{ name: 'related', type: 'relationship', relationTo: 'pages' },
{ name: 'list', type: 'relationship', hasMany: true, relationTo: 'pages' },
{ name: 'layout', type: 'blocks', blocks: [{ slug: 'link', fields: [{ name: 'page', type: 'relationship', relationTo: ['pages', 'posts'] }] }] },
],
versions: { drafts: true },
},
{ slug: 'posts', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }, { name: 'see', type: 'relationship', relationTo: 'pages' }], versions: { drafts: true } },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-draft-relations') } },
],
db: testDatabase('draft_relations'),
editor: lexicalEditor(),
plugins: [iapl({ access: { authCollection: 'users' }, content: { collections: [{ slug: 'posts' }] }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail: { relay: false }, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'draft-relations-0123456789-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
const secret = await payload.create({ collection: 'pages' as never, data: { slug: 'tajna', _status: 'draft', title: 'Secret price list' } as never, draft: true })
const live = await payload.create({ collection: 'pages' as never, data: { slug: 'o-nas', _status: 'published', title: 'About' } as never })
await payload.create({
collection: 'pages' as never,
data: { slug: 'start', _status: 'published', layout: [{ blockType: 'link', page: { relationTo: 'pages', value: secret.id } }], list: [live.id, secret.id], related: secret.id, title: 'Start' } as never,
})
await payload.create({ collection: 'posts' as never, data: { slug: 'wpis', _status: 'published', see: secret.id, title: 'Post' } as never })
}, 120_000)
afterAll(async () => {
await payload?.destroy?.()
})
const start = async (options: Record<string, unknown> = {}) => (await resolveRoute({ locale: 'pl', payload, segments: ['start'], ...options }))?.doc as Record<string, unknown>
test('resolveRoute: the page answers without the draft it points at (single, list, polymorphic block)', async () => {
const doc = await start()
expect(doc.related).toBeNull()
expect((doc.list as { title: string }[]).map((p) => p.title)).toEqual(['About'])
expect((doc.layout as { page: { value: unknown } }[])[0].page.value).toBeNull()
expect(JSON.stringify(doc)).not.toContain('Secret price list')
})
test("draftRelations: 'keep' and a preview answer them as before", async () => {
for (const options of [{ draftRelations: 'keep' }, { draft: true }]) {
expect(JSON.stringify(await start(options))).toContain('Secret price list')
}
})
test('getArchiveEntries: an entry without the draft it points at; keep as before', async () => {
const hidden = await getArchiveEntries({ collection: 'posts', locale: 'pl', payload })
expect((hidden.docs[0] as { see: unknown }).see).toBeNull()
const kept = await getArchiveEntries({ collection: 'posts', draftRelations: 'keep', locale: 'pl', payload })
expect(JSON.stringify(kept.docs)).toContain('Secret price list')
})
})
+109
View File
@@ -0,0 +1,109 @@
/**
* Plugin writes that do not carry an old copy of a settings global back (owner's decision Q3, 1.18.0).
*
* - The integration status (`emailStatus`, `turnstileStatus`) is written after an ANONYMOUS form submit or a mail
* send. Payload's `updateGlobal` reads the whole document, merges the change and writes the whole result: an
* admin's SMTP or Turnstile change saved in between was put back silently. The status is now written alone.
* - `addToCookieList` (cookie approval, review) read the cookie list, added a row and wrote the whole list: a row
* an editor saved in between was lost. It now checks the list again right before writing and starts over when
* it changed.
*
* The race is made exact by holding the plugin's read and letting the other save land in between.
* Real database; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { addToCookieList } from '../src/modules/consent/scanner/sync.js'
import { recordIntegrationStatus } from '../src/modules/integrations/status.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
vi.mock('server-only', () => ({}))
let payload: Payload
const SI = 'site-integrations'
const si = async () => (await payload.findGlobal({ slug: SI as never })) as unknown as Record<string, unknown>
beforeAll(async () => {
const config = buildTestConfig({
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-status-writes') } }],
db: testDatabase('status_writes'),
editor: lexicalEditor(),
plugins: [iapl({ access: { authCollection: 'users' }, cookieScanner: true, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })],
secret: 'status-writes-0123456789-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
}, 120_000)
afterAll(async () => {
await payload?.destroy?.()
})
describe('the integration status is written alone', () => {
test("an admin's SMTP change saved while the status is written stays", async () => {
await payload.updateGlobal({ slug: SI as never, data: { smtpHost: 'old.example.com', smtpPassword: 'old-secret', smtpUser: 'u' } as never })
// the copy any read-merge-write would hold: taken before the admin's save
const before = await payload.db.findGlobal({ slug: SI, req: {} as never })
const real = payload.db.findGlobal.bind(payload.db)
let held = true
const spy = vi.spyOn(payload.db, 'findGlobal').mockImplementation(async (args) => {
if (args.slug === SI && held) {
held = false
// the admin's save lands while the status write is under way
await payload.updateGlobal({ slug: SI as never, data: { smtpHost: 'new.example.com', smtpPassword: 'new-secret' } as never })
return before as never
}
return real(args)
})
try {
await recordIntegrationStatus(payload, 'emailStatus', null, { code: 'smtp-auth', message: 'Login refused', state: 'degraded' })
} finally {
spy.mockRestore()
}
const after = await si()
expect(after).toMatchObject({ smtpHost: 'new.example.com', smtpPassword: 'new-secret' })
expect(after.emailStatus).toMatchObject({ code: 'smtp-auth', state: 'degraded' })
})
test('the status write changes nothing else in the document', async () => {
await payload.updateGlobal({ slug: SI as never, data: { ga4MeasurementId: 'G-KEEP', smtpHost: 'keep.example.com', turnstileSiteKey: 'site-key' } as never })
const { turnstileStatus: _t, updatedAt: _u, ...before } = await si()
await recordIntegrationStatus(payload, 'turnstileStatus', null, { code: 'bad-secret', state: 'degraded' })
const { turnstileStatus, updatedAt: _u2, ...after } = await si()
expect(after).toEqual(before)
expect(turnstileStatus).toMatchObject({ code: 'bad-secret', state: 'degraded' })
})
})
describe('the cookie list keeps a row saved in between', () => {
test('an editor adds a row while the scanner adds its own: both rows stay', async () => {
await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: [{ name: 'first', category: 'necessary' }] } as never, locale: 'pl' })
const real = payload.findGlobal.bind(payload)
let held = true
const spy = vi.spyOn(payload, 'findGlobal').mockImplementation(async (args) => {
const result = await real(args as never)
if ((args as { slug: string }).slug === 'cookie-settings' && held) {
held = false
// the editor's save lands after the scanner read the list
const rows = ((await real({ slug: 'cookie-settings' as never, depth: 0, locale: 'pl' as never })) as { cookies?: object[] }).cookies ?? []
await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: [...rows, { name: 'editor_cookie', category: 'analytics' }] } as never, locale: 'pl' })
}
return result as never
})
try {
expect(await addToCookieList({ entry: { name: 'scanned_cookie', category: 'marketing' } as never, payload })).toBe('added')
} finally {
spy.mockRestore()
}
const names = (((await payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0, locale: 'pl' as never })) as { cookies?: { name?: string }[] }).cookies ?? []).map((r) => r.name)
expect(names).toEqual(expect.arrayContaining(['first', 'editor_cookie', 'scanned_cookie']))
})
})