MCP site tools, Turnstile key alert, required 2FA injection, a11y, more tests

- MCP: new get_site_info and list_pages tools (public by design, published
  and indexable content only); search results collapse the homepage to root.
  New listContent() helper shared with searchContent.
- Dashboard alert when Turnstile is half-configured (it is silently off then).
- twoFactor.plugin is now required; the dynamic-import fallback (which never
  worked under Next and caused a Turbopack warning) is gone.
- a11y: cookie category checkboxes are labelled, buttons have type, test-email
  input is labelled; tab labels keep localized collection labels.
- IPAL_IP_HEADER: one-time production warning when unset, opt-in
  ipalEnvRules({ ipHeader: true }).
- Tests: SEO/robots/sitemap/hreflang, CSP, Markdown, consent, MCP, and a real
  Payload + SQLite integration test for forms and the roles guard (74 total).
- Drop unused mongodb-memory-server; dev .env.example for SQLite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-16 01:15:19 +02:00
co-authored by Claude Opus 5.5
parent 86e69b0bcf
commit ab854ef37a
36 changed files with 708 additions and 328 deletions
+2 -1
View File
@@ -1,2 +1,3 @@
DATABASE_URL=mongodb://127.0.0.1/payload-plugin-template
# SQLite file for the dev sandbox (default: ./payload.db). Delete the file to start fresh.
DATABASE_URI=file:./payload.db
PAYLOAD_SECRET=YOUR_SECRET_HERE
+9
View File
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
## This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
+4 -4
View File
@@ -280,7 +280,7 @@ ipalKit({
**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 nie
importuje. Do 1.8.x plugin bez tego robił dynamiczny import, którego **Next nie
wbundluje** (webpack zamienia import ze zmiennej w pusty kontekst) → błąd
**„Cannot find module '@clocklimited/payload-2fa'"** w `next build` i na każdej
stronie (także publicznej). Build potrafi przy tym przejść „na zielono", bo
@@ -289,9 +289,9 @@ stronie (także publicznej). Build potrafi przy tym przejść „na zielono", bo
**`serverExternalPackages` NIE jest obejściem.** Pakiet importuje własne
`*.module.css`; po externalizacji ładuje go Node, który nie zna `.css` →
`ERR_UNKNOWN_FILE_EXTENSION` przy zbieraniu danych `/admin`. Jedyna działająca
konfiguracja w Next to wstrzyknięcie. Dynamiczny import zostaje tylko dla
kontekstów bez Next (CLI `payload …`), gdzie pakiet rozwiązuje się jako opcjonalny
peer ipal-kit.
konfiguracja w Next to wstrzyknięcie, dlatego od 1.9.0 `plugin` jest **wymagany**
(brak → czytelny błąd przy starcie). CLI `payload …` ładuje ten sam config, więc
dostaje wstrzyknięty plugin.
Plugin ustawia `forceSetup: true` — każdy użytkownik MUSI skonfigurować TOTP po
zalogowaniu. Nie ma opcji „włącz/wyłącz" dla użytkownika.
-1
View File
@@ -111,7 +111,6 @@
"eslint": "^9.23.0",
"eslint-config-next": "16.4.0",
"graphql": "^16.8.1",
"mongodb-memory-server": "10.1.4",
"next": "16.4.0",
"open": "^10.1.0",
"payload": "3.90.2",
-240
View File
@@ -90,9 +90,6 @@ importers:
graphql:
specifier: ^16.8.1
version: 16.14.2
mongodb-memory-server:
specifier: 10.1.4
version: 10.1.4
next:
specifier: 16.4.0
version: 16.4.0(@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])
@@ -1601,9 +1598,6 @@ packages:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
'@mongodb-js/[email protected]':
resolution: {integrity: sha512-QAfAMwNgnYxZ2C6D1HgeP7Gc4i/uvJRim415PCIL9ptRxWMNbWeLBYb2/9R4pGKny/s1FVu2JA2cxCUBUOggrA==}
'@napi-rs/[email protected]':
resolution: {integrity: sha512-kjirL3N6TnRPv5iuHw36wnucNqXAO46dzK9oPb0wj076R5Xm8PfUVA9nAFB5ZNMmfJQJVKACAPd/Z2KYMppthw==}
engines: {node: '>= 10'}
@@ -2358,15 +2352,9 @@ packages:
'@types/[email protected]':
resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
'@types/[email protected]':
resolution: {integrity: sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==}
'@types/[email protected]':
resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==}
'@types/[email protected]':
resolution: {integrity: sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==}
'@types/[email protected]':
resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
@@ -2665,10 +2653,6 @@ packages:
engines: {node: '>=0.4.0'}
hasBin: true
[email protected]:
resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}
engines: {node: '>= 14'}
[email protected]:
resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==}
@@ -2740,9 +2724,6 @@ packages:
resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==}
engines: {node: '>= 0.4'}
[email protected]:
resolution: {integrity: sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==}
[email protected]:
resolution: {integrity: sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==}
engines: {node: '>=8.0.0'}
@@ -2866,10 +2847,6 @@ packages:
[email protected]:
resolution: {integrity: sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==}
[email protected]:
resolution: {integrity: sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==}
engines: {node: '>=16.20.1'}
[email protected]:
resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==}
@@ -2922,10 +2899,6 @@ packages:
resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==}
engines: {node: '>=6'}
[email protected]:
resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==}
engines: {node: '>=10'}
[email protected]:
resolution: {integrity: sha512-g/uHREV2ZpK9qMalCsWaxmA6ol+DX8GYhuf3T40RKoP+oL7vhRJh8LNt73PCjpnR6l14FzfPrB5Yux4PKm2meg==}
@@ -3001,9 +2974,6 @@ packages:
resolution: {integrity: sha512-0h+uSNtQGW3D98eQt3jJ8L06Fves8hncB4V/PKdw/Qb8Hnk19VaKuTr55UNRYiSoVa7WwrFls+rh3ux9agmkeQ==}
engines: {node: '>= 12.0.0'}
[email protected]:
resolution: {integrity: sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==}
[email protected]:
resolution: {integrity: sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==}
@@ -3760,10 +3730,6 @@ packages:
resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}
engines: {node: '>=8'}
[email protected]:
resolution: {integrity: sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==}
engines: {node: '>=8'}
[email protected]:
resolution: {integrity: sha512-UC2I2+nx1ZuOBclWVNdcnbDR5dlrOdVb7xNjmT/lHE+LsgztWks3dG7boJ37yTS/venXw84B/mAW9uHVoC5QRg==}
@@ -3796,15 +3762,6 @@ packages:
[email protected]:
resolution: {integrity: sha512-N7kHdlgsO/v+iD/dMoJKtsSqs5Dz/dXZVebRgJw23LDk+jMi/974zyiOYDziY2JPp8xivq9BmUGwIJMiuSBi7w==}
[email protected]:
resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
peerDependenciesMeta:
debug:
optional: true
[email protected]:
resolution: {integrity: sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==}
engines: {node: '>= 0.4'}
@@ -4006,10 +3963,6 @@ packages:
resolution: {integrity: sha512-V5nVw1PAOgfI3Lmeaj2Exmeg7fenjhRUgz1lPSezy1CuhPYbgQtbQj4jZfEAEMlaL+vupsvhjqCyjzob0yxsmQ==}
engines: {node: '>=10.19.0'}
[email protected]:
resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}
engines: {node: '>= 14'}
[email protected]:
resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==}
engines: {node: '>=10.17.0'}
@@ -4417,10 +4370,6 @@ packages:
[email protected]:
resolution: {integrity: sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==}
[email protected]:
resolution: {integrity: sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==}
engines: {node: '>=8'}
[email protected]:
resolution: {integrity: sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==}
engines: {node: '>= 18'}
@@ -4451,9 +4400,6 @@ packages:
[email protected]:
resolution: {integrity: sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==}
[email protected]:
resolution: {integrity: sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==}
[email protected]:
resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==}
@@ -4578,44 +4524,6 @@ packages:
[email protected]:
resolution: {integrity: sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==}
[email protected]:
resolution: {integrity: sha512-rMO7CGo/9BFwyZABcKAWL8UJwH/Kc2x0g72uhDWzG48URRax5TCIcJ7Rc3RZqffZzO/Gwff/jyKwCU9TN8gehA==}
[email protected]:
resolution: {integrity: sha512-o8fgY7ZalEd8pGps43fFPr/hkQu1L8i6HFEGbsTfA2zDOW0TopgpswaBCqDr0qD7ptibyPfB5DmC+UlIxbThzA==}
engines: {node: '>=16.20.1'}
[email protected]:
resolution: {integrity: sha512-+oKQ/kc3CX+816oPFRtaF0CN4vNcGKNjpOQe4bHo/21A3pMD+lC7Xz1EX5HP7siCX4iCpVchDMmCOFXVQSGkUg==}
engines: {node: '>=16.20.1'}
[email protected]:
resolution: {integrity: sha512-URyb/VXMjJ4da46OeSXg+puO39XH9DeQpWCslifrRn9JWugy0D+DvvBvkm2WxmHe61O/H19JM66p1z7RHVkZ6A==}
engines: {node: '>=16.20.1'}
peerDependencies:
'@aws-sdk/credential-providers': ^3.188.0
'@mongodb-js/zstd': ^1.1.0 || ^2.0.0
gcp-metadata: ^5.2.0
kerberos: ^2.0.1
mongodb-client-encryption: '>=6.0.0 <7'
snappy: ^7.3.2
socks: ^2.7.1
peerDependenciesMeta:
'@aws-sdk/credential-providers':
optional: true
'@mongodb-js/zstd':
optional: true
gcp-metadata:
optional: true
kerberos:
optional: true
mongodb-client-encryption:
optional: true
snappy:
optional: true
socks:
optional: true
[email protected]:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
@@ -4635,10 +4543,6 @@ packages:
[email protected]:
resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}
[email protected]:
resolution: {integrity: sha512-lDcBsjBSMlj3LXH2v/FW3txlh2pYTjmbOXPYJD93HI5EwuLzI11tdHSIpUMmfq/IOsldj4Ps8M8flhm+pCK4Ew==}
engines: {node: '>=12.22.0'}
[email protected]:
resolution: {integrity: sha512-N2C+9q89Z/oLrsepSRS4jRMtwmUZAoZuAHU0e9T6+sAB5DdhADmrnOW+zjYijlrYFmVfmQhGVGy9eMFoB7UgKg==}
engines: {node: '>=20.9.0'}
@@ -4905,10 +4809,6 @@ packages:
[email protected]:
resolution: {integrity: sha512-3e3ka9QCE8RJ5I9uszdAADZnkcYi21cqmF3gxox3u884N72qpFHCsIVhHt8cEQ9t3Auq/NqoiCEuhxlxxQuDWA==}
[email protected]:
resolution: {integrity: sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==}
engines: {node: '>=8'}
[email protected]:
resolution: {integrity: sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==}
engines: {node: '>=20'}
@@ -5327,9 +5227,6 @@ packages:
resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==}
engines: {node: '>= 12'}
[email protected]:
resolution: {integrity: sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==}
[email protected]:
resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==}
engines: {node: '>= 10.x'}
@@ -5504,10 +5401,6 @@ packages:
resolution: {integrity: sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww==}
engines: {node: '>=14.16'}
[email protected]:
resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==}
engines: {node: '>=18'}
[email protected]:
resolution: {integrity: sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ==}
@@ -5761,18 +5654,10 @@ packages:
resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
engines: {node: '>= 8'}
[email protected]:
resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==}
engines: {node: '>=12'}
[email protected]:
resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==}
engines: {node: '>=12'}
[email protected]:
resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==}
engines: {node: '>=18'}
[email protected]:
resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==}
engines: {node: '>= 0.4'}
@@ -7336,10 +7221,6 @@ snapshots:
react: 19.3.0
react-dom: 19.3.0([email protected])
'@mongodb-js/[email protected]':
dependencies:
sparse-bitfield: 3.0.3
'@napi-rs/[email protected]':
optional: true
@@ -8225,14 +8106,8 @@ snapshots:
'@types/[email protected]': {}
'@types/[email protected]': {}
'@types/[email protected]': {}
'@types/[email protected]':
dependencies:
'@types/webidl-conversions': 7.0.3
'@types/[email protected]':
dependencies:
'@types/node': 22.20.5
@@ -8646,8 +8521,6 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]:
dependencies:
fast-deep-equal: 3.1.3
@@ -8752,10 +8625,6 @@ snapshots:
[email protected]: {}
[email protected]:
dependencies:
tslib: 2.8.1
[email protected]: {}
[email protected]:
@@ -8857,8 +8726,6 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
@@ -8918,8 +8785,6 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
@@ -8987,8 +8852,6 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
@@ -10010,12 +9873,6 @@ snapshots:
dependencies:
to-regex-range: 5.0.1
[email protected]:
dependencies:
commondir: 1.0.1
make-dir: 3.1.0
pkg-dir: 4.2.0
[email protected]:
dependencies:
findup-sync: 4.0.0
@@ -10055,10 +9912,6 @@ snapshots:
dependencies:
tabbable: 6.5.0
[email protected]([email protected]):
optionalDependencies:
debug: 4.4.3
[email protected]:
dependencies:
is-callable: 1.2.7
@@ -10273,13 +10126,6 @@ snapshots:
quick-lru: 5.1.1
resolve-alpn: 1.2.1
[email protected]:
dependencies:
agent-base: 7.1.4
debug: 4.4.3
transitivePeerDependencies:
- supports-color
[email protected]: {}
[email protected]: {}
@@ -10661,10 +10507,6 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.6.0
[email protected]:
dependencies:
semver: 6.3.1
[email protected]: {}
[email protected]: {}
@@ -10732,8 +10574,6 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
@@ -10943,61 +10783,6 @@ snapshots:
dompurify: 3.2.7
marked: 14.0.0
[email protected]:
dependencies:
'@types/whatwg-url': 11.0.5
whatwg-url: 14.2.0
[email protected]:
dependencies:
async-mutex: 0.5.0
camelcase: 6.3.0
debug: 4.4.3
find-cache-dir: 3.3.2
follow-redirects: 1.16.0([email protected])
https-proxy-agent: 7.0.6
mongodb: 6.21.0
new-find-package-json: 2.0.0
semver: 7.8.5
tar-stream: 3.2.0
tslib: 2.8.1
yauzl: 3.4.0
transitivePeerDependencies:
- '@aws-sdk/credential-providers'
- '@mongodb-js/zstd'
- bare-abort-controller
- bare-buffer
- gcp-metadata
- kerberos
- mongodb-client-encryption
- react-native-b4a
- snappy
- socks
- supports-color
[email protected]:
dependencies:
mongodb-memory-server-core: 10.1.4
tslib: 2.8.1
transitivePeerDependencies:
- '@aws-sdk/credential-providers'
- '@mongodb-js/zstd'
- bare-abort-controller
- bare-buffer
- gcp-metadata
- kerberos
- mongodb-client-encryption
- react-native-b4a
- snappy
- socks
- supports-color
[email protected]:
dependencies:
'@mongodb-js/saslprep': 1.4.12
bson: 6.10.4
mongodb-connection-string-url: 3.0.2
[email protected]: {}
[email protected]: {}
@@ -11008,12 +10793,6 @@ snapshots:
[email protected]: {}
[email protected]:
dependencies:
debug: 4.4.3
transitivePeerDependencies:
- supports-color
[email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]):
dependencies:
'@next/env': 16.4.0
@@ -11352,10 +11131,6 @@ snapshots:
optionalDependencies:
'@napi-rs/nice': 1.1.1
[email protected]:
dependencies:
find-up: 4.1.0
[email protected]: {}
[email protected]:
@@ -11861,10 +11636,6 @@ snapshots:
[email protected]: {}
[email protected]:
dependencies:
memory-pager: 1.5.0
[email protected]: {}
[email protected]: {}
@@ -12070,10 +11841,6 @@ snapshots:
'@tokenizer/token': 0.3.0
ieee754: 1.2.1
[email protected]:
dependencies:
punycode: 2.3.1
[email protected]:
dependencies:
utf8-byte-length: 1.0.5
@@ -12323,15 +12090,8 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]:
dependencies:
tr46: 5.1.1
webidl-conversions: 7.0.0
[email protected]:
dependencies:
is-bigint: 1.1.0
@@ -35,6 +35,8 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
<FieldLabel htmlFor={`field-${path}`} label={label} />
<div className="field-type__wrap" style={{ alignItems: 'center', display: 'flex', gap: '.5rem' }}>
{/* Labelled by <FieldLabel htmlFor> above — the rule can't see through the component. */}
{/* eslint-disable-next-line jsx-a11y/control-has-associated-label */}
<input
autoComplete="off"
className="field-type__input"
@@ -43,12 +43,14 @@ export const TestEmailButton = () => {
return (
<div className="field-type" style={{ marginTop: '1rem' }}>
<label className="field-label">Send a test email</label>
<label className="field-label" htmlFor="ipal-test-email-to">Send a test email</label>
<p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>
Sends through the transport selected above. Save your changes first.
</p>
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '.5rem' }}>
<input
aria-label="Test email recipient"
id="ipal-test-email-to"
onChange={(e) => setTo(e.target.value)}
placeholder="[email protected]"
style={{ flex: 1, minWidth: '220px' }}
+1
View File
@@ -43,6 +43,7 @@ export {
createMarkdownRenderer,
createSearchRoute,
getArchiveEntries,
listContent,
MARKDOWN_PREFIX,
markdownHref,
markdownResponse,
+1
View File
@@ -13,6 +13,7 @@ export type BlockData = {
* Maps a blockType to the client's component for it.
* The client owns the components; the plugin only receives this map.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- each block component has its own props shape
export type BlockComponentMap = Record<string, ComponentType<any>>
/**
+1
View File
@@ -93,6 +93,7 @@ export function ConsentScript({
if (asyncAttr) {el.async = true}
if (defer) {el.defer = true}
if (attributes) {for (const [k, v] of Object.entries(attributes)) {el.setAttribute(k, v)}}
// eslint-disable-next-line @eslint-react/web-api/no-leaked-event-listener -- one-shot, and the script is never unloaded (see below)
el.addEventListener('load', runInline, { once: true })
document.head.appendChild(el)
} else {
+11 -7
View File
@@ -101,13 +101,13 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
</p>
</div>
<div className="flex shrink-0 gap-2">
<button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)}>
<button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)} type="button">
{texts.buttons.settings}
</button>
<button className={secondaryClass} data-ipal="reject" onClick={rejectAll}>
<button className={secondaryClass} data-ipal="reject" onClick={rejectAll} type="button">
{texts.buttons.reject}
</button>
<button className={primaryClass} data-ipal="accept" onClick={acceptAll}>
<button className={primaryClass} data-ipal="accept" onClick={acceptAll} type="button">
{texts.buttons.acceptAll}
</button>
</div>
@@ -122,12 +122,16 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
{CONSENT_CATEGORIES.map((cat) => (
<li className="flex items-start justify-between gap-4" key={cat}>
<div>
<p className={`text-sm font-medium ${strongText}`}>
<p className={`text-sm font-medium ${strongText}`} id={`ipal-consent-${cat}`}>
{texts.categories[cat].title}
</p>
<p className={`text-xs ${mutedText}`}>{texts.categories[cat].description}</p>
<p className={`text-xs ${mutedText}`} id={`ipal-consent-${cat}-desc`}>
{texts.categories[cat].description}
</p>
</div>
<input
aria-describedby={`ipal-consent-${cat}-desc`}
aria-labelledby={`ipal-consent-${cat}`}
checked={cat === 'necessary' ? true : choices[cat]}
className="mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]"
disabled={cat === 'necessary'}
@@ -138,10 +142,10 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
))}
</ul>
<div className="flex justify-end gap-2">
<button className={secondaryClass} data-ipal="back" onClick={() => setShowSettings(false)}>
<button className={secondaryClass} data-ipal="back" onClick={() => setShowSettings(false)} type="button">
{texts.buttons.back}
</button>
<button className={primaryClass} data-ipal="save" onClick={() => savePreferences(choices)}>
<button className={primaryClass} data-ipal="save" onClick={() => savePreferences(choices)} type="button">
{texts.buttons.save}
</button>
</div>
+1
View File
@@ -36,6 +36,7 @@ export function CookieButton({ className }: { className?: string } = {}) {
className={cls}
data-ipal="cookie-button"
onClick={reopen}
type="button"
>
<Cookie
aria-hidden="true"
+1 -1
View File
@@ -10,7 +10,7 @@ export { resolveNotFoundPage } from './resolveNotFoundPage.js'
export { resolveRedirect } from './resolveRedirect.js'
export { resolveRoute } from './resolveRoute.js'
export type { ResolvedRoute } from './resolveRoute.js'
export { searchContent } from './searchContent.js'
export { listContent, searchContent } from './searchContent.js'
export type { SearchResult } from './searchContent.js'
export type { ContentCollectionOption, ContentOption } from './types.js'
export { archiveFieldName } from './types.js'
+52 -2
View File
@@ -89,6 +89,20 @@ export async function searchContent({
return []
}
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField })
}
type ToResultsArgs = {
config: I18nConfig
homeSlug?: Record<string, string> | string
locale: string
max: number
origin: string
summaryField?: string
}
/** Published, indexable docs → results. Shared by searchContent and listContent. */
function toResults(docs: PageRow[], { config, homeSlug, locale, max, origin, summaryField }: ToResultsArgs): SearchResult[] {
const results: SearchResult[] = []
for (const doc of docs) {
if (doc._status && doc._status !== 'published') {continue}
@@ -96,7 +110,7 @@ export async function searchContent({
const title = typeof doc.title === 'string' ? doc.title : undefined
const slug = typeof doc.slug === 'string' ? doc.slug : undefined
if (!title || !slug) {continue}
const path = buildLocalizedPath({ config, homeSlug, locale: loc, slugs: { [loc]: slug } })
const path = buildLocalizedPath({ config, homeSlug, locale, slugs: { [locale]: slug } })
// Prefer the richer AI summary when configured and present, else meta.description.
const summary =
summaryField && typeof doc[summaryField] === 'string'
@@ -113,6 +127,42 @@ export async function searchContent({
})
if (results.length >= max) {break}
}
return results
}
/**
* Every published, indexable page of a collection (title order), as the same
* structured results searchContent returns — the "table of contents" an AI
* agent browses before fetching pages. Behind the MCP server's list_pages tool.
*
* Degrades to [] (never throws) like searchContent.
*/
export async function listContent({
baseUrl,
collection = 'pages',
config,
homeSlug,
limit = 50,
locale,
payload,
summaryField,
}: Omit<SearchContentArgs, 'query'>): Promise<SearchResult[]> {
const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config)
const max = Math.min(Math.max(Math.trunc(limit) || 50, 1), 200)
const origin = baseUrl?.replace(/\/$/, '') ?? ''
let docs: PageRow[] = []
try {
const res = await payload.find({
collection: collection as never,
depth: 0,
limit: max * 2, // over-fetch; drafts/noindex filtered in memory
locale: loc as never,
sort: 'title',
})
docs = (res?.docs ?? []) as PageRow[]
} catch {
return []
}
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField })
}
+2 -1
View File
@@ -137,7 +137,8 @@ export const graphAdapter =
// Graph accepts either HTML or Text; Payload gives us html and/or text.
const isHtml = typeof message.html === 'string' && message.html.length > 0
const content = isHtml ? String(message.html) : String(message.text ?? '')
const text = typeof message.text === 'string' ? message.text : ''
const content = isHtml ? (message.html as string) : text
// Reply-To: prefer whatever the caller set; otherwise the panel address.
const replyTo = message.replyTo
+1 -1
View File
@@ -79,7 +79,7 @@ export const panelSmtpAdapter =
// normalises CRLF in standard headers, but the form-builder interpolates
// user data into the subject via {{field}} placeholders, so strip any
// newlines from header-bound values before they reach the transport.
const stripCRLF = (v: unknown): string => String(v ?? '').replace(/[\r\n]+/g, ' ').trim()
const stripCRLF = (v: string): string => v.replace(/[\r\n]+/g, ' ').trim()
const { default: nodemailer } = await import('nodemailer')
+15
View File
@@ -7,6 +7,11 @@ export type IpalEnvFeatures = {
databaseVar?: string
/** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */
emailGraph?: boolean
/**
* Require IPAL_IP_HEADER in production — the header the rate limit trusts for
* the client IP (see clientIp). Outside production it stays optional.
*/
ipHeader?: boolean
/** Override the Payload secret var. Default 'PAYLOAD_SECRET'. */
secretVar?: string
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
@@ -44,6 +49,7 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
const {
databaseVar = 'DATABASE_URI',
emailGraph = false,
ipHeader = false,
secretVar = 'PAYLOAD_SECRET',
serverUrlVar = 'NEXT_PUBLIC_SERVER_URL',
storage = false,
@@ -94,6 +100,15 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
)
}
if (ipHeader) {
rules.push({
name: 'IPAL_IP_HEADER',
description: 'Header holding the real client IP, e.g. cf-connecting-ip (Cloudflare) or x-forwarded-for',
required: process.env.NODE_ENV === 'production',
validate: (v) => (/^[a-z0-9-]+$/i.test(v) ? true : `IPAL_IP_HEADER must be a header name (got "${v}")`),
})
}
if (turnstile) {
const names = typeof turnstile === 'object' ? turnstile : {}
rules.push(
+1 -1
View File
@@ -147,7 +147,7 @@ export async function submitForm({
form: formId,
submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({
field,
value: value == null ? '' : String(value),
value: value == null ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string),
})),
} as never,
})
@@ -1,4 +1,4 @@
import type { BasePayload, CollectionAfterChangeHook } from 'payload'
import type { CollectionAfterChangeHook } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
+1 -1
View File
@@ -33,7 +33,7 @@ export function buildPreventDeleteSystemPage(
const assigned = settings[field]
const assignedId =
assigned && typeof assigned === 'object' ? (assigned as { id?: unknown }).id : assigned
if (assignedId != null && String(assignedId) === String(id)) {
if ((typeof assignedId === 'string' || typeof assignedId === 'number') && String(assignedId) === String(id)) {
throw new APIError(
`Cannot delete a page assigned to the system role "${field}". ` +
`Detach the role in Site Settings first.`,
+1 -1
View File
@@ -21,7 +21,7 @@ export function buildValidateUniqueRole(args: { siblingFields: string[] }): Fiel
for (const sibling of args.siblingFields) {
const other = (siblingData as Record<string, unknown>)?.[sibling]
const otherId = other && typeof other === 'object' ? (other as { id?: unknown }).id : other
if (otherId != null && String(otherId) === String(thisId)) {
if ((typeof otherId === 'string' || typeof otherId === 'number') && String(otherId) === String(thisId)) {
const name = typeof field === 'object' && 'name' in field ? field.name : 'ta rola'
throw new APIError(
`Ta sama strona jest przypisana do "${name}" i "${sibling}". ` +
+1 -1
View File
@@ -20,5 +20,5 @@ export function resolveLocalized(value: unknown, locale: string, fallback = ''):
const first = Object.values(map).find((v) => typeof v === 'string')
return (first) ?? fallback
}
return String(value)
return typeof value === 'number' || typeof value === 'boolean' ? String(value) : fallback
}
+15 -4
View File
@@ -2,6 +2,8 @@ import type { Payload } from 'payload'
import type { IntegrationStatus } from './status.js'
import { turnstileKeyProblem } from '../turnstile/config.js'
type Props = {
/** Admin route, for the link. Default '/admin'. */
adminRoute?: string
@@ -25,8 +27,17 @@ export async function IntegrationAlerts({ adminRoute = '/admin', checks = { emai
return null
}
const failing = Object.entries(checks)
.map(([field, label]) => ({ label, status: doc?.[field] as IntegrationStatus | undefined }))
.filter((x) => x.status?.state === 'degraded')
.map(([field, label]) => {
const status = doc?.[field] as IntegrationStatus | undefined
return { label, message: status?.state === 'degraded' ? (status.message ?? status.code ?? 'error') : null }
})
.filter((x): x is { label: string; message: string } => x.message !== null)
// Configuration problems no request will ever record (nothing is verified
// while Turnstile is off) — checked live from the saved keys.
const keyProblem = turnstileKeyProblem(doc ?? {})
if (keyProblem && !failing.some((f) => f.label === 'Turnstile')) {
failing.push({ label: 'Turnstile', message: keyProblem })
}
if (!failing.length) {return null}
return (
@@ -42,9 +53,9 @@ export async function IntegrationAlerts({ adminRoute = '/admin', checks = { emai
>
<strong>Integration problem — the site still works, but something needs attention.</strong>
<ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem' }}>
{failing.map(({ label, status }) => (
{failing.map(({ label, message }) => (
<li key={label}>
<strong>{label}:</strong> {status?.message ?? status?.code ?? 'error'}
<strong>{label}:</strong> {message}
</li>
))}
</ul>
+87 -10
View File
@@ -4,8 +4,9 @@ import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { ClientIpOptions } from '../shared/rateLimit.js'
import { createMarkdownRenderer, searchContent } from '../content/index.js'
import { createMarkdownRenderer, listContent, searchContent } from '../content/index.js'
import { getDefaultLocale, isValidLocale } from '../i18n/index.js'
import { readSiteMetaConfig } from '../seo/readSiteMetaConfig.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
/**
@@ -20,10 +21,15 @@ import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit
* transport: initialize, tools/list, tools/call, ping. Uses the global
* Request/Response — no next/server import.
*
* Exposes two tools:
* Exposes four tools:
* - get_site_info({ locale? }) → site name, description, languages, key URLs
* - list_pages({ locale?, limit? }) → every published page (title, url, description)
* - search_content({ query, locale?, limit? }) → matching pages (title, url, description)
* - get_page({ path }) → that page as Markdown
*
* Public on purpose — it exposes exactly what the public site shows (published,
* non-noindex content), so AI assistants can browse it like any visitor.
*
* // app/api/mcp/route.ts
* import { createMcpRoute } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
@@ -99,7 +105,27 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
const origin = baseUrl?.replace(/\/$/, '') ?? ''
const renderMarkdown = createMarkdownRenderer({ collection, content, settingsSlug })
const localeProp = { type: 'string', description: `Locale code (default ${config.defaultLocale})` }
const TOOLS = [
{
name: 'get_site_info',
description:
'Overview of the site: name, description, available languages and key URLs. Call this first.',
inputSchema: { type: 'object', properties: { locale: localeProp } },
},
{
name: 'list_pages',
description:
'List all published pages of the site with title, URL and description — the table of contents. Fetch one with get_page.',
inputSchema: {
type: 'object',
properties: {
limit: { type: 'number', description: 'Max results (default 50, max 200)' },
locale: localeProp,
},
},
},
{
name: 'search_content',
description:
@@ -108,7 +134,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
type: 'object',
properties: {
limit: { type: 'number', description: 'Max results (default 10)' },
locale: { type: 'string', description: `Locale code (default ${config.defaultLocale})` },
locale: localeProp,
query: { type: 'string', description: 'Search keywords' },
},
required: ['query'],
@@ -128,21 +154,72 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
},
]
const pickLocale = (params: Record<string, unknown>): string =>
typeof params.locale === 'string' && isValidLocale(params.locale, config)
? params.locale
: getDefaultLocale(config)
const formatResults = (results: { description?: string; title: string; url: string }[]) =>
results.map((r) => `- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`).join('\n')
async function siteMeta(payload: BasePayload, locale: string) {
try {
return await readSiteMetaConfig({ locale, pagesSlug: collection, payload, settingsSlug })
} catch {
return null
}
}
async function getSiteInfo(params: Record<string, unknown>): Promise<string> {
const locale = pickLocale(params)
const payload = await getCachedPayload()
const meta = await siteMeta(payload, locale)
// The homepage always collapses to the language root ('/' on single-locale sites).
const home = config.locales.length === 1 ? '/' : `/${locale}`
const lines = [
`Site: ${meta?.siteName || serverName}`,
...(meta?.siteDescription ? [`Description: ${meta.siteDescription}`] : []),
`Languages: ${config.locales.map((l) => `${l.code} (${l.label})`).join(', ')} — default ${config.defaultLocale}`,
`Home: ${origin}${home}`,
...(origin ? [`Sitemap: ${origin}/sitemap.xml`] : []),
'Tools: list_pages (all pages), search_content (keyword search), get_page (one page as Markdown).',
]
return lines.join('\n')
}
async function runList(params: Record<string, unknown>): Promise<string> {
const locale = pickLocale(params)
const limit = typeof params.limit === 'number' ? params.limit : 50
const payload = await getCachedPayload()
const meta = await siteMeta(payload, locale)
const results = await listContent({
baseUrl: origin,
collection,
config,
homeSlug: meta?.homeSlug,
limit,
locale,
payload,
summaryField,
})
if (results.length === 0) {return 'No published pages.'}
return formatResults(results)
}
async function runSearch(params: Record<string, unknown>): Promise<string> {
const query = typeof params.query === 'string' ? params.query.trim() : ''
if (!query) {return 'No query provided.'}
const locale =
typeof params.locale === 'string' && isValidLocale(params.locale, config)
? params.locale
: getDefaultLocale(config)
const locale = pickLocale(params)
const limit = typeof params.limit === 'number' ? params.limit : 10
const payload = await getCachedPayload()
const meta = await siteMeta(payload, locale)
// Shared with the JSON search route — one ranking everywhere.
const results = await searchContent({
baseUrl: origin,
collection,
config,
homeSlug: meta?.homeSlug,
limit,
locale,
payload,
@@ -150,9 +227,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
summaryField,
})
if (results.length === 0) {return `No pages matched "${query}".`}
return results
.map((r) => `- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`)
.join('\n')
return formatResults(results)
}
async function getPage(params: Record<string, unknown>): Promise<string> {
@@ -193,6 +268,8 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
const p = (params ?? {}) as { arguments?: Record<string, unknown>; name?: string }
const toolArgs = p.arguments ?? {}
try {
if (p.name === 'get_site_info') {return rpcResult(id, toolText(await getSiteInfo(toolArgs)))}
if (p.name === 'list_pages') {return rpcResult(id, toolText(await runList(toolArgs)))}
if (p.name === 'search_content') {return rpcResult(id, toolText(await runSearch(toolArgs)))}
if (p.name === 'get_page') {return rpcResult(id, toolText(await getPage(toolArgs)))}
return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true))
-1
View File
@@ -1,5 +1,4 @@
import type { I18nConfig } from '../i18n/index.js'
import type { SystemPageRole } from './types.js'
import { buildLocalizedPath, getLocalizedSlugs } from '../i18n/index.js'
+1 -1
View File
@@ -55,7 +55,7 @@ export function injectSeoTabs(config: Config, seo: SeoOption): Config {
const tabs: TabsField = {
type: 'tabs',
tabs: [
{ fields: otherFields, label: collection.labels?.singular?.toString() || 'Content' },
{ fields: otherFields, label: collection.labels?.singular || 'Content' },
{ fields: [metaField], label: 'SEO' },
],
}
+10
View File
@@ -167,9 +167,19 @@ export type ClientIpOptions = {
* Empty string when nothing usable is present — the limiter then lets the
* request through.
*/
let warnedUnpinned = false
export function clientIp(source: Headers | Request, options: ClientIpOptions = {}): string {
const h = source instanceof Headers ? source : source.headers
const pinned = options.header ?? process.env.IPAL_IP_HEADER
if (!pinned && !warnedUnpinned && process.env.NODE_ENV === 'production') {
warnedUnpinned = true
console.warn(
'[ipal] IPAL_IP_HEADER is not set — the rate limit trusts whichever IP header a request carries, ' +
'so a client reaching the app directly can spoof it. Set IPAL_IP_HEADER=cf-connecting-ip ' +
'(behind Cloudflare) or x-forwarded-for (behind Traefik/nginx only).',
)
}
if (pinned) {
const value = h.get(pinned)
if (!value) {return ''}
+20 -2
View File
@@ -20,6 +20,25 @@ export type TurnstileConfig = {
let warnedPartial = false
function resolveKeys(integrations: IntegrationsWithTurnstileKeys) {
return {
secret: integrations.turnstileSecretKey?.trim() || process.env[TURNSTILE_SECRET_ENV]?.trim() || '',
siteKey: integrations.turnstileSiteKey?.trim() || process.env[TURNSTILE_SITE_KEY_ENV]?.trim() || '',
}
}
/**
* Why Turnstile is half-configured (only one of the two keys set), or null when
* it's fully on or fully off. Shown as a dashboard alert by IntegrationAlerts —
* the half-configured state silently turns Turnstile OFF, which an editor who
* just pasted one key wouldn't expect.
*/
export function turnstileKeyProblem(integrations: IntegrationsWithTurnstileKeys): null | string {
const { secret, siteKey } = resolveKeys(integrations)
if (Boolean(siteKey) === Boolean(secret)) {return null}
return `${siteKey ? 'Secret key' : 'Site key'} is missing, so Turnstile is OFF — forms are not protected. Fill in both keys (or clear both).`
}
/**
* Whether Turnstile is on, and the public key to render it with.
*
@@ -41,8 +60,7 @@ let warnedPartial = false
*/
export async function getTurnstileConfig(payload: BasePayload): Promise<TurnstileConfig> {
const integrations = await getSiteIntegrations<IntegrationsWithTurnstileKeys>(payload)
const siteKey = integrations.turnstileSiteKey?.trim() || process.env[TURNSTILE_SITE_KEY_ENV]?.trim() || ''
const secret = integrations.turnstileSecretKey?.trim() || process.env[TURNSTILE_SECRET_ENV]?.trim() || ''
const { secret, siteKey } = resolveKeys(integrations)
if (siteKey && secret) {return { enabled: true, siteKey }}
+12 -36
View File
@@ -58,10 +58,10 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// --- enforced 2FA (TOTP) via @clocklimited/payload-2fa ---
// Enforced by default (forceSetup) unless twoFactor is explicitly false. The
// plugin is a PEER dependency imported dynamically — ipal-kit doesn't bundle
// it, so projects that opt out (twoFactor: false) needn't install it, and the
// import never runs under generate:importmap when 2FA is off. Wrapping access
// control (not just admin UI) means TOTP gates data access — no API bypass.
// package is an optional PEER the project injects — ipal-kit doesn't bundle
// or import it, so projects that opt out (twoFactor: false) needn't install it.
// Wrapping access control (not just admin UI) means TOTP gates data access —
// no API bypass.
if (options.twoFactor !== false) {
const tf = options.twoFactor
if (!tf?.issuer) {
@@ -71,41 +71,17 @@ export const ipalKit = (options: IpalOptions): Plugin => {
'opt out (discouraged).',
)
}
// 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, resolvable because the package is an optional
// peer. Variable specifier dodges the plugin's own TS2307. Works only
// outside Next (payload CLI): webpack turns it into an empty context, and
// serverExternalPackages fails on the package's own .css imports — in
// Next the project MUST inject `plugin` (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(
'[ipal] 2FA is enforced but @clocklimited/payload-2fa could not be loaded. ' +
'Inject it (required in Next): `import { payloadTotp } from "@clocklimited/payload-2fa"` ' +
'then `twoFactor: { issuer, plugin: payloadTotp }`. Adding it to ' +
'serverExternalPackages does NOT help (the package imports .css). Or set ' +
`twoFactor: false to opt out (discouraged). Original error: ${String(err)}`,
)
}
}
// The project INJECTS the factory (twoFactor.plugin = payloadTotp) — the
// plugin never imports the optional peer itself, so Next has nothing it
// can't bundle. See TotpPluginFactory / docs/security.md.
const totp: TotpPluginFactory | undefined = tf.plugin
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.',
'[ipal] 2FA is enforced but no 2FA plugin was injected. Add ' +
'`import { payloadTotp } from "@clocklimited/payload-2fa"` and pass ' +
'`twoFactor: { issuer, plugin: payloadTotp }`. Or set twoFactor: false ' +
'to opt out (discouraged).',
)
}
+8 -9
View File
@@ -98,16 +98,15 @@ export type IpalOptions = {
issuer: string
/**
* The 2FA plugin factory, INJECTED from the project:
* `import { payloadTotp } from '@clocklimited/payload-2fa'`. REQUIRED in
* Next — injecting it (the same pattern as NextResponse / revalidatePath)
* means the plugin never dynamically imports the optional peer, which
* Next can't bundle ("Cannot find module '@clocklimited/payload-2fa'",
* even on public frontend pages). serverExternalPackages is no fix: the
* package imports its own .css, which Node can't load. If omitted, the
* plugin falls back to a dynamic import — works only outside Next
* (payload CLI). See docs/security.md.
* `import { payloadTotp } from '@clocklimited/payload-2fa'`. Injecting it
* (the same pattern as NextResponse / revalidatePath) means ipal-kit never
* imports the optional peer itself — Next can't bundle such an import
* ("Cannot find module '@clocklimited/payload-2fa'", even on public
* pages), and serverExternalPackages is no fix (the package imports its
* own .css). The payload CLI loads the same config, so it gets the
* injected factory too. See docs/security.md.
*/
plugin?: TotpPluginFactory
plugin: TotpPluginFactory
}
| false
+134
View File
@@ -0,0 +1,134 @@
/**
* End-to-end through a REAL Payload (SQLite in memory): plugin config → form
* built in the "panel" (Local API) → submitForm → stored submission. Catches
* what unit tests with a fake payload can't: schema, access control, hooks.
*/
import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { submitForm } from '../src/modules/forms/submitForm.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
let payload: Payload
let formId: string
beforeAll(async () => {
const config = buildConfig({
collections: [
// Open sign-up, the risky setup the roles field guard exists for.
{ slug: 'users', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }] },
// SiteSettings' logo/favicon upload fields point here.
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: false,
}),
],
secret: 'integration-test-secret',
telemetry: false,
})
payload = await getPayload({ config })
const form = await payload.create({
collection: 'forms' as never,
data: {
confirmationMessage: {
root: {
type: 'root',
children: [
{
type: 'paragraph',
children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'Dziękujemy', version: 1 }],
direction: null,
format: '',
indent: 0,
version: 1,
},
],
direction: null,
format: '',
indent: 0,
version: 1,
},
},
fields: [
{ name: 'name', blockType: 'text', label: 'Imię', required: true },
{ name: 'consent', blockType: 'checkbox', label: 'Zgoda' },
],
title: 'Kontakt',
} as never,
})
formId = String(form.id)
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
describe('forms against a real Payload', () => {
test('a valid submission is stored with only the form fields', async () => {
const result = await submitForm({ data: { name: 'Ala', consent: true }, formId, ip: '10.7.0.1', payload })
expect(result.success).toBe(true)
if (!result.success) {return}
const stored = (await payload.findByID({
id: result.submissionId,
collection: 'form-submissions' as never,
depth: 0,
})) as unknown as { form: number | string; submissionData: { field: string; value: string }[] }
expect(String(stored.form)).toBe(formId)
expect(stored.submissionData.map(({ field, value }) => ({ field, value }))).toEqual([
{ field: 'name', value: 'Ala' },
{ field: 'consent', value: 'true' },
])
})
test('the gates hold: consent, required, unknown keys', async () => {
const send = (data: Record<string, unknown>) => submitForm({ data, formId, ip: '10.7.0.2', maxPerMinute: 0, payload })
expect(await send({ name: 'Ala', consent: false })).toMatchObject({ reason: 'consent' })
expect(await send({ consent: true })).toMatchObject({ field: 'name', reason: 'validation' })
expect(await send({ name: 'Ala', consent: true, role: 'admin' })).toMatchObject({ kind: 'unknown_fields' })
})
test('REST/anonymous creation of submissions is closed (only submitForm writes)', async () => {
await expect(
payload.create({
collection: 'form-submissions' as never,
data: { form: formId, submissionData: [] } as never,
overrideAccess: false,
}),
).rejects.toThrow()
})
test('open sign-up cannot self-assign admin — roles fall back to the default', async () => {
const user = (await payload.create({
collection: 'users',
data: { email: '[email protected]', password: 'Passw0rd!x', roles: ['admin'] } as never,
overrideAccess: false,
})) as unknown as { roles: string[] }
expect(user.roles).toEqual(['user'])
})
test('seed / Local API with overrideAccess can still create an admin', async () => {
const admin = (await payload.create({
collection: 'users',
data: { email: '[email protected]', password: 'Passw0rd!x', roles: ['admin'] } as never,
})) as unknown as { roles: string[] }
expect(admin.roles).toEqual(['admin'])
})
})
+113
View File
@@ -0,0 +1,113 @@
import type { BasePayload } from 'payload'
import { afterEach, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { createMcpRoute } from '../src/modules/mcp/createMcpRoute.js'
const config: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
const pages = [
{ id: 1, slug: 'o-nas', _status: 'published', meta: { description: 'Kim jesteśmy' }, title: 'O nas' },
{ id: 2, slug: 'szkic', _status: 'draft', title: 'Szkic' },
{ id: 3, slug: 'ukryta', _status: 'published', noindex: true, title: 'Ukryta' },
{ id: 4, slug: 'strona-glowna', _status: 'published', title: 'Start' },
]
const payload = {
find: vi.fn(async () => ({ docs: pages })),
findGlobal: vi.fn(async () => ({
homepage: { id: 4, slug: 'strona-glowna' },
siteDescription: 'Usługi IT',
siteName: 'Acme',
})),
} as unknown as BasePayload
let n = 0
const mcp = createMcpRoute({ baseUrl: 'https://acme.pl/', config, getCachedPayload: async () => payload })
async function rpc(body: unknown, ip = `10.1.0.${++n}`) {
const res = await mcp.POST(
new Request('https://acme.pl/api/mcp', {
body: JSON.stringify(body),
headers: { 'content-type': 'application/json', 'x-real-ip': ip },
method: 'POST',
}),
)
return { body: res.status === 202 ? null : await res.json(), status: res.status }
}
const call = async (name: string, args: Record<string, unknown> = {}) => {
const { body } = await rpc({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { name, arguments: args } })
return (body as { result: { content: { text: string }[]; isError?: boolean } }).result
}
describe('createMcpRoute', () => {
afterEach(() => vi.clearAllMocks())
test('initialize + tools/list advertise the four read-only tools', async () => {
const init = await rpc({ id: 1, jsonrpc: '2.0', method: 'initialize', params: { protocolVersion: '2025-06-18' } })
expect(init.body.result.capabilities.tools).toBeDefined()
const list = await rpc({ id: 2, jsonrpc: '2.0', method: 'tools/list' })
expect(list.body.result.tools.map((t: { name: string }) => t.name)).toEqual([
'get_site_info',
'list_pages',
'search_content',
'get_page',
])
})
test('get_site_info: name, description, languages, home URL', async () => {
const text = (await call('get_site_info')).content[0].text
expect(text).toContain('Site: Acme')
expect(text).toContain('Description: Usługi IT')
expect(text).toContain('pl (Polski), en (English) — default pl')
expect(text).toContain('Home: https://acme.pl/pl')
expect(text).toContain('Sitemap: https://acme.pl/sitemap.xml')
})
test('list_pages: only published, indexable pages; home collapses to the root', async () => {
const text = (await call('list_pages')).content[0].text
expect(text).toContain('- O nas (https://acme.pl/pl/o-nas) — Kim jesteśmy')
expect(text).toContain('- Start (https://acme.pl/pl)')
expect(text).not.toContain('Szkic')
expect(text).not.toContain('Ukryta')
})
test('search_content needs a query', async () => {
expect((await call('search_content')).content[0].text).toBe('No query provided.')
expect((await call('search_content', { query: 'nas' })).content[0].text).toContain('O nas')
})
test('tool errors stay generic (no internals leak)', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
;(payload.find as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('ECONNREFUSED db:5432'))
const res = await call('get_page', { path: '/pl/o-nas' })
expect(res.isError).toBe(true)
expect(res.content[0].text).toBe('Tool execution failed.')
})
test('protocol edges: notifications, unknown method, parse error, batch cap', async () => {
expect((await rpc({ jsonrpc: '2.0', method: 'notifications/initialized' })).status).toBe(202)
expect((await rpc({ id: 9, jsonrpc: '2.0', method: 'nope' })).body.error.code).toBe(-32601)
const bad = await mcp.POST(new Request('https://acme.pl/api/mcp', { body: '{', method: 'POST' }))
expect(bad.status).toBe(400)
const batch = Array.from({ length: 11 }, (_, i) => ({ id: i, jsonrpc: '2.0', method: 'ping' }))
expect((await rpc(batch)).status).toBe(400)
expect((await mcp.GET()).status).toBe(405)
})
test('rate limit counts every message in a batch', async () => {
const ip = '10.9.9.9'
const batch = Array.from({ length: 10 }, (_, i) => ({ id: i, jsonrpc: '2.0', method: 'ping' }))
for (let i = 0; i < 6; i++) {expect((await rpc(batch, ip)).status).toBe(200)}
expect((await rpc(batch, ip)).status).toBe(429)
})
})
+4 -1
View File
@@ -35,7 +35,10 @@ describe('ipalKit — config transform', () => {
})
test('enforces 2FA unless explicitly disabled', async () => {
await expect(ipalKit({ i18n })(base())).rejects.toThrow(/twoFactor\.issuer is required/)
await expect(ipalKit({ i18n } as never)(base())).rejects.toThrow(/twoFactor\.issuer is required/)
await expect(ipalKit({ i18n, twoFactor: { issuer: 'Acme' } } as never)(base())).rejects.toThrow(
/no 2FA plugin was injected/,
)
const totp = vi.fn(() => (c: Config) => c)
await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: totp as never } })(base())
+18
View File
@@ -95,3 +95,21 @@ describe('consumeRateLimit', () => {
warn.mockRestore()
})
})
describe('IPAL_IP_HEADER', () => {
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
test('ipalEnvRules({ ipHeader }) requires it in production only', async () => {
const { assertEnv } = await import('../src/modules/env/assertEnv.js')
const { ipalEnvRules } = await import('../src/modules/env/ipalEnvRules.js')
const base = { DATABASE_URI: 'x', NEXT_PUBLIC_SERVER_URL: 'https://acme.pl', PAYLOAD_SECRET: 'x' }
vi.stubEnv('NODE_ENV', 'production')
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: base })).toThrow(/IPAL_IP_HEADER/)
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: { ...base, IPAL_IP_HEADER: 'cf-connecting-ip' } })).not.toThrow()
vi.stubEnv('NODE_ENV', 'development')
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: base })).not.toThrow()
})
})
+161
View File
@@ -0,0 +1,161 @@
import { describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { parseConsent, serializeConsent } from '../src/modules/consent/storage.js'
import { markdownHref, prefersMarkdown } from '../src/modules/content/markdownNegotiation.js'
import { lexicalToMarkdown } from '../src/modules/richtext/lexicalToMarkdown.js'
import { buildCsp } from '../src/modules/security/buildCsp.js'
import { buildSecurityHeaders } from '../src/modules/security/buildSecurityHeaders.js'
import { AI_TRAINING_BOTS, buildRobots } from '../src/modules/seo/buildRobots.js'
import { buildSitemapXml } from '../src/modules/seo/buildSitemapXml.js'
import { buildHreflangAlternates } from '../src/modules/seo/hreflang.js'
const config: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
describe('buildRobots', () => {
test('defaults: allow all but admin/api, sitemap, explicit AI allow', () => {
const r = buildRobots({ baseUrl: 'https://acme.pl/' })
expect(r.sitemap).toBe('https://acme.pl/sitemap.xml')
expect(r.host).toBe('https://acme.pl')
const [base, ai] = r.rules as { disallow: string[]; userAgent: string | string[] }[]
expect(base.disallow).toEqual(['/admin', '/api'])
expect(ai.userAgent).toEqual(expect.arrayContaining(['ClaudeBot', 'GPTBot']))
})
test('hidden admin route is not revealed', () => {
const r = buildRobots({ adminRoute: false, aiBots: false, baseUrl: 'https://acme.pl' })
expect((r.rules as { disallow: string[] }).disallow).toEqual(['/api'])
})
test('block-training keeps assistants, blocks training crawlers', () => {
const rules = buildRobots({ aiBots: 'block-training', baseUrl: 'https://acme.pl' }).rules as {
disallow: string[]
userAgent: string[]
}[]
const training = rules.find((r) => r.userAgent.includes(AI_TRAINING_BOTS[0]))
expect(training?.disallow).toEqual(['/'])
})
test('disallowParams covers the param in any position', () => {
const r = buildRobots({ aiBots: false, baseUrl: 'https://acme.pl', disallowParams: ['s'] })
expect((r.rules as { disallow: string[] }).disallow).toEqual(['/admin', '/api', '/*?s=', '/*&s='])
})
})
describe('buildSitemapXml', () => {
test('escapes URLs and emits hreflang alternates', () => {
const xml = buildSitemapXml(
[
{
alternates: { languages: { en: 'https://acme.pl/en/a', pl: 'https://acme.pl/pl/a' } },
lastModified: new Date('2026-01-02T00:00:00Z'),
url: 'https://acme.pl/pl/a?x=1&y=2',
},
],
{ cssUrl: '/sitemap.css' },
)
expect(xml).toMatch(/^<\?xml/)
expect(xml).toContain('<?xml-stylesheet type="text/css" href="/sitemap.css"?>')
expect(xml).toContain('<loc>https://acme.pl/pl/a?x=1&amp;y=2</loc>')
expect(xml).toContain('<lastmod>2026-01-02T00:00:00.000Z</lastmod>')
expect(xml).toContain('<xhtml:link rel="alternate" hreflang="en" href="https://acme.pl/en/a"/>')
})
})
describe('buildHreflangAlternates', () => {
test('one URL per locale plus x-default → default locale', () => {
expect(
buildHreflangAlternates({ baseUrl: 'https://acme.pl', config, slugs: { en: 'about', pl: 'o-nas' } }),
).toEqual({
en: 'https://acme.pl/en/about',
pl: 'https://acme.pl/pl/o-nas',
'x-default': 'https://acme.pl/pl/o-nas',
})
})
test('single-locale sites get no alternates', () => {
const single: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
expect(buildHreflangAlternates({ config: single, slugs: { pl: 'o-nas' } })).toEqual({})
})
})
describe('security headers', () => {
test('CSP: hard defaults, opt-in sources, report-only header name', () => {
const csp = buildCsp({ turnstile: true })
expect(csp.key).toBe('Content-Security-Policy')
expect(csp.value).toContain("frame-ancestors 'none'")
expect(csp.value).toContain("object-src 'none'")
expect(csp.value).toMatch(/script-src [^;]*https:\/\/challenges\.cloudflare\.com/)
expect(csp.value).not.toContain('unsafe-eval')
expect(buildCsp({ mode: 'report-only' }).key).toBe('Content-Security-Policy-Report-Only')
})
test('CSP: relative R2 URL is not added (already self)', () => {
expect(buildCsp({ r2Url: '/media' }).value).not.toContain('/media')
expect(buildCsp({ r2Url: 'https://cdn.acme.pl' }).value).toContain('https://cdn.acme.pl')
})
test('headers: HSTS, nosniff, overrides by key', () => {
const headers = buildSecurityHeaders({ additional: [{ key: 'x-frame-options', value: 'SAMEORIGIN' }] })
const get = (k: string) => headers.find((h) => h.key.toLowerCase() === k.toLowerCase())?.value
expect(get('Strict-Transport-Security')).toBe('max-age=63072000; includeSubDomains')
expect(get('X-Content-Type-Options')).toBe('nosniff')
expect(get('X-Frame-Options')).toBe('SAMEORIGIN')
expect(headers.filter((h) => h.key.toLowerCase() === 'x-frame-options')).toHaveLength(1)
})
})
describe('Markdown for AI', () => {
test('markdownHref', () => {
expect(markdownHref('/pl/o-nas')).toBe('/md/pl/o-nas')
expect(markdownHref('/')).toBe('/md')
expect(markdownHref('pl', '/ai/')).toBe('/ai/pl')
})
test('prefersMarkdown respects q-values', () => {
expect(prefersMarkdown('text/markdown')).toBe(true)
expect(prefersMarkdown('text/html,text/markdown;q=0.5')).toBe(false)
expect(prefersMarkdown(new Headers({ accept: 'text/markdown, text/html' }))).toBe(true)
expect(prefersMarkdown('text/html')).toBe(false)
expect(prefersMarkdown(undefined)).toBe(false)
})
test('lexicalToMarkdown renders the common nodes', () => {
const text = (t: string, format = 0) => ({ type: 'text', format, text: t })
const md = lexicalToMarkdown({
root: {
children: [
{ type: 'heading', children: [text('Tytuł')], tag: 'h2' },
{ type: 'paragraph', children: [text('Zwykły '), text('gruby', 1), text(' i '), text('kursywa', 2)] },
{ type: 'paragraph', children: [{ type: 'link', children: [text('link')], fields: { url: 'https://acme.pl' } }] },
{ type: 'paragraph', children: [] },
{ type: 'upload', value: { alt: 'Logo', url: '/media/logo.png' } },
],
},
} as never)
expect(md).toBe(
'## Tytuł\n\nZwykły **gruby** i _kursywa_\n\n[link](https://acme.pl)\n\n![Logo](/media/logo.png)',
)
expect(lexicalToMarkdown(null)).toBe('')
})
})
describe('consent cookie', () => {
test('round-trips and always keeps necessary on', () => {
const raw = serializeConsent({ analytics: true, functional: false, marketing: false, necessary: false } as never)
expect(parseConsent(raw)).toMatchObject({ analytics: true, marketing: false, necessary: true })
})
test('garbage or an old version → null (ask again)', () => {
expect(parseConsent('%%%')).toBeNull()
expect(parseConsent(encodeURIComponent(JSON.stringify({ state: {}, version: 0 })))).toBeNull()
expect(parseConsent(undefined)).toBeNull()
})
})
+14
View File
@@ -157,3 +157,17 @@ describe('submitForm — other gates', () => {
)
})
})
describe('turnstileKeyProblem', () => {
afterEach(() => vi.unstubAllEnvs())
test('only flags a half-configured setup', async () => {
const { turnstileKeyProblem } = await import('../src/modules/turnstile/config.js')
expect(turnstileKeyProblem({})).toBeNull()
expect(turnstileKeyProblem({ turnstileSecretKey: 's', turnstileSiteKey: 'k' })).toBeNull()
expect(turnstileKeyProblem({ turnstileSiteKey: 'k' })).toMatch(/Secret key is missing/)
expect(turnstileKeyProblem({ turnstileSecretKey: 's' })).toMatch(/Site key is missing/)
vi.stubEnv('TURNSTILE_SECRET_KEY', 's')
expect(turnstileKeyProblem({ turnstileSiteKey: 'k' })).toBeNull()
})
})