Files
ipal-kit/src/modules/shared/switches.ts
T
Radosław SmolińskiandClaude Opus 5.5 ecf03c8dc0 IAWL ideas, group B: sizes before work, one link rule, no stand-in locale, strict switches
- Request bodies from strangers are read only up to a cap, declared length or not:
  mail-service confirm, CSP reports, page views, MCP (maxBytes, 413). readCappedBody moves
  to shared/ (the consent log keeps exporting it).
- searchContent / createSearchRoute / MCP search: queryLimit (default 200 characters,
  10 words) before the database; an unknown ?locale is the default locale throughout.
- Rich text: autolinks and links marked internal pass safeHref too; lexicalToMarkdown
  drops unsafe link targets.
- truncate() never returns more than its limit (summary / meta autofill after validation).
- resolveRoute answers null for a locale the site does not have (xx, all, *): no
  default-locale page under another code (page route past the proxy, /md/xx, MCP).
- A 404 page that is a draft is not shown (resolveNotFoundPage, getNotFoundPage).
- readPublished() access rule (exported); Site integrations readVersions: admin.
- Plugin switches, buildCsp, buildSecurityHeaders and the seed guard refuse nonsense
  values at start; an unknown role name is met by nobody, requireRole throws on one.
- Docs, AGENT.md, iapl-collection and iapl-audit skills.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:25:26 +01:00

118 lines
6.7 KiB
TypeScript

/**
* IAWL idea 21: a switch must never read a value nobody understands as "off" or "open".
*
* A JavaScript config is not type-checked, so `accounts: 0`, `stats: 'false'` or
* `consentLog: { retentionDays: null }` reach the plugin as they are. Where such a value would switch a
* protection off, widen who sees something, or switch an opt-in feature (a public endpoint) on, the plugin stops
* at start with a message that names the option — like `twoFactor.requireSetup.windowHours` since 1.16.6.
* Real values (`true`, `false`, an object, a number in range, a known name) are unchanged.
*
* Exported so a project (or another plugin) can check its own switches the same way.
*/
const where = (path: string) => `[iapl] ${path}`
/** Throws unless `value` is `undefined`, `true` or `false`. */
export function assertBooleanSwitch(path: string, value: unknown): void {
if (value === undefined || typeof value === 'boolean') {return}
throw new Error(`${where(path)} must be true or false (received ${JSON.stringify(value)}). A string such as "false" is not read as off.`)
}
/** Throws unless `value` is `undefined`, `true`, `false` or an object (the option's settings). */
export function assertSwitchOrObject(path: string, value: unknown, { allowTrue = true }: { allowTrue?: boolean } = {}): void {
if (value === undefined || value === false || (allowTrue && value === true)) {return}
if (value && typeof value === 'object' && !Array.isArray(value)) {return}
const allowed = allowTrue ? 'true, false or an object' : 'false or an object'
throw new Error(`${where(path)} must be ${allowed} (received ${JSON.stringify(value)}). A value like 0, "" or "false" is not read as off.`)
}
/** Throws unless `value` is `undefined` or a finite number that is at least `min` (above it when `exclusive`). */
export function assertNumberSwitch(path: string, value: unknown, { exclusive = false, min }: { exclusive?: boolean; min: number }): void {
if (value === undefined) {return}
if (typeof value === 'number' && Number.isFinite(value) && (exclusive ? value > min : value >= min)) {return}
throw new Error(`${where(path)} must be a number ${exclusive ? 'above' : 'of at least'} ${min} (received ${JSON.stringify(value)}).`)
}
/** Throws unless `value` is `undefined` or one of `allowed`. */
export function assertOneOf(path: string, value: unknown, allowed: readonly string[]): void {
if (value === undefined || (typeof value === 'string' && allowed.includes(value))) {return}
throw new Error(`${where(path)} must be one of ${allowed.map((a) => `"${a}"`).join(', ')} (received ${JSON.stringify(value)}).`)
}
type Bag = Record<string, unknown> | undefined
const bag = (value: unknown): Bag => (value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined)
/**
* The plugin options whose nonsense values used to read as off or open. Called by iapl() before anything is built.
* Each line names what a bad value did before 1.17.1.
*/
export function assertPluginSwitches(options: Record<string, unknown>): void {
// `accounts: 0` / `''` dropped every account rule (staff-only reads, admin-only writes, the panel role,
// the password rule, the closed first-user route).
assertSwitchOrObject('accounts', options.accounts, { allowTrue: false })
// Opt-in features that add public endpoints or outbound calls: `'false'` switched them ON.
for (const name of ['cookieScanner', 'stats', 'consentLog', 'adminMeta', 'whiteLabel'] as const) {
assertSwitchOrObject(name, options[name])
}
assertBooleanSwitch('indexNow', options.indexNow)
// an unknown name ('IAPL') used to mean 'ipal': the scanner declared one visitor cookie while the site set another
assertOneOf('storageNames', options.storageNames, ['ipal', 'iapl'])
assertBooleanSwitch('lightbox', options.lightbox)
assertBooleanSwitch('enabled', options.enabled)
const forms = bag(options.forms)
if (forms) {assertSwitchOrObject('forms.attachments', forms.attachments)}
// `maxPerMinute: 'off'` / `null` / `{}` turned the upload endpoint's limit off; only 0 is documented as off.
const submit = bag(bag(forms?.attachments)?.submit)
if (submit) {
assertNumberSwitch('forms.attachments.submit.maxPerMinute', submit.maxPerMinute, { min: 0 })
assertNumberSwitch('forms.attachments.submit.timeoutMs', submit.timeoutMs, { min: 0 })
assertNumberSwitch('forms.attachments.submit.idleTimeoutMs', submit.idleTimeoutMs, { min: 0 })
}
const scanner = bag(options.cookieScanner)
if (scanner) {assertSwitchOrObject('cookieScanner.crawl', scanner.crawl)}
// `'false'` accepted a 2FA target that is not the admin collection (panel users without 2FA).
const twoFactor = bag(options.twoFactor)
if (twoFactor) {assertBooleanSwitch('twoFactor.allowCollectionMismatch', twoFactor.allowCollectionMismatch)}
// `null` / `0` / a negative number purged every proof of consent once a day.
const consentLog = bag(options.consentLog)
if (consentLog) {assertNumberSwitch('consentLog.retentionDays', consentLog.retentionDays, { exclusive: true, min: 0 })}
// `robots.index: 'false'` / `0` / `null` took the noindex off the admin panel.
const adminMeta = bag(options.adminMeta)
const robots = bag(adminMeta?.robots)
if (robots) {
assertBooleanSwitch('adminMeta.robots.index', robots.index)
assertBooleanSwitch('adminMeta.robots.follow', robots.follow)
}
// An unknown role name ('Admin', 'admins') showed the failure details to every staff account.
const alerts = bag(options.dashboardAlerts)
if (alerts) {
assertOneOf('dashboardAlerts.integrations', alerts.integrations, ['admin', 'editor', 'all'])
assertOneOf('dashboardAlerts.cookies', alerts.cookies, ['editor', 'all'])
}
// A window of 0 minutes (or 0 ms) is a limit that never fills.
const mail = bag(options.mail)
if (mail) {assertSwitchOrObject('mail.relay', mail.relay)}
const relay = bag(mail?.relay)
if (relay) {
const accountMail = relay.accountMail
if (accountMail !== false && accountMail !== undefined) {
const limits = bag(accountMail)
if (!limits) {throw new Error(`${where('mail.relay.accountMail')} must be false or an object (received ${JSON.stringify(accountMail)}).`)}
assertNumberSwitch('mail.relay.accountMail.windowMinutes', limits.windowMinutes, { exclusive: true, min: 0 })
assertNumberSwitch('mail.relay.accountMail.perAddress', limits.perAddress, { min: 1 })
assertNumberSwitch('mail.relay.accountMail.perVisitor', limits.perVisitor, { min: 1 })
}
const confirm = bag(relay.confirmRateLimit)
if (confirm) {
assertNumberSwitch('mail.relay.confirmRateLimit.windowMs', confirm.windowMs, { exclusive: true, min: 0 })
assertNumberSwitch('mail.relay.confirmRateLimit.max', confirm.max, { min: 1 })
}
}
}