@softistx/alxia-secure-headers 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/guide.md ADDED
@@ -0,0 +1,749 @@
1
+ # Guide
2
+
3
+ This page covers `secureHeaders`: what it sends, how to change or drop each
4
+ header, the per-request nonce, which responses it reaches, and how a page or
5
+ another middleware sets its own policy. It also covers the four additions for
6
+ server-rendered pages: `csp()` writes the policy from directives,
7
+ `pageHeaders()` is the preset for a page, `cacheControl` keeps pages out of
8
+ caches, and `clearSiteData()` empties the browser's cache on sign-out.
9
+
10
+ ```ts
11
+ import { alxia } from '@softistx/alxia';
12
+ import { secureHeaders } from '@softistx/alxia-secure-headers';
13
+
14
+ const app = alxia()
15
+ .use(secureHeaders())
16
+ .get('/health', ({ reply }) => reply(200, 'ok'));
17
+
18
+ app.listen(3000);
19
+ ```
20
+
21
+ Every response of that app now carries the headers below, and none carries
22
+ `X-Powered-By` or `Server`.
23
+
24
+ ## The signature
25
+
26
+ ```ts
27
+ function secureHeaders(options: SecureHeadersOptions & { readonly nonce: true }): NonceMiddleware;
28
+ function secureHeaders(options?: SecureHeadersOptions & { readonly nonce?: false }): SecureHeaders;
29
+
30
+ interface SecureHeadersOptions {
31
+ readonly contentSecurityPolicy?: string | false;
32
+ readonly strictTransportSecurity?: string | false;
33
+ readonly xContentTypeOptions?: string | false;
34
+ readonly xFrameOptions?: string | false;
35
+ readonly referrerPolicy?: string | false;
36
+ readonly crossOriginOpenerPolicy?: string | false;
37
+ readonly crossOriginResourcePolicy?: string | false;
38
+ readonly crossOriginEmbedderPolicy?: string | false;
39
+ readonly originAgentCluster?: string | false;
40
+ readonly xDnsPrefetchControl?: string | false;
41
+ readonly xPermittedCrossDomainPolicies?: string | false;
42
+ readonly permissionsPolicy?: string | false;
43
+ readonly cacheControl?: string | false;
44
+ readonly hidePoweredBy?: boolean;
45
+ }
46
+ ```
47
+
48
+ `nonce` is not in `SecureHeadersOptions`: each overload adds it, so options
49
+ typed by that interface still give the plain `SecureHeaders`.
50
+
51
+ `secureHeaders` returns a middleware: give it to `app.use`, called, and the
52
+ app keeps its type. `SecureHeaders` is a `Middleware` from `@softistx/alxia`
53
+ that adds nothing to the context. It waits for the rest of the chain with
54
+ `settle`, then sets the headers on the response, so it covers every route
55
+ declared after it, and every request no route matches — a 404, a 405 —
56
+ because those run all of the app's top-level middlewares too. A route
57
+ declared **before** it is not covered. Used inside a `group`, it covers only
58
+ that group's routes, and not a 404 under the group's prefix: declare it on
59
+ the app. To vary a header for some routes, set it on their replies
60
+ ([below](#a-header-a-route-sets-is-kept)).
61
+
62
+ The options are read once, when `secureHeaders(…)` is called; the header
63
+ values are fixed from then on, but for the nonce, which is new on every
64
+ request.
65
+
66
+ With `nonce: true` it returns a `NonceMiddleware` instead: a middleware, still
67
+ given to `app.use` called, that covers the same responses as above, and which
68
+ adds `nonce` to the context of the routes declared after it
69
+ ([below](#a-nonce-per-request)).
70
+
71
+ ## The options
72
+
73
+ Each header option takes the header's value as a string, or `false` to
74
+ leave the header out. An option left out keeps the default.
75
+
76
+ | Option | Header | Default | What the default does |
77
+ | --- | --- | --- | --- |
78
+ | `contentSecurityPolicy` | `Content-Security-Policy` | `default-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'` | a policy for an API: the response may load nothing, set no `<base>`, post no form, and be framed by no page |
79
+ | `strictTransportSecurity` | `Strict-Transport-Security` | `max-age=31536000; includeSubDomains` | over HTTPS, the browser uses HTTPS for this host and its subdomains for a year |
80
+ | `xContentTypeOptions` | `X-Content-Type-Options` | `nosniff` | the browser trusts `Content-Type` and does not guess |
81
+ | `xFrameOptions` | `X-Frame-Options` | `DENY` | no page may frame the response, for browsers that predate `frame-ancestors` |
82
+ | `referrerPolicy` | `Referrer-Policy` | `no-referrer` | links and requests from the response send no `Referer` |
83
+ | `crossOriginOpenerPolicy` | `Cross-Origin-Opener-Policy` | `same-origin` | a window of another origin opened from, or opening, this one gets no handle on it |
84
+ | `crossOriginResourcePolicy` | `Cross-Origin-Resource-Policy` | `same-origin` | another origin cannot embed the response with `<img>`, `<script>` or a `no-cors` fetch |
85
+ | `crossOriginEmbedderPolicy` | `Cross-Origin-Embedder-Policy` | not sent | — |
86
+ | `originAgentCluster` | `Origin-Agent-Cluster` | `?1` | the browser isolates the origin in its own agent cluster |
87
+ | `xDnsPrefetchControl` | `X-DNS-Prefetch-Control` | `off` | the browser does not resolve the response's links ahead of time |
88
+ | `xPermittedCrossDomainPolicies` | `X-Permitted-Cross-Domain-Policies` | `none` | Adobe clients load no cross-domain policy file |
89
+ | `permissionsPolicy` | `Permissions-Policy` | not sent | — the policy is the app's to write |
90
+ | `cacheControl` | `Cache-Control` | not sent | — an API often wants its own caching; a page with a nonce must not be stored ([below](#pages-are-not-cached)) |
91
+
92
+ | Option | Type | Default | Effect |
93
+ | --- | --- | --- | --- |
94
+ | `hidePoweredBy` | `boolean` | `true` | removes `X-Powered-By` and `Server` from every response, a route's own included |
95
+ | `nonce` | `boolean` | `false` | a fresh nonce per request, in the policy and on the context: [A nonce per request](#a-nonce-per-request) |
96
+
97
+ ### A value
98
+
99
+ A string replaces the default as it is, with no parsing: write the header
100
+ exactly as it should go out.
101
+
102
+ ```ts
103
+ app.use(
104
+ secureHeaders({
105
+ contentSecurityPolicy: "default-src 'self'; img-src 'self' data:",
106
+ referrerPolicy: 'strict-origin-when-cross-origin',
107
+ permissionsPolicy: 'camera=(), microphone=(), geolocation=()',
108
+ }),
109
+ );
110
+ ```
111
+
112
+ ### `false`
113
+
114
+ `false` leaves the header out of every response the middleware touches.
115
+
116
+ ```ts
117
+ app.use(secureHeaders({ xFrameOptions: false, strictTransportSecurity: false }));
118
+ ```
119
+
120
+ An empty string is refused: `secureHeaders({ xFrameOptions: '' })` throws a
121
+ `TypeError` at startup
122
+ ([troubleshooting](troubleshooting.md#typeerror-secureheaders--is-empty-give-false-to-leave-the--header-out)).
123
+ Use `false` to drop a header.
124
+
125
+ ### The defaults, explicitly
126
+
127
+ With `exactOptionalPropertyTypes` on, an option set to `undefined` is a
128
+ compile error; with it off, `undefined` means the default (under
129
+ `pageHeaders`, the preset's value: the key is ignored, so `cacheControl:
130
+ undefined` keeps `private, no-store`). To keep the default under a
131
+ condition, leave the key out:
132
+
133
+ ```ts
134
+ const production = Bun.env.NODE_ENV === 'production';
135
+
136
+ app.use(
137
+ secureHeaders({
138
+ ...(production ? {} : { strictTransportSecurity: false }),
139
+ }),
140
+ );
141
+ ```
142
+
143
+ ### `hidePoweredBy`
144
+
145
+ On by default: `X-Powered-By` and `Server` are deleted from the response,
146
+ even when a route set them.
147
+
148
+ ```ts
149
+ const app = alxia()
150
+ .use(secureHeaders())
151
+ .get('/', ({ reply }) => reply(200, 'hi', { headers: { 'x-powered-by': 'php' } }));
152
+
153
+ (await app.request('/')).headers.get('x-powered-by'); // null
154
+ ```
155
+
156
+ `hidePoweredBy: false` keeps whatever the route or another middleware sent.
157
+
158
+ ## A header a route sets is kept
159
+
160
+ The middleware only fills in a header the response does not have yet. A route
161
+ that needs its own policy sets it on its reply, and the other defaults
162
+ still apply:
163
+
164
+ ```ts
165
+ import { alxia } from '@softistx/alxia';
166
+ import { secureHeaders } from '@softistx/alxia-secure-headers';
167
+
168
+ const app = alxia()
169
+ .use(secureHeaders({ referrerPolicy: 'same-origin', xFrameOptions: false }))
170
+ .get('/page', ({ reply }) =>
171
+ reply(200, '<p>hi</p>', {
172
+ headers: { 'content-security-policy': "default-src 'self'" },
173
+ }),
174
+ );
175
+
176
+ const response = await app.request('/page');
177
+ response.headers.get('content-security-policy'); // "default-src 'self'" — the route's
178
+ response.headers.get('x-content-type-options'); // 'nosniff' — the default
179
+ response.headers.get('referrer-policy'); // 'same-origin' — the option
180
+ response.headers.get('x-frame-options'); // null — false
181
+ ```
182
+
183
+ `set.headers` in a handler or a `derive` works the same way, since it ends
184
+ up on the response before the middleware reads it.
185
+
186
+ That is how `@softistx/alxia-graphql`'s IDE loads under the strict default: it sets
187
+ the `Content-Security-Policy` it needs, and `secureHeaders` keeps it.
188
+
189
+ ## A nonce per request
190
+
191
+ A policy that allows a page's inline scripts without `'unsafe-inline'`
192
+ names a nonce: `script-src 'nonce-…'`, and the same value on each
193
+ `<script nonce="…">`. It must be unguessable and new on every response.
194
+ `nonce: true` does both halves.
195
+
196
+ ```ts
197
+ import { alxia } from '@softistx/alxia';
198
+ import { secureHeaders } from '@softistx/alxia-secure-headers';
199
+
200
+ const app = alxia()
201
+ .use(
202
+ secureHeaders({
203
+ nonce: true,
204
+ contentSecurityPolicy: "default-src 'self'; script-src 'self'; frame-ancestors 'none'",
205
+ }),
206
+ )
207
+ .get('/', ({ nonce, reply }) =>
208
+ reply(
209
+ 200,
210
+ `<!doctype html><script nonce="${nonce}">document.title = 'ready'</script>`,
211
+ { headers: { 'content-type': 'text/html; charset=utf-8' } },
212
+ ),
213
+ );
214
+
215
+ const response = await app.request('/');
216
+ response.headers.get('content-security-policy');
217
+ // "default-src 'self'; script-src 'self' 'nonce-Gm1y0S3h1JZcVvXQ4l6x0A=='; frame-ancestors 'none'"
218
+ await response.text();
219
+ // "<!doctype html><script nonce=\"Gm1y0S3h1JZcVvXQ4l6x0A==\">…"
220
+ ```
221
+
222
+ ### What it is
223
+
224
+ 16 bytes from `crypto.getRandomValues`, base64: 24 characters, `==` at the
225
+ end. Each request makes its own, when the middleware runs,
226
+ and every reader of that request — the route, its middlewares, the header — gets
227
+ the same one. Two requests never share one.
228
+
229
+ ### Where it goes in the policy
230
+
231
+ | The policy | The nonce goes |
232
+ | --- | --- |
233
+ | names `NONCE` | where `NONCE` stands, each time, and nowhere else |
234
+ | has no `NONCE`, has `script-src` or `script-src-elem` | at the end of each of those directives (their name in any case) |
235
+ | has neither, as the default policy | nowhere: `secureHeaders()` throws at startup; give `contentSecurityPolicy` with `nonce: true` |
236
+
237
+ `NONCE`, exported, is a placeholder string (`'nonce-{alxia}'`) that no real
238
+ policy contains. Use it to put the nonce in `style-src`, or in a directive
239
+ of your own choosing:
240
+
241
+ ```ts
242
+ import { NONCE, secureHeaders } from '@softistx/alxia-secure-headers';
243
+
244
+ app.use(
245
+ secureHeaders({
246
+ nonce: true,
247
+ contentSecurityPolicy: [
248
+ "default-src 'self'",
249
+ `script-src 'self' ${NONCE} 'strict-dynamic'`,
250
+ `style-src 'self' ${NONCE}`,
251
+ ].join('; '),
252
+ }),
253
+ );
254
+ ```
255
+
256
+ Leaving `style-src` alone is the default on purpose: once a directive holds
257
+ a nonce, browsers ignore its `'unsafe-inline'`, and `style="…"` attributes,
258
+ which take no nonce, stop applying
259
+ ([troubleshooting](troubleshooting.md#inline-style-attributes-stop-applying-once-style-src-has-the-nonce)).
260
+
261
+ ### Who reads it
262
+
263
+ The header covers every response that comes back through the middleware, as
264
+ without the nonce: a 404 and a 500 get a policy with a nonce of their own.
265
+ `ctx.nonce` is typed and set on the routes declared **after** `app.use`, in
266
+ their middlewares and their handler, as any middleware's context. A route
267
+ declared before it gets neither a policy nor a `ctx.nonce`:
268
+
269
+ ```ts
270
+ alxia()
271
+ .get('/early', ({ reply }) => reply(200, 'no policy from this middleware, no ctx.nonce'))
272
+ .use(secureHeaders({ nonce: true, contentSecurityPolicy: "script-src 'self'" }))
273
+ .derive(({ nonce }) => ({ scriptTag: (code: string) => `<script nonce="${nonce}">${code}</script>` }))
274
+ .get('/late', ({ scriptTag, reply }) => reply(200, scriptTag('…')));
275
+ ```
276
+
277
+ A route that sets its own `Content-Security-Policy` keeps it, as
278
+ [above](#a-header-a-route-sets-is-kept); its `ctx.nonce` is then in no
279
+ header, unless it writes it into its own policy.
280
+
281
+ ### With React Router
282
+
283
+ `@softistx/alxia-react-router` reads the nonce from the context, if one is there,
284
+ with `nonceOf(loadContext)` in `entry.server.tsx`. Neither package depends
285
+ on the other. `pageHeaders({ https })` is the policy that goes with it
286
+ ([below](#pages-pageheaders)). See
287
+ [its guide](https://github.com/softistx/alxia/blob/develop/packages/react-router/docs/guide/csp-nonce.md#a-csp-nonce).
288
+
289
+ ### Without `nonce: true`
290
+
291
+ Nothing changes: the same headers, the same values, no `nonce` on the
292
+ context. A policy that names `NONCE` without `nonce: true` is refused at
293
+ startup, so the placeholder never reaches a browser.
294
+
295
+ ## Writing the policy as directives
296
+
297
+ A long policy string hides a typo until a browser refuses a page. `csp()`
298
+ takes the directives as an object and returns the string, so
299
+ `contentSecurityPolicy` still takes a string and nothing else changes.
300
+
301
+ ```ts
302
+ import { csp, NONCE, secureHeaders } from '@softistx/alxia-secure-headers';
303
+
304
+ app.use(
305
+ secureHeaders({
306
+ nonce: true,
307
+ contentSecurityPolicy: csp({
308
+ 'default-src': ["'self'"],
309
+ 'script-src': ["'self'", NONCE],
310
+ 'style-src-elem': ["'self'", NONCE],
311
+ 'frame-ancestors': ["'none'"],
312
+ 'upgrade-insecure-requests': true,
313
+ }),
314
+ }),
315
+ );
316
+ ```
317
+
318
+ - **Order.** Directives are written in the order of the object, so the
319
+ header reads as the code does.
320
+ - **A list is an array.** `'img-src': 'self'` is a type error: write
321
+ `["'self'"]`. The quotes are part of the source, as in a header.
322
+ - **`true`, `false`, `undefined`.** `true` writes a bare directive
323
+ (`upgrade-insecure-requests`, `sandbox`): a bare directive takes `true`, not an empty array. `false` and `undefined` leave it
324
+ out, so `'upgrade-insecure-requests': isProduction` works.
325
+ - **`NONCE`.** It passes through as it is, and `nonce: true` replaces each
326
+ one with the request's `'nonce-…'` ([above](#where-it-goes-in-the-policy)).
327
+ - **Tokens.** A directive that takes keywords is an array like any other:
328
+ `sandbox: ['allow-scripts', 'allow-forms']` is written
329
+ `sandbox allow-scripts allow-forms`.
330
+ - **Any name.** The known directives complete; another lowercase name
331
+ (`report-uri`) is written as given.
332
+ - **Checked at startup.** An empty source list (write `["'none'"]`), a name
333
+ that is not lowercase letters, digits and hyphens starting with a letter, a source that holds `;`, `,` or
334
+ a space, and a policy with no directive left throw a `TypeError` that
335
+ starts `csp():`, before the first request
336
+ ([troubleshooting](troubleshooting.md#runtime)).
337
+
338
+ ## Pages: `pageHeaders`
339
+
340
+ `pageHeaders({ https })` is `secureHeaders` with the settings a
341
+ server-rendered page with a nonce needs, so an app does not write the policy
342
+ itself.
343
+
344
+ ```ts
345
+ import { alxia } from '@softistx/alxia';
346
+ import { pageHeaders } from '@softistx/alxia-secure-headers';
347
+
348
+ const app = alxia()
349
+ .use(pageHeaders({ https: true }))
350
+ .get('/', ({ nonce, reply }) => reply(200, `<script nonce="${nonce}">…</script>`));
351
+ ```
352
+
353
+ What it sets:
354
+
355
+ - `nonce: true`, and the policy `PAGE_DIRECTIVES` with
356
+ `upgrade-insecure-requests` when `https` is true.
357
+ - `Strict-Transport-Security` when `https` is true, none otherwise.
358
+ - `Referrer-Policy: strict-origin-when-cross-origin`.
359
+ - `Cache-Control: private, no-store`, since a cache must never store a nonce.
360
+ - Every other `secureHeaders` option, as given: yours win over the preset's.
361
+ `contentSecurityPolicy` and `nonce` are not options (a type error): the
362
+ policy goes through `directives`.
363
+
364
+ `https` is required. Pass `import.meta.env.PROD` or your own flag; the
365
+ package never reads the environment, so a development server on plain HTTP
366
+ gets no HSTS.
367
+
368
+ ### The directives
369
+
370
+ | directive | holds | why |
371
+ | --- | --- | --- |
372
+ | `default-src` | `'self'` | anything a directive below does not name loads from this site only |
373
+ | `script-src` | `'self'`, `NONCE`, `'strict-dynamic'` | only the scripts this response's nonce marks, and what they load; `'self'` is a fallback for browsers without `'strict-dynamic'` |
374
+ | `style-src-elem` | `'self'`, `NONCE` | this site's stylesheets and the `<style>` elements that carry the nonce (a UI library's nonced style elements, a dev client's); no `'unsafe-inline'`, since an injected `<style>` can read a value out with attribute selectors |
375
+ | `style-src-attr` | `'unsafe-inline'` | `style` attributes (custom properties, positions); no nonce covers an attribute, and this allows no `<style>` element and no script |
376
+ | `img-src` | `'self'` | icons, sprites and logos; no `data:` or `blob:` until a feature needs one |
377
+ | `font-src` | `'self'` | self-hosted fonts |
378
+ | `connect-src` | `'self'` | the framework's data requests, to this site only; a development server's WebSocket on the page's own host |
379
+ | `worker-src` | `'self'` | the service worker |
380
+ | `manifest-src` | `'self'` | the web app manifest |
381
+ | `object-src` | `'none'` | no plugin content |
382
+ | `base-uri` | `'none'` | no `<base>`: a relative URL always means this site |
383
+ | `form-action` | `'self'` | forms post to this site only, a submit before hydration included |
384
+ | `frame-ancestors` | `'none'` | no page frames this one (clickjacking); `X-Frame-Options: DENY` covers older browsers |
385
+
386
+ Never add `'unsafe-eval'`, nor `'unsafe-inline'` to `script-src`.
387
+
388
+ ### Changing the policy
389
+
390
+ `directives` merges over `PAGE_DIRECTIVES`: a list replaces that directive's
391
+ sources (it does not append), `false` removes the directive, `undefined`
392
+ keeps the preset's value, and a name the preset lacks is added. Three cannot be removed, with `false` or `true`:
393
+ `default-src`, which covers frame, media and child sources, and `base-uri`,
394
+ which has no fallback, so an injected `<base>` would redirect nonced
395
+ relative scripts, and `object-src`, which blocks plugin content. They throw a
396
+ `TypeError` that starts `pageHeaders():`
397
+ ([troubleshooting](troubleshooting.md#typeerror-pageheaders-name-cannot-be-removed-from-a-page-policy-)); give a list to change one. A source goes in the directive that loads it, never in
398
+ `default-src`. Under `'strict-dynamic'` a third-party script is loaded by a
399
+ nonced script, not by allowlisting its host: browsers that support it ignore
400
+ host sources in `script-src`.
401
+
402
+ ```ts
403
+ pageHeaders({
404
+ https: true,
405
+ directives: {
406
+ 'img-src': ["'self'", 'https://img.example'],
407
+ 'font-src': ["'self'", 'https://fonts.example'],
408
+ 'manifest-src': false,
409
+ },
410
+ });
411
+ ```
412
+
413
+ An `upgrade-insecure-requests` given in `directives` wins over `https`. A
414
+ `script-src`, or a `script-src-elem` list, without `NONCE` throws at startup, a `TypeError` that starts
415
+ `pageHeaders():`: the nonce would reach no script and the page would not
416
+ hydrate ([troubleshooting](troubleshooting.md#typeerror-pageheaders-script-src-has-no-nonce-a-page-script-runs-only-with-the-responses-nonce-so-write-script-src-with-nonce-in-directives-such-as-self-nonce-strict-dynamic)).
417
+
418
+ ## Pages are not cached
419
+
420
+ A page that carries a nonce, or a viewer's data, must not be stored: a shared
421
+ cache (a CDN, a proxy) that kept it would hand one viewer's nonce, or
422
+ account, to the next. The nonce also stops protecting anything once it is
423
+ reused, since it is only worth something if an attacker cannot guess it.
424
+ `cacheControl` is off by default, because an API often wants its own caching.
425
+
426
+ ```ts
427
+ import { alxia } from '@softistx/alxia';
428
+ import { csp, NONCE, secureHeaders } from '@softistx/alxia-secure-headers';
429
+
430
+ const app = alxia();
431
+
432
+ app.use(
433
+ secureHeaders({
434
+ nonce: true,
435
+ contentSecurityPolicy: csp({ 'script-src': ["'self'", NONCE] }),
436
+ cacheControl: 'private, no-store',
437
+ }),
438
+ );
439
+ ```
440
+
441
+ It is set like every other header: a route's own `Cache-Control` is kept
442
+ (a static asset can stay cacheable), and a 404 or a thrown error gets it too.
443
+ An empty value is refused at startup; give `false` to leave it out. A page's
444
+ own `Cache-Control` must stay `private` or `no-store` while it carries a
445
+ nonce, never `public`.
446
+
447
+ ## Clear-Site-Data
448
+
449
+ After a sign-out, the browser's HTTP cache can still hold pages the viewer
450
+ saw, which matters on a shared device. `Clear-Site-Data` tells the browser to
451
+ empty it. `clearSiteData(types, options?)` sends the header on a successful
452
+ answer, and only on one:
453
+
454
+ ```ts
455
+ import { alxia } from '@softistx/alxia';
456
+ import { clearSiteData } from '@softistx/alxia-secure-headers';
457
+
458
+ const cleared = clearSiteData(['cache']);
459
+
460
+ const app = alxia()
461
+ .use('/sign-out', cleared)
462
+ .use('/sign-out.data', cleared);
463
+ ```
464
+
465
+ - **Only a sign-out that went through.** It sends the header on a 2xx or 3xx
466
+ answer to one of `methods` (`['POST']` by default). A GET, or a refused
467
+ request (a 403, a 415, a failure), signed nobody out and must not empty
468
+ their cache. Pass `{ methods: ['POST', 'DELETE'] }` to widen the rule.
469
+ - **Not for another site's request.** A form on another site can post to
470
+ `/sign-out` and get a redirect, which would wipe the viewer's cache or
471
+ cookies. So when `Sec-Fetch-Site` is present, it alone decides: anything
472
+ other than `same-origin` or `none` clears nothing (`same-site` too, since a
473
+ sibling subdomain may be attacker-controlled), and `Origin` is not
474
+ read. Only without it (an older browser) is an `Origin` compared with the
475
+ app's own origin. A request with neither header (curl) is cleared.
476
+ Modern browsers need nothing more behind a TLS-terminating proxy, since
477
+ the proxy does not rewrite `Sec-Fetch-Site`. For older browsers behind
478
+ one, where the request's URL says `http:` and `Origin` says `https:`, set
479
+ `origin: 'https://app.example.com'` (or a function returning it). Pass
480
+ `{ crossSite: true }` only to give the protection up.
481
+ - **A route's own header wins.** An answer that already carries
482
+ `Clear-Site-Data` keeps it, as `secureHeaders` does for its headers.
483
+ - **Several types** are written quoted and comma-separated:
484
+ `clearSiteData(['cache', 'cookies'])` sends `"cache", "cookies"`.
485
+ - **Both paths with React Router.** A form posts `/sign-out`, but the client
486
+ navigates with single fetch, which posts `/sign-out.data`. Its answer
487
+ carries a redirect's cookies, not its other headers, so the route cannot
488
+ set the header: the middleware does, on the way out. Mount it on both paths.
489
+ `/sign-outs` matches neither.
490
+ - **Checked at startup.** An empty list or an unknown type throws a
491
+ `TypeError` that starts `clearSiteData():`
492
+ ([troubleshooting](troubleshooting.md#runtime)).
493
+
494
+ ## Which responses get the headers
495
+
496
+ The middleware settles `next()`: it sets the headers on the response the
497
+ client would get, whatever produced it.
498
+
499
+ | Response | Headers |
500
+ | --- | --- |
501
+ | a route's reply, `static` and `file` included | yes |
502
+ | the core's 400, 404, 405 and 500, and a `try`/`catch` middleware's reply declared after it | yes |
503
+ | a `Response` another middleware returned (a CORS preflight, a redirect) | yes, when that middleware is declared after `secureHeaders` |
504
+ | a route declared before `app.use(secureHeaders())` | no: the middleware does not run for it |
505
+ | a WebSocket upgrade that succeeds (`101`) | no: the upgrade is not a response a middleware can decorate |
506
+ | a page served with `page()` | no: `Bun.serve` serves it, around no middleware |
507
+
508
+ ```ts
509
+ const app = alxia().use(secureHeaders());
510
+
511
+ const response = await app.request('/nope');
512
+ response.status; // 404
513
+ response.headers.get('x-content-type-options'); // 'nosniff'
514
+ ```
515
+
516
+ ## Order with other middlewares
517
+
518
+ Middlewares nest: the first `use` is the outermost, and on the way out each
519
+ one sees the response of the ones after it. The middleware never overwrites
520
+ a header that is already there. So:
521
+
522
+ - a middleware declared **after** `secureHeaders` that sets one of its
523
+ headers wins: `secureHeaders` finds it already there;
524
+ - a middleware declared **before** it that sets one of its headers wins too,
525
+ by overwriting;
526
+ - a middleware declared **before** it that adds `X-Powered-By` or `Server`
527
+ keeps it: `secureHeaders` deleted them before that one ran.
528
+
529
+ ```ts
530
+ import { alxia, defineMiddleware, settle, withHeaders } from '@softistx/alxia';
531
+ import { secureHeaders } from '@softistx/alxia-secure-headers';
532
+
533
+ const referrerOrigin = defineMiddleware(async (ctx, next) =>
534
+ withHeaders(await settle(ctx, next()), (headers) => headers.set('referrer-policy', 'origin')),
535
+ );
536
+
537
+ const app = alxia()
538
+ .use(secureHeaders())
539
+ .use(referrerOrigin)
540
+ .get('/', ({ reply }) => reply(200, 'ok'));
541
+
542
+ (await app.request('/')).headers.get('referrer-policy'); // 'origin'
543
+ ```
544
+
545
+ Declare `secureHeaders()` among the observers, first: `logger()`,
546
+ `telemetry()`, `secureHeaders()`, `cors()`, `compress()`. An
547
+ error-handling middleware — a `try`/`catch` around `next()`, or
548
+ `janusErrors()` — goes **after** it. `secureHeaders()` settles `next()`: it
549
+ sets the headers on the response the error would be answered with (its
550
+ `HttpError`'s status, or a 500), then the error
551
+ goes on, so a `try`/`catch` catches it wherever it is declared; declared
552
+ before `secureHeaders()`, its reply does not carry the headers. A guard on the app (`bearer`, a required
553
+ session) declared before it answers its `401` without them.
554
+
555
+ ## A header the middleware does not know
556
+
557
+ The middleware sends the twelve headers above and nothing else. Another one —
558
+ `Content-Security-Policy-Report-Only` while a policy is being tried, say —
559
+ is a middleware of your own, with `settle` and `withHeaders` from
560
+ `@softistx/alxia`:
561
+
562
+ ```ts
563
+ import { alxia, defineMiddleware, settle, withHeaders } from '@softistx/alxia';
564
+ import { secureHeaders } from '@softistx/alxia-secure-headers';
565
+
566
+ const reportOnly = defineMiddleware(async (ctx, next) =>
567
+ withHeaders(await settle(ctx, next()), (headers) => {
568
+ if (!headers.has('content-security-policy-report-only')) {
569
+ headers.set('content-security-policy-report-only', "default-src 'self'; report-to csp");
570
+ }
571
+ }),
572
+ );
573
+
574
+ const app = alxia()
575
+ .use(secureHeaders())
576
+ .use(reportOnly);
577
+ ```
578
+
579
+ See [Middleware](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/middleware.md)
580
+ in the core's guide for what a middleware may do.
581
+
582
+ ## Recipes
583
+
584
+ ### An app that serves HTML too
585
+
586
+ The default policy blocks everything a page loads. Loosen it for the whole
587
+ app when it serves its own pages, and keep framing refused:
588
+
589
+ ```ts
590
+ app.use(
591
+ secureHeaders({
592
+ contentSecurityPolicy:
593
+ "default-src 'self'; img-src 'self' data:; base-uri 'self'; form-action 'self'; frame-ancestors 'none'",
594
+ }),
595
+ );
596
+ ```
597
+
598
+ Or keep the strict default for the API and give the pages their policy on
599
+ their reply, as in [A header a route sets is kept](#a-header-a-route-sets-is-kept).
600
+ When the pages run inline scripts, add `nonce: true` rather than
601
+ `'unsafe-inline'`: [A nonce per request](#a-nonce-per-request).
602
+
603
+ ### Framed by your own origin
604
+
605
+ Both `frame-ancestors` in the policy and `X-Frame-Options` refuse framing;
606
+ change both:
607
+
608
+ ```ts
609
+ app.use(
610
+ secureHeaders({
611
+ contentSecurityPolicy: "default-src 'none'; frame-ancestors 'self'",
612
+ xFrameOptions: 'SAMEORIGIN',
613
+ }),
614
+ );
615
+ ```
616
+
617
+ ### Images or files embedded by another origin
618
+
619
+ `Cross-Origin-Resource-Policy: same-origin` stops another origin's
620
+ `<img>`, `<script>` or `no-cors` fetch from reading the response. A
621
+ CORS `fetch` is not affected. For a public asset host:
622
+
623
+ ```ts
624
+ app.use(secureHeaders({ crossOriginResourcePolicy: 'cross-origin' }));
625
+ ```
626
+
627
+ ### Sign-in in a popup
628
+
629
+ `Cross-Origin-Opener-Policy: same-origin` cuts the link between a page and
630
+ a popup of another origin, which a sign-in popup that reports back through
631
+ `window.opener` needs:
632
+
633
+ ```ts
634
+ app.use(secureHeaders({ crossOriginOpenerPolicy: 'same-origin-allow-popups' }));
635
+ ```
636
+
637
+ ### Cross-origin isolation
638
+
639
+ `SharedArrayBuffer` and precise timers need the page to be cross-origin
640
+ isolated, which takes `Cross-Origin-Embedder-Policy` beside the default
641
+ `Cross-Origin-Opener-Policy: same-origin`:
642
+
643
+ ```ts
644
+ app.use(secureHeaders({ crossOriginEmbedderPolicy: 'require-corp' }));
645
+ ```
646
+
647
+ ## In a real app
648
+
649
+ An API with a sign-in page, its own pages' policy, HSTS only in production,
650
+ and a test that holds the headers in place:
651
+
652
+ ```ts
653
+ // app.ts
654
+ import { alxia } from '@softistx/alxia';
655
+ import { secureHeaders } from '@softistx/alxia-secure-headers';
656
+
657
+ const production = Bun.env.NODE_ENV === 'production';
658
+ const PAGE_POLICY =
659
+ "default-src 'self'; img-src 'self' data:; base-uri 'self'; form-action 'self'; frame-ancestors 'none'";
660
+
661
+ export const app = alxia()
662
+ .use(
663
+ secureHeaders({
664
+ permissionsPolicy: 'camera=(), microphone=(), geolocation=()',
665
+ ...(production ? {} : { strictTransportSecurity: false }),
666
+ }),
667
+ )
668
+ .get('/api/me', ({ reply }) => reply(200, { name: 'Ada' }))
669
+ .get('/sign-in', ({ reply }) =>
670
+ reply(200, '<form method="post" action="/sign-in">…</form>', {
671
+ headers: {
672
+ 'content-type': 'text/html; charset=utf-8',
673
+ 'content-security-policy': PAGE_POLICY,
674
+ },
675
+ }),
676
+ );
677
+ ```
678
+
679
+ ```ts
680
+ // app.spec.ts
681
+ import { expect, test } from 'bun:test';
682
+ import { app } from './app';
683
+
684
+ test('the API keeps the strict policy', async () => {
685
+ const response = await app.request('/api/me');
686
+ expect(response.headers.get('content-security-policy')).toStartWith("default-src 'none'");
687
+ expect(response.headers.get('x-frame-options')).toBe('DENY');
688
+ });
689
+
690
+ test('the sign-in page has its own', async () => {
691
+ const response = await app.request('/sign-in');
692
+ expect(response.headers.get('content-security-policy')).toContain("form-action 'self'");
693
+ expect(response.headers.get('permissions-policy')).toBe('camera=(), microphone=(), geolocation=()');
694
+ });
695
+
696
+ test('a 404 is covered too', async () => {
697
+ const response = await app.request('/nope');
698
+ expect(response.status).toBe(404);
699
+ expect(response.headers.get('x-content-type-options')).toBe('nosniff');
700
+ });
701
+ ```
702
+
703
+ ### A server-rendered page
704
+
705
+ The same app with `pageHeaders`, a font from another origin, and the spec
706
+ that holds the policy in place:
707
+
708
+ ```ts
709
+ // app.ts
710
+ import { alxia } from '@softistx/alxia';
711
+ import { pageHeaders } from '@softistx/alxia-secure-headers';
712
+
713
+ export const app = alxia()
714
+ .use(
715
+ pageHeaders({
716
+ https: Bun.env.NODE_ENV === 'production',
717
+ directives: { 'font-src': ["'self'", 'https://fonts.example'] },
718
+ }),
719
+ )
720
+ .get('/', ({ nonce, reply }) =>
721
+ reply(200, `<script nonce="${nonce}">console.log('hi')</script>`, {
722
+ headers: { 'content-type': 'text/html; charset=utf-8' },
723
+ }),
724
+ );
725
+ ```
726
+
727
+ ```ts
728
+ // app.spec.ts
729
+ import { expect, test } from 'bun:test';
730
+ import { app } from './app';
731
+
732
+ test('a page carries its nonce, is never cached, and may load the font', async () => {
733
+ const response = await app.request('/');
734
+ const html = await response.text();
735
+ const nonce = /nonce="([^"]+)"/.exec(html)?.[1];
736
+ const policy = response.headers.get('content-security-policy') ?? '';
737
+ expect(policy).toContain(`'nonce-${nonce}'`);
738
+ expect(policy).toContain("font-src 'self' https://fonts.example");
739
+ expect(response.headers.get('cache-control')).toBe('private, no-store');
740
+ });
741
+ ```
742
+
743
+ ## See also
744
+
745
+ - [Troubleshooting](troubleshooting.md): a browser refuses something, or
746
+ TypeScript does.
747
+ - [Middleware](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/middleware.md)
748
+ and [Groups and plugins](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/groups-and-plugins.md)
749
+ in the core's guide.