UNPKG

1.82 kBPlain TextView Raw
1import * as path from 'path'
2import { _assert, _stringMapEntries, StringMap } from '@naturalcycles/js-lib'
3import * as fs from 'fs-extra'
4import globby = require('globby')
5import { dimGrey, yellow } from '../colors'
6import { encryptRandomIVBuffer, encryptString } 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 = globby.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: StringMap = JSON.parse(fs.readFileSync(filename, 'utf8'))
45
46 _stringMapEntries(json).forEach(([k, plain]) => {
47 json[k] = encryptString(plain, encKey)
48 })
49
50 fs.writeFileSync(encFilename, JSON.stringify(json, null, 2))
51 } else {
52 const plain = fs.readFileSync(filename)
53 const enc = encryptRandomIVBuffer(plain, encKey)
54 encFilename = `${filename}.enc`
55 fs.writeFileSync(encFilename, enc)
56 }
57
58 if (del) {
59 fs.unlinkSync(filename)
60 }
61
62 console.log(` ${path.basename(filename)} > ${path.basename(encFilename)}`)
63 })
64
65 console.log(`encrypted ${yellow(filenames.length)} files in (${dimGrey(pattern.join(' '))})`)
66}