This repository has been archived by the owner on Mar 22, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
csp.ts
54 lines (45 loc) · 1.49 KB
/
csp.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import {
InterfaceAlagarrOptions,
InterfaceRequest,
InterfaceResponseData,
} from '../../types'
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/default-src
const DEFAULT_POLICIES = {
'default-src': "'self' https: 'unsafe-inline'",
'img-src': '* data: blob:',
}
// Apply CSP headers
export default function cspHeaders(
response: InterfaceResponseData,
_: InterfaceRequest,
options: InterfaceAlagarrOptions,
): InterfaceResponseData {
const { headers = {}, ...rest } = response
const cspPolicies = {
...DEFAULT_POLICIES,
...options.cspPolicies,
} as any
const cspPolicy = Object.keys(cspPolicies)
.map((policy: string): string => `${policy} ${cspPolicies[policy]}`)
.join(';') as any
return {
...rest,
headers: {
...headers,
// Only transmit the origin cross-domain and no referer without HTTPS:
'referrer-policy': 'strict-origin-when-cross-origin',
// Instruct browsers to strictly follow the Content-Type header:
'x-content-type-options': 'nosniff',
// Always enable the browser XSS protection:
'x-xss-protection': '1; mode=block',
// Convert the csp options in package.json to a policies list:
'content-security-policy': cspPolicy,
// Map "frame-ancestors" to the equivalent "X-Frame-Options":
'x-frame-options':
({
"'none'": 'DENY',
"'self'": 'SAMEORIGIN',
} as any)[cspPolicies['frame-ancestors']] || undefined,
},
}
}