What grows: the doctor's growth group (sizes, versions, retention, submissions, KV, unused media, disk) with thresholds, expired mail-service nonces swept, opt-in forms.submissionRetentionDays, docs
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
6b16b9f933
commit
8991867e01
@@ -7,9 +7,13 @@
|
||||
*/
|
||||
export { DOCTOR_USAGE, expandSites, parseDoctorArgs, runDoctorCli } from '../modules/doctor/cli.js'
|
||||
export { formatDriftTable, formatReport } from '../modules/doctor/format.js'
|
||||
// What grows (docs/performance.md → "What grows"): the deep collector, the rules and their thresholds
|
||||
export { collectGrowth } from '../modules/doctor/growth.js'
|
||||
export type { GrowthStatus } from '../modules/doctor/growth.js'
|
||||
export { bareHost, createDoctorContext, loadDoctorConfig, parseEnvFile, readAuditSkips } from '../modules/doctor/project.js'
|
||||
export type { DoctorContext } from '../modules/doctor/project.js'
|
||||
export { planSkills } from '../modules/doctor/rules/agents.js'
|
||||
export { folderBytes, GROWTH_DEFAULTS, growthRules } from '../modules/doctor/rules/growth.js'
|
||||
export { DEFAULT_SRC_ALLOW, findFrontend } from '../modules/doctor/rules/layout.js'
|
||||
export type { FrontendLayout } from '../modules/doctor/rules/layout.js'
|
||||
export { createLiveFetcher } from '../modules/doctor/rules/live.js'
|
||||
@@ -30,6 +34,7 @@ export type {
|
||||
DoctorStatus,
|
||||
RuleFinding,
|
||||
} from '../modules/doctor/types.js'
|
||||
export type { GrowthThresholds } from '../modules/doctor/types.js'
|
||||
// Performance budgets (docs/performance.md): the defaults, a project's own on top, and the check the gate runs
|
||||
export { IMAGE_RULES, overBudget, PERF_BUDGETS, perfBudgets, SERVER_BUDGET } from '../modules/performance/budgets.js'
|
||||
export type { PerfBudget, PerfMeasurement, PerfProfile, ServerBudget } from '../modules/performance/budgets.js'
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
/**
|
||||
* What grows in the database (docs/performance.md → "What grows"): read-only counts for the doctor's `growth` rules.
|
||||
* Counts, sizes and dates only — never a value. Every read is capped, so the check stays cheap on a big site.
|
||||
*/
|
||||
export type GrowthStatus = {
|
||||
/** Every collection (the plugin's, the project's and Payload's own): documents, bytes on MongoDB (null elsewhere), the oldest record. */
|
||||
collections: Array<{ bytes: null | number; docs: number; oldest: null | string; slug: string }>
|
||||
/** Key-value store entries (`payload-kv`): all of them, and those whose own expiry has passed (null = not readable). */
|
||||
kv: { expired: null | number; total: number } | null
|
||||
/** Media no document or global points at (by id), from the first `checked` documents. null = no upload collection. */
|
||||
media: { capped: boolean; checked: number; orphaned: number; total: number } | null
|
||||
/** Versioned collections and globals: the configured limit (0 = unlimited), all versions, and the documents. */
|
||||
versions: Array<{ docs: number; kind: 'collection' | 'global'; max: number; slug: string; total: number }>
|
||||
}
|
||||
|
||||
type CollectionLike = { slug: string; timestamps?: boolean; upload?: unknown; versions?: { maxPerDoc?: number } | false }
|
||||
type GlobalLike = { slug: string; versions?: { max?: number } | false }
|
||||
|
||||
/** Documents read to find orphaned media (all collections and globals together). */
|
||||
export const ORPHAN_SCAN_LIMIT = 5000
|
||||
/** Key-value entries read to count expired ones. */
|
||||
export const KV_SCAN_LIMIT = 5000
|
||||
|
||||
/** An expiry a plugin entry carries in its data (`resetAt`, `expiresAt`, `until`, epoch ms or ISO). */
|
||||
function expiryOf(data: unknown): null | number {
|
||||
if (!data || typeof data !== 'object') {return null}
|
||||
for (const name of ['expiresAt', 'resetAt', 'until', 'exp']) {
|
||||
const v = (data as Record<string, unknown>)[name]
|
||||
const t = typeof v === 'number' ? v : typeof v === 'string' ? Date.parse(v) : Number.NaN
|
||||
if (Number.isFinite(t)) {return t}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function mongoBytes(payload: BasePayload, slug: string): Promise<null | number> {
|
||||
const db = payload.db as unknown as { collections?: Record<string, { collection?: { collectionName?: string } }>; connection?: { db?: { command: (c: object) => Promise<{ size?: number; totalIndexSize?: number }> } }; name?: string }
|
||||
const name = db.collections?.[slug]?.collection?.collectionName
|
||||
if (db.name !== 'mongoose' || !name || !db.connection?.db) {return null}
|
||||
try {
|
||||
const stats = await db.connection.db.command({ collStats: name })
|
||||
return (stats.size ?? 0) + (stats.totalIndexSize ?? 0)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function collectGrowth(payload: BasePayload): Promise<GrowthStatus> {
|
||||
const collections = (payload.config.collections ?? []) as unknown as CollectionLike[]
|
||||
const globals = (payload.config.globals ?? []) as unknown as GlobalLike[]
|
||||
const out: GrowthStatus = { collections: [], kv: null, media: null, versions: [] }
|
||||
|
||||
for (const c of collections) {
|
||||
const collection = c.slug as never
|
||||
try {
|
||||
const docs = (await payload.count({ collection, overrideAccess: true })).totalDocs
|
||||
let oldest: null | string = null
|
||||
if (docs && c.timestamps !== false) {
|
||||
const first = await payload.find({ collection, depth: 0, limit: 1, overrideAccess: true, pagination: false, select: { createdAt: true } as never, sort: 'createdAt' })
|
||||
oldest = (first.docs[0] as { createdAt?: string } | undefined)?.createdAt ?? null
|
||||
}
|
||||
out.collections.push({ slug: c.slug, bytes: await mongoBytes(payload, c.slug), docs, oldest })
|
||||
if (c.versions) {
|
||||
const total = (await payload.countVersions({ collection, overrideAccess: true })).totalDocs
|
||||
out.versions.push({ slug: c.slug, docs, kind: 'collection', max: c.versions.maxPerDoc ?? 100, total })
|
||||
}
|
||||
} catch {
|
||||
// a collection the adapter cannot count (a virtual one): left out
|
||||
}
|
||||
}
|
||||
for (const g of globals) {
|
||||
if (!g.versions) {continue}
|
||||
try {
|
||||
const total = (await payload.countGlobalVersions({ global: g.slug as never, overrideAccess: true })).totalDocs
|
||||
out.versions.push({ slug: g.slug, docs: 1, kind: 'global', max: g.versions.max ?? 100, total })
|
||||
} catch {
|
||||
// not countable on this adapter
|
||||
}
|
||||
}
|
||||
|
||||
// payload-kv: entries carry no expiry of their own in Payload; the plugin's carry one in their data
|
||||
const kv = (payload as unknown as { kv?: { get: (k: string) => Promise<unknown>; keys: () => Promise<string[]> } }).kv
|
||||
if (kv) {
|
||||
try {
|
||||
const keys = await kv.keys()
|
||||
let expired = 0
|
||||
const now = Date.now()
|
||||
for (const key of keys.slice(0, KV_SCAN_LIMIT)) {
|
||||
const t = expiryOf(await kv.get(key))
|
||||
if (t !== null && t < now) {expired++}
|
||||
}
|
||||
out.kv = { expired: keys.length > KV_SCAN_LIMIT ? null : expired, total: keys.length }
|
||||
} catch {
|
||||
out.kv = null
|
||||
}
|
||||
}
|
||||
|
||||
// Orphaned media: ids of the upload collections that no other document or global mentions (any field, any depth)
|
||||
const uploads = collections.filter((c) => c.upload)
|
||||
if (uploads.length) {
|
||||
const ids = new Set<string>()
|
||||
for (const u of uploads) {
|
||||
const res = await payload.find({ collection: u.slug as never, depth: 0, limit: ORPHAN_SCAN_LIMIT, overrideAccess: true, pagination: false, select: {} as never })
|
||||
for (const d of res.docs as Array<{ id: number | string }>) {ids.add(String(d.id))}
|
||||
}
|
||||
const seen = new Set<string>()
|
||||
let checked = 0
|
||||
// every string and number anywhere in a document (relations, uploads, rich text, blocks) — ids are among them
|
||||
const mark = (value: unknown, depth = 0): void => {
|
||||
if (depth > 40 || value == null) {return}
|
||||
if (typeof value === 'string' || typeof value === 'number') {
|
||||
const key = String(value)
|
||||
if (ids.has(key)) {seen.add(key)}
|
||||
return
|
||||
}
|
||||
if (Array.isArray(value)) {for (const v of value) {mark(v, depth + 1)}}
|
||||
else if (typeof value === 'object') {for (const v of Object.values(value)) {mark(v, depth + 1)}}
|
||||
}
|
||||
for (const c of collections) {
|
||||
if (c.upload || c.slug.startsWith('payload-') || checked >= ORPHAN_SCAN_LIMIT) {continue}
|
||||
try {
|
||||
const res = await payload.find({ collection: c.slug as never, depth: 0, draft: true, limit: ORPHAN_SCAN_LIMIT - checked, locale: 'all' as never, overrideAccess: true, pagination: false })
|
||||
checked += res.docs.length
|
||||
for (const d of res.docs) {mark(d)}
|
||||
} catch {
|
||||
// not readable this way: its references are not counted (the orphan count can then be too high, never too low)
|
||||
}
|
||||
}
|
||||
for (const g of globals) {
|
||||
try {
|
||||
mark(await payload.findGlobal({ slug: g.slug as never, depth: 0, draft: true, locale: 'all' as never, overrideAccess: true }))
|
||||
} catch {
|
||||
// not readable
|
||||
}
|
||||
}
|
||||
out.media = { capped: checked >= ORPHAN_SCAN_LIMIT, checked, orphaned: [...ids].filter((id) => !seen.has(id)).length, total: ids.size }
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { readdirSync, statSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
import type { DoctorContext } from '../project.js'
|
||||
import type { DoctorRule, GrowthThresholds, RuleFinding } from '../types.js'
|
||||
|
||||
/**
|
||||
* The growth group (docs/performance.md → "What grows"): what makes a site and its database swell over the years.
|
||||
* Deep rules read counts, sizes and dates (never values) from the status; the static one measures two folders on this
|
||||
* machine. Warnings in 1.18.0, every threshold set in `iapl-doctor.json` → `growth`. Nothing here deletes anything.
|
||||
*/
|
||||
|
||||
const DOCS = 'docs/performance.md'
|
||||
const DAY = 86_400_000
|
||||
|
||||
export const GROWTH_DEFAULTS: Required<GrowthThresholds> = {
|
||||
expiredKv: 1000,
|
||||
imageCacheMB: 1024,
|
||||
maxDocs: 200_000,
|
||||
maxMB: 512,
|
||||
maxVersions: 50_000,
|
||||
orphanedMedia: 25,
|
||||
submissionDays: 730,
|
||||
uploadsMB: 2048,
|
||||
}
|
||||
|
||||
const limits = (ctx: DoctorContext): Required<GrowthThresholds> => ({
|
||||
...GROWTH_DEFAULTS,
|
||||
// only numbers from iapl-doctor.json; anything else keeps the default
|
||||
...Object.fromEntries(Object.entries(ctx.config.growth ?? {}).filter(([, v]) => typeof v === 'number' && Number.isFinite(v) && v >= 0)),
|
||||
})
|
||||
const days = (iso: null | string, today: string) => (iso ? Math.max(0, Math.floor((Date.parse(today) - Date.parse(iso)) / DAY)) : 0)
|
||||
const mb = (bytes: number) => Math.round(bytes / 1024 / 1024)
|
||||
|
||||
/** Size of a folder on disk (bytes), capped at 200 000 files; 0 when it is not there. */
|
||||
export function folderBytes(dir: string): number {
|
||||
let total = 0
|
||||
let files = 0
|
||||
const walk = (d: string) => {
|
||||
let names: string[]
|
||||
try {
|
||||
names = readdirSync(d)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const name of names) {
|
||||
if (++files > 200_000) {return}
|
||||
const file = path.join(d, name)
|
||||
try {
|
||||
const s = statSync(file)
|
||||
if (s.isDirectory()) {walk(file)} else {total += s.size}
|
||||
} catch {
|
||||
// gone meanwhile
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(dir)
|
||||
return total
|
||||
}
|
||||
|
||||
export const growthRules: DoctorRule[] = [
|
||||
{
|
||||
// A collection past the thresholds: slower queries, backups and restores, a bigger bill on a managed database
|
||||
id: 'growth-size',
|
||||
check: (ctx) => {
|
||||
const g = ctx.deep?.growth
|
||||
if (!g) {return []}
|
||||
const t = limits(ctx)
|
||||
const big = g.collections.filter((c) => c.docs > t.maxDocs || (c.bytes ?? 0) > t.maxMB * 1024 * 1024)
|
||||
return big.map((c) => ({
|
||||
fix: 'a retention for logs (consentLog / stats retentionDays, forms.submissionRetentionDays), or raise growth.maxDocs / maxMB in iapl-doctor.json with a reason',
|
||||
message: `${c.slug}: ${c.docs} documents${c.bytes === null ? '' : `, ${mb(c.bytes)} MB with indexes`}${c.oldest ? `, the oldest from ${c.oldest.slice(0, 10)}` : ''}`,
|
||||
severity: 'warning' as const,
|
||||
}))
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'growth',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// Versions: Payload keeps 100 per document by default; 0 keeps every save forever
|
||||
id: 'growth-versions',
|
||||
check: (ctx) => {
|
||||
const g = ctx.deep?.growth
|
||||
if (!g) {return []}
|
||||
const t = limits(ctx)
|
||||
const out: RuleFinding[] = []
|
||||
for (const v of g.versions) {
|
||||
if (v.max === 0) {out.push({ fix: `versions: { ${v.kind === 'global' ? 'max' : 'maxPerDoc'}: 20 } (Payload's default is 100)`, message: `${v.kind} ${v.slug} keeps every version without a limit (${v.total} now)`, severity: 'warning' })}
|
||||
else if (v.total > t.maxVersions) {out.push({ fix: `a lower ${v.kind === 'global' ? 'max' : 'maxPerDoc'} (now ${v.max}); Payload trims a document's oldest versions on its next save`, message: `${v.kind} ${v.slug}: ${v.total} versions for ${v.docs} document(s)`, severity: 'warning' })}
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'growth',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// A log with a retention whose oldest record is older than it: the purge is not running (it runs after a new
|
||||
// record, at most once a day per process — a site without new records keeps the old ones)
|
||||
id: 'growth-retention',
|
||||
check: (ctx) => {
|
||||
const g = ctx.deep?.growth
|
||||
if (!g) {return []}
|
||||
const out: RuleFinding[] = []
|
||||
for (const [slug, keep] of Object.entries(g.retention)) {
|
||||
const c = g.collections.find((x) => x.slug === slug)
|
||||
if (!c || !keep || !c.oldest) {continue}
|
||||
const age = days(c.oldest, ctx.today)
|
||||
if (age > keep + 2) {out.push({ fix: 'check the server log for "retention purge failed"; the purge runs after the next new record', message: `${slug} keeps records for ${keep} days, but the oldest is ${age} days old`, severity: 'warning' })}
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'growth',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// Form submissions are personal data and the one plugin collection without a retention by default
|
||||
id: 'growth-submissions',
|
||||
check: (ctx) => {
|
||||
const g = ctx.deep?.growth
|
||||
const c = g?.collections.find((x) => x.slug === 'form-submissions')
|
||||
if (!g || !c || !c.docs || g.retention['form-submissions']) {return []}
|
||||
const age = days(c.oldest, ctx.today)
|
||||
const t = limits(ctx)
|
||||
return [{
|
||||
fix: 'iapl({ forms: { submissionRetentionDays: 365 } }) — or delete old ones in the panel; a decision for the client (AGENTS.md → Project decisions)',
|
||||
message: `${c.docs} form submissions kept without a retention, the oldest ${age} days old`,
|
||||
severity: age > t.submissionDays ? 'warning' : 'info',
|
||||
}]
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'growth',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
id: 'growth-kv',
|
||||
check: (ctx) => {
|
||||
const kv = ctx.deep?.growth?.kv
|
||||
if (!kv || kv.expired === null || kv.expired <= limits(ctx).expiredKv) {return []}
|
||||
return [{ fix: 'expired entries are dead weight: the plugin sweeps its own mail-service nonces (1.18.0); entries of another package are its own', message: `payload-kv holds ${kv.total} entries, ${kv.expired} of them expired`, severity: 'warning' }]
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'growth',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// Media nobody points at: storage, backups and the panel's media list grow for nothing
|
||||
id: 'growth-media',
|
||||
check: (ctx) => {
|
||||
const m = ctx.deep?.growth?.media
|
||||
if (!m || !m.orphaned) {return []}
|
||||
return [{
|
||||
fix: 'review them in the panel (Media) and delete what no page needs — the plugin never deletes media by itself',
|
||||
message: `${m.orphaned} of ${m.total} media files are not used by any document or global${m.capped ? ` (from the first ${m.checked} documents: may be fewer)` : ''}`,
|
||||
severity: m.orphaned > limits(ctx).orphanedMedia ? 'warning' : 'info',
|
||||
}]
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'growth',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// On this machine: Next's image cache has no size cap of its own; local uploads belong on R2 in production
|
||||
id: 'growth-disk',
|
||||
check: (ctx) => {
|
||||
const t = limits(ctx)
|
||||
const out: RuleFinding[] = []
|
||||
const cache = folderBytes(path.join(ctx.root, '.next', 'cache', 'images'))
|
||||
if (mb(cache) > t.imageCacheMB) {out.push({ file: '.next/cache/images', fix: 'it is rebuilt on demand: delete it, or let each Coolify deploy start with an empty one (no persistent volume on .next)', message: `the image cache is ${mb(cache)} MB (no size cap in Next; each image × width × format)`, severity: 'info' })}
|
||||
const uploads = folderBytes(path.join(ctx.root, 'media'))
|
||||
if (mb(uploads) > t.uploadsMB) {out.push({ file: 'media', fix: 'production media on R2 (buildR2Storage); locally, a copy of the database you no longer need can go', message: `the local upload folder is ${mb(uploads)} MB`, severity: 'info' })}
|
||||
return out
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'growth',
|
||||
source: 'static',
|
||||
},
|
||||
]
|
||||
@@ -10,6 +10,7 @@ import { agentRules } from './rules/agents.js'
|
||||
import { blockRules } from './rules/blocks.js'
|
||||
import { consentRules } from './rules/consent.js'
|
||||
import { envRules } from './rules/env.js'
|
||||
import { growthRules } from './rules/growth.js'
|
||||
import { layoutRules } from './rules/layout.js'
|
||||
import { legacyRules } from './rules/legacy.js'
|
||||
import { createLiveFetcher, liveRules } from './rules/live.js'
|
||||
@@ -43,6 +44,7 @@ export const doctorRules: DoctorRule[] = [
|
||||
...seedRules,
|
||||
...blockRules,
|
||||
...performanceRules,
|
||||
...growthRules,
|
||||
...toolingRules,
|
||||
...liveRules,
|
||||
...deepRules,
|
||||
|
||||
@@ -15,7 +15,9 @@ import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFac
|
||||
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
|
||||
import { readEnv } from '../shared/envName.js'
|
||||
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
|
||||
import { retentionMap } from '../shared/retention.js'
|
||||
import { turnstileSecretFromEnv } from '../turnstile/config.js'
|
||||
import { collectGrowth } from './growth.js'
|
||||
import { visitorWritableEntities } from './visitorWrites.js'
|
||||
|
||||
/** The plugin's own version — a constant (src/version.ts), never a file read at run time. */
|
||||
@@ -72,6 +74,12 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
}
|
||||
const pendingCookies = collections.some((c) => c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null
|
||||
const media = await countHeavyMedia(payload, collections)
|
||||
let growth: DoctorStatus['growth'] = null
|
||||
try {
|
||||
growth = { ...(await collectGrowth(payload)), retention: retentionMap(payload) }
|
||||
} catch {
|
||||
growth = null
|
||||
}
|
||||
// Turnstile: the recorded state and where the secret comes from — never the keys themselves.
|
||||
let turnstile: DoctorStatus['turnstile'] = null
|
||||
let secretFromEnv: boolean | null = null
|
||||
@@ -146,7 +154,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
}
|
||||
const { csrf, serverURL } = payload.config as { csrf?: unknown; serverURL?: unknown }
|
||||
const originKnown = (typeof serverURL === 'string' && serverURL.trim() !== '') || (Array.isArray(csrf) && csrf.some((o) => typeof o === 'string' && o.trim() !== ''))
|
||||
return { mail, media, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa, visitorWrites }
|
||||
return { growth, mail, media, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa, visitorWrites }
|
||||
}
|
||||
|
||||
export type DoctorEndpointOptions = {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { GrowthStatus } from './growth.js'
|
||||
import type { DoctorContext } from './project.js'
|
||||
|
||||
/** How bad a finding is: error fails CI, warning is drift to fix, info is worth knowing. */
|
||||
@@ -40,6 +41,8 @@ export type DoctorConfig = {
|
||||
domain?: string
|
||||
/** Paths of extra rule modules (relative to the project), each exporting `rules: DoctorRule[]`. */
|
||||
extraRules?: string[]
|
||||
/** Thresholds of the `growth` rules (docs/performance.md → "What grows"). */
|
||||
growth?: GrowthThresholds
|
||||
/** true once the site is live: seeds must then name their records. */
|
||||
launched?: boolean
|
||||
/**
|
||||
@@ -58,6 +61,8 @@ export type DoctorStatus = {
|
||||
envProblems?: string[]
|
||||
/** Why the deep check could not finish (first line). */
|
||||
error?: string
|
||||
/** What grows (1.18.0, docs/performance.md): counts, sizes, oldest dates, versions, KV, orphaned media, retention in days. */
|
||||
growth?: ({ retention: Partial<Record<string, number>> } & GrowthStatus) | null
|
||||
/** null = not compared (the endpoint cannot read files). */
|
||||
importMapCurrent?: boolean | null
|
||||
/**
|
||||
@@ -161,3 +166,23 @@ export type DoctorReport = {
|
||||
skipped: string[]
|
||||
summary: { error: number; info: number; silenced: number; warning: number }
|
||||
}
|
||||
|
||||
/** When the `growth` rules speak up — every number can be set in iapl-doctor.json `growth`. */
|
||||
export type GrowthThresholds = {
|
||||
/** Expired entries in payload-kv. Default 1000. */
|
||||
expiredKv?: number
|
||||
/** `.next/cache/images` on this machine, MB. Default 1024. */
|
||||
imageCacheMB?: number
|
||||
/** Documents in one collection. Default 200 000. */
|
||||
maxDocs?: number
|
||||
/** Size of one collection with its indexes (MongoDB), MB. Default 512. */
|
||||
maxMB?: number
|
||||
/** Versions of one collection or global. Default 50 000. */
|
||||
maxVersions?: number
|
||||
/** Media no document points at. Default 25. */
|
||||
orphanedMedia?: number
|
||||
/** Form submissions kept without a retention: older than this many days is a warning. Default 730. */
|
||||
submissionDays?: number
|
||||
/** Local upload folder (`media/`), MB. Default 2048. */
|
||||
uploadsMB?: number
|
||||
}
|
||||
|
||||
@@ -173,6 +173,7 @@ export const dropRelayCandidate = (payload: BasePayload, host: string = ownHost(
|
||||
/** Remembers that the site at `host` started an enrolment with `nonce`. Only the nonce's hash is stored. */
|
||||
export async function holdNonce(payload: BasePayload, nonce: string, ttlMs: number, host: string = ownHost(payload)): Promise<string> {
|
||||
const nonceHash = sha256Hex(nonce)
|
||||
await sweepExpiredNonces(payload)
|
||||
await kvOf(payload).set(nonceKey(nonceHash), { expiresAt: Date.now() + ttlMs, hash: nonceHash, host })
|
||||
return nonceHash
|
||||
}
|
||||
@@ -194,3 +195,36 @@ export async function takeNonce(payload: BasePayload, nonce: string): Promise<{
|
||||
}
|
||||
|
||||
export const releaseNonce = (payload: BasePayload, nonce: string) => kvOf(payload).delete(nonceKey(sha256Hex(nonce)))
|
||||
|
||||
/**
|
||||
* Removes held nonces whose time has passed (1.18.0). A nonce whose call-back never came stayed in payload-kv for
|
||||
* good: its expiry was only checked when read. An expired nonce can never be taken again (takeNonce refuses it) and
|
||||
* a new enrolment uses a new key, so this changes nothing but the size of the store. At most once a day per process,
|
||||
* started by the next enrolment; a failure is ignored (the next one tries again).
|
||||
*/
|
||||
let lastNonceSweep = 0
|
||||
export async function sweepExpiredNonces(payload: BasePayload, now = Date.now()): Promise<number> {
|
||||
if (now - lastNonceSweep < 86_400_000) {return 0}
|
||||
lastNonceSweep = now
|
||||
let removed = 0
|
||||
try {
|
||||
const kv = kvOf(payload)
|
||||
const prefix = nonceKey('')
|
||||
if (typeof kv.keys !== 'function') {return 0}
|
||||
for (const key of (await kv.keys()).filter((k) => k.startsWith(prefix))) {
|
||||
const held = (await kv.get(key)) as { expiresAt?: unknown } | null
|
||||
if (held && typeof held.expiresAt === 'number' && held.expiresAt < now) {
|
||||
await kv.delete(key)
|
||||
removed++
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
lastNonceSweep = 0
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
/** Tests: forget when the last sweep ran. */
|
||||
export const resetNonceSweep = () => {
|
||||
lastNonceSweep = 0
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ import type { AcceptedFormFile, FormFileFailure } from './attachments/fileGate.j
|
||||
import type { FormValidationResult } from './validateSubmission.js'
|
||||
|
||||
import { mailAttachmentLimit } from '../email/attachmentLimit.js'
|
||||
import { createDailyPurge } from '../shared/purge.js'
|
||||
import { retentionOf } from '../shared/retention.js'
|
||||
import { getTurnstileConfig } from '../turnstile/config.js'
|
||||
import { verifyTurnstile } from '../turnstile/verify.js'
|
||||
import { getFormAttachments } from './attachments/config.js'
|
||||
@@ -15,6 +17,9 @@ import { formatFileSize } from './attachments/fileTypes.js'
|
||||
import { consumeRateLimit } from './rateLimit.js'
|
||||
import { validateSubmission } from './validateSubmission.js'
|
||||
|
||||
/** forms.submissionRetentionDays: old submissions deleted at most once a day, off the visitor's request. */
|
||||
const purgeSubmissions = createDailyPurge('form-submissions')
|
||||
|
||||
export type SubmitFormArgs = {
|
||||
/**
|
||||
* A key the browser makes per submit attempt (16–64 letters, digits, `-`, `_`).
|
||||
@@ -333,6 +338,8 @@ export async function storeSubmission({
|
||||
...(delivery ? { filesDelivery: 'failed', submissionFiles: files.map((f) => ({ name: f.name, type: f.type, field: f.field, size: f.size })) } : {}),
|
||||
} as never,
|
||||
})
|
||||
const keepDays = retentionOf(payload, 'form-submissions')
|
||||
if (keepDays) {purgeSubmissions(payload, { createdAt: { less_than: new Date(Date.now() - keepDays * 86_400_000).toISOString() } })}
|
||||
if (!delivery) {return { submissionId: submission.id, success: true }}
|
||||
|
||||
const result = delivery.result ?? { note: 'No e-mail was sent for this form.', state: 'failed' as const }
|
||||
|
||||
@@ -104,6 +104,12 @@ export type FormsOption = {
|
||||
formSubmissionOverrides?: FormsCollectionOverrides
|
||||
/** Collections a form can redirect to (e.g. ['pages']). */
|
||||
redirectRelationships?: string[]
|
||||
/**
|
||||
* Keep form submissions this many days, then delete them (1.18.0; checked at most once a day, after a new
|
||||
* submission). Default: kept until someone deletes them in the panel, as before. Submissions hold personal data
|
||||
* (GDPR: no longer than needed) and are the one plugin collection that grows without end (docs/performance.md).
|
||||
*/
|
||||
submissionRetentionDays?: number
|
||||
/**
|
||||
* What a form does while Turnstile CANNOT check — the secret is missing or
|
||||
* wrong, Cloudflare is down (the "degraded" state, shown in Site
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { BasePayload, Config } from 'payload'
|
||||
|
||||
/**
|
||||
* How long each plugin log keeps its records, in days (`config.custom.iapl.retention`): written by iapl() for the
|
||||
* consent log, the statistics and — when the project sets one — form submissions. The purge reads it; the doctor's
|
||||
* `growth-retention` rule checks that the oldest record is not older (the purge runs), docs/performance.md.
|
||||
*/
|
||||
export type RetentionMap = Partial<Record<string, number>>
|
||||
|
||||
export function withRetention(config: Config, slug: string, days: number | undefined): Config {
|
||||
if (typeof days !== 'number' || !(days > 0)) {return config}
|
||||
const iapl = (config.custom?.iapl ?? {}) as { retention?: RetentionMap }
|
||||
return { ...config, custom: { ...config.custom, iapl: { ...iapl, retention: { ...iapl.retention, [slug]: days } } } }
|
||||
}
|
||||
|
||||
export function retentionOf(payload: Pick<BasePayload, 'config'>, slug: string): number | undefined {
|
||||
const days = ((payload.config?.custom as { iapl?: { retention?: RetentionMap } } | undefined)?.iapl?.retention ?? {})[slug]
|
||||
return typeof days === 'number' && days > 0 ? days : undefined
|
||||
}
|
||||
|
||||
export const retentionMap = (payload: Pick<BasePayload, 'config'>): RetentionMap =>
|
||||
({ ...((payload.config?.custom as { iapl?: { retention?: RetentionMap } } | undefined)?.iapl?.retention ?? {}) })
|
||||
@@ -74,6 +74,7 @@ import { searchSettingsFields } from './modules/seo/searchSettings.js'
|
||||
import { migrateTitleSeparator } from './modules/seo/titleSeparator.js'
|
||||
import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
|
||||
import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js'
|
||||
import { withRetention } from './modules/shared/retention.js'
|
||||
import { assertPluginSwitches } from './modules/shared/switches.js'
|
||||
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
|
||||
import { visitorCookieFor } from './modules/stats/visitorCookie.js'
|
||||
@@ -733,6 +734,12 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
// --- forms: apply @payloadcms/plugin-form-builder directly ---
|
||||
if (options.forms) {
|
||||
config = await buildFormsPlugin(options.forms)(config)
|
||||
if (options.forms.submissionRetentionDays !== undefined) {
|
||||
if (!(Number.isFinite(options.forms.submissionRetentionDays) && options.forms.submissionRetentionDays > 0)) {
|
||||
throw new Error('[iapl] forms.submissionRetentionDays must be a number of days above 0 (leave it out to keep submissions)')
|
||||
}
|
||||
config = withRetention(config, 'form-submissions', options.forms.submissionRetentionDays)
|
||||
}
|
||||
// submitForm reads it from payload.config when the call doesn't pass one
|
||||
if (options.forms.consentFieldName) {
|
||||
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, consentFieldName: options.forms.consentFieldName } }
|
||||
@@ -847,6 +854,7 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
const logOptions = options.consentLog === true || options.consentLog === undefined ? {} : options.consentLog
|
||||
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildConsentLogCollection(), logOptions.collectionOverrides)]
|
||||
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
|
||||
config = withRetention(config, 'consent-records', logOptions.retentionDays ?? 1095)
|
||||
}
|
||||
|
||||
// --- cookie scanner: review list + "Scan cookies" (opt-in) ---
|
||||
@@ -928,6 +936,7 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
const viewProps = { adminRoute, ...(statsOptions.timeZone ? { timeZone: statsOptions.timeZone } : {}) }
|
||||
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildStatsCollection(), statsOptions.collectionOverrides)]
|
||||
config.endpoints = [...(config.endpoints ?? []), buildStatsEndpoint(statsOptions)]
|
||||
config = withRetention(config, 'stats-visits', statsOptions.retentionDays ?? 90)
|
||||
config.admin = {
|
||||
...(config.admin ?? {}),
|
||||
components: {
|
||||
|
||||
Reference in New Issue
Block a user