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:
+5
-3
@@ -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`.
|
||||
|
||||
@@ -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>) =>
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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' } })
|
||||
|
||||
@@ -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 }))
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
Reference in New Issue
Block a user