diff --git a/src/index.ts b/src/index.ts index ab62c8f..e03f19e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -297,6 +297,16 @@ export { buildTableOfContentsField, extractHeadings, headingText } from './modul export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './modules/richtext/headings.js' // Lexical → Markdown (pure, no React) — for AI-readable output. export { lexicalToMarkdown } from './modules/richtext/lexicalToMarkdown.js' +export { + INTEGRATION_SECRET_FIELDS, + isSecretMask, + keepSecretBeforeValidate, + maskSecretAfterRead, + SECRET_CLEAR, + SECRET_MASK, + writeOnlySecret, + writeOnlySecrets, +} from './modules/secrets/writeOnly.js' export { buildAdminCsp, buildAdminCspHeaders, @@ -316,6 +326,7 @@ export { UPLOAD_SECURITY_HEADERS, withSecurityConfig, } from './modules/security/index.js' + export type { BuildAdminCspArgs, BuildCspArgs, @@ -327,21 +338,10 @@ export type { TotpUser, WithSecurityConfigOptions, } from './modules/security/index.js' - export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js' export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js' export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js' export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js' -export { - INTEGRATION_SECRET_FIELDS, - isSecretMask, - keepSecretBeforeValidate, - maskSecretAfterRead, - SECRET_CLEAR, - SECRET_MASK, - writeOnlySecret, - writeOnlySecrets, -} from './modules/secrets/writeOnly.js' export { requireSecondFactor, secondFactorPassed, twoFactorSetupDeadline, twoFactorSetupState } from './modules/security/totp/secondFactor.js' export type { TwoFactorSetupState } from './modules/security/totp/secondFactor.js' export { SETUP_FROM_FIELD } from './modules/security/totp/secondFactor.js' @@ -425,7 +425,7 @@ export type { Theme, ThemeConfig, ThemeSetting } from './modules/theme/index.js' // which imports 'server-only'. export { defineTokens, IPAL_BREAKPOINTS, IPAL_TOKENS, ipalVar } from './modules/tokens/index.js' export type { IpalTokenName, TokensInput } from './modules/tokens/index.js' -export { getTurnstileConfig } from './modules/turnstile/config.js' +export { getTurnstileConfig, TURNSTILE_SECRET_ENV, turnstileSecretFromEnv } from './modules/turnstile/config.js' export type { TurnstileConfig } from './modules/turnstile/config.js' export { ipalKit } from './plugin.js' export type { IpalOptions, ThemeOptions } from './types.js' diff --git a/src/modules/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts index 5347d50..c359178 100644 --- a/src/modules/doctor/rules/security.ts +++ b/src/modules/doctor/rules/security.ts @@ -141,6 +141,51 @@ export const securityRules: DoctorRule[] = [ group: 'security', source: 'static', }, + { + // Without `access` the plugin adds no roles: every account that can log in to the panel is an admin. + id: 'access-missing', + check: (ctx) => { + const code = cfg(ctx) + if (!/ipalKit\s*\(/.test(code)) {return []} + // `access: { authCollection | defaultRole | … }`, an empty `access: {}`, or a variable whose name says so + const set = /\baccess\s*:\s*\{\}/.test(code.replace(/\s+/g, '')) || /\baccess\s*:\s*\{[^{}]*\b(?:authCollection|defaultRole|authAccess|firstUserAdmin|staffCollections|panelRole|selfRegistration|password)\b/.test(code) || /\baccess\s*:\s*\w*[aA]ccess\w*\s*[,}]/.test(code) + return set + ? [] + : [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "ipalKit({ access: { authCollection: 'users' } }) — roles admin > editor > user; or record the reason in ipal-doctor.json", message: 'ipalKit has no `access` option: there are no roles, so every account that can log in to the panel is an admin', severity: 'warning' }] + }, + docs: 'docs/access.md', + group: 'security', + source: 'static', + }, + { + // Turnstile lets submissions through while it is misconfigured or Cloudflare fails ("degraded") — visible here. + id: 'turnstile-degraded', + check: (ctx) => { + const status = ctx.deep?.turnstile + if (!status || status.state !== 'degraded') {return []} + const hours = status.since ? Math.floor((Date.parse(`${ctx.today}T23:59:59Z`) - Date.parse(status.since)) / 3_600_000) : null + const long = hours !== null && hours >= 24 + return [{ + fix: 'Site integrations → Spam protection: both keys from the same Cloudflare widget; then send a test form', + message: `Turnstile is not checking forms (${status.code ?? 'unknown'})${status.since ? `, since ${status.since.slice(0, 16).replace('T', ' ')}` : ''}: text forms are accepted without the check and forms with files are refused (unless forms.turnstileOnConfigError says otherwise)`, + severity: long ? 'error' : 'warning', + }] + }, + docs: 'docs/turnstile.md', + group: 'security', + source: 'deep', + }, + { + // The secret key from the environment is deprecated: the panel is its source. + id: 'turnstile-env-key', + check: (ctx) => + ctx.deep?.turnstileSecretFromEnv + ? [{ fix: 'copy the key into Site integrations → Spam protection → Secret key, check a form, then remove TURNSTILE_SECRET_KEY from the environment (Coolify)', message: 'the Turnstile secret key comes from the TURNSTILE_SECRET_KEY environment variable (deprecated; it will be removed in a later release)', severity: 'warning' }] + : [], + docs: 'docs/turnstile.md', + group: 'security', + source: 'deep', + }, { id: 'cookie-scanner', check: (ctx) => { diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index 955419b..a25c62c 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -10,6 +10,7 @@ import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js' import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js' import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' +import { turnstileSecretFromEnv } from '../turnstile/config.js' /** The plugin's own version (package.json next to dist/ and src/). */ export function pluginVersion(): string { @@ -44,7 +45,23 @@ export async function collectDoctorStatus(payload: BasePayload): Promise c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null - return { node: process.version, pendingCookies, plugin: pluginVersion(), usersSetupClosed, usersWithout2fa } + // Turnstile: the recorded state and where the secret comes from — never the keys themselves. + let turnstile: DoctorStatus['turnstile'] = null + let secretFromEnv: boolean | null = null + if ((payload.config.globals ?? []).some((g) => g.slug === 'site-integrations')) { + try { + const integrations = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0, overrideAccess: true })) as unknown as { + turnstileSecretKey?: null | string + turnstileStatus?: { code?: null | string; since?: null | string; state?: null | string } | null + } + const status = integrations.turnstileStatus + turnstile = status?.state ? { code: status.code ?? null, since: status.since ?? null, state: status.state } : null + secretFromEnv = turnstileSecretFromEnv(integrations) + } catch { + /* the global cannot be read: unknown */ + } + } + return { node: process.version, pendingCookies, plugin: pluginVersion(), turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa } } export type DoctorEndpointOptions = { diff --git a/src/modules/doctor/types.ts b/src/modules/doctor/types.ts index 0f676e2..639aefe 100644 --- a/src/modules/doctor/types.ts +++ b/src/modules/doctor/types.ts @@ -63,6 +63,10 @@ export type DoctorStatus = { node?: string pendingCookies?: null | number plugin?: string + /** The Turnstile integration's recorded state (Site integrations): never a key, only the state. null = not known. */ + turnstile?: { code?: null | string; since?: null | string; state?: null | string } | null + /** The Turnstile secret key in use comes from the environment (the panel field is empty). Deprecated. */ + turnstileSecretFromEnv?: boolean | null /** Of `usersWithout2fa`: accounts whose setup window has passed (blocked until an admin reopens setup). */ usersSetupClosed?: null | number usersWithout2fa?: null | number diff --git a/src/modules/turnstile/config.ts b/src/modules/turnstile/config.ts index 136b540..3ec5d27 100644 --- a/src/modules/turnstile/config.ts +++ b/src/modules/turnstile/config.ts @@ -19,6 +19,27 @@ export type TurnstileConfig = { } let warnedPartial = false +let warnedEnvSecret = false + +/** + * True when the secret key in use comes from the environment (`TURNSTILE_SECRET_KEY`) because + * the panel field is empty. **Deprecated:** the panel is the source of the secret; the + * environment value keeps working for now and will be removed in a later, announced release. + */ +export function turnstileSecretFromEnv(integrations: IntegrationsWithTurnstileKeys): boolean { + return !integrations.turnstileSecretKey?.trim() && Boolean(process.env[TURNSTILE_SECRET_ENV]?.trim()) +} + +/** Says once per process that the secret came from the environment (see turnstileSecretFromEnv). */ +export function warnTurnstileEnvSecret(integrations: IntegrationsWithTurnstileKeys): void { + if (warnedEnvSecret || !turnstileSecretFromEnv(integrations)) {return} + warnedEnvSecret = true + console.warn( + `[ipal] Deprecated: the Turnstile secret key comes from the ${TURNSTILE_SECRET_ENV} environment variable. ` + + 'Put it into Site integrations → Spam protection → Secret key (the panel is the source of this secret). ' + + 'The environment value keeps working for now and will be removed in a later release, named in the changelog.', + ) +} function resolveKeys(integrations: IntegrationsWithTurnstileKeys) { return { @@ -69,7 +90,10 @@ export async function getTurnstileConfig(payload: BasePayload): Promise(payload) const { secret, siteKey } = resolveKeys(integrations) - if (siteKey && secret) {return { enabled: true, siteKey }} + if (siteKey && secret) { + warnTurnstileEnvSecret(integrations) + return { enabled: true, siteKey } + } if ((siteKey || secret) && !warnedPartial) { warnedPartial = true diff --git a/src/modules/turnstile/verify.ts b/src/modules/turnstile/verify.ts index 7418818..28ec399 100644 --- a/src/modules/turnstile/verify.ts +++ b/src/modules/turnstile/verify.ts @@ -83,7 +83,7 @@ const LOG_DETAIL: Record = { /** * Verifies a Turnstile token with Cloudflare and classifies the result (server-only). * - * Secret: SiteIntegrations → Turnstile (panel) first, then TURNSTILE_SECRET_KEY. + * Secret: SiteIntegrations → Turnstile (panel) first, then TURNSTILE_SECRET_KEY (deprecated: turnstile/config.ts). * Every result is logged when not `pass`, and the integration status on * SiteIntegrations is updated (throttled) so the panel shows failures. */ diff --git a/test/doctor.test.ts b/test/doctor.test.ts index b014d07..d4afd43 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -150,6 +150,54 @@ describe('2FA setup required: what a project must have', () => { }) }) +describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () => { + const run = async (config: string, only: string[], deepStatus?: object) => + rules(await doctor(project({ ...base(), 'src/payload.config.ts': config }), only, deepStatus ? { deepStatus } : {})) + + test('access-missing: ipalKit without `access` means every account is an admin', async () => { + expect(await run("plugins: [ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: payloadTotp } })]", ['access-missing'])).toEqual(['access-missing:warning']) + // a collection's own access rules are not the plugin option + expect(await run("collections: [{ slug: 'pages', access: { read: () => true } }], plugins: [ipalKit({ i18n })]", ['access-missing'])).toEqual(['access-missing:warning']) + for (const ok of ["ipalKit({ access: { authCollection: 'users' }, i18n })", "ipalKit({ i18n, access: { defaultRole: 'editor' } })", 'ipalKit({ access: {}, i18n })', 'ipalKit({ access: accessOptions, i18n })', '// no plugin here']) { + expect([ok, await run(`plugins: [${ok}]`, ['access-missing'])]).toEqual([ok, []]) + } + }) + + test('turnstile-degraded: a warning, an error after a day', async () => { + const at = (hoursAgo: number) => new Date(Date.parse(`${TODAY}T12:00:00Z`) - hoursAgo * 3_600_000).toISOString() + const cfg = "ipalKit({ access: { authCollection: 'users' } })" + expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(2), state: 'degraded' } })).toEqual(['turnstile-degraded:warning']) + expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(48), state: 'degraded' } })).toEqual(['turnstile-degraded:error']) + expect(await run(cfg, ['turnstile-degraded'], { turnstile: { state: 'degraded' } })).toEqual(['turnstile-degraded:warning']) + expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(48), state: 'ok' } })).toEqual([]) + expect(await run(cfg, ['turnstile-degraded'], { turnstile: null })).toEqual([]) + expect(await run(cfg, ['turnstile-degraded'])).toEqual([]) // no deep status: nothing to say + }) + + test('turnstile-env-key: the secret still comes from the environment', async () => { + const cfg = "ipalKit({ access: { authCollection: 'users' } })" + expect(await run(cfg, ['turnstile-env-key'], { turnstileSecretFromEnv: true })).toEqual(['turnstile-env-key:warning']) + expect(await run(cfg, ['turnstile-env-key'], { turnstileSecretFromEnv: false })).toEqual([]) + expect(await run(cfg, ['turnstile-env-key'])).toEqual([]) + }) + + test('the deep status reports the state and where the secret comes from, never a key', async () => { + vi.stubEnv('TURNSTILE_SECRET_KEY', 'env-secret-value') + const fake = (integrations: object) => ({ + config: { admin: { user: 'users' }, collections: [{ slug: 'users', fields: [] }], globals: [{ slug: 'site-integrations' }] }, + findGlobal: async () => integrations, + }) + const degraded = await collectDoctorStatus(fake({ turnstileSecretKey: 'panel-secret-value', turnstileStatus: { code: 'invalid-input-secret', message: 'x', since: '2026-10-28T10:00:00.000Z', state: 'degraded' } }) as never) + expect(degraded.turnstile).toEqual({ code: 'invalid-input-secret', since: '2026-10-28T10:00:00.000Z', state: 'degraded' }) + expect(degraded.turnstileSecretFromEnv).toBe(false) + expect(JSON.stringify(degraded)).not.toMatch(/secret-value/) + const fromEnv = await collectDoctorStatus(fake({ turnstileSiteKey: 'site' }) as never) + expect(fromEnv.turnstile).toBeNull() + expect(fromEnv.turnstileSecretFromEnv).toBe(true) + expect(JSON.stringify(fromEnv)).not.toMatch(/secret-value/) + }) +}) + describe('helpers', () => { test('parseEnvFile reads KEY=value, strips quotes, skips comments', () => { expect(parseEnvFile('# c\nA=1\nexport B="two"\n C = \'3\'\nbad line')).toEqual({ A: '1', B: 'two', C: '3' }) @@ -433,7 +481,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(['node', 'pendingCookies', 'plugin', 'usersSetupClosed', 'usersWithout2fa']) + expect(Object.keys(status).sort()).toEqual(['node', 'pendingCookies', 'plugin', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa']) expect(status.usersSetupClosed).toBeNull() // no setup window in this config }) test('collectDoctorStatus counts the accounts whose 2FA setup window has passed', async () => { diff --git a/test/m1TurnstileEnv.test.ts b/test/m1TurnstileEnv.test.ts new file mode 100644 index 0000000..335f22d --- /dev/null +++ b/test/m1TurnstileEnv.test.ts @@ -0,0 +1,60 @@ +/** + * M1: the Turnstile secret key from the environment is deprecated — it still works, and says so once. + * Cloudflare is the mocked `fetch`. + */ +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { passTurnstile } from '../src/modules/forms/submitForm.js' +import { getTurnstileConfig, turnstileSecretFromEnv } from '../src/modules/turnstile/config.js' + +vi.mock('server-only', () => ({})) + +type Option = 'allow' | 'reject' | { files?: 'allow' | 'reject'; text?: 'allow' | 'reject' } | undefined +const payloadWith = (integrations: Record, option?: Option) => ({ + config: { custom: { ipal: { forms: option ? { turnstileOnConfigError: option } : {} } }, globals: [{ slug: 'site-integrations' }] }, + findGlobal: async () => integrations, + logger: { error: () => undefined, info: () => undefined, warn: () => undefined }, + updateGlobal: async () => ({}), +}) +const KEYS = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' } +const cloudflare = (body: unknown, status = 200) => vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(body), { status }))) + +afterEach(() => { + vi.unstubAllGlobals() + vi.unstubAllEnvs() + vi.restoreAllMocks() +}) + +describe('the Turnstile secret from the environment (deprecated)', () => { + test('turnstileSecretFromEnv: only when the panel field is empty and the variable is set', () => { + vi.stubEnv('TURNSTILE_SECRET_KEY', 'from-env') + expect(turnstileSecretFromEnv({})).toBe(true) + expect(turnstileSecretFromEnv({ turnstileSecretKey: ' ' })).toBe(true) + expect(turnstileSecretFromEnv({ turnstileSecretKey: 'from-panel' })).toBe(false) + vi.stubEnv('TURNSTILE_SECRET_KEY', '') + expect(turnstileSecretFromEnv({})).toBe(false) + }) + + test('it still works, and says once that it is deprecated', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.stubEnv('TURNSTILE_SECRET_KEY', 'from-env') + const payload = payloadWith({ turnstileSiteKey: 'site' }) + expect(await getTurnstileConfig(payload as never)).toEqual({ enabled: true, siteKey: 'site' }) + expect(await getTurnstileConfig(payload as never)).toEqual({ enabled: true, siteKey: 'site' }) + const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('Deprecated')) + expect(lines).toHaveLength(1) + expect(lines[0]).toMatch(/TURNSTILE_SECRET_KEY.*Site integrations.*keeps working for now/) + // the check itself runs with the env secret + cloudflare({ success: true }) + expect(await passTurnstile({ payload: payload as never, turnstileToken: 'token' })).toBeNull() + const sent = String((vi.mocked(fetch).mock.calls[0] as unknown as [string, { body: URLSearchParams }])[1].body) + expect(sent).toContain('secret=from-env') + }) + + test('with the key in the panel there is nothing to say', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.stubEnv('TURNSTILE_SECRET_KEY', 'from-env') + await getTurnstileConfig(payloadWith(KEYS) as never) + expect(warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('Deprecated'))).toEqual([]) + }) +})