Added healhtRoute, honeypot, ConsentScript, asserEnv

This commit is contained in:
2026-10-10 00:17:13 +02:00
parent 52977e67fc
commit 1b52060dce
63 changed files with 2110 additions and 36 deletions
+137
View File
@@ -0,0 +1,137 @@
/**
* Zero-dependency environment validation. The plugin deliberately does NOT pull
* in zod — forcing a validation library on every project would be a dependency
* the project didn't ask for (against the A0 "no imposed deps" rule). This is a
* tiny validator that does the one thing we need: check the vars a deploy needs
* and FAIL FAST with a readable, all-at-once message instead of a cryptic
* runtime crash (e.g. `getaddrinfo ENOTFOUND` halfway through a Docker build).
*/
export type EnvKind = 'boolean' | 'email' | 'number' | 'port' | 'string' | 'url'
export type EnvRule = {
/** Shown in the error to tell the deployer what the var is for. */
description?: string
/** Shape check applied when a value is present. Default 'string' (non-empty). */
kind?: EnvKind
/** Variable name, e.g. 'DATABASE_URI'. */
name: string
/** Allowed values (e.g. NODE_ENV). Checked when a value is present. */
oneOf?: readonly string[]
/** Default true. When false, the var is only validated if present. */
required?: boolean
/** Custom check: return true if OK, or an error message string. */
validate?: (value: string) => string | true
}
export type AssertEnvOptions = {
/** Source of values. Default process.env. */
env?: Record<string, string | undefined>
/** Error prefix. Default '[ipal]'. */
label?: string
}
const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
/** Validate one present value against its rule. Returns an error message or null. */
function checkValue(rule: EnvRule, value: string): null | string {
const { name, kind = 'string', oneOf } = rule
if (oneOf && !oneOf.includes(value)) {
return `${name} must be one of: ${oneOf.join(', ')} (got "${value}")`
}
switch (kind) {
case 'boolean':
if (!/^(true|false|1|0|yes|no)$/i.test(value)) {
return `${name} must be a boolean (true/false/1/0/yes/no, got "${value}")`
}
break
case 'email':
if (!EMAIL_RE.test(value)) {return `${name} must be an e-mail address (got "${value}")`}
break
case 'number':
if (!Number.isFinite(Number(value))) {return `${name} must be a number (got "${value}")`}
break
case 'port': {
const n = Number(value)
if (!Number.isInteger(n) || n < 1 || n > 65535) {
return `${name} must be a port 1–65535 (got "${value}")`
}
break
}
case 'url':
try {
new URL(value)
} catch {
return `${name} must be a valid URL (got "${value}")`
}
break
case 'string':
default:
break
}
if (rule.validate) {
const res = rule.validate(value)
if (res !== true) {return typeof res === 'string' ? res : `${name} is invalid`}
}
return null
}
/**
* Validates the given rules against the environment and THROWS a single,
* aggregated error listing every problem at once (not just the first). Call it
* once at boot — in payload.config.ts, or Next's instrumentation.ts register().
*
* import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'
* assertEnv(ipalEnvRules({ storage: true, turnstile: true }))
*
* or with hand-written rules:
*
* assertEnv([
* { name: 'DATABASE_URI', description: 'MongoDB connection string' },
* { name: 'NEXT_PUBLIC_SERVER_URL', kind: 'url' },
* { name: 'NODE_ENV', oneOf: ['development', 'production', 'test'] },
* ])
*
* Runs server-side only (reads process.env) — never import it into a client
* component.
*/
export function assertEnv(rules: EnvRule[], options: AssertEnvOptions = {}): void {
const env = options.env ?? process.env
const label = options.label ?? '[ipal]'
const problems: string[] = []
for (const rule of rules) {
const raw = env[rule.name]
const value = typeof raw === 'string' ? raw.trim() : ''
const required = rule.required !== false
if (!value) {
if (required) {
problems.push(
`${rule.name} is required but missing${rule.description ? ` — ${rule.description}` : ''}`,
)
}
continue // optional + absent → nothing to check
}
const err = checkValue(rule, value)
if (err) {
problems.push(`${err}${rule.description ? ` — ${rule.description}` : ''}`)
}
}
if (problems.length === 0) {return}
const message =
`${label} Environment validation failed (${problems.length} ` +
`problem${problems.length === 1 ? '' : 's'}):\n` +
problems.map((p) => ` • ${p}`).join('\n') +
`\nSet these in your environment (Coolify → Environment, or .env) and redeploy.`
throw new Error(message)
}
+4
View File
@@ -0,0 +1,4 @@
export { assertEnv } from './assertEnv.js'
export type { EnvRule, EnvKind, AssertEnvOptions } from './assertEnv.js'
export { ipalEnvRules } from './ipalEnvRules.js'
export type { IpalEnvFeatures } from './ipalEnvRules.js'
+103
View File
@@ -0,0 +1,103 @@
import type { EnvRule } from './assertEnv.js'
type TurnstileNames = { secretVar?: string; siteKeyVar?: string }
export type IpalEnvFeatures = {
/** Override the database var. Default 'DATABASE_URI'. */
databaseVar?: string
/** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */
emailGraph?: boolean
/** 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. */
storage?: 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 {
databaseVar = 'DATABASE_URI',
emailGraph = false,
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' },
{
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) {
rules.push(
{ name: 'R2_BUCKET', description: 'R2 bucket name' },
{ name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id' },
{ name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key' },
{ name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url' },
{ name: 'R2_PUBLIC_URL', description: 'Public base URL media is served from', kind: 'url' },
)
}
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 (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',
},
)
}
return rules
}