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:
Radosław Smoliński
2026-12-01 14:48:35 +01:00
co-authored by Claude Opus 5.5
parent 6b16b9f933
commit 8991867e01
21 changed files with 729 additions and 7 deletions
+1 -1
View File
@@ -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
+171
View File
@@ -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) } } }))
})
})