import type { EnvRule } from './assertEnv.js' type TurnstileNames = { secretVar?: string; siteKeyVar?: string } import { checkDatabaseName } from './databaseName.js' export type IpalEnvFeatures = { /** * Cookie crawl (cookieScanner.crawl): the scanner service URL and the shared * token (at least 16 characters). Required in production only. */ cookieCrawl?: boolean /** * Warn (never fail) when the database name in DATABASE_URI breaks the naming rule * `_prod` / `_dev` (docs/deployment.md). `true` takes the domain from * NEXT_PUBLIC_SERVER_URL (skipped for localhost); `{ domain }` sets it; `{ warn }` replaces * the console.warn. Default off. */ databaseName?: { domain?: string; warn?: (message: string) => void } | boolean /** Override the database var. Default 'DATABASE_URI'. */ databaseVar?: string /** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */ emailGraph?: boolean /** * Require IPAL_IP_HEADER in production — the header the rate limit trusts for * 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'. */ serverUrlVar?: string /** * R2 object storage (buildR2Storage). Adds the R2_* vars — the credentials * are required in production (media on a container disk vanish on redeploy). * Outside production they're optional (media go to the local disk), but a * partial set is an error: buildR2Storage needs all of them. * * R2_PUBLIC_URL is optional: empty = media served by the app * (/api/media/file/…). `{ requirePublicUrl: true }` requires it wherever the * credentials are required (a media domain on Cloudflare). */ storage?: { requirePublicUrl?: boolean } | boolean /** * Cloudflare Turnstile. true uses the common var names * (NEXT_PUBLIC_TURNSTILE_SITE_KEY + TURNSTILE_SECRET_KEY); pass an object to * override either name if your project differs. */ turnstile?: boolean | TurnstileNames } /** * The env schema for a standard ipal-kit deploy, assembled from the features the * project actually uses — so a site on local-disk storage isn't forced to set * R2_*, and a site with no forms isn't forced to set Turnstile. Opt-in, not a * fixed required set (A0: the plugin never demands config a project doesn't use). * * Variable names match what the plugin's own modules read (R2_*, GRAPH_*, * NEXT_PUBLIC_SERVER_URL). DATABASE_URI and PAYLOAD_SECRET are Payload-core. * Override any name via the options if your project names them differently. * * assertEnv(ipalEnvRules({ storage: true, emailGraph: true, turnstile: true })) * * Extend with project-specific vars by spreading: * * assertEnv([ * ...ipalEnvRules({ storage: true }), * { name: 'MY_API_KEY', description: 'Third-party integration key' }, * ]) */ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] { const { cookieCrawl = false, databaseName = false, databaseVar = 'DATABASE_URI', emailGraph = false, ipHeader = false, secretMinLength = 32, secretVar = 'PAYLOAD_SECRET', serverUrlVar = 'NEXT_PUBLIC_SERVER_URL', storage = false, turnstile = false, } = features const rules: EnvRule[] = [ { name: databaseVar, description: 'Database connection string (e.g. MongoDB URI)' }, { 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', description: 'Node environment', oneOf: ['development', 'production', 'test'], required: false, }, ] if (storage) { const requirePublicUrl = typeof storage === 'object' && storage.requirePublicUrl === true const r2Credentials = ['R2_BUCKET', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_ENDPOINT'] // Production: always. Development: once any credential is set (all or nothing). // R2_PUBLIC_URL alone is the read-only media mode (buildR2Storage) — allowed in dev. const r2Required = process.env.NODE_ENV === 'production' || r2Credentials.some((name) => Boolean(process.env[name])) rules.push( { name: 'R2_BUCKET', description: 'R2 bucket name', required: r2Required }, { name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id', required: r2Required }, { name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key', required: r2Required }, { name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url', required: r2Required }, { name: 'R2_PUBLIC_URL', description: 'Public base URL media is served from (custom domain of the bucket); empty = served by the app', required: requirePublicUrl && r2Required, // Production: absolute URL (https://media.example.com). Outside production a // site-relative path ('/media') is accepted — buildR2Storage prefixes it with // NEXT_PUBLIC_SERVER_URL (e.g. a dev rewrite /media → bucket). validate: (v) => { if (/^https?:\/\/[^/\s]+/i.test(v)) {return true} if (v.startsWith('/') && process.env.NODE_ENV !== 'production') {return true} return v.startsWith('/') ? `R2_PUBLIC_URL must be an absolute URL in production (got "${v}") — e.g. https://media.example.com` : `R2_PUBLIC_URL must be an absolute URL (https://…) or, outside production, a path starting with "/" (got "${v}")` }, }, ) } if (emailGraph) { rules.push( { name: 'GRAPH_TENANT_ID', description: 'Microsoft Graph tenant id' }, { name: 'GRAPH_CLIENT_ID', description: 'Microsoft Graph client id' }, { name: 'GRAPH_CLIENT_SECRET', description: 'Microsoft Graph client secret' }, { name: 'GRAPH_SENDER', description: 'From-address mail is sent as', kind: 'email' }, ) } if (ipHeader) { rules.push({ name: 'IPAL_IP_HEADER', description: 'Header holding the real client IP, e.g. cf-connecting-ip (Cloudflare) or x-forwarded-for', required: process.env.NODE_ENV === 'production', validate: (v) => (/^[a-z0-9-]+$/i.test(v) ? true : `IPAL_IP_HEADER must be a header name (got "${v}")`), }) } if (cookieCrawl) { const required = process.env.NODE_ENV === 'production' rules.push( { name: 'IPAL_COOKIE_SCAN_URL', description: 'Cookie crawler service base URL, e.g. https://cookie-crawler.example.com', kind: 'url', required }, { name: 'IPAL_COOKIE_SCAN_TOKEN', description: 'Token shared with the cookie crawler (this site\'s entry in IPAL_CRAWLER_SITES)', required, validate: (v) => (v.length >= 16 ? true : 'IPAL_COOKIE_SCAN_TOKEN must be at least 16 characters'), }, ) } if (turnstile) { const names = typeof turnstile === 'object' ? turnstile : {} rules.push( { name: names.siteKeyVar ?? 'NEXT_PUBLIC_TURNSTILE_SITE_KEY', description: 'Cloudflare Turnstile public site key', }, { name: names.secretVar ?? 'TURNSTILE_SECRET_KEY', description: 'Cloudflare Turnstile secret key', }, ) } if (databaseName) { const { domain, warn = (message: string) => console.warn(`[ipal] ${message}`) } = databaseName === true ? {} : databaseName rules.push({ name: databaseVar, description: 'Database name: _prod / _dev (warning only)', required: false, // A warning, never an error: the project may have a reason (an old database, a shared server). validate: (value) => { const message = checkDatabaseName({ databaseUri: value, domain: domain ?? process.env[serverUrlVar] }) if (message) {warn(`${databaseVar}: ${message}`)} return true }, }) } return rules }