fix(dialogkeywords.ts): injected security context inside DialogKeywords

This commit is contained in:
Alan 2023-01-25 10:49:00 -03:00
parent dea972f233
commit 81953d7d9f
5 changed files with 55 additions and 44 deletions

View file

@ -507,17 +507,17 @@ export class AzureDeployerService implements IGBInstallationDeployer {
*/ */
public async internalDeployBot ( public async internalDeployBot (
instance, instance,
accessToken, accessToken: string,
botId, botId: string,
name, name: string,
group, group,
description, description: string ,
endpoint, endpoint,
location, location,
nlpAppId, nlpAppId,
nlpKey, nlpKey: string,
appId, appId: string,
appPassword, appPassword: string,
subscriptionId subscriptionId
): Promise<IGBInstance> { ): Promise<IGBInstance> {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {

View file

@ -422,7 +422,11 @@ export class DialogKeywords {
* @example TALK TOLIST (array,member) * @example TALK TOLIST (array,member)
* *
*/ */
public getToLst(array, member) { public async getToLst(pid,array, member) {
const {
min, user
} = await DialogKeywords.getProcessInfo(pid);
if (!array) { if (!array) {
return '<Empty>'; return '<Empty>';
} }
@ -447,7 +451,11 @@ export class DialogKeywords {
* @example hour = HOUR (date) * @example hour = HOUR (date)
* *
*/ */
public getHourFromDate(pid, date) { public async getHourFromDate(pid, date) {
const {
min, user
} = await DialogKeywords.getProcessInfo(pid);
function addZero(i) { function addZero(i) {
if (i < 10) { if (i < 10) {
i = '0' + i; i = '0' + i;
@ -456,7 +464,7 @@ export class DialogKeywords {
} }
const contentLocale = this.min.core.getParam<string>( const contentLocale = this.min.core.getParam<string>(
this.min.instance, min.instance,
'Default Content Language', 'Default Content Language',
GBConfigService.get('DEFAULT_CONTENT_LANGUAGE') GBConfigService.get('DEFAULT_CONTENT_LANGUAGE')
); );
@ -577,7 +585,7 @@ export class DialogKeywords {
*/ */
public async setIdGeneration({ mode }) { public async setIdGeneration({ mode }) {
this['idGeneration'] = mode; this['idGeneration'] = mode;
this['id'] = await this.sys().getRandomId(); this['id'] = this.sys().getRandomId();
} }
/** /**
@ -793,14 +801,14 @@ export class DialogKeywords {
setTimeout(resolve, ms); setTimeout(resolve, ms);
}); });
}; };
this.min.cbMap[userId] = {}; min.cbMap[userId] = {};
this.min.cbMap[userId]['promise'] = '!GBHEAR'; min.cbMap[userId]['promise'] = '!GBHEAR';
while (this.min.cbMap[userId].promise === '!GBHEAR') { while (min.cbMap[userId].promise === '!GBHEAR') {
await sleep(500); await sleep(500);
} }
const text = this.min.cbMap[userId].promise; const text = min.cbMap[userId].promise;
if (kind === 'file') { if (kind === 'file') {
// TODO: https://github.com/GeneralBots/BotServer/issues/227 // TODO: https://github.com/GeneralBots/BotServer/issues/227
@ -887,7 +895,7 @@ export class DialogKeywords {
result = value; result = value;
} else if (kind === 'hour') { } else if (kind === 'hour') {
const extractEntity = text => { const extractEntity = (text: string) => {
return text.match(/^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/gi); return text.match(/^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/gi);
}; };
@ -900,7 +908,7 @@ export class DialogKeywords {
result = value; result = value;
} else if (kind === 'money') { } else if (kind === 'money') {
const extractEntity = text => { const extractEntity = (text: string) => {
// https://github.com/GeneralBots/BotServer/issues/307 // https://github.com/GeneralBots/BotServer/issues/307
if (user.locale === 'en') { if (user.locale === 'en') {
return text.match(/(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/gi); return text.match(/(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/gi);
@ -937,7 +945,7 @@ export class DialogKeywords {
result = phoneNumber; result = phoneNumber;
} else if (kind === 'zipcode') { } else if (kind === 'zipcode') {
const extractEntity = text => { const extractEntity = (text: string) => {
text = text.replace(/\-/gi, ''); text = text.replace(/\-/gi, '');
if (user.locale === 'en') { if (user.locale === 'en') {
@ -1077,37 +1085,40 @@ export class DialogKeywords {
private async internalSendFile({ pid, mobile, filename, caption }) { private async internalSendFile({ pid, mobile, filename, caption }) {
// Handles SEND FILE TO mobile,element in Web Automation. // Handles SEND FILE TO mobile,element in Web Automation.
const {
min, user
} = await DialogKeywords.getProcessInfo(pid);
const element = filename._page ? filename._page : filename.screenshot ? filename : null; const element = filename._page ? filename._page : filename.screenshot ? filename : null;
if (element) { if (element) {
const gbaiName = `${this.min.botId}.gbai`; const gbaiName = `${min.botId}.gbai`;
const localName = Path.join('work', gbaiName, 'cache', `img${GBAdminService.getRndReadableIdentifier()}.jpg`); const localName = Path.join('work', gbaiName, 'cache', `img${GBAdminService.getRndReadableIdentifier()}.jpg`);
await element.screenshot({ path: localName, fullPage: true }); await element.screenshot({ path: localName, fullPage: true });
const url = urlJoin(GBServer.globals.publicAddress, this.min.botId, 'cache', Path.basename(localName)); const url = urlJoin(GBServer.globals.publicAddress, min.botId, 'cache', Path.basename(localName));
GBLog.info(`BASIC: WebAutomation: Sending the file ${url} to mobile ${mobile}.`); GBLog.info(`BASIC: WebAutomation: Sending the file ${url} to mobile ${mobile}.`);
await this.min.conversationalService.sendFile(this.min, null, mobile, url, caption); await min.conversationalService.sendFile(min, null, mobile, url, caption);
} }
// Handles Markdown. // Handles Markdown.
else if (filename.indexOf('.md') > -1) { else if (filename.indexOf('.md') > -1) {
GBLog.info(`BASIC: Sending the contents of ${filename} markdown to mobile ${mobile}.`); GBLog.info(`BASIC: Sending the contents of ${filename} markdown to mobile ${mobile}.`);
const md = await this.min.kbService.getAnswerTextByMediaName(this.min.instance.instanceId, filename); const md = await min.kbService.getAnswerTextByMediaName(min.instance.instanceId, filename);
if (!md) { if (!md) {
GBLog.info(`BASIC: Markdown file ${filename} not found on database for ${this.min.instance.botId}.`); GBLog.info(`BASIC: Markdown file ${filename} not found on database for ${min.instance.botId}.`);
} }
await this.min.conversationalService['playMarkdown'](this.min, md, DialogKeywords.getChannel(), mobile); await min.conversationalService['playMarkdown'](min, md, DialogKeywords.getChannel(), mobile);
} else { } else {
GBLog.info(`BASIC: Sending the file ${filename} to mobile ${mobile}.`); GBLog.info(`BASIC: Sending the file ${filename} to mobile ${mobile}.`);
let url; let url: string;
if (!filename.startsWith('https://')) { if (!filename.startsWith('https://')) {
url = urlJoin( url = urlJoin(
GBServer.globals.publicAddress, GBServer.globals.publicAddress,
'kb', 'kb',
`${this.min.botId}.gbai`, `${min.botId}.gbai`,
`${this.min.botId}.gbkb`, `${min.botId}.gbkb`,
'assets', 'assets',
filename filename
); );
@ -1115,7 +1126,7 @@ export class DialogKeywords {
url = filename; url = filename;
} }
await this.min.conversationalService.sendFile(this.min, null, mobile, url, caption); await min.conversationalService.sendFile(min, null, mobile, url, caption);
} }
} }

View file

@ -481,7 +481,7 @@ export class SystemKeywords {
}); });
if (!documents || documents.length === 0) { if (!documents || documents.length === 0) {
throw `File '${file}' specified on GBasic command not found. Check the .gbdata or the .gb'dialog' associated.`; throw `File '${file}' specified on GBasic command not found. Check the .gbdata or the .gbdialog associated.`;
} }
return documents[0]; return documents[0];

View file

@ -75,8 +75,8 @@ export class WhatsappDirectLine extends GBService {
private locale: string = 'pt-BR'; private locale: string = 'pt-BR';
provider: any; provider: any;
INSTANCE_URL = 'https://api.maytapi.com/api'; INSTANCE_URL = 'https://api.maytapi.com/api';
private customClient; private customClient: any;
private browserWSEndpoint; private browserWSEndpoint: any;
private groupId; private groupId;
constructor( constructor(
@ -111,20 +111,20 @@ export class WhatsappDirectLine extends GBService {
} }
} }
public async setup(setUrl) { public async setup(setUrl: boolean) {
this.directLineClient = new Swagger({ this.directLineClient = new Swagger({
spec: JSON.parse(Fs.readFileSync('directline-3.0.json', 'utf8')), spec: JSON.parse(Fs.readFileSync('directline-3.0.json', 'utf8')),
usePromise: true usePromise: true
}); });
const client = await this.directLineClient; const client = await this.directLineClient;
let url; let url: string;
let body; let body: any;
client.clientAuthorizations.add( client.clientAuthorizations.add(
'AuthorizationBotConnector', 'AuthorizationBotConnector',
new Swagger.ApiKeyAuthorization('Authorization', `Bearer ${this.directLineSecret}`, 'header') new Swagger.ApiKeyAuthorization('Authorization', `Bearer ${this.directLineSecret}`, 'header')
); );
let options; let options: any;
switch (this.provider) { switch (this.provider) {
case 'GeneralBots': case 'GeneralBots':
@ -166,7 +166,7 @@ export class WhatsappDirectLine extends GBService {
client.on( client.on(
'message', 'message',
(async message => { (async (message: string) => {
await this.WhatsAppCallback(message, null); await this.WhatsAppCallback(message, null);
}).bind(this) }).bind(this)
); );
@ -227,7 +227,7 @@ export class WhatsappDirectLine extends GBService {
const chats = await client.getChats(); const chats = await client.getChats();
await CollectionUtil.asyncForEach(chats, async chat => { await CollectionUtil.asyncForEach(chats, async chat => {
const sleep = ms => { const sleep = (ms: number) => {
return new Promise(resolve => { return new Promise(resolve => {
setTimeout(resolve, ms); setTimeout(resolve, ms);
}); });
@ -303,7 +303,7 @@ export class WhatsappDirectLine extends GBService {
} }
} }
public async resetConversationId(botId, number, group = '') { public async resetConversationId(botId: string, number: number, group = '') {
WhatsappDirectLine.conversationIds[botId + number + group] = undefined; WhatsappDirectLine.conversationIds[botId + number + group] = undefined;
} }
@ -326,14 +326,14 @@ export class WhatsappDirectLine extends GBService {
} }
} }
public static providerFromRequest(req) { public static providerFromRequest(req: any) {
return req.body.messages ? 'chatapi' : req.body.message ? 'maytapi' : 'GeneralBots'; return req.body.messages ? 'chatapi' : req.body.message ? 'maytapi' : 'GeneralBots';
} }
public async received(req, res) { public async received(req, res) {
const provider = WhatsappDirectLine.providerFromRequest(req); const provider = WhatsappDirectLine.providerFromRequest(req);
let message, from, fromName, text; let message, from, fromName, text: string;
let group = ''; let group = '';
let answerText = null; let answerText = null;
let attachments = null; let attachments = null;

View file

@ -1,8 +1,8 @@
export const Messages = { export const Messages = {
'en-US': { 'en-US': {
notify_end_transfer: botName => `Now talking to ${botName} again.` notify_end_transfer: (botName: any) => `Now talking to ${botName} again.`
}, },
'pt-BR': { 'pt-BR': {
notify_end_transfer: botName => `Falando com o bot ${botName} novamente.` notify_end_transfer: (botName: any) => `Falando com o bot ${botName} novamente.`
} }
}; };