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
+109
View File
@@ -0,0 +1,109 @@
'use client'
import { useEffect, useRef } from 'react'
import type { ConsentCategory } from './categories.js'
import { useConsentContext } from './ConsentContext.js'
type ConsentScriptProps = {
/** Default true. */
async?: boolean
/** Extra attributes on the <script> (e.g. { 'data-domain': 'x.com' }). */
attributes?: Record<string, string>
/**
* Consent category that must be granted before the script loads. Typically
* 'analytics' (GA, Plausible) or 'marketing' (Meta Pixel, ads, chat widgets).
*/
category: ConsentCategory
/**
* Inline JS to run once granted. If `src` is also set, it runs after the
* external script loads (so init code can rely on the library). A plain
* string of code — NOT user input (you control it), it goes into a <script>.
*/
code?: string
defer?: boolean
/** Stable id used to dedupe — the script is injected at most once. */
id?: string
/** External script URL. Injected only once the category is granted. */
src?: string
}
/**
* Loads a third-party script ONLY after the visitor has granted consent for its
* category — the GDPR-correct default for anything that isn't strictly
* necessary. Renders nothing until then. Reacts live to the consent context, so
* a script appears the moment the visitor accepts in the banner, with no reload.
*
* Use this for third parties that have NO Google Consent Mode of their own (Meta
* Pixel, LinkedIn Insight, chat widgets, custom analytics). GA/GTM are better
* handled by Consent Mode (the module's updateConsent already does that) — reach
* for ConsentScript when a vendor can't be gated that way.
*
* Must be rendered inside <ConsentProvider>.
*
* <ConsentScript category="marketing" src="https://connect.facebook.net/en_US/fbevents.js" />
* <ConsentScript category="analytics"
* src="https://plausible.io/js/script.js"
* attributes={{ 'data-domain': 'example.com' }} />
* <ConsentScript category="marketing" code={`fbq('init','123');fbq('track','PageView')`} />
*
* Note on withdrawal: once a script has loaded it keeps running for that page
* (a <script> tag can't be truly unloaded) — withdrawing consent stops the NEXT
* load. For vendors that support it, prefer Consent Mode so running tags honor
* the change immediately; ConsentScript gates the initial load.
*/
export function ConsentScript({
id,
async: asyncAttr = true,
attributes,
category,
code,
defer,
src,
}: ConsentScriptProps) {
const { state } = useConsentContext()
const granted = state[category] === true
const injectedRef = useRef(false)
useEffect(() => {
if (!granted || injectedRef.current) {return}
if (!src && !code) {return}
const dedupeId = id ?? (src ? `ipal-cs-${src}` : undefined)
if (dedupeId && document.getElementById(dedupeId)) {
injectedRef.current = true
return
}
injectedRef.current = true
const runInline = () => {
if (!code) {return}
const inline = document.createElement('script')
if (dedupeId) {inline.id = `${dedupeId}-inline`}
inline.textContent = code
document.head.appendChild(inline)
}
if (src) {
const el = document.createElement('script')
el.src = src
if (dedupeId) {el.id = dedupeId}
if (asyncAttr) {el.async = true}
if (defer) {el.defer = true}
if (attributes) {for (const [k, v] of Object.entries(attributes)) {el.setAttribute(k, v)}}
el.addEventListener('load', runInline, { once: true })
document.head.appendChild(el)
} else {
runInline()
}
// Deliberately no removal on cleanup: a loaded third-party script can't be
// meaningfully unloaded. Withdrawal is handled by not re-injecting (and, for
// vendors that support it, Consent Mode). See the component doc.
}, [granted, src, code, id, attributes, asyncAttr, defer])
return null
}
export default ConsentScript
+1
View File
@@ -1,5 +1,6 @@
'use client'
export { ConsentProvider, useConsentContext } from './ConsentContext.js'
export { ConsentScript } from './ConsentScript.js'
export { CookieBanner } from './CookieBanner.js'
export type { CookieBannerClassNames } from './CookieBanner.js'
export { CookieButton } from './CookieButton.js'
+1
View File
@@ -2,6 +2,7 @@ export { buildArchiveFields } from './archiveFields.js'
export { getArchiveEntries } from './getArchiveEntries.js'
export type { ArchiveEntries } from './getArchiveEntries.js'
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'
export { resolveRedirect } from './resolveRedirect.js'
export { resolveRoute } from './resolveRoute.js'
export type { ResolvedRoute } from './resolveRoute.js'
export type { ContentCollectionOption, ContentOption } from './types.js'
+119
View File
@@ -0,0 +1,119 @@
import type { BasePayload } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import { buildLocalizedPath } from '../i18n/index.js'
type RedirectCollection = {
/**
* Array field holding past slugs, each row `{ slug }`. Default 'slugHistory'
* — the field `trackSlugHistoryHook` writes. The subfield queried is
* `<field>.slug`.
*/
historyField?: string
/** Collection slug to search, e.g. 'pages'. */
slug: string
/** Current-slug field on the doc. Default 'slug'. */
slugField?: string
}
type ResolveRedirectArgs = {
/**
* Collections to search, in order. Default [{ slug: 'pages' }]. A collection
* without a slug-history field is skipped safely (no crash), so passing a
* collection that lacks it costs nothing.
*/
collections?: RedirectCollection[]
config: I18nConfig
/** Home slug map/string, so a renamed homepage still collapses to the root. */
homeSlug?: Record<string, string> | string
/** Active locale (the request's locale). */
locale: string
payload: BasePayload
/** Incoming route segments (what 404'd), e.g. ['uslugi', 'stara-nazwa']. */
segments: string[] | undefined
}
type DocShape = { slug?: unknown }
/**
* Resolves a 301/308 destination for a URL that no longer matches any current
* slug, by looking the old slug up in each collection's slug-history. Returns
* the current localized path to redirect to, or null when nothing matches.
*
* This is the read side of `trackSlugHistoryHook`: that hook records old slugs
* on save; this turns them back into a redirect so a renamed page never 404s
* (a real SEO loss). The plugin only COMPUTES the destination — the project
* issues the redirect, keeping the peer-dep boundary (no next/navigation import
* here):
*
* // app/[locale]/[[...slug]]/page.tsx (or app/[[...slug]] when single-locale)
* const route = await resolveRoute({ ... })
* if (!route) {
* const dest = await resolveRedirect({
* payload, locale, segments: slug, config: i18nConfig, homeSlug,
* collections: [{ slug: 'pages' }],
* })
* if (dest) permanentRedirect(dest) // from 'next/navigation' → HTTP 308 (SEO-equivalent to 301)
* notFound()
* }
*
* Multi-segment slugs (an editor slug like 'uslugi/biznesowe') are matched as
* the joined path, so they work unchanged. Archive ENTRY URLs
* (/artykuly/<entry>) aren't handled here yet — only flat collections; pass
* the collections whose slugs map directly to a path.
*/
export async function resolveRedirect({
collections = [{ slug: 'pages' }],
config,
homeSlug,
locale,
payload,
segments,
}: ResolveRedirectArgs): Promise<null | string> {
const oldSlug = (segments ?? []).filter(Boolean).join('/')
// Root never redirects — there's no "old slug" for the locale home.
if (!oldSlug) {return null}
for (const col of collections) {
const historyField = col.historyField ?? 'slugHistory'
const slugField = col.slugField ?? 'slug'
let currentSlug: string | undefined
try {
const res = await payload.find({
collection: col.slug as never,
depth: 0,
limit: 1,
locale: locale as never,
pagination: false,
where: { [`${historyField}.slug`]: { equals: oldSlug } } as never,
})
const doc = (res?.docs?.[0] ?? null) as DocShape | null
if (doc && typeof doc[slugField as keyof DocShape] === 'string') {
currentSlug = doc[slugField as keyof DocShape] as string
}
} catch {
// Collection has no slug-history field (path not queryable) or the query
// failed — skip it rather than 500 the 404 path. Same guard as the
// drafts/_status lesson.
continue
}
if (!currentSlug || currentSlug === oldSlug) {continue}
const dest = buildLocalizedPath({
config,
homeSlug,
locale,
slugs: { [locale]: currentSlug },
})
// Never redirect a path to itself (would loop).
if (dest && dest !== `/${oldSlug}` && dest !== `/${locale}/${oldSlug}`) {
return dest
}
}
return null
}
+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
}
+58
View File
@@ -0,0 +1,58 @@
/**
* A honeypot: a hidden field real users never see or fill, but naive bots do.
* A cheap, zero-friction second layer alongside Turnstile — no network call, no
* user interaction. Pure functions, usable on client (render the input) and
* server (check it in the action).
*/
/**
* Default field name. Looks like a real field a bot would want to fill, but is
* not one your form uses. Override per project if you like — just keep the
* client and server in sync.
*/
export const HONEYPOT_FIELD = 'company_url'
/**
* Props for the hidden input. Hidden from sight AND from assistive tech and tab
* order, so no real user (sighted, screen-reader, or keyboard) ever fills it —
* only a bot auto-filling every field.
*
* <input {...honeypotInputProps()} />
* // or with your own name:
* <input {...honeypotInputProps('website_2')} />
*/
export function honeypotInputProps(name: string = HONEYPOT_FIELD) {
return {
name,
type: 'text' as const,
'aria-hidden': true,
autoComplete: 'off' as const,
tabIndex: -1,
// Off-screen rather than display:none — some bots skip display:none fields.
style: {
height: '1px',
left: '-9999px',
overflow: 'hidden' as const,
position: 'absolute' as const,
width: '1px',
},
}
}
/**
* True when the honeypot was filled → treat the submission as spam and drop it
* (silently return success so the bot gets no signal). Call it FIRST in your
* server action, before submitForm:
*
* if (isHoneypotTripped(values)) return { success: true } // pretend-accept
* // strip it so submitForm doesn't see an unknown field:
* const { [HONEYPOT_FIELD]: _hp, ...clean } = values
* return submitForm({ ...clean })
*/
export function isHoneypotTripped(
values: Record<string, unknown>,
name: string = HONEYPOT_FIELD,
): boolean {
const v = values[name]
return typeof v === 'string' ? v.trim().length > 0 : v != null
}
+2
View File
@@ -1,6 +1,8 @@
// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only
// (Turnstile secret) — never import it from a client component.
export { buildFormsPlugin } from './formsPluginConfig.js'
// Honeypot anti-spam (pure — client renders the input, server checks it).
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './honeypot.js'
export { checkRateLimit } from './rateLimit.js'
export type { RateLimitArgs } from './rateLimit.js'
export { submitForm } from './submitForm.js'
+74
View File
@@ -0,0 +1,74 @@
import type { BasePayload } from 'payload'
type CreateHealthRouteArgs = {
/**
* Collection to ping for a real DB round-trip. Default 'pages'. Pick any
* collection that always exists in the project.
*/
collection?: string
/**
* Optional extra checks merged into the body (e.g. a cache or queue ping).
* Throwing marks the whole healthcheck unhealthy.
*/
extra?: () => Promise<Record<string, unknown>>
/** Same cached accessor the rest of the app uses. */
getCachedPayload: () => Promise<BasePayload>
}
/**
* A liveness/readiness route for Coolify/Docker healthchecks and uptime
* monitors. Does a real DB round-trip (not just "process is up") and returns
* 200 when reachable, 503 when not — so an orchestrator can restart or hold
* traffic off a container whose database is down.
*
* // app/api/health/route.ts
* import { createHealthRoute } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* export const dynamic = 'force-dynamic' // never prerender/cache a healthcheck
* export const GET = createHealthRoute({ getCachedPayload })
*
* Point Coolify's healthcheck at /api/health. Uses the global `Response`
* (standard in Next route handlers) — no next/server import, peer-dep clean.
*/
export function createHealthRoute(args: CreateHealthRouteArgs): () => Promise<Response> {
const { collection = 'pages', extra, getCachedPayload } = args
return async () => {
const startedAt = Date.now()
try {
const payload = await getCachedPayload()
// Cheapest real round-trip: ask for at most one row, no population.
await payload.find({
collection: collection as never,
depth: 0,
limit: 1,
pagination: false,
})
const extraData = extra ? await extra() : {}
const body = {
db: 'up',
status: 'ok',
timestamp: new Date().toISOString(),
tookMs: Date.now() - startedAt,
...extraData,
}
return new Response(JSON.stringify(body), {
headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },
status: 200,
})
} catch (err) {
const body = {
db: 'down',
error: err instanceof Error ? err.message : 'unknown',
status: 'error',
timestamp: new Date().toISOString(),
tookMs: Date.now() - startedAt,
}
return new Response(JSON.stringify(body), {
headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },
status: 503,
})
}
}
}
+1
View File
@@ -0,0 +1 @@
export { createHealthRoute } from './createHealthRoute.js'