UNPKG

1.17 kBPlain TextView Raw
1import * as fs from 'fs-extra'
2import globby = require('globby')
3import * as path from 'path'
4import { dimGrey, yellow } from '../colors'
5import { encryptRandomIVBuffer } from '../security/crypto.util'
6
7export interface EncryptCLIOptions {
8 pattern: string[]
9 encKey: string
10 algorithm?: string
11 del?: boolean
12}
13
14/**
15 * Encrypts all files in given directory (except *.enc), saves encrypted versions as filename.ext.enc.
16 * Using provided encKey.
17 */
18export function secretsEncrypt(
19 pattern: string[],
20 encKey: string,
21 algorithm?: string,
22 del?: boolean,
23): void {
24 const patterns = [
25 ...pattern,
26 `!**/*.enc`, // excluding already encoded
27 ]
28 const filenames = globby.sync(patterns)
29
30 filenames.forEach(filename => {
31 const plain = fs.readFileSync(filename)
32 const enc = encryptRandomIVBuffer(plain, encKey, algorithm)
33
34 const encFilename = `${filename}.enc`
35 fs.writeFileSync(encFilename, enc)
36
37 if (del) {
38 fs.unlinkSync(filename)
39 }
40
41 console.log(` ${path.basename(filename)} > ${path.basename(encFilename)}`)
42 })
43
44 console.log(`encrypted ${yellow(filenames.length)} files in (${dimGrey(pattern.join(' '))})`)
45}