{"id":"6b09a4bfff996234422a274c","slug":"security-headers-and-csp","title":"Nagłówki bezpieczeństwa i CSP – nonce, strict-dynamic, report-only, HSTS, Permissions-Policy i CORS w Express, NestJS i CloudFront","summary":"Konfigurujemy nagłówki bezpieczeństwa sklepu pierogarni – Content Security Policy z nonce i strict-dynamic wdrażaną najpierw w trybie report-only, HSTS z preload, ochronę przed osadzaniem w ramkach, Referrer-Policy, Permissions-Policy i CORS bez „gwiazdki”. Helmet w Express i NestJS, polityka nagłówków w CloudFront dla statycznej SPA, prawdziwe zrzuty nagłówków, interaktywny kreator CSP i narzędzia do testowania.","servedLang":"pl","availableLangs":["pl","en"],"topics":["web-security","express","nestjs"],"techs":["node","typescript","javascript"],"tags":["csp","content-security-policy","nonce","strict-dynamic","hsts","cors","helmet","permissions-policy","referrer-policy","clickjacking","cloudfront","security-headers"],"level":"intermediate","kind":"tutorial","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":12,"stats":{"views":0,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T15:41:51.458Z","updatedAt":"2026-11-27T15:41:51.508Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"rose","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"Nagłówki bezpieczeństwa HTTP w praktyce – Content-Security-Policy (nonce, hash, strict-dynamic, report-only, report-to), Strict-Transport-Security i preload, X-Content-Type-Options, frame-ancestors, Referrer-Policy, Permissions-Policy, COOP, CORS z credentials; helmet dla Express i NestJS, CloudFron","wordCount":2306,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Po teście penetracyjnym sklep pierogarni poprawił wszystkie znalezione miejsca podatne na XSS. Audytor zapytał jednak: „A co, jeśli jutro ktoś doda nowe?”. Nagłówki bezpieczeństwa to druga linia obrony: przeglądarka sama odmówi wykonania skryptu, którego nie autoryzowałeś, osadzenia strony w cudzej ramce czy połączenia przez HTTP – nawet jeśli w kodzie jest błąd. W tym poradniku konfigurujemy je w Express, NestJS i CloudFront, wdrażamy CSP bez psucia produkcji i sprawdzamy wynik."}]},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"CSP z nonce i ","marks":[{"type":"bold"}]},{"type":"text","text":"strict-dynamic","marks":[{"type":"code"}]},{"type":"text","text":" to najskuteczniejsza ochrona przed skutkami XSS.","marks":[{"type":"bold"}]},{"type":"text","text":" Skrypt bez losowego, jednorazowego "},{"type":"text","text":"nonce","marks":[{"type":"code"}]},{"type":"text","text":" z bieżącej odpowiedzi nie wykona się – także wstrzyknięty."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Wdrażaj w dwóch krokach.","marks":[{"type":"bold"}]},{"type":"text","text":" Najpierw "},{"type":"text","text":"Content-Security-Policy-Report-Only","marks":[{"type":"code"}]},{"type":"text","text":" z raportami, potem egzekwowanie. Inaczej pierwszy zapomniany skrypt analityki zepsuje stronę."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"CORS to nie zabezpieczenie, tylko poluzowanie.","marks":[{"type":"bold"}]},{"type":"text","text":" Domyślnie przeglądarka blokuje odczyt odpowiedzi z innych domen; CORS mówi, komu na to pozwolić. Lista konkretnych originów, nigdy "},{"type":"text","text":"*","marks":[{"type":"code"}]},{"type":"text","text":" z ciasteczkami."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"Co zbudujesz"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Moduł Express z helmet: CSP z nonce generowanym dla każdej odpowiedzi, "},{"type":"text","text":"strict-dynamic","marks":[{"type":"code"}]},{"type":"text","text":", raportowaniem ("},{"type":"text","text":"report-uri","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"report-to","marks":[{"type":"code"}]},{"type":"text","text":") i trybem report-only, HSTS z preload, "},{"type":"text","text":"frame-ancestors","marks":[{"type":"code"}]},{"type":"text","text":", Referrer-Policy, Permissions-Policy i CORS z listą originów. Do tego serwer wstawiający nonce do "},{"type":"text","text":"index.html","marks":[{"type":"code"}]},{"type":"text","text":" aplikacji SPA, endpoint na raporty naruszeń, konfigurację NestJS, politykę nagłówków CloudFront w CDK oraz interaktywny kreator nagłówka CSP. Kod (5 plików) pobierzesz jako ZIP."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Wymagania wstępne:","marks":[{"type":"bold"}]},{"type":"text","text":" Express lub NestJS ("},{"type":"text","text":"poradnik Express","marks":[{"type":"link","attrs":{"href":"/pl/articles/express"}}]},{"type":"text","text":", "},{"type":"text","text":"poradnik NestJS","marks":[{"type":"link","attrs":{"href":"/pl/articles/nestjs"}}]},{"type":"text","text":"), podstawy HTTP i przeglądarkowej polityki tego samego pochodzenia ("},{"type":"text","text":"same-origin policy","marks":[{"type":"italic"}]},{"type":"text","text":"). Warto najpierw przeczytać "},{"type":"text","text":"OWASP Top 10 w praktyce","marks":[{"type":"link","attrs":{"href":"/pl/articles/owasp-top-10-in-practice"}}]},{"type":"text","text":"."}]},{"type":"stats","attrs":{"items":[{"value":"128 bitów","label":"losowości nonce","hint":"nowy w każdej odpowiedzi"},{"value":"≥ 1 rok","label":"max-age HSTS","hint":"wymagane do listy preload"},{"value":"0","label":"X-XSS-Protection","hint":"stary filtr przeglądarek – wyłączony"},{"value":"2 kroki","label":"wdrożenie CSP","hint":"report-only, potem egzekwowanie"}]}},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  S[Serwer / CloudFront<br/>wysyła nagłówki] --> B{Przeglądarka}\n  B -->|CSP| C1[blokuje skrypty bez nonce<br/>i ładowanie z obcych hostów]\n  B -->|frame-ancestors| C2[blokuje osadzenie w cudzej ramce]\n  B -->|HSTS| C3[zawsze HTTPS, bez możliwości kliknięcia „dalej”]\n  B -->|CORS| C4[pozwala odczytać odpowiedź API<br/>tylko wskazanym originom]\n  B -->|Permissions-Policy| C5[wyłącza kamerę, mikrofon, USB…]\n  C1 -.raport naruszenia.-> R[(/csp-reports)]","caption":"Kto egzekwuje nagłówki: serwer je wysyła, przeglądarka pilnuje"}},{"type":"heading","attrs":{"level":2,"id":"mapa-naglowkow"},"content":[{"type":"text","text":"Mapa nagłówków"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Nagłówek"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Przed czym chroni"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Zalecana wartość"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Content-Security-Policy","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"skutki XSS, ładowanie zasobów z obcych hostów, clickjacking ("},{"type":"text","text":"frame-ancestors","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"strict CSP z nonce (poniżej)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Strict-Transport-Security","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"przechwycenie ruchu, zdegradowanie do HTTP"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"max-age=63072000; includeSubDomains; preload","marks":[{"type":"code"}]},{"type":"text","text":" (po przygotowaniu)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"X-Content-Type-Options","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zgadywanie typu MIME (np. „obrazek”, który jest skryptem)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nosniff","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"X-Frame-Options","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"clickjacking w starszych przeglądarkach"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"DENY","marks":[{"type":"code"}]},{"type":"text","text":" (bliźniak "},{"type":"text","text":"frame-ancestors 'none'","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Referrer-Policy","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"wyciek ścieżek i parametrów URL do innych serwisów"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"strict-origin-when-cross-origin","marks":[{"type":"code"}]},{"type":"text","text":" albo "},{"type":"text","text":"no-referrer","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Permissions-Policy","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nadużycie API przeglądarki przez skrypty i ramki"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"camera=(), microphone=(), geolocation=(self)","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Cross-Origin-Opener-Policy","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"dostęp do twojego okna z okien otwartych przez inne strony"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"same-origin","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Cross-Origin-Resource-Policy","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"osadzanie twoich zasobów przez obce strony"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"same-origin","marks":[{"type":"code"}]},{"type":"text","text":" lub "},{"type":"text","text":"same-site","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"X-XSS-Protection","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nic – stary filtr bywał źródłem podatności"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"0","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"csp-od-podstaw"},"content":[{"type":"text","text":"CSP od podstaw"}]},{"type":"paragraph","content":[{"type":"text","text":"Content Security Policy to lista dyrektyw mówiących przeglądarce, skąd strona może ładować skrypty, style, obrazki, połączenia i ramki. Kluczowe są skrypty – i tu są trzy podejścia:"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Lista dozwolonych hostów","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"script-src 'self' https://cdn.example","marks":[{"type":"code"}]},{"type":"text","text":") – łatwa, ale słaba: badania Google pokazały, że większość takich polityk da się obejść przez dozwolone hosty serwujące JSONP czy stare biblioteki."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Strict CSP z nonce","marks":[{"type":"bold"}]},{"type":"text","text":": "},{"type":"text","text":"script-src 'nonce-R4nd0m' 'strict-dynamic'","marks":[{"type":"code"}]},{"type":"text","text":". Wykona się tylko skrypt z atrybutem "},{"type":"text","text":"nonce","marks":[{"type":"code"}]},{"type":"text","text":" równym wartości z nagłówka tej konkretnej odpowiedzi, a "},{"type":"text","text":"strict-dynamic","marks":[{"type":"code"}]},{"type":"text","text":" przenosi zaufanie na skrypty, które on sam doładuje. Atakujący, który wstrzyknie "},{"type":"text","text":"<script>","marks":[{"type":"code"}]},{"type":"text","text":", nie zna nonce."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Strict CSP z hashami","marks":[{"type":"bold"}]},{"type":"text","text":" – dla stron statycznych, gdzie nie da się wstawiać nonce per odpowiedź: "},{"type":"text","text":"script-src 'sha256-…'","marks":[{"type":"code"}]},{"type":"text","text":" dla każdego skryptu inline. Statyczna SPA bez skryptów inline (typowy build Vite) może po prostu użyć "},{"type":"text","text":"script-src 'self'","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"https:","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"'unsafe-inline'","marks":[{"type":"code"}]},{"type":"text","text":" w strict CSP to wyłącznie zabezpieczenie dla bardzo starych przeglądarek – nowoczesne ignorują je, gdy widzą nonce i "},{"type":"text","text":"strict-dynamic","marks":[{"type":"code"}]},{"type":"text","text":". Do tego zawsze "},{"type":"text","text":"object-src 'none'","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"base-uri 'none'","marks":[{"type":"code"}]},{"type":"text","text":" (bez nich da się obejść "},{"type":"text","text":"script-src","marks":[{"type":"code"}]},{"type":"text","text":") oraz "},{"type":"text","text":"frame-ancestors","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"playground","attrs":{"template":"vanilla","files":{"/index.html":{"code":"<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"UTF-8\" />\n    <title>Kreator CSP</title>\n  </head>\n  <body>\n    <form id=\"form\">\n      <fieldset>\n        <legend>Skrypty</legend>\n        <label><input type=\"radio\" name=\"scripts\" value=\"strict\" checked /> nonce + 'strict-dynamic' (zalecane)</label>\n        <label><input type=\"radio\" name=\"scripts\" value=\"self\" /> tylko 'self' (statyczna SPA)</label>\n        <label><input type=\"radio\" name=\"scripts\" value=\"unsafe\" /> 'self' 'unsafe-inline' (słabe)</label>\n      </fieldset>\n      <label>Dodatkowe hosty obrazków <input name=\"img\" value=\"https://media.pierogarnia.example\" /></label>\n      <label>Dodatkowe hosty API (connect-src) <input name=\"connect\" placeholder=\"https://api.pierogarnia.example\" /></label>\n      <div class=\"checks\">\n        <label><input type=\"checkbox\" name=\"object\" checked /> object-src 'none'</label>\n        <label><input type=\"checkbox\" name=\"base\" checked /> base-uri 'none'</label>\n        <label><input type=\"checkbox\" name=\"frames\" checked /> frame-ancestors 'none'</label>\n        <label><input type=\"checkbox\" name=\"upgrade\" checked /> upgrade-insecure-requests</label>\n        <label><input type=\"checkbox\" name=\"report\" /> raporty (report-to)</label>\n        <label><input type=\"checkbox\" name=\"reportOnly\" /> tylko raportuj (Report-Only)</label>\n      </div>\n    </form>\n    <h3>Nagłówek</h3>\n    <pre id=\"header\"></pre>\n    <h3>Uwagi</h3>\n    <ul id=\"warnings\"></ul>\n    <script src=\"index.js\"></script>\n  </body>\n</html>"},"/index.js":{"code":"import \"./styles.css\";\n\nconst T = {\n  unsafe: \"'unsafe-inline' pozwala uruchomić każdy wstrzyknięty skrypt inline – CSP prawie nie chroni przed XSS.\",\n  object: \"Brak object-src 'none' – stare wtyczki (<object>, <embed>) mogą ominąć script-src.\",\n  base: \"Brak base-uri – wstrzyknięty <base href> może przekierować względne adresy skryptów.\",\n  frames: \"Brak frame-ancestors – stronę da się osadzić w cudzej ramce (clickjacking).\",\n  reportOnly: \"Tryb Report-Only niczego nie blokuje – to etap wdrożenia, nie stan docelowy.\",\n  report: \"Bez raportów nie dowiesz się, co polityka blokuje u użytkowników.\",\n  ok: \"Wygląda dobrze. Pamiętaj: nonce musi być losowy w każdej odpowiedzi.\",\n};\n\nconst form = document.getElementById(\"form\");\n\nfunction build() {\n  const f = Object.fromEntries(new FormData(form));\n  const scripts = {\n    strict: \"'nonce-R4nd0mPerResponse' 'strict-dynamic' https: 'unsafe-inline'\",\n    self: \"'self'\",\n    unsafe: \"'self' 'unsafe-inline'\",\n  }[f.scripts];\n\n  const d = [[\"default-src\", \"'self'\"], [\"script-src\", scripts]];\n  d.push([\"img-src\", `'self' data: ${f.img}`.trim()]);\n  d.push([\"connect-src\", `'self' ${f.connect}`.trim()]);\n  if (f.object) d.push([\"object-src\", \"'none'\"]);\n  if (f.base) d.push([\"base-uri\", \"'none'\"]);\n  if (f.frames) d.push([\"frame-ancestors\", \"'none'\"]);\n  if (f.upgrade) d.push([\"upgrade-insecure-requests\"]);\n  if (f.report) d.push([\"report-to\", \"csp\"]);\n\n  const name = f.reportOnly ? \"Content-Security-Policy-Report-Only\" : \"Content-Security-Policy\";\n  document.getElementById(\"header\").textContent = `${name}: ${d.map((x) => x.join(\" \")).join(\"; \")}`;\n\n  const notes = [];\n  if (f.scripts === \"unsafe\") notes.push(T.unsafe);\n  if (!f.object) notes.push(T.object);\n  if (!f.base) notes.push(T.base);\n  if (!f.frames) notes.push(T.frames);\n  if (f.reportOnly) notes.push(T.reportOnly);\n  if (!f.report) notes.push(T.report);\n  const items = (notes.length ? notes : [T.ok]).map((text) => Object.assign(document.createElement(\"li\"), { textContent: text }));\n  document.getElementById(\"warnings\").replaceChildren(...items);\n}\n\nform.addEventListener(\"input\", build);\nbuild();","active":true},"/styles.css":{"code":"body { font-family: system-ui, sans-serif; margin: 0; padding: 16px; color: #1f2328; font-size: 14px; }\nform { display: grid; gap: 10px; max-width: 680px; }\nfieldset { border: 1px solid #d0d7de; border-radius: 8px; display: grid; gap: 4px; }\ninput[name=\"img\"], input[name=\"connect\"] { width: 100%; box-sizing: border-box; padding: 6px; font: 12px ui-monospace, monospace; }\n.checks { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 4px; }\npre { background: #f6f8fa; padding: 10px; border-radius: 8px; white-space: pre-wrap; word-break: break-all; font-size: 12px; }\nh3 { margin: 12px 0 4px; font-size: 14px; }\nli { margin: 4px 0; }"}},"layout":"preview","height":620,"title":"Kreator nagłówka Content-Security-Policy","caption":"Zaznaczaj opcje i czytaj uwagi – to szkic do dalszej pracy, nie zastępuje testu w przeglądarce.","editable":true}},{"type":"heading","attrs":{"level":2,"id":"krok-1-express-i-helmet"},"content":[{"type":"text","text":"Krok 1. Express i helmet"}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"npm install helmet cors pino"}]},{"type":"codeGroup","attrs":{"title":"Nagłówki bezpieczeństwa w Express (helmet, CORS, nonce dla SPA)"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/security-headers.ts"},"content":[{"type":"text","text":"import type { Express, Response } from 'express';\nimport cors from 'cors';\nimport helmet from 'helmet';\nimport { randomBytes } from 'node:crypto';\n\nexport function securityHeaders(app: Express, opts: { reportOnly?: boolean } = {}) {\n  // A fresh, unpredictable nonce for every HTML response.\n  app.use((_req, res, next) => {\n    res.locals.cspNonce = randomBytes(16).toString('base64');\n    next();\n  });\n\n  app.use(helmet({\n    contentSecurityPolicy: {\n      useDefaults: false,\n      reportOnly: opts.reportOnly, // roll out as Content-Security-Policy-Report-Only first\n      directives: {\n        defaultSrc: [\"'self'\"],\n        // Strict CSP: only scripts carrying our nonce, plus what they load ('strict-dynamic').\n        // https: and 'unsafe-inline' are fallbacks for old browsers – modern ones ignore them.\n        scriptSrc: [(_req, res) => `'nonce-${(res as Response).locals.cspNonce}'`, \"'strict-dynamic'\", 'https:', \"'unsafe-inline'\"],\n        styleSrc: [\"'self'\"],\n        imgSrc: [\"'self'\", 'data:', 'https://media.pierogarnia.example'],\n        connectSrc: [\"'self'\"],\n        fontSrc: [\"'self'\"],\n        objectSrc: [\"'none'\"],\n        baseUri: [\"'none'\"],\n        formAction: [\"'self'\"],\n        frameAncestors: [\"'none'\"], // nobody may frame us (clickjacking)\n        upgradeInsecureRequests: [],\n        reportUri: ['/csp-reports'], // widely supported\n        reportTo: ['csp'], // Reporting API, endpoint defined below\n      },\n    },\n    strictTransportSecurity: { maxAge: 63_072_000, includeSubDomains: true, preload: true }, // 2 years\n    referrerPolicy: { policy: 'strict-origin-when-cross-origin' },\n    xFrameOptions: { action: 'deny' }, // legacy twin of frame-ancestors 'none'\n  }));\n\n  // Headers helmet doesn't set.\n  app.use((_req, res, next) => {\n    res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=(self), usb=()');\n    res.setHeader('Reporting-Endpoints', 'csp=\"https://pierogarnia.example/csp-reports\"');\n    next();\n  });\n\n  // CORS only for the API and only for our own front-ends – never \"*\" with credentials.\n  app.use('/api', cors({\n    origin: ['https://pierogarnia.example', 'https://admin.pierogarnia.example'],\n    credentials: true,\n    methods: ['GET', 'POST', 'PUT', 'DELETE'],\n    allowedHeaders: ['Content-Type', 'Authorization'],\n    maxAge: 600,\n  }));\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/server.ts"},"content":[{"type":"text","text":"import express from 'express';\nimport { readFileSync } from 'node:fs';\nimport { pino } from 'pino';\nimport { securityHeaders } from './security-headers.js';\n\nconst log = pino();\nconst app = express();\nsecurityHeaders(app, { reportOnly: process.env.CSP_REPORT_ONLY === 'true' });\n\n// CSP violation reports: the classic format (report-uri) and the Reporting API (report-to).\napp.post('/csp-reports', express.json({ type: ['application/csp-report', 'application/reports+json'], limit: '20kb' }), (req, res) => {\n  log.warn({ csp: req.body }, 'csp violation');\n  res.sendStatus(204);\n});\n\napp.get('/api/menu', (_req, res) => { res.json([{ name: 'Ruskie', price: 32 }]); });\n\n// The SPA shell: every <script> gets this response's nonce. Don't let a CDN cache this HTML.\nconst indexHtml = readFileSync(new URL('../public/index.html', import.meta.url), 'utf8');\napp.get(/^\\/(?!api\\/).*/, (_req, res) => {\n  res.set('Cache-Control', 'no-store')\n    .type('html')\n    .send(indexHtml.replaceAll('<script', `<script nonce=\"${res.locals.cspNonce}\"`));\n});\n\napp.listen(3006, () => log.info('http://localhost:3006'));"}]},{"type":"codeBlock","attrs":{"language":"html","filename":"public/index.html"},"content":[{"type":"text","text":"<!doctype html>\n<html lang=\"pl\">\n  <head><meta charset=\"utf-8\" /><title>Pierogarnia</title></head>\n  <body><div id=\"root\"></div><script type=\"module\" src=\"/assets/index-4f2a9c.js\"></script></body>\n</html>"}]}]}]},"toc":[{"id":"mapa-naglowkow","text":"Mapa nagłówków","level":2,"locked":false},{"id":"csp-od-podstaw","text":"CSP od podstaw","level":2,"locked":false},{"id":"krok-1-express-i-helmet","text":"Krok 1. Express i helmet","level":2,"locked":false},{"id":"krok-2-wdrozenie-najpierw-report-only","text":"Krok 2. Wdrożenie: najpierw report-only","level":2,"locked":true},{"id":"hsts-i-lista-preload","text":"HSTS i lista preload","level":2,"locked":true},{"id":"ramki-referer-uprawnienia-i-izolacja","text":"Ramki, referer, uprawnienia i izolacja","level":2,"locked":true},{"id":"cors-zrobiony-dobrze","text":"CORS zrobiony dobrze","level":2,"locked":true},{"id":"krok-3-nestjs","text":"Krok 3. NestJS","level":2,"locked":true},{"id":"krok-4-cloudfront-dla-statycznej-spa","text":"Krok 4. CloudFront dla statycznej SPA","level":2,"locked":true},{"id":"jak-testowac","text":"Jak testować","level":2,"locked":true},{"id":"typowe-bledy","text":"Typowe błędy","level":2,"locked":true},{"id":"sprawdz-sie","text":"Sprawdź się","level":2,"locked":true},{"id":"co-dalej","text":"Co dalej","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":58,"visibleBlocks":16,"resources":[{"id":"6b0857c53c96f2d34d0b47c3","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=j9QmMEWmcfo","embedUrl":"https://www.youtube-nocookie.com/embed/j9QmMEWmcfo","title":"SSL, TLS, HTTPS Explained","description":"To get better at system design, subscribe to our weekly newsletter: https://bit.ly/3tfAlYD Checkout our bestselling System Design Interview books: Volume 1: https://amzn.to/3Ou7gkd Volume 2: https://amzn.to/3HqGozy ABOUT US: Covering topics and trends in large-scale system design, from the authors…","author":"ByteByteGo","thumbnailUrl":"https://i.ytimg.com/vi/j9QmMEWmcfo/hqdefault.jpg","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["system-design"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2022-12-08T16:30:04.000Z","popularity":91,"verifiedAt":"2026-11-26T10:55:10.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:07.480Z","updatedAt":"2026-11-26T16:01:07.480Z"},{"id":"6b0857c63c96f2d34d0b48dd","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=WvSVSbGo0wI","embedUrl":"https://www.youtube-nocookie.com/embed/WvSVSbGo0wI","title":"HTTP vs HTTPS Explained","description":"To get better at system design, subscribe to our weekly newsletter: https://bit.ly/3tfAlYD Checkout our bestselling System Design Interview books: Volume 1: https://amzn.to/3Ou7gkd Volume 2: https://amzn.to/3HqGozy ABOUT US: Covering topics and trends in large-scale system design, from the authors…","author":"ByteByteGo","thumbnailUrl":"https://i.ytimg.com/vi/WvSVSbGo0wI/hqdefault.jpg","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["system-design"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2026-08-12T15:00:38.000Z","popularity":68,"verifiedAt":"2026-11-26T10:54:48.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857bf3c96f2d34d0b42af","type":"article","provider":"web","url":"https://learn.microsoft.com/en-us/azure/architecture/patterns/gateway-offloading","embedUrl":null,"title":"Gateway Offloading Pattern","description":"Centralize shared capabilities, such as TLS termination and authentication, in a gateway to simplify backend services.","author":"Microsoft Azure Architecture Center","thumbnailUrl":"https://learn.microsoft.com/en-us/media/open-graph-image.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["azure","cloud"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":61,"verifiedAt":"2026-11-26T11:07:50.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857c43c96f2d34d0b4753","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL19543758W","embedUrl":null,"title":"Agile Application Security: Enabling Security in a Continuous Delivery Pipeline","description":"","author":"Laura Bell, Michael Brunton-Spall, Rich Smith, Jim Bird","thumbnailUrl":"https://covers.openlibrary.org/b/id/8510263-L.jpg","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["book","security","devops"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2017-01-01T00:00:00.000Z","popularity":31,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:07.480Z","updatedAt":"2026-11-26T16:01:07.480Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":104,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Autorytet","articles":90},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":61},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":59},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":46}]}}