@softistx/alxia-secure-headers 0.0.0-stage → 0.6.1
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/LICENSE +21 -0
- package/README.md +231 -2
- package/dist/clear-site-data.d.ts +49 -0
- package/dist/clear-site-data.d.ts.map +1 -0
- package/dist/csp.d.ts +36 -0
- package/dist/csp.d.ts.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +292 -0
- package/dist/index.js.map +14 -0
- package/dist/nonce.d.ts +34 -0
- package/dist/nonce.d.ts.map +1 -0
- package/dist/page.d.ts +58 -0
- package/dist/page.d.ts.map +1 -0
- package/dist/secure-headers.d.ts +64 -0
- package/dist/secure-headers.d.ts.map +1 -0
- package/docs/README.md +11 -0
- package/docs/guide.md +749 -0
- package/docs/roadmap.md +77 -0
- package/docs/troubleshooting.md +959 -0
- package/package.json +51 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Steve Tsala
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,232 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @softistx/alxia-secure-headers
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Moved from `@alxia/secure-headers`: see the [migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md).
|
|
4
|
+
|
|
5
|
+
Secure HTTP headers on every response of an
|
|
6
|
+
[alxia](https://www.npmjs.com/package/@softistx/alxia) app, 404s included, with
|
|
7
|
+
no dependency.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
bun add @softistx/alxia-secure-headers @softistx/alxia
|
|
11
|
+
bun add -d typescript
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { secureHeaders } from '@softistx/alxia-secure-headers';
|
|
18
|
+
|
|
19
|
+
app.use(secureHeaders());
|
|
20
|
+
app.use(secureHeaders({ contentSecurityPolicy: "default-src 'self'", xFrameOptions: false }));
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`secureHeaders()` is a middleware: every response that comes back through
|
|
24
|
+
it carries the headers, a 404's, an error's and a refused preflight's
|
|
25
|
+
included. A header a route sets itself is kept: a page that needs its own
|
|
26
|
+
policy sets it on its reply.
|
|
27
|
+
|
|
28
|
+
## A nonce per request
|
|
29
|
+
|
|
30
|
+
`nonce: true` makes a fresh nonce for each request (128 random bits,
|
|
31
|
+
base64), puts it in the policy as `'nonce-…'`, and gives it to the routes
|
|
32
|
+
declared after the middleware as `ctx.nonce`. The header and the context always
|
|
33
|
+
carry the same one, so a page's inline scripts need no `'unsafe-inline'`.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { alxia } from '@softistx/alxia';
|
|
37
|
+
import { secureHeaders } from '@softistx/alxia-secure-headers';
|
|
38
|
+
|
|
39
|
+
const app = alxia()
|
|
40
|
+
.use(
|
|
41
|
+
secureHeaders({
|
|
42
|
+
nonce: true,
|
|
43
|
+
// The nonce is added to script-src (and script-src-elem).
|
|
44
|
+
contentSecurityPolicy: "default-src 'self'; script-src 'self'",
|
|
45
|
+
}),
|
|
46
|
+
)
|
|
47
|
+
.get('/', ({ nonce, reply }) =>
|
|
48
|
+
reply(200, `<script nonce="${nonce}">console.log('allowed')</script>`, {
|
|
49
|
+
headers: { 'content-type': 'text/html' },
|
|
50
|
+
}),
|
|
51
|
+
);
|
|
52
|
+
// content-security-policy: default-src 'self'; script-src 'self' 'nonce-3q2+7w…=='
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
To place it yourself, in `style-src` say, write `NONCE` where it goes;
|
|
56
|
+
each occurrence becomes the request's `'nonce-…'`, and `script-src` is then
|
|
57
|
+
left as written:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { NONCE, secureHeaders } from '@softistx/alxia-secure-headers';
|
|
61
|
+
|
|
62
|
+
app.use(
|
|
63
|
+
secureHeaders({
|
|
64
|
+
nonce: true,
|
|
65
|
+
contentSecurityPolicy: `default-src 'self'; script-src 'self' ${NONCE}; style-src 'self' ${NONCE}`,
|
|
66
|
+
}),
|
|
67
|
+
);
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
A policy with nowhere to put the nonce (no `script-src`, no `NONCE`) is
|
|
71
|
+
refused at startup, the default policy included: give `contentSecurityPolicy`
|
|
72
|
+
with `nonce: true`. Without `nonce: true`, the headers are what they always
|
|
73
|
+
were. With `@softistx/alxia-react-router`, `nonceOf(loadContext)` hands it to
|
|
74
|
+
`entry.server.tsx` ([its README](https://github.com/softistx/alxia/tree/develop/packages/react-router#a-csp-nonce)).
|
|
75
|
+
|
|
76
|
+
## A policy from directives
|
|
77
|
+
|
|
78
|
+
`csp()` writes the policy from directives, in the order you list them, and
|
|
79
|
+
checks it once at startup. A list of sources is an array, `true` is a bare
|
|
80
|
+
directive and `false` leaves one out; `NONCE` passes through, for
|
|
81
|
+
`nonce: true` to replace on each request.
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import { csp, NONCE, secureHeaders } from '@softistx/alxia-secure-headers';
|
|
85
|
+
|
|
86
|
+
app.use(
|
|
87
|
+
secureHeaders({
|
|
88
|
+
nonce: true,
|
|
89
|
+
contentSecurityPolicy: csp({
|
|
90
|
+
'default-src': ["'self'"],
|
|
91
|
+
'script-src': ["'self'", NONCE],
|
|
92
|
+
'object-src': ["'none'"],
|
|
93
|
+
'upgrade-insecure-requests': true,
|
|
94
|
+
}),
|
|
95
|
+
}),
|
|
96
|
+
);
|
|
97
|
+
// default-src 'self'; script-src 'self' 'nonce-…'; object-src 'none'; upgrade-insecure-requests
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
An empty source list, a source holding `;`, `,` or a space, a name that is
|
|
101
|
+
not lowercase letters, digits and hyphens starting with a letter, and a policy with no directive are
|
|
102
|
+
refused with a `TypeError` that starts `csp():`.
|
|
103
|
+
|
|
104
|
+
## Clearing the browser on sign-out
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { clearSiteData } from '@softistx/alxia-secure-headers';
|
|
108
|
+
|
|
109
|
+
const cleared = clearSiteData(['cache']);
|
|
110
|
+
|
|
111
|
+
app.use('/sign-out', cleared).use('/sign-out.data', cleared);
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`Clear-Site-Data: "cache"` is sent on a 2xx or 3xx answer to a `POST`, so
|
|
115
|
+
nothing of the visit stays in the browser's HTTP cache on a shared device. A
|
|
116
|
+
GET, a 400, a 403 or a 500 clears nothing. `{ methods: ['POST', 'DELETE'] }`
|
|
117
|
+
widens the rule. A route's own `Clear-Site-Data` is kept. React Router's client-side sign-out posts `/sign-out.data`,
|
|
118
|
+
so mount both paths. An empty list or an unknown type is refused with a
|
|
119
|
+
`TypeError` that starts `clearSiteData():`.
|
|
120
|
+
|
|
121
|
+
## Pages
|
|
122
|
+
|
|
123
|
+
`pageHeaders()` is `secureHeaders` for server-rendered pages: a strict policy
|
|
124
|
+
with a nonce per request, HSTS and `upgrade-insecure-requests` only over
|
|
125
|
+
HTTPS, `Referrer-Policy: strict-origin-when-cross-origin`, and
|
|
126
|
+
`Cache-Control: private, no-store`, since a cache must never store a nonce.
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import { createServer } from '@softistx/alxia-react-router';
|
|
130
|
+
import { pageHeaders } from '@softistx/alxia-secure-headers';
|
|
131
|
+
|
|
132
|
+
export default createServer({
|
|
133
|
+
configure: (app) => app.use(pageHeaders({ https: import.meta.env.PROD })),
|
|
134
|
+
});
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`https` is required and never read from the environment. `PAGE_DIRECTIVES`
|
|
138
|
+
is the policy: `'self'` for everything, scripts only with the nonce (and what
|
|
139
|
+
they load, `'strict-dynamic'`), nonced `<style>` elements, no `<base>`, forms
|
|
140
|
+
to this site, no framing. `directives` merges over it: a list replaces a
|
|
141
|
+
directive's sources, `false` removes the directive.
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
app.use(
|
|
145
|
+
pageHeaders({
|
|
146
|
+
https: true,
|
|
147
|
+
directives: {
|
|
148
|
+
'img-src': ["'self'", 'https://images.example'],
|
|
149
|
+
'manifest-src': false,
|
|
150
|
+
},
|
|
151
|
+
}),
|
|
152
|
+
);
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Any other `secureHeaders` option passes through and wins over the preset's;
|
|
156
|
+
`contentSecurityPolicy` and `nonce` are not options here, and an explicit
|
|
157
|
+
`undefined` keeps the preset's value. A `script-src`, or a `script-src-elem`
|
|
158
|
+
list, without `NONCE` is refused with a `TypeError` that starts
|
|
159
|
+
`pageHeaders():`; so is removing `default-src`, `base-uri` or `object-src`.
|
|
160
|
+
`csp()` refuses a keyword written without its quotes (`self` for `'self'`) with
|
|
161
|
+
a `TypeError` that starts `csp():`. `clearSiteData()` sends nothing for a
|
|
162
|
+
request another site made (`Sec-Fetch-Site`, else `Origin` against the
|
|
163
|
+
`origin` option, which a TLS-terminating proxy needs for older browsers),
|
|
164
|
+
unless `crossSite: true`.
|
|
165
|
+
|
|
166
|
+
## Defaults
|
|
167
|
+
|
|
168
|
+
| header | default | option |
|
|
169
|
+
| --- | --- | --- |
|
|
170
|
+
| `Content-Security-Policy` | `default-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'` | `contentSecurityPolicy` |
|
|
171
|
+
| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains` | `strictTransportSecurity` |
|
|
172
|
+
| `X-Content-Type-Options` | `nosniff` | `xContentTypeOptions` |
|
|
173
|
+
| `X-Frame-Options` | `DENY` | `xFrameOptions` |
|
|
174
|
+
| `Referrer-Policy` | `no-referrer` | `referrerPolicy` |
|
|
175
|
+
| `Cross-Origin-Opener-Policy` | `same-origin` | `crossOriginOpenerPolicy` |
|
|
176
|
+
| `Cross-Origin-Resource-Policy` | `same-origin` | `crossOriginResourcePolicy` |
|
|
177
|
+
| `Cross-Origin-Embedder-Policy` | not sent | `crossOriginEmbedderPolicy` |
|
|
178
|
+
| `Origin-Agent-Cluster` | `?1` | `originAgentCluster` |
|
|
179
|
+
| `X-DNS-Prefetch-Control` | `off` | `xDnsPrefetchControl` |
|
|
180
|
+
| `X-Permitted-Cross-Domain-Policies` | `none` | `xPermittedCrossDomainPolicies` |
|
|
181
|
+
| `Permissions-Policy` | not sent | `permissionsPolicy` |
|
|
182
|
+
| `Cache-Control` | not sent | `cacheControl` |
|
|
183
|
+
|
|
184
|
+
Each option takes a value, or `false` to leave the header out; an empty
|
|
185
|
+
value is refused at startup. `nonce` is off by default.
|
|
186
|
+
`X-Powered-By` and `Server` are removed unless `hidePoweredBy: false`.
|
|
187
|
+
|
|
188
|
+
`cacheControl` is for pages that carry a nonce or a viewer's data:
|
|
189
|
+
`cacheControl: 'private, no-store'` keeps a cache from storing them. A route's
|
|
190
|
+
own `Cache-Control` wins, and a 404 or a thrown error gets it too.
|
|
191
|
+
|
|
192
|
+
## API
|
|
193
|
+
|
|
194
|
+
| export | |
|
|
195
|
+
| --- | --- |
|
|
196
|
+
| `secureHeaders(options?)` | the middleware, for `app.use`: a `SecureHeaders`, or with `nonce: true` a `NonceMiddleware` |
|
|
197
|
+
| `SecureHeadersOptions` | its options: the headers (`cacheControl` included) and `hidePoweredBy`; `nonce` is added by each overload |
|
|
198
|
+
| `Setting` | a header option's type: its value, or `false` to leave it out |
|
|
199
|
+
| `csp(directives)` | a `Content-Security-Policy` string from directives, checked at startup |
|
|
200
|
+
| `CspDirectives` | its argument: directive names to a `CspValue`, any name allowed |
|
|
201
|
+
| `CspDirectiveName` | the directive names it completes |
|
|
202
|
+
| `CspValue` | a directive's value: a list of sources, `true` for a bare directive, `false` to leave it out |
|
|
203
|
+
| `clearSiteData(types, options?)` | a middleware sending `Clear-Site-Data` on a 2xx or 3xx answer to a `POST` (or `options.methods`) |
|
|
204
|
+
| `ClearSiteDataType` | a value of the header: `'cache'`, `'cookies'`, `'storage'`, `'executionContexts'`, `'clientHints'`, `'prefetchCache'`, `'prerenderCache'` or `'*'` |
|
|
205
|
+
| `ClearSiteDataOptions` | its options: `methods`, `['POST']` by default |
|
|
206
|
+
| `ClearSiteData` | what `clearSiteData()` returns: a middleware that adds nothing to the context |
|
|
207
|
+
| `pageHeaders(options)` | `secureHeaders({ nonce: true, … })` for server-rendered pages: `PAGE_DIRECTIVES` with a nonce, HSTS with `https`, no-store |
|
|
208
|
+
| `PageHeadersOptions` | its options: `https` (required), `directives`, and every `secureHeaders` option but the policy and `nonce` |
|
|
209
|
+
| `PAGE_DIRECTIVES` | the page policy's 13 directives, a `CspDirectives` |
|
|
210
|
+
| `NONCE` | where the nonce goes in `contentSecurityPolicy`, each time it is named |
|
|
211
|
+
| `NonceContext` | what `nonce: true` adds to the context: `nonce`, a string |
|
|
212
|
+
| `SecureHeaders` | what `secureHeaders()` returns: a middleware that adds nothing to the context |
|
|
213
|
+
| `NonceMiddleware` | what `secureHeaders({ nonce: true })` returns: a middleware adding `NonceContext` |
|
|
214
|
+
|
|
215
|
+
## Traps
|
|
216
|
+
|
|
217
|
+
`use` it first: a route declared before `app.use(secureHeaders())` gets no
|
|
218
|
+
header, and `ctx.nonce` exists only on routes declared after it. It
|
|
219
|
+
settles `next()` without swallowing the error: a `try`/`catch` middleware
|
|
220
|
+
catches it wherever it stands, but only one declared after
|
|
221
|
+
`secureHeaders()` has the headers on its reply. Declare error-handling
|
|
222
|
+
middleware after it.
|
|
223
|
+
|
|
224
|
+
```ts
|
|
225
|
+
const app = alxia().use(secureHeaders()).use(errorHandler).get(...);
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## Documentation
|
|
229
|
+
|
|
230
|
+
- [Guide](https://github.com/softistx/alxia/tree/develop/packages/secure-headers/docs): every option and its default, the per-request nonce, `csp()`, `pageHeaders()`, `cacheControl` and `clearSiteData()`, which responses get the headers, a page's own policy, the order with other middlewares, and recipes.
|
|
231
|
+
- [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/secure-headers/docs/troubleshooting.md): an error message or a browser refusal, and what to do about it.
|
|
232
|
+
- [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/secure-headers/docs/roadmap.md): what is coming, and what is not planned.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `clearSiteData`: `Clear-Site-Data` on a successful, same-site sign-out, as a
|
|
3
|
+
* middleware for the sign-out path.
|
|
4
|
+
*/
|
|
5
|
+
import { type Empty, type Middleware } from '@softistx/alxia';
|
|
6
|
+
declare const TYPES: readonly ["cache", "cookies", "storage", "executionContexts", "clientHints", "prefetchCache", "prerenderCache", "*"];
|
|
7
|
+
/** A value of the `Clear-Site-Data` header, without its quotes. */
|
|
8
|
+
export type ClearSiteDataType = (typeof TYPES)[number];
|
|
9
|
+
export interface ClearSiteDataOptions {
|
|
10
|
+
/** Defaults to `['POST']`: a GET to a sign-out URL clears nothing. */
|
|
11
|
+
readonly methods?: readonly string[];
|
|
12
|
+
/**
|
|
13
|
+
* Also clear on a request another site made. Defaults to `false`: a
|
|
14
|
+
* request whose `Sec-Fetch-Site` is not `same-origin` or `none`, or whose
|
|
15
|
+
* `Origin` is not the request's own, clears nothing.
|
|
16
|
+
*/
|
|
17
|
+
readonly crossSite?: boolean;
|
|
18
|
+
/**
|
|
19
|
+
* The origin a request must come from, such as `https://app.example.com`:
|
|
20
|
+
* required behind a TLS-terminating proxy, where the request's own URL
|
|
21
|
+
* says `http:`, for a browser that sends no `Sec-Fetch-Site`. A getter is
|
|
22
|
+
* read at each request. Else the request's own origin.
|
|
23
|
+
*/
|
|
24
|
+
readonly origin?: string | (() => string | undefined);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* What `clearSiteData()` returns: a middleware, for `app.use`, that adds
|
|
28
|
+
* nothing to the context.
|
|
29
|
+
*/
|
|
30
|
+
export type ClearSiteData = Middleware<Empty, Promise<Response>>;
|
|
31
|
+
/**
|
|
32
|
+
* `Clear-Site-Data` on a 2xx or 3xx answer to one of `methods` (`POST` by
|
|
33
|
+
* default). A request clears nothing when it is refused (a 403, a failure) or
|
|
34
|
+
* when another site made it (`Sec-Fetch-Site` other than `same-origin` or
|
|
35
|
+
* `none`; without that header, a foreign `Origin`), unless `crossSite` is `true`; a request
|
|
36
|
+
* with neither header, such as curl's, is cleared. Give it to `use(path, …)` for the sign-out path; React Router's
|
|
37
|
+
* single fetch posts `.data` too, so mount both:
|
|
38
|
+
*
|
|
39
|
+
* ```ts
|
|
40
|
+
* const cleared = clearSiteData(['cache']);
|
|
41
|
+
* app.use('/sign-out', cleared).use('/sign-out.data', cleared);
|
|
42
|
+
* ```
|
|
43
|
+
*
|
|
44
|
+
* Throws a `TypeError` at declaration on an empty `types`, a type that is not
|
|
45
|
+
* one of `ClearSiteDataType`, and an empty `methods` or an empty method name.
|
|
46
|
+
*/
|
|
47
|
+
export declare function clearSiteData(types: readonly ClearSiteDataType[], options?: ClearSiteDataOptions): ClearSiteData;
|
|
48
|
+
export {};
|
|
49
|
+
//# sourceMappingURL=clear-site-data.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clear-site-data.d.ts","sourceRoot":"","sources":["../src/clear-site-data.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAEN,KAAK,KAAK,EACV,KAAK,UAAU,EAIf,MAAM,iBAAiB,CAAC;AAEzB,QAAA,MAAM,KAAK,sHASD,CAAC;AAEX,mEAAmE;AACnE,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC;AAEvD,MAAM,WAAW,oBAAoB;IACpC,sEAAsE;IACtE,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC;;;;OAIG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAC7B;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,GAAG,SAAS,CAAC,CAAC;CACtD;AAED;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG,UAAU,CAAC,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;AAwBjE;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,aAAa,CAC5B,KAAK,EAAE,SAAS,iBAAiB,EAAE,EACnC,OAAO,GAAE,oBAAyB,GAChC,aAAa,CAgCf"}
|
package/dist/csp.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `csp`: a `Content-Security-Policy` written as directives, checked once at
|
|
3
|
+
* startup, instead of one long string.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* A directive's value: its sources; `true` for a bare directive
|
|
7
|
+
* (`upgrade-insecure-requests`); `false` to leave it out.
|
|
8
|
+
*/
|
|
9
|
+
export type CspValue = readonly string[] | boolean;
|
|
10
|
+
/** The directives a policy usually names, for completion. */
|
|
11
|
+
export type CspDirectiveName = 'default-src' | 'script-src' | 'script-src-elem' | 'script-src-attr' | 'style-src' | 'style-src-elem' | 'style-src-attr' | 'img-src' | 'font-src' | 'connect-src' | 'media-src' | 'object-src' | 'frame-src' | 'child-src' | 'worker-src' | 'manifest-src' | 'base-uri' | 'form-action' | 'frame-ancestors' | 'upgrade-insecure-requests' | 'sandbox';
|
|
12
|
+
/** A policy's directives: the known names complete, any other name is allowed. */
|
|
13
|
+
export type CspDirectives = {
|
|
14
|
+
readonly [K in CspDirectiveName]?: CspValue | undefined;
|
|
15
|
+
} & {
|
|
16
|
+
readonly [name: string]: CspValue | undefined;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* The policy, written in insertion order: `name src src; name src`. `NONCE`
|
|
20
|
+
* passes through as it is, for `secureHeaders({ nonce: true })` to replace.
|
|
21
|
+
* Throws a `TypeError` at startup on a policy a browser would misread, such
|
|
22
|
+
* as a keyword written without its quotes (`self` for `'self'`).
|
|
23
|
+
*
|
|
24
|
+
* ```ts
|
|
25
|
+
* secureHeaders({
|
|
26
|
+
* nonce: true,
|
|
27
|
+
* contentSecurityPolicy: csp({
|
|
28
|
+
* 'default-src': ["'self'"],
|
|
29
|
+
* 'script-src': ["'self'", NONCE],
|
|
30
|
+
* 'upgrade-insecure-requests': true,
|
|
31
|
+
* }),
|
|
32
|
+
* });
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
export declare function csp(directives: CspDirectives): string;
|
|
36
|
+
//# sourceMappingURL=csp.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"csp.d.ts","sourceRoot":"","sources":["../src/csp.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAAG,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC;AAEnD,6DAA6D;AAC7D,MAAM,MAAM,gBAAgB,GACzB,aAAa,GACb,YAAY,GACZ,iBAAiB,GACjB,iBAAiB,GACjB,WAAW,GACX,gBAAgB,GAChB,gBAAgB,GAChB,SAAS,GACT,UAAU,GACV,aAAa,GACb,WAAW,GACX,YAAY,GACZ,WAAW,GACX,WAAW,GACX,YAAY,GACZ,cAAc,GACd,UAAU,GACV,aAAa,GACb,iBAAiB,GACjB,2BAA2B,GAC3B,SAAS,CAAC;AAEb,kFAAkF;AAClF,MAAM,MAAM,aAAa,GAAG;IAC3B,QAAQ,EAAE,CAAC,IAAI,gBAAgB,CAAC,CAAC,EAAE,QAAQ,GAAG,SAAS;CACvD,GAAG;IACH,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC;CAC9C,CAAC;AAuBF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,GAAG,CAAC,UAAU,EAAE,aAAa,GAAG,MAAM,CAwCrD"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { type ClearSiteData, type ClearSiteDataOptions, type ClearSiteDataType, clearSiteData, } from './clear-site-data';
|
|
2
|
+
export { type CspDirectiveName, type CspDirectives, type CspValue, csp, } from './csp';
|
|
3
|
+
export { NONCE, type NonceContext } from './nonce';
|
|
4
|
+
export { PAGE_DIRECTIVES, type PageHeadersOptions, pageHeaders, } from './page';
|
|
5
|
+
export { type NonceMiddleware, type SecureHeaders, type SecureHeadersOptions, type Setting, secureHeaders, } from './secure-headers';
|
|
6
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,aAAa,GACb,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACN,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,QAAQ,EACb,GAAG,GACH,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,KAAK,EAAE,KAAK,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EACN,eAAe,EACf,KAAK,kBAAkB,EACvB,WAAW,GACX,MAAM,QAAQ,CAAC;AAChB,OAAO,EACN,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,OAAO,EACZ,aAAa,GACb,MAAM,kBAAkB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
// src/clear-site-data.ts
|
|
2
|
+
import {
|
|
3
|
+
defineMiddleware,
|
|
4
|
+
markFactory,
|
|
5
|
+
settle,
|
|
6
|
+
withHeaders
|
|
7
|
+
} from "@softistx/alxia";
|
|
8
|
+
var TYPES = [
|
|
9
|
+
"cache",
|
|
10
|
+
"cookies",
|
|
11
|
+
"storage",
|
|
12
|
+
"executionContexts",
|
|
13
|
+
"clientHints",
|
|
14
|
+
"prefetchCache",
|
|
15
|
+
"prerenderCache",
|
|
16
|
+
"*"
|
|
17
|
+
];
|
|
18
|
+
function quoted(names) {
|
|
19
|
+
return names.map((name) => `"${name}"`).join(", ");
|
|
20
|
+
}
|
|
21
|
+
function isCrossSite(request, own) {
|
|
22
|
+
const site = request.headers.get("sec-fetch-site");
|
|
23
|
+
if (site !== null)
|
|
24
|
+
return site !== "same-origin" && site !== "none";
|
|
25
|
+
const origin = request.headers.get("origin");
|
|
26
|
+
if (origin === null)
|
|
27
|
+
return false;
|
|
28
|
+
const set = typeof own === "function" ? own() : own;
|
|
29
|
+
return origin !== (set ?? new URL(request.url).origin);
|
|
30
|
+
}
|
|
31
|
+
function clearSiteData(types, options = {}) {
|
|
32
|
+
if (types.length === 0) {
|
|
33
|
+
throw new TypeError('clearSiteData(): no type is given: write at least one, such as ["cache"]');
|
|
34
|
+
}
|
|
35
|
+
for (const type of types) {
|
|
36
|
+
if (!TYPES.includes(type)) {
|
|
37
|
+
throw new TypeError(`clearSiteData(): "${type}" is not a type: write one of ${quoted(TYPES)}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const value = quoted(types);
|
|
41
|
+
const given = options.methods ?? ["POST"];
|
|
42
|
+
if (given.length === 0 || given.some((method) => method === "")) {
|
|
43
|
+
throw new TypeError('clearSiteData(): methods is empty or holds an empty method: write at least one, such as ["POST"], or leave methods out');
|
|
44
|
+
}
|
|
45
|
+
const methods = new Set(given.map((method) => method.toUpperCase()));
|
|
46
|
+
const crossSite = options.crossSite === true;
|
|
47
|
+
return defineMiddleware(async function clearSiteData(ctx, next) {
|
|
48
|
+
const response = await settle(ctx, next());
|
|
49
|
+
if (!methods.has(ctx.request.method))
|
|
50
|
+
return response;
|
|
51
|
+
if (response.status < 200 || response.status >= 400)
|
|
52
|
+
return response;
|
|
53
|
+
if (!crossSite && isCrossSite(ctx.request, options.origin))
|
|
54
|
+
return response;
|
|
55
|
+
return withHeaders(response, (headers) => {
|
|
56
|
+
if (!headers.has("clear-site-data"))
|
|
57
|
+
headers.set("clear-site-data", value);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
markFactory(clearSiteData);
|
|
62
|
+
// src/csp.ts
|
|
63
|
+
var KEYWORDS = new Set([
|
|
64
|
+
"self",
|
|
65
|
+
"none",
|
|
66
|
+
"unsafe-inline",
|
|
67
|
+
"unsafe-eval",
|
|
68
|
+
"unsafe-hashes",
|
|
69
|
+
"strict-dynamic",
|
|
70
|
+
"wasm-unsafe-eval",
|
|
71
|
+
"report-sample",
|
|
72
|
+
"inline-speculation-rules"
|
|
73
|
+
]);
|
|
74
|
+
function isUnquotedKeyword(source) {
|
|
75
|
+
const lower = source.toLowerCase();
|
|
76
|
+
return KEYWORDS.has(lower) || /^(nonce|sha256|sha384|sha512)-[a-z0-9+/_-]+=*$/.test(lower);
|
|
77
|
+
}
|
|
78
|
+
function csp(directives) {
|
|
79
|
+
const written = [];
|
|
80
|
+
for (const [name, value] of Object.entries(directives)) {
|
|
81
|
+
if (!/^[a-z][a-z0-9-]*$/.test(name)) {
|
|
82
|
+
throw new TypeError(`csp(): "${name}" is not a directive name: write lowercase letters, digits and hyphens, starting with a letter, as in "script-src"`);
|
|
83
|
+
}
|
|
84
|
+
if (value === undefined || value === false)
|
|
85
|
+
continue;
|
|
86
|
+
if (value === true) {
|
|
87
|
+
written.push(name);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (value.length === 0) {
|
|
91
|
+
throw new TypeError(`csp(): ${name} has no source: write ["'none'"] to allow nothing, or false to leave it out`);
|
|
92
|
+
}
|
|
93
|
+
for (const source of value) {
|
|
94
|
+
if (/[;,\s]/.test(source) || source === "") {
|
|
95
|
+
throw new TypeError(`csp(): ${name} has the source "${source}", which is empty or holds ";", "," or a space: a source is one token, so split a list into several sources, and write a comma inside a URL as %2C`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
for (const source of value) {
|
|
99
|
+
if (isUnquotedKeyword(source)) {
|
|
100
|
+
throw new TypeError(`csp(): ${source} in ${name} is a keyword: write it quoted, '${source}'`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
written.push(`${name} ${value.join(" ")}`);
|
|
104
|
+
}
|
|
105
|
+
if (written.length === 0) {
|
|
106
|
+
throw new TypeError(`csp(): no directive is left: give at least one, such as { "default-src": ["'none'"] }`);
|
|
107
|
+
}
|
|
108
|
+
return written.join("; ");
|
|
109
|
+
}
|
|
110
|
+
// src/nonce.ts
|
|
111
|
+
var NONCE = "'nonce-{alxia}'";
|
|
112
|
+
var SCRIPT_DIRECTIVES = new Set(["script-src", "script-src-elem"]);
|
|
113
|
+
function policyWithNonce(policy) {
|
|
114
|
+
const placed = policy.includes(NONCE) ? policy : policy.split(";").map((directive) => {
|
|
115
|
+
const name = directive.trim().split(/\s+/)[0]?.toLowerCase() ?? "";
|
|
116
|
+
return SCRIPT_DIRECTIVES.has(name) ? `${directive.trimEnd()} ${NONCE}` : directive;
|
|
117
|
+
}).join(";");
|
|
118
|
+
if (!placed.includes(NONCE)) {
|
|
119
|
+
throw new TypeError(`secureHeaders: nonce is on, but the content-security-policy has no script-src to add it to: write one, or place NONCE where the nonce goes (the policy is "${policy}")`);
|
|
120
|
+
}
|
|
121
|
+
const parts = placed.split(NONCE);
|
|
122
|
+
return (nonce) => parts.join(`'nonce-${nonce}'`);
|
|
123
|
+
}
|
|
124
|
+
function freshNonce() {
|
|
125
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
126
|
+
return btoa(String.fromCharCode(...bytes));
|
|
127
|
+
}
|
|
128
|
+
// src/page.ts
|
|
129
|
+
import { markFactory as markFactory3 } from "@softistx/alxia";
|
|
130
|
+
|
|
131
|
+
// src/secure-headers.ts
|
|
132
|
+
import {
|
|
133
|
+
defineMiddleware as defineMiddleware2,
|
|
134
|
+
markFactory as markFactory2,
|
|
135
|
+
settle as settle2,
|
|
136
|
+
withHeaders as withHeaders2
|
|
137
|
+
} from "@softistx/alxia";
|
|
138
|
+
var DEFAULTS = {
|
|
139
|
+
"content-security-policy": "default-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
|
|
140
|
+
"strict-transport-security": "max-age=31536000; includeSubDomains",
|
|
141
|
+
"x-content-type-options": "nosniff",
|
|
142
|
+
"x-frame-options": "DENY",
|
|
143
|
+
"referrer-policy": "no-referrer",
|
|
144
|
+
"cross-origin-opener-policy": "same-origin",
|
|
145
|
+
"cross-origin-resource-policy": "same-origin",
|
|
146
|
+
"cross-origin-embedder-policy": false,
|
|
147
|
+
"origin-agent-cluster": "?1",
|
|
148
|
+
"x-dns-prefetch-control": "off",
|
|
149
|
+
"x-permitted-cross-domain-policies": "none",
|
|
150
|
+
"permissions-policy": false,
|
|
151
|
+
"cache-control": false
|
|
152
|
+
};
|
|
153
|
+
var OPTION = {
|
|
154
|
+
"content-security-policy": "contentSecurityPolicy",
|
|
155
|
+
"strict-transport-security": "strictTransportSecurity",
|
|
156
|
+
"x-content-type-options": "xContentTypeOptions",
|
|
157
|
+
"x-frame-options": "xFrameOptions",
|
|
158
|
+
"referrer-policy": "referrerPolicy",
|
|
159
|
+
"cross-origin-opener-policy": "crossOriginOpenerPolicy",
|
|
160
|
+
"cross-origin-resource-policy": "crossOriginResourcePolicy",
|
|
161
|
+
"cross-origin-embedder-policy": "crossOriginEmbedderPolicy",
|
|
162
|
+
"origin-agent-cluster": "originAgentCluster",
|
|
163
|
+
"x-dns-prefetch-control": "xDnsPrefetchControl",
|
|
164
|
+
"x-permitted-cross-domain-policies": "xPermittedCrossDomainPolicies",
|
|
165
|
+
"permissions-policy": "permissionsPolicy",
|
|
166
|
+
"cache-control": "cacheControl"
|
|
167
|
+
};
|
|
168
|
+
function secureHeaders(options = {}) {
|
|
169
|
+
const headers = fixedHeaders(options);
|
|
170
|
+
const hide = options.hidePoweredBy ?? true;
|
|
171
|
+
const policy = headers.get("content-security-policy");
|
|
172
|
+
if (!options.nonce) {
|
|
173
|
+
if (policy?.includes(NONCE)) {
|
|
174
|
+
throw new TypeError("secureHeaders: contentSecurityPolicy names NONCE, but nonce is off: give nonce: true");
|
|
175
|
+
}
|
|
176
|
+
const set = setter(headers, hide);
|
|
177
|
+
return defineMiddleware2(async function secureHeaders(ctx, next) {
|
|
178
|
+
return set(await settle2(ctx, next()));
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
if (policy === undefined) {
|
|
182
|
+
throw new TypeError("secureHeaders: nonce is on, but contentSecurityPolicy is false: a nonce is only read through the content-security-policy header");
|
|
183
|
+
}
|
|
184
|
+
headers.delete("content-security-policy");
|
|
185
|
+
const withNonce = policyWithNonce(policy);
|
|
186
|
+
const set = setter(headers, hide);
|
|
187
|
+
return defineMiddleware2(async function secureHeaders(ctx, next) {
|
|
188
|
+
const added = { nonce: freshNonce() };
|
|
189
|
+
const response = await settle2(ctx, next(added));
|
|
190
|
+
return set(response, withNonce(added.nonce));
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
function fixedHeaders(options) {
|
|
194
|
+
const headers = new Map;
|
|
195
|
+
for (const [name, fallback] of Object.entries(DEFAULTS)) {
|
|
196
|
+
const setting = options[OPTION[name]];
|
|
197
|
+
if (typeof setting === "string" && setting.trim() === "") {
|
|
198
|
+
throw new TypeError(`secureHeaders: ${OPTION[name]} is empty; give false to leave the ${name} header out`);
|
|
199
|
+
}
|
|
200
|
+
const value = setting === undefined ? fallback : setting;
|
|
201
|
+
if (typeof value === "string")
|
|
202
|
+
headers.set(name, value);
|
|
203
|
+
}
|
|
204
|
+
return headers;
|
|
205
|
+
}
|
|
206
|
+
function setter(headers, hide) {
|
|
207
|
+
return (response, policy) => withHeaders2(response, (current) => {
|
|
208
|
+
for (const [name, value] of headers) {
|
|
209
|
+
if (!current.has(name))
|
|
210
|
+
current.set(name, value);
|
|
211
|
+
}
|
|
212
|
+
if (policy !== undefined && !current.has("content-security-policy")) {
|
|
213
|
+
current.set("content-security-policy", policy);
|
|
214
|
+
}
|
|
215
|
+
if (hide) {
|
|
216
|
+
current.delete("x-powered-by");
|
|
217
|
+
current.delete("server");
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
markFactory2(secureHeaders);
|
|
222
|
+
|
|
223
|
+
// src/page.ts
|
|
224
|
+
var PAGE_POLICY = {
|
|
225
|
+
"default-src": ["'self'"],
|
|
226
|
+
"script-src": ["'self'", NONCE, "'strict-dynamic'"],
|
|
227
|
+
"style-src-elem": ["'self'", NONCE],
|
|
228
|
+
"style-src-attr": ["'unsafe-inline'"],
|
|
229
|
+
"img-src": ["'self'"],
|
|
230
|
+
"font-src": ["'self'"],
|
|
231
|
+
"connect-src": ["'self'"],
|
|
232
|
+
"worker-src": ["'self'"],
|
|
233
|
+
"manifest-src": ["'self'"],
|
|
234
|
+
"object-src": ["'none'"],
|
|
235
|
+
"base-uri": ["'none'"],
|
|
236
|
+
"form-action": ["'self'"],
|
|
237
|
+
"frame-ancestors": ["'none'"]
|
|
238
|
+
};
|
|
239
|
+
var PAGE_DIRECTIVES = Object.freeze(Object.fromEntries(Object.entries(PAGE_POLICY).map(([name, sources]) => [
|
|
240
|
+
name,
|
|
241
|
+
Object.freeze(sources)
|
|
242
|
+
])));
|
|
243
|
+
var REQUIRED = {
|
|
244
|
+
"default-src": "it covers frame, media and child sources",
|
|
245
|
+
"base-uri": "it has no fallback, so an injected <base> would redirect nonced relative scripts",
|
|
246
|
+
"object-src": "it blocks plugin content"
|
|
247
|
+
};
|
|
248
|
+
function pageHeaders(options) {
|
|
249
|
+
const { https, directives: asGiven = {}, ...given } = options;
|
|
250
|
+
const defined = (entries) => Object.fromEntries(Object.entries(entries).filter(([, value]) => value !== undefined));
|
|
251
|
+
const rest = defined(given);
|
|
252
|
+
const directives = defined(asGiven);
|
|
253
|
+
for (const [name, why] of Object.entries(REQUIRED)) {
|
|
254
|
+
const value = directives[name];
|
|
255
|
+
if (value === false || value === true) {
|
|
256
|
+
throw new TypeError(`pageHeaders(): ${name} cannot be removed from a page policy: ${why}, so give it a list of sources`);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const merged = {
|
|
260
|
+
...PAGE_DIRECTIVES,
|
|
261
|
+
...directives,
|
|
262
|
+
"upgrade-insecure-requests": directives["upgrade-insecure-requests"] ?? https
|
|
263
|
+
};
|
|
264
|
+
const scripts = merged["script-src"];
|
|
265
|
+
if (!Array.isArray(scripts) || !scripts.includes(NONCE)) {
|
|
266
|
+
throw new TypeError(`pageHeaders(): script-src has no NONCE: a page script runs only with the response's nonce, so write script-src with NONCE in directives, such as ["'self'", NONCE, "'strict-dynamic'"]`);
|
|
267
|
+
}
|
|
268
|
+
const elements = merged["script-src-elem"];
|
|
269
|
+
if (Array.isArray(elements) && !elements.includes(NONCE)) {
|
|
270
|
+
throw new TypeError("pageHeaders(): script-src-elem has no NONCE: script elements follow it instead of script-src, so add NONCE to it, or give false to remove it");
|
|
271
|
+
}
|
|
272
|
+
return secureHeaders({
|
|
273
|
+
...https ? {} : { strictTransportSecurity: false },
|
|
274
|
+
referrerPolicy: "strict-origin-when-cross-origin",
|
|
275
|
+
cacheControl: "private, no-store",
|
|
276
|
+
...rest,
|
|
277
|
+
nonce: true,
|
|
278
|
+
contentSecurityPolicy: csp(merged)
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
markFactory3(pageHeaders);
|
|
282
|
+
export {
|
|
283
|
+
NONCE,
|
|
284
|
+
PAGE_DIRECTIVES,
|
|
285
|
+
clearSiteData,
|
|
286
|
+
csp,
|
|
287
|
+
pageHeaders,
|
|
288
|
+
secureHeaders
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
//# debugId=BC4B199738C0725A64756E2164756E21
|
|
292
|
+
//# sourceMappingURL=index.js.map
|