Merge main (security-perf + SEO) into docs; finish English docs and agent guide
- Resolve conflicts in analytics, consent, content, i18n, mcp and stats, keeping the docs fixes and the new code behaviour, verified against src - Translate the remaining 14 module pages, ipal-seo-check skill and script - Integrate the security-perf and SEO agent-guide text: getRobots, isPathVisible, Search & AI (DNS verification first, meta fields optional), sitemap index/cache/503, consentMode basic/advanced, policyVersion, globalOverrides, revalidatePath / buildGlobalRevalidateHook, authAccess, firstUserAdmin, allowCollectionMismatch, unknown-IP rate limit; stale claims fixed across AGENT.md, skills, frontend, developer guide, vibe - docsConsistency: pending list removed (all docs English); relative links now also check #anchors Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+221
-178
@@ -1,20 +1,21 @@
|
||||
# security
|
||||
|
||||
Generyczne nagłówki bezpieczeństwa HTTP (HSTS, X-Frame-Options, nosniff,
|
||||
Referrer-Policy, Permissions-Policy) jako funkcja do `next.config`. CSP CELOWO
|
||||
pominięte — zależy od domen projektu, zostaje w projekcie.
|
||||
Generic HTTP security headers (HSTS, X-Frame-Options, nosniff,
|
||||
Referrer-Policy, Permissions-Policy, Cross-Origin-Opener-Policy; `X-Robots-Tag` on staging)
|
||||
as a function for `next.config`. CSP is DELIBERATELY
|
||||
left out — it depends on the project's domains, so it stays in the project.
|
||||
|
||||
## Zasada
|
||||
## Rule
|
||||
|
||||
Nagłówki, które są IDENTYCZNE między projektami, plugin dostarcza raz. CSP
|
||||
(Content-Security-Policy) wymaga znajomości domen konkretnego projektu (skąd
|
||||
ładują się skrypty, obrazy, fonty, analytics), więc nie może być generyczne —
|
||||
zostaje w projekcie, dodawane przez `additional`.
|
||||
Headers that are IDENTICAL across projects are provided once by the plugin. CSP
|
||||
(Content-Security-Policy) needs to know the domains of a specific project (where
|
||||
scripts, images, fonts and analytics load from), so it cannot be generic —
|
||||
it stays in the project and is added through `additional`.
|
||||
|
||||
## Użycie — next.config.ts
|
||||
## Usage — next.config.ts
|
||||
|
||||
Nagłówki wpina się w `next.config`, NIE w proxy — bo muszą pokryć CAŁĄ
|
||||
aplikację (też `/admin`, statyki), a proxy pomija te trasy.
|
||||
Wire the headers in `next.config`, NOT in the proxy — they must cover the WHOLE
|
||||
application (including `/admin` and static files), and the proxy skips those routes.
|
||||
|
||||
```ts
|
||||
// next.config.ts
|
||||
@@ -23,9 +24,9 @@ import type { NextConfig } from 'next'
|
||||
import { buildSecurityHeaders } from '@intecion/ipal-kit'
|
||||
|
||||
const securityHeaders = buildSecurityHeaders({
|
||||
hsts: process.env.NODE_ENV === 'production', // WAŻNE: off w dev (http)
|
||||
hsts: process.env.NODE_ENV === 'production', // IMPORTANT: off in dev (http)
|
||||
additional: [
|
||||
// CSP projektu — zna swoje domeny:
|
||||
// the project's CSP — it knows its own domains:
|
||||
// { key: 'Content-Security-Policy', value: "default-src 'self'; ..." },
|
||||
],
|
||||
})
|
||||
@@ -39,56 +40,63 @@ const nextConfig: NextConfig = {
|
||||
export default withPayload(nextConfig)
|
||||
```
|
||||
|
||||
## Opcje
|
||||
## Options
|
||||
|
||||
| Opcja | Domyślnie | Rola |
|
||||
| Option | Default | Role |
|
||||
|---|---|---|
|
||||
| `hsts` | `true` | Strict-Transport-Security (wymuś HTTPS) |
|
||||
| `hstsMaxAge` | `63072000` (2 lata) | max-age HSTS w sekundach |
|
||||
| `hstsIncludeSubDomains` | `true` | HSTS na subdomeny |
|
||||
| `hstsPreload` | `false` | preload (tylko jeśli zgłaszasz do listy) |
|
||||
| `frameOptions` | `'DENY'` | X-Frame-Options (anty-clickjacking) |
|
||||
| `referrerPolicy` | `'strict-origin-when-cross-origin'` | Referrer-Policy |
|
||||
| `permissionsPolicy` | blokuje camera/mic/geolocation | Permissions-Policy |
|
||||
| `additional` | `[]` | dodatkowe nagłówki (np. CSP); same-key nadpisuje |
|
||||
| `hsts` | `true` | Strict-Transport-Security (force HTTPS) |
|
||||
| `hstsMaxAge` | `63072000` (2 years) | HSTS max-age in seconds |
|
||||
| `hstsIncludeSubDomains` | `true` | HSTS on subdomains |
|
||||
| `hstsPreload` | `false` | preload (only if you submit to the list) |
|
||||
| `frameOptions` | `'DENY'` | X-Frame-Options (anti-clickjacking); `null` = no header |
|
||||
| `referrerPolicy` | `'strict-origin-when-cross-origin'` | Referrer-Policy; `null` = no header |
|
||||
| `permissionsPolicy` | blocks camera/mic/geolocation | Permissions-Policy; your own string, or `null` = no header |
|
||||
| `coop` | `'same-origin'` | Cross-Origin-Opener-Policy; `'same-origin-allow-popups'`, or `false` = no header |
|
||||
| `additional` | `[]` | extra headers (e.g. CSP); the same key overrides |
|
||||
|
||||
## PUŁAPKA — HSTS w dev
|
||||
With `IPAL_NOINDEX=1` (staging), `X-Robots-Tag: noindex, nofollow` is added to every response.
|
||||
|
||||
HSTS nad HTTP na localhost może zablokować przeglądarkę na HTTPS dla localhost.
|
||||
ZAWSZE wyłączaj w dev: `hsts: process.env.NODE_ENV === 'production'`.
|
||||
**Uploads:** `buildUploadSecurityHeaders({ collections = ['media'] })` returns `headers()` rules for
|
||||
`/api/<collection>/file/*` (sandbox, no scripts) — an SVG from local disk cannot run a script on the site's
|
||||
domain. Wire it alongside: `[{ source: '/:path*', headers: securityHeaders }, ...buildUploadSecurityHeaders()]`.
|
||||
|
||||
## Nadpisywanie i CSP
|
||||
## TRAP — HSTS in dev
|
||||
|
||||
`additional` z tym samym kluczem NADPISUJE domyślny (np. zmień X-Frame-Options
|
||||
na SAMEORIGIN). Nowy klucz (jak CSP) dodaje. CSP zawsze przez `additional` —
|
||||
plugin go nie generuje, bo zależy od projektu.
|
||||
HSTS over HTTP on localhost can lock the browser into HTTPS for localhost.
|
||||
ALWAYS turn it off in dev: `hsts: process.env.NODE_ENV === 'production'`.
|
||||
|
||||
### Dlaczego CSP zostaje w projekcie (nie plugin)
|
||||
## Overriding and CSP
|
||||
|
||||
HSTS, nosniff, Referrer-Policy są IDENTYCZNE dla każdego projektu → plugin je
|
||||
generuje. CSP wylicza KONKRETNE domeny, z których projekt ładuje (jego R2,
|
||||
analytics, Turnstile, fonty). Generyczny CSP byłby albo za luźny (`*` =
|
||||
bezużyteczny), albo psułby stronę. Więc plugin daje mechanizm (`additional`),
|
||||
projekt dostarcza CSP dopasowany do siebie.
|
||||
`additional` with the same key OVERRIDES the default (e.g. change X-Frame-Options
|
||||
to SAMEORIGIN). A new key (like CSP) is added. CSP always goes through `additional` —
|
||||
the plugin does not generate it, because it depends on the project.
|
||||
|
||||
### buildCsp — generator CSP (zalecane zamiast ręcznego)
|
||||
### Why CSP stays in the project (not the plugin)
|
||||
|
||||
Zamiast pisać surowy CSP w każdym projekcie (ryzyko pominięcia base-uri,
|
||||
object-src), użyj `buildCsp` — ma twarde reguły OWASP/Lighthouse wbudowane, a Ty
|
||||
włączasz tylko flagi tego, co projekt ładuje:
|
||||
HSTS, nosniff and Referrer-Policy are IDENTICAL for every project → the plugin
|
||||
generates them. CSP lists the SPECIFIC domains the project loads from (its R2,
|
||||
analytics, Turnstile, fonts). A generic CSP would be either too loose (`*` =
|
||||
useless) or would break the site. So the plugin provides the mechanism (`additional`),
|
||||
and the project supplies a CSP that fits it.
|
||||
|
||||
### buildCsp — CSP generator (recommended over writing it by hand)
|
||||
|
||||
Instead of writing a raw CSP in every project (risk of forgetting base-uri,
|
||||
object-src), use `buildCsp` — it has hard OWASP/Lighthouse rules built in, and you
|
||||
turn on only the flags for what the project loads:
|
||||
|
||||
```ts
|
||||
// next.config.ts
|
||||
import { buildCsp, buildSecurityHeaders } from '@intecion/ipal-kit'
|
||||
|
||||
const csp = buildCsp({
|
||||
mode: 'report-only', // zacznij tu; 'enforce' gdy konsola czysta
|
||||
r2Url: process.env.R2_PUBLIC_URL, // media R2 → img-src
|
||||
mode: 'report-only', // start here; 'enforce' once the console is clean
|
||||
r2Url: process.env.R2_PUBLIC_URL, // R2 media → img-src
|
||||
turnstile: true, // challenges.cloudflare.com → script/frame/connect
|
||||
analytics: true, // GTM + GA
|
||||
youtube: true, // youtube → frame-src
|
||||
googleMaps: true, // mapy Google
|
||||
// extra: { 'script-src': ['https://inny-skrypt.pl'] }, // dodatkowe źródła
|
||||
googleMaps: true, // Google Maps
|
||||
// extra: { 'script-src': ['https://other-script.example'] }, // extra sources
|
||||
})
|
||||
|
||||
const securityHeaders = buildSecurityHeaders({
|
||||
@@ -97,21 +105,27 @@ const securityHeaders = buildSecurityHeaders({
|
||||
})
|
||||
```
|
||||
|
||||
**Twarde reguły wbudowane** (zawsze, nie da się zapomnieć): `base-uri 'self'`,
|
||||
`object-src 'none'`, `frame-ancestors 'none'`. To te, które Lighthouse/OWASP
|
||||
wymagają, a łatwo je pominąć pisząc CSP ręcznie.
|
||||
**Hard rules built in** (always on, impossible to forget): `base-uri 'self'`,
|
||||
`object-src 'none'`, `frame-ancestors 'none'`. These are the ones Lighthouse/OWASP
|
||||
require and that are easy to miss when writing CSP by hand.
|
||||
|
||||
`buildCsp` NIE dodaje `'unsafe-eval'` (osłabia CSP) — dodaj przez `extra` tylko
|
||||
jeśli biblioteka tego wymaga. `mode: 'report-only'` daje nagłówek
|
||||
`…-Report-Only`; `'enforce'` daje `Content-Security-Policy`.
|
||||
Base sources: `default-src 'self'`, `form-action 'self'`, `script-src 'self' 'unsafe-inline'`
|
||||
(Next / analytics), `style-src 'self' 'unsafe-inline' https://fonts.googleapis.com`. `r2Url` goes into
|
||||
`img-src` only as an absolute address (`https://…`); `youtube` also adds `i.ytimg.com` (the
|
||||
`YouTubeEmbed` poster); `googleMaps` adds `*.googleapis.com`, `*.gstatic.com`, `*.google.com`, `*.ggpht.com`,
|
||||
`*.googleusercontent.com` (iframe and Maps JS).
|
||||
|
||||
CSP dalej „w projekcie" (Ty wybierasz flagi wg tego, co ładujesz), ale skeleton
|
||||
jest z pluginu — każdy projekt ma ten sam zahardowany fundament.
|
||||
`buildCsp` does NOT add `'unsafe-eval'` (it weakens CSP) — add it through `extra` only
|
||||
if a library requires it. `mode` defaults to `'enforce'` (`Content-Security-Policy`);
|
||||
`'report-only'` gives `…-Report-Only` — start with it when rolling out.
|
||||
|
||||
### Budowa CSP — ręcznie (jeśli potrzebujesz pełnej kontroli)
|
||||
CSP is still "in the project" (you pick the flags for what you load), but the skeleton
|
||||
comes from the plugin — every project has the same hardened foundation.
|
||||
|
||||
Domenę mediów czytaj z `R2_PUBLIC_URL` (env), nie zaszywaj. Resztę źródeł
|
||||
dopasuj do tego, co projekt faktycznie ładuje:
|
||||
### Building CSP by hand (if you need full control)
|
||||
|
||||
Read the media domain from `R2_PUBLIC_URL` (env), do not hard-code it. Match the other
|
||||
sources to what the project actually loads:
|
||||
|
||||
```ts
|
||||
// next.config.ts
|
||||
@@ -119,19 +133,19 @@ const r2Url = process.env.R2_PUBLIC_URL || ''
|
||||
|
||||
const csp = [
|
||||
"default-src 'self'",
|
||||
// skrypty: self + Turnstile (Cloudflare) + analytics (GTM/GA jeśli używasz)
|
||||
// scripts: self + Turnstile (Cloudflare) + analytics (GTM/GA if you use them)
|
||||
"script-src 'self' 'unsafe-inline' https://challenges.cloudflare.com https://*.googletagmanager.com",
|
||||
// style: self + inline (Tailwind) + Google Fonts
|
||||
// styles: self + inline (Tailwind) + Google Fonts
|
||||
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
|
||||
// obrazy: self + media R2 (z env!) + data:
|
||||
// images: self + R2 media (from env!) + data:
|
||||
`img-src 'self' data: https://*.google-analytics.com https://*.googletagmanager.com ${r2Url}`.trim(),
|
||||
"font-src 'self' https://fonts.gstatic.com data:",
|
||||
// GA4: wildcardy obowiązkowe — ruch z UE idzie na region1.google-analytics.com
|
||||
// GA4: wildcards are required — EU traffic goes to region1.google-analytics.com
|
||||
"connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com",
|
||||
// ramki: Turnstile (widget captcha)
|
||||
// frames: Turnstile (captcha widget)
|
||||
"frame-src https://challenges.cloudflare.com",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'", // zastępuje X-Frame-Options w nowych przeglądarkach
|
||||
"frame-ancestors 'none'", // replaces X-Frame-Options in modern browsers
|
||||
].join('; ')
|
||||
|
||||
const securityHeaders = buildSecurityHeaders({
|
||||
@@ -140,131 +154,131 @@ const securityHeaders = buildSecurityHeaders({
|
||||
})
|
||||
```
|
||||
|
||||
Dopasuj źródła do projektu: mapy Google (`https://maps.googleapis.com`,
|
||||
`https://*.google.com`), inne embedy, inne analytics. To, czego nie wymienisz,
|
||||
zostanie zablokowane.
|
||||
Match the sources to the project: Google Maps (`https://maps.googleapis.com`,
|
||||
`https://*.google.com`), other embeds, other analytics. Anything you do not list
|
||||
will be blocked.
|
||||
|
||||
### WDRAŻAJ CSP OSTROŻNIE — najpierw Report-Only
|
||||
### ROLL OUT CSP CAREFULLY — Report-Only first
|
||||
|
||||
CSP za ścisły **psuje stronę** (blokuje skrypty/style/obrazy). NIGDY nie wdrażaj
|
||||
enforcing CSP na ślepo. Metoda bezpieczna:
|
||||
A CSP that is too strict **breaks the site** (blocks scripts/styles/images). NEVER deploy
|
||||
an enforcing CSP blindly. The safe method:
|
||||
|
||||
1. **Najpierw raportowanie** — użyj klucza `Content-Security-Policy-Report-Only`
|
||||
(nie `Content-Security-Policy`). Przeglądarka RAPORTUJE naruszenia w konsoli,
|
||||
ale NIE blokuje — strona działa normalnie.
|
||||
1. **Reporting first** — use the key `Content-Security-Policy-Report-Only`
|
||||
(not `Content-Security-Policy`). The browser REPORTS violations in the console
|
||||
but does NOT block — the site works as usual.
|
||||
```ts
|
||||
additional: [{ key: 'Content-Security-Policy-Report-Only', value: csp }]
|
||||
```
|
||||
2. **Otwórz stronę** → DevTools → Console → szukaj „Content Security Policy"
|
||||
violations. Każde naruszenie = brakująca domena. Dodaj ją do odpowiedniej
|
||||
dyrektywy CSP.
|
||||
3. **Przejdź przez cały serwis** — strona główna, formularze (Turnstile!),
|
||||
galeria (obrazy R2), strony z mapą/embedami. Zbierz wszystkie naruszenia.
|
||||
4. **Dopiero gdy konsola czysta** → zmień klucz na `Content-Security-Policy`
|
||||
(enforcing). Teraz CSP chroni, nie psując.
|
||||
2. **Open the site** → DevTools → Console → look for "Content Security Policy"
|
||||
violations. Each violation = a missing domain. Add it to the matching CSP
|
||||
directive.
|
||||
3. **Go through the whole site** — home page, forms (Turnstile!),
|
||||
gallery (R2 images), pages with maps/embeds. Collect every violation.
|
||||
4. **Only when the console is clean** → change the key to `Content-Security-Policy`
|
||||
(enforcing). Now CSP protects without breaking anything.
|
||||
|
||||
### Weryfikacja nagłówków na produkcji
|
||||
### Checking headers in production
|
||||
|
||||
```bash
|
||||
# sprawdź, które nagłówki faktycznie wychodzą:
|
||||
curl -sI https://<DOMENA>/pl | grep -i "strict-transport\|content-type-options\|referrer\|content-security\|x-frame"
|
||||
# check which headers actually go out:
|
||||
curl -sI https://<DOMAIN>/pl | grep -i "strict-transport\|content-type-options\|referrer\|content-security\|x-frame"
|
||||
```
|
||||
|
||||
Jeśli HSTS/nosniff/Referrer są, a CSP brak → dodaj CSP (wyżej). Jeśli BRAK
|
||||
wszystkich mimo buildSecurityHeaders w config → sprawdź, czy `headers()` jest
|
||||
wpięte i czy Cloudflare (jeśli przed aplikacją) nie filtruje nagłówków.
|
||||
If HSTS/nosniff/Referrer are there but CSP is missing → add CSP (above). If ALL of them
|
||||
are missing despite buildSecurityHeaders in the config → check that `headers()` is
|
||||
wired and that Cloudflare (if it sits in front of the app) does not filter headers.
|
||||
|
||||
> Uwaga Cloudflare: jeśli CF jest przed aplikacją, może nadpisywać/filtrować
|
||||
> nagłówki. Wtedy ustaw je też w CF (Transform Rules → Modify Response Header)
|
||||
> albo upewnij się, że CF przepuszcza nagłówki z origin.
|
||||
> Cloudflare note: if CF sits in front of the app, it may override/filter
|
||||
> headers. Then set them in CF as well (Transform Rules → Modify Response Header),
|
||||
> or make sure CF passes the origin's headers through.
|
||||
|
||||
|
||||
## COOP (Cross-Origin-Opener-Policy) — domyślnie włączony
|
||||
## COOP (Cross-Origin-Opener-Policy) — on by default
|
||||
|
||||
buildSecurityHeaders wysyła domyślnie `Cross-Origin-Opener-Policy: same-origin` —
|
||||
izoluje kontekst przeglądarki (ochrona przed XS-Leaks / Spectre, wyciekiem
|
||||
window.opener). Uniwersalny nagłówek, więc z automatu.
|
||||
buildSecurityHeaders sends `Cross-Origin-Opener-Policy: same-origin` by default —
|
||||
it isolates the browsing context (protection against XS-Leaks / Spectre and
|
||||
window.opener leaks). It is a universal header, so it is on automatically.
|
||||
|
||||
- Domyślnie `same-origin` (najbezpieczniejsze)
|
||||
- `coop: 'same-origin-allow-popups'` — jeśli otwierasz popupy OAuth/płatności
|
||||
wymagające window.opener
|
||||
- `coop: false` — wyłącz (rzadko potrzebne)
|
||||
- Default `same-origin` (the safest)
|
||||
- `coop: 'same-origin-allow-popups'` — if you open OAuth/payment popups
|
||||
that need window.opener
|
||||
- `coop: false` — turn it off (rarely needed)
|
||||
|
||||
## Trusted Types — NIE wdrażać (na teraz)
|
||||
## Trusted Types — do NOT roll out (for now)
|
||||
|
||||
NIE wymuszaj `require-trusted-types-for 'script'`. Powód:
|
||||
- Audyt Lighthouse to „Bez oceny" (informacyjny/eksperymentalny w Chromium)
|
||||
- Wymuszenie bez kompleksowego silnika polityk w Next/React powoduje `TypeError`
|
||||
przy zewnętrznych skryptach manipulujących DOM stringami (Turnstile, GA)
|
||||
- Zysk bezpieczeństwa nie równoważy ryzyka zepsucia strony
|
||||
Do NOT enforce `require-trusted-types-for 'script'`. Why:
|
||||
- The Lighthouse audit is "Not scored" (informational/experimental in Chromium)
|
||||
- Enforcing it without a complete policy engine in Next/React causes a `TypeError`
|
||||
with third-party scripts that manipulate the DOM with strings (Turnstile, GA)
|
||||
- The security gain does not outweigh the risk of breaking the site
|
||||
|
||||
Zostaw Trusted Types poza CSP, dopóki Next/React nie da natywnego wsparcia.
|
||||
Leave Trusted Types out of CSP until Next/React support it natively.
|
||||
|
||||
## Zmiana ścieżki panelu admina (/admin → /its)
|
||||
## Changing the admin panel path (/admin → /its)
|
||||
|
||||
Ukrycie panelu przed botami skanującymi znane ścieżki (`/admin`, `/wp-admin`).
|
||||
Plugin ustawia ścieżkę przez opcję `adminRoute`:
|
||||
Hides the panel from bots that scan well-known paths (`/admin`, `/wp-admin`).
|
||||
The plugin sets the path through the `adminRoute` option:
|
||||
|
||||
```ts
|
||||
// payload.config.ts
|
||||
ipalKit({
|
||||
i18n: i18nConfig,
|
||||
adminRoute: '/its', // panel pod /its zamiast /admin
|
||||
adminRoute: '/its', // panel at /its instead of /admin
|
||||
})
|
||||
```
|
||||
|
||||
**`robots.txt` przy ukrytym panelu:** domyślny `robots` blokuje `/admin`. Nie
|
||||
wpisuj tam `/its` — `robots.txt` jest publiczny i zdradziłby ścieżkę (panel i
|
||||
tak ma `noindex`). W `createContentHelpers` ustaw `robots: { adminRoute: false }`.
|
||||
**`robots.txt` with a hidden panel:** the default `robots` blocks `/admin`. Do not
|
||||
put `/its` there — `robots.txt` is public and would reveal the path (the panel has
|
||||
`noindex` anyway). In `createContentHelpers` set `robots: { adminRoute: false }`.
|
||||
|
||||
### WYMAGANE — przenieś folder panelu w projekcie
|
||||
### REQUIRED — move the panel folder in the project
|
||||
|
||||
Plugin ustawia `config.routes.admin`, ale NIE tworzy plików w `app/` projektu.
|
||||
Musisz przenieść folder panelu, żeby ścieżka zadziałała:
|
||||
The plugin sets `config.routes.admin`, but does NOT create files in the project's `app/`.
|
||||
You must move the panel folder for the path to work:
|
||||
|
||||
```
|
||||
# PRZED:
|
||||
# BEFORE:
|
||||
app/(payload)/admin/[[...segments]]/page.tsx
|
||||
app/(payload)/admin/[[...segments]]/not-found.tsx
|
||||
|
||||
# PO (nazwa folderu = adminRoute bez ukośnika):
|
||||
# AFTER (folder name = adminRoute without the slash):
|
||||
app/(payload)/its/[[...segments]]/page.tsx
|
||||
app/(payload)/its/[[...segments]]/not-found.tsx
|
||||
```
|
||||
|
||||
Bez przeniesienia folderu: `config.routes.admin = '/its'`, ale `/its` daje 404
|
||||
(brak pliku), a `/admin` też nie działa (config zmieniony). Oba muszą się zgadzać.
|
||||
Without moving the folder: `config.routes.admin = '/its'`, but `/its` returns 404
|
||||
(no file), and `/admin` does not work either (the config changed). Both must match.
|
||||
|
||||
### To OBSCURITY, nie SECURITY
|
||||
### This is OBSCURITY, not SECURITY
|
||||
|
||||
Zmiana ścieżki utrudnia automatyczne skany, ale NIE jest zabezpieczeniem.
|
||||
Prawdziwa ochrona panelu:
|
||||
- **2FA** dla każdego użytkownika (planowane — wymuszenie przez plugin)
|
||||
- Silne hasła
|
||||
- Rate limiting na logowaniu
|
||||
- IP allowlist (jeśli panel tylko dla zespołu)
|
||||
- buildSecurityHeaders (nagłówki)
|
||||
Changing the path makes automated scans harder, but it is NOT a safeguard.
|
||||
Real panel protection:
|
||||
- **2FA** for every user (enforced by the plugin — section below)
|
||||
- Strong passwords
|
||||
- Rate limiting on login
|
||||
- IP allowlist (if the panel is for the team only)
|
||||
- buildSecurityHeaders (headers)
|
||||
|
||||
Zmiana `/admin → /its` to warstwa (odsiewa głupie boty), nie zamek. Traktuj jako
|
||||
dodatek do prawdziwych zabezpieczeń, nie zamiast nich.
|
||||
`/admin → /its` is a layer (it filters out dumb bots), not a lock. Treat it as an
|
||||
addition to real safeguards, not a replacement for them.
|
||||
|
||||
## 2FA (TOTP) — WYMUSZONE dla każdego użytkownika
|
||||
## 2FA (TOTP) — ENFORCED for every user
|
||||
|
||||
Plugin wymusza dwuskładnikowe uwierzytelnianie (TOTP) dla WSZYSTKICH użytkowników
|
||||
panelu — bez możliwości wyłączenia per użytkownik. Każdy projekt ma to z automatu.
|
||||
Używa sprawdzonego `@clocklimited/payload-2fa` (wrapuje access control — TOTP
|
||||
sprawdzane przed dostępem do DANYCH, nie tylko UI panelu).
|
||||
The plugin enforces two-factor authentication (TOTP) for ALL panel users —
|
||||
with no way to turn it off per user. Every project gets it automatically.
|
||||
It uses the proven `@clocklimited/payload-2fa` (it wraps access control — TOTP is
|
||||
checked before access to DATA, not only the panel UI).
|
||||
|
||||
### Zależność
|
||||
### Dependency
|
||||
|
||||
```bash
|
||||
pnpm add @clocklimited/[email protected]
|
||||
```
|
||||
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
|
||||
Note: the package has no stable 3.0.0 yet — use a specific beta version
|
||||
(or `^3.0.0-0` to allow prereleases). Plain `^3.0.0` fails with
|
||||
ERR_PNPM_NO_MATCHING_VERSION.
|
||||
|
||||
### Konfiguracja (payload.config.ts) — WSTRZYKNIJ plugin (wymagane w Next)
|
||||
### Configuration (payload.config.ts) — INJECT the plugin (required in Next)
|
||||
|
||||
```ts
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
@@ -272,65 +286,94 @@ import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
ipalKit({
|
||||
i18n: i18nConfig,
|
||||
twoFactor: {
|
||||
issuer: 'Nazwa Firmy', // pokazywane w aplikacji authenticator
|
||||
plugin: payloadTotp, // ← WSTRZYKNIJ — patrz niżej dlaczego
|
||||
// collectionSlug: 'users',
|
||||
issuer: 'Company Name', // shown in the authenticator app
|
||||
plugin: payloadTotp, // ← INJECT — see below why
|
||||
// collectionSlug: 'users', // default: the panel login collection (admin.user, else the first auth collection)
|
||||
// allowCollectionMismatch: true, // deliberate only: 2FA on a collection other than admin.user
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
**Dlaczego `plugin: payloadTotp` (wstrzyknięcie):** to ten sam wzorzec co
|
||||
`NextResponse`/`revalidatePath` — projekt podaje peer-dep, plugin go 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
|
||||
`generateStaticParams` łapie błąd — strona jest zepsuta dopiero w runtime.
|
||||
**Why `plugin: payloadTotp` (injection):** it is the same pattern as
|
||||
`NextResponse`/`revalidatePath` — the project provides the peer dependency, the plugin does NOT
|
||||
import it. Up to 1.8.x the plugin did a dynamic import instead, which **Next does not
|
||||
bundle** (webpack turns an import from a variable into an empty context) → the error
|
||||
**"Cannot find module '@clocklimited/payload-2fa'"** in `next build` and on every
|
||||
page (public ones too). The build can still go "green", because
|
||||
`generateStaticParams` catches the error — the page only breaks at runtime.
|
||||
|
||||
**`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, 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.
|
||||
**`serverExternalPackages` is NOT a workaround.** The package imports its own
|
||||
`*.module.css`; once externalized it is loaded by Node, which does not know `.css` →
|
||||
`ERR_UNKNOWN_FILE_EXTENSION` while collecting data for `/admin`. The only working
|
||||
configuration in Next is injection, so since 1.9.0 `plugin` is **required**
|
||||
(missing → a clear error at startup). The `payload …` CLI loads the same config, so it
|
||||
gets the injected plugin.
|
||||
|
||||
Plugin ustawia `forceSetup: true` — każdy użytkownik MUSI skonfigurować TOTP po
|
||||
zalogowaniu. Nie ma opcji „włącz/wyłącz" dla użytkownika.
|
||||
The plugin sets `forceSetup: true` — every user MUST set up TOTP after
|
||||
logging in. There is no per-user "on/off" option.
|
||||
|
||||
### Wyłączenie (ODRADZANE)
|
||||
### Turning it off (DISCOURAGED)
|
||||
|
||||
```ts
|
||||
twoFactor: false // TYLKO gdy projekt naprawdę nie może użyć 2FA (rzadkie)
|
||||
twoFactor: false // ONLY when the project really cannot use 2FA (rare)
|
||||
```
|
||||
Domyślnie 2FA jest WYMUSZONE. `false` to świadoma rezygnacja — unikaj.
|
||||
2FA is ENFORCED by default. `false` is a deliberate opt-out — avoid it. Leaving out `twoFactor`
|
||||
(even though the type marks it optional) stops startup with `twoFactor.issuer is required` — the decision must be explicit.
|
||||
|
||||
### Jak działa dla użytkownika
|
||||
### How it works for the user
|
||||
|
||||
1. Loguje się (email + hasło)
|
||||
2. Przy pierwszym logowaniu: przekierowanie na Setup TOTP (QR + sekret)
|
||||
3. Skanuje QR aplikacją (Google Authenticator, Authy, 1Password, Microsoft Auth)
|
||||
4. Wpisuje kod → 2FA aktywne
|
||||
5. Kolejne logowania: email + hasło + kod TOTP
|
||||
1. Logs in (email + password)
|
||||
2. On first login: redirected to TOTP Setup (QR + secret)
|
||||
3. Scans the QR with an app (Google Authenticator, Authy, 1Password, Microsoft Authenticator)
|
||||
4. Enters the code → 2FA is active
|
||||
5. Next logins: email + password + TOTP code
|
||||
|
||||
### Reset 2FA (admin)
|
||||
### Resetting 2FA (admin)
|
||||
|
||||
Admin może zresetować 2FA innego użytkownika (gdy zgubi telefon) — przez
|
||||
`adminManageAccess` w konfiguracji @clocklimited. Patrz jego dokumentacja.
|
||||
An admin can reset another user's 2FA (when they lose their phone) — through
|
||||
`adminManageAccess` in the @clocklimited configuration. ipalKit passes it only `collection`,
|
||||
`forceSetup` and `issuer`; pass other options by wrapping the injected factory:
|
||||
`plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user) })`.
|
||||
|
||||
### Dlaczego @clocklimited, nie inne
|
||||
### Why @clocklimited and not another one
|
||||
|
||||
Wybrany, bo wrapuje ACCESS CONTROL (TOTP przed dostępem do danych) + forceSetup
|
||||
(wymuszenie dla wszystkich). Inne pluginy 2FA dla Payload gatują tylko nawigację
|
||||
/admin — user z hasłem może omijać przez REST/GraphQL/Bearer. @clocklimited chroni
|
||||
dostęp do danych, nie tylko UI.
|
||||
Chosen because it wraps ACCESS CONTROL (TOTP before data access) + forceSetup
|
||||
(enforced for everyone). Other 2FA plugins for Payload only gate /admin
|
||||
navigation — a user with a password can bypass them through REST/GraphQL/Bearer. @clocklimited protects
|
||||
data access, not just the UI.
|
||||
|
||||
## 1.9.1 — wyniki przeglądu bezpieczeństwa
|
||||
## 1.9.1 — security review results
|
||||
|
||||
- Drafty nigdy nieopublikowane nie są już dostępne publicznie (`resolveRoute`, Markdown, MCP,
|
||||
metadata) ani na listach archiwów (`getArchiveEntries`). Podgląd: `resolveRoute({ draft: true })`,
|
||||
`getArchiveEntries({ draft: true })` w trybie `draftMode()`.
|
||||
- Linki z CMS: tylko `http(s)`, `mailto`, `tel`, `sms`, `#`, `/` (`safeHref`); `javascript:` i `data:` odrzucane.
|
||||
- ID analityki walidowane (panel i przed wysłaniem do przeglądarki).
|
||||
- Zgłoszenia formularzy: odczyt `editor+`; adresy z zakładki Emails niewidoczne publicznie.
|
||||
- Uploady: `buildUploadSecurityHeaders()` w `next.config.ts` (SVG nie uruchomi skryptu na domenie strony).
|
||||
- `users`: plugin wstrzykuje kolekcję auth, gdy projekt jej nie ma (role i 2FA zawsze się wpinają).
|
||||
- Drafts that were never published are no longer publicly available (`resolveRoute`, Markdown, MCP,
|
||||
metadata), nor on archive lists (`getArchiveEntries`). Preview: `resolveRoute({ draft: true })`,
|
||||
`getArchiveEntries({ draft: true })` in `draftMode()`.
|
||||
- Links from the CMS: only `http(s)`, `mailto`, `tel`, `sms`, `#`, `/` (`safeHref`); `javascript:` and `data:` are rejected —
|
||||
also in rich text (`RenderRichText` replaces them with `#`).
|
||||
- Analytics IDs are validated (in the panel and before being sent to the browser).
|
||||
- Form submissions: read `editor+`; addresses from the Emails tab are not publicly visible.
|
||||
- Uploads: `buildUploadSecurityHeaders()` in `next.config.ts` (an SVG cannot run a script on the site's domain).
|
||||
- `users`: the plugin injects an auth collection when the project has none (roles and 2FA always attach).
|
||||
|
||||
## Access control (since the version after 1.12.3)
|
||||
|
||||
- Injected auth collection with roles: a `user` account reads and edits only itself; only an
|
||||
admin creates and deletes. Before, any logged-in account could change an admin's email/password.
|
||||
- 2FA without `collectionSlug` wraps the panel login collection (`admin.user`, else the first auth
|
||||
collection), not the literal `'users'`. Plugin startup fails with `[ipal] twoFactor…` when the target is not
|
||||
an auth collection or differs from `admin.user` — deliberate exception: `twoFactor.allowCollectionMismatch: true`.
|
||||
- Injected auth collection with roles: `unlock` is admin-only too. You can override all of it:
|
||||
`access.authAccess`, `access.firstUserAdmin: false`, `globalOverrides`, `forms.formOverrides`.
|
||||
- Site Settings, Cookie Settings, Notifications and the Forms collection: write is `editor+` only; a form's
|
||||
Emails tab (recipients, BCC) is readable only by `editor+`.
|
||||
- Full table: [access.md](./access.md#what-the-plugin-locks-down-by-itself).
|
||||
|
||||
## Turn off, override, extend
|
||||
|
||||
- **Turn off:** headers — do not call `buildSecurityHeaders`, or `null` / `false` per header (`frameOptions`,
|
||||
`referrerPolicy`, `permissionsPolicy`, `coop`), `hsts: false`; 2FA — `twoFactor: false` (discouraged).
|
||||
- **Override:** `additional` (the same key overrides the plugin's header), `buildCsp({ extra })`, `mode`;
|
||||
2FA — `collectionSlug`, `allowCollectionMismatch`, your own TOTP options by wrapping `plugin`;
|
||||
access — `access.authAccess`, `access.firstUserAdmin`, `globalOverrides` ([access.md](./access.md)).
|
||||
- **Extend:** `buildCsp`, `buildUploadSecurityHeaders({ collections })` for your own upload collections.
|
||||
- **Check:** `curl -sI https://domain/ | grep -iE "strict-transport|x-frame|referrer|permissions|cross-origin|content-security"`;
|
||||
on staging also `x-robots-tag`; startup with a wrong `twoFactor.collectionSlug` fails with `[ipal] twoFactor…`.
|
||||
|
||||
Reference in New Issue
Block a user