ipalEnvRules: PAYLOAD_SECRET at least 32 characters in production

New option secretMinLength (default 32, 0 turns it off); checked only with
NODE_ENV=production. Docs: env table, deployment (what changing the secret
does, checked in Payload 3.94.1 and payload-2fa), AGENT.md, ipal-reference,
ipal-setup. Tests: short secret fails in production, passes in dev, 0 and a
custom minimum.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 00:01:18 +01:00
co-authored by Claude Opus 5.5
parent 40fed78da2
commit 36f8f69f82
13 changed files with 68 additions and 12 deletions
+4
View File
@@ -49,6 +49,10 @@ Write new rules, AGENTS.md entries and plugin-gap reports in English.
`postgres://…@db:5432/intecioncom_prod`. You derive the names from the domain and confirm them with the owner (ipal-setup
stage 0). `ipalEnvRules({ databaseName: true })` warns when they do not match (deployment.md §4.2a).
**`PAYLOAD_SECRET`:** at least 32 random characters, different per environment (`ipal-kit create` writes 64). In
production `ipalEnvRules` refuses a shorter one (`secretMinLength`, default 32, `0` = off). Never change it on a live
site without the owner's OK: every login session and every stored API key depends on it (deployment.md §1).
**Seeding on production** (details: `node_modules/@intecion/ipal-kit/docs/seeding.md`). Write seeds with
`createSeeder` from `@intecion/ipal-kit/seed` (the templates do) — it enforces every rule below:
- Call `guardSeedExit()` first in every seed script (before `getPayload`): a run that ends early exits 1 with the reason
+1 -1
View File
@@ -231,7 +231,7 @@ and what throws without `i18n`: frontend.md. `SiteProviders` props: `shell`, `ba
| variable | required when | effect when missing | where to set |
|---|---|---|---|
| `DATABASE_URI` | always (Payload; `ipalEnvRules` always) | no database, startup fails | env (name: `databaseVar`); the database is named `<domain without dots>_prod` / `_dev` (`intecioncom_prod`), checked by `databaseName: true` |
| `PAYLOAD_SECRET` | always | Payload does not start; `assertEnv` throws | env, ≥32 characters, different in prod (`secretVar`) |
| `PAYLOAD_SECRET` | always; ≥ 32 characters in production (`ipalEnvRules({ secretMinLength })`, default 32, `0` = off) | Payload does not start; `assertEnv` throws (also for a too-short secret in production) | env, different in prod (`secretVar`) |
| `NEXT_PUBLIC_SERVER_URL` | always (`kind: 'url'`) | sitemap/robots/canonical/JSON-LD/llms with origin `''` (relative), IndexNow does not send, R2 relative URL without a prefix | env (`serverUrlVar`) |
| `NODE_ENV` | no (`development`/`production`/`test`) | `production` is stricter: R2 and `IPAL_IP_HEADER` required, IndexNow works, IP warning, `buildImagesConfig` prod | set by Next / hosting |
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` | `storage: true` + production, or when at least one is set (all or none) | local disk (in prod files disappear on redeploy); incomplete set → warning | env |
@@ -288,7 +288,7 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection,
| Export | Import from | What it does / when |
|---|---|---|
| `assertEnv(rules, { env?, label? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | validates `process.env` against the rules at startup; collects every missing item and throws one error |
| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, databaseVar?, databaseName? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv`; `R2_PUBLIC_URL` optional unless `storage: { requirePublicUrl: true }`; `databaseName: true \| { domain?, warn? }` only warns when the `DATABASE_URI` database is not `<domain without dots>_prod` / `_dev` |
| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, secretMinLength?, databaseVar?, databaseName? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv`; `R2_PUBLIC_URL` optional unless `storage: { requirePublicUrl: true }`; `secretMinLength` (default 32, `0` = off) is the minimum `PAYLOAD_SECRET` length in production; `databaseName: true \| { domain?, warn? }` only warns when the `DATABASE_URI` database is not `<domain without dots>_prod` / `_dev` |
| `databaseNamesFor(domainOrUrl)` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | the two database names for a site: `intecion.com` → `{ prod: 'intecioncom_prod', dev: 'intecioncom_dev' }` (`www.` dropped, dots removed) |
| `databaseNameFromUri(uri)` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | the database name (URI path) of a Mongo / Postgres `DATABASE_URI`; null for SQLite files or no name |
| `checkDatabaseName({ databaseUri, domain })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | warning text when the name breaks the rule, else null (skips localhost / no domain) — what `databaseName` uses |
+1 -1
View File
@@ -199,7 +199,7 @@ export default buildConfig({
`R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_PUBLIC_URL` (empty = media through the app — the default), `IPAL_IP_HEADER` (`cf-connecting-ip`
behind Cloudflare, `x-forwarded-for` behind a plain proxy), `IPAL_NOINDEX` (empty; `1` on staging only), `INDEXNOW_KEY`,
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` (panel fallback), with Graph `GRAPH_TENANT_ID`,
`GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER`. Local `.env` with `PAYLOAD_SECRET` ≥ 32 characters.
`GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER`. Local `.env` with `PAYLOAD_SECRET` ≥ 32 characters (in production `ipalEnvRules` refuses a shorter one; `secretMinLength` changes it).
One language: one entry in `locales`, no `[locale]` folder (i18n.md).
**Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without
+14 -1
View File
@@ -24,12 +24,25 @@ DATABASE_URI=mongodb://user:pass@mongo:27017/intecioncom_prod?authSource=admin
# dev: …/intecioncom_dev, or file:./dev.db
# Payload secret (signs sessions/tokens) — random, long
PAYLOAD_SECRET=<random-string-min-32-chars>
PAYLOAD_SECRET=<random-string-min-32-chars> # ipalEnvRules: ≥ 32 characters in production (secretMinLength)
# Public site URL (canonical, hreflang, OG, manifest)
NEXT_PUBLIC_SERVER_URL=https://klient.pl # dev: http://localhost:3000
```
**`PAYLOAD_SECRET` — length and changing it.** `ipalEnvRules` refuses a secret shorter than 32 characters in
production (`secretMinLength`; `0` turns the check off, outside production nothing is checked). Payload (3.94)
derives its signing key from it (`sha256(secret)`, first 32 hex characters). Changing it on a live site therefore:
- **logs everyone out** — every login token (the `payload-token` cookie, JWTs from login / refresh / password reset)
is signed with it and stops being valid;
- **asks every user for the 2FA code again** — `@clocklimited/payload-2fa` signs its own 2FA cookie with it; the TOTP
keys themselves are stored as they are, so the authenticator apps keep working;
- **breaks stored API keys** (only in collections with `useAPIKey`) — Payload stores them encrypted with the secret
and finds them by an HMAC of it: they no longer authenticate and cannot be revealed — generate new ones;
- fails uploads that are in progress (client upload receipts are signed with it).
ipal-kit itself derives nothing from it. Change it only with the owner's OK, at a quiet time, and tell the editors
they will have to log in again.
### Email — Graph (OPTIONAL, agency-level, when transport = Graph)
```bash
+1 -1
View File
@@ -460,7 +460,7 @@ pnpm dev
| Variable | Required | Description |
|---|---|---|
| `DATABASE_URI` | ✅ | Postgres / Mongo (dev can use SQLite) |
| `PAYLOAD_SECRET` | ✅ | random, ≥32 characters, different in production |
| `PAYLOAD_SECRET` | ✅ | random, ≥32 characters, different in production — `ipalEnvRules` checks the length in production (`secretMinLength`, default 32, `0` = off) |
| `NEXT_PUBLIC_SERVER_URL` | ✅ | public URL (canonical, hreflang, OG); without it links are relative |
| `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | ⬜ | email through Microsoft Graph |
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` | ✅ prod | media in Cloudflare R2 — always in production (missing → container disk, files vanish on redeploy without a volume); in dev they can be empty (storage.md) |
+2 -1
View File
@@ -66,13 +66,14 @@ ipalEnvRules({
turnstile?: boolean | { siteKeyVar?: string; secretVar?: string }, // NEXT_PUBLIC_TURNSTILE_SITE_KEY, TURNSTILE_SECRET_KEY
serverUrlVar?: string, // default 'NEXT_PUBLIC_SERVER_URL'
secretVar?: string, // default 'PAYLOAD_SECRET'
secretMinLength?: number, // default 32 — minimum PAYLOAD_SECRET length, checked in production only; 0 = off
databaseVar?: string, // default 'DATABASE_URI'
databaseName?: boolean | { domain?: string; warn?: (message: string) => void },
// WARN (never fail) when the DATABASE_URI database is not <domain without dots>_prod / _dev
})
```
Always (core): `DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` (URL),
Always (core): `DATABASE_URI`, `PAYLOAD_SECRET` (in production at least `secretMinLength` = 32 characters), `NEXT_PUBLIC_SERVER_URL` (URL),
`NODE_ENV` (optional, oneOf `development`/`production`/`test`). The names `R2_*` / `GRAPH_*` /
`NEXT_PUBLIC_SERVER_URL` / `IPAL_IP_HEADER` / Turnstile match what the plugin modules
read; DB/secret are Payload variables — their names can be overridden.
@@ -231,7 +231,7 @@ and what throws without `i18n`: frontend.md. `SiteProviders` props: `shell`, `ba
| variable | required when | effect when missing | where to set |
|---|---|---|---|
| `DATABASE_URI` | always (Payload; `ipalEnvRules` always) | no database, startup fails | env (name: `databaseVar`); the database is named `<domain without dots>_prod` / `_dev` (`intecioncom_prod`), checked by `databaseName: true` |
| `PAYLOAD_SECRET` | always | Payload does not start; `assertEnv` throws | env, ≥32 characters, different in prod (`secretVar`) |
| `PAYLOAD_SECRET` | always; ≥ 32 characters in production (`ipalEnvRules({ secretMinLength })`, default 32, `0` = off) | Payload does not start; `assertEnv` throws (also for a too-short secret in production) | env, different in prod (`secretVar`) |
| `NEXT_PUBLIC_SERVER_URL` | always (`kind: 'url'`) | sitemap/robots/canonical/JSON-LD/llms with origin `''` (relative), IndexNow does not send, R2 relative URL without a prefix | env (`serverUrlVar`) |
| `NODE_ENV` | no (`development`/`production`/`test`) | `production` is stricter: R2 and `IPAL_IP_HEADER` required, IndexNow works, IP warning, `buildImagesConfig` prod | set by Next / hosting |
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` | `storage: true` + production, or when at least one is set (all or none) | local disk (in prod files disappear on redeploy); incomplete set → warning | env |
@@ -288,7 +288,7 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection,
| Export | Import from | What it does / when |
|---|---|---|
| `assertEnv(rules, { env?, label? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | validates `process.env` against the rules at startup; collects every missing item and throws one error |
| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, databaseVar?, databaseName? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv`; `R2_PUBLIC_URL` optional unless `storage: { requirePublicUrl: true }`; `databaseName: true \| { domain?, warn? }` only warns when the `DATABASE_URI` database is not `<domain without dots>_prod` / `_dev` |
| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, secretMinLength?, databaseVar?, databaseName? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv`; `R2_PUBLIC_URL` optional unless `storage: { requirePublicUrl: true }`; `secretMinLength` (default 32, `0` = off) is the minimum `PAYLOAD_SECRET` length in production; `databaseName: true \| { domain?, warn? }` only warns when the `DATABASE_URI` database is not `<domain without dots>_prod` / `_dev` |
| `databaseNamesFor(domainOrUrl)` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | the two database names for a site: `intecion.com` → `{ prod: 'intecioncom_prod', dev: 'intecioncom_dev' }` (`www.` dropped, dots removed) |
| `databaseNameFromUri(uri)` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | the database name (URI path) of a Mongo / Postgres `DATABASE_URI`; null for SQLite files or no name |
| `checkDatabaseName({ databaseUri, domain })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | warning text when the name breaks the rule, else null (skips localhost / no domain) — what `databaseName` uses |
+1 -1
View File
@@ -199,7 +199,7 @@ export default buildConfig({
`R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_PUBLIC_URL` (empty = media through the app — the default), `IPAL_IP_HEADER` (`cf-connecting-ip`
behind Cloudflare, `x-forwarded-for` behind a plain proxy), `IPAL_NOINDEX` (empty; `1` on staging only), `INDEXNOW_KEY`,
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` (panel fallback), with Graph `GRAPH_TENANT_ID`,
`GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER`. Local `.env` with `PAYLOAD_SECRET` ≥ 32 characters.
`GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER`. Local `.env` with `PAYLOAD_SECRET` ≥ 32 characters (in production `ipalEnvRules` refuses a shorter one; `secretMinLength` changes it).
One language: one entry in `locales`, no `[locale]` folder (i18n.md).
**Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without
+15 -1
View File
@@ -26,6 +26,11 @@ export type IpalEnvFeatures = {
* the client IP (see clientIp). Outside production it stays optional.
*/
ipHeader?: boolean
/**
* Minimum length of PAYLOAD_SECRET, checked in production only (NODE_ENV=production). Payload signs
* login tokens and encrypts API keys with it, so a short secret is weak. Default 32; 0 turns it off.
*/
secretMinLength?: number
/** Override the Payload secret var. Default 'PAYLOAD_SECRET'. */
secretVar?: string
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
@@ -75,6 +80,7 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
databaseVar = 'DATABASE_URI',
emailGraph = false,
ipHeader = false,
secretMinLength = 32,
secretVar = 'PAYLOAD_SECRET',
serverUrlVar = 'NEXT_PUBLIC_SERVER_URL',
storage = false,
@@ -83,7 +89,15 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
const rules: EnvRule[] = [
{ name: databaseVar, description: 'Database connection string (e.g. MongoDB URI)' },
{ name: secretVar, description: 'Payload secret used to sign tokens' },
{
name: secretVar,
description: 'Payload secret used to sign tokens',
...(secretMinLength > 0 && process.env.NODE_ENV === 'production' && {
validate: (value: string) =>
value.length >= secretMinLength ||
`${secretVar} must be at least ${secretMinLength} characters in production (got ${value.length}) — use a long random value, or ipalEnvRules({ secretMinLength }) to change the minimum (0 turns the check off)`,
}),
},
{ name: serverUrlVar, description: 'Public site origin, e.g. https://example.com', kind: 'url' },
{
name: 'NODE_ENV',
+25 -1
View File
@@ -4,7 +4,7 @@ import { assertEnv } from '../src/modules/env/assertEnv.js'
import { checkDatabaseName, databaseNameFromUri, databaseNamesFor } from '../src/modules/env/databaseName.js'
import { ipalEnvRules } from '../src/modules/env/ipalEnvRules.js'
const base = { DATABASE_URI: 'mongodb://db/x', NEXT_PUBLIC_SERVER_URL: 'http://localhost:3000', PAYLOAD_SECRET: 's' }
const base = { DATABASE_URI: 'mongodb://db/x', NEXT_PUBLIC_SERVER_URL: 'http://localhost:3000', PAYLOAD_SECRET: 'a-long-random-test-secret-of-32-chars' }
const r2 = {
R2_ACCESS_KEY_ID: 'k',
R2_BUCKET: 'b',
@@ -90,3 +90,27 @@ describe('database naming rule', () => {
vi.unstubAllEnvs()
})
})
describe('PAYLOAD_SECRET minimum length', () => {
const env = { DATABASE_URI: 'mongodb://db/x', NEXT_PUBLIC_SERVER_URL: 'https://acme.pl', PAYLOAD_SECRET: 'short-secret' }
afterEach(() => vi.unstubAllEnvs())
test('a short secret fails in production', () => {
vi.stubEnv('NODE_ENV', 'production')
expect(() => assertEnv(ipalEnvRules(), { env })).toThrow(/PAYLOAD_SECRET must be at least 32 characters in production \(got 12\)/)
expect(() => assertEnv(ipalEnvRules(), { env: { ...env, PAYLOAD_SECRET: 'x'.repeat(32) } })).not.toThrow()
})
test('a short secret passes outside production', () => {
vi.stubEnv('NODE_ENV', 'development')
expect(() => assertEnv(ipalEnvRules(), { env })).not.toThrow()
})
test('secretMinLength: 0 turns the check off; a custom minimum is used', () => {
vi.stubEnv('NODE_ENV', 'production')
expect(() => assertEnv(ipalEnvRules({ secretMinLength: 0 }), { env })).not.toThrow()
expect(() => assertEnv(ipalEnvRules({ secretMinLength: 64 }), { env: { ...env, PAYLOAD_SECRET: 'x'.repeat(40) } })).toThrow(/at least 64 characters/)
expect(() => assertEnv(ipalEnvRules({ secretMinLength: 8 }), { env })).not.toThrow()
expect(() => assertEnv(ipalEnvRules({ secretVar: 'MY_SECRET' }), { env: { ...env, MY_SECRET: 'short' } })).toThrow(/MY_SECRET must be at least 32/)
})
})
+1 -1
View File
@@ -116,7 +116,7 @@ describe('IPAL_IP_HEADER', () => {
test('ipalEnvRules({ ipHeader }) requires it in production only', async () => {
const { assertEnv } = await import('../src/modules/env/assertEnv.js')
const { ipalEnvRules } = await import('../src/modules/env/ipalEnvRules.js')
const base = { DATABASE_URI: 'x', NEXT_PUBLIC_SERVER_URL: 'https://acme.pl', PAYLOAD_SECRET: 'x' }
const base = { DATABASE_URI: 'x', NEXT_PUBLIC_SERVER_URL: 'https://acme.pl', PAYLOAD_SECRET: 'a-long-random-test-secret-of-32-chars' }
vi.stubEnv('NODE_ENV', 'production')
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: base })).toThrow(/IPAL_IP_HEADER/)
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: { ...base, IPAL_IP_HEADER: 'cf-connecting-ip' } })).not.toThrow()