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
@@ -1058,6 +1058,7 @@ Example `styles.css`: [section-code.md](./skills/iapl-block/resources/section-co
|
||||
| animations | `transform` / `opacity` only, the token durations (`duration-fast`, reduced motion built in) or `motion-reduce:`; IntersectionObserver for "is it on screen" | animating `height` / `top` / `margin`, `transition-all`, a `scroll` listener doing work per event |
|
||||
| client components | small, interaction only (§6.9); import from `@intecion/ipal-kit/client` freely — a page ships only what it renders (1.18.0) | a whole section `'use client'` |
|
||||
| data | the cached helpers of `lib/content` (`getSettings`, `resolveRoute`, `getSiteShell`…), `depth` as low as the page needs, `select` when you need one field, `cache()` around your own getters | `findGlobal` in a component without `cache()`, `depth: 2` "to be safe", a query per list item |
|
||||
| what grows | logs with a retention (consent log 1095 days, statistics 90; `forms: { submissionRetentionDays }` on the client's decision), `versions: { maxPerDoc: 20 }` where you turn versions on, unused media reviewed; `iapl-doctor --deep --only growth` ([performance.md](../performance.md) §6) | `maxPerDoc: 0`, submissions kept forever without a decision, a persistent volume on `.next` |
|
||||
| budgets | `e2e/performance.spec.ts` from the `iapl-performance` skill (`perfBudgets()` from `/doctor`): fails when a page gets slower | "it felt fast on my machine" |
|
||||
|
||||
Target on the built site (mobile, Lighthouse/PageSpeed): LCP < 2.5 s, CLS < 0.1, INP < 200 ms — the plugin's default
|
||||
@@ -1562,6 +1563,7 @@ bash .agents/skills/iapl-audit/scripts/audit.sh
|
||||
pnpm exec iapl-doctor # + --deep --url http://localhost:3000 on the built site
|
||||
node .agents/skills/iapl-seo-check/scripts/seo-check.mjs http://localhost:3000
|
||||
pnpm test:e2e e2e/performance.spec # the budget gate (iapl-performance) on the built site
|
||||
pnpm exec iapl-doctor --deep --only growth # what grows: sizes, versions, retention, old submissions, unused media
|
||||
pnpm generate:types && pnpm tsc --noEmit
|
||||
pnpm build # --webpack in the script; locally, not only dev
|
||||
# hardcoding and the field zoo in blocks
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: iapl-performance
|
||||
description: Makes and keeps an IAPL site fast — page loading (LCP image, fonts, nothing render-blocking, static rendering), elements (lazy below the fold, reserved space, click-to-load embeds), animations (transform/opacity, reduced motion, no scroll handlers), resources (only the JS a page uses, compression, no third-party request before consent), images (AVIF/WebP, sizes, upload limits) and the server (queries per render, depth, select, caching). Measures the built site, runs the doctor's performance group, and adds the budget gate that fails when a change makes the site slower. Use when building pages or blocks, before handing over, after an IAPL upgrade, and whenever "slow", PageSpeed, Lighthouse, Core Web Vitals, LCP, CLS or INP come up.
|
||||
description: Makes and keeps an IAPL site fast — page loading (LCP image, fonts, nothing render-blocking, static rendering), elements (lazy below the fold, reserved space, click-to-load embeds), animations (transform/opacity, reduced motion, no scroll handlers), resources (only the JS a page uses, compression, no third-party request before consent), images (AVIF/WebP, sizes, upload limits) and the server (queries per render, depth, select, caching); what grows in the database and on disk over the years (logs and their retention, form submissions, versions, KV, unused media, the image cache). Measures the built site, runs the doctor's performance group, and adds the budget gate that fails when a change makes the site slower. Use when building pages or blocks, before handing over, after an IAPL upgrade, and whenever "slow", PageSpeed, Lighthouse, Core Web Vitals, LCP, CLS, INP, a growing database or disk come up.
|
||||
---
|
||||
|
||||
# iapl-performance
|
||||
@@ -48,7 +48,19 @@ a change makes a page slower. PageSpeed Insights on the deployed site shows the
|
||||
- **Queries per render** (the reference gate counts them): over 30 for an ordinary page → a missing `cache()`, a
|
||||
`depth` too high, or a loop of `findByID`.
|
||||
|
||||
## 4. Before "done"
|
||||
## 4. What grows (performance.md §6)
|
||||
```bash
|
||||
pnpm exec iapl-doctor --deep --only growth # counts and sizes per collection, oldest records, versions, expired KV, unused media, disk
|
||||
```
|
||||
- Logs purge themselves (consent log 1095 days, statistics 90). Form submissions are kept unless
|
||||
`iapl({ forms: { submissionRetentionDays } })` — ask the client (personal data) and record it in AGENTS.md.
|
||||
- Versions: where you turn them on, `versions: { maxPerDoc: 20 }` (globals `max`); never `0`.
|
||||
- Unused media (`growth-media`): list them for the client; the plugin never deletes media or submissions by itself.
|
||||
- Coolify: no persistent volume on `.next` (the image cache starts empty on each deploy); database backups on the
|
||||
MongoDB resource.
|
||||
- Thresholds of the findings: `iapl-doctor.json` → `growth`.
|
||||
|
||||
## 5. Before "done"
|
||||
`iapl-doctor --only performance` without warnings (or each one silenced with a reason in `iapl-doctor.json`),
|
||||
the budget test green, and the numbers in `AGENTS.md` → "Project decisions" when the client accepted an exception
|
||||
(a heavy font, a third-party widget).
|
||||
|
||||
@@ -215,6 +215,7 @@ Mandatory set: AGENT.md §0b, skill **iapl-setup**; checks: **iapl-audit**, **ia
|
||||
| storage | `payload.config.ts` | `buildR2Storage(['media'], { s3Storage })` — always (without `R2_*` = local disk) | upload → URL from `R2_PUBLIC_URL` | storage.md |
|
||||
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP from the panel / Graph from env; also `panelSmtpAdapter`, `graphAdapter`, `sendEmail` from `/server`) | Site integrations → E-mail sending → **Send test** | email.md |
|
||||
| forms — action | `app/(frontend)/[locale]/actions.ts` | `'use server'`; `export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`/server`) | submit → document in Form Submissions + e-mails | forms.md, skill **iapl-form** |
|
||||
| forms — retention | config (client decision) | `forms: { submissionRetentionDays: 365 }` (1.18.0; default: kept) | `iapl-doctor --deep --only growth-submissions` quiet; old submissions gone a day after the next submission | performance.md §6, forms.md |
|
||||
| forms — files | config + panel | `forms: { attachments: true }`; a **File** field on the form; an e-mail with fixed recipients in Forms → E-mails; `mailAdapter({ graph: { largeAttachments } })` when Graph must stay under 3 MB; Azure: `Mail.ReadWrite` limited to the forms mailbox for files of 3 MB and more over Graph | Test e-mail with "Attach a 10 MB test file" arrives; a submission with a PDF arrives with the attachment; nothing in Media | forms.md "Files", email.md "Attachments" |
|
||||
| forms — render | form block | `<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />` (`/rsc`) | form from the panel, Turnstile, message from Notifications | forms.md |
|
||||
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site integrations → Spam protection or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
|
||||
|
||||
@@ -452,7 +452,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `createSubmitAction({ getCachedPayload, headers, … })` | `@intecion/ipal-kit/server` | Creates the server action `sendForm(formId, locale, values, token?)`: honeypot → `clientIp` → `submitForm` → text from Notifications; returns `SubmitActionResult`. Standard: `export const sendForm = createSubmitAction({ getCachedPayload, headers })` in `actions.ts` |
|
||||
| `submitForm({ payload, formId, data, files?, attemptKey?, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `iapl({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
|
||||
| `submitForm({ payload, formId, data, files?, attemptKey?, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `iapl({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission (and, with `forms.submissionRetentionDays`, deletes older ones at most once a day); returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
|
||||
|
||||
### Honeypot
|
||||
|
||||
@@ -878,6 +878,7 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f
|
||||
| `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. |
|
||||
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `media` (images over `IMAGE_RULES`, 1.18.0), `plugin`, `node`. |
|
||||
| `PERF_BUDGETS`, `SERVER_BUDGET`, `perfBudgets(overrides)`, `overBudget(measured, budget)`, `IMAGE_RULES` | `@intecion/ipal-kit/doctor` | Performance budgets (1.18.0, performance.md): the defaults per profile (`mobile`, `desktop`: `lcp`, `cls`, `inp`, `tbt`, `jsBytes`, `cssBytes`, `fontBytes`, `requests`, `renderBlocking`, `thirdParty`) and per render (`queriesPerRender`); a project's own on top; the broken budgets of one measurement as lines (empty = within budget); the image limits (1.5 MB, 2560 px, AVIF/WebP). Types `PerfBudget`, `PerfMeasurement`, `PerfProfile`, `ServerBudget`. The gate: `iapl-performance/resources/performance.spec.template.ts` + `perf-lab.mjs`. |
|
||||
| `collectGrowth(payload)` → `GrowthStatus`, `growthRules`, `GROWTH_DEFAULTS`, `folderBytes(dir)` | `@intecion/ipal-kit/doctor` | What grows (1.18.0, performance.md §6): per collection documents, bytes (MongoDB) and the oldest record; versions per collection and global with their limit; `payload-kv` entries and expired ones; media no document points at (first 5000 documents) — counts only. The `growth` rules (`growth-size`, `-versions`, `-retention`, `-submissions`, `-kv`, `-media`, `-disk`) and their default thresholds (`iapl-doctor.json` → `growth`, type `GrowthThresholds`). |
|
||||
| `performanceRules` | `@intecion/ipal-kit/doctor` | The doctor's `performance` group (`perf-images-config`, `perf-fonts`, `perf-render-blocking`, `perf-embeds`, `perf-animations`, `perf-budgets`, `perf-live`, `perf-images`) — part of `doctorRules`. |
|
||||
| `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IAPL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `iapl` unless `doctor: false`. |
|
||||
| `jobsRunAccess({ secretVar? })` | `@intecion/ipal-kit` | The rule iapl puts on `jobs.access.run` when the project writes none: `cronSecretMatches(req, process.env[secretVar])` or an admin with the second factor. Reuse it in your own rule: `run: (a) => jobsRunAccess()(a) \|\| myCheck(a)`. Type `JobsRunAccessOptions`. |
|
||||
|
||||
+37
-1
@@ -140,9 +140,45 @@ the proxy does no database work; the 434 KB cookie database is loaded only by a
|
||||
8. **Doctor performance rules: warnings now, errors later?** In 1.18.0 they warn (as asked); `perf-live`
|
||||
uncompressed HTML and `perf-images` could become errors in 1.19.0.
|
||||
|
||||
## Growth review (owner's addition, 2026-12-01): what swells the site and its database
|
||||
|
||||
Measured on the reference site (MongoDB 7) after the full reference suite as traffic: 15 collections, the largest
|
||||
`pages` (15 × 9 KB); consent record 185 B, form submission 647 B, KV entry 371 B on average, plus 2–6 indexes per
|
||||
collection. `pnpm exec iapl-doctor --deep --only growth` on it: 2.6 s, two infos (3 submissions without a
|
||||
retention; 1 of 17 media unused — `logo-example-studio-1.webp`, a duplicate logo a test uploaded).
|
||||
|
||||
| Store | Today (1.17.2 defaults) | file:line | 1.18.0 |
|
||||
|---|---|---|---|
|
||||
| consent-records | purged after 1095 days, once a day per process, only after a new record; one unbounded `deleteMany` | `consent/consentLog.ts:124,161`, `shared/purge.ts:16` | retention recorded for the doctor; `growth-retention` reports a purge that has not caught up |
|
||||
| stats-visits (opt-in) | purged after 90 days, same mechanism | `stats/endpoint.ts:53,153` | same |
|
||||
| form-submissions | **no retention, nothing deletes them**; files never stored | `forms/submitForm.ts:324` | opt-in `forms.submissionRetentionDays` (default: kept); `growth-submissions` |
|
||||
| payload-kv: mail-service nonces | expiry checked only on read: a nonce whose call-back never came stayed for good | `email/relay/store.ts:174` | expired nonces swept (once a day, at the next enrolment) |
|
||||
| payload-kv: 2FA counters, relay state | one per staff account / host; never deleted | `security/totp/verifyLimit.ts:84`, `relay/store.ts:114` | left alone: bounded; a sweep could race a live verify |
|
||||
| versions | the plugin turns none on; Payload keeps 100 per document / global | `payload/dist/collections/config/sanitize.js:172` | `growth-versions` (0 = unlimited, or over 50 000) |
|
||||
| cookie-review (opt-in) | upsert by name; `gone` rows kept | `consent/scanner/scan.ts:297` | documented |
|
||||
| payload-preferences / locked-documents / jobs | Payload cleans them; the plugin queues no jobs | — | — |
|
||||
| media | deleted with the document (disk and R2); nothing finds unused media | `storage/buildR2Storage.ts:140` | `growth-media` (counts, never deletes) |
|
||||
| `.next/cache/images` | 31-day TTL, no size cap | `storage/buildImagesConfig.ts:56` | `growth-disk` (info); Coolify: no volume on `.next` |
|
||||
| logs | the plugin writes no files | — | — |
|
||||
|
||||
Postgres / SQLite: the same purges through Drizzle's `deleteMany`; no TTL indexes; sizes not read (counts only).
|
||||
|
||||
### Growth — for the owner (yes / no)
|
||||
|
||||
9. **A default retention for form submissions** (e.g. 365 days) on every site, existing ones included. Deletes
|
||||
data on live sites on their next submission. Recommendation: no default; the agent asks the client
|
||||
(`submissionRetentionDays`) and the doctor reports sites without one — or yes with 730 days and a loud upgrade note.
|
||||
10. **MongoDB TTL indexes** for the consent log and statistics (expire `createdAt` / `lastAt` after the retention),
|
||||
so the purge runs even when no new record comes. Same records deleted as today, sooner on a quiet site; one index
|
||||
build per site at start. Recommendation: yes for 1.19.0 (opt-out), Mongo only.
|
||||
11. **Delete `gone` cookie-review rows after a year.** Deletes the scanner's history. Recommendation: no.
|
||||
12. **A media clean-up action in the panel** (list the unused media, delete after confirmation). Recommendation:
|
||||
yes, as a panel view — never automatic.
|
||||
13. **`maxPerDoc: 20`** in the reference and the starter wherever versions get turned on (none today). Recommendation: yes (no data deleted until a document is saved again).
|
||||
|
||||
### Shared with IAWL
|
||||
|
||||
Proposed for both products (performance.md §6): the Core Web Vitals targets and the lab profile; JS ≤ 250 KB,
|
||||
Proposed for both products (performance.md §7): the Core Web Vitals targets and the lab profile; JS ≤ 250 KB,
|
||||
CSS ≤ 50 KB, fonts ≤ 250 KB and two families, ≤ 40 requests on the phone, one render-blocking stylesheet, no
|
||||
third-party origin before consent; images ≤ 1.5 MB and ≤ 2560 px at upload, AVIF / WebP in the width the screen
|
||||
needs, one high-priority LCP image, lazy below the fold. Not shared: the database budget (MongoDB queries per render
|
||||
|
||||
@@ -70,6 +70,11 @@ returns counts only — never names, e-mails or values:
|
||||
{ "mail": { "graphEnv": false, "relay": { "connected": true, "disconnected": false, "nameReplaced": false, "state": "active" }, "replyAddress": true, "status": null, "transport": "relay" }, "media": { "images": 42, "oversized": 0, "tooWide": 0 }, "node": "v22.20.0", "openSignUp": [], "pendingCookies": 0, "plugin": "1.15.0", "staffOnOwnRoles": [], "staffOpenToOthers": [], "turnstile": null, "turnstileSecretFromEnv": false, "usersSetupClosed": 0, "usersWithout2fa": 0 }
|
||||
```
|
||||
|
||||
`growth` (since 1.18.0): per collection its documents, its size with indexes (MongoDB; `null` elsewhere) and the date
|
||||
of its oldest record; versions per versioned collection and global with their limit; `payload-kv` entries and how
|
||||
many have expired; media no document points at (`checked` documents read, at most 5000); the retention in days of
|
||||
each plugin log — counts, sizes and dates only.
|
||||
|
||||
`media` (since 1.18.0): how many images the upload collections hold and how many are over the plugin's limits
|
||||
(1.5 MB, 2560 px) — counts only, `null` without an upload collection.
|
||||
|
||||
@@ -146,6 +151,13 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE
|
||||
| | `perf-budgets` | info | a project that runs Playwright has a performance budget test in `e2e/` (the `iapl-performance` skill's template) |
|
||||
| | `perf-live` | warning | (live) the home HTML is compressed, has no blocking `<script>` in `<head>`, preloads at most four fonts, its first image in `<main>` is not lazy, and is at most 150 KB |
|
||||
| | `perf-images` | warning | (deep) no stored image over 1.5 MB or 2560 px wide (`IMAGE_RULES`) |
|
||||
| growth | `growth-size` | warning | (deep) no collection over `growth.maxDocs` (200 000) documents or `growth.maxMB` (512, data + indexes, MongoDB) — [performance.md](./performance.md) §6 |
|
||||
| | `growth-versions` | warning | (deep) no collection or global keeps versions without a limit (`maxPerDoc` / `max`: 0), none over `growth.maxVersions` (50 000) |
|
||||
| | `growth-retention` | warning | (deep) a log with a retention (consent log, statistics, form submissions with `submissionRetentionDays`) holds no record older than it — its purge runs |
|
||||
| | `growth-submissions` | info / warning | (deep) form submissions kept without a retention; a warning when the oldest is over `growth.submissionDays` (730) |
|
||||
| | `growth-kv` | warning | (deep) at most `growth.expiredKv` (1000) expired entries in `payload-kv` |
|
||||
| | `growth-media` | info / warning | (deep) media no document or global points at; a warning over `growth.orphanedMedia` (25). From the first 5000 documents |
|
||||
| | `growth-disk` | info | `.next/cache/images` over `growth.imageCacheMB` (1024), the local `media/` over `growth.uploadsMB` (2048), on the machine the doctor runs on |
|
||||
| audit | `i18n-literals` | error / warning | from `iapl-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code (not the panel's `adminText()` / `{ en, pl }` labels in a schema file — the `iapl-audit` skill) |
|
||||
| | `audit:<title>` | as reported | every other `iapl-audit --quick` finding, one per file |
|
||||
| live | `live-reachable`, `live-health`, `live-noindex`, `live-seo` | error / warning | the URL answers; `/api/health` 200; production not noindex (staging must be); every `iapl-seo-check` error and warning |
|
||||
@@ -181,6 +193,7 @@ of the two exists, `iapl-doctor.json` when both do):
|
||||
|---|---|
|
||||
| `domain` | the production domain (dots allowed) — the base of the database names. Without it: a non-local `NEXT_PUBLIC_SERVER_URL`, else the folder name minus `-web` |
|
||||
| `launched` | the site is live: seeds must then name their records. Also true when "Project decisions" has a line with "launch" and a date |
|
||||
| `growth` | thresholds of the `growth` rules: `maxDocs`, `maxMB`, `maxVersions`, `submissionDays`, `expiredKv`, `orphanedMedia`, `imageCacheMB`, `uploadsMB` ([performance.md](./performance.md) §6) |
|
||||
| `layout.allow` | more top-level `src/` entries the convention allows |
|
||||
| `layout.frontend` | the folder that holds the site's pages, e.g. `src/app/(site)` — only for a layout the doctor cannot tell (two route groups with pages); the route group's name is otherwise free |
|
||||
| `rules.<id>` | `off` (silence), `severity` (`error` / `warning` / `info`), `reason` (**required** — an entry without one is ignored and reported), `until` (ISO date; after it the entry stops applying and the report says so), `files` (globs: only findings in those files). The id is the rule (`csp`) or an audit finding (`audit:collections-present`); `audit` covers all audit findings |
|
||||
|
||||
@@ -60,6 +60,7 @@ iapl({
|
||||
| `formOverrides` / `formSubmissionOverrides` | — | collection overrides (`fields` as a function + any collection settings) |
|
||||
| `emailLayout` | `false` | nice emails + the Site settings → E-mails tab |
|
||||
| `beforeEmail` | — | the form-builder's `beforeEmail` (after the layout, when `emailLayout`) |
|
||||
| `submissionRetentionDays` | — (kept) | 1.18.0: delete submissions older than this many days (checked at most once a day, after a new submission). Submissions are personal data — set it on the client's decision (AGENTS.md → Project decisions); the doctor's `growth-submissions` reports a site without one ([performance.md](./performance.md) §6) |
|
||||
| `consentFieldName` | `'consent'` | name of the GDPR consent field for `submitForm` / `createSubmitAction` (the call's argument wins) |
|
||||
|
||||
`payment` is always off — `fields: { payment: true }` does **not** turn it on (the value `true`
|
||||
|
||||
+48
-1
@@ -138,7 +138,54 @@ All in the `performance` group (`iapl-doctor --only performance`), warnings in 1
|
||||
|
||||
Silence a finding with a reason in `iapl-doctor.json` like any other ([doctor.md](./doctor.md)).
|
||||
|
||||
## 6. Shared with IAWL
|
||||
## 6. What grows — keeping the site and its database small over the years
|
||||
|
||||
Measured on the reference site after a full test run (MongoDB; average record without indexes): a consent record
|
||||
185 B, a form submission 647 B, a key-value entry 371 B, a page 9 KB. Every collection also carries 2–6 indexes.
|
||||
|
||||
| What | Grows with | What the plugin does (1.18.0) | What the project decides |
|
||||
|---|---|---|---|
|
||||
| Consent log (`consent-records`) | one record per banner choice | deleted after `retentionDays` (default 1095 — three years, the proof-of-consent period); the purge runs at most once a day, after a new record | `consentLog: { retentionDays }` |
|
||||
| Statistics (`stats-visits`, opt-in) | one record per visit | deleted after `retentionDays` (default 90), same purge | `stats: { retentionDays }` |
|
||||
| Form submissions | one per sent form (files are never stored: they go out by e-mail) | **kept** until deleted in the panel — unless `forms: { submissionRetentionDays }` is set (1.18.0), then deleted after that many days, once a day after a new submission | the retention: personal data, a client decision (AGENTS.md → Project decisions) |
|
||||
| Versions and drafts | every save | the plugin turns versions on nowhere; Payload keeps 100 per document by default (`maxPerDoc`, `max` for globals) | a lower limit where you turn versions on: `versions: { maxPerDoc: 20 }`; never `0` (unlimited) |
|
||||
| `payload-kv` | 2FA attempt counters (one per staff account), the mail service state (one per host), enrolment nonces | expired mail-service nonces are swept (at most once a day, when the next enrolment starts); counters and state are bounded by accounts and hosts | — |
|
||||
| Cookie review (opt-in) | distinct cookie names | upserted by name; a cookie that disappears is marked `gone`, not deleted (the history of what the site set) | delete old `gone` rows in the panel when the client agrees |
|
||||
| `payload-preferences`, `payload-locked-documents`, `payload-jobs` | panel users, open documents, queued jobs | Payload removes them with the user, on save, and on completion (`deleteJobOnComplete`); the plugin queues no jobs | — |
|
||||
| Media | uploads | Payload deletes the files (and R2 objects) with the document; nothing deletes media nobody uses | review `growth-media` findings in the panel |
|
||||
| `.next/cache/images` | each image × width × format (AVIF + WebP) | kept 31 days per variant (`minimumCacheTTL`); Next caps nothing by size | no persistent volume on `.next` in Coolify: every deploy starts empty |
|
||||
| ISR output | pages × languages | rewritten in place on each revalidation | — |
|
||||
| Logs | — | the plugin writes no files; it logs to stdout (Coolify keeps the container's log) | Coolify's log retention |
|
||||
|
||||
**Postgres and SQLite:** the same purges (one `DELETE … WHERE created_at < …`); no TTL indexes; the doctor reports
|
||||
counts but not sizes. A consent log without its migration records nothing and so never purges.
|
||||
|
||||
**What a project schedules:** nothing for the plugin's own logs — the purges run inside the site. A site that gets
|
||||
no new consent records (or submissions) for a long time keeps the old ones until the next one comes; the doctor's
|
||||
`growth-retention` rule says so. Database backups are the hosting's job (Coolify → the MongoDB resource → Backups).
|
||||
|
||||
**How to check:** `pnpm exec iapl-doctor --deep --only growth` (or `--url` with `IAPL_DOCTOR_TOKEN`): document
|
||||
counts, sizes (MongoDB), the oldest record, versions per collection and global, expired KV entries, media no
|
||||
document points at; and on the machine it runs on, the image cache and the local upload folder. Thresholds in
|
||||
`iapl-doctor.json`:
|
||||
|
||||
```json
|
||||
{ "growth": { "maxDocs": 200000, "maxMB": 512, "maxVersions": 50000, "submissionDays": 730, "expiredKv": 1000, "orphanedMedia": 25, "imageCacheMB": 1024, "uploadsMB": 2048 } }
|
||||
```
|
||||
|
||||
| Rule | Source | It means |
|
||||
|---|---|---|
|
||||
| `growth-size` | deep | a collection over `maxDocs` documents or `maxMB` (data + indexes, MongoDB) |
|
||||
| `growth-versions` | deep | a collection or global keeps versions without a limit, or over `maxVersions` |
|
||||
| `growth-retention` | deep | a log with a retention holds records older than it: its purge has not run |
|
||||
| `growth-submissions` | deep | form submissions kept without a retention (info; a warning when the oldest is over `submissionDays`) |
|
||||
| `growth-kv` | deep | more than `expiredKv` expired entries in `payload-kv` |
|
||||
| `growth-media` | deep | media nothing points at (info; a warning over `orphanedMedia`). Counted from the first 5000 documents |
|
||||
| `growth-disk` | static | `.next/cache/images` over `imageCacheMB`, the local `media/` folder over `uploadsMB` (info) |
|
||||
|
||||
None of these rules deletes anything; the plugin never deletes media or submissions by itself.
|
||||
|
||||
## 7. Shared with IAWL
|
||||
|
||||
IAWL (the WordPress line) holds its sites to the same numbers where the measurement is the same: the Core Web Vitals
|
||||
targets and lab profile, JS ≤ 250 KB, CSS ≤ 50 KB, fonts ≤ 250 KB and two families, requests ≤ 40 on the phone,
|
||||
|
||||
@@ -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: {
|
||||
|
||||
+1
-1
@@ -554,7 +554,7 @@ describe('security and deep status', () => {
|
||||
}
|
||||
const status = await collectDoctorStatus(payload as never)
|
||||
expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 })
|
||||
expect(Object.keys(status).sort()).toEqual(['mail', 'media', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites'])
|
||||
expect(Object.keys(status).sort()).toEqual(['growth', 'mail', 'media', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites'])
|
||||
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
|
||||
expect(status.mail).toBeNull() // no Site integrations global in this config
|
||||
expect(status.media).toBeNull() // no upload collection in this config
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { collectGrowth } from '../src/modules/doctor/growth.js'
|
||||
import { folderBytes, GROWTH_DEFAULTS } from '../src/modules/doctor/rules/growth.js'
|
||||
import { runDoctor } from '../src/modules/doctor/run.js'
|
||||
import { resetNonceSweep, sweepExpiredNonces } from '../src/modules/email/relay/store.js'
|
||||
import { submitForm } from '../src/modules/forms/submitForm.js'
|
||||
import { retentionMap, retentionOf, withRetention } from '../src/modules/shared/retention.js'
|
||||
import { fakePayload } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const packageRoot = path.resolve(import.meta.dirname, '..')
|
||||
let dirs: string[] = []
|
||||
afterEach(() => {
|
||||
for (const d of dirs) {rmSync(d, { force: true, recursive: true })}
|
||||
dirs = []
|
||||
})
|
||||
const project = (files: Record<string, string> = {}) => {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'iapl-growth-'))
|
||||
dirs.push(root)
|
||||
for (const [rel, content] of Object.entries({ 'package.json': '{"name":"x-web"}', ...files })) {
|
||||
mkdirSync(path.dirname(path.join(root, rel)), { recursive: true })
|
||||
writeFileSync(path.join(root, rel), content)
|
||||
}
|
||||
return root
|
||||
}
|
||||
const growth = (over: object = {}) => ({ collections: [], kv: null, media: null, retention: {}, versions: [], ...over })
|
||||
const found = async (root: string, deep: null | object, config: object = {}) =>
|
||||
(await runDoctor({ config, deepStatus: deep ? ({ growth: deep } as never) : null, offline: true, only: ['growth'], packageRoot, root, today: '2026-12-01', writeSeen: false })).findings.map((f) => `${f.rule} ${f.severity}: ${f.message}`)
|
||||
|
||||
describe('doctor: growth rules', () => {
|
||||
test('nothing to say about a small, purged site', async () => {
|
||||
const deep = growth({
|
||||
collections: [{ slug: 'consent-records', bytes: 4096, docs: 20, oldest: '2026-11-30T10:00:00Z' }],
|
||||
kv: { expired: 0, total: 3 },
|
||||
media: { capped: false, checked: 30, orphaned: 0, total: 17 },
|
||||
retention: { 'consent-records': 1095 },
|
||||
versions: [{ slug: 'pages', docs: 15, kind: 'collection', max: 100, total: 300 }],
|
||||
})
|
||||
expect(await found(project(), deep)).toEqual([])
|
||||
})
|
||||
|
||||
test('size, unlimited versions, a purge that does not run, old submissions, expired KV, orphaned media', async () => {
|
||||
const deep = growth({
|
||||
collections: [
|
||||
{ slug: 'consent-records', bytes: 900 * 1024 * 1024, docs: 250_000, oldest: '2021-01-01T00:00:00Z' },
|
||||
{ slug: 'form-submissions', bytes: null, docs: 40, oldest: '2023-06-01T00:00:00Z' },
|
||||
],
|
||||
kv: { expired: 1500, total: 1600 },
|
||||
media: { capped: true, checked: 5000, orphaned: 30, total: 400 },
|
||||
retention: { 'consent-records': 1095 },
|
||||
versions: [{ slug: 'site-settings', docs: 1, kind: 'global', max: 0, total: 812 }, { slug: 'pages', docs: 900, kind: 'collection', max: 100, total: 60_000 }],
|
||||
})
|
||||
expect(await found(project(), deep)).toEqual([
|
||||
'growth-size warning: consent-records: 250000 documents, 900 MB with indexes, the oldest from 2021-01-01',
|
||||
'growth-versions warning: global site-settings keeps every version without a limit (812 now)',
|
||||
'growth-versions warning: collection pages: 60000 versions for 900 document(s)',
|
||||
'growth-retention warning: consent-records keeps records for 1095 days, but the oldest is 2160 days old',
|
||||
'growth-submissions warning: 40 form submissions kept without a retention, the oldest 1279 days old',
|
||||
'growth-kv warning: payload-kv holds 1600 entries, 1500 of them expired',
|
||||
'growth-media warning: 30 of 400 media files are not used by any document or global (from the first 5000 documents: may be fewer)',
|
||||
])
|
||||
})
|
||||
|
||||
test('thresholds from iapl-doctor.json; non-numbers keep the default; a retention silences the submissions rule', async () => {
|
||||
const deep = growth({ collections: [{ slug: 'form-submissions', bytes: null, docs: 40, oldest: '2023-06-01T00:00:00Z' }], media: { capped: false, checked: 9, orphaned: 3, total: 9 } })
|
||||
expect(await found(project(), deep, { growth: { orphanedMedia: 2, submissionDays: 'x' } })).toEqual([
|
||||
'growth-submissions warning: 40 form submissions kept without a retention, the oldest 1279 days old',
|
||||
'growth-media warning: 3 of 9 media files are not used by any document or global',
|
||||
])
|
||||
// with a retention the submissions rule is quiet — and the retention rule says the purge has not caught up yet
|
||||
expect(await found(project(), { ...deep, retention: { 'form-submissions': 365 } }, { growth: { submissionDays: 1000 } })).toEqual([
|
||||
'growth-retention warning: form-submissions keeps records for 365 days, but the oldest is 1279 days old',
|
||||
'growth-media info: 3 of 9 media files are not used by any document or global',
|
||||
])
|
||||
expect(GROWTH_DEFAULTS.maxDocs).toBe(200_000)
|
||||
})
|
||||
|
||||
test('growth-disk measures the image cache and the local upload folder on this machine', async () => {
|
||||
const root = project({ '.next/cache/images/a/b.webp': 'x'.repeat(3 * 1024 * 1024), 'media/a.jpg': 'y'.repeat(2048) })
|
||||
expect(folderBytes(path.join(root, '.next', 'cache', 'images'))).toBe(3 * 1024 * 1024)
|
||||
expect(await found(root, null, { growth: { imageCacheMB: 2, uploadsMB: 1 } })).toEqual([
|
||||
'growth-disk info: the image cache is 3 MB (no size cap in Next; each image × width × format)',
|
||||
])
|
||||
expect(folderBytes(path.join(root, 'missing'))).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('deep collector', () => {
|
||||
test('counts, oldest, versions, expired KV entries and media nobody points at — values never leave it', async () => {
|
||||
const kv = new Map<string, unknown>([
|
||||
['iapl:2fa-verify:users:1', { count: 0, resetAt: Date.now() + 60_000 }],
|
||||
['iapl:mail-relay:nonce:a', { expiresAt: Date.now() - 1000 }],
|
||||
['other', 'plain'],
|
||||
])
|
||||
const docs: Record<string, object[]> = {
|
||||
media: [{ id: 'm1' }, { id: 'm2' }, { id: 'm3' }],
|
||||
pages: [{ id: 'p1', layout: [{ blockType: 'hero', media: 'm1' }], richText: { root: { children: [{ type: 'upload', value: 'm2' }] } } }],
|
||||
}
|
||||
const payload = {
|
||||
config: {
|
||||
collections: [{ slug: 'pages', versions: { maxPerDoc: 0 } }, { slug: 'media', upload: true }],
|
||||
custom: {},
|
||||
globals: [{ slug: 'site-settings', versions: { max: 20 } }],
|
||||
},
|
||||
count: async ({ collection }: { collection: string }) => ({ totalDocs: docs[collection]?.length ?? 0 }),
|
||||
countGlobalVersions: async () => ({ totalDocs: 7 }),
|
||||
countVersions: async () => ({ totalDocs: 42 }),
|
||||
db: { name: 'drizzle' },
|
||||
find: async ({ collection, select }: { collection: string; select?: object }) => ({ docs: select && 'createdAt' in select ? [{ createdAt: '2026-01-01T00:00:00Z' }] : (docs[collection] ?? []) }),
|
||||
findGlobal: async () => ({ logo: 'm3' }),
|
||||
kv: { get: async (k: string) => kv.get(k) ?? null, keys: async () => [...kv.keys()] },
|
||||
}
|
||||
const g = await collectGrowth(payload as never)
|
||||
expect(g.collections).toEqual([
|
||||
{ slug: 'pages', bytes: null, docs: 1, oldest: '2026-01-01T00:00:00Z' },
|
||||
{ slug: 'media', bytes: null, docs: 3, oldest: '2026-01-01T00:00:00Z' },
|
||||
])
|
||||
expect(g.versions).toEqual([
|
||||
{ slug: 'pages', docs: 1, kind: 'collection', max: 0, total: 42 },
|
||||
{ slug: 'site-settings', docs: 1, kind: 'global', max: 20, total: 7 },
|
||||
])
|
||||
expect(g.kv).toEqual({ expired: 1, total: 3 })
|
||||
expect(g.media).toEqual({ capped: false, checked: 1, orphaned: 0, total: 3 })
|
||||
expect(JSON.stringify(g)).not.toContain('hero')
|
||||
})
|
||||
})
|
||||
|
||||
describe('mail service: expired nonces are swept', () => {
|
||||
test('only nonces past their expiry, at most once a day; the 2FA counters and live nonces stay', async () => {
|
||||
resetNonceSweep()
|
||||
const now = Date.now()
|
||||
const store = new Map<string, unknown>([
|
||||
['iapl:2fa-verify:users:1', { count: 3, resetAt: now - 1 }],
|
||||
['iapl:mail-relay:nonce:live', { expiresAt: now + 60_000 }],
|
||||
['iapl:mail-relay:nonce:old', { expiresAt: now - 1 }],
|
||||
])
|
||||
const kv = { delete: async (k: string) => void store.delete(k), get: async (k: string) => store.get(k) ?? null, keys: async () => [...store.keys()], set: async (k: string, v: unknown) => void store.set(k, v) }
|
||||
const payload = { config: {}, kv } as never
|
||||
expect(await sweepExpiredNonces(payload, now)).toBe(1)
|
||||
expect([...store.keys()].sort()).toEqual(['iapl:2fa-verify:users:1', 'iapl:mail-relay:nonce:live'])
|
||||
store.set('iapl:mail-relay:nonce:old2', { expiresAt: now - 1 })
|
||||
expect(await sweepExpiredNonces(payload, now + 1000)).toBe(0) // not again the same day
|
||||
expect(await sweepExpiredNonces(payload, now + 86_400_001)).toBe(2) // a day on: old2 and the one that was live
|
||||
})
|
||||
})
|
||||
|
||||
describe('retention', () => {
|
||||
test('recorded per collection in the config; invalid values ignored', () => {
|
||||
const config = withRetention(withRetention({ custom: { iapl: { mail: {} } } } as never, 'consent-records', 1095), 'form-submissions', 0)
|
||||
expect(retentionMap({ config } as never)).toEqual({ 'consent-records': 1095 })
|
||||
expect((config.custom as { iapl: { mail: object } }).iapl.mail).toEqual({}) // the rest kept
|
||||
expect(retentionOf({ config } as never, 'form-submissions')).toBeUndefined()
|
||||
})
|
||||
|
||||
test('forms.submissionRetentionDays: old submissions deleted after a new one (once a day); without it nothing is deleted', async () => {
|
||||
const { payload } = fakePayload({ forms: { f: { fields: [{ name: 'company', blockType: 'text' }] } } })
|
||||
const deleteMany = vi.fn(async () => {})
|
||||
Object.assign(payload, { config: {}, db: { deleteMany } })
|
||||
await submitForm({ data: { company: 'Acme' }, formId: 'f', maxPerMinute: 0, payload })
|
||||
expect(deleteMany).not.toHaveBeenCalled()
|
||||
Object.assign(payload, { config: withRetention({} as never, 'form-submissions', 365) })
|
||||
await submitForm({ data: { company: 'Acme' }, formId: 'f', maxPerMinute: 0, payload })
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
expect(deleteMany).toHaveBeenCalledWith(expect.objectContaining({ collection: 'form-submissions', where: { createdAt: { less_than: expect.any(String) } } }))
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user