diff --git a/agents.md b/agents.md index 3fb2da2..bc67781 100644 --- a/agents.md +++ b/agents.md @@ -194,7 +194,7 @@ Wpinaj w kolekcje gdzie dotyczy (patrz `hooks.md`): - **buildSecurityHeaders** w next.config — HSTS, COOP, nosniff, Referrer-Policy (z automatu, uniwersalne). - **buildCsp** — generator CSP z twardymi regułami (base-uri, object-src, frame-ancestors). Flagi: turnstile, analytics, youtube, r2Url. Wdrażaj przez `report-only` → sprawdź konsolę → `enforce`. -- **2FA WYMUSZONE** — `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy' } })` + `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`. Wymuszone dla WSZYSTKICH użytkowników (forceSetup), bez opcji wyłączenia per user. NIE ustawiaj `twoFactor: false` (chyba że klient wprost odmawia). Bez zależności = błąd buildu. Patrz security.md. +- **2FA WYMUSZONE** — `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`, potem WSTRZYKNIJ: `import { payloadTotp } from '@clocklimited/payload-2fa'` + `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy', plugin: payloadTotp } })`. Wstrzyknięcie obowiązkowe — bez niego plugin robi dynamiczny import, którego Next nie wbundluje → „Cannot find module" na froncie. (Ewentualnie zamiast wstrzyknięcia: `serverExternalPackages: ['@clocklimited/payload-2fa']` w next.config.) Wymuszone dla WSZYSTKICH (forceSetup), bez opcji per user. NIE `twoFactor: false` (chyba że klient wprost odmawia). Patrz security.md. - **Ścieżka panelu** — `ipalKit({ adminRoute: '/its' })` ukrywa panel. WYMAGA przeniesienia folderu `app/(payload)/admin/` → `app/(payload)/its/`. To obscurity, nie security (2FA to prawdziwa ochrona). - CSP zostaje w projekcie (domeny), ale skeleton z pluginu. NIE Trusted Types (psuje Turnstile/GA). diff --git a/dist/modules/branding/adminGraphics.d.ts b/dist/modules/branding/adminGraphics.d.ts index c3d8f7c..a3a5bb7 100644 --- a/dist/modules/branding/adminGraphics.d.ts +++ b/dist/modules/branding/adminGraphics.d.ts @@ -17,29 +17,36 @@ * set, nothing is forced. */ type BrandingProps = { - /** SiteSettings global slug. Default 'site-settings'. */ - settingsSlug?: string; - /** Field holding the site name. Default 'siteName'. */ - nameField?: string; /** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */ imageField?: string; + /** Field holding the site name. Default 'siteName'. */ + nameField?: string; + /** SiteSettings global slug. Default 'site-settings'. */ + settingsSlug?: string; }; -/** Admin panel logo (login screen + nav). SiteSettings `logo`, falls back to `siteName`. */ +/** + * Admin panel logo — this is the LARGE logo on the login / unauthorized screens + * (Payload uses `graphics.Icon` for the small nav glyph). SiteSettings `logo`, + * falls back to `siteName` text. Sized generously for the login screen. + */ export declare function AdminLogo(props?: BrandingProps): Promise; /** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */ export declare function AdminIcon(props?: BrandingProps): Promise; /** - * Discreet vendor credit shown at the bottom of the admin nav: "Technology by - * Intecion.com". This is the PLUGIN VENDOR's credit (Intecion ships ipal-kit), - * not client data — so a sensible default here is fine and A0-safe. The client's - * own brand still owns the logo/name above (AdminLogo); this is a small line - * stating who provides the technology. Text/URL overridable; turn it off with - * `whiteLabel: { credit: false }`. + * Discreet vendor credit: "Technology supported by Intecion.com". This is the + * PLUGIN VENDOR's credit (Intecion ships ipal-kit, the framework), not client + * data — a sensible default here is fine and A0-safe. The client's own brand + * still owns the logo/name; this is a small line stating who supports the tech. + * Text/URL overridable; turn it off with `whiteLabel: { credit: false }`. * - * Wired by ipalKit into admin.components.afterNavLinks. + * Wired by ipalKit into admin.components.afterNavLinks (nav) AND afterLogin + * (login screen footer). `variant` adjusts placement: + * - 'nav' → left-aligned line under the nav links + * - 'login' → centered line below the login form */ export declare function IntecionCredit(props?: { text?: string; url?: string; + variant?: 'login' | 'nav'; }): import("react/jsx-runtime").JSX.Element; export {}; diff --git a/dist/modules/branding/adminGraphics.js b/dist/modules/branding/adminGraphics.js index aa92492..f85ac5c 100644 --- a/dist/modules/branding/adminGraphics.js +++ b/dist/modules/branding/adminGraphics.js @@ -3,8 +3,8 @@ import { getPayload } from 'payload'; async function loadBranding(settingsSlug, nameField, imageField) { try { // Consumer alias — resolved in the project's build, hidden from plugin tsc. - // @ts-ignore - const mod = await import('@payload-config'); + const spec = '@payload-config'; + const mod = await import(spec); const payload = await getPayload({ config: mod.default }); @@ -26,76 +26,97 @@ async function loadBranding(settingsSlug, nameField, imageField) { }; } } -/** Admin panel logo (login screen + nav). SiteSettings `logo`, falls back to `siteName`. */ export async function AdminLogo(props = {}) { - const { settingsSlug = 'site-settings', nameField = 'siteName', imageField = 'logo' } = props; +/** + * Admin panel logo — this is the LARGE logo on the login / unauthorized screens + * (Payload uses `graphics.Icon` for the small nav glyph). SiteSettings `logo`, + * falls back to `siteName` text. Sized generously for the login screen. + */ export async function AdminLogo(props = {}) { + const { imageField = 'logo', nameField = 'siteName', settingsSlug = 'site-settings' } = props; const { name, url } = await loadBranding(settingsSlug, nameField, imageField); if (url) { return /*#__PURE__*/ _jsx("img", { - src: url, alt: name ?? '', + src: url, style: { - maxHeight: 60, - maxWidth: 240, - width: 'auto', - height: 'auto' + height: 'auto', + maxHeight: 120, + maxWidth: 420, + width: 'auto' } }); } - if (name) return /*#__PURE__*/ _jsx("div", { - style: { - fontSize: '1.5rem', - fontWeight: 600 - }, - children: name - }); + if (name) { + return /*#__PURE__*/ _jsx("div", { + style: { + fontSize: '2rem', + fontWeight: 600 + }, + children: name + }); + } return null // nothing configured → Payload's default ; } /** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */ export async function AdminIcon(props = {}) { - const { settingsSlug = 'site-settings', nameField = 'siteName', imageField = 'favicon' } = props; + const { imageField = 'favicon', nameField = 'siteName', settingsSlug = 'site-settings' } = props; const { name, url } = await loadBranding(settingsSlug, nameField, imageField); if (url) { return /*#__PURE__*/ _jsx("img", { - src: url, alt: name ?? '', + src: url, style: { + height: 'auto', maxHeight: 28, maxWidth: 28, - width: 'auto', - height: 'auto' + width: 'auto' } }); } - if (name) return /*#__PURE__*/ _jsx("div", { - style: { - fontWeight: 700 - }, - children: name.slice(0, 2).toUpperCase() - }); + if (name) { + return /*#__PURE__*/ _jsx("div", { + style: { + fontWeight: 700 + }, + children: name.slice(0, 2).toUpperCase() + }); + } return null; } /** - * Discreet vendor credit shown at the bottom of the admin nav: "Technology by - * Intecion.com". This is the PLUGIN VENDOR's credit (Intecion ships ipal-kit), - * not client data — so a sensible default here is fine and A0-safe. The client's - * own brand still owns the logo/name above (AdminLogo); this is a small line - * stating who provides the technology. Text/URL overridable; turn it off with - * `whiteLabel: { credit: false }`. + * Discreet vendor credit: "Technology supported by Intecion.com". This is the + * PLUGIN VENDOR's credit (Intecion ships ipal-kit, the framework), not client + * data — a sensible default here is fine and A0-safe. The client's own brand + * still owns the logo/name; this is a small line stating who supports the tech. + * Text/URL overridable; turn it off with `whiteLabel: { credit: false }`. * - * Wired by ipalKit into admin.components.afterNavLinks. + * Wired by ipalKit into admin.components.afterNavLinks (nav) AND afterLogin + * (login screen footer). `variant` adjusts placement: + * - 'nav' → left-aligned line under the nav links + * - 'login' → centered line below the login form */ export function IntecionCredit(props = {}) { - const { text = 'Technology by Intecion.com', url = 'https://intecion.com' } = props; + const { text = 'Technology supported by Intecion.com', url = 'https://intecion.com', variant = 'nav' } = props; + const style = variant === 'login' ? { + color: 'inherit', + display: 'block', + fontSize: '0.75rem', + marginTop: '2rem', + opacity: 0.6, + padding: '0.5rem', + textAlign: 'center', + textDecoration: 'none' + } : { + color: 'inherit', + display: 'block', + fontSize: '0.75rem', + opacity: 0.6, + padding: '0.75rem 1rem', + textDecoration: 'none' + }; return /*#__PURE__*/ _jsx("a", { href: url, - target: "_blank", rel: "noopener noreferrer", - style: { - display: 'block', - padding: '0.75rem 1rem', - fontSize: '0.75rem', - opacity: 0.6, - textDecoration: 'none' - }, + style: style, + target: "_blank", children: text }); } diff --git a/dist/modules/branding/adminGraphics.js.map b/dist/modules/branding/adminGraphics.js.map index cd3c469..837341e 100644 --- a/dist/modules/branding/adminGraphics.js.map +++ b/dist/modules/branding/adminGraphics.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/branding/adminGraphics.tsx"],"sourcesContent":["import { getPayload } from 'payload'\n\n/**\n * White-label admin branding: the Payload admin panel's logo (login + nav) and\n * icon, pulled from the project's SiteSettings so each client sees THEIR brand,\n * set by the editor in the panel — not hardcoded per project. Wired\n * automatically by `ipalKit({ whiteLabel: true })` (it injects\n * admin.components.graphics.Logo/Icon pointing here).\n *\n * Server Components — they read the SiteSettings global at render. Data access\n * uses the project's `@payload-config` alias (universal in Payload 3 Next apps),\n * loaded via a variable specifier so the PLUGIN's own typecheck doesn't try to\n * resolve it (same pattern as the optional 2FA import). Everything is wrapped in\n * try/catch: on the login screen before the DB is ready, or a build with no DB,\n * the component falls back to the site name text, then to null (Payload's own\n * default) — never throws, never blocks the panel.\n *\n * A0: no client brand in code. The logo/name come from the panel; if nothing is\n * set, nothing is forced.\n */\n\ntype BrandingProps = {\n /** SiteSettings global slug. Default 'site-settings'. */\n settingsSlug?: string\n /** Field holding the site name. Default 'siteName'. */\n nameField?: string\n /** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */\n imageField?: string\n}\n\ntype MediaLike = { url?: string | null } | null | undefined\n\nasync function loadBranding(\n settingsSlug: string,\n nameField: string,\n imageField: string,\n): Promise<{ name: string | null; url: string | null }> {\n try {\n // Consumer alias — resolved in the project's build, hidden from plugin tsc.\n // @ts-ignore\n const mod = (await import('@payload-config')) as { default: unknown }\n const payload = await getPayload({ config: mod.default as never })\n const settings = (await payload.findGlobal({\n slug: settingsSlug as never,\n depth: 1,\n })) as Record\n\n const name = typeof settings[nameField] === 'string' ? (settings[nameField] as string) : null\n const image = settings[imageField] as MediaLike\n const url =\n image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null\n return { name, url }\n } catch {\n return { name: null, url: null }\n }\n}\n\n/** Admin panel logo (login screen + nav). SiteSettings `logo`, falls back to `siteName`. */\nexport async function AdminLogo(props: BrandingProps = {}) {\n const { settingsSlug = 'site-settings', nameField = 'siteName', imageField = 'logo' } = props\n const { name, url } = await loadBranding(settingsSlug, nameField, imageField)\n if (url) {\n return (\n \n )\n }\n if (name) return
{name}
\n return null // nothing configured → Payload's default\n}\n\n/** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */\nexport async function AdminIcon(props: BrandingProps = {}) {\n const { settingsSlug = 'site-settings', nameField = 'siteName', imageField = 'favicon' } = props\n const { name, url } = await loadBranding(settingsSlug, nameField, imageField)\n if (url) {\n return (\n \n )\n }\n if (name) return
{name.slice(0, 2).toUpperCase()}
\n return null\n}\n\n/**\n * Discreet vendor credit shown at the bottom of the admin nav: \"Technology by\n * Intecion.com\". This is the PLUGIN VENDOR's credit (Intecion ships ipal-kit),\n * not client data — so a sensible default here is fine and A0-safe. The client's\n * own brand still owns the logo/name above (AdminLogo); this is a small line\n * stating who provides the technology. Text/URL overridable; turn it off with\n * `whiteLabel: { credit: false }`.\n *\n * Wired by ipalKit into admin.components.afterNavLinks.\n */\nexport function IntecionCredit(props: { text?: string; url?: string } = {}) {\n const { text = 'Technology by Intecion.com', url = 'https://intecion.com' } = props\n return (\n \n {text}\n \n )\n}\n"],"names":["getPayload","loadBranding","settingsSlug","nameField","imageField","mod","payload","config","default","settings","findGlobal","slug","depth","name","image","url","AdminLogo","props","img","src","alt","style","maxHeight","maxWidth","width","height","div","fontSize","fontWeight","AdminIcon","slice","toUpperCase","IntecionCredit","text","a","href","target","rel","display","padding","opacity","textDecoration"],"mappings":";AAAA,SAASA,UAAU,QAAQ,UAAS;AAgCpC,eAAeC,aACbC,YAAoB,EACpBC,SAAiB,EACjBC,UAAkB;IAElB,IAAI;QACF,4EAA4E;QAC5E,aAAa;QACb,MAAMC,MAAO,MAAM,MAAM,CAAC;QAC1B,MAAMC,UAAU,MAAMN,WAAW;YAAEO,QAAQF,IAAIG,OAAO;QAAU;QAChE,MAAMC,WAAY,MAAMH,QAAQI,UAAU,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Q;YAAO;;IAG1E;IACA,IAAIZ,MAAM,qBAAO,KAACa;QAAIL,OAAO;YAAEO,YAAY;QAAI;kBAAIf,KAAKiB,KAAK,CAAC,GAAG,GAAGC,WAAW;;IAC/E,OAAO;AACT;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASC,eAAef,QAAyC,CAAC,CAAC;IACxE,MAAM,EAAEgB,OAAO,4BAA4B,EAAElB,MAAM,sBAAsB,EAAE,GAAGE;IAC9E,qBACE,KAACiB;QACCC,MAAMpB;QACNqB,QAAO;QACPC,KAAI;QACJhB,OAAO;YACLiB,SAAS;YACTC,SAAS;YACTZ,UAAU;YACVa,SAAS;YACTC,gBAAgB;QAClB;kBAECR;;AAGP"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/branding/adminGraphics.tsx"],"sourcesContent":["import { getPayload } from 'payload'\n\n/**\n * White-label admin branding: the Payload admin panel's logo (login + nav) and\n * icon, pulled from the project's SiteSettings so each client sees THEIR brand,\n * set by the editor in the panel — not hardcoded per project. Wired\n * automatically by `ipalKit({ whiteLabel: true })` (it injects\n * admin.components.graphics.Logo/Icon pointing here).\n *\n * Server Components — they read the SiteSettings global at render. Data access\n * uses the project's `@payload-config` alias (universal in Payload 3 Next apps),\n * loaded via a variable specifier so the PLUGIN's own typecheck doesn't try to\n * resolve it (same pattern as the optional 2FA import). Everything is wrapped in\n * try/catch: on the login screen before the DB is ready, or a build with no DB,\n * the component falls back to the site name text, then to null (Payload's own\n * default) — never throws, never blocks the panel.\n *\n * A0: no client brand in code. The logo/name come from the panel; if nothing is\n * set, nothing is forced.\n */\n\ntype BrandingProps = {\n /** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */\n imageField?: string\n /** Field holding the site name. Default 'siteName'. */\n nameField?: string\n /** SiteSettings global slug. Default 'site-settings'. */\n settingsSlug?: string\n}\n\ntype MediaLike = { url?: null | string } | null | undefined\n\nasync function loadBranding(\n settingsSlug: string,\n nameField: string,\n imageField: string,\n): Promise<{ name: null | string; url: null | string }> {\n try {\n // Consumer alias — resolved in the project's build, hidden from plugin tsc.\n const spec = '@payload-config'\n const mod = (await import(spec)) as { default: unknown }\n const payload = await getPayload({ config: mod.default as never })\n const settings = (await payload.findGlobal({\n slug: settingsSlug as never,\n depth: 1,\n })) as Record\n\n const name = typeof settings[nameField] === 'string' ? (settings[nameField]) : null\n const image = settings[imageField] as MediaLike\n const url =\n image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null\n return { name, url }\n } catch {\n return { name: null, url: null }\n }\n}\n\n/**\n * Admin panel logo — this is the LARGE logo on the login / unauthorized screens\n * (Payload uses `graphics.Icon` for the small nav glyph). SiteSettings `logo`,\n * falls back to `siteName` text. Sized generously for the login screen.\n */\nexport async function AdminLogo(props: BrandingProps = {}) {\n const { imageField = 'logo', nameField = 'siteName', settingsSlug = 'site-settings' } = props\n const { name, url } = await loadBranding(settingsSlug, nameField, imageField)\n if (url) {\n return (\n \n )\n }\n if (name) {return
{name}
}\n return null // nothing configured → Payload's default\n}\n\n/** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */\nexport async function AdminIcon(props: BrandingProps = {}) {\n const { imageField = 'favicon', nameField = 'siteName', settingsSlug = 'site-settings' } = props\n const { name, url } = await loadBranding(settingsSlug, nameField, imageField)\n if (url) {\n return (\n \n )\n }\n if (name) {return
{name.slice(0, 2).toUpperCase()}
}\n return null\n}\n\n/**\n * Discreet vendor credit: \"Technology supported by Intecion.com\". This is the\n * PLUGIN VENDOR's credit (Intecion ships ipal-kit, the framework), not client\n * data — a sensible default here is fine and A0-safe. The client's own brand\n * still owns the logo/name; this is a small line stating who supports the tech.\n * Text/URL overridable; turn it off with `whiteLabel: { credit: false }`.\n *\n * Wired by ipalKit into admin.components.afterNavLinks (nav) AND afterLogin\n * (login screen footer). `variant` adjusts placement:\n * - 'nav' → left-aligned line under the nav links\n * - 'login' → centered line below the login form\n */\nexport function IntecionCredit(\n props: { text?: string; url?: string; variant?: 'login' | 'nav' } = {},\n) {\n const {\n text = 'Technology supported by Intecion.com',\n url = 'https://intecion.com',\n variant = 'nav',\n } = props\n const style =\n variant === 'login'\n ? {\n color: 'inherit' as const,\n display: 'block',\n fontSize: '0.75rem',\n marginTop: '2rem',\n opacity: 0.6,\n padding: '0.5rem',\n textAlign: 'center' as const,\n textDecoration: 'none',\n }\n : {\n color: 'inherit' as const,\n display: 'block',\n fontSize: '0.75rem',\n opacity: 0.6,\n padding: '0.75rem 1rem',\n textDecoration: 'none',\n }\n return (\n \n {text}\n \n )\n}\n"],"names":["getPayload","loadBranding","settingsSlug","nameField","imageField","spec","mod","payload","config","default","settings","findGlobal","slug","depth","name","image","url","AdminLogo","props","img","alt","src","style","height","maxHeight","maxWidth","width","div","fontSize","fontWeight","AdminIcon","slice","toUpperCase","IntecionCredit","text","variant","color","display","marginTop","opacity","padding","textAlign","textDecoration","a","href","rel","target"],"mappings":";AAAA,SAASA,UAAU,QAAQ,UAAS;AAgCpC,eAAeC,aACbC,YAAoB,EACpBC,SAAiB,EACjBC,UAAkB;IAElB,IAAI;QACF,4EAA4E;QAC5E,MAAMC,OAAO;QACb,MAAMC,MAAO,MAAM,MAAM,CAACD;QAC1B,MAAME,UAAU,MAAMP,WAAW;YAAEQ,QAAQF,IAAIG,OAAO;QAAU;QAChE,MAAMC,WAAY,MAAMH,QAAQI,UAAU,CAAC;YACzCC,MAAMV;YACNW,OAAO;QACT;QAEA,MAAMC,OAAO,OAAOJ,QAAQ,CAACP,UAAU,KAAK,WAAYO,QAAQ,CAACP,UAAU,GAAI;QAC/E,MAAMY,QAAQL,QAAQ,CAACN,WAAW;QAClC,MAAMY,MACJD,SAAS,OAAOA,UAAU,YAAY,OAAOA,MAAMC,GAAG,KAAK,WAAWD,MAAMC,GAAG,GAAG;QACpF,OAAO;YAAEF;YAAME;QAAI;IACrB,EAAE,OAAM;QACN,OAAO;YAAEF,MAAM;YAAME,KAAK;QAAK;IACjC;AACF;AAEA;;;;CAIC,GACD,OAAO,eAAeC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;QACVU,WAAW;QACXC,SAAS;QACTC,SAAS;QACTC,WAAW;QACXC,gBAAgB;IAClB,IACA;QACEN,OAAO;QACPC,SAAS;QACTT,UAAU;QACVW,SAAS;QACTC,SAAS;QACTE,gBAAgB;IAClB;IACN,qBACE,KAACC;QAAEC,MAAM5B;QAAK6B,KAAI;QAAsBvB,OAAOA;QAAOwB,QAAO;kBAC1DZ;;AAGP"} \ No newline at end of file diff --git a/dist/plugin.js b/dist/plugin.js index 5f71915..0639700 100644 --- a/dist/plugin.js +++ b/dist/plugin.js @@ -62,29 +62,35 @@ import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo if (!tf?.issuer) { throw new Error('[ipal] twoFactor.issuer is required (name shown in the authenticator ' + 'app). Pass twoFactor: { issuer: "Your Site" }, or twoFactor: false to ' + 'opt out (discouraged).'); } - try { - // Dynamic specifier via a variable so TS doesn't try to resolve this - // optional peer dependency at build time (it isn't in the plugin's own - // node_modules). Avoids TS2307 without @ts-expect-error; the module - // exists at runtime in projects that installed it. - // @ts-ignore - const mod = await import('@clocklimited/payload-2fa'); - // The package exports `payloadTotp`; older/other builds may use - // `totpPlugin`. Accept either so a rename doesn't break us. - const totp = mod.payloadTotp ?? mod.totpPlugin; - if (typeof totp !== 'function') { - throw new Error('expected export payloadTotp (or totpPlugin) to be a function — ' + 'check the installed @clocklimited/payload-2fa version'); + // Prefer the INJECTED plugin factory (recommended): the project imports + // payloadTotp from @clocklimited/payload-2fa and passes it in. Then the + // plugin never imports the optional peer itself — no dynamic import, so + // Next can't fail to bundle it (the cause of "Cannot find module + // '@clocklimited/payload-2fa'" crashing even public frontend pages). + let totp = tf.plugin; + if (!totp) { + // Fallback: dynamic import. Variable specifier dodges the plugin's own + // TS2307, but Next may NOT trace it into the server bundle — projects + // using this path MUST add '@clocklimited/payload-2fa' to + // serverExternalPackages in next.config (see docs/security.md). + try { + const pkg = '@clocklimited/payload-2fa'; + const mod = await import(pkg); + totp = mod.payloadTotp ?? mod.totpPlugin; + } catch (err) { + throw new Error('[ipal] 2FA is enforced but @clocklimited/payload-2fa could not be loaded. ' + 'Best fix — inject it: `import { payloadTotp } from "@clocklimited/payload-2fa"` ' + 'then `twoFactor: { issuer, plugin: payloadTotp }`. Or install it AND add ' + "'@clocklimited/payload-2fa' to serverExternalPackages in next.config. Or set " + `twoFactor: false to opt out (discouraged). Original error: ${String(err)}`); } - config = await totp({ - collection: tf.collectionSlug ?? 'users', - forceSetup: true, - totp: { - issuer: tf.issuer - } - })(config); - } catch (err) { - throw new Error('[ipal] 2FA is enforced but @clocklimited/payload-2fa is not installed. ' + 'Run: pnpm add @clocklimited/payload-2fa — or set twoFactor: false to ' + `opt out (discouraged). Original error: ${String(err)}`); } + if (typeof totp !== 'function') { + throw new Error('[ipal] 2FA: expected payloadTotp (or totpPlugin) to be a function — check the ' + 'injected `plugin` or the installed @clocklimited/payload-2fa version.'); + } + config = await totp({ + collection: tf.collectionSlug ?? 'users', + forceSetup: true, + totp: { + issuer: tf.issuer + } + })(config); } // --- white-label admin branding --- // Inject admin.components.graphics.Logo/Icon pointing at the plugin's @@ -139,11 +145,24 @@ import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo } }, ...creditOn ? { + afterLogin: [ + ...config.admin?.components?.afterLogin ?? [], + { + path: '@intecion/ipal-kit/admin#IntecionCredit', + serverProps: { + ...creditProps, + variant: 'login' + } + } + ], afterNavLinks: [ ...config.admin?.components?.afterNavLinks ?? [], { path: '@intecion/ipal-kit/admin#IntecionCredit', - serverProps: creditProps + serverProps: { + ...creditProps, + variant: 'nav' + } } ] } : {} diff --git a/dist/plugin.js.map b/dist/plugin.js.map index cb5bb75..b878643 100644 --- a/dist/plugin.js.map +++ b/dist/plugin.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/plugin.ts"],"sourcesContent":["import type { Config, Plugin } from 'payload'\n\nimport type { IpalOptions } from './types.js'\n\nimport { buildCookieSettings } from './globals/CookieSettings/index.js'\nimport { buildNotifications } from './globals/Notifications/index.js'\nimport { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'\nimport { buildSiteSettings } from './globals/SiteSettings/index.js'\nimport { injectRoles } from './modules/access/index.js'\nimport { buildArchiveFields } from './modules/content/index.js'\nimport { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'\nimport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nimport { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'\nimport { buildSystemPagesFields } from './modules/pages/index.js'\nimport { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'\n\n/**\n * IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.\n *\n * @example\n * ```ts\n * import { ipalKit } from 'ipal-kit'\n *\n * export default buildConfig({\n * plugins: [\n * ipalKit({\n * i18n: {\n * locales: [\n * { code: 'pl', label: 'Polski' },\n * { code: 'en', label: 'English' },\n * ],\n * defaultLocale: 'pl',\n * },\n * access: { authCollection: 'users' },\n * }),\n * ],\n * })\n * ```\n */\nexport const ipalKit = (options: IpalOptions): Plugin => {\n // Validate eagerly — fail fast before Payload boots\n validateI18nConfig(options.i18n)\n\n return async (incomingConfig: Config): Promise => {\n // Early return when disabled — schema stays, behavior off\n if (options.enabled === false) {\n return incomingConfig\n }\n\n let config = { ...incomingConfig }\n\n // --- custom admin route (e.g. '/its' instead of '/admin') ---\n // Sets config.routes.admin; the project must move its app/(payload)//\n // folder to match (plugin can't create files in the project's app/).\n if (options.adminRoute) {\n config.routes = { ...(config.routes ?? {}), admin: options.adminRoute }\n }\n\n // --- enforced 2FA (TOTP) via @clocklimited/payload-2fa ---\n // Enforced by default (forceSetup) unless twoFactor is explicitly false. The\n // plugin is a PEER dependency imported dynamically — ipal-kit doesn't bundle\n // it, so projects that opt out (twoFactor: false) needn't install it, and the\n // import never runs under generate:importmap when 2FA is off. Wrapping access\n // control (not just admin UI) means TOTP gates data access — no API bypass.\n if (options.twoFactor !== false) {\n const tf = options.twoFactor\n if (!tf?.issuer) {\n throw new Error(\n '[ipal] twoFactor.issuer is required (name shown in the authenticator ' +\n 'app). Pass twoFactor: { issuer: \"Your Site\" }, or twoFactor: false to ' +\n 'opt out (discouraged).',\n )\n }\n try {\n // Dynamic specifier via a variable so TS doesn't try to resolve this\n // optional peer dependency at build time (it isn't in the plugin's own\n // node_modules). Avoids TS2307 without @ts-expect-error; the module\n // exists at runtime in projects that installed it.\n // @ts-ignore\n const mod = (await import('@clocklimited/payload-2fa')) as {\n payloadTotp?: (opts: Record) => Plugin\n totpPlugin?: (opts: Record) => Plugin\n }\n // The package exports `payloadTotp`; older/other builds may use\n // `totpPlugin`. Accept either so a rename doesn't break us.\n const totp = mod.payloadTotp ?? mod.totpPlugin\n if (typeof totp !== 'function') {\n throw new Error(\n 'expected export payloadTotp (or totpPlugin) to be a function — ' +\n 'check the installed @clocklimited/payload-2fa version',\n )\n }\n config = await totp({\n collection: tf.collectionSlug ?? 'users',\n forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out\n totp: { issuer: tf.issuer },\n })(config)\n } catch (err) {\n throw new Error(\n '[ipal] 2FA is enforced but @clocklimited/payload-2fa is not installed. ' +\n 'Run: pnpm add @clocklimited/payload-2fa — or set twoFactor: false to ' +\n `opt out (discouraged). Original error: ${String(err)}`,\n )\n }\n }\n\n // --- white-label admin branding ---\n // Inject admin.components.graphics.Logo/Icon pointing at the plugin's\n // /admin export. The components read SiteSettings at render, so each client\n // sees their own brand from the panel (no brand in code). Project must run\n // `pnpm generate:importmap` so Payload resolves the component paths.\n if (options.whiteLabel) {\n const wl = options.whiteLabel === true ? {} : options.whiteLabel\n const serverProps: Record = {}\n if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug}\n if (wl.nameField) {serverProps.nameField = wl.nameField}\n const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }\n const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }\n\n // Vendor credit (\"Technology by Intecion.com\") under the nav — on by\n // default, hidden with credit:false, text/url overridable.\n const creditOn = wl.credit !== false\n const creditProps =\n wl.credit && typeof wl.credit === 'object'\n ? {\n ...(wl.credit.text ? { text: wl.credit.text } : {}),\n ...(wl.credit.url ? { url: wl.credit.url } : {}),\n }\n : {}\n\n config.admin = {\n ...(config.admin ?? {}),\n components: {\n ...(config.admin?.components ?? {}),\n graphics: {\n ...(config.admin?.components?.graphics ?? {}),\n Icon: { path: '@intecion/ipal-kit/admin#AdminIcon', serverProps: iconProps },\n Logo: { path: '@intecion/ipal-kit/admin#AdminLogo', serverProps: logoProps },\n },\n ...(creditOn\n ? {\n afterNavLinks: [\n ...(config.admin?.components?.afterNavLinks ?? []),\n { path: '@intecion/ipal-kit/admin#IntecionCredit', serverProps: creditProps },\n ],\n }\n : {}),\n },\n ...(wl.titleSuffix\n ? { meta: { ...(config.admin?.meta ?? {}), titleSuffix: wl.titleSuffix } }\n : {}),\n }\n }\n\n // --- i18n ---\n config.localization = buildLocalizationConfig(options.i18n)\n\n // --- access: inject roles into the client's auth collection ---\n if (options.access) {\n config = injectRoles(config, options.access)\n }\n\n // --- seo: apply @payloadcms/plugin-seo directly ---\n // NOTE: apply the plugin function to the config immediately rather than\n // pushing it onto config.plugins. Payload has already iterated the plugins\n // array by the time IPAL runs, so nested plugins added to that list are\n // never executed. Calling the plugin as (config) => config applies its\n // transform now.\n if (options.seo) {\n config = await buildSeoPlugin({ seo: options.seo })(config)\n // Auto-fill empty meta from document content on save\n config = injectAutoFillMeta(config, options.seo)\n // Wrap fields into Content + SEO tabs (replaces plugin-seo's tabbedUI,\n // which breaks when other fields already exist in the collection)\n config = injectSeoTabs(config, options.seo)\n }\n\n // --- forms: apply @payloadcms/plugin-form-builder directly ---\n if (options.forms) {\n config = await buildFormsPlugin(options.forms)(config)\n }\n\n // --- globals ---\n // The System Pages tab collects every \"which page plays this role\"\n // assignment. Composing it here keeps SiteSettings unaware of which modules\n // are enabled — it just renders the fields it's given.\n const systemPageFields = [\n ...(options.pages ? buildSystemPagesFields(options.pages) : []),\n ...(options.content && options.pages\n ? buildArchiveFields(options.content, options.pages.slug)\n : []),\n ]\n\n config.globals = [\n ...(config.globals ?? []),\n buildSiteSettings({\n additionalFields: options.siteSettingsFields,\n systemPageFields,\n }),\n buildSiteIntegrations({ additionalFields: options.integrationsFields }),\n buildCookieSettings(),\n buildNotifications(),\n ]\n\n config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint]\n\n // --- hooks: onInit ---\n const incomingOnInit = config.onInit\n config.onInit = async (payload) => {\n if (incomingOnInit) {await incomingOnInit(payload)}\n payload.logger.info('[ipal] Plugin initialized.')\n }\n\n return config\n }\n}\n"],"names":["buildCookieSettings","buildNotifications","buildSiteIntegrations","buildSiteSettings","injectRoles","buildArchiveFields","testEmailEndpoint","buildFormsPlugin","buildLocalizationConfig","validateI18nConfig","buildSystemPagesFields","buildSeoPlugin","injectAutoFillMeta","injectSeoTabs","ipalKit","options","i18n","incomingConfig","enabled","config","adminRoute","routes","admin","twoFactor","tf","issuer","Error","mod","totp","payloadTotp","totpPlugin","collection","collectionSlug","forceSetup","err","String","whiteLabel","wl","serverProps","settingsSlug","nameField","logoProps","logoField","imageField","iconProps","iconField","creditOn","credit","creditProps","text","url","components","graphics","Icon","path","Logo","afterNavLinks","titleSuffix","meta","localization","access","seo","forms","systemPageFields","pages","content","slug","globals","additionalFields","siteSettingsFields","integrationsFields","endpoints","incomingOnInit","onInit","payload","logger","info"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,oCAAmC;AACvE,SAASC,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,qBAAqB,QAAQ,sCAAqC;AAC3E,SAASC,iBAAiB,QAAQ,kCAAiC;AACnE,SAASC,WAAW,QAAQ,4BAA2B;AACvD,SAASC,kBAAkB,QAAQ,6BAA4B;AAC/D,SAASC,iBAAiB,QAAQ,4CAA2C;AAC7E,SAASC,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,uBAAu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ClB,mEAAmE;QACnE,4EAA4E;QAC5E,uDAAuD;QACvD,MAAM4C,mBAAmB;eACnBhD,QAAQiD,KAAK,GAAGtD,uBAAuBK,QAAQiD,KAAK,IAAI,EAAE;eAC1DjD,QAAQkD,OAAO,IAAIlD,QAAQiD,KAAK,GAChC3D,mBAAmBU,QAAQkD,OAAO,EAAElD,QAAQiD,KAAK,CAACE,IAAI,IACtD,EAAE;SACP;QAED/C,OAAOgD,OAAO,GAAG;eACXhD,OAAOgD,OAAO,IAAI,EAAE;YACxBhE,kBAAkB;gBAChBiE,kBAAkBrD,QAAQsD,kBAAkB;gBAC5CN;YACF;YACA7D,sBAAsB;gBAAEkE,kBAAkBrD,QAAQuD,kBAAkB;YAAC;YACrEtE;YACAC;SACD;QAEDkB,OAAOoD,SAAS,GAAG;eAAKpD,OAAOoD,SAAS,IAAI,EAAE;YAAGjE;SAAkB;QAEnE,wBAAwB;QACxB,MAAMkE,iBAAiBrD,OAAOsD,MAAM;QACpCtD,OAAOsD,MAAM,GAAG,OAAOC;YACrB,IAAIF,gBAAgB;gBAAC,MAAMA,eAAeE;YAAQ;YAClDA,QAAQC,MAAM,CAACC,IAAI,CAAC;QACtB;QAEA,OAAOzD;IACT;AACF,EAAC"} \ No newline at end of file +{"version":3,"sources":["../src/plugin.ts"],"sourcesContent":["import type { Config, Plugin } from 'payload'\n\nimport type { IpalOptions, TotpPluginFactory } from './types.js'\n\nimport { buildCookieSettings } from './globals/CookieSettings/index.js'\nimport { buildNotifications } from './globals/Notifications/index.js'\nimport { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'\nimport { buildSiteSettings } from './globals/SiteSettings/index.js'\nimport { injectRoles } from './modules/access/index.js'\nimport { buildArchiveFields } from './modules/content/index.js'\nimport { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'\nimport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nimport { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'\nimport { buildSystemPagesFields } from './modules/pages/index.js'\nimport { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'\n\n/**\n * IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.\n *\n * @example\n * ```ts\n * import { ipalKit } from 'ipal-kit'\n *\n * export default buildConfig({\n * plugins: [\n * ipalKit({\n * i18n: {\n * locales: [\n * { code: 'pl', label: 'Polski' },\n * { code: 'en', label: 'English' },\n * ],\n * defaultLocale: 'pl',\n * },\n * access: { authCollection: 'users' },\n * }),\n * ],\n * })\n * ```\n */\nexport const ipalKit = (options: IpalOptions): Plugin => {\n // Validate eagerly — fail fast before Payload boots\n validateI18nConfig(options.i18n)\n\n return async (incomingConfig: Config): Promise => {\n // Early return when disabled — schema stays, behavior off\n if (options.enabled === false) {\n return incomingConfig\n }\n\n let config = { ...incomingConfig }\n\n // --- custom admin route (e.g. '/its' instead of '/admin') ---\n // Sets config.routes.admin; the project must move its app/(payload)//\n // folder to match (plugin can't create files in the project's app/).\n if (options.adminRoute) {\n config.routes = { ...(config.routes ?? {}), admin: options.adminRoute }\n }\n\n // --- enforced 2FA (TOTP) via @clocklimited/payload-2fa ---\n // Enforced by default (forceSetup) unless twoFactor is explicitly false. The\n // plugin is a PEER dependency imported dynamically — ipal-kit doesn't bundle\n // it, so projects that opt out (twoFactor: false) needn't install it, and the\n // import never runs under generate:importmap when 2FA is off. Wrapping access\n // control (not just admin UI) means TOTP gates data access — no API bypass.\n if (options.twoFactor !== false) {\n const tf = options.twoFactor\n if (!tf?.issuer) {\n throw new Error(\n '[ipal] twoFactor.issuer is required (name shown in the authenticator ' +\n 'app). Pass twoFactor: { issuer: \"Your Site\" }, or twoFactor: false to ' +\n 'opt out (discouraged).',\n )\n }\n // Prefer the INJECTED plugin factory (recommended): the project imports\n // payloadTotp from @clocklimited/payload-2fa and passes it in. Then the\n // plugin never imports the optional peer itself — no dynamic import, so\n // Next can't fail to bundle it (the cause of \"Cannot find module\n // '@clocklimited/payload-2fa'\" crashing even public frontend pages).\n let totp: TotpPluginFactory | undefined = tf.plugin\n\n if (!totp) {\n // Fallback: dynamic import. Variable specifier dodges the plugin's own\n // TS2307, but Next may NOT trace it into the server bundle — projects\n // using this path MUST add '@clocklimited/payload-2fa' to\n // serverExternalPackages in next.config (see docs/security.md).\n try {\n const pkg = '@clocklimited/payload-2fa'\n const mod = (await import(pkg)) as {\n payloadTotp?: TotpPluginFactory\n totpPlugin?: TotpPluginFactory\n }\n totp = mod.payloadTotp ?? mod.totpPlugin\n } catch (err) {\n throw new Error(\n '[ipal] 2FA is enforced but @clocklimited/payload-2fa could not be loaded. ' +\n 'Best fix — inject it: `import { payloadTotp } from \"@clocklimited/payload-2fa\"` ' +\n 'then `twoFactor: { issuer, plugin: payloadTotp }`. Or install it AND add ' +\n \"'@clocklimited/payload-2fa' to serverExternalPackages in next.config. Or set \" +\n `twoFactor: false to opt out (discouraged). Original error: ${String(err)}`,\n )\n }\n }\n\n if (typeof totp !== 'function') {\n throw new Error(\n '[ipal] 2FA: expected payloadTotp (or totpPlugin) to be a function — check the ' +\n 'injected `plugin` or the installed @clocklimited/payload-2fa version.',\n )\n }\n\n config = await totp({\n collection: tf.collectionSlug ?? 'users',\n forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out\n totp: { issuer: tf.issuer },\n })(config)\n }\n\n // --- white-label admin branding ---\n // Inject admin.components.graphics.Logo/Icon pointing at the plugin's\n // /admin export. The components read SiteSettings at render, so each client\n // sees their own brand from the panel (no brand in code). Project must run\n // `pnpm generate:importmap` so Payload resolves the component paths.\n if (options.whiteLabel) {\n const wl = options.whiteLabel === true ? {} : options.whiteLabel\n const serverProps: Record = {}\n if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug}\n if (wl.nameField) {serverProps.nameField = wl.nameField}\n const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }\n const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }\n\n // Vendor credit (\"Technology by Intecion.com\") under the nav — on by\n // default, hidden with credit:false, text/url overridable.\n const creditOn = wl.credit !== false\n const creditProps =\n wl.credit && typeof wl.credit === 'object'\n ? {\n ...(wl.credit.text ? { text: wl.credit.text } : {}),\n ...(wl.credit.url ? { url: wl.credit.url } : {}),\n }\n : {}\n\n config.admin = {\n ...(config.admin ?? {}),\n components: {\n ...(config.admin?.components ?? {}),\n graphics: {\n ...(config.admin?.components?.graphics ?? {}),\n Icon: { path: '@intecion/ipal-kit/admin#AdminIcon', serverProps: iconProps },\n Logo: { path: '@intecion/ipal-kit/admin#AdminLogo', serverProps: logoProps },\n },\n ...(creditOn\n ? {\n afterLogin: [\n ...(config.admin?.components?.afterLogin ?? []),\n {\n path: '@intecion/ipal-kit/admin#IntecionCredit',\n serverProps: { ...creditProps, variant: 'login' },\n },\n ],\n afterNavLinks: [\n ...(config.admin?.components?.afterNavLinks ?? []),\n {\n path: '@intecion/ipal-kit/admin#IntecionCredit',\n serverProps: { ...creditProps, variant: 'nav' },\n },\n ],\n }\n : {}),\n },\n ...(wl.titleSuffix\n ? { meta: { ...(config.admin?.meta ?? {}), titleSuffix: wl.titleSuffix } }\n : {}),\n }\n }\n\n // --- i18n ---\n config.localization = buildLocalizationConfig(options.i18n)\n\n // --- access: inject roles into the client's auth collection ---\n if (options.access) {\n config = injectRoles(config, options.access)\n }\n\n // --- seo: apply @payloadcms/plugin-seo directly ---\n // NOTE: apply the plugin function to the config immediately rather than\n // pushing it onto config.plugins. Payload has already iterated the plugins\n // array by the time IPAL runs, so nested plugins added to that list are\n // never executed. Calling the plugin as (config) => config applies its\n // transform now.\n if (options.seo) {\n config = await buildSeoPlugin({ seo: options.seo })(config)\n // Auto-fill empty meta from document content on save\n config = injectAutoFillMeta(config, options.seo)\n // Wrap fields into Content + SEO tabs (replaces plugin-seo's tabbedUI,\n // which breaks when other fields already exist in the collection)\n config = injectSeoTabs(config, options.seo)\n }\n\n // --- forms: apply @payloadcms/plugin-form-builder directly ---\n if (options.forms) {\n config = await buildFormsPlugin(options.forms)(config)\n }\n\n // --- globals ---\n // The System Pages tab collects every \"which page plays this role\"\n // assignment. Composing it here keeps SiteSettings unaware of which modules\n // are enabled — it just renders the fields it's given.\n const systemPageFields = [\n ...(options.pages ? buildSystemPagesFields(options.pages) : []),\n ...(options.content && options.pages\n ? buildArchiveFields(options.content, options.pages.slug)\n : []),\n ]\n\n config.globals = [\n ...(config.globals ?? []),\n buildSiteSettings({\n additionalFields: options.siteSettingsFields,\n systemPageFields,\n }),\n buildSiteIntegrations({ additionalFields: options.integrationsFields }),\n buildCookieSettings(),\n buildNotifications(),\n ]\n\n config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint]\n\n // --- hooks: onInit ---\n const incomingOnInit = config.onInit\n config.onInit = async (payload) => {\n if (incomingOnInit) {await incomingOnInit(payload)}\n payload.logger.info('[ipal] Plugin initialized.')\n }\n\n return config\n }\n}\n"],"names":["buildCookieSettings","buildNotifications","buildSiteIntegrations","buildSiteSettings","injectRoles","buildArchiveFields","testEmailEndpoint","buildFormsPlugin","buildLocalizationConfig","validateI18nConfig","buildSystemPagesFields","buildSeoPlugin","injectAutoFillMeta","injectSeoTabs","ipalKit","options","i18n","incomingConfig","enabled","config","adminRoute","routes","admin","twoFactor","tf","issuer","Error","totp","plugin","pkg","mod","payloadTotp","totpPlugin","err","String","collection","collectionSlug","forceSetup","whiteLabel","wl","serverProps","settingsSlug","nameField","logoProps","logoField","imageField","iconProps","iconField","creditOn","credit","creditProps","text","url","components","graphics","Icon","path","Logo","afterLogin","variant","afterNavLinks","titleSuffix","meta","localization","access","seo","forms","systemPageFields","pages","content","slug","globals","additionalFields","siteSettingsFields","integrationsFields","endpoints","incomingOnInit","onInit","payload","logger","info"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,oCAAmC;AACvE,SAASC,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,qBAAqB,QAAQ,sCAAqC;AAC3E,SAASC,iBAAiB,QAAQ,kCAAiC;AACnE,SAASC,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file diff --git a/dist/types.d.ts b/dist/types.d.ts index 269dde0..53aa9d2 100644 --- a/dist/types.d.ts +++ b/dist/types.d.ts @@ -1,4 +1,15 @@ -import type { Field } from 'payload'; +import type { Field, Plugin } from 'payload'; +/** + * Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected + * so the plugin never imports the optional peer itself. + */ +export type TotpPluginFactory = (options: { + collection: string; + forceSetup: boolean; + totp: { + issuer: string; + }; +}) => Plugin; import type { AccessOption } from './modules/access/types.js'; import type { ContentOption } from './modules/content/types.js'; import type { FormsOption } from './modules/forms/types.js'; @@ -71,6 +82,18 @@ export type IpalOptions = { collectionSlug?: string; /** Name shown in the authenticator app (e.g. company/site name). */ issuer: string; + /** + * The 2FA plugin factory, INJECTED from the project: + * `import { payloadTotp } from '@clocklimited/payload-2fa'`. Strongly + * recommended — injecting it (the same pattern as NextResponse / + * revalidatePath) means the plugin never dynamically imports the + * optional peer, which Next can fail to bundle into the server chunks + * ("Cannot find module '@clocklimited/payload-2fa'" at runtime, even on + * public frontend pages). If omitted, the plugin falls back to a dynamic + * import and you MUST add '@clocklimited/payload-2fa' to + * serverExternalPackages in next.config. See docs/security.md. + */ + plugin?: TotpPluginFactory; } | false; /** * White-label the admin panel: show the CLIENT's brand (logo + name) in the diff --git a/dist/types.js.map b/dist/types.js.map index 37be3e7..26a303d 100644 --- a/dist/types.js.map +++ b/dist/types.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { Field } from 'payload'\n\nimport type { AccessOption } from './modules/access/types.js'\nimport type { ContentOption } from './modules/content/types.js'\nimport type { FormsOption } from './modules/forms/types.js'\nimport type { I18nConfig } from './modules/i18n/types.js'\nimport type { PagesOption } from './modules/pages/types.js'\nimport type { SeoOption } from './modules/seo/types.js'\n\n/**\n * Configuration options for the IPAL plugin.\n * Passed by the client project in payload.config.ts.\n */\nexport type IpalOptions = {\n /**\n * Role-based access control. Injects a fixed `roles` field\n * (admin > editor > user) into the client's auth collection.\n */\n access?: AccessOption\n\n /**\n * Custom admin panel route, e.g. '/its' instead of the default '/admin'.\n * The plugin sets config.routes.admin. IMPORTANT: this alone isn't enough —\n * the project must ALSO move its panel folder to match:\n * app/(payload)/its/[[...segments]]/page.tsx (and the not-found). The plugin\n * can't create files in the project's app/. See docs/security.md.\n *\n * This is obscurity, not security: it hides the panel from dumb bots scanning\n * /admin, but real protection is strong auth + 2FA + rate limiting.\n */\n adminRoute?: string\n\n /**\n * Collections whose entries live under an archive page — blog posts, case\n * studies, anything with a listing. Adds an \"archive page\" assignment per\n * collection in SiteSettings; the assigned page's localized slug becomes the\n * URL segment (/pl/artykuly/moj-post, /en/articles/my-post). Requires `pages`.\n */\n content?: ContentOption\n\n /** Disable the plugin without uninstalling (keeps DB schema intact) */\n enabled?: boolean\n\n /**\n * Forms — form-builder collections (forms, form-submissions) plus the\n * callable submitForm (Turnstile + persistence + SMTP-from-panel email).\n */\n forms?: FormsOption\n\n /** Internationalization — locales, default locale, fallback behavior */\n i18n: I18nConfig\n\n /** Additional fields injected into SiteIntegrations global */\n integrationsFields?: Field[]\n\n /**\n * System-page assignments (homepage, privacy, cookies) in SiteSettings.\n * Provide the slug of the client's Pages collection to enable.\n */\n pages?: PagesOption\n\n /**\n * SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo)\n * and enables locale-aware metadata helpers.\n */\n seo?: SeoOption\n\n /** Additional fields injected into SiteSettings global */\n siteSettingsFields?: Field[]\n\n /**\n * Two-factor authentication (TOTP), ENFORCED for every user. Wires\n * @clocklimited/payload-2fa with forceSetup — no per-project opt-out. Every\n * user must configure an authenticator app after login; TOTP is checked before\n * data access (not just the admin UI). Requires the peer dep installed and an\n * issuer name (shown in the authenticator app).\n *\n * Pass `false` ONLY for a project that genuinely can't use 2FA (rare, discouraged)\n * — default is enforced. See docs/security.md.\n */\n twoFactor?:\n | {\n /** Auth collection slug. Defaults to 'users'. */\n collectionSlug?: string\n /** Name shown in the authenticator app (e.g. company/site name). */\n issuer: string\n }\n | false\n\n /**\n * White-label the admin panel: show the CLIENT's brand (logo + name) in the\n * admin — login screen and nav — pulled from SiteSettings, set by the editor\n * in the panel (no brand hardcoded in code). `true` wires it with defaults\n * (SiteSettings `logo`/`favicon`/`siteName`); the object form overrides the\n * global slug, field names, or the browser-tab title suffix.\n *\n * Injects admin.components.graphics.Logo/Icon pointing at\n * `@intecion/ipal-kit/admin`. After enabling, run `pnpm generate:importmap`\n * so Payload can resolve the components. See docs/white-label.md.\n */\n whiteLabel?:\n | {\n /**\n * Vendor credit (\"Technology by Intecion.com\") at the bottom of the\n * admin nav. Default on; `false` hides it, or override text/url.\n */\n credit?:\n | {\n text?: string\n url?: string\n }\n | boolean\n /** Upload field for the small nav icon. Default 'favicon'. */\n iconField?: string\n /** Upload field for the login/nav logo. Default 'logo'. */\n logoField?: string\n /** Field with the site name. Default 'siteName'. */\n nameField?: string\n /** SiteSettings global slug. Default 'site-settings'. */\n settingsSlug?: string\n /** Static browser-tab title suffix (e.g. ' · Acme Admin'). */\n titleSuffix?: string\n }\n | boolean\n}\n"],"names":[],"mappings":"AASA;;;CAGC,GACD,WA+GC"} \ No newline at end of file +{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { Field, Plugin } from 'payload'\n\n/**\n * Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected\n * so the plugin never imports the optional peer itself.\n */\nexport type TotpPluginFactory = (options: {\n collection: string\n forceSetup: boolean\n totp: { issuer: string }\n}) => Plugin\nimport type { AccessOption } from './modules/access/types.js'\nimport type { ContentOption } from './modules/content/types.js'\nimport type { FormsOption } from './modules/forms/types.js'\nimport type { I18nConfig } from './modules/i18n/types.js'\nimport type { PagesOption } from './modules/pages/types.js'\nimport type { SeoOption } from './modules/seo/types.js'\n\n/**\n * Configuration options for the IPAL plugin.\n * Passed by the client project in payload.config.ts.\n */\nexport type IpalOptions = {\n /**\n * Role-based access control. Injects a fixed `roles` field\n * (admin > editor > user) into the client's auth collection.\n */\n access?: AccessOption\n\n /**\n * Custom admin panel route, e.g. '/its' instead of the default '/admin'.\n * The plugin sets config.routes.admin. IMPORTANT: this alone isn't enough —\n * the project must ALSO move its panel folder to match:\n * app/(payload)/its/[[...segments]]/page.tsx (and the not-found). The plugin\n * can't create files in the project's app/. See docs/security.md.\n *\n * This is obscurity, not security: it hides the panel from dumb bots scanning\n * /admin, but real protection is strong auth + 2FA + rate limiting.\n */\n adminRoute?: string\n\n /**\n * Collections whose entries live under an archive page — blog posts, case\n * studies, anything with a listing. Adds an \"archive page\" assignment per\n * collection in SiteSettings; the assigned page's localized slug becomes the\n * URL segment (/pl/artykuly/moj-post, /en/articles/my-post). Requires `pages`.\n */\n content?: ContentOption\n\n /** Disable the plugin without uninstalling (keeps DB schema intact) */\n enabled?: boolean\n\n /**\n * Forms — form-builder collections (forms, form-submissions) plus the\n * callable submitForm (Turnstile + persistence + SMTP-from-panel email).\n */\n forms?: FormsOption\n\n /** Internationalization — locales, default locale, fallback behavior */\n i18n: I18nConfig\n\n /** Additional fields injected into SiteIntegrations global */\n integrationsFields?: Field[]\n\n /**\n * System-page assignments (homepage, privacy, cookies) in SiteSettings.\n * Provide the slug of the client's Pages collection to enable.\n */\n pages?: PagesOption\n\n /**\n * SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo)\n * and enables locale-aware metadata helpers.\n */\n seo?: SeoOption\n\n /** Additional fields injected into SiteSettings global */\n siteSettingsFields?: Field[]\n\n /**\n * Two-factor authentication (TOTP), ENFORCED for every user. Wires\n * @clocklimited/payload-2fa with forceSetup — no per-project opt-out. Every\n * user must configure an authenticator app after login; TOTP is checked before\n * data access (not just the admin UI). Requires the peer dep installed and an\n * issuer name (shown in the authenticator app).\n *\n * Pass `false` ONLY for a project that genuinely can't use 2FA (rare, discouraged)\n * — default is enforced. See docs/security.md.\n */\n twoFactor?:\n | {\n /** Auth collection slug. Defaults to 'users'. */\n collectionSlug?: string\n /** Name shown in the authenticator app (e.g. company/site name). */\n issuer: string\n /**\n * The 2FA plugin factory, INJECTED from the project:\n * `import { payloadTotp } from '@clocklimited/payload-2fa'`. Strongly\n * recommended — injecting it (the same pattern as NextResponse /\n * revalidatePath) means the plugin never dynamically imports the\n * optional peer, which Next can fail to bundle into the server chunks\n * (\"Cannot find module '@clocklimited/payload-2fa'\" at runtime, even on\n * public frontend pages). If omitted, the plugin falls back to a dynamic\n * import and you MUST add '@clocklimited/payload-2fa' to\n * serverExternalPackages in next.config. See docs/security.md.\n */\n plugin?: TotpPluginFactory\n }\n | false\n\n /**\n * White-label the admin panel: show the CLIENT's brand (logo + name) in the\n * admin — login screen and nav — pulled from SiteSettings, set by the editor\n * in the panel (no brand hardcoded in code). `true` wires it with defaults\n * (SiteSettings `logo`/`favicon`/`siteName`); the object form overrides the\n * global slug, field names, or the browser-tab title suffix.\n *\n * Injects admin.components.graphics.Logo/Icon pointing at\n * `@intecion/ipal-kit/admin`. After enabling, run `pnpm generate:importmap`\n * so Payload can resolve the components. See docs/white-label.md.\n */\n whiteLabel?:\n | {\n /**\n * Vendor credit (\"Technology by Intecion.com\") at the bottom of the\n * admin nav. Default on; `false` hides it, or override text/url.\n */\n credit?:\n | {\n text?: string\n url?: string\n }\n | boolean\n /** Upload field for the small nav icon. Default 'favicon'. */\n iconField?: string\n /** Upload field for the login/nav logo. Default 'logo'. */\n logoField?: string\n /** Field with the site name. Default 'siteName'. */\n nameField?: string\n /** SiteSettings global slug. Default 'site-settings'. */\n settingsSlug?: string\n /** Static browser-tab title suffix (e.g. ' · Acme Admin'). */\n titleSuffix?: string\n }\n | boolean\n}\n"],"names":[],"mappings":"AAkBA;;;CAGC,GACD,WA2HC"} \ No newline at end of file diff --git a/docs/agents-template.md b/docs/agents-template.md index 037d257..e4ef821 100644 --- a/docs/agents-template.md +++ b/docs/agents-template.md @@ -210,7 +210,7 @@ Wpinaj w kolekcje gdzie dotyczy (patrz `hooks.md`): - **buildSecurityHeaders** w next.config — HSTS, COOP, nosniff, Referrer-Policy (z automatu, uniwersalne). - **buildCsp** — generator CSP z twardymi regułami (base-uri, object-src, frame-ancestors). Flagi: turnstile, analytics, youtube, r2Url. Wdrażaj przez `report-only` → sprawdź konsolę → `enforce`. -- **2FA WYMUSZONE** — `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy' } })` + `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`. Wymuszone dla WSZYSTKICH użytkowników (forceSetup), bez opcji wyłączenia per user. NIE ustawiaj `twoFactor: false` (chyba że klient wprost odmawia). Bez zależności = błąd buildu. Patrz security.md. +- **2FA WYMUSZONE** — `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`, potem WSTRZYKNIJ: `import { payloadTotp } from '@clocklimited/payload-2fa'` + `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy', plugin: payloadTotp } })`. Wstrzyknięcie obowiązkowe — bez niego plugin robi dynamiczny import, którego Next nie wbundluje → „Cannot find module" na froncie. (Ewentualnie: `serverExternalPackages: ['@clocklimited/payload-2fa']` w next.config.) Wymuszone dla WSZYSTKICH (forceSetup), bez opcji per user. NIE `twoFactor: false` (chyba że klient wprost odmawia). Patrz security.md. - **Ścieżka panelu** — `ipalKit({ adminRoute: '/its' })` ukrywa panel. WYMAGA przeniesienia folderu `app/(payload)/admin/` → `app/(payload)/its/`. To obscurity, nie security (2FA to prawdziwa ochrona). - CSP zostaje w projekcie (domeny), ale skeleton z pluginu. NIE Trusted Types (psuje Turnstile/GA). diff --git a/docs/security.md b/docs/security.md index c9b9b9f..daad447 100644 --- a/docs/security.md +++ b/docs/security.md @@ -258,23 +258,41 @@ pnpm add @clocklimited/payload-2fa@3.0.0-beta.7 Uwaga: pakiet nie ma jeszcze stabilnego 3.0.0 — użyj konkretnej wersji beta (albo `^3.0.0-0`, żeby dopuścić prereleasy). Sam `^3.0.0` da błąd ERR_PNPM_NO_MATCHING_VERSION. -To PEER dependency — ipal-kit importuje ją dynamicznie tylko gdy 2FA włączone -(domyślnie). Bez niej i z włączonym 2FA plugin rzuci jasny błąd. -### Konfiguracja (payload.config.ts) +### Konfiguracja (payload.config.ts) — WSTRZYKNIJ plugin (zalecane) ```ts +import { payloadTotp } from '@clocklimited/payload-2fa' + ipalKit({ i18n: i18nConfig, twoFactor: { - issuer: 'Nazwa Firmy', // pokazywane w aplikacji authenticator (Google Auth itp.) - // collectionSlug: 'users', // domyślnie 'users' + issuer: 'Nazwa Firmy', // pokazywane w aplikacji authenticator + plugin: payloadTotp, // ← WSTRZYKNIJ — patrz niżej dlaczego + // collectionSlug: 'users', }, }) ``` +**Dlaczego `plugin: payloadTotp` (wstrzyknięcie):** to ten sam wzorzec co +`NextResponse`/`revalidatePath` — projekt podaje peer-dep, plugin go NIE +importuje. Bez tego plugin robi dynamiczny import, którego **Next potrafi nie +wbundlować** do server chunks → błąd runtime **„Cannot find module +'@clocklimited/payload-2fa'"** lecący nawet na publicznych stronach frontu. +Wstrzyknięcie eliminuje ten problem u źródła. + +**Jeśli NIE wstrzykujesz** (zostawiasz dynamiczny import) — MUSISZ dodać pakiet do +`serverExternalPackages` w `next.config`, żeby Next nie próbował go bundlować: + +```ts +// next.config.ts +const nextConfig = { + serverExternalPackages: ['@clocklimited/payload-2fa'], +} +``` + Plugin ustawia `forceSetup: true` — każdy użytkownik MUSI skonfigurować TOTP po -zalogowaniu (przekierowanie na setup). Nie ma opcji „włącz/wyłącz" dla użytkownika. +zalogowaniu. Nie ma opcji „włącz/wyłącz" dla użytkownika. ### Wyłączenie (ODRADZANE) diff --git a/docs/white-label.md b/docs/white-label.md index 1c00ec4..a4c78d1 100644 --- a/docs/white-label.md +++ b/docs/white-label.md @@ -37,20 +37,30 @@ whiteLabel: { } ``` -## Kredyt dostawcy — „Technology by Intecion.com" +## Kredyt dostawcy — „Technology supported by Intecion.com" -Pod nawigacją panelu (`afterNavLinks`) wyświetla się dyskretny kredyt -**„Technology by Intecion.com"** z linkiem do `https://intecion.com`. To kredyt -DOSTAWCY technologii (Intecion dostarcza ipal-kit) — marka klienta nadal rządzi -logiem i nazwą u góry; to tylko mała linijka „kto dostarcza technologię". +Dyskretny kredyt **„Technology supported by Intecion.com"** (link do +`https://intecion.com`) pojawia się w **dwóch miejscach**: +- **pod nawigacją** panelu (`afterNavLinks`, wariant `nav` — wyrównany do lewej), +- **na dole ekranu logowania** (`afterLogin`, wariant `login` — wyśrodkowany). + +To kredyt DOSTAWCY technologii (Intecion dostarcza framework ipal-kit) — marka +klienta nadal rządzi logiem i nazwą; to tylko linijka „kto wspiera technologię". Domyślnie włączony z `whiteLabel`. Sterowanie: ```ts -whiteLabel: { credit: false } // ukryj +whiteLabel: { credit: false } // ukryj (oba miejsca) whiteLabel: { credit: { text: 'Powered by Intecion', url: 'https://intecion.com' } } // własny tekst/url ``` +## Logo na ekranie logowania + +`AdminLogo` to DUŻE logo na ekranie logowania (Payload używa `graphics.Icon` do +małej ikony w nawigacji). Renderuje się sporo większe (`maxHeight 120 / maxWidth +420`), żeby marka klienta była wyraźna przy logowaniu. Mała ikona nav to `favicon` +przez `AdminIcon`. + ## Jak to działa - `AdminLogo` / `AdminIcon` to **Server Components** czytające SiteSettings przy diff --git a/src/modules/branding/adminGraphics.tsx b/src/modules/branding/adminGraphics.tsx index 7d94b57..1039f0d 100644 --- a/src/modules/branding/adminGraphics.tsx +++ b/src/modules/branding/adminGraphics.tsx @@ -20,32 +20,32 @@ import { getPayload } from 'payload' */ type BrandingProps = { - /** SiteSettings global slug. Default 'site-settings'. */ - settingsSlug?: string - /** Field holding the site name. Default 'siteName'. */ - nameField?: string /** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */ imageField?: string + /** Field holding the site name. Default 'siteName'. */ + nameField?: string + /** SiteSettings global slug. Default 'site-settings'. */ + settingsSlug?: string } -type MediaLike = { url?: string | null } | null | undefined +type MediaLike = { url?: null | string } | null | undefined async function loadBranding( settingsSlug: string, nameField: string, imageField: string, -): Promise<{ name: string | null; url: string | null }> { +): Promise<{ name: null | string; url: null | string }> { try { // Consumer alias — resolved in the project's build, hidden from plugin tsc. - // @ts-ignore - const mod = (await import('@payload-config')) as { default: unknown } + const spec = '@payload-config' + const mod = (await import(spec)) as { default: unknown } const payload = await getPayload({ config: mod.default as never }) const settings = (await payload.findGlobal({ slug: settingsSlug as never, depth: 1, })) as Record - const name = typeof settings[nameField] === 'string' ? (settings[nameField] as string) : null + const name = typeof settings[nameField] === 'string' ? (settings[nameField]) : null const image = settings[imageField] as MediaLike const url = image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null @@ -55,65 +55,86 @@ async function loadBranding( } } -/** Admin panel logo (login screen + nav). SiteSettings `logo`, falls back to `siteName`. */ +/** + * Admin panel logo — this is the LARGE logo on the login / unauthorized screens + * (Payload uses `graphics.Icon` for the small nav glyph). SiteSettings `logo`, + * falls back to `siteName` text. Sized generously for the login screen. + */ export async function AdminLogo(props: BrandingProps = {}) { - const { settingsSlug = 'site-settings', nameField = 'siteName', imageField = 'logo' } = props + const { imageField = 'logo', nameField = 'siteName', settingsSlug = 'site-settings' } = props const { name, url } = await loadBranding(settingsSlug, nameField, imageField) if (url) { return ( {name ) } - if (name) return
{name}
+ if (name) {return
{name}
} return null // nothing configured → Payload's default } /** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */ export async function AdminIcon(props: BrandingProps = {}) { - const { settingsSlug = 'site-settings', nameField = 'siteName', imageField = 'favicon' } = props + const { imageField = 'favicon', nameField = 'siteName', settingsSlug = 'site-settings' } = props const { name, url } = await loadBranding(settingsSlug, nameField, imageField) if (url) { return ( {name ) } - if (name) return
{name.slice(0, 2).toUpperCase()}
+ if (name) {return
{name.slice(0, 2).toUpperCase()}
} return null } /** - * Discreet vendor credit shown at the bottom of the admin nav: "Technology by - * Intecion.com". This is the PLUGIN VENDOR's credit (Intecion ships ipal-kit), - * not client data — so a sensible default here is fine and A0-safe. The client's - * own brand still owns the logo/name above (AdminLogo); this is a small line - * stating who provides the technology. Text/URL overridable; turn it off with - * `whiteLabel: { credit: false }`. + * Discreet vendor credit: "Technology supported by Intecion.com". This is the + * PLUGIN VENDOR's credit (Intecion ships ipal-kit, the framework), not client + * data — a sensible default here is fine and A0-safe. The client's own brand + * still owns the logo/name; this is a small line stating who supports the tech. + * Text/URL overridable; turn it off with `whiteLabel: { credit: false }`. * - * Wired by ipalKit into admin.components.afterNavLinks. + * Wired by ipalKit into admin.components.afterNavLinks (nav) AND afterLogin + * (login screen footer). `variant` adjusts placement: + * - 'nav' → left-aligned line under the nav links + * - 'login' → centered line below the login form */ -export function IntecionCredit(props: { text?: string; url?: string } = {}) { - const { text = 'Technology by Intecion.com', url = 'https://intecion.com' } = props +export function IntecionCredit( + props: { text?: string; url?: string; variant?: 'login' | 'nav' } = {}, +) { + const { + text = 'Technology supported by Intecion.com', + url = 'https://intecion.com', + variant = 'nav', + } = props + const style = + variant === 'login' + ? { + color: 'inherit' as const, + display: 'block', + fontSize: '0.75rem', + marginTop: '2rem', + opacity: 0.6, + padding: '0.5rem', + textAlign: 'center' as const, + textDecoration: 'none', + } + : { + color: 'inherit' as const, + display: 'block', + fontSize: '0.75rem', + opacity: 0.6, + padding: '0.75rem 1rem', + textDecoration: 'none', + } return ( - + {text} ) diff --git a/src/plugin.ts b/src/plugin.ts index 841066b..e3e3721 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -1,6 +1,6 @@ import type { Config, Plugin } from 'payload' -import type { IpalOptions } from './types.js' +import type { IpalOptions, TotpPluginFactory } from './types.js' import { buildCookieSettings } from './globals/CookieSettings/index.js' import { buildNotifications } from './globals/Notifications/index.js' @@ -71,37 +71,48 @@ export const ipalKit = (options: IpalOptions): Plugin => { 'opt out (discouraged).', ) } - try { - // Dynamic specifier via a variable so TS doesn't try to resolve this - // optional peer dependency at build time (it isn't in the plugin's own - // node_modules). Avoids TS2307 without @ts-expect-error; the module - // exists at runtime in projects that installed it. - // @ts-ignore - const mod = (await import('@clocklimited/payload-2fa')) as { - payloadTotp?: (opts: Record) => Plugin - totpPlugin?: (opts: Record) => Plugin - } - // The package exports `payloadTotp`; older/other builds may use - // `totpPlugin`. Accept either so a rename doesn't break us. - const totp = mod.payloadTotp ?? mod.totpPlugin - if (typeof totp !== 'function') { + // Prefer the INJECTED plugin factory (recommended): the project imports + // payloadTotp from @clocklimited/payload-2fa and passes it in. Then the + // plugin never imports the optional peer itself — no dynamic import, so + // Next can't fail to bundle it (the cause of "Cannot find module + // '@clocklimited/payload-2fa'" crashing even public frontend pages). + let totp: TotpPluginFactory | undefined = tf.plugin + + if (!totp) { + // Fallback: dynamic import. Variable specifier dodges the plugin's own + // TS2307, but Next may NOT trace it into the server bundle — projects + // using this path MUST add '@clocklimited/payload-2fa' to + // serverExternalPackages in next.config (see docs/security.md). + try { + const pkg = '@clocklimited/payload-2fa' + const mod = (await import(pkg)) as { + payloadTotp?: TotpPluginFactory + totpPlugin?: TotpPluginFactory + } + totp = mod.payloadTotp ?? mod.totpPlugin + } catch (err) { throw new Error( - 'expected export payloadTotp (or totpPlugin) to be a function — ' + - 'check the installed @clocklimited/payload-2fa version', + '[ipal] 2FA is enforced but @clocklimited/payload-2fa could not be loaded. ' + + 'Best fix — inject it: `import { payloadTotp } from "@clocklimited/payload-2fa"` ' + + 'then `twoFactor: { issuer, plugin: payloadTotp }`. Or install it AND add ' + + "'@clocklimited/payload-2fa' to serverExternalPackages in next.config. Or set " + + `twoFactor: false to opt out (discouraged). Original error: ${String(err)}`, ) } - config = await totp({ - collection: tf.collectionSlug ?? 'users', - forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out - totp: { issuer: tf.issuer }, - })(config) - } catch (err) { + } + + if (typeof totp !== 'function') { throw new Error( - '[ipal] 2FA is enforced but @clocklimited/payload-2fa is not installed. ' + - 'Run: pnpm add @clocklimited/payload-2fa — or set twoFactor: false to ' + - `opt out (discouraged). Original error: ${String(err)}`, + '[ipal] 2FA: expected payloadTotp (or totpPlugin) to be a function — check the ' + + 'injected `plugin` or the installed @clocklimited/payload-2fa version.', ) } + + config = await totp({ + collection: tf.collectionSlug ?? 'users', + forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out + totp: { issuer: tf.issuer }, + })(config) } // --- white-label admin branding --- @@ -139,9 +150,19 @@ export const ipalKit = (options: IpalOptions): Plugin => { }, ...(creditOn ? { + afterLogin: [ + ...(config.admin?.components?.afterLogin ?? []), + { + path: '@intecion/ipal-kit/admin#IntecionCredit', + serverProps: { ...creditProps, variant: 'login' }, + }, + ], afterNavLinks: [ ...(config.admin?.components?.afterNavLinks ?? []), - { path: '@intecion/ipal-kit/admin#IntecionCredit', serverProps: creditProps }, + { + path: '@intecion/ipal-kit/admin#IntecionCredit', + serverProps: { ...creditProps, variant: 'nav' }, + }, ], } : {}), diff --git a/src/types.ts b/src/types.ts index cdca3bd..e53807f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,5 +1,14 @@ -import type { Field } from 'payload' +import type { Field, Plugin } from 'payload' +/** + * Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected + * so the plugin never imports the optional peer itself. + */ +export type TotpPluginFactory = (options: { + collection: string + forceSetup: boolean + totp: { issuer: string } +}) => Plugin import type { AccessOption } from './modules/access/types.js' import type { ContentOption } from './modules/content/types.js' import type { FormsOption } from './modules/forms/types.js' @@ -84,6 +93,18 @@ export type IpalOptions = { collectionSlug?: string /** Name shown in the authenticator app (e.g. company/site name). */ issuer: string + /** + * The 2FA plugin factory, INJECTED from the project: + * `import { payloadTotp } from '@clocklimited/payload-2fa'`. Strongly + * recommended — injecting it (the same pattern as NextResponse / + * revalidatePath) means the plugin never dynamically imports the + * optional peer, which Next can fail to bundle into the server chunks + * ("Cannot find module '@clocklimited/payload-2fa'" at runtime, even on + * public frontend pages). If omitted, the plugin falls back to a dynamic + * import and you MUST add '@clocklimited/payload-2fa' to + * serverExternalPackages in next.config. See docs/security.md. + */ + plugin?: TotpPluginFactory } | false