1 | import * as path from 'path'
|
2 | import { _assert } from '@naturalcycles/js-lib'
|
3 | import * as fs from 'fs-extra'
|
4 | import { dimGrey, yellow } from '../colors'
|
5 | import { fastGlob } from '../index'
|
6 | import { encryptObject, encryptRandomIVBuffer } from '../security/crypto.util'
|
7 |
|
8 | export interface EncryptCLIOptions {
|
9 | pattern: string[]
|
10 | file?: string
|
11 | encKey: string
|
12 | del?: boolean
|
13 | jsonMode?: boolean
|
14 | }
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | export 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`,
|
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 | }
|