UNPKG

1.69 kBPlain TextView Raw
1import * as path from 'path'
2import { _assert } from '@naturalcycles/js-lib'
3import * as fs from 'fs-extra'
4import { dimGrey, yellow } from '../colors'
5import { fastGlob } from '../index'
6import { encryptObject, encryptRandomIVBuffer } from '../security/crypto.util'
7
8export interface EncryptCLIOptions {
9 pattern: string[]
10 file?: string
11 encKey: string
12 del?: boolean
13 jsonMode?: boolean
14}
15
16/**
17 * Encrypts all files in given directory (except *.enc), saves encrypted versions as filename.ext.enc.
18 * Using provided encKey.
19 */
20export function secretsEncrypt(
21 pattern: string[],
22 file: string | undefined,
23 encKey: string,
24 del = false,
25 jsonMode = false,
26): void {
27 const patterns = file
28 ? [file]
29 : [
30 ...pattern,
31 `!**/*.enc`, // excluding already encoded
32 ]
33 const filenames = fastGlob.sync(patterns)
34 let encFilename
35
36 filenames.forEach(filename => {
37 if (jsonMode) {
38 _assert(
39 filename.endsWith('.plain.json'),
40 `${path.basename(filename)} MUST end with '.plain.json'`,
41 )
42 encFilename = filename.replace('.plain', '')
43
44 const json = encryptObject(JSON.parse(fs.readFileSync(filename, 'utf8')), encKey)
45
46 fs.writeFileSync(encFilename, JSON.stringify(json, null, 2))
47 } else {
48 const plain = fs.readFileSync(filename)
49 const enc = encryptRandomIVBuffer(plain, encKey)
50 encFilename = `${filename}.enc`
51 fs.writeFileSync(encFilename, enc)
52 }
53
54 if (del) {
55 fs.unlinkSync(filename)
56 }
57
58 console.log(` ${path.basename(filename)} > ${path.basename(encFilename)}`)
59 })
60
61 console.log(`encrypted ${yellow(filenames.length)} files in (${dimGrey(pattern.join(' '))})`)
62}