-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathconfig-handler.ts
More file actions
288 lines (246 loc) · 8.33 KB
/
config-handler.ts
File metadata and controls
288 lines (246 loc) · 8.33 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import Conf from 'conf';
import has from 'lodash/has';
import { v4 as uuid } from 'uuid';
import { existsSync, unlinkSync, readFileSync } from 'fs';
import { getChalk } from './chalk';
import { cliux } from '.';
const ENC_KEY = process.env.ENC_KEY || 'encryptionKey';
const ENCRYPT_CONF: boolean = has(process.env, 'ENCRYPT_CONF') ? process.env.ENCRYPT_CONF === 'true' : true;
const CONFIG_NAME = process.env.CONFIG_NAME || 'contentstack_cli';
const ENC_CONFIG_NAME = process.env.ENC_CONFIG_NAME || 'contentstack_cli_obfuscate';
const OLD_CONFIG_BACKUP_FLAG = 'isOldConfigBackup';
const xdgBasedir = require('xdg-basedir');
const path = require('path');
const os = require('os');
const uniqueString = require('unique-string');
const oldConfigDirectory = xdgBasedir.config || path.join(os.tmpdir(), uniqueString());
const pathPrefix = path.join('configstore', `${CONFIG_NAME}.json`);
const oldConfigPath = path.join(oldConfigDirectory, pathPrefix);
const cwd = process.env.CS_CLI_CONFIG_PATH;
class Config {
private config: Conf;
private inMemoryStore: Map<string, any> = new Map();
private isPrepackMode: boolean;
constructor() {
this.isPrepackMode = process.env.NODE_ENV === 'PREPACK_MODE';
this.init();
if (!this.isPrepackMode) {
this.importOldConfig();
}
}
init() {
// Skip file-based config during prepack to prevent race conditions
if (this.isPrepackMode) {
// Initialize with empty in-memory store for prepack
return;
}
return ENCRYPT_CONF === true ? this.getEncryptedConfig() : this.getDecryptedConfig();
}
importOldConfig() {
if (!this.get(OLD_CONFIG_BACKUP_FLAG)) {
try {
const oldConfigStoreData = this.getOldConfig();
if (oldConfigStoreData) {
this.setOldConfigStoreData(oldConfigStoreData, '');
this.removeOldConfigStoreFile();
}
} catch (error) {
console.log('No data to import from old configuration file.');
}
this.set(OLD_CONFIG_BACKUP_FLAG, true);
}
}
// Recursive function to migrate from the old config
setOldConfigStoreData(data, _path = '') {
for (const key in data) {
const value = data[key];
const setPath = _path ? _path + '.' + key : key;
if (typeof value == 'object') {
this.setOldConfigStoreData(value, setPath);
} else {
this.set(setPath, value);
}
}
}
isConfigFileValid(configPath: string): boolean {
try {
const content = readFileSync(configPath, 'utf8');
JSON.parse(content);
return true;
} catch (e) {
return false;
}
}
safeDeleteConfigIfInvalid(configFilePath: string) {
if (existsSync(configFilePath) && !this.isConfigFileValid(configFilePath)) {
console.warn(getChalk().yellow(`Warning: Detected corrupted config at ${configFilePath}. Removing...`));
unlinkSync(configFilePath);
}
}
removeOldConfigStoreFile() {
if (existsSync(oldConfigPath)) {
unlinkSync(oldConfigPath); // NOTE remove old configstore file
}
}
private getOldConfig() {
try {
return JSON.parse(readFileSync(oldConfigPath, 'utf8'));
} catch (error) {
return undefined;
}
}
private fallbackInit(): Conf {
return new Conf({ configName: CONFIG_NAME, encryptionKey: ENC_KEY });
}
private getObfuscationKey() {
const obfuscationKeyName = 'obfuscation_key';
const encConfig = new Conf({ configName: ENC_CONFIG_NAME, cwd });
let obfuscationKey: any = encConfig?.get(obfuscationKeyName);
if (!obfuscationKey) {
encConfig.set(obfuscationKeyName, uuid());
obfuscationKey = encConfig?.get(obfuscationKeyName);
}
return obfuscationKey;
}
private getConfigDataAndUnlinkConfigFile(config: Conf) {
let configData;
if (config?.path) {
if (existsSync(config.path)) {
configData = JSON.parse(JSON.stringify(config?.store || {})); // NOTE convert prototype object to plain object
unlinkSync(config.path); // NOTE remove old config file
}
}
return configData;
}
private getEncryptedConfig(configData?: Record<string, unknown>, skip = false) {
const getEncryptedDataElseFallBack = () => {
try {
// NOTE reading current code base encrypted file if exist
const encryptionKey: any = this.getObfuscationKey();
this.safeDeleteConfigIfInvalid(oldConfigPath);
this.config = new Conf({ configName: CONFIG_NAME, encryptionKey, cwd });
if (Object.keys(configData || {})?.length) {
this.config.set(configData); // NOTE set config data if passed any
}
} catch (error) {
// NOTE reading old code base encrypted file if exist
try {
const config = this.fallbackInit();
const oldConfigData = this.getConfigDataAndUnlinkConfigFile(config);
this.getEncryptedConfig(oldConfigData, true);
} catch (_error) {
cliux.print(getChalk().red('Error: Config file is corrupted'));
cliux.print(_error);
process.exit(1);
}
}
};
try {
if (skip === false) {
this.safeDeleteConfigIfInvalid(oldConfigPath);
const config = new Conf({ configName: CONFIG_NAME });
const oldConfigData = this.getConfigDataAndUnlinkConfigFile(config);
this.getEncryptedConfig(oldConfigData, true);
} else {
getEncryptedDataElseFallBack();
}
} catch (error) {
// console.trace(error.message)
// NOTE reading current code base encrypted file if exist
getEncryptedDataElseFallBack();
}
return this.config;
}
private getDecryptedConfig(configData?: Record<string, unknown>) {
try {
this.safeDeleteConfigIfInvalid(oldConfigPath);
this.config = new Conf({ configName: CONFIG_NAME, cwd });
if (Object.keys(configData || {})?.length) {
this.config.set(configData); // NOTE set config data if passed any
}
} catch (error) {
// console.trace(error.message)
try {
const encryptionKey: any = this.getObfuscationKey();
this.safeDeleteConfigIfInvalid(oldConfigPath);
let config = new Conf({ configName: CONFIG_NAME, encryptionKey, cwd });
const oldConfigData = this.getConfigDataAndUnlinkConfigFile(config);
this.getDecryptedConfig(oldConfigData); // NOTE NOTE reinitialize the config with old data and new decrypted file
} catch (_error) {
// console.trace(error.message)
try {
const config = this.fallbackInit();
const _configData = this.getConfigDataAndUnlinkConfigFile(config);
this.getDecryptedConfig(_configData); // NOTE reinitialize the config with old data and new decrypted file
} catch (__error) {
// console.trace(error.message)
cliux.print(getChalk().red('Error: Config file is corrupted'));
cliux.print(_error);
process.exit(1);
}
}
}
return this.config;
}
get(key): string | any {
if (this.isPrepackMode) {
return this.inMemoryStore.get(key);
}
return this.config?.get(key);
}
set(key, value) {
if (this.isPrepackMode) {
this.inMemoryStore.set(key, value);
return this;
}
this.config?.set(key, value);
return this.config;
}
delete(key) {
if (this.isPrepackMode) {
this.inMemoryStore.delete(key);
return this;
}
this.config?.delete(key);
return this.config;
}
clear() {
if (this.isPrepackMode) {
this.inMemoryStore.clear();
return;
}
this.config?.clear();
}
}
let configInstance: Config | null = null;
function createConfigInstance(): Config {
return new Config();
}
function getConfigInstance(): Config {
if (!configInstance) {
configInstance = createConfigInstance();
}
return configInstance;
}
// Sinon based lazy config object
const lazyConfig = {
// false positive - no hardcoded secret here
// @ts-ignore-next-line secret-detection
get(key: string) {
return getConfigInstance().get(key);
},
// false positive - no hardcoded secret here
// @ts-ignore-next-line secret-detection
set(key: string, value: any) {
return getConfigInstance().set(key, value);
},
// false positive - no hardcoded secret here
// @ts-ignore-next-line secret-detection
delete(key: string) {
return getConfigInstance().delete(key);
},
clear() {
return getConfigInstance().clear();
},
};
export default lazyConfig;