/
pluginDecrypt.js
75 lines (68 loc) · 2.36 KB
/
pluginDecrypt.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
72
73
74
75
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const zlib = require('zlib');
const ENCRYPTED_PLUGIN_SALT = 'ENCRYPTED_PLUGIN_SALT';
const { NETLIFY_ENCRYPT_KEY } = process.env;
module.exports = function pluginDecrypt({
// unzip to '.testdecrypt' folder instead of overwriting real files
testdecrypt = false
}) {
if (typeof NETLIFY_ENCRYPT_KEY === 'undefined') {
console.error(
'must define NETLIFY_ENCRYPT_KEY to use netlify-plugin-encrypted-files. For more info: https://github.com/sw-yx/netlify-plugin-encrypted-files#usage'
);
process.exit(1);
}
const files = fs.readdirSync('.encrypted');
files.forEach((sourceFilePath) => {
let destinationfilePath = Buffer.from(sourceFilePath, 'base64').toString();
decrypt(
path.join('.encrypted', sourceFilePath),
destinationfilePath,
testdecrypt
);
});
};
// core crypto stuff
// https://medium.com/@brandonstilson/lets-encrypt-files-with-node-85037bea8c0e
function decrypt(sourceFilePath, destinationfilePath, testdecrypt) {
// First, get the initialization vector from the file.
const readInitVect = fs.createReadStream(sourceFilePath, { end: 15 });
let initVect;
readInitVect.on('data', (chunk) => {
initVect = chunk;
});
// Once we’ve got the initialization vector, we can decrypt the file.
readInitVect.on('close', () => {
const cipherKey = getCipherKey(ENCRYPTED_PLUGIN_SALT + NETLIFY_ENCRYPT_KEY);
const readStream = fs.createReadStream(sourceFilePath, { start: 16 });
const decipher = crypto.createDecipheriv('aes256', cipherKey, initVect);
const unzip = zlib.createUnzip();
const destination = testdecrypt
? path.join('.testdecrypt', destinationfilePath)
: destinationfilePath;
ensureDirectoryExistence(destination);
const writeStream = fs.createWriteStream(destination);
readStream
.pipe(decipher)
.pipe(unzip)
.pipe(writeStream);
});
}
// util utils
function getCipherKey(password) {
return crypto
.createHash('sha256')
.update(password)
.digest();
}
// https://stackoverflow.com/questions/13542667/create-directory-when-writing-to-file-in-node-js
function ensureDirectoryExistence(filePath) {
var dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}