-
Notifications
You must be signed in to change notification settings - Fork 274
/
botConfiguration.ts
488 lines (422 loc) · 19.6 KB
/
botConfiguration.ts
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/**
* Copyright(c) Microsoft Corporation.All rights reserved.
* Licensed under the MIT License.
*/
import * as fsx from 'fs-extra';
import * as path from 'path';
import * as process from 'process';
import * as txtfile from 'read-text-file';
import * as util from 'util';
import * as uuid from 'uuid';
import { BotConfigurationBase } from './botConfigurationBase';
import { BotRecipe, IBlobResource, ICosmosDBResource, IDispatchResource, IFileResource, IGenericResource, IResource, IUrlResource } from './botRecipe';
import * as encrypt from './encrypt';
import { ExportOptions } from './exportOptions';
import { ConnectedService } from './models';
import { IBlobStorageService, IBotConfiguration, IConnectedService, ICosmosDBService, IDispatchService, IEndpointService, IFileService, IGenericService, ILuisService, IQnAService, ServiceTypes } from './schema';
let exec = util.promisify(require('child_process').exec);
interface InternalBotConfig {
location?: string;
}
// This class adds loading and saving from disk and encryption/decryption semantics on top of BotConfigurationBase
export class BotConfiguration extends BotConfigurationBase {
private internal: InternalBotConfig = {};
public static fromJSON(source: Partial<IBotConfiguration> = {}): BotConfiguration {
// tslint:disable-next-line:prefer-const
let { name = '', description = '', version = '2.0', secretKey = '', services = [] } = source;
services = <IConnectedService[]>services.slice().map(BotConfigurationBase.serviceFromJSON);
const botConfig: BotConfiguration = new BotConfiguration();
Object.assign(botConfig, { services, description, name, version, secretKey });
return botConfig;
}
// load first bot in a folder
public static async loadBotFromFolder(folder?: string, secret?: string): Promise<BotConfiguration> {
folder = folder || process.cwd();
let files: string[] = await fsx.readdir(folder);
files = files.sort();
for (const file of files) {
if (path.extname(<string>file) === '.bot') {
return await BotConfiguration.load(`${folder}/${<string>file}`, secret);
}
}
throw new Error(`Error: no bot file found in ${folder}. Choose a different location or use msbot init to create a .bot file."`);
}
// load first bot in a folder (blocking)
public static loadBotFromFolderSync(folder?: string, secret?: string): BotConfiguration {
folder = folder || process.cwd();
let files: string[] = fsx.readdirSync(folder);
files = files.sort();
for (const file of files) {
if (path.extname(<string>file) === '.bot') {
return BotConfiguration.loadSync(`${folder}/${<string>file}`, secret);
}
}
throw new Error(`Error: no bot file found in ${folder}. Choose a different location or use msbot init to create a .bot file."`);
}
// load the config from a file
public static async load(botpath: string, secret?: string): Promise<BotConfiguration> {
const json: string = await txtfile.read(botpath);
const bot: BotConfiguration = BotConfiguration.internalLoad(json, secret);
bot.internal.location = botpath;
return bot;
}
// load the config from a file (blocking)
public static loadSync(botpath: string, secret?: string): BotConfiguration {
const json: string = txtfile.readSync(botpath);
const bot: BotConfiguration = BotConfiguration.internalLoad(json, secret);
bot.internal.location = botpath;
return bot;
}
// save the config file to specificed botpath
public async saveAs(botpath: string, secret?: string): Promise<void> {
if (!botpath) {
throw new Error(`missing path`);
}
this.internal.location = botpath;
this.savePrep(secret);
const hasSecret: boolean = !!this.secretKey;
if (hasSecret) {
this.encrypt(secret);
}
await fsx.writeJson(botpath, this.toJSON(), { spaces: 4 });
if (hasSecret) {
this.decrypt(secret);
}
}
// save the config file to specificed botpath
public saveAsSync(botpath: string, secret?: string): void {
if (!botpath) {
throw new Error(`missing path`);
}
this.internal.location = botpath;
this.savePrep(secret);
const hasSecret: boolean = !!this.secretKey;
if (hasSecret) {
this.encrypt(secret);
}
fsx.writeJsonSync(botpath, this.toJSON(), { spaces: 4 });
if (hasSecret) {
this.decrypt(secret);
}
}
// save the config file back over original
public async save(secret?: string): Promise<void> {
return this.saveAs(this.internal.location, secret);
}
// save the config file back over original (blocking)
public saveSync(secret?: string): void {
return this.saveAsSync(this.internal.location, secret);
}
private savePrep(secret?: string): void {
if (!!secret) {
this.validateSecretKey(secret);
}
// make sure that all dispatch serviceIds still match services that are in the bot
for (const service of this.services) {
if (service.type === ServiceTypes.Dispatch) {
const dispatchService: IDispatchService = <IDispatchService>service;
const validServices: string[] = [];
for (const dispatchServiceId of dispatchService.serviceIds) {
for (const this_service of this.services) {
if (this_service.id === dispatchServiceId) {
validServices.push(dispatchServiceId);
}
}
}
dispatchService.serviceIds = validServices;
}
}
}
private static internalLoad(json: string, secret?: string): BotConfiguration {
const bot: BotConfiguration = BotConfiguration.fromJSON(JSON.parse(json));
const hasSecret: boolean = !!bot.secretKey;
if (hasSecret) {
bot.decrypt(secret);
}
return bot;
}
// Generate a key for encryption
public static generateKey(): string {
return encrypt.generateKey();
}
public clearSecret(): void {
this.secretKey = '';
}
// encrypt all values in the config
public encrypt(secret: string): void {
this.validateSecretKey(secret);
for (const service of this.services) {
(<ConnectedService>service).encrypt(secret, encrypt.encryptString);
}
}
// decrypt all values in the config
public decrypt(secret?: string): void {
try {
this.validateSecretKey(secret);
for (const connected_service of this.services) {
(<ConnectedService>connected_service).decrypt(secret, encrypt.decryptString);
}
} catch (err) {
try {
// legacy decryption
this.secretKey = encrypt.legacyDecrypt(this.secretKey, secret);
this.clearSecret();
this.version = '2.0';
const encryptedProperties: { [key: string]: string[] } = {
abs: [],
endpoint: ['appPassword'],
luis: ['authoringKey', 'subscriptionKey'],
dispatch: ['authoringKey', 'subscriptionKey'],
file: [],
qna: ['subscriptionKey']
};
for (const service of this.services) {
for (const prop of encryptedProperties[service.type]) {
const val: string = <string>(<any>service)[prop];
(<any>service)[prop] = encrypt.legacyDecrypt(val, secret);
}
}
// assign new ids
// map old ids -> new Ids
const map: any = {};
const oldServices: IConnectedService[] = this.services;
this.services = [];
for (const oldService of oldServices) {
// connecting causes new ids to be created
const newServiceId: string = this.connectService(oldService);
map[oldService.id] = newServiceId;
}
// fix up dispatch serviceIds to new ids
for (const service of this.services) {
if (service.type === ServiceTypes.Dispatch) {
const dispatch: IDispatchService = (<IDispatchService>service);
for (let i: number = 0; i < dispatch.serviceIds.length; i++) {
dispatch.serviceIds[i] = map[dispatch.serviceIds[i]];
}
}
}
} catch (err2) {
throw err;
}
}
}
// return the path that this config was loaded from. .save() will save to this path
public getPath(): string {
return this.internal.location;
}
// make sure secret is correct by decrypting the secretKey with it
public validateSecretKey(secret: string): void {
if (!secret) {
throw new Error('You are attempting to perform an operation which needs access to the secret and --secret is missing');
}
try {
if (!this.secretKey || this.secretKey.length === 0) {
// if no key, create a guid and enrypt that to use as secret validator
this.secretKey = encrypt.encryptString(uuid(), secret);
} else {
// validate we can decrypt the secretKey, this tells us we have the correct secret for the rest of the file.
encrypt.decryptString(this.secretKey, secret);
}
} catch (ex) {
throw new Error('You are attempting to perform an operation which needs access to the secret and --secret is incorrect.');
}
}
// export the services from the bot file as resource files and recipe file
public async export(folder: string, exportOptions?: Partial<ExportOptions>): Promise<BotRecipe> {
let options = Object.assign({ download: true }, exportOptions);
let recipe = new BotRecipe();
await fsx.ensureDir(folder);
let index = 0;
for (let service of this.services) {
index++;
switch (service.type) {
case ServiceTypes.Dispatch:
{
let luisService = <ILuisService>service;
if (options.download) {
let command = `luis export version --appId ${luisService.appId} --authoringKey ${luisService.authoringKey} --versionId "${luisService.version}"`;
if (options.progress) {
options.progress(service, command, index, this.services.length);
}
let p = await exec(command);
var json = p.stdout;
// make sure it's json
JSON.parse(json);
await fsx.writeFile(folder + `/${luisService.id}.luis`, json, { encoding: 'utf8' });
}
else {
if (options.progress) {
options.progress(service, '', index, this.services.length);
}
}
let dispatchResource: IDispatchResource = {
type: service.type,
id: service.id,
name: service.name,
serviceIds: (<IDispatchService>service).serviceIds
};
recipe.resources.push(dispatchResource);
}
break;
case ServiceTypes.Luis:
{
let luisService = <ILuisService>service;
if (options.download) {
let command = `luis export version --appId ${luisService.appId} --authoringKey ${luisService.authoringKey} --versionId "${luisService.version}"`;
if (options.progress) {
options.progress(service, command, index, this.services.length);
}
let p = await exec(command);
var json = p.stdout;
// make sure it's json
JSON.parse(json);
await fsx.writeFile(folder + `/${luisService.id}.luis`, json, { encoding: 'utf8' });
}
else {
if (options.progress) {
options.progress(service, '', index, this.services.length);
}
}
let resource: IResource = {
type: service.type,
id: service.id,
name: service.name
};
recipe.resources.push(resource);
}
break;
case ServiceTypes.QnA:
{
let qnaService = <IQnAService>service;
if (options.download) {
let command = `qnamaker export kb --kbId ${qnaService.kbId} --environment prod --subscriptionKey ${qnaService.subscriptionKey} --hostname ${qnaService.hostname} --endpointKey ${qnaService.endpointKey}`;
if (options.progress) {
options.progress(service, command, index, this.services.length);
}
let p = await exec(command);
var json = p.stdout;
// make sure it's json
JSON.parse(json);
await fsx.writeFile(folder + `/${qnaService.id}.qna`, json, { encoding: 'utf8' });
}
else {
if (options.progress) {
options.progress(service, '', index, this.services.length);
}
}
let resource: IResource = {
type: service.type,
id: service.id,
name: service.name
};
recipe.resources.push(resource);
}
break;
case ServiceTypes.Endpoint:
{
if (options.progress) {
options.progress(service, '', index, this.services.length);
}
let endpointResource: IUrlResource = {
type: ServiceTypes.Endpoint,
id: service.id,
name: service.name,
url: (<IEndpointService>service).endpoint
};
recipe.resources.push(endpointResource);
}
break;
case ServiceTypes.BlobStorage:
{
if (options.progress) {
options.progress(service, '', index, this.services.length);
}
let blobResource: IBlobResource = {
type: ServiceTypes.BlobStorage,
id: service.id,
name: service.name,
container: (<IBlobStorageService>service).container
};
recipe.resources.push(blobResource);
}
break;
case ServiceTypes.CosmosDB:
{
if (options.progress) {
options.progress(service, '', index, this.services.length);
}
let cosmosDBResource: ICosmosDBResource = {
type: ServiceTypes.CosmosDB,
id: service.id,
name: service.name,
database: (<ICosmosDBService>service).database,
collection: (<ICosmosDBService>service).collection,
};
recipe.resources.push(cosmosDBResource);
}
break;
case ServiceTypes.File:
{
if (options.progress) {
options.progress(service, '', index, this.services.length);
}
let fileResource: IFileResource = {
type: ServiceTypes.File,
id: service.id,
name: service.name,
path: (<IFileService>service).path,
};
recipe.resources.push(fileResource);
}
break;
case ServiceTypes.Generic:
{
if (options.progress) {
options.progress(service, '', index, this.services.length);
}
console.warn(`WARNING: Generic services cannot be cloned and all configuration data will be passed unchanged and unencrypted `);
let genericService = <IGenericService>service;
let genericResource: IGenericResource = {
type: ServiceTypes.Generic,
id: service.id,
name: service.name,
url: genericService.url,
configuration: genericService.configuration,
};
recipe.resources.push(genericResource);
}
break;
case ServiceTypes.Bot:
{
if (options.progress) {
options.progress(service, '', index, this.services.length);
}
let resource: IResource = {
type: service.type,
id: service.id,
name: service.name
};
recipe.resources.push(resource);
}
break;
case ServiceTypes.AppInsights:
{
if (options.progress) {
options.progress(service, '', index, this.services.length);
}
let resource: IResource = {
type: service.type,
id: service.id,
name: service.name
};
recipe.resources.push(resource);
}
break;
default:
throw new Error(`Unknown service type for export ${service.type}`);
}
}
await fsx.writeFile(folder + `/bot.recipe`, JSON.stringify(recipe, null, 2), { encoding: 'utf8' });
return recipe;
}
}