-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcf_headers.js
71 lines (62 loc) · 2.12 KB
/
cf_headers.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import fs from 'fs'
import path from 'path'
import { parse } from 'node-html-parser'
const __dirname = path.resolve()
const buildDir = path.join(__dirname, '.svelte-kit', 'cloudflare')
let previous_content = ''
function removeCspMeta(inputFile) {
const fileContents = fs.readFileSync(inputFile, { encoding: 'utf-8' })
const root = parse(fileContents)
const element = root.querySelector('head meta[http-equiv="content-security-policy"]')
if (element == null) {
return previous_content
}
const content = element.getAttribute('content')
root.remove(element)
previous_content = content
return content
}
const cspMap = new Map()
function findCspMeta(startPath, filter = /\.html$/) {
if (!fs.existsSync(startPath)) {
console.error(`Unable to find CSP start path: ${startPath}`)
return
}
const files = fs.readdirSync(startPath)
files.forEach((item) => {
const filename = path.join(startPath, item)
const stat = fs.lstatSync(filename)
if (stat.isDirectory()) {
findCspMeta(filename, filter)
} else if (filter.test(filename)) {
cspMap.set(
filename
.replace(buildDir, '')
.replace(/\.html$/, '')
.replace(/^\/index$/, '/'),
removeCspMeta(filename),
)
}
})
}
function createHeaders() {
const headers = `/*
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: accelerometer=(), camera=(), document-domain=(), encrypted-media=(), gyroscope=(), interest-cohort=(), magnetometer=(), microphone=(), midi=(), payment=(), picture-in-picture=(), publickey-credentials-get=(), sync-xhr=(), usb=(), xr-spatial-tracking=(), geolocation=()
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
`
const cspArray = []
cspMap.forEach((csp, pagePath) =>
cspArray.push(`${pagePath}\n Content-Security-Policy: ${csp}`),
)
const headersFile = path.join(buildDir, '_headers')
fs.writeFileSync(headersFile, `${headers}${cspArray.join('\n')}`)
}
async function main() {
findCspMeta(buildDir)
createHeaders()
}
main()