-
Notifications
You must be signed in to change notification settings - Fork 4
/
csp-util.mjs
80 lines (66 loc) · 2.15 KB
/
csp-util.mjs
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
72
73
74
75
76
77
78
79
80
#!/usr/bin/env node
import fs from 'fs'
import path from 'path'
import * as htmlparser2 from 'htmlparser2'
import { replaceInFileSync } from 'replace-in-file'
const TARGET_FOLDER = path.join(process.cwd(), 'public')
const INPUT_FILE = path.join(TARGET_FOLDER, 'index.html')
const OUTPUT_FILE = path.join(TARGET_FOLDER, '_headers')
const TOKEN_TO_REPLACE = '__REPLACE_ME__'
console.log('Copying the CSP for Netlify headers')
const cspContent = getCspContentFrom(INPUT_FILE)
updateNetlifyHeaderFile(cspContent, OUTPUT_FILE)
function getCspContentFrom(inputFile) {
console.log(`Getting the CSP content from ${inputFile}`)
try {
const fileContents = fs.readFileSync(inputFile, { encoding: 'utf-8' })
let found = false
let retVal = ''
const parser = new htmlparser2.Parser({
onopentag: (name, attributes) => {
if (name === 'meta') {
if (
attributes['http-equiv'] &&
'Content-Security-Policy' === attributes['http-equiv']
) {
console.log('Found the CSP content:', attributes['content'])
found = true
retVal = attributes['content']
}
}
},
})
parser.write(fileContents)
if (found === false) {
throw new Error(`Could not find the CSP`)
}
return retVal
} catch (err) {
console.error(
'Could not retrieve the CSP content. Did you build first? Is the gatsby-config.js still correct?'
)
throw err
}
}
function updateNetlifyHeaderFile(cspText, outputFile) {
console.log(`Updating the CSP in the output file [${outputFile}]`)
const replacementOptions = {
files: outputFile,
from: new RegExp(TOKEN_TO_REPLACE, 'g'),
to: cspText,
}
try {
console.log(`Modifying Netlify's header file`)
const changes = replaceInFileSync(replacementOptions)
if (changes && changes.length && changes.length > 0) {
console.log(`Modified Netlify's headers file successfully`)
} else {
throw new Error(
`Failed to find the expected token to replace: ${TOKEN_TO_REPLACE}`
)
}
} catch (error) {
console.error(`Failed to modify Netlify's header file`)
throw error
}
}