From 0f073b963e5ca5d2713dbc3eee9d3123f01113f3 Mon Sep 17 00:00:00 2001 From: rasm-its Date: Wed, 14 Oct 2026 11:05:57 +0200 Subject: [PATCH] Added fluid skills support --- dist/exports/env.d.ts | 17 +++++++++ dist/exports/env.js | 17 +++++++++ dist/exports/env.js.map | 1 + dist/modules/env/assertEnv.js | 2 +- dist/modules/env/assertEnv.js.map | 2 +- dist/modules/env/ipalEnvRules.js | 15 +++++++- dist/modules/env/ipalEnvRules.js.map | 2 +- .../frontend/createContentHelpers.d.ts | 2 +- dist/modules/security/buildCsp.js | 3 +- dist/modules/security/buildCsp.js.map | 2 +- dist/modules/seo/routeHandlers.d.ts | 2 +- dist/modules/seo/routeHandlers.js | 8 ++-- dist/modules/seo/routeHandlers.js.map | 2 +- dist/modules/storage/buildR2Storage.js | 6 ++- dist/modules/storage/buildR2Storage.js.map | 2 +- dist/styles/fluid.css | 34 +++++++++++++++++ docs/agent/AGENT.md | 10 +++-- docs/agent/skills/ipal-audit/scripts/audit.sh | 8 +++- .../skills/ipal-audit/scripts/html-check.mjs | 38 +++++++++++++++++++ docs/agent/skills/ipal-debug/SKILL.md | 2 + docs/agent/skills/ipal-setup/SKILL.md | 2 +- docs/dev/PROGRAMISTA.md | 20 +++++++++- docs/dev/vibe.md | 2 +- docs/env.md | 23 +++++++++-- docs/storage.md | 1 + src/exports/env.ts | 17 +++++++++ src/modules/env/assertEnv.ts | 2 +- src/modules/env/ipalEnvRules.ts | 21 +++++++--- src/modules/security/buildCsp.ts | 6 +-- src/modules/seo/routeHandlers.ts | 12 +++--- src/modules/storage/buildR2Storage.ts | 7 +++- src/styles/fluid.css | 34 +++++++++++++++++ 32 files changed, 280 insertions(+), 42 deletions(-) create mode 100644 dist/exports/env.d.ts create mode 100644 dist/exports/env.js create mode 100644 dist/exports/env.js.map create mode 100644 dist/styles/fluid.css create mode 100644 docs/agent/skills/ipal-audit/scripts/html-check.mjs create mode 100644 src/exports/env.ts create mode 100644 src/styles/fluid.css diff --git a/dist/exports/env.d.ts b/dist/exports/env.d.ts new file mode 100644 index 0000000..20237fc --- /dev/null +++ b/dist/exports/env.d.ts @@ -0,0 +1,17 @@ +/** + * Entry point: @intecion/ipal-kit/env + * + * Environment validation ONLY — zero imports beyond this module, no Payload, + * no Node built-ins, no React. Safe for Next's instrumentation.ts, which Next + * also compiles for the Edge runtime: importing the package root there drags in + * Payload / file-type / fs and crashes Turbopack ("Export fileTypeFromFile + * doesn't exist in target module"). + * + * // src/instrumentation.ts + * import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env' + * export function register() { + * if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true })) + * } + */ +export { assertEnv, ipalEnvRules } from '../modules/env/index.js'; +export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from '../modules/env/index.js'; diff --git a/dist/exports/env.js b/dist/exports/env.js new file mode 100644 index 0000000..001e068 --- /dev/null +++ b/dist/exports/env.js @@ -0,0 +1,17 @@ +/** + * Entry point: @intecion/ipal-kit/env + * + * Environment validation ONLY — zero imports beyond this module, no Payload, + * no Node built-ins, no React. Safe for Next's instrumentation.ts, which Next + * also compiles for the Edge runtime: importing the package root there drags in + * Payload / file-type / fs and crashes Turbopack ("Export fileTypeFromFile + * doesn't exist in target module"). + * + * // src/instrumentation.ts + * import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env' + * export function register() { + * if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true })) + * } + */ export { assertEnv, ipalEnvRules } from '../modules/env/index.js'; + +//# sourceMappingURL=env.js.map \ No newline at end of file diff --git a/dist/exports/env.js.map b/dist/exports/env.js.map new file mode 100644 index 0000000..3569b19 --- /dev/null +++ b/dist/exports/env.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/exports/env.ts"],"sourcesContent":["/**\n * Entry point: @intecion/ipal-kit/env\n *\n * Environment validation ONLY — zero imports beyond this module, no Payload,\n * no Node built-ins, no React. Safe for Next's instrumentation.ts, which Next\n * also compiles for the Edge runtime: importing the package root there drags in\n * Payload / file-type / fs and crashes Turbopack (\"Export fileTypeFromFile\n * doesn't exist in target module\").\n *\n * // src/instrumentation.ts\n * import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env'\n * export function register() {\n * if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true }))\n * }\n */\nexport { assertEnv, ipalEnvRules } from '../modules/env/index.js'\nexport type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from '../modules/env/index.js'\n"],"names":["assertEnv","ipalEnvRules"],"mappings":"AAAA;;;;;;;;;;;;;;CAcC,GACD,SAASA,SAAS,EAAEC,YAAY,QAAQ,0BAAyB"} \ No newline at end of file diff --git a/dist/modules/env/assertEnv.js b/dist/modules/env/assertEnv.js index 68511d6..fc46d0c 100644 --- a/dist/modules/env/assertEnv.js +++ b/dist/modules/env/assertEnv.js @@ -13,7 +13,7 @@ } switch(kind){ case 'boolean': - if (!/^(true|false|1|0|yes|no)$/i.test(value)) { + 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; diff --git a/dist/modules/env/assertEnv.js.map b/dist/modules/env/assertEnv.js.map index 5b5fd7e..48f23a5 100644 --- a/dist/modules/env/assertEnv.js.map +++ b/dist/modules/env/assertEnv.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/env/assertEnv.ts"],"sourcesContent":["/**\n * Zero-dependency environment validation. The plugin deliberately does NOT pull\n * in zod — forcing a validation library on every project would be a dependency\n * the project didn't ask for (against the A0 \"no imposed deps\" rule). This is a\n * tiny validator that does the one thing we need: check the vars a deploy needs\n * and FAIL FAST with a readable, all-at-once message instead of a cryptic\n * runtime crash (e.g. `getaddrinfo ENOTFOUND` halfway through a Docker build).\n */\n\nexport type EnvKind = 'boolean' | 'email' | 'number' | 'port' | 'string' | 'url'\n\nexport type EnvRule = {\n /** Shown in the error to tell the deployer what the var is for. */\n description?: string\n /** Shape check applied when a value is present. Default 'string' (non-empty). */\n kind?: EnvKind\n /** Variable name, e.g. 'DATABASE_URI'. */\n name: string\n /** Allowed values (e.g. NODE_ENV). Checked when a value is present. */\n oneOf?: readonly string[]\n /** Default true. When false, the var is only validated if present. */\n required?: boolean\n /** Custom check: return true if OK, or an error message string. */\n validate?: (value: string) => string | true\n}\n\nexport type AssertEnvOptions = {\n /** Source of values. Default process.env. */\n env?: Record\n /** Error prefix. Default '[ipal]'. */\n label?: string\n}\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@][^\\s.@]*\\.[^\\s@]+$/\n\n/** Validate one present value against its rule. Returns an error message or null. */\nfunction checkValue(rule: EnvRule, value: string): null | string {\n const { name, kind = 'string', oneOf } = rule\n\n if (oneOf && !oneOf.includes(value)) {\n return `${name} must be one of: ${oneOf.join(', ')} (got \"${value}\")`\n }\n\n switch (kind) {\n case 'boolean':\n if (!/^(true|false|1|0|yes|no)$/i.test(value)) {\n return `${name} must be a boolean (true/false/1/0/yes/no, got \"${value}\")`\n }\n break\n case 'email':\n if (!EMAIL_RE.test(value)) {return `${name} must be an e-mail address (got \"${value}\")`}\n break\n case 'number':\n if (!Number.isFinite(Number(value))) {return `${name} must be a number (got \"${value}\")`}\n break\n case 'port': {\n const n = Number(value)\n if (!Number.isInteger(n) || n < 1 || n > 65535) {\n return `${name} must be a port 1–65535 (got \"${value}\")`\n }\n break\n }\n case 'url':\n try {\n \n new URL(value)\n } catch {\n return `${name} must be a valid URL (got \"${value}\")`\n }\n break\n case 'string':\n default:\n break\n }\n\n if (rule.validate) {\n const res = rule.validate(value)\n if (res !== true) {return typeof res === 'string' ? res : `${name} is invalid`}\n }\n\n return null\n}\n\n/**\n * Validates the given rules against the environment and THROWS a single,\n * aggregated error listing every problem at once (not just the first). Call it\n * once at boot — in payload.config.ts, or Next's instrumentation.ts register().\n *\n * import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'\n * assertEnv(ipalEnvRules({ storage: true, turnstile: true }))\n *\n * or with hand-written rules:\n *\n * assertEnv([\n * { name: 'DATABASE_URI', description: 'MongoDB connection string' },\n * { name: 'NEXT_PUBLIC_SERVER_URL', kind: 'url' },\n * { name: 'NODE_ENV', oneOf: ['development', 'production', 'test'] },\n * ])\n *\n * Runs server-side only (reads process.env) — never import it into a client\n * component.\n */\nexport function assertEnv(rules: EnvRule[], options: AssertEnvOptions = {}): void {\n const env = options.env ?? process.env\n const label = options.label ?? '[ipal]'\n const problems: string[] = []\n\n for (const rule of rules) {\n const raw = env[rule.name]\n const value = typeof raw === 'string' ? raw.trim() : ''\n const required = rule.required !== false\n\n if (!value) {\n if (required) {\n problems.push(\n `${rule.name} is required but missing${rule.description ? ` — ${rule.description}` : ''}`,\n )\n }\n continue // optional + absent → nothing to check\n }\n\n const err = checkValue(rule, value)\n if (err) {\n problems.push(`${err}${rule.description ? ` — ${rule.description}` : ''}`)\n }\n }\n\n if (problems.length === 0) {return}\n\n const message =\n `${label} Environment validation failed (${problems.length} ` +\n `problem${problems.length === 1 ? '' : 's'}):\\n` +\n problems.map((p) => ` • ${p}`).join('\\n') +\n `\\nSet these in your environment (Coolify → Environment, or .env) and redeploy.`\n\n throw new Error(message)\n}\n"],"names":["EMAIL_RE","checkValue","rule","value","name","kind","oneOf","includes","join","test","Number","isFinite","n","isInteger","URL","validate","res","assertEnv","rules","options","env","process","label","problems","raw","trim","required","push","description","err","length","message","map","p","Error"],"mappings":"AAAA;;;;;;;CAOC,GA0BD,MAAMA,WAAW;AAEjB,mFAAmF,GACnF,SAASC,WAAWC,IAAa,EAAEC,KAAa;IAC9C,MAAM,EAAEC,IAAI,EAAEC,OAAO,QAAQ,EAAEC,KAAK,EAAE,GAAGJ;IAEzC,IAAII,SAAS,CAACA,MAAMC,QAAQ,CAACJ,QAAQ;QACnC,OAAO,GAAGC,KAAK,iBAAiB,EAAEE,MAAME,IAAI,CAAC,MAAM,OAAO,EAAEL,MAA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MJ,GAAG,CAAClB,KAAKE,IAAI,CAAC;QAC1B,MAAMD,QAAQ,OAAOqB,QAAQ,WAAWA,IAAIC,IAAI,KAAK;QACrD,MAAMC,WAAWxB,KAAKwB,QAAQ,KAAK;QAEnC,IAAI,CAACvB,OAAO;YACV,IAAIuB,UAAU;gBACZH,SAASI,IAAI,CACX,GAAGzB,KAAKE,IAAI,CAAC,wBAAwB,EAAEF,KAAK0B,WAAW,GAAG,CAAC,GAAG,EAAE1B,KAAK0B,WAAW,EAAE,GAAG,IAAI;YAE7F;YACA,UAAS,uCAAuC;QAClD;QAEA,MAAMC,MAAM5B,WAAWC,MAAMC;QAC7B,IAAI0B,KAAK;YACPN,SAASI,IAAI,CAAC,GAAGE,MAAM3B,KAAK0B,WAAW,GAAG,CAAC,GAAG,EAAE1B,KAAK0B,WAAW,EAAE,GAAG,IAAI;QAC3E;IACF;IAEA,IAAIL,SAASO,MAAM,KAAK,GAAG;QAAC;IAAM;IAElC,MAAMC,UACJ,GAAGT,MAAM,gCAAgC,EAAEC,SAASO,MAAM,CAAC,CAAC,CAAC,GAC7D,CAAC,OAAO,EAAEP,SAASO,MAAM,KAAK,IAAI,KAAK,IAAI,IAAI,CAAC,GAChDP,SAASS,GAAG,CAAC,CAACC,IAAM,CAAC,IAAI,EAAEA,GAAG,EAAEzB,IAAI,CAAC,QACrC,CAAC,8EAA8E,CAAC;IAElF,MAAM,IAAI0B,MAAMH;AAClB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/env/assertEnv.ts"],"sourcesContent":["/**\n * Zero-dependency environment validation. The plugin deliberately does NOT pull\n * in zod — forcing a validation library on every project would be a dependency\n * the project didn't ask for (against the A0 \"no imposed deps\" rule). This is a\n * tiny validator that does the one thing we need: check the vars a deploy needs\n * and FAIL FAST with a readable, all-at-once message instead of a cryptic\n * runtime crash (e.g. `getaddrinfo ENOTFOUND` halfway through a Docker build).\n */\n\nexport type EnvKind = 'boolean' | 'email' | 'number' | 'port' | 'string' | 'url'\n\nexport type EnvRule = {\n /** Shown in the error to tell the deployer what the var is for. */\n description?: string\n /** Shape check applied when a value is present. Default 'string' (non-empty). */\n kind?: EnvKind\n /** Variable name, e.g. 'DATABASE_URI'. */\n name: string\n /** Allowed values (e.g. NODE_ENV). Checked when a value is present. */\n oneOf?: readonly string[]\n /** Default true. When false, the var is only validated if present. */\n required?: boolean\n /** Custom check: return true if OK, or an error message string. */\n validate?: (value: string) => string | true\n}\n\nexport type AssertEnvOptions = {\n /** Source of values. Default process.env. */\n env?: Record\n /** Error prefix. Default '[ipal]'. */\n label?: string\n}\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@][^\\s.@]*\\.[^\\s@]+$/\n\n/** Validate one present value against its rule. Returns an error message or null. */\nfunction checkValue(rule: EnvRule, value: string): null | string {\n const { name, kind = 'string', oneOf } = rule\n\n if (oneOf && !oneOf.includes(value)) {\n return `${name} must be one of: ${oneOf.join(', ')} (got \"${value}\")`\n }\n\n switch (kind) {\n case 'boolean':\n if (!/^(?:true|false|1|0|yes|no)$/i.test(value)) {\n return `${name} must be a boolean (true/false/1/0/yes/no, got \"${value}\")`\n }\n break\n case 'email':\n if (!EMAIL_RE.test(value)) {return `${name} must be an e-mail address (got \"${value}\")`}\n break\n case 'number':\n if (!Number.isFinite(Number(value))) {return `${name} must be a number (got \"${value}\")`}\n break\n case 'port': {\n const n = Number(value)\n if (!Number.isInteger(n) || n < 1 || n > 65535) {\n return `${name} must be a port 1–65535 (got \"${value}\")`\n }\n break\n }\n case 'url':\n try {\n \n new URL(value)\n } catch {\n return `${name} must be a valid URL (got \"${value}\")`\n }\n break\n case 'string':\n default:\n break\n }\n\n if (rule.validate) {\n const res = rule.validate(value)\n if (res !== true) {return typeof res === 'string' ? res : `${name} is invalid`}\n }\n\n return null\n}\n\n/**\n * Validates the given rules against the environment and THROWS a single,\n * aggregated error listing every problem at once (not just the first). Call it\n * once at boot — in payload.config.ts, or Next's instrumentation.ts register().\n *\n * import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'\n * assertEnv(ipalEnvRules({ storage: true, turnstile: true }))\n *\n * or with hand-written rules:\n *\n * assertEnv([\n * { name: 'DATABASE_URI', description: 'MongoDB connection string' },\n * { name: 'NEXT_PUBLIC_SERVER_URL', kind: 'url' },\n * { name: 'NODE_ENV', oneOf: ['development', 'production', 'test'] },\n * ])\n *\n * Runs server-side only (reads process.env) — never import it into a client\n * component.\n */\nexport function assertEnv(rules: EnvRule[], options: AssertEnvOptions = {}): void {\n const env = options.env ?? process.env\n const label = options.label ?? '[ipal]'\n const problems: string[] = []\n\n for (const rule of rules) {\n const raw = env[rule.name]\n const value = typeof raw === 'string' ? raw.trim() : ''\n const required = rule.required !== false\n\n if (!value) {\n if (required) {\n problems.push(\n `${rule.name} is required but missing${rule.description ? ` — ${rule.description}` : ''}`,\n )\n }\n continue // optional + absent → nothing to check\n }\n\n const err = checkValue(rule, value)\n if (err) {\n problems.push(`${err}${rule.description ? ` — ${rule.description}` : ''}`)\n }\n }\n\n if (problems.length === 0) {return}\n\n const message =\n `${label} Environment validation failed (${problems.length} ` +\n `problem${problems.length === 1 ? '' : 's'}):\\n` +\n problems.map((p) => ` • ${p}`).join('\\n') +\n `\\nSet these in your environment (Coolify → Environment, or .env) and redeploy.`\n\n throw new Error(message)\n}\n"],"names":["EMAIL_RE","checkValue","rule","value","name","kind","oneOf","includes","join","test","Number","isFinite","n","isInteger","URL","validate","res","assertEnv","rules","options","env","process","label","problems","raw","trim","required","push","description","err","length","message","map","p","Error"],"mappings":"AAAA;;;;;;;CAOC,GA0BD,MAAMA,WAAW;AAEjB,mFAAmF,GACnF,SAASC,WAAWC,IAAa,EAAEC,KAAa;IAC9C,MAAM,EAAEC,IAAI,EAAEC,OAAO,QAAQ,EAAEC,KAAK,EAAE,GAAGJ;IAEzC,IAAII,SAAS,CAACA,MAAMC,QAAQ,CAACJ,QAAQ;QACnC,OAAO,GAAGC,KAAK,iBAAiB,EAAEE,MAAME,IAAI,CAAC,MAAM,O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ACxB,MAAMM,MAAMJ,GAAG,CAAClB,KAAKE,IAAI,CAAC;QAC1B,MAAMD,QAAQ,OAAOqB,QAAQ,WAAWA,IAAIC,IAAI,KAAK;QACrD,MAAMC,WAAWxB,KAAKwB,QAAQ,KAAK;QAEnC,IAAI,CAACvB,OAAO;YACV,IAAIuB,UAAU;gBACZH,SAASI,IAAI,CACX,GAAGzB,KAAKE,IAAI,CAAC,wBAAwB,EAAEF,KAAK0B,WAAW,GAAG,CAAC,GAAG,EAAE1B,KAAK0B,WAAW,EAAE,GAAG,IAAI;YAE7F;YACA,UAAS,uCAAuC;QAClD;QAEA,MAAMC,MAAM5B,WAAWC,MAAMC;QAC7B,IAAI0B,KAAK;YACPN,SAASI,IAAI,CAAC,GAAGE,MAAM3B,KAAK0B,WAAW,GAAG,CAAC,GAAG,EAAE1B,KAAK0B,WAAW,EAAE,GAAG,IAAI;QAC3E;IACF;IAEA,IAAIL,SAASO,MAAM,KAAK,GAAG;QAAC;IAAM;IAElC,MAAMC,UACJ,GAAGT,MAAM,gCAAgC,EAAEC,SAASO,MAAM,CAAC,CAAC,CAAC,GAC7D,CAAC,OAAO,EAAEP,SAASO,MAAM,KAAK,IAAI,KAAK,IAAI,IAAI,CAAC,GAChDP,SAASS,GAAG,CAAC,CAACC,IAAM,CAAC,IAAI,EAAEA,GAAG,EAAEzB,IAAI,CAAC,QACrC,CAAC,8EAA8E,CAAC;IAElF,MAAM,IAAI0B,MAAMH;AAClB"} \ No newline at end of file diff --git a/dist/modules/env/ipalEnvRules.js b/dist/modules/env/ipalEnvRules.js index 11fcf51..22653a9 100644 --- a/dist/modules/env/ipalEnvRules.js +++ b/dist/modules/env/ipalEnvRules.js @@ -59,8 +59,19 @@ kind: 'url' }, { name: 'R2_PUBLIC_URL', - description: 'Public base URL media is served from', - kind: 'url' + description: 'Public base URL media is served from (custom domain of the bucket)', + // 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) { diff --git a/dist/modules/env/ipalEnvRules.js.map b/dist/modules/env/ipalEnvRules.js.map index 1f81d89..1179f48 100644 --- a/dist/modules/env/ipalEnvRules.js.map +++ b/dist/modules/env/ipalEnvRules.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/env/ipalEnvRules.ts"],"sourcesContent":["import type { EnvRule } from './assertEnv.js'\n\ntype TurnstileNames = { secretVar?: string; siteKeyVar?: string }\n\nexport type IpalEnvFeatures = {\n /** Override the database var. Default 'DATABASE_URI'. */\n databaseVar?: string\n /** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */\n emailGraph?: boolean\n /** Override the Payload secret var. Default 'PAYLOAD_SECRET'. */\n secretVar?: string\n /** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */\n serverUrlVar?: string\n /** R2 object storage (buildR2Storage). Adds the R2_* vars. */\n storage?: boolean\n /**\n * Cloudflare Turnstile. true uses the common var names\n * (NEXT_PUBLIC_TURNSTILE_SITE_KEY + TURNSTILE_SECRET_KEY); pass an object to\n * override either name if your project differs.\n */\n turnstile?: boolean | TurnstileNames\n}\n\n/**\n * The env schema for a standard ipal-kit deploy, assembled from the features the\n * project actually uses — so a site on local-disk storage isn't forced to set\n * R2_*, and a site with no forms isn't forced to set Turnstile. Opt-in, not a\n * fixed required set (A0: the plugin never demands config a project doesn't use).\n *\n * Variable names match what the plugin's own modules read (R2_*, GRAPH_*,\n * NEXT_PUBLIC_SERVER_URL). DATABASE_URI and PAYLOAD_SECRET are Payload-core.\n * Override any name via the options if your project names them differently.\n *\n * assertEnv(ipalEnvRules({ storage: true, emailGraph: true, turnstile: true }))\n *\n * Extend with project-specific vars by spreading:\n *\n * assertEnv([\n * ...ipalEnvRules({ storage: true }),\n * { name: 'MY_API_KEY', description: 'Third-party integration key' },\n * ])\n */\nexport function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {\n const {\n databaseVar = 'DATABASE_URI',\n emailGraph = false,\n secretVar = 'PAYLOAD_SECRET',\n serverUrlVar = 'NEXT_PUBLIC_SERVER_URL',\n storage = false,\n turnstile = false,\n } = features\n\n const rules: EnvRule[] = [\n { name: databaseVar, description: 'Database connection string (e.g. MongoDB URI)' },\n { name: secretVar, description: 'Payload secret used to sign tokens' },\n {\n name: serverUrlVar,\n description: 'Public site origin, e.g. https://example.com',\n kind: 'url',\n },\n {\n name: 'NODE_ENV',\n description: 'Node environment',\n oneOf: ['development', 'production', 'test'],\n required: false,\n },\n ]\n\n if (storage) {\n rules.push(\n { name: 'R2_BUCKET', description: 'R2 bucket name' },\n { name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id' },\n { name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key' },\n { name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url' },\n { name: 'R2_PUBLIC_URL', description: 'Public base URL media is served from', kind: 'url' },\n )\n }\n\n if (emailGraph) {\n rules.push(\n { name: 'GRAPH_TENANT_ID', description: 'Microsoft Graph tenant id' },\n { name: 'GRAPH_CLIENT_ID', description: 'Microsoft Graph client id' },\n { name: 'GRAPH_CLIENT_SECRET', description: 'Microsoft Graph client secret' },\n { name: 'GRAPH_SENDER', description: 'From-address mail is sent as', kind: 'email' },\n )\n }\n\n if (turnstile) {\n const names = typeof turnstile === 'object' ? turnstile : {}\n rules.push(\n {\n name: names.siteKeyVar ?? 'NEXT_PUBLIC_TURNSTILE_SITE_KEY',\n description: 'Cloudflare Turnstile public site key',\n },\n {\n name: names.secretVar ?? 'TURNSTILE_SECRET_KEY',\n description: 'Cloudflare Turnstile secret key',\n },\n )\n }\n\n return rules\n}\n"],"names":["ipalEnvRules","features","databaseVar","emailGraph","secretVar","serverUrlVar","storage","turnstile","rules","name","description","kind","oneOf","required","push","names","siteKeyVar"],"mappings":"AAuBA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASA,aAAaC,WAA4B,CAAC,CAAC;IACzD,MAAM,EACJC,cAAc,cAAc,EAC5BC,aAAa,KAAK,EAClBC,YAAY,gBAAgB,EAC5BC,eAAe,wBAAwB,EACvCC,UAAU,KAAK,EACfC,YAAY,KAAK,EAClB,GAAGN;IAEJ,MAAMO,QAAmB;QACvB;YAAEC,MAAMP;YAAaQ,aAAa;QAAgD;QAClF;YAAED,MAAML;YAAWM,aAAa;QAAqC;QACrE;YACED,MAAMJ;YACNK,aAAa;YACbC,MAAM;QACR;QACA;YACEF,MAAM;YACNC,aAAa;YACbE,OAAO;gBAAC;gBAAe;gBAAc;aAAO;YAC5CC,UAAU;QACZ;KACD;IAED,IAAIP,SAAS;QACXE,MAAMM,IAAI,CACR;YAAEL,MAAM;YAAaC,aAAa;QAAiB,GACnD;YAAED,MAAM;YAAoBC,aAAa;QAAmB,GAC5D;YAAED,MAAM;YAAwBC,aAAa;QAAuB,GACpE;YAAED,MAAM;YAAeC,aAAa;YAA0BC,MAAM;QAAM,GAC1E;YAAEF,MAAM;YAAiBC,aAAa;YAAwCC,MAAM;QAAM;IAE9F;IAEA,IAAIR,YAAY;QACdK,MAAMM,IAAI,CACR;YAAEL,MAAM;YAAmBC,aAAa;QAA4B,GACpE;YAAED,MAAM;YAAmBC,aAAa;QAA4B,GACpE;YAAED,MAAM;YAAuBC,aAAa;QAAgC,GAC5E;YAAED,MAAM;YAAgBC,aAAa;YAAgCC,MAAM;QAAQ;IAEvF;IAEA,IAAIJ,WAAW;QACb,MAAMQ,QAAQ,OAAOR,cAAc,WAAWA,YAAY,CAAC;QAC3DC,MAAMM,IAAI,CACR;YACEL,MAAMM,MAAMC,UAAU,IAAI;YAC1BN,aAAa;QACf,GACA;YACED,MAAMM,MAAMX,SAAS,IAAI;YACzBM,aAAa;QACf;IAEJ;IAEA,OAAOF;AACT"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/env/ipalEnvRules.ts"],"sourcesContent":["import type { EnvRule } from './assertEnv.js'\n\ntype TurnstileNames = { secretVar?: string; siteKeyVar?: string }\n\nexport type IpalEnvFeatures = {\n /** Override the database var. Default 'DATABASE_URI'. */\n databaseVar?: string\n /** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */\n emailGraph?: boolean\n /** Override the Payload secret var. Default 'PAYLOAD_SECRET'. */\n secretVar?: string\n /** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */\n serverUrlVar?: string\n /** R2 object storage (buildR2Storage). Adds the R2_* vars. */\n storage?: boolean\n /**\n * Cloudflare Turnstile. true uses the common var names\n * (NEXT_PUBLIC_TURNSTILE_SITE_KEY + TURNSTILE_SECRET_KEY); pass an object to\n * override either name if your project differs.\n */\n turnstile?: boolean | TurnstileNames\n}\n\n/**\n * The env schema for a standard ipal-kit deploy, assembled from the features the\n * project actually uses — so a site on local-disk storage isn't forced to set\n * R2_*, and a site with no forms isn't forced to set Turnstile. Opt-in, not a\n * fixed required set (A0: the plugin never demands config a project doesn't use).\n *\n * Variable names match what the plugin's own modules read (R2_*, GRAPH_*,\n * NEXT_PUBLIC_SERVER_URL). DATABASE_URI and PAYLOAD_SECRET are Payload-core.\n * Override any name via the options if your project names them differently.\n *\n * assertEnv(ipalEnvRules({ storage: true, emailGraph: true, turnstile: true }))\n *\n * Extend with project-specific vars by spreading:\n *\n * assertEnv([\n * ...ipalEnvRules({ storage: true }),\n * { name: 'MY_API_KEY', description: 'Third-party integration key' },\n * ])\n */\nexport function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {\n const {\n databaseVar = 'DATABASE_URI',\n emailGraph = false,\n secretVar = 'PAYLOAD_SECRET',\n serverUrlVar = 'NEXT_PUBLIC_SERVER_URL',\n storage = false,\n turnstile = false,\n } = features\n\n const rules: EnvRule[] = [\n { name: databaseVar, description: 'Database connection string (e.g. MongoDB URI)' },\n { name: secretVar, description: 'Payload secret used to sign tokens' },\n { name: serverUrlVar, description: 'Public site origin, e.g. https://example.com', kind: 'url' },\n {\n name: 'NODE_ENV',\n description: 'Node environment',\n oneOf: ['development', 'production', 'test'],\n required: false,\n },\n ]\n\n if (storage) {\n rules.push(\n { name: 'R2_BUCKET', description: 'R2 bucket name' },\n { name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id' },\n { name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key' },\n { name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url' },\n {\n name: 'R2_PUBLIC_URL',\n description: 'Public base URL media is served from (custom domain of the bucket)',\n // Production: absolute URL (https://media.example.com). Outside production a\n // site-relative path ('/media') is accepted — buildR2Storage prefixes it with\n // NEXT_PUBLIC_SERVER_URL (e.g. a dev rewrite /media → bucket).\n validate: (v) => {\n if (/^https?:\\/\\/[^/\\s]+/i.test(v)) {return true}\n if (v.startsWith('/') && process.env.NODE_ENV !== 'production') {return true}\n return v.startsWith('/')\n ? `R2_PUBLIC_URL must be an absolute URL in production (got \"${v}\") — e.g. https://media.example.com`\n : `R2_PUBLIC_URL must be an absolute URL (https://…) or, outside production, a path starting with \"/\" (got \"${v}\")`\n },\n },\n )\n }\n\n if (emailGraph) {\n rules.push(\n { name: 'GRAPH_TENANT_ID', description: 'Microsoft Graph tenant id' },\n { name: 'GRAPH_CLIENT_ID', description: 'Microsoft Graph client id' },\n { name: 'GRAPH_CLIENT_SECRET', description: 'Microsoft Graph client secret' },\n { name: 'GRAPH_SENDER', description: 'From-address mail is sent as', kind: 'email' },\n )\n }\n\n if (turnstile) {\n const names = typeof turnstile === 'object' ? turnstile : {}\n rules.push(\n {\n name: names.siteKeyVar ?? 'NEXT_PUBLIC_TURNSTILE_SITE_KEY',\n description: 'Cloudflare Turnstile public site key',\n },\n {\n name: names.secretVar ?? 'TURNSTILE_SECRET_KEY',\n description: 'Cloudflare Turnstile secret key',\n },\n )\n }\n\n return rules\n}\n"],"names":["ipalEnvRules","features","databaseVar","emailGraph","secretVar","serverUrlVar","storage","turnstile","rules","name","description","kind","oneOf","required","push","validate","v","test","startsWith","process","env","NODE_ENV","names","siteKeyVar"],"mappings":"AAuBA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASA,aAAaC,WAA4B,CAAC,CAAC;IACzD,MAAM,EACJC,cAAc,cAAc,EAC5BC,aAAa,KAAK,EAClBC,YAAY,gBAAgB,EAC5BC,eAAe,wBAAwB,EACvCC,UAAU,KAAK,EACfC,YAAY,KAAK,EAClB,GAAGN;IAEJ,MAAMO,QAAmB;QACvB;YAAEC,MAAMP;YAAaQ,aAAa;QAAgD;QAClF;YAAED,MAAML;YAAWM,aAAa;QAAqC;QACrE;YAAED,MAAMJ;YAAcK,aAAa;YAAgDC,MAAM;QAAM;QAC/F;YACEF,MAAM;YACNC,aAAa;YACbE,OAAO;gBAAC;gBAAe;gBAAc;aAAO;YAC5CC,UAAU;QACZ;KACD;IAED,IAAIP,SAAS;QACXE,MAAMM,IAAI,CACR;YAAEL,MAAM;YAAaC,aAAa;QAAiB,GACnD;YAAED,MAAM;YAAoBC,aAAa;QAAmB,GAC5D;YAAED,MAAM;YAAwBC,aAAa;QAAuB,GACpE;YAAED,MAAM;YAAeC,aAAa;YAA0BC,MAAM;QAAM,GAC1E;YACEF,MAAM;YACNC,aAAa;YACb,6EAA6E;YAC7E,8EAA8E;YAC9E,+DAA+D;YAC/DK,UAAU,CAACC;gBACT,IAAI,uBAAuBC,IAAI,CAACD,IAAI;oBAAC,OAAO;gBAAI;gBAChD,IAAIA,EAAEE,UAAU,CAAC,QAAQC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;oBAAC,OAAO;gBAAI;gBAC5E,OAAOL,EAAEE,UAAU,CAAC,OAChB,CAAC,0DAA0D,EAAEF,EAAE,mCAAmC,CAAC,GACnG,CAAC,yGAAyG,EAAEA,EAAE,EAAE,CAAC;YACvH;QACF;IAEJ;IAEA,IAAIb,YAAY;QACdK,MAAMM,IAAI,CACR;YAAEL,MAAM;YAAmBC,aAAa;QAA4B,GACpE;YAAED,MAAM;YAAmBC,aAAa;QAA4B,GACpE;YAAED,MAAM;YAAuBC,aAAa;QAAgC,GAC5E;YAAED,MAAM;YAAgBC,aAAa;YAAgCC,MAAM;QAAQ;IAEvF;IAEA,IAAIJ,WAAW;QACb,MAAMe,QAAQ,OAAOf,cAAc,WAAWA,YAAY,CAAC;QAC3DC,MAAMM,IAAI,CACR;YACEL,MAAMa,MAAMC,UAAU,IAAI;YAC1Bb,aAAa;QACf,GACA;YACED,MAAMa,MAAMlB,SAAS,IAAI;YACzBM,aAAa;QACf;IAEJ;IAEA,OAAOF;AACT"} \ No newline at end of file diff --git a/dist/modules/frontend/createContentHelpers.d.ts b/dist/modules/frontend/createContentHelpers.d.ts index 1d3fc64..931a6e4 100644 --- a/dist/modules/frontend/createContentHelpers.d.ts +++ b/dist/modules/frontend/createContentHelpers.d.ts @@ -84,6 +84,6 @@ export declare function createContentHelpers({ baseUrl, config, content, i18n, p resolveRoute: (locale: string, segments: string[] | undefined, page: number) => Promise; robots: () => RobotsRules; sitemap: () => Promise; - sitemapRoute: (req?: Request) => Promise; + sitemapRoute: (req: Request) => Promise; }; export {}; diff --git a/dist/modules/security/buildCsp.js b/dist/modules/security/buildCsp.js index 292a43d..312fe69 100644 --- a/dist/modules/security/buildCsp.js +++ b/dist/modules/security/buildCsp.js @@ -68,7 +68,8 @@ "'none'" ] }; - if (r2Url) { + // Site-relative R2_PUBLIC_URL ('/media', dev) is same-origin — already covered by 'self'. + if (r2Url && /^https?:\/\//i.test(r2Url)) { src['img-src'].push(r2Url); } if (turnstile) { diff --git a/dist/modules/security/buildCsp.js.map b/dist/modules/security/buildCsp.js.map index 2347172..68423d4 100644 --- a/dist/modules/security/buildCsp.js.map +++ b/dist/modules/security/buildCsp.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/security/buildCsp.ts"],"sourcesContent":["export type BuildCspArgs = {\n /** Google Analytics / GTM — adds googletagmanager + google-analytics. */\n analytics?: boolean\n /** Extra sources per directive, merged with the built-ins. */\n extra?: Partial>\n /** Google Maps embeds — adds maps.google.com / *.gstatic.com. */\n googleMaps?: boolean\n /** 'enforce' → Content-Security-Policy; 'report-only' → …-Report-Only header. */\n mode?: 'enforce' | 'report-only'\n /** Media/R2 public URL (from R2_PUBLIC_URL) — added to img-src. */\n r2Url?: string\n /** Cloudflare Turnstile — adds challenges.cloudflare.com to script/frame/connect. */\n turnstile?: boolean\n /** YouTube embeds — adds youtube to frame-src. */\n youtube?: boolean\n}\n\ntype CspDirective =\n | 'base-uri'\n | 'connect-src'\n | 'default-src'\n | 'font-src'\n | 'form-action'\n | 'frame-ancestors'\n | 'frame-src'\n | 'img-src'\n | 'media-src'\n | 'object-src'\n | 'script-src'\n | 'style-src'\n | 'worker-src'\n\n/**\n * Builds a Content-Security-Policy string with the hard OWASP/Lighthouse-required\n * directives baked in, and opt-in sources for common third parties. Solves the\n * real risk of hand-writing raw CSP per project and forgetting `base-uri 'self'`\n * or `object-src 'none'`.\n *\n * CSP still lives in the project (it lists the project's own domains), but this\n * helper standardizes the skeleton so every project's CSP has the same hardened\n * base — you only flip flags for what the project actually loads.\n *\n * Returns { key, value } ready for buildSecurityHeaders `additional`:\n *\n * import { buildCsp, buildSecurityHeaders } from '@intecion/ipal-kit'\n * const csp = buildCsp({\n * mode: 'report-only', // start here; switch to 'enforce' when clean\n * r2Url: process.env.R2_PUBLIC_URL,\n * turnstile: true, analytics: true,\n * })\n * const headers = buildSecurityHeaders({ hsts: prod, additional: [csp] })\n *\n * Deploy CSP carefully: start with mode:'report-only', check the console for\n * violations across the whole site (forms/Turnstile, gallery/R2, embeds), add\n * missing sources via `extra`, THEN switch to 'enforce'. See docs/security.md.\n */\nexport function buildCsp(args: BuildCspArgs = {}): { key: string; value: string } {\n const { analytics, extra = {}, googleMaps, mode = 'enforce', r2Url, turnstile, youtube } = args\n\n const src: Record = {\n 'default-src': [\"'self'\"],\n // 'unsafe-inline' is hard to avoid with Next/analytics; 'unsafe-eval' is NOT\n // added by default (weakens CSP) — add via extra only if a library needs it.\n 'connect-src': [\"'self'\"],\n 'font-src': [\"'self'\", 'https://fonts.gstatic.com', 'data:'],\n 'form-action': [\"'self'\"],\n 'frame-src': [],\n 'img-src': [\"'self'\", 'data:', 'blob:'],\n 'media-src': [], // video/audio sources — filled via extra when needed\n 'script-src': [\"'self'\", \"'unsafe-inline'\"],\n 'style-src': [\"'self'\", \"'unsafe-inline'\", 'https://fonts.googleapis.com'],\n 'worker-src': [], // web workers — filled via extra when needed\n // HARD defaults (OWASP/Lighthouse) — always on, no reason to omit:\n 'base-uri': [\"'self'\"], // block hijacking\n 'frame-ancestors': [\"'none'\"], // clickjacking protection (replaces X-Frame-Options)\n 'object-src': [\"'none'\"], // block / (Flash-era attack surface)\n }\n\n if (r2Url) {src['img-src'].push(r2Url)}\n\n if (turnstile) {\n src['script-src'].push('https://challenges.cloudflare.com')\n src['frame-src'].push('https://challenges.cloudflare.com')\n src['connect-src'].push('https://challenges.cloudflare.com')\n }\n\n if (analytics) {\n src['script-src'].push('https://www.googletagmanager.com')\n src['connect-src'].push('https://www.google-analytics.com', 'https://www.googletagmanager.com')\n src['img-src'].push('https://www.google-analytics.com', 'https://www.googletagmanager.com')\n }\n\n if (youtube) {\n src['frame-src'].push('https://www.youtube.com', 'https://www.youtube-nocookie.com')\n }\n\n if (googleMaps) {\n src['frame-src'].push('https://www.google.com', 'https://maps.google.com')\n src['script-src'].push('https://maps.googleapis.com')\n src['img-src'].push('https://maps.gstatic.com', 'https://*.googleapis.com')\n }\n\n // Merge caller extras.\n for (const [dir, values] of Object.entries(extra) as Array<[CspDirective, string[]]>) {\n if (values && values.length) {src[dir] = [...(src[dir] ?? []), ...values]}\n }\n\n const value = (Object.entries(src) as Array<[CspDirective, string[]]>)\n .filter(([, values]) => values.length > 0)\n .map(([dir, values]) => `${dir} ${values.join(' ')}`)\n .join('; ')\n\n const key =\n mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy'\n return { key, value }\n}\n"],"names":["buildCsp","args","analytics","extra","googleMaps","mode","r2Url","turnstile","youtube","src","push","dir","values","Object","entries","length","value","filter","map","join","key"],"mappings":"AAgCA;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,SAASA,SAASC,OAAqB,CAAC,CAAC;IAC9C,MAAM,EAAEC,SAAS,EAAEC,QAAQ,CAAC,CAAC,EAAEC,UAAU,EAAEC,OAAO,SAAS,EAAEC,KAAK,EAAEC,SAAS,EAAEC,OAAO,EAAE,GAAGP;IAE3F,MAAMQ,MAAsC;QAC1C,eAAe;YAAC;SAAS;QACzB,6EAA6E;QAC7E,6EAA6E;QAC7E,eAAe;YAAC;SAAS;QACzB,YAAY;YAAC;YAAU;YAA6B;SAAQ;QAC5D,eAAe;YAAC;SAAS;QACzB,aAAa,EAAE;QACf,WAAW;YAAC;YAAU;YAAS;SAAQ;QACvC,aAAa,EAAE;QACf,cAAc;YAAC;YAAU;SAAkB;QAC3C,aAAa;YAAC;YAAU;YAAmB;SAA+B;QAC1E,cAAc,EAAE;QAChB,mEAAmE;QACnE,YAAY;YAAC;SAAS;QACtB,mBAAmB;YAAC;SAAS;QAC7B,cAAc;YAAC;SAAS;IAC1B;IAEA,IAAIH,OAAO;QAACG,GAAG,CAAC,UAAU,CAACC,IAAI,CAACJ;IAAM;IAEtC,IAAIC,WAAW;QACbE,GAAG,CAAC,aAAa,CAACC,IAAI,CAAC;QACvBD,GAAG,CAAC,YAAY,CAACC,IAAI,CAAC;QACtBD,GAAG,CAAC,cAAc,CAACC,IAAI,CAAC;IAC1B;IAEA,IAAIR,WAAW;QACbO,GAAG,CAAC,aAAa,CAACC,IAAI,CAAC;QACvBD,GAAG,CAAC,cAAc,CAACC,IAAI,CAAC,oCAAoC;QAC5DD,GAAG,CAAC,UAAU,CAACC,IAAI,CAAC,oCAAoC;IAC1D;IAEA,IAAIF,SAAS;QACXC,GAAG,CAAC,YAAY,CAACC,IAAI,CAAC,2BAA2B;IACnD;IAEA,IAAIN,YAAY;QACdK,GAAG,CAAC,YAAY,CAACC,IAAI,CAAC,0BAA0B;QAChDD,GAAG,CAAC,aAAa,CAACC,IAAI,CAAC;QACvBD,GAAG,CAAC,UAAU,CAACC,IAAI,CAAC,4BAA4B;IAClD;IAEA,uBAAuB;IACvB,KAAK,MAAM,CAACC,KAAKC,OAAO,IAAIC,OAAOC,OAAO,CAACX,OAA2C;QACpF,IAAIS,UAAUA,OAAOG,MAAM,EAAE;YAACN,GAAG,CAACE,IAAI,GAAG;mBAAKF,GAAG,CAACE,IAAI,IAAI,EAAE;mBAAMC;aAAO;QAAA;IAC3E;IAEA,MAAMI,QAAQ,AAACH,OAAOC,OAAO,CAACL,KAC3BQ,MAAM,CAAC,CAAC,GAAGL,OAAO,GAAKA,OAAOG,MAAM,GAAG,GACvCG,GAAG,CAAC,CAAC,CAACP,KAAKC,OAAO,GAAK,GAAGD,IAAI,CAAC,EAAEC,OAAOO,IAAI,CAAC,MAAM,EACnDA,IAAI,CAAC;IAER,MAAMC,MACJf,SAAS,gBAAgB,wCAAwC;IACnE,OAAO;QAAEe;QAAKJ;IAAM;AACtB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/security/buildCsp.ts"],"sourcesContent":["export type BuildCspArgs = {\n /** Google Analytics / GTM — adds googletagmanager + google-analytics. */\n analytics?: boolean\n /** Extra sources per directive, merged with the built-ins. */\n extra?: Partial>\n /** Google Maps embeds — adds maps.google.com / *.gstatic.com. */\n googleMaps?: boolean\n /** 'enforce' → Content-Security-Policy; 'report-only' → …-Report-Only header. */\n mode?: 'enforce' | 'report-only'\n /** Media/R2 public URL (from R2_PUBLIC_URL) — added to img-src. */\n r2Url?: string\n /** Cloudflare Turnstile — adds challenges.cloudflare.com to script/frame/connect. */\n turnstile?: boolean\n /** YouTube embeds — adds youtube to frame-src. */\n youtube?: boolean\n}\n\ntype CspDirective =\n | 'base-uri'\n | 'connect-src'\n | 'default-src'\n | 'font-src'\n | 'form-action'\n | 'frame-ancestors'\n | 'frame-src'\n | 'img-src'\n | 'media-src'\n | 'object-src'\n | 'script-src'\n | 'style-src'\n | 'worker-src'\n\n/**\n * Builds a Content-Security-Policy string with the hard OWASP/Lighthouse-required\n * directives baked in, and opt-in sources for common third parties. Solves the\n * real risk of hand-writing raw CSP per project and forgetting `base-uri 'self'`\n * or `object-src 'none'`.\n *\n * CSP still lives in the project (it lists the project's own domains), but this\n * helper standardizes the skeleton so every project's CSP has the same hardened\n * base — you only flip flags for what the project actually loads.\n *\n * Returns { key, value } ready for buildSecurityHeaders `additional`:\n *\n * import { buildCsp, buildSecurityHeaders } from '@intecion/ipal-kit'\n * const csp = buildCsp({\n * mode: 'report-only', // start here; switch to 'enforce' when clean\n * r2Url: process.env.R2_PUBLIC_URL,\n * turnstile: true, analytics: true,\n * })\n * const headers = buildSecurityHeaders({ hsts: prod, additional: [csp] })\n *\n * Deploy CSP carefully: start with mode:'report-only', check the console for\n * violations across the whole site (forms/Turnstile, gallery/R2, embeds), add\n * missing sources via `extra`, THEN switch to 'enforce'. See docs/security.md.\n */\nexport function buildCsp(args: BuildCspArgs = {}): { key: string; value: string } {\n const { analytics, extra = {}, googleMaps, mode = 'enforce', r2Url, turnstile, youtube } = args\n\n const src: Record = {\n 'default-src': [\"'self'\"],\n // 'unsafe-inline' is hard to avoid with Next/analytics; 'unsafe-eval' is NOT\n // added by default (weakens CSP) — add via extra only if a library needs it.\n 'connect-src': [\"'self'\"],\n 'font-src': [\"'self'\", 'https://fonts.gstatic.com', 'data:'],\n 'form-action': [\"'self'\"],\n 'frame-src': [],\n 'img-src': [\"'self'\", 'data:', 'blob:'],\n 'media-src': [], // video/audio sources — filled via extra when needed\n 'script-src': [\"'self'\", \"'unsafe-inline'\"],\n 'style-src': [\"'self'\", \"'unsafe-inline'\", 'https://fonts.googleapis.com'],\n 'worker-src': [], // web workers — filled via extra when needed\n // HARD defaults (OWASP/Lighthouse) — always on, no reason to omit:\n 'base-uri': [\"'self'\"], // block hijacking\n 'frame-ancestors': [\"'none'\"], // clickjacking protection (replaces X-Frame-Options)\n 'object-src': [\"'none'\"], // block / (Flash-era attack surface)\n }\n\n // Site-relative R2_PUBLIC_URL ('/media', dev) is same-origin — already covered by 'self'.\n if (r2Url && /^https?:\\/\\//i.test(r2Url)) {src['img-src'].push(r2Url)}\n\n if (turnstile) {\n src['script-src'].push('https://challenges.cloudflare.com')\n src['frame-src'].push('https://challenges.cloudflare.com')\n src['connect-src'].push('https://challenges.cloudflare.com')\n }\n\n if (analytics) {\n src['script-src'].push('https://www.googletagmanager.com')\n src['connect-src'].push('https://www.google-analytics.com', 'https://www.googletagmanager.com')\n src['img-src'].push('https://www.google-analytics.com', 'https://www.googletagmanager.com')\n }\n\n if (youtube) {\n src['frame-src'].push('https://www.youtube.com', 'https://www.youtube-nocookie.com')\n }\n\n if (googleMaps) {\n src['frame-src'].push('https://www.google.com', 'https://maps.google.com')\n src['script-src'].push('https://maps.googleapis.com')\n src['img-src'].push('https://maps.gstatic.com', 'https://*.googleapis.com')\n }\n\n // Merge caller extras.\n for (const [dir, values] of Object.entries(extra) as Array<[CspDirective, string[]]>) {\n if (values && values.length) {src[dir] = [...(src[dir] ?? []), ...values]}\n }\n\n const value = (Object.entries(src) as Array<[CspDirective, string[]]>)\n .filter(([, values]) => values.length > 0)\n .map(([dir, values]) => `${dir} ${values.join(' ')}`)\n .join('; ')\n\n const key = mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy'\n return { key, value }\n}\n"],"names":["buildCsp","args","analytics","extra","googleMaps","mode","r2Url","turnstile","youtube","src","test","push","dir","values","Object","entries","length","value","filter","map","join","key"],"mappings":"AAgCA;;;;;;;;;;;;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,aAAa,CAACE,IAAI,CAAC;QACvBF,GAAG,CAAC,UAAU,CAACE,IAAI,CAAC,4BAA4B;IAClD;IAEA,uBAAuB;IACvB,KAAK,MAAM,CAACC,KAAKC,OAAO,IAAIC,OAAOC,OAAO,CAACZ,OAA2C;QACpF,IAAIU,UAAUA,OAAOG,MAAM,EAAE;YAACP,GAAG,CAACG,IAAI,GAAG;mBAAKH,GAAG,CAACG,IAAI,IAAI,EAAE;mBAAMC;aAAO;QAAA;IAC3E;IAEA,MAAMI,QAAQ,AAACH,OAAOC,OAAO,CAACN,KAC3BS,MAAM,CAAC,CAAC,GAAGL,OAAO,GAAKA,OAAOG,MAAM,GAAG,GACvCG,GAAG,CAAC,CAAC,CAACP,KAAKC,OAAO,GAAK,GAAGD,IAAI,CAAC,EAAEC,OAAOO,IAAI,CAAC,MAAM,EACnDA,IAAI,CAAC;IAER,MAAMC,MAAMhB,SAAS,gBAAgB,wCAAwC;IAC7E,OAAO;QAAEgB;QAAKJ;IAAM;AACtB"} \ No newline at end of file diff --git a/dist/modules/seo/routeHandlers.d.ts b/dist/modules/seo/routeHandlers.d.ts index d17d3e9..1a3b16b 100644 --- a/dist/modules/seo/routeHandlers.d.ts +++ b/dist/modules/seo/routeHandlers.d.ts @@ -56,4 +56,4 @@ export type SitemapRouteOptions = { * `GET /sitemap.xml` → XML (crawlers), `GET /sitemap.xml?style` → its CSS. * Don't keep app/sitemap.ts next to it — two sitemaps confuse crawlers. */ -export declare function createSitemapRouteHandler(sitemap: () => Promise, opts?: SitemapRouteOptions): (req?: Request) => Promise; +export declare function createSitemapRouteHandler(sitemap: () => Promise, opts?: SitemapRouteOptions): (req: Request) => Promise; diff --git a/dist/modules/seo/routeHandlers.js b/dist/modules/seo/routeHandlers.js index b698fd3..0c02128 100644 --- a/dist/modules/seo/routeHandlers.js +++ b/dist/modules/seo/routeHandlers.js @@ -61,9 +61,11 @@ import { buildSitemapCss, SITEMAP_STYLE_PARAM } from './sitemapStyle.js'; * Don't keep app/sitemap.ts next to it — two sitemaps confuse crawlers. */ export function createSitemapRouteHandler(sitemap, opts = {}) { const style = opts.cssUrl ? false : opts.style === false ? false : opts.style ?? {}; + // `req` is required: Next 16 type-checks the first argument of a route handler + // (`Request | undefined` fails the build). A zero-argument call is not supported. return async (req)=>{ - const url = req ? new URL(req.url) : null; - if (style && url?.searchParams.has(SITEMAP_STYLE_PARAM)) { + const url = new URL(req.url); + if (style && url.searchParams.has(SITEMAP_STYLE_PARAM)) { let title; try { title = typeof style.title === 'function' ? await style.title() : style.title; @@ -81,7 +83,7 @@ import { buildSitemapCss, SITEMAP_STYLE_PARAM } from './sitemapStyle.js'; } }); } - const cssUrl = opts.cssUrl ?? (style ? `${url?.pathname ?? '/sitemap.xml'}?${SITEMAP_STYLE_PARAM}` : undefined); + const cssUrl = opts.cssUrl ?? (style ? `${url.pathname}?${SITEMAP_STYLE_PARAM}` : undefined); try { const entries = await sitemap(); const xml = buildSitemapXml(entries, { diff --git a/dist/modules/seo/routeHandlers.js.map b/dist/modules/seo/routeHandlers.js.map index 5292462..a31e214 100644 --- a/dist/modules/seo/routeHandlers.js.map +++ b/dist/modules/seo/routeHandlers.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/seo/routeHandlers.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\nimport type { SitemapEntry } from './buildSitemapEntries.js'\n\nimport { buildLlmsTxt } from './buildLlmsTxt.js'\nimport { buildSitemapXml } from './buildSitemapXml.js'\nimport { buildSitemapCss, SITEMAP_STYLE_PARAM, type SitemapStyleOptions } from './sitemapStyle.js'\n\n/**\n * Ready-made Next route handler for /llms.txt. Replaces the ~60-line try/catch\n * every project was copying. buildLlmsTxt already handles collections without\n * drafts, so no workaround is needed here.\n *\n * // app/llms.txt/route.ts\n * import { createLlmsTxtRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })\n *\n * For the full-content variant, add a second route with `full: true`:\n *\n * // app/llms-full.txt/route.ts\n * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, full: true })\n */\nexport function createLlmsTxtRoute(opts: {\n baseUrl: string\n config: I18nConfig\n /** Inline every page's full Markdown (llms-full.txt). Default false. */\n full?: boolean\n getCachedPayload: () => Promise\n pagesSlug?: string\n settingsSlug?: string\n /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */\n summaryField?: string\n}): () => Promise {\n return async () => {\n try {\n const payload = await opts.getCachedPayload()\n const body = await buildLlmsTxt({\n baseUrl: opts.baseUrl,\n config: opts.config,\n full: opts.full,\n pagesSlug: opts.pagesSlug,\n payload,\n settingsSlug: opts.settingsSlug,\n summaryField: opts.summaryField,\n })\n return new Response(body, {\n headers: { 'Content-Type': 'text/plain; charset=utf-8' },\n })\n } catch (err) {\n // DB unreachable at build (container) — return a minimal valid file so the\n // route doesn't 500; it fills in at runtime. No per-project try/catch.\n console.warn('[ipal] createLlmsTxtRoute: could not build llms.txt:', err)\n return new Response('# llms.txt\\n', {\n headers: { 'Content-Type': 'text/plain; charset=utf-8' },\n })\n }\n }\n}\n\nexport type SitemapRouteOptions = {\n /** Legacy: your own stylesheet URL (e.g. '/sitemap.css'). Overrides `style`. */\n cssUrl?: string\n /**\n * Built-in browser look (default ON): the XML points at `?style`\n * and the same handler serves the CSS — nothing to copy into /public.\n * `false` = raw XML. Object = header/credit/accent (SitemapStyleOptions);\n * `title` may be async (sitemapRoute passes the Site Settings name).\n */\n style?: ({ title?: (() => Promise) | string } & Omit) | false\n}\n\n/**\n * Ready-made Next route handler for /sitemap.xml, styled for humans out of the box.\n * Usually you don't call this — `createContentHelpers` returns `sitemapRoute`:\n *\n * // app/sitemap.xml/route.ts — the whole file\n * export { sitemapRoute as GET } from '@/lib/content'\n * export const dynamic = 'force-dynamic'\n *\n * `GET /sitemap.xml` → XML (crawlers), `GET /sitemap.xml?style` → its CSS.\n * Don't keep app/sitemap.ts next to it — two sitemaps confuse crawlers.\n */\nexport function createSitemapRouteHandler(\n sitemap: () => Promise,\n opts: SitemapRouteOptions = {},\n): (req?: Request) => Promise {\n const style = opts.cssUrl ? false : opts.style === false ? false : (opts.style ?? {})\n\n return async (req?: Request) => {\n const url = req ? new URL(req.url) : null\n\n if (style && url?.searchParams.has(SITEMAP_STYLE_PARAM)) {\n let title: string | undefined\n try {\n title = typeof style.title === 'function' ? await style.title() : style.title\n } catch {\n title = undefined // DB down → generic heading, never a broken stylesheet\n }\n return new Response(buildSitemapCss({ ...style, title }), {\n headers: {\n 'Cache-Control': 'public, max-age=3600',\n 'Content-Type': 'text/css; charset=utf-8',\n 'X-Robots-Tag': 'noindex',\n },\n })\n }\n\n const cssUrl = opts.cssUrl ?? (style ? `${url?.pathname ?? '/sitemap.xml'}?${SITEMAP_STYLE_PARAM}` : undefined)\n try {\n const entries = await sitemap()\n const xml = buildSitemapXml(entries, { cssUrl })\n return new Response(xml, {\n headers: { 'Content-Type': 'application/xml; charset=utf-8' },\n })\n } catch (err) {\n console.warn('[ipal] createSitemapRouteHandler: could not build sitemap:', err)\n // Valid empty urlset so the route doesn't 500 during a DB-less build.\n const empty =\n '\\n' +\n ''\n return new Response(empty, {\n headers: { 'Content-Type': 'application/xml; charset=utf-8' },\n })\n }\n }\n}\n"],"names":["buildLlmsTxt","buildSitemapXml","buildSitemapCss","SITEMAP_STYLE_PARAM","createLlmsTxtRoute","opts","payload","getCachedPayload","body","baseUrl","config","full","pagesSlug","settingsSlug","summaryField","Response","headers","err","console","warn","createSitemapRouteHandler","sitemap","style","cssUrl","req","url","URL","searchParams","has","title","undefined","pathname","entries","xml","empty"],"mappings":"AAKA,SAASA,YAAY,QAAQ,oBAAmB;AAChD,SAASC,eAAe,QA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YAAM,IAAI;gBACxDb,SAAS;oBACP,iBAAiB;oBACjB,gBAAgB;oBAChB,gBAAgB;gBAClB;YACF;QACF;QAEA,MAAMO,SAASlB,KAAKkB,MAAM,IAAKD,CAAAA,QAAQ,GAAGG,KAAKM,YAAY,eAAe,CAAC,EAAE5B,qBAAqB,GAAG2B,SAAQ;QAC7G,IAAI;YACF,MAAME,UAAU,MAAMX;YACtB,MAAMY,MAAMhC,gBAAgB+B,SAAS;gBAAET;YAAO;YAC9C,OAAO,IAAIR,SAASkB,KAAK;gBACvBjB,SAAS;oBAAE,gBAAgB;gBAAiC;YAC9D;QACF,EAAE,OAAOC,KAAK;YACZC,QAAQC,IAAI,CAAC,8DAA8DF;YAC3E,sEAAsE;YACtE,MAAMiB,QACJ,6CACA;YACF,OAAO,IAAInB,SAASmB,OAAO;gBACzBlB,SAAS;oBAAE,gBAAgB;gBAAiC;YAC9D;QACF;IACF;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/seo/routeHandlers.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\nimport type { SitemapEntry } from './buildSitemapEntries.js'\n\nimport { buildLlmsTxt } from './buildLlmsTxt.js'\nimport { buildSitemapXml } from './buildSitemapXml.js'\nimport { buildSitemapCss, SITEMAP_STYLE_PARAM, type SitemapStyleOptions } from './sitemapStyle.js'\n\n/**\n * Ready-made Next route handler for /llms.txt. Replaces the ~60-line try/catch\n * every project was copying. buildLlmsTxt already handles collections without\n * drafts, so no workaround is needed here.\n *\n * // app/llms.txt/route.ts\n * import { createLlmsTxtRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })\n *\n * For the full-content variant, add a second route with `full: true`:\n *\n * // app/llms-full.txt/route.ts\n * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, full: true })\n */\nexport function createLlmsTxtRoute(opts: {\n baseUrl: string\n config: I18nConfig\n /** Inline every page's full Markdown (llms-full.txt). Default false. */\n full?: boolean\n getCachedPayload: () => Promise\n pagesSlug?: string\n settingsSlug?: string\n /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */\n summaryField?: string\n}): () => Promise {\n return async () => {\n try {\n const payload = await opts.getCachedPayload()\n const body = await buildLlmsTxt({\n baseUrl: opts.baseUrl,\n config: opts.config,\n full: opts.full,\n pagesSlug: opts.pagesSlug,\n payload,\n settingsSlug: opts.settingsSlug,\n summaryField: opts.summaryField,\n })\n return new Response(body, {\n headers: { 'Content-Type': 'text/plain; charset=utf-8' },\n })\n } catch (err) {\n // DB unreachable at build (container) — return a minimal valid file so the\n // route doesn't 500; it fills in at runtime. No per-project try/catch.\n console.warn('[ipal] createLlmsTxtRoute: could not build llms.txt:', err)\n return new Response('# llms.txt\\n', {\n headers: { 'Content-Type': 'text/plain; charset=utf-8' },\n })\n }\n }\n}\n\nexport type SitemapRouteOptions = {\n /** Legacy: your own stylesheet URL (e.g. '/sitemap.css'). Overrides `style`. */\n cssUrl?: string\n /**\n * Built-in browser look (default ON): the XML points at `?style`\n * and the same handler serves the CSS — nothing to copy into /public.\n * `false` = raw XML. Object = header/credit/accent (SitemapStyleOptions);\n * `title` may be async (sitemapRoute passes the Site Settings name).\n */\n style?: ({ title?: (() => Promise) | string } & Omit) | false\n}\n\n/**\n * Ready-made Next route handler for /sitemap.xml, styled for humans out of the box.\n * Usually you don't call this — `createContentHelpers` returns `sitemapRoute`:\n *\n * // app/sitemap.xml/route.ts — the whole file\n * export { sitemapRoute as GET } from '@/lib/content'\n * export const dynamic = 'force-dynamic'\n *\n * `GET /sitemap.xml` → XML (crawlers), `GET /sitemap.xml?style` → its CSS.\n * Don't keep app/sitemap.ts next to it — two sitemaps confuse crawlers.\n */\nexport function createSitemapRouteHandler(\n sitemap: () => Promise,\n opts: SitemapRouteOptions = {},\n): (req: Request) => Promise {\n const style = opts.cssUrl ? false : opts.style === false ? false : (opts.style ?? {})\n\n // `req` is required: Next 16 type-checks the first argument of a route handler\n // (`Request | undefined` fails the build). A zero-argument call is not supported.\n return async (req: Request) => {\n const url = new URL(req.url)\n\n if (style && url.searchParams.has(SITEMAP_STYLE_PARAM)) {\n let title: string | undefined\n try {\n title = typeof style.title === 'function' ? await style.title() : style.title\n } catch {\n title = undefined // DB down → generic heading, never a broken stylesheet\n }\n return new Response(buildSitemapCss({ ...style, title }), {\n headers: {\n 'Cache-Control': 'public, max-age=3600',\n 'Content-Type': 'text/css; charset=utf-8',\n 'X-Robots-Tag': 'noindex',\n },\n })\n }\n\n const cssUrl = opts.cssUrl ?? (style ? `${url.pathname}?${SITEMAP_STYLE_PARAM}` : undefined)\n try {\n const entries = await sitemap()\n const xml = buildSitemapXml(entries, { cssUrl })\n return new Response(xml, {\n headers: { 'Content-Type': 'application/xml; charset=utf-8' },\n })\n } catch (err) {\n console.warn('[ipal] createSitemapRouteHandler: could not build sitemap:', err)\n // Valid empty urlset so the route doesn't 500 during a DB-less build.\n const empty =\n '\\n' +\n ''\n return new Response(empty, {\n headers: { 'Content-Type': 'application/xml; charset=utf-8' },\n })\n }\n }\n}\n"],"names":["buildLlmsTxt","buildSitemapXml","buildSitemapCss","SITEMAP_STYLE_PARAM","createLlmsTxtRoute","opts","payload","getCachedPayload","body","baseUrl","config","full","pagesSlug","settingsSlug","summaryField","Response","headers","err","console","warn","createSitemapRouteHandler","sitemap","style","cssUrl","req","url","URL","searchParams","has","title","undefined","pathname","entries","xml","empty"],"mappings":"AAKA,SAASA,YAAY,QAAQ,oBAAmB;AAChD,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,eAAe,EAAEC,mBAAmB,QAAkC,oBAAmB;AAElG;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC,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ACF;QAEA,MAAMO,SAASlB,KAAKkB,MAAM,IAAKD,CAAAA,QAAQ,GAAGG,IAAIM,QAAQ,CAAC,CAAC,EAAE5B,qBAAqB,GAAG2B,SAAQ;QAC1F,IAAI;YACF,MAAME,UAAU,MAAMX;YACtB,MAAMY,MAAMhC,gBAAgB+B,SAAS;gBAAET;YAAO;YAC9C,OAAO,IAAIR,SAASkB,KAAK;gBACvBjB,SAAS;oBAAE,gBAAgB;gBAAiC;YAC9D;QACF,EAAE,OAAOC,KAAK;YACZC,QAAQC,IAAI,CAAC,8DAA8DF;YAC3E,sEAAsE;YACtE,MAAMiB,QACJ,6CACA;YACF,OAAO,IAAInB,SAASmB,OAAO;gBACzBlB,SAAS;oBAAE,gBAAgB;gBAAiC;YAC9D;QACF;IACF;AACF"} \ No newline at end of file diff --git a/dist/modules/storage/buildR2Storage.js b/dist/modules/storage/buildR2Storage.js index 86f9630..4268bb6 100644 --- a/dist/modules/storage/buildR2Storage.js +++ b/dist/modules/storage/buildR2Storage.js @@ -45,8 +45,12 @@ // (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs // pointing there. Without it, uploads work but images don't display publicly. // See docs/storage.md. - const publicUrl = process.env.R2_PUBLIC_URL?.replace(/\/$/, '') // strip trailing slash + // Site-relative value ('/media', dev only — ipalEnvRules rejects it in production) + // → prefixed with NEXT_PUBLIC_SERVER_URL so Payload still stores absolute URLs. + const rawPublicUrl = process.env.R2_PUBLIC_URL?.trim().replace(/\/$/, '') // strip trailing slash ; + const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL?.trim().replace(/\/$/, ''); + const publicUrl = rawPublicUrl?.startsWith('/') && serverUrl ? `${serverUrl}${rawPublicUrl}` : rawPublicUrl; // generateFileURL is a PER-COLLECTION option in @payloadcms/storage-s3 (not a // top-level one) — R2 needs it to point served URLs at the custom domain // instead of the private S3 endpoint. Each collection gets either `true` diff --git a/dist/modules/storage/buildR2Storage.js.map b/dist/modules/storage/buildR2Storage.js.map index 192145a..083b698 100644 --- a/dist/modules/storage/buildR2Storage.js.map +++ b/dist/modules/storage/buildR2Storage.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/storage/buildR2Storage.ts"],"sourcesContent":["import type { Plugin } from 'payload'\n\ntype GenerateFileURL = (args: { filename: string; prefix?: string }) => string\n\n/**\n * Minimal shape of `s3Storage` from @payloadcms/storage-s3 — the plugin never\n * imports that package (it's optional: projects on local disk don't install it).\n * The project injects the real function; TypeScript checks it fits this shape.\n */\nexport type S3StorageFactory = (options: {\n bucket: string\n collections: Record\n config: {\n credentials: { accessKeyId: string; secretAccessKey: string }\n endpoint: string\n forcePathStyle: boolean\n region: string\n }\n}) => Plugin\n\nexport type BuildR2StorageDeps = {\n /** `import { s3Storage } from '@payloadcms/storage-s3'` — required when R2 env is set. */\n s3Storage?: S3StorageFactory\n}\n\n/**\n * Cloudflare R2 media storage — configured from environment variables (agency\n * infrastructure, not per-project panel data). R2 is S3-compatible, so we use\n * @payloadcms/storage-s3 pointed at the R2 endpoint.\n *\n * Storage is infrastructure (like the database or PAYLOAD_SECRET): it binds at\n * boot, and its credentials are agency-owned — so it lives in .env, not the\n * panel. See docs/storage.md for the required variables.\n *\n * Returns the storage plugin when all R2 vars are present; otherwise returns a\n * no-op passthrough so the project falls back to Payload's default local disk\n * storage (useful in dev without R2). This mirrors how mailAdapter degrades\n * gracefully when a transport isn't configured.\n *\n * The S3 adapter is INJECTED by the project (same pattern as 2FA / NextResponse):\n *\n * import { s3Storage } from '@payloadcms/storage-s3'\n * plugins: [buildR2Storage(['media'], { s3Storage })]\n *\n * A static import here would make @payloadcms/storage-s3 mandatory for every\n * project — including ones on local disk — because this module is exported\n * from the package's main entry.\n *\n * @param collections - slugs of upload collections to offload to R2 (e.g. ['media'])\n * @param deps - `{ s3Storage }` from @payloadcms/storage-s3 (needed only when R2 env is set)\n */\nexport const buildR2Storage = (\n collections: string[] = ['media'],\n deps: BuildR2StorageDeps = {},\n): Plugin => {\n const bucket = process.env.R2_BUCKET\n const endpoint = process.env.R2_ENDPOINT\n const accessKeyId = process.env.R2_ACCESS_KEY_ID\n const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY\n\n // Any missing → skip R2, fall back to local disk. Warn so it's not silent.\n if (!bucket || !endpoint || !accessKeyId || !secretAccessKey) {\n return (config) => {\n // Only warn when SOME vars are set (partial config = likely a mistake).\n if (bucket || endpoint || accessKeyId || secretAccessKey) {\n console.warn(\n '[ipal] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' +\n 'R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). Falling back to local disk.',\n )\n }\n return config\n }\n }\n\n // Public URL for served media. R2 is private by default; its S3 endpoint only\n // accepts uploads and won't serve files (403). With a custom domain\n // (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs\n // pointing there. Without it, uploads work but images don't display publicly.\n // See docs/storage.md.\n const publicUrl = process.env.R2_PUBLIC_URL?.replace(/\\/$/, '') // strip trailing slash\n\n // generateFileURL is a PER-COLLECTION option in @payloadcms/storage-s3 (not a\n // top-level one) — R2 needs it to point served URLs at the custom domain\n // instead of the private S3 endpoint. Each collection gets either `true`\n // (plain offload) or an object carrying generateFileURL when a public URL is set.\n const generateFileURL = publicUrl\n ? ({ filename, prefix }: { filename: string; prefix?: string }) =>\n [publicUrl, prefix, filename].filter(Boolean).join('/')\n : undefined\n\n // R2 env is complete → the adapter is required. Fail loudly at boot rather\n // than silently storing media on the container disk (lost on redeploy).\n const { s3Storage } = deps\n if (!s3Storage) {\n throw new Error(\n '[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' +\n \"Install @payloadcms/storage-s3 and pass it: buildR2Storage(['media'], { s3Storage }) \" +\n \"with `import { s3Storage } from '@payloadcms/storage-s3'`. See docs/storage.md.\",\n )\n }\n\n const collectionsConfig: Record = {}\n for (const slug of collections) {\n collectionsConfig[slug] = generateFileURL ? { generateFileURL } : true\n }\n\n return s3Storage({\n bucket,\n collections: collectionsConfig,\n config: {\n credentials: { accessKeyId, secretAccessKey },\n endpoint,\n region: 'auto', // R2 uses 'auto'\n // R2 requires path-style addressing for S3 compatibility.\n forcePathStyle: true,\n },\n })\n}\n"],"names":["buildR2Storage","collections","deps","bucket","process","env","R2_BUCKET","endpoint","R2_ENDPOINT","accessKeyId","R2_ACCESS_KEY_ID","secretAccessKey","R2_SECRET_ACCESS_KEY","config","console","warn","publicUrl","R2_PUBLIC_URL","replace","generateFileURL","filename","prefix","filter","Boolean","join","undefined","s3Storage","Error","collectionsConfig","slug","credentials","region","forcePathStyle"],"mappings":"AAyBA;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GACD,OAAO,MAAMA,iBAAiB,CAC5BC,cAAwB;IAAC;CAAQ,EACjCC,OAA2B,CAAC,CAAC;IAE7B,MAAMC,SAASC,QAAQC,GAAG,CAACC,SAAS;IACpC,MAAMC,WAAWH,QAAQC,GAAG,CAACG,WAAW;IACxC,MAAMC,cAAcL,QAAQC,GAAG,CAACK,gBAAgB;IAChD,MAAMC,kBAAkBP,QAAQC,GAAG,CAACO,oBAAoB;IAExD,2EAA2E;IAC3E,IAAI,CAACT,UAAU,CAACI,YAAY,CAACE,eAAe,CAACE,iBAAiB;QAC5D,OAAO,CAACE;YACN,wEAAwE;YACxE,IAAIV,UAAUI,YAAYE,eAAeE,iBAAiB;gBACxDG,QAAQC,IAAI,CACV,qEACE;YAEN;YACA,OAAOF;QACT;IACF;IAEA,8EAA8E;IAC9E,oEAAoE;IACpE,yEAAyE;IACzE,8EAA8E;IAC9E,uBAAuB;IACvB,MAAMG,YAAYZ,QAAQC,GAAG,CAACY,aAAa,EAAEC,QAAQ,OAAO,IAAI,uBAAuB;;IAEvF,8EAA8E;IAC9E,yEAAyE;IACzE,yEAAyE;IACzE,kFAAkF;IAClF,MAAMC,kBAAkBH,YACpB,CAAC,EAAEI,QAAQ,EAAEC,MAAM,EAAyC,GAC1D;YAACL;YAAWK;YAAQD;SAAS,CAACE,MAAM,CAACC,SAASC,IAAI,CAAC,OACrDC;IAEJ,2EAA2E;IAC3E,wEAAwE;IACxE,MAAM,EAAEC,SAAS,EAAE,GAAGxB;IACtB,IAAI,CAACwB,WAAW;QACd,MAAM,IAAIC,MACR,6EACE,0FACA;IAEN;IAEA,MAAMC,oBAAiF,CAAC;IACxF,KAAK,MAAMC,QAAQ5B,YAAa;QAC9B2B,iBAAiB,CAACC,KAAK,GAAGV,kBAAkB;YAAEA;QAAgB,IAAI;IACpE;IAEA,OAAOO,UAAU;QACfvB;QACAF,aAAa2B;QACbf,QAAQ;YACNiB,aAAa;gBAAErB;gBAAaE;YAAgB;YAC5CJ;YACAwB,QAAQ;YACR,0DAA0D;YAC1DC,gBAAgB;QAClB;IACF;AACF,EAAC"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/storage/buildR2Storage.ts"],"sourcesContent":["import type { Plugin } from 'payload'\n\ntype GenerateFileURL = (args: { filename: string; prefix?: string }) => string\n\n/**\n * Minimal shape of `s3Storage` from @payloadcms/storage-s3 — the plugin never\n * imports that package (it's optional: projects on local disk don't install it).\n * The project injects the real function; TypeScript checks it fits this shape.\n */\nexport type S3StorageFactory = (options: {\n bucket: string\n collections: Record\n config: {\n credentials: { accessKeyId: string; secretAccessKey: string }\n endpoint: string\n forcePathStyle: boolean\n region: string\n }\n}) => Plugin\n\nexport type BuildR2StorageDeps = {\n /** `import { s3Storage } from '@payloadcms/storage-s3'` — required when R2 env is set. */\n s3Storage?: S3StorageFactory\n}\n\n/**\n * Cloudflare R2 media storage — configured from environment variables (agency\n * infrastructure, not per-project panel data). R2 is S3-compatible, so we use\n * @payloadcms/storage-s3 pointed at the R2 endpoint.\n *\n * Storage is infrastructure (like the database or PAYLOAD_SECRET): it binds at\n * boot, and its credentials are agency-owned — so it lives in .env, not the\n * panel. See docs/storage.md for the required variables.\n *\n * Returns the storage plugin when all R2 vars are present; otherwise returns a\n * no-op passthrough so the project falls back to Payload's default local disk\n * storage (useful in dev without R2). This mirrors how mailAdapter degrades\n * gracefully when a transport isn't configured.\n *\n * The S3 adapter is INJECTED by the project (same pattern as 2FA / NextResponse):\n *\n * import { s3Storage } from '@payloadcms/storage-s3'\n * plugins: [buildR2Storage(['media'], { s3Storage })]\n *\n * A static import here would make @payloadcms/storage-s3 mandatory for every\n * project — including ones on local disk — because this module is exported\n * from the package's main entry.\n *\n * @param collections - slugs of upload collections to offload to R2 (e.g. ['media'])\n * @param deps - `{ s3Storage }` from @payloadcms/storage-s3 (needed only when R2 env is set)\n */\nexport const buildR2Storage = (\n collections: string[] = ['media'],\n deps: BuildR2StorageDeps = {},\n): Plugin => {\n const bucket = process.env.R2_BUCKET\n const endpoint = process.env.R2_ENDPOINT\n const accessKeyId = process.env.R2_ACCESS_KEY_ID\n const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY\n\n // Any missing → skip R2, fall back to local disk. Warn so it's not silent.\n if (!bucket || !endpoint || !accessKeyId || !secretAccessKey) {\n return (config) => {\n // Only warn when SOME vars are set (partial config = likely a mistake).\n if (bucket || endpoint || accessKeyId || secretAccessKey) {\n console.warn(\n '[ipal] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' +\n 'R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). Falling back to local disk.',\n )\n }\n return config\n }\n }\n\n // Public URL for served media. R2 is private by default; its S3 endpoint only\n // accepts uploads and won't serve files (403). With a custom domain\n // (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs\n // pointing there. Without it, uploads work but images don't display publicly.\n // See docs/storage.md.\n // Site-relative value ('/media', dev only — ipalEnvRules rejects it in production)\n // → prefixed with NEXT_PUBLIC_SERVER_URL so Payload still stores absolute URLs.\n const rawPublicUrl = process.env.R2_PUBLIC_URL?.trim().replace(/\\/$/, '') // strip trailing slash\n const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL?.trim().replace(/\\/$/, '')\n const publicUrl =\n rawPublicUrl?.startsWith('/') && serverUrl ? `${serverUrl}${rawPublicUrl}` : rawPublicUrl\n\n // generateFileURL is a PER-COLLECTION option in @payloadcms/storage-s3 (not a\n // top-level one) — R2 needs it to point served URLs at the custom domain\n // instead of the private S3 endpoint. Each collection gets either `true`\n // (plain offload) or an object carrying generateFileURL when a public URL is set.\n const generateFileURL = publicUrl\n ? ({ filename, prefix }: { filename: string; prefix?: string }) =>\n [publicUrl, prefix, filename].filter(Boolean).join('/')\n : undefined\n\n // R2 env is complete → the adapter is required. Fail loudly at boot rather\n // than silently storing media on the container disk (lost on redeploy).\n const { s3Storage } = deps\n if (!s3Storage) {\n throw new Error(\n '[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' +\n \"Install @payloadcms/storage-s3 and pass it: buildR2Storage(['media'], { s3Storage }) \" +\n \"with `import { s3Storage } from '@payloadcms/storage-s3'`. See docs/storage.md.\",\n )\n }\n\n const collectionsConfig: Record = {}\n for (const slug of collections) {\n collectionsConfig[slug] = generateFileURL ? { generateFileURL } : true\n }\n\n return s3Storage({\n bucket,\n collections: collectionsConfig,\n config: {\n credentials: { accessKeyId, secretAccessKey },\n endpoint,\n region: 'auto', // R2 uses 'auto'\n // R2 requires path-style addressing for S3 compatibility.\n forcePathStyle: true,\n },\n })\n}\n"],"names":["buildR2Storage","collections","deps","bucket","process","env","R2_BUCKET","endpoint","R2_ENDPOINT","accessKeyId","R2_ACCESS_KEY_ID","secretAccessKey","R2_SECRET_ACCESS_KEY","config","console","warn","rawPublicUrl","R2_PUBLIC_URL","trim","replace","serverUrl","NEXT_PUBLIC_SERVER_URL","publicUrl","startsWith","generateFileURL","filename","prefix","filter","Boolean","join","undefined","s3Storage","Error","collectionsConfig","slug","credentials","region","forcePathStyle"],"mappings":"AAyBA;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GACD,OAAO,MAAMA,iBAAiB,CAC5BC,cAAwB;IAAC;CAAQ,EACjCC,OAA2B,CAAC,CAAC;IAE7B,MAAMC,SAASC,QAAQC,GAAG,CAACC,SAAS;IACpC,MAA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YACNsB,aAAa;gBAAE1B;gBAAaE;YAAgB;YAC5CJ;YACA6B,QAAQ;YACR,0DAA0D;YAC1DC,gBAAgB;QAClB;IACF;AACF,EAAC"} \ No newline at end of file diff --git a/dist/styles/fluid.css b/dist/styles/fluid.css new file mode 100644 index 0000000..b7cedf8 --- /dev/null +++ b/dist/styles/fluid.css @@ -0,0 +1,34 @@ +/* + * @intecion/ipal-kit/fluid.css — fluid type & spacing scale (variables only, no classes). + * Scales smoothly from a 360px to a 1280px viewport; rem-based, so browser zoom and + * user font size still work (WCAG 1.4.4). Opt-in: + * + * @import "tailwindcss"; + * @import "@intecion/ipal-kit/fluid.css"; + * @theme inline { + * --text-display: var(--ipal-fs-display); + * --text-h1: var(--ipal-fs-h1); + * --text-h2: var(--ipal-fs-h2); + * --text-h3: var(--ipal-fs-h3); + * --text-lead: var(--ipal-fs-lg); + * --spacing-section: var(--ipal-space-section); + * --spacing-gutter: var(--ipal-space-gutter); + * --spacing-gap: var(--ipal-space-gap); + * } + * → text-h1, text-display, py-section, px-gutter, gap-gap + * + * The design (DESIGN.md) decides the numbers: override any variable in the project's + * :root — the plugin only removes the clamp() maths from every project. + */ +:root { + --ipal-fs-sm: clamp(0.875rem, 0.8505rem + 0.1087vw, 0.9375rem); /* 0.875→0.9375rem · small print, captions */ + --ipal-fs-base: clamp(1rem, 0.9511rem + 0.2174vw, 1.125rem); /* 1→1.125rem · body text */ + --ipal-fs-lg: clamp(1.125rem, 1.0272rem + 0.4348vw, 1.375rem); /* 1.125→1.375rem · lead / intro */ + --ipal-fs-h3: clamp(1.25rem, 1.0543rem + 0.8696vw, 1.75rem); /* 1.25→1.75rem · h3 */ + --ipal-fs-h2: clamp(1.5rem, 1.1087rem + 1.7391vw, 2.5rem); /* 1.5→2.5rem · h2 — section headings */ + --ipal-fs-h1: clamp(2rem, 1.413rem + 2.6087vw, 3.5rem); /* 2→3.5rem · h1 — page heading */ + --ipal-fs-display: clamp(2.5rem, 1.7174rem + 3.4783vw, 4.5rem); /* 2.5→4.5rem · hero / display */ + --ipal-space-gap: clamp(1rem, 0.6087rem + 1.7391vw, 2rem); /* 1→2rem · gap between items in a section */ + --ipal-space-gutter: clamp(1rem, 0.413rem + 2.6087vw, 2.5rem); /* 1→2.5rem · container side padding */ + --ipal-space-section: clamp(3rem, 1.2391rem + 7.8261vw, 7.5rem); /* 3→7.5rem · vertical padding of a section */ +} diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 5c6db07..f97f841 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -168,7 +168,7 @@ src/ sitemap.xml/route.ts # sitemapRoute z lib/content + force-dynamic (wygląd z pluginu) robots.ts # z lib/content api/health/route.ts # createHealthRoute - instrumentation.ts # assertEnv(ipalEnvRules({...})) + instrumentation.ts # assertEnv(ipalEnvRules({...})) z '@intecion/ipal-kit/env' fields/ # sectionHeader.ts, sectionSettings.ts (linki: z pluginu) components/ ui/ # prymitywy: CMSLink, Button, Media, Section, SectionHeader @@ -221,7 +221,7 @@ Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`, 7. **`export const dynamic = 'force-dynamic'`** na trasach czytających bazę: `manifest.ts`, `sitemap.xml/route.ts`, `llms.txt`, `api/health`. Handlery pluginu mają try/catch, ale `dynamic` musi być w pliku trasy. -8. **`instrumentation.ts`** z `assertEnv(ipalEnvRules({...}))` (env.md). +8. **`instrumentation.ts`** z `assertEnv(ipalEnvRules({...}))` importowanym z **`@intecion/ipal-kit/env`** (root ciągnie Payload → crash Edge/Turbopack), w `if (process.env.NEXT_RUNTIME === 'nodejs')` (env.md). 9. **RSC domyślnie.** `'use client'` tylko dla stanu/interakcji, w osobnym pliku; sekcja zostaje serwerowa i podaje mu dane. Sekrety: `import 'server-only'`. 10. **Bloki nie importują `lib/*`** (cykl). Dane server-side → `enhanceProps`. @@ -535,6 +535,10 @@ bloku nie importował Reacta). Kod: [kod-sekcji.md](./skills/ipal-block/resource ze źródła `DESIGN.md`. W komponentach tylko tokeny (`bg-primary`), **nigdy** `bg-[#ff6600]` ani hex. - Tokeny pluginu mapuj na projekt: `--ipal-primary: var(--color-primary)`. +- Płynna typografia i odstępy: `@import "@intecion/ipal-kit/fluid.css"` + mapowanie w + `@theme` (`text-h1`, `py-section`, `px-gutter` — PROGRAMISTA §2.5). Nie pisz `clamp()` + w komponentach; inne wartości z `DESIGN.md` → nadpisz zmienne `--ipal-*` w `:root`. +- JSON-LD tylko przez `` z `/rsc` — nigdy własny `" typed in the panel breaks out of the tag) → JsonLdGraph from /rsc +// - inline JSON-LD with escaping → WARNING (works; JsonLdGraph is the shared version) +// - anything else → WARNING (rich text → RenderRichText; other HTML must be sanitized) +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { join } from 'node:path' + +const files = [] +const walk = (p) => { + let st + try { st = statSync(p) } catch { return } + if (st.isDirectory()) { if (!/node_modules|\.next/.test(p)) for (const n of readdirSync(p)) walk(join(p, n)) } + else if (/\.(tsx|jsx)$/.test(p)) files.push(p) +} +process.argv.slice(2).forEach(walk) + +for (const file of files) { + // blank out comments (keeps offsets/line numbers) + const src = readFileSync(file, 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, ' ')) + .replace(/(^|[^:'"`])\/\/.*$/gm, (c, p) => p + ' '.repeat(c.length - p.length)) + for (const m of src.matchAll(/dangerouslySetInnerHTML/g)) { + // the element this prop belongs to: from its opening " from @intecion/ipal-kit/rsc (seo.md)|${at}`) + else console.log(`ERROR|unescaped JSON-LD in " in panel text; use from @intecion/ipal-kit/rsc|${at}`) + } else { + console.log(`WARNING|raw HTML (dangerouslySetInnerHTML) — rich text → RenderRichText; other HTML must be sanitized|${at}`) + } + } +} diff --git a/docs/agent/skills/ipal-debug/SKILL.md b/docs/agent/skills/ipal-debug/SKILL.md index 3c224d3..fbcd8c0 100644 --- a/docs/agent/skills/ipal-debug/SKILL.md +++ b/docs/agent/skills/ipal-debug/SKILL.md @@ -43,6 +43,8 @@ tej procedury. Pytasz tylko, gdy brakuje czegoś, czego nie możesz uzyskać sam | build pada `ENOTFOUND` / Mongoose | trasa czyta bazę w buildzie bez bazy | sitemap/robots/llms: `export const dynamic = 'force-dynamic'` (tylko one) | | `slug.join is not a function` | `[slug]` zamiast `[[...slug]]` | zmień nazwę folderu | | `Missing and ` | layout `[locale]` bez `` po usunięciu root layoutu | `` i `` w `[locale]/layout.tsx` | +| `Export fileTypeFromFile doesn't exist in target module` (Turbopack, start dev) | `instrumentation.ts` importuje z roota pakietu → Payload w bundlu Edge | import z `@intecion/ipal-kit/env` + `NEXT_RUNTIME === 'nodejs'` (env.md) | +| `R2_PUBLIC_URL must be a valid URL (got "/media")` | stara wersja reguły / produkcja ze ścieżką względną | dev: `/media` dozwolone od nowej wersji; produkcja: pełny URL domeny bucketu | | `server-only` w kliencie | import z `@intecion/ipal-kit/server` w `'use client'` | wywołuj przez server action | ### Panel (`/admin`) diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index 8cdb728..ec7a9f4 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -32,7 +32,7 @@ tylko, gdy użytkownik o to poprosi. Pełna budowa strony: skill **ipal-site**. `not-found.tsx` z `LocaleView` — bez `headers()`, wersja na każdy język (PROGRAMISTA §2.6–2.8, pages.md). 7. **SEO i bezpieczeństwo** — sitemap (`sitemap.xml/route.ts` = `sitemapRoute`, bez CSS w `public/`), robots, manifest, llms.txt, health (wszystkie z `force-dynamic`), `htmlLimitedBots`, `buildSecurityHeaders`, - `instrumentation.ts` z `assertEnv` (PROGRAMISTA §2.8–2.9). + `instrumentation.ts` z `assertEnv` z `@intecion/ipal-kit/env` (PROGRAMISTA §2.8–2.9, env.md). 8. **Nawigacja** — skill **ipal-nav**. 9. `pnpm generate:types`, `pnpm payload generate:importmap`, skill **ipal-audit** (pełny), lista kroków w panelu dla użytkownika (PROGRAMISTA §2.11). diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 33cdda9..189de94 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -158,8 +158,23 @@ export default { plugins: { '@tailwindcss/postcss': {} } } ```css /* src/app/(frontend)/styles.css */ @import "tailwindcss"; +@import "@intecion/ipal-kit/fluid.css"; /* opcjonalnie: płynna skala typografii i odstępów */ @source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js"; + +@theme inline { + --text-display: var(--ipal-fs-display); + --text-h1: var(--ipal-fs-h1); + --text-h2: var(--ipal-fs-h2); + --text-h3: var(--ipal-fs-h3); + --text-lead: var(--ipal-fs-lg); + --spacing-section: var(--ipal-space-section); + --spacing-gutter: var(--ipal-space-gutter); + --spacing-gap: var(--ipal-space-gap); +} ``` +`fluid.css` to same zmienne `clamp()` (360 → 1280 px, w `rem`) — klasy `text-h1`, +`py-section`, `px-gutter`. Liczby z `DESIGN.md` nadpisujesz w `:root` projektu +(`--ipal-fs-h1: clamp(…)`); formuł nie piszesz od zera. Bez `@source` komponenty pluginu (baner cookies, Turnstile) są bez stylów. Kolory komponentów pluginu: `--ipal-primary`, `--ipal-radius` (consent.md). @@ -325,7 +340,7 @@ export default withPayload({ }) ``` CSP (`buildCsp`) — najpierw `report-only`, po sprawdzeniu konsoli `enforce` -(security.md). `src/instrumentation.ts`: `assertEnv(ipalEnvRules({...}))` (env.md). +(security.md). `src/instrumentation.ts`: `assertEnv(ipalEnvRules({...}))` z **`@intecion/ipal-kit/env`**, tylko gdy `NEXT_RUNTIME === 'nodejs'` (env.md). ### 2.10 Generowanie i start ```bash @@ -472,6 +487,9 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi: | 15d | brak limitów na za duże obrazy / wideo w Media | `buildOptimizeUploadHook()` + `buildOptimizeUploadField()`, migracja pola | storage.md | | 15e | tablice „Add Row”, wiersze „Item 01”, `cta1`/`cta2`, etykiety PL w panelu | `labels` + `rowLabel()` na tablicach, sloty → tablica (z migracją!), etykiety EN — AGENT.md §6.5a; po aktualizacji pluginu **`pnpm payload generate:importmap`** (buildLinksField używa `RowLabel`) | links.md | | 15f | `public/sitemap.css` + własna trasa / `app/sitemap.ts` | `app/sitemap.xml/route.ts`: `export { sitemapRoute as GET } from '@/lib/content'` + `force-dynamic`; usuń `public/sitemap.css` i `app/sitemap.ts` | seo.md | +| 15g | `instrumentation.ts` importuje z roota (crash Edge/Turbopack: `fileTypeFromFile`) | `import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env'` + `if (process.env.NEXT_RUNTIME !== 'nodejs') return`; usuń dynamiczny `await import` | env.md | +| 15h | `` w panelu = XSS) | seo.md | +| 15i | własne formuły `clamp()` w `styles.css` | `@import "@intecion/ipal-kit/fluid.css"` + mapowanie w `@theme` (§2.5) | — | | 16 | 404 na sztywno | rola 404 w System Pages + `getNotFoundPage` | pages.md | | 16a | `privacyPolicy: { label: 'Polityka prywatności', … }` w layoucie | usuń cały parametr; tekst wpisz w Cookie Settings → Privacy link label | consent.md | | 17 | Opcjonalnie — AI/GEO | Markdown per strona, llms-full, boty AI w robots, MCP, wyszukiwarka, speakable, aiSummary | content.md, seo.md, mcp.md | diff --git a/docs/dev/vibe.md b/docs/dev/vibe.md index 9656c9c..3c30be7 100644 --- a/docs/dev/vibe.md +++ b/docs/dev/vibe.md @@ -189,7 +189,7 @@ Zrób wg PROGRAMISTA.md §2.8–2.9 i seo.md: - next.config.ts: htmlLimitedBots, buildSecurityHeaders, - metadata strony przez generatePageMetadata z lib/content (wspólny cache), favicon przez buildIconsMetadata, - JSON-LD w root layoucie: Organization + WebSite (seo.md) z danych z panelu, -- src/instrumentation.ts z assertEnv(ipalEnvRules(...)) (env.md). +- src/instrumentation.ts z assertEnv(ipalEnvRules(...)) importowanym z @intecion/ipal-kit/env (env.md). CSP jeszcze nie — będzie w kroku 14. Plan najpierw. ``` diff --git a/docs/env.md b/docs/env.md index 4885c8d..67b9b63 100644 --- a/docs/env.md +++ b/docs/env.md @@ -20,14 +20,21 @@ Najlepsze miejsce to `instrumentation.ts` (Next woła `register()` raz przy starcie serwera): ```ts -// instrumentation.ts -import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit' +// src/instrumentation.ts +import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env' export function register() { + if (process.env.NEXT_RUNTIME !== 'nodejs') return // Edge: brak process.env serwera assertEnv(ipalEnvRules({ storage: true, emailGraph: true, turnstile: true })) } ``` +> **Import z `@intecion/ipal-kit/env`, nie z roota.** Next kompiluje +> `instrumentation.ts` także dla Edge. Root pakietu ciągnie Payload, `file-type`, +> `fs` — Turbopack pada (`Export fileTypeFromFile doesn't exist in target module`). +> `/env` to tylko walidator, zero zależności. Root nadal eksportuje `assertEnv` +> (np. dla `payload.config.ts`). + Alternatywnie na górze `payload.config.ts` (ładuje się i w buildzie, i w runtime). Działa tylko po stronie serwera (czyta `process.env`) — NIE importuj do komponentu klienckiego. @@ -114,6 +121,14 @@ redeployów. ## Eksport ```ts -import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit' -import type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from '@intecion/ipal-kit' +import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env' +import type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from '@intecion/ipal-kit/env' ``` + +## `R2_PUBLIC_URL` — produkcja vs dev + +`ipalEnvRules({ storage: true })` wymaga w **produkcji** pełnego URL-a +(`https://media.klient.pl`). Poza produkcją dopuszcza ścieżkę względną +(`/media`) — `buildR2Storage` dokleja do niej `NEXT_PUBLIC_SERVER_URL`, CSP jej nie +dodaje (to `'self'`), `MediaPreconnect` ją pomija. Dev bez bucketu: nie ustawiaj +`R2_*` wcale i nie włączaj `storage` — media lądują na dysku. diff --git a/docs/storage.md b/docs/storage.md index 2d197ed..020f4f7 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -106,6 +106,7 @@ S3. Dodaj zmienną i przekaż ją do adaptera: ```bash # .env R2_PUBLIC_URL=https://media.klient.pl +# dev z rewrite /media → bucket: R2_PUBLIC_URL=/media (tylko poza produkcją; env.md) ``` Adapter `buildR2Storage` czyta ją i ustawia jako bazowy URL mediów (jeśli diff --git a/src/exports/env.ts b/src/exports/env.ts new file mode 100644 index 0000000..7d54929 --- /dev/null +++ b/src/exports/env.ts @@ -0,0 +1,17 @@ +/** + * Entry point: @intecion/ipal-kit/env + * + * Environment validation ONLY — zero imports beyond this module, no Payload, + * no Node built-ins, no React. Safe for Next's instrumentation.ts, which Next + * also compiles for the Edge runtime: importing the package root there drags in + * Payload / file-type / fs and crashes Turbopack ("Export fileTypeFromFile + * doesn't exist in target module"). + * + * // src/instrumentation.ts + * import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env' + * export function register() { + * if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true })) + * } + */ +export { assertEnv, ipalEnvRules } from '../modules/env/index.js' +export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from '../modules/env/index.js' diff --git a/src/modules/env/assertEnv.ts b/src/modules/env/assertEnv.ts index 7853893..2237ec8 100644 --- a/src/modules/env/assertEnv.ts +++ b/src/modules/env/assertEnv.ts @@ -43,7 +43,7 @@ function checkValue(rule: EnvRule, value: string): null | string { switch (kind) { case 'boolean': - if (!/^(true|false|1|0|yes|no)$/i.test(value)) { + 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 diff --git a/src/modules/env/ipalEnvRules.ts b/src/modules/env/ipalEnvRules.ts index 744b2bb..e0847ae 100644 --- a/src/modules/env/ipalEnvRules.ts +++ b/src/modules/env/ipalEnvRules.ts @@ -53,11 +53,7 @@ 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: serverUrlVar, - description: 'Public site origin, e.g. https://example.com', - kind: 'url', - }, + { name: serverUrlVar, description: 'Public site origin, e.g. https://example.com', kind: 'url' }, { name: 'NODE_ENV', description: 'Node environment', @@ -72,7 +68,20 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] { { 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' }, + { + name: 'R2_PUBLIC_URL', + description: 'Public base URL media is served from (custom domain of the bucket)', + // 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}")` + }, + }, ) } diff --git a/src/modules/security/buildCsp.ts b/src/modules/security/buildCsp.ts index 7a9df50..bf23fad 100644 --- a/src/modules/security/buildCsp.ts +++ b/src/modules/security/buildCsp.ts @@ -76,7 +76,8 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string 'object-src': ["'none'"], // block / (Flash-era attack surface) } - if (r2Url) {src['img-src'].push(r2Url)} + // Site-relative R2_PUBLIC_URL ('/media', dev) is same-origin — already covered by 'self'. + if (r2Url && /^https?:\/\//i.test(r2Url)) {src['img-src'].push(r2Url)} if (turnstile) { src['script-src'].push('https://challenges.cloudflare.com') @@ -110,7 +111,6 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string .map(([dir, values]) => `${dir} ${values.join(' ')}`) .join('; ') - const key = - mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy' + const key = mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy' return { key, value } } diff --git a/src/modules/seo/routeHandlers.ts b/src/modules/seo/routeHandlers.ts index e363b67..7d801da 100644 --- a/src/modules/seo/routeHandlers.ts +++ b/src/modules/seo/routeHandlers.ts @@ -89,13 +89,15 @@ export type SitemapRouteOptions = { export function createSitemapRouteHandler( sitemap: () => Promise, opts: SitemapRouteOptions = {}, -): (req?: Request) => Promise { +): (req: Request) => Promise { const style = opts.cssUrl ? false : opts.style === false ? false : (opts.style ?? {}) - return async (req?: Request) => { - const url = req ? new URL(req.url) : null + // `req` is required: Next 16 type-checks the first argument of a route handler + // (`Request | undefined` fails the build). A zero-argument call is not supported. + return async (req: Request) => { + const url = new URL(req.url) - if (style && url?.searchParams.has(SITEMAP_STYLE_PARAM)) { + if (style && url.searchParams.has(SITEMAP_STYLE_PARAM)) { let title: string | undefined try { title = typeof style.title === 'function' ? await style.title() : style.title @@ -111,7 +113,7 @@ export function createSitemapRouteHandler( }) } - const cssUrl = opts.cssUrl ?? (style ? `${url?.pathname ?? '/sitemap.xml'}?${SITEMAP_STYLE_PARAM}` : undefined) + const cssUrl = opts.cssUrl ?? (style ? `${url.pathname}?${SITEMAP_STYLE_PARAM}` : undefined) try { const entries = await sitemap() const xml = buildSitemapXml(entries, { cssUrl }) diff --git a/src/modules/storage/buildR2Storage.ts b/src/modules/storage/buildR2Storage.ts index af5867b..0e5fec9 100644 --- a/src/modules/storage/buildR2Storage.ts +++ b/src/modules/storage/buildR2Storage.ts @@ -77,7 +77,12 @@ export const buildR2Storage = ( // (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs // pointing there. Without it, uploads work but images don't display publicly. // See docs/storage.md. - const publicUrl = process.env.R2_PUBLIC_URL?.replace(/\/$/, '') // strip trailing slash + // Site-relative value ('/media', dev only — ipalEnvRules rejects it in production) + // → prefixed with NEXT_PUBLIC_SERVER_URL so Payload still stores absolute URLs. + const rawPublicUrl = process.env.R2_PUBLIC_URL?.trim().replace(/\/$/, '') // strip trailing slash + const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL?.trim().replace(/\/$/, '') + const publicUrl = + rawPublicUrl?.startsWith('/') && serverUrl ? `${serverUrl}${rawPublicUrl}` : rawPublicUrl // generateFileURL is a PER-COLLECTION option in @payloadcms/storage-s3 (not a // top-level one) — R2 needs it to point served URLs at the custom domain diff --git a/src/styles/fluid.css b/src/styles/fluid.css new file mode 100644 index 0000000..b7cedf8 --- /dev/null +++ b/src/styles/fluid.css @@ -0,0 +1,34 @@ +/* + * @intecion/ipal-kit/fluid.css — fluid type & spacing scale (variables only, no classes). + * Scales smoothly from a 360px to a 1280px viewport; rem-based, so browser zoom and + * user font size still work (WCAG 1.4.4). Opt-in: + * + * @import "tailwindcss"; + * @import "@intecion/ipal-kit/fluid.css"; + * @theme inline { + * --text-display: var(--ipal-fs-display); + * --text-h1: var(--ipal-fs-h1); + * --text-h2: var(--ipal-fs-h2); + * --text-h3: var(--ipal-fs-h3); + * --text-lead: var(--ipal-fs-lg); + * --spacing-section: var(--ipal-space-section); + * --spacing-gutter: var(--ipal-space-gutter); + * --spacing-gap: var(--ipal-space-gap); + * } + * → text-h1, text-display, py-section, px-gutter, gap-gap + * + * The design (DESIGN.md) decides the numbers: override any variable in the project's + * :root — the plugin only removes the clamp() maths from every project. + */ +:root { + --ipal-fs-sm: clamp(0.875rem, 0.8505rem + 0.1087vw, 0.9375rem); /* 0.875→0.9375rem · small print, captions */ + --ipal-fs-base: clamp(1rem, 0.9511rem + 0.2174vw, 1.125rem); /* 1→1.125rem · body text */ + --ipal-fs-lg: clamp(1.125rem, 1.0272rem + 0.4348vw, 1.375rem); /* 1.125→1.375rem · lead / intro */ + --ipal-fs-h3: clamp(1.25rem, 1.0543rem + 0.8696vw, 1.75rem); /* 1.25→1.75rem · h3 */ + --ipal-fs-h2: clamp(1.5rem, 1.1087rem + 1.7391vw, 2.5rem); /* 1.5→2.5rem · h2 — section headings */ + --ipal-fs-h1: clamp(2rem, 1.413rem + 2.6087vw, 3.5rem); /* 2→3.5rem · h1 — page heading */ + --ipal-fs-display: clamp(2.5rem, 1.7174rem + 3.4783vw, 4.5rem); /* 2.5→4.5rem · hero / display */ + --ipal-space-gap: clamp(1rem, 0.6087rem + 1.7391vw, 2rem); /* 1→2rem · gap between items in a section */ + --ipal-space-gutter: clamp(1rem, 0.413rem + 2.6087vw, 2.5rem); /* 1→2.5rem · container side padding */ + --ipal-space-section: clamp(3rem, 1.2391rem + 7.8261vw, 7.5rem); /* 3→7.5rem · vertical padding of a section */ +}