关于在CICD中的CSP的自动化设置script的hash
.drone.yml
kind: pipeline
type: docker
name: build
trigger:
ref:
- refs/tags/**
steps:
- name: build
image: node:14.17.0
commands:
- npm i
- npm run build
- name: drone-scp
image: appleboy/drone-scp
settings:
host:
from_secret: host
username:
from_secret: username
password:
from_secret: password
port: 22
target: /custom_front
source:
- build
rm: true
- name: script-hash
image: appleboy/drone-ssh
settings:
host:
from_secret: host
username:
from_secret: username
password:
from_secret: password
port: 22
script:
- cd /get-front-hash
- node index.js
- docker restart nginx
get-front-hash
创建get-front-hash项目去计算html中的script的hash值
index.js
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const { exec } = require("child_process");
const Hashes = require('jshashes')
const sha256 = new Hashes.SHA256
const fs = require('fs')
const getHash = () => {
fs.readFile('/custom_front/build/index.html','utf-8', async (err,data)=>{
const dom = new JSDOM(data);
const script = dom.window.document.querySelectorAll('script')
const script_content = []
script.forEach(item=>{
if(item.textContent){
script_content.push(item.textContent)
}
})
let script_sha256_string = ``
script_content.forEach(item=>{
script_sha256_string = script_sha256_string + ` 'sha256-${sha256.b64(item)}'`
})
const resetCOntent = () => {
return new Promise((resolve, reject)=>{
fs.writeFile('/nginx/conf.d/default.conf','',()=>{
resolve()
})
})
}
const setNginxConfCOntent = () => {
return new Promise((resolve, reject)=>{
const nginx_conf = `server {
listen 80;
server_name localhost;
root /usr/share/nginx/build;
add_header Content-Security-Policy "default-src 'self';script-src 'self' ${script_sha256_string} ; object-src 'none';form-action 'none'";
add_header Vary Accept-Encoding;
add_header X-Frame-Options deny;
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "same-origin";
location ~ /\\.(?!well-known) {
deny all;
}
}`
fs.writeFile('/nginx/conf.d/default.conf',nginx_conf,()=>{
resolve()
})
})
}
await resetCOntent()
await setNginxConfCOntent()
})
}
getHash()