@microsoft/teamsfx 3.0.0-rc.0 → 3.0.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.esm2017.js +1734 -1
- package/dist/index.esm2017.js.map +1 -1
- package/dist/index.esm2017.mjs +3577 -16
- package/dist/index.esm2017.mjs.map +1 -1
- package/dist/index.esm5.js +1778 -15
- package/dist/index.esm5.js.map +1 -1
- package/dist/index.node.cjs.js +3735 -15
- package/dist/index.node.cjs.js.map +1 -1
- package/package.json +8 -8
- package/types/teamsfx.d.ts +2181 -0
package/dist/index.esm2017.mjs
CHANGED
@@ -1,17 +1,3578 @@
|
|
1
|
-
import{jwtDecode as e}from"jwt-decode";import{ConfidentialClientApplication as t}from"@azure/msal-node";import{createHash as n}from"crypto";import{ActivityTypes as i,Channels as o,TeamsInfo as a,CardFactory as r,ActionTypes as s,MessageFactory as c,StatusCodes as d,verifyStateOperationName as l,tokenExchangeOperationName as u,TurnContext as h,TeamsActivityHandler as p,MemoryStorage as v,UserState as m,ConversationState as f,ConfigurationServiceClientCredentialFactory as y,ConfigurationBotFrameworkAuthentication as g,CloudAdapter as w}from"botbuilder";import{Dialog as C,ComponentDialog as A,WaterfallDialog as S,DialogSet as I,DialogTurnStatus as T}from"botbuilder-dialogs";import{v4 as k}from"uuid";import E from"axios";import{Agent as x}from"https";import*as R from"adaptivecards-templating";import*as b from"path";import*as O from"fs";var P,F;!function(e){e.InvalidParameter="InvalidParameter",e.InvalidConfiguration="InvalidConfiguration",e.InvalidCertificate="InvalidCertificate",e.InternalError="InternalError",e.ChannelNotSupported="ChannelNotSupported",e.FailedToRetrieveSsoToken="FailedToRetrieveSsoToken",e.FailedToProcessSsoHandler="FailedToProcessSsoHandler",e.CannotFindCommand="CannotFindCommand",e.FailedToRunSsoStep="FailedToRunSsoStep",e.FailedToRunDedupStep="FailedToRunDedupStep",e.SsoActivityHandlerIsUndefined="SsoActivityHandlerIsUndefined",e.RuntimeNotSupported="RuntimeNotSupported",e.ConsentFailed="ConsentFailed",e.UiRequiredError="UiRequiredError",e.TokenExpiredError="TokenExpiredError",e.ServiceError="ServiceError",e.FailedOperation="FailedOperation",e.InvalidResponse="InvalidResponse",e.AuthorizationInfoAlreadyExists="AuthorizationInfoAlreadyExists"}(P||(P={}));class D{}D.InvalidConfiguration="{0} in configuration is invalid: {1}.",D.ConfigurationNotExists="Configuration does not exist. {0}",D.ResourceConfigurationNotExists="{0} resource configuration does not exist.",D.MissingResourceConfiguration="Missing resource configuration with type: {0}, name: {1}.",D.AuthenticationConfigurationNotExists="Authentication configuration does not exist.",D.BrowserRuntimeNotSupported="{0} is not supported in browser.",D.NodejsRuntimeNotSupported="{0} is not supported in Node.",D.FailToAcquireTokenOnBehalfOfUser="Failed to acquire access token on behalf of user: {0}",D.OnlyMSTeamsChannelSupported="{0} is only supported in MS Teams Channel",D.FailedToProcessSsoHandler="Failed to process sso handler: {0}",D.FailedToRetrieveSsoToken="Failed to retrieve sso token, user failed to finish the AAD consent flow.",D.CannotFindCommand="Cannot find command: {0}",D.FailedToRunSsoStep="Failed to run dialog to retrieve sso token: {0}",D.FailedToRunDedupStep="Failed to run dialog to remove duplicated messages: {0}",D.SsoActivityHandlerIsNull="Sso command can only be used or added when sso activity handler is not undefined",D.AuthorizationHeaderAlreadyExists="Authorization header already exists!",D.BasicCredentialAlreadyExists="Basic credential already exists!",D.EmptyParameter="Parameter {0} is empty",D.DuplicateHttpsOptionProperty="Axios HTTPS agent already defined value for property {0}",D.DuplicateApiKeyInHeader="The request already defined api key in request header with name {0}.",D.DuplicateApiKeyInQueryParam="The request already defined api key in query parameter with name {0}.",D.OnlySupportInQueryActivity="The handleMessageExtensionQueryWithToken only support in handleTeamsMessagingExtensionQuery with composeExtension/query type.",D.OnlySupportInLinkQueryActivity="The handleMessageExtensionLinkQueryWithSSO only support in handleTeamsAppBasedLinkQuery with composeExtension/queryLink type.";class M extends Error{constructor(e,t){if(!t)return super(e),this;super(e),Object.setPrototypeOf(this,M.prototype),this.name=`${new.target.name}.${t}`,this.code=t}}function N(e){B.level=e}function H(){return B.level}!function(e){e[e.Verbose=0]="Verbose",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(F||(F={}));const B=new class{constructor(e,t){this.level=void 0,this.defaultLogger={verbose:console.debug,info:console.info,warn:console.warn,error:console.error},this.name=e,this.level=t}error(e){this.log(F.Error,(e=>e.error),e)}warn(e){this.log(F.Warn,(e=>e.warn),e)}info(e){this.log(F.Info,(e=>e.info),e)}verbose(e){this.log(F.Verbose,(e=>e.verbose),e)}log(e,t,n){if(""===n.trim())return;const i=(new Date).toUTCString();let o;o=this.name?`[${i}] : @microsoft/teamsfx - ${this.name} : ${F[e]} - `:`[${i}] : @microsoft/teamsfx : ${F[e]} - `;const a=`${o}${n}`;void 0!==this.level&&this.level<=e&&(this.customLogger?t(this.customLogger)(a):this.customLogFunction?this.customLogFunction(e,a):t(this.defaultLogger)(a))}};function U(e){B.customLogger=e}function q(e){B.customLogFunction=e}function j(t){try{const n=e(t);if(!n||!n.exp)throw new M("Decoded token is null or exp claim does not exists.",P.InternalError);return n}catch(e){const t="Parse jwt token failed in node env with error: "+e.message;throw B.error(t),new M(t,P.InternalError)}}function L(e,...t){const n=t;return e.replace(/{(\d+)}/g,(function(e,t){return void 0!==n[t]?n[t]:e}))}function $(e){if("string"==typeof e||e instanceof String)return;if(Array.isArray(e)&&0===e.length)return;if(Array.isArray(e)&&e.length>0&&e.every((e=>"string"==typeof e)))return;const t="The type of scopes is not valid, it must be string or string array";throw B.error(t),new M(t,P.InvalidParameter)}function z(e){return("string"==typeof e?e.split(" "):e).filter((e=>null!==e&&""!==e))}function K(e){const i=(o=e.authorityHost,a=e.tenantId,o.replace(/\/+$/g,"")+"/"+a);var o,a;const r=function(e){if(!e)return;const t=/(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/.exec(e);if(!t){const e="The certificate content does not contain a PEM-encoded certificate.";throw B.error(e),new M(e,P.InvalidCertificate)}return{thumbprintSha256:n("sha256").update(Buffer.from(t[3],"base64")).digest("hex").toUpperCase(),privateKey:e}}(e.certificateContent),s={clientId:e.clientId,authority:i};return r?s.clientCertificate=r:s.clientSecret=e.clientSecret,new t({auth:s})}class G{constructor(e){B.info("Create M365 tenant credential");const t=this.loadAndValidateConfig(e);this.msalClient=K(t)}async getToken(e,t){let n;$(e);const i="string"==typeof e?e:e.join(" ");B.info("Get access token with scopes: "+i);try{const t=z(e),i=await this.msalClient.acquireTokenByClientCredential({scopes:t});i&&(n={token:i.accessToken,expiresOnTimestamp:i.expiresOn.getTime()})}catch(e){const t="Get M365 tenant credential failed with error: "+e.message;throw B.error(t),new M(t,P.ServiceError)}if(!n){const e="Get M365 tenant credential access token failed with empty access token";throw B.error(e),new M(e,P.InternalError)}return n}loadAndValidateConfig(e){if(B.verbose("Validate authentication configuration"),e.clientId&&(e.clientSecret||e.certificateContent)&&e.tenantId&&e.authorityHost)return e;const t=[];e.clientId||t.push("clientId"),e.clientSecret||e.certificateContent||t.push("clientSecret or certificateContent"),e.tenantId||t.push("tenantId"),e.authorityHost||t.push("authorityHost");const n=L(D.InvalidConfiguration,t.join(", "),"undefined");throw B.error(n),new M(n,P.InvalidConfiguration)}}class _{constructor(e,t){B.info("Get on behalf of user credential");const n=[];if(t.clientId||n.push("clientId"),t.authorityHost||n.push("authorityHost"),t.clientSecret||t.certificateContent||n.push("clientSecret or certificateContent"),t.tenantId||n.push("tenantId"),0!=n.length){const e=L(D.InvalidConfiguration,n.join(", "),"undefined");throw B.error(e),new M(e,P.InvalidConfiguration)}this.msalClient=K(t);const i=j(e);this.ssoToken={token:e,expiresOnTimestamp:i.exp}}async getToken(e,t){$(e);const n=z(e);let i;if(n.length){let e;B.info("Get access token with scopes: "+n.join(" "));try{e=await this.msalClient.acquireTokenOnBehalfOf({oboAssertion:this.ssoToken.token,scopes:n})}catch(e){throw this.generateAuthServerError(e)}if(!e){const e="Access token is null";throw B.error(e),new M(L(D.FailToAcquireTokenOnBehalfOfUser,e),P.InternalError)}i={token:e.accessToken,expiresOnTimestamp:e.expiresOn.getTime()}}else{if(B.info("Get SSO token."),Math.floor(Date.now()/1e3)>this.ssoToken.expiresOnTimestamp){const e="Sso token has already expired.";throw B.error(e),new M(e,P.TokenExpiredError)}i=this.ssoToken}return i}getUserInfo(){return B.info("Get basic user info from SSO token"),function(e){if(!e){const e="SSO token is undefined.";throw B.error(e),new M(e,P.InvalidParameter)}const t=j(e),n={displayName:t.name,objectId:t.oid,tenantId:t.tid,preferredUserName:""};return"2.0"===t.ver?n.preferredUserName=t.preferred_username:"1.0"===t.ver&&(n.preferredUserName=t.upn),n}(this.ssoToken.token)}generateAuthServerError(e){const t=e.errorMessage;if("InteractionRequiredAuthError"===e.name){const e="Failed to get access token from AAD server, interaction required: "+t;return B.warn(e),new M(e,P.UiRequiredError)}if(t&&t.indexOf("AADSTS50013")>=0){const e="Failed to get access token from AAD server, assertion is invalid because of various reasons: "+t;return B.error(e),new M(e,P.TokenExpiredError)}{const e=L(D.FailToAcquireTokenOnBehalfOfUser,t);return B.error(e),new M(e,P.ServiceError)}}}class Q{constructor(e){throw new M(L(D.NodejsRuntimeNotSupported,"TeamsUserCredential"),P.RuntimeNotSupported)}login(e,t){return Promise.reject(new M(L(D.NodejsRuntimeNotSupported,"TeamsUserCredential"),P.RuntimeNotSupported))}getToken(e,t){return Promise.reject(new M(L(D.NodejsRuntimeNotSupported,"TeamsUserCredential"),P.RuntimeNotSupported))}getUserInfo(e){return Promise.reject(new M(L(D.NodejsRuntimeNotSupported,"TeamsUserCredential"),P.RuntimeNotSupported))}}const V="invokeResponse";class W{constructor(e,t){this.id=e,this.failureDetail=t}}class J extends C{constructor(e,t,n,i){super(n),this.initiateLoginEndpoint=t,this.authConfig=e,this.settings=i,$(this.settings.scopes),function(e){if(e.clientId&&(e.clientSecret||e.certificateContent)&&e.tenantId&&e.authorityHost)return;const t=[];e.clientId||t.push("clientId"),e.clientSecret||e.certificateContent||t.push("clientSecret or certificateContent"),e.tenantId||t.push("tenantId"),e.authorityHost||t.push("authorityHost");const n=L(D.InvalidConfiguration,t.join(", "),"undefined");throw B.error(n),new M(n,P.InvalidConfiguration)}(this.authConfig),B.info("Create a new Teams Bot SSO Prompt")}async beginDialog(e){var t;B.info("Begin Teams Bot SSO Prompt"),this.ensureMsTeamsChannel(e);let n=9e5;if(this.settings.timeout){if("number"!=typeof this.settings.timeout){const e="type of timeout property in teamsBotSsoPromptSettings should be number.";throw B.error(e),new M(e,P.InvalidParameter)}if(this.settings.timeout<=0){const e="value of timeout property in teamsBotSsoPromptSettings should be positive.";throw B.error(e),new M(e,P.InvalidParameter)}n=this.settings.timeout}void 0===this.settings.endOnInvalidMessage&&(this.settings.endOnInvalidMessage=!0);const i=null===(t=e.activeDialog)||void 0===t?void 0:t.state;return i.state={},i.options={},i.expires=(new Date).getTime()+n,await this.sendOAuthCardAsync(e.context),C.EndOfTurn}async continueDialog(e){var t;B.info("Continue Teams Bot SSO Prompt"),this.ensureMsTeamsChannel(e);const n=null===(t=e.activeDialog)||void 0===t?void 0:t.state,o=e.context.activity.type===i.Message;if((o||this.isTeamsVerificationInvoke(e.context)||this.isTokenExchangeRequestInvoke(e.context))&&(new Date).getTime()>n.expires)return B.warn("End Teams Bot SSO Prompt due to timeout"),await e.endDialog(void 0);if(this.isTeamsVerificationInvoke(e.context)||this.isTokenExchangeRequestInvoke(e.context)){const t=await this.recognizeToken(e);if(t.succeeded)return await e.endDialog(t.value)}else if(o&&this.settings.endOnInvalidMessage)return B.warn("End Teams Bot SSO Prompt due to invalid message"),await e.endDialog(void 0);return C.EndOfTurn}ensureMsTeamsChannel(e){if(e.context.activity.channelId!=o.Msteams){const e=L(D.OnlyMSTeamsChannelSupported,"Teams Bot SSO Prompt");throw B.error(e),new M(e,P.ChannelNotSupported)}}async sendOAuthCardAsync(e){B.verbose("Send OAuth card to get SSO token");const t=await a.getMember(e,e.activity.from.id);B.verbose("Get Teams member account user principal name: "+(t.userPrincipalName?t.userPrincipalName:""));const n=t.userPrincipalName?t.userPrincipalName:"",i=this.getSignInResource(n),o=r.oauthCard("","Teams SSO Sign In","Sign In",i.signInLink,i.tokenExchangeResource);o.content.buttons[0].type=s.Signin;const d=c.attachment(o);await e.sendActivity(d)}getSignInResource(e){B.verbose("Get sign in authentication configuration");const t=`${this.initiateLoginEndpoint}?scope=${encodeURI(this.settings.scopes.join(" "))}&clientId=${this.authConfig.clientId}&tenantId=${this.authConfig.tenantId}&loginHint=${e}`;B.verbose("Sign in link: "+t);return{signInLink:t,tokenExchangeResource:{id:k()}}}async recognizeToken(e){const t=e.context;let n;if(this.isTokenExchangeRequestInvoke(t))if(B.verbose("Receive token exchange request"),t.activity.value&&this.isTokenExchangeRequest(t.activity.value)){const e=t.activity.value.token,i=new _(e,this.authConfig);let o;try{if(o=await i.getToken(this.settings.scopes),o){await t.sendActivity(this.getTokenExchangeInvokeResponse(d.OK,"",t.activity.value.id));const i=j(e).exp;n={ssoToken:e,ssoTokenExpiration:new Date(1e3*i).toISOString(),connectionName:"",token:o.token,expiration:o.expiresOnTimestamp.toString()}}}catch(e){const n="The bot is unable to exchange token. Ask for user consent.";B.info(n),await t.sendActivity(this.getTokenExchangeInvokeResponse(d.PRECONDITION_FAILED,n,t.activity.value.id))}}else{const e="The bot received an InvokeActivity that is missing a TokenExchangeInvokeRequest value. This is required to be sent with the InvokeActivity.";B.warn(e),await t.sendActivity(this.getTokenExchangeInvokeResponse(d.BAD_REQUEST,e))}else this.isTeamsVerificationInvoke(t)&&(B.verbose("Receive Teams state verification request"),await this.sendOAuthCardAsync(e.context),await t.sendActivity({type:V,value:{status:d.OK}}));return void 0!==n?{succeeded:!0,value:n}:{succeeded:!1}}getTokenExchangeInvokeResponse(e,t,n){return{type:V,value:{status:e,body:new W(n,t)}}}isTeamsVerificationInvoke(e){const t=e.activity;return t.type===i.Invoke&&t.name===l}isTokenExchangeRequestInvoke(e){const t=e.activity;return t.type===i.Invoke&&t.name===u}isTokenExchangeRequest(e){return e.hasOwnProperty("token")}}function Z(e,t){const n=E.create({baseURL:e});return n.interceptors.request.use((async function(e){return await t.AddAuthenticationInfo(e)})),n}class X{constructor(e){this.getToken=e}async AddAuthenticationInfo(e){const t=await this.getToken();if(e.headers||(e.headers={}),e.headers.Authorization)throw new M(D.AuthorizationHeaderAlreadyExists,P.AuthorizationInfoAlreadyExists);return e.headers.Authorization=`Bearer ${t}`,e}}class Y{constructor(e,t){if(!e)throw new M(L(D.EmptyParameter,"username"),P.InvalidParameter);if(!t)throw new M(L(D.EmptyParameter,"password"),P.InvalidParameter);this.userName=e,this.password=t}AddAuthenticationInfo(e){return e.headers&&e.headers.Authorization?Promise.reject(new M(D.AuthorizationHeaderAlreadyExists,P.AuthorizationInfoAlreadyExists)):e.auth?Promise.reject(new M(D.BasicCredentialAlreadyExists,P.AuthorizationInfoAlreadyExists)):(e.auth={username:this.userName,password:this.password},Promise.resolve(e))}}class ee{constructor(e,t,n){if(!e)throw new M(L(D.EmptyParameter,"keyName"),P.InvalidParameter);if(!t)throw new M(L(D.EmptyParameter,"keyVaule"),P.InvalidParameter);this.keyName=e,this.keyValue=t,this.keyLocation=n}AddAuthenticationInfo(e){switch(this.keyLocation){case te.Header:if(e.headers||(e.headers={}),e.headers[this.keyName])return Promise.reject(new M(L(D.DuplicateApiKeyInHeader,this.keyName),P.AuthorizationInfoAlreadyExists));e.headers[this.keyName]=this.keyValue;break;case te.QueryParams:e.params||(e.params={});let t=!1;if(e.url){t=new URL(e.url,e.baseURL).searchParams.has(this.keyName)}if(e.params[this.keyName]||t)return Promise.reject(new M(L(D.DuplicateApiKeyInQueryParam,this.keyName),P.AuthorizationInfoAlreadyExists));e.params[this.keyName]=this.keyValue}return Promise.resolve(e)}}var te,ne,ie,oe;!function(e){e[e.Header=0]="Header",e[e.QueryParams=1]="QueryParams"}(te||(te={}));class ae{constructor(e){if(!e||0===Object.keys(e).length)throw new M(L(D.EmptyParameter,"certOption"),P.InvalidParameter);this.certOption=e}AddAuthenticationInfo(e){if(e.httpsAgent){const t=new Set(Object.keys(e.httpsAgent.options));for(const e of Object.keys(this.certOption))if(t.has(e))return Promise.reject(new M(L(D.DuplicateHttpsOptionProperty,e),P.InvalidParameter));Object.assign(e.httpsAgent.options,this.certOption)}else e.httpsAgent=new x(this.certOption);return Promise.resolve(e)}}function re(e,t,n){if(0===e.length)throw new M(L(D.EmptyParameter,"cert"),P.InvalidParameter);if(0===t.length)throw new M(L(D.EmptyParameter,"key"),P.InvalidParameter);return{cert:e,key:t,passphrase:null==n?void 0:n.passphrase,ca:null==n?void 0:n.ca}}function se(e,t){if(0===e.length)throw new M(L(D.EmptyParameter,"pfx"),P.InvalidParameter);return{pfx:e,passphrase:null==t?void 0:t.passphrase}}!function(e){e.Channel="Channel",e.Group="Group",e.Person="Person"}(ne||(ne={})),function(e){e[e.ReplaceForInteractor=0]="ReplaceForInteractor",e[e.ReplaceForAll=1]="ReplaceForAll",e[e.NewForAll=2]="NewForAll"}(ie||(ie={})),function(e){e[e.BadRequest=400]="BadRequest",e[e.InternalServerError=500]="InternalServerError"}(oe||(oe={}));let ce="BotSsoExecutionDialog",de="TeamsFxSsoPrompt",le="CommandRouteDialog";class ue extends A{constructor(e,t,n,i,o){super(null!=o?o:ce),this.dedupStorageKeys=[],this.commandMapping=new Map,o&&(ce=o,de=o+de,le=o+le);const a=new J(n,i,de,t);this.addDialog(a),this.initialDialogId=le,this.dedupStorage=e,this.dedupStorageKeys=[];const r=new S(le,[this.commandRouteStep.bind(this)]);this.addDialog(r)}addCommand(e,t){const n=this.getCommandHash(t),i=new S(n,[this.ssoStep.bind(this),this.dedupStep.bind(this),async t=>{const n=t.result.tokenResponse,i=t.context,o=t.result.message;try{if(!n)throw new Error(D.FailedToRetrieveSsoToken);return await e(i,n,o),await t.endDialog()}catch(e){const n=L(D.FailedToProcessSsoHandler,e.message);return B.error(n),await t.endDialog(new M(n,P.FailedToProcessSsoHandler))}}]);this.commandMapping.set(n,t),this.addDialog(i)}getCommandHash(e){const t=(Array.isArray(e)?e:[e]).join();return t.replace(/[^a-zA-Z0-9]/g,"")+n("sha256").update(t).digest("hex").toLowerCase()}async run(e,t){const n=new I(t);n.add(this);const i=await n.createContext(e);this.ensureMsTeamsChannel(i);const o=await i.continueDialog();if(o&&o.status===T.empty)await i.beginDialog(this.id);else if(o&&o.status===T.complete&&o.result instanceof Error)throw o.result}getActivityText(e){let t=e.text;const n=h.removeRecipientMention(e);return n&&(t=n.toLowerCase().replace(/\n|\r\n/g,"").trim()),t}async commandRouteStep(e){const t=e.context,n=this.getActivityText(t.activity),i=this.getMatchesCommandId(n);if(i)return await e.beginDialog(i);const o=L(D.CannotFindCommand,t.activity.text);throw B.error(o),new M(o,P.CannotFindCommand)}async ssoStep(e){try{const t=e.context,n={text:this.getActivityText(t.activity)};return e.options.commandMessage=n,await e.beginDialog(de)}catch(t){const n=L(D.FailedToRunSsoStep,t.message);return B.error(n),await e.endDialog(new M(n,P.FailedToRunSsoStep))}}async dedupStep(e){const t=e.result;if(!t)return B.error(D.FailedToRetrieveSsoToken),await e.endDialog(new M(D.FailedToRetrieveSsoToken,P.FailedToRunSsoStep));try{return t&&await this.shouldDedup(e.context)?C.EndOfTurn:await e.next({tokenResponse:t,message:e.options.commandMessage})}catch(t){const n=L(D.FailedToRunDedupStep,t.message);return B.error(n),await e.endDialog(new M(n,P.FailedToRunDedupStep))}}async onEndDialog(e){const t=e.activity.conversation.id,n=this.dedupStorageKeys.filter((e=>e.indexOf(t)>0));await this.dedupStorage.delete(n),this.dedupStorageKeys=this.dedupStorageKeys.filter((e=>e.indexOf(t)<0))}async shouldDedup(e){const t={eTag:e.activity.value.id},n=this.getStorageKey(e),i={[n]:t};try{await this.dedupStorage.write(i),this.dedupStorageKeys.push(n)}catch(e){if(e instanceof Error&&e.message.indexOf("eTag conflict"))return!0;throw e}return!1}getStorageKey(e){if(!e||!e.activity||!e.activity.conversation)throw new Error("Invalid context, can not get storage key!");const t=e.activity,n=t.channelId,o=t.conversation.id;if(t.type!==i.Invoke||t.name!==u)throw new Error("TokenExchangeState can only be used with Invokes of signin/tokenExchange.");const a=t.value;if(!a||!a.id)throw new Error("Invalid signin/tokenExchange. Missing activity.value.id.");return`${n}/${o}/${a.id}`}matchPattern(e,t){if(t){if("string"==typeof e){return new RegExp(e,"i").test(t)}if(e instanceof RegExp){const n=t.match(e);return null!=n&&n}}return!1}isPatternMatched(e,t){const n=Array.isArray(e)?e:[e];for(const e of n){return!!this.matchPattern(e,t)}return!1}getMatchesCommandId(e){for(const t of this.commandMapping){const n=t[1];if(this.isPatternMatched(n,e))return t[0]}}ensureMsTeamsChannel(e){if(e.context.activity.channelId!=o.Msteams){const e=L(D.OnlyMSTeamsChannelSupported,"SSO execution dialog");throw B.error(e),new M(e,P.ChannelNotSupported)}}}class he{static attachAdaptiveCard(e,t){const n={$root:t};return{attachments:[r.adaptiveCard(new R.Template(e).expand(n))]}}static attachAdaptiveCardWithoutData(e){return{attachments:[r.adaptiveCard(e)]}}static attachHeroCard(e,t,n,i){return he.attachContent(r.heroCard(e,t,n,i))}static attachSigninCard(e,t,n){return he.attachContent(r.signinCard(e,t,n))}static attachO365ConnectorCard(e){return he.attachContent(r.o365ConnectorCard(e))}static AttachReceiptCard(e){return he.attachContent(r.receiptCard(e))}static attachThumbnailCard(e,t,n,i){return he.attachContent(r.thumbnailCard(e,t,n,i))}static attachContent(e){return{attachments:[e]}}}var pe,ve,me;!function(e){e.AdaptiveCard="application/vnd.microsoft.card.adaptive",e.Message="application/vnd.microsoft.activity.message",e.Error="application/vnd.microsoft.error"}(pe||(pe={}));class fe{static textMessage(e){if(!e)throw new Error("The text message cannot be null or empty");return{status:d.OK,body:{statusCode:d.OK,type:pe.Message,value:e}}}static adaptiveCard(e){if(!e)throw new Error("The adaptive card content cannot be null or undefined");return{status:d.OK,body:{statusCode:d.OK,type:pe.AdaptiveCard,value:e}}}static errorResponse(e,t){return{status:d.OK,body:{statusCode:e,type:pe.Error,value:{code:e.toString(),message:t}}}}static createInvokeResponse(e,t){return{status:e,body:t}}}async function ye(e,t,n,o,a){const r=e.activity.value;if(!r.authentication||!r.authentication.token)return B.verbose("No AccessToken in request, return silentAuth for AccessToken"),function(e,t,n){const i=z(n);return{composeExtension:{type:"silentAuth",suggestedActions:{actions:[{type:"openUrl",value:`${t}?scope=${encodeURI(i.join(" "))}&clientId=${e.clientId}&tenantId=${e.tenantId}`,title:"Message Extension OAuth"}]}}}}(t,n,o);try{const e=new _(r.authentication.token,t),n=await e.getToken(o),i=j(r.authentication.token).exp,s={ssoToken:r.authentication.token,ssoTokenExpiration:new Date(1e3*i).toISOString(),token:n.token,expiration:n.expiresOnTimestamp.toString(),connectionName:""};if(a)return await a(s)}catch(a){if(a instanceof M&&a.code===P.UiRequiredError&&"composeExtension/query"===e.activity.name){B.verbose("User not consent yet, return 412 to user consent first.");const t={status:412};return void await e.sendActivity({value:t,type:i.InvokeResponse})}if(a instanceof M&&a.code===P.UiRequiredError&&"composeExtension/queryLink"===e.activity.name){B.verbose("User not consent yet, return auth card for user login");const a=function(e,t,n){const i=z(n);return{composeExtension:{type:"auth",suggestedActions:{actions:[{type:"openUrl",value:`${t}?scope=${encodeURI(i.join(" "))}&clientId=${e.clientId}&tenantId=${e.tenantId}`,title:"Message Extension OAuth"}]}}}}(t,n,o);return void await e.sendActivity({value:{status:200,body:a},type:i.InvokeResponse})}throw a}}async function ge(e,t,n,i,o){if("composeExtension/query"!=e.activity.name)throw B.error(D.OnlySupportInQueryActivity),new M(L(D.OnlySupportInQueryActivity),P.FailedOperation);return await ye(e,null!=t?t:{},n,i,o)}async function we(e,t,n,i,o){if("composeExtension/queryLink"!=e.activity.name)throw B.error(D.OnlySupportInLinkQueryActivity),new M(L(D.OnlySupportInLinkQueryActivity),P.FailedOperation);return await ye(e,null!=t?t:{},n,i,o)}class Ce{constructor(e){this.actionHandlers=[],this.defaultMessage="Your response was sent to the app",e&&e.length>0&&this.actionHandlers.push(...e)}async onTurn(e,t){var n,i,o;if("adaptiveCard/action"===e.activity.name){const t=e.activity.value.action,a=t.verb;for(const s of this.actionHandlers)if((null===(n=s.triggerVerb)||void 0===n?void 0:n.toLowerCase())===(null==a?void 0:a.toLowerCase())){let n;try{n=await s.handleActionInvoked(e,t.data)}catch(t){const n=fe.errorResponse(oe.InternalServerError,t.message);throw await this.sendInvokeResponse(e,n),t}switch(null===(i=n.body)||void 0===i?void 0:i.type){case pe.AdaptiveCard:const t=null===(o=n.body)||void 0===o?void 0:o.value;if(!t){const t="Adaptive card content cannot be found in the response body";throw await this.sendInvokeResponse(e,fe.errorResponse(oe.InternalServerError,t)),new Error(t)}t.refresh&&s.adaptiveCardResponse!==ie.NewForAll&&(s.adaptiveCardResponse=ie.ReplaceForAll);const i=c.attachment(r.adaptiveCard(t));s.adaptiveCardResponse===ie.NewForAll?(await this.sendInvokeResponse(e,fe.textMessage(this.defaultMessage)),await e.sendActivity(i)):s.adaptiveCardResponse===ie.ReplaceForAll?(i.id=e.activity.replyToId,await e.updateActivity(i),await this.sendInvokeResponse(e,n)):await this.sendInvokeResponse(e,n);break;case pe.Message:case pe.Error:default:await this.sendInvokeResponse(e,n)}break}}await t()}async sendInvokeResponse(e,t){await e.sendActivity({type:i.InvokeResponse,value:t})}}class Ae{constructor(e,t){this.middleware=new Ce(null==t?void 0:t.actions),this.adapter=e.use(this.middleware)}registerHandler(e){e&&this.middleware.actionHandlers.push(e)}registerHandlers(e){e&&this.middleware.actionHandlers.push(...e)}}class Se{constructor(e,t,n){if(this.commandHandlers=[],this.ssoCommandHandlers=[],e=null!=e?e:[],t=null!=t?t:[],this.hasSsoCommand=t.length>0,this.ssoActivityHandler=n,this.hasSsoCommand&&!this.ssoActivityHandler)throw B.error(D.SsoActivityHandlerIsNull),new M(D.SsoActivityHandlerIsNull,P.SsoActivityHandlerIsUndefined);this.commandHandlers.push(...e);for(const e of t)this.addSsoCommand(e)}addSsoCommand(e){var t;null===(t=this.ssoActivityHandler)||void 0===t||t.addCommand((async(t,n,i)=>{const o=this.shouldTrigger(e.triggerPatterns,i.text);i.matches=Array.isArray(o)?o:void 0;const a=await e.handleCommandReceived(t,i,n);await this.processResponse(t,a)}),e.triggerPatterns),this.ssoCommandHandlers.push(e),this.hasSsoCommand=!0}async onTurn(e,t){var n,o;if(e.activity.type===i.Message){const t=this.getActivityText(e.activity);let i=!1;for(const n of this.commandHandlers){const o=this.shouldTrigger(n.triggerPatterns,t);if(o){const a={text:t};a.matches=Array.isArray(o)?o:void 0;const r=await n.handleCommandReceived(e,a);await this.processResponse(e,r),i=!0;break}}if(!i)for(const i of this.ssoCommandHandlers){if(this.shouldTrigger(i.triggerPatterns,t)){await(null===(n=this.ssoActivityHandler)||void 0===n?void 0:n.run(e));break}}}else this.hasSsoCommand&&await(null===(o=this.ssoActivityHandler)||void 0===o?void 0:o.run(e));await t()}async processResponse(e,t){if("string"==typeof t)await e.sendActivity(t);else{const n=t;n&&await e.sendActivity(n)}}matchPattern(e,t){if(t){if("string"==typeof e){return new RegExp(e,"i").test(t)}if(e instanceof RegExp){const n=t.match(e);return null!=n&&n}}return!1}shouldTrigger(e,t){const n=Array.isArray(e)?e:[e];for(const e of n){const n=this.matchPattern(e,t);if(n)return n}return!1}getActivityText(e){let t=e.text;const n=h.removeRecipientMention(e);return n&&(t=n.toLowerCase().replace(/\n|\r\n/g,"").trim()),t}}class Ie{constructor(e,t,n,i){this.ssoConfig=i,this.middleware=new Se(null==t?void 0:t.commands,null==t?void 0:t.ssoCommands,n),this.adapter=e.use(this.middleware)}registerCommand(e){e&&this.middleware.commandHandlers.push(e)}registerCommands(e){e&&this.middleware.commandHandlers.push(...e)}registerSsoCommand(e){this.validateSsoActivityHandler(),this.middleware.addSsoCommand(e)}registerSsoCommands(e){if(e.length>0){this.validateSsoActivityHandler();for(const t of e)this.middleware.addSsoCommand(t)}}validateSsoActivityHandler(){if(!this.middleware.ssoActivityHandler)throw B.error(D.SsoActivityHandlerIsNull),new M(D.SsoActivityHandlerIsNull,P.SsoActivityHandlerIsUndefined)}}function Te(e){return JSON.parse(JSON.stringify(e))}function ke(e){var t,n;return`_${null===(t=e.conversation)||void 0===t?void 0:t.tenantId}_${null===(n=e.conversation)||void 0===n?void 0:n.id}`}function Ee(e){var t,n,i;const o=null===(i=null===(n=null===(t=e.activity)||void 0===t?void 0:t.channelData)||void 0===n?void 0:n.team)||void 0===i?void 0:i.id;return o||(void 0===e.activity.conversation.name?e.activity.conversation.id:void 0)}!function(e){e[e.CurrentBotInstalled=0]="CurrentBotInstalled",e[e.CurrentBotMessaged=1]="CurrentBotMessaged",e[e.CurrentBotUninstalled=2]="CurrentBotUninstalled",e[e.TeamDeleted=3]="TeamDeleted",e[e.TeamRestored=4]="TeamRestored",e[e.Unknown=5]="Unknown"}(ve||(ve={}));class xe{constructor(e){this.conversationReferenceStore=e.conversationReferenceStore}async onTurn(e,t){switch(this.classifyActivity(e.activity)){case ve.CurrentBotInstalled:case ve.TeamRestored:{const t=h.getConversationReference(e.activity);await this.conversationReferenceStore.add(ke(t),t,{overwrite:!0});break}case ve.CurrentBotMessaged:await this.tryAddMessagedReference(e);break;case ve.CurrentBotUninstalled:case ve.TeamDeleted:{const t=h.getConversationReference(e.activity);await this.conversationReferenceStore.remove(ke(t),t);break}}await t()}classifyActivity(e){var t,n;const i=e.type;if("installationUpdate"===i){const n=null===(t=e.action)||void 0===t?void 0:t.toLowerCase();return"add"===n||"add-upgrade"===n?ve.CurrentBotInstalled:ve.CurrentBotUninstalled}if("conversationUpdate"===i){const t=null===(n=e.channelData)||void 0===n?void 0:n.eventType;if("teamDeleted"===t)return ve.TeamDeleted;if("teamRestored"===t)return ve.TeamRestored}else if("message"===i)return ve.CurrentBotMessaged;return ve.Unknown}async tryAddMessagedReference(e){var t,n,i,o,a,r;const s=h.getConversationReference(e.activity),c=null===(t=null==s?void 0:s.conversation)||void 0===t?void 0:t.conversationType;if("personal"===c||"groupChat"===c)await this.conversationReferenceStore.add(ke(s),s,{overwrite:!1});else if("channel"===c){const t=null===(o=null===(i=null===(n=e.activity)||void 0===n?void 0:n.channelData)||void 0===i?void 0:i.team)||void 0===o?void 0:o.id,c=null===(r=null===(a=e.activity.channelData)||void 0===a?void 0:a.channel)||void 0===r?void 0:r.id;if(void 0!==t&&(void 0===c||t===c)){const e=Te(s);e.conversation.id=t,await this.conversationReferenceStore.add(ke(e),e,{overwrite:!1})}}}}class Re{constructor(e){var t;this.localFileName=null!==(t=process.env.TEAMSFX_NOTIFICATION_STORE_FILENAME)&&void 0!==t?t:".notification.localstore.json",this.filePath=b.resolve(e,this.localFileName)}async add(e,t,n){if(n.overwrite||!await this.storeFileExists()){if(await this.storeFileExists()){const n=await this.readFromFile();await this.writeToFile(Object.assign(n,{[e]:t}))}else await this.writeToFile({[e]:t});return!0}return!1}async remove(e,t){if(!await this.storeFileExists())return!1;if(await this.storeFileExists()){const t=await this.readFromFile();void 0!==t[e]&&(delete t[e],await this.writeToFile(t))}return!0}async list(e,t){if(!await this.storeFileExists())return{data:[],continuationToken:""};const n=await this.readFromFile();return{data:Object.entries(n).map((e=>e[1])),continuationToken:""}}storeFileExists(){return new Promise((e=>{try{O.access(this.filePath,(t=>{e(!t)}))}catch(t){e(!1)}}))}readFromFile(){return new Promise(((e,t)=>{try{O.readFile(this.filePath,{encoding:"utf-8"},((n,i)=>{n?t(n):e(JSON.parse(i))}))}catch(e){t(e)}}))}async writeToFile(e){return new Promise(((t,n)=>{try{const i=JSON.stringify(e,void 0,2);O.writeFile(this.filePath,i,{encoding:"utf-8"},(e=>{e?n(e):t()}))}catch(e){n(e)}}))}}class be{constructor(e,t){this.type=ne.Channel,this.parent=e,this.info=t}async sendMessage(e,t){const n={};return await this.parent.adapter.continueConversationAsync(this.parent.botAppId,this.parent.conversationReference,(async i=>{const o=await this.newConversation(i);await this.parent.adapter.continueConversationAsync(this.parent.botAppId,o,(async i=>{try{const t=await i.sendActivity(e);n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(i,e)}}))})),n}async sendAdaptiveCard(e,t){const n={};return await this.parent.adapter.continueConversationAsync(this.parent.botAppId,this.parent.conversationReference,(async i=>{const o=await this.newConversation(i);await this.parent.adapter.continueConversationAsync(this.parent.botAppId,o,(async i=>{try{const t=await i.sendActivity({attachments:[r.adaptiveCard(e)]});n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(i,e)}}))})),n}newConversation(e){const t=Te(h.getConversationReference(e.activity));return t.conversation.id=this.info.id||"",Promise.resolve(t)}}class Oe{constructor(e,t){this.type=ne.Person,this.parent=e,this.account=t}async sendMessage(e,t){const n={};return await this.parent.adapter.continueConversationAsync(this.parent.botAppId,this.parent.conversationReference,(async i=>{const o=await this.newConversation(i);await this.parent.adapter.continueConversationAsync(this.parent.botAppId,o,(async i=>{try{const t=await i.sendActivity(e);n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(i,e)}}))})),n}async sendAdaptiveCard(e,t){const n={};return await this.parent.adapter.continueConversationAsync(this.parent.botAppId,this.parent.conversationReference,(async i=>{const o=await this.newConversation(i);await this.parent.adapter.continueConversationAsync(this.parent.botAppId,o,(async i=>{try{const t=await i.sendActivity({attachments:[r.adaptiveCard(e)]});n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(i,e)}}))})),n}async newConversation(e){const t=Te(h.getConversationReference(e.activity)),n=e.turnState.get(this.parent.adapter.ConnectorClientKey),i=await n.conversations.createConversation({isGroup:!1,tenantId:e.activity.conversation.tenantId,bot:e.activity.recipient,members:[this.account],channelData:{}});return t.conversation.id=i.id,t}}class Pe{constructor(e,t,n){this.adapter=e,this.conversationReference=t,this.type=function(e){var t;const n=null===(t=e.conversation)||void 0===t?void 0:t.conversationType;return"personal"===n?ne.Person:"groupChat"===n?ne.Group:"channel"===n?ne.Channel:void 0}(t),this.botAppId=n}async sendMessage(e,t){const n={};return await this.adapter.continueConversationAsync(this.botAppId,this.conversationReference,(async i=>{try{const t=await i.sendActivity(e);n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(i,e)}})),n}async sendAdaptiveCard(e,t){const n={};return await this.adapter.continueConversationAsync(this.botAppId,this.conversationReference,(async i=>{try{const t=await i.sendActivity({attachments:[r.adaptiveCard(e)]});n.id=null==t?void 0:t.id}catch(e){if(!t)throw e;await t(i,e)}})),n}async channels(){const e=[];if(this.type!==ne.Channel)return e;let t=[];await this.adapter.continueConversationAsync(this.botAppId,this.conversationReference,(async e=>{const n=Ee(e);void 0!==n&&(t=await a.getTeamChannels(e,n))}));for(const n of t)e.push(new be(this,n));return e}async getPagedMembers(e,t){let n={data:[],continuationToken:""};return await this.adapter.continueConversationAsync(this.botAppId,this.conversationReference,(async i=>{const o=await a.getPagedMembers(i,e,t);n={data:o.members.map((e=>new Oe(this,e))),continuationToken:o.continuationToken}})),n}async getTeamDetails(){if(this.type!==ne.Channel)return;let e;return await this.adapter.continueConversationAsync(this.botAppId,this.conversationReference,(async t=>{const n=Ee(t);void 0!==n&&(e=await a.getTeamDetails(t,n))})),e}}class Fe{constructor(e,t){var n,i;(null==t?void 0:t.store)?this.conversationReferenceStore=t.store:this.conversationReferenceStore=new Re(b.resolve("1"===process.env.RUNNING_ON_AZURE&&null!==(n=process.env.TEMP)&&void 0!==n?n:"./")),this.adapter=e.use(new xe({conversationReferenceStore:this.conversationReferenceStore})),this.botAppId=null!==(i=null==t?void 0:t.botAppId)&&void 0!==i?i:process.env.BOT_ID}buildTeamsBotInstallation(e){if(!e)throw new Error("conversationReference is required.");return new Pe(this.adapter,e,this.botAppId)}async validateInstallation(e){let t=!0;return await this.adapter.continueConversationAsync(this.botAppId,e,(async e=>{try{await a.getPagedMembers(e,1)}catch(e){"BotNotInConversationRoster"===e.code&&(t=!1)}})),t}async getPagedInstallations(e,t,n=!0){if(void 0===this.conversationReferenceStore||void 0===this.adapter)throw new Error("NotificationBot has not been initialized.");const i=await this.conversationReferenceStore.list(e,t),o=[];for(const e of i.data){let t;n&&(t=await this.validateInstallation(e)),!n||n&&t?o.push(new Pe(this.adapter,e,this.botAppId)):await this.conversationReferenceStore.remove(ke(e),e)}return{data:o,continuationToken:i.continuationToken}}async findMember(e,t){for(const n of await this.installations())if(this.matchSearchScope(n,t)){const t=[];let i;do{const e=await n.getPagedMembers(void 0,i);i=e.continuationToken,t.push(...e.data)}while(i);for(const n of t)if(await e(n))return n}}async findChannel(e){for(const t of await this.installations())if(t.type===ne.Channel){const n=await t.getTeamDetails();for(const i of await t.channels())if(await e(i,n))return i}}async findAllMembers(e,t){const n=[];for(const i of await this.installations())if(this.matchSearchScope(i,t)){const t=[];let o;do{const e=await i.getPagedMembers(void 0,o);o=e.continuationToken,t.push(...e.data)}while(o);for(const i of t)await e(i)&&n.push(i)}return n}async findAllChannels(e){const t=[];for(const n of await this.installations())if(n.type===ne.Channel){const i=await n.getTeamDetails();for(const o of await n.channels())await e(o,i)&&t.push(o)}return t}matchSearchScope(e,t){return t=null!=t?t:me.All,e.type===ne.Channel&&0!=(t&me.Channel)||e.type===ne.Group&&0!=(t&me.Group)||e.type===ne.Person&&0!=(t&me.Person)}async installations(){let e;const t=[];do{const n=await this.getPagedInstallations(void 0,e);e=n.continuationToken,t.push(...n.data)}while(e);return t}}!function(e){e[e.Person=1]="Person",e[e.Group=2]="Group",e[e.Channel=4]="Channel",e[e.All=7]="All"}(me||(me={}));class De extends p{constructor(e){var t,n,i,o,a,r,s,c,d,l;super();const u=new v,h=null!==(n=null===(t=e.dialog)||void 0===t?void 0:t.userState)&&void 0!==n?n:new m(u),p=null!==(o=null===(i=e.dialog)||void 0===i?void 0:i.conversationState)&&void 0!==o?o:new f(u),y=null!==(r=null===(a=e.dialog)||void 0===a?void 0:a.dedupStorage)&&void 0!==r?r:u,g=e.aad,{scopes:w}=g,C=
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
1
|
+
import { jwtDecode } from 'jwt-decode';
|
2
|
+
import { ConfidentialClientApplication } from '@azure/msal-node';
|
3
|
+
import { createHash } from 'crypto';
|
4
|
+
import { ActivityTypes, Channels, TeamsInfo, CardFactory, ActionTypes, MessageFactory, StatusCodes, verifyStateOperationName, tokenExchangeOperationName, TurnContext, TeamsActivityHandler, MemoryStorage, UserState, ConversationState, ConfigurationServiceClientCredentialFactory, ConfigurationBotFrameworkAuthentication, CloudAdapter } from 'botbuilder';
|
5
|
+
import { Dialog, ComponentDialog, WaterfallDialog, DialogSet, DialogTurnStatus } from 'botbuilder-dialogs';
|
6
|
+
import { v4 } from 'uuid';
|
7
|
+
import axios from 'axios';
|
8
|
+
import { Agent } from 'https';
|
9
|
+
import * as ACData from 'adaptivecards-templating';
|
10
|
+
import * as path from 'path';
|
11
|
+
import * as fs from 'fs';
|
12
|
+
|
13
|
+
// Copyright (c) Microsoft Corporation.
|
14
|
+
// Licensed under the MIT license.
|
15
|
+
/**
|
16
|
+
* Error code to trace the error types.
|
17
|
+
*/
|
18
|
+
var ErrorCode;
|
19
|
+
(function (ErrorCode) {
|
20
|
+
/**
|
21
|
+
* Invalid parameter error.
|
22
|
+
*/
|
23
|
+
ErrorCode["InvalidParameter"] = "InvalidParameter";
|
24
|
+
/**
|
25
|
+
* Invalid configuration error.
|
26
|
+
*/
|
27
|
+
ErrorCode["InvalidConfiguration"] = "InvalidConfiguration";
|
28
|
+
/**
|
29
|
+
* Invalid certificate error.
|
30
|
+
*/
|
31
|
+
ErrorCode["InvalidCertificate"] = "InvalidCertificate";
|
32
|
+
/**
|
33
|
+
* Internal error.
|
34
|
+
*/
|
35
|
+
ErrorCode["InternalError"] = "InternalError";
|
36
|
+
/**
|
37
|
+
* Channel is not supported error.
|
38
|
+
*/
|
39
|
+
ErrorCode["ChannelNotSupported"] = "ChannelNotSupported";
|
40
|
+
/**
|
41
|
+
* Failed to retrieve sso token
|
42
|
+
*/
|
43
|
+
ErrorCode["FailedToRetrieveSsoToken"] = "FailedToRetrieveSsoToken";
|
44
|
+
/**
|
45
|
+
* Failed to process sso handler
|
46
|
+
*/
|
47
|
+
ErrorCode["FailedToProcessSsoHandler"] = "FailedToProcessSsoHandler";
|
48
|
+
/**
|
49
|
+
* Cannot find command
|
50
|
+
*/
|
51
|
+
ErrorCode["CannotFindCommand"] = "CannotFindCommand";
|
52
|
+
/**
|
53
|
+
* Failed to run sso step
|
54
|
+
*/
|
55
|
+
ErrorCode["FailedToRunSsoStep"] = "FailedToRunSsoStep";
|
56
|
+
/**
|
57
|
+
* Failed to run dedup step
|
58
|
+
*/
|
59
|
+
ErrorCode["FailedToRunDedupStep"] = "FailedToRunDedupStep";
|
60
|
+
/**
|
61
|
+
* Sso activity handler is undefined
|
62
|
+
*/
|
63
|
+
ErrorCode["SsoActivityHandlerIsUndefined"] = "SsoActivityHandlerIsUndefined";
|
64
|
+
/**
|
65
|
+
* Runtime is not supported error.
|
66
|
+
*/
|
67
|
+
ErrorCode["RuntimeNotSupported"] = "RuntimeNotSupported";
|
68
|
+
/**
|
69
|
+
* User failed to finish the AAD consent flow failed.
|
70
|
+
*/
|
71
|
+
ErrorCode["ConsentFailed"] = "ConsentFailed";
|
72
|
+
/**
|
73
|
+
* The user or administrator has not consented to use the application error.
|
74
|
+
*/
|
75
|
+
ErrorCode["UiRequiredError"] = "UiRequiredError";
|
76
|
+
/**
|
77
|
+
* Token is not within its valid time range error.
|
78
|
+
*/
|
79
|
+
ErrorCode["TokenExpiredError"] = "TokenExpiredError";
|
80
|
+
/**
|
81
|
+
* Call service (AAD or simple authentication server) failed.
|
82
|
+
*/
|
83
|
+
ErrorCode["ServiceError"] = "ServiceError";
|
84
|
+
/**
|
85
|
+
* Operation failed.
|
86
|
+
*/
|
87
|
+
ErrorCode["FailedOperation"] = "FailedOperation";
|
88
|
+
/**
|
89
|
+
* Invalid response error.
|
90
|
+
*/
|
91
|
+
ErrorCode["InvalidResponse"] = "InvalidResponse";
|
92
|
+
/**
|
93
|
+
* Authentication info already exists error.
|
94
|
+
*/
|
95
|
+
ErrorCode["AuthorizationInfoAlreadyExists"] = "AuthorizationInfoAlreadyExists";
|
96
|
+
})(ErrorCode || (ErrorCode = {}));
|
97
|
+
/**
|
98
|
+
* @internal
|
99
|
+
*/
|
100
|
+
class ErrorMessage {
|
101
|
+
}
|
102
|
+
// InvalidConfiguration Error
|
103
|
+
ErrorMessage.InvalidConfiguration = "{0} in configuration is invalid: {1}.";
|
104
|
+
ErrorMessage.ConfigurationNotExists = "Configuration does not exist. {0}";
|
105
|
+
ErrorMessage.ResourceConfigurationNotExists = "{0} resource configuration does not exist.";
|
106
|
+
ErrorMessage.MissingResourceConfiguration = "Missing resource configuration with type: {0}, name: {1}.";
|
107
|
+
ErrorMessage.AuthenticationConfigurationNotExists = "Authentication configuration does not exist.";
|
108
|
+
// RuntimeNotSupported Error
|
109
|
+
ErrorMessage.BrowserRuntimeNotSupported = "{0} is not supported in browser.";
|
110
|
+
ErrorMessage.NodejsRuntimeNotSupported = "{0} is not supported in Node.";
|
111
|
+
// Internal Error
|
112
|
+
ErrorMessage.FailToAcquireTokenOnBehalfOfUser = "Failed to acquire access token on behalf of user: {0}";
|
113
|
+
// ChannelNotSupported Error
|
114
|
+
ErrorMessage.OnlyMSTeamsChannelSupported = "{0} is only supported in MS Teams Channel";
|
115
|
+
ErrorMessage.FailedToProcessSsoHandler = "Failed to process sso handler: {0}";
|
116
|
+
// FailedToRetrieveSsoToken Error
|
117
|
+
ErrorMessage.FailedToRetrieveSsoToken = "Failed to retrieve sso token, user failed to finish the AAD consent flow.";
|
118
|
+
// CannotFindCommand Error
|
119
|
+
ErrorMessage.CannotFindCommand = "Cannot find command: {0}";
|
120
|
+
ErrorMessage.FailedToRunSsoStep = "Failed to run dialog to retrieve sso token: {0}";
|
121
|
+
ErrorMessage.FailedToRunDedupStep = "Failed to run dialog to remove duplicated messages: {0}";
|
122
|
+
// SsoActivityHandlerIsUndefined Error
|
123
|
+
ErrorMessage.SsoActivityHandlerIsNull = "Sso command can only be used or added when sso activity handler is not undefined";
|
124
|
+
// AuthorizationInfoError
|
125
|
+
ErrorMessage.AuthorizationHeaderAlreadyExists = "Authorization header already exists!";
|
126
|
+
ErrorMessage.BasicCredentialAlreadyExists = "Basic credential already exists!";
|
127
|
+
// InvalidParameter Error
|
128
|
+
ErrorMessage.EmptyParameter = "Parameter {0} is empty";
|
129
|
+
ErrorMessage.DuplicateHttpsOptionProperty = "Axios HTTPS agent already defined value for property {0}";
|
130
|
+
ErrorMessage.DuplicateApiKeyInHeader = "The request already defined api key in request header with name {0}.";
|
131
|
+
ErrorMessage.DuplicateApiKeyInQueryParam = "The request already defined api key in query parameter with name {0}.";
|
132
|
+
ErrorMessage.OnlySupportInQueryActivity = "The handleMessageExtensionQueryWithToken only support in handleTeamsMessagingExtensionQuery with composeExtension/query type.";
|
133
|
+
ErrorMessage.OnlySupportInLinkQueryActivity = "The handleMessageExtensionLinkQueryWithSSO only support in handleTeamsAppBasedLinkQuery with composeExtension/queryLink type.";
|
134
|
+
/**
|
135
|
+
* Error class with code and message thrown by the SDK.
|
136
|
+
*/
|
137
|
+
class ErrorWithCode extends Error {
|
138
|
+
/**
|
139
|
+
* Constructor of ErrorWithCode.
|
140
|
+
*
|
141
|
+
* @param {string} message - error message.
|
142
|
+
* @param {ErrorCode} code - error code.
|
143
|
+
*/
|
144
|
+
constructor(message, code) {
|
145
|
+
if (!code) {
|
146
|
+
super(message);
|
147
|
+
return this;
|
148
|
+
}
|
149
|
+
super(message);
|
150
|
+
Object.setPrototypeOf(this, ErrorWithCode.prototype);
|
151
|
+
this.name = `${new.target.name}.${code}`;
|
152
|
+
this.code = code;
|
153
|
+
}
|
154
|
+
}
|
155
|
+
|
156
|
+
// Copyright (c) Microsoft Corporation.
|
157
|
+
// Licensed under the MIT license.
|
158
|
+
/**
|
159
|
+
* Log level.
|
160
|
+
*/
|
161
|
+
var LogLevel;
|
162
|
+
(function (LogLevel) {
|
163
|
+
/**
|
164
|
+
* Show verbose, information, warning and error message.
|
165
|
+
*/
|
166
|
+
LogLevel[LogLevel["Verbose"] = 0] = "Verbose";
|
167
|
+
/**
|
168
|
+
* Show information, warning and error message.
|
169
|
+
*/
|
170
|
+
LogLevel[LogLevel["Info"] = 1] = "Info";
|
171
|
+
/**
|
172
|
+
* Show warning and error message.
|
173
|
+
*/
|
174
|
+
LogLevel[LogLevel["Warn"] = 2] = "Warn";
|
175
|
+
/**
|
176
|
+
* Show error message.
|
177
|
+
*/
|
178
|
+
LogLevel[LogLevel["Error"] = 3] = "Error";
|
179
|
+
})(LogLevel || (LogLevel = {}));
|
180
|
+
/**
|
181
|
+
* Update log level helper.
|
182
|
+
*
|
183
|
+
* @param { LogLevel } level - log level in configuration
|
184
|
+
*/
|
185
|
+
function setLogLevel(level) {
|
186
|
+
internalLogger.level = level;
|
187
|
+
}
|
188
|
+
/**
|
189
|
+
* Get log level.
|
190
|
+
*
|
191
|
+
* @returns Log level
|
192
|
+
*/
|
193
|
+
function getLogLevel() {
|
194
|
+
return internalLogger.level;
|
195
|
+
}
|
196
|
+
class InternalLogger {
|
197
|
+
constructor(name, logLevel) {
|
198
|
+
this.level = undefined;
|
199
|
+
this.defaultLogger = {
|
200
|
+
verbose: console.debug,
|
201
|
+
info: console.info,
|
202
|
+
warn: console.warn,
|
203
|
+
error: console.error,
|
204
|
+
};
|
205
|
+
this.name = name;
|
206
|
+
this.level = logLevel;
|
207
|
+
}
|
208
|
+
error(message) {
|
209
|
+
this.log(LogLevel.Error, (x) => x.error, message);
|
210
|
+
}
|
211
|
+
warn(message) {
|
212
|
+
this.log(LogLevel.Warn, (x) => x.warn, message);
|
213
|
+
}
|
214
|
+
info(message) {
|
215
|
+
this.log(LogLevel.Info, (x) => x.info, message);
|
216
|
+
}
|
217
|
+
verbose(message) {
|
218
|
+
this.log(LogLevel.Verbose, (x) => x.verbose, message);
|
219
|
+
}
|
220
|
+
log(logLevel, logFunction, message) {
|
221
|
+
if (message.trim() === "") {
|
222
|
+
return;
|
223
|
+
}
|
224
|
+
const timestamp = new Date().toUTCString();
|
225
|
+
let logHeader;
|
226
|
+
if (this.name) {
|
227
|
+
logHeader = `[${timestamp}] : @microsoft/teamsfx - ${this.name} : ${LogLevel[logLevel]} - `;
|
228
|
+
}
|
229
|
+
else {
|
230
|
+
logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;
|
231
|
+
}
|
232
|
+
const logMessage = `${logHeader}${message}`;
|
233
|
+
if (this.level !== undefined && this.level <= logLevel) {
|
234
|
+
if (this.customLogger) {
|
235
|
+
logFunction(this.customLogger)(logMessage);
|
236
|
+
}
|
237
|
+
else if (this.customLogFunction) {
|
238
|
+
this.customLogFunction(logLevel, logMessage);
|
239
|
+
}
|
240
|
+
else {
|
241
|
+
logFunction(this.defaultLogger)(logMessage);
|
242
|
+
}
|
243
|
+
}
|
244
|
+
}
|
245
|
+
}
|
246
|
+
/**
|
247
|
+
* Logger instance used internally
|
248
|
+
*
|
249
|
+
* @internal
|
250
|
+
*/
|
251
|
+
const internalLogger = new InternalLogger();
|
252
|
+
/**
|
253
|
+
* Set custom logger. Use the output functions if it's set. Priority is higher than setLogFunction.
|
254
|
+
*
|
255
|
+
* @param {Logger} logger - custom logger. If it's undefined, custom logger will be cleared.
|
256
|
+
*
|
257
|
+
* @example
|
258
|
+
* ```typescript
|
259
|
+
* setLogger({
|
260
|
+
* verbose: console.debug,
|
261
|
+
* info: console.info,
|
262
|
+
* warn: console.warn,
|
263
|
+
* error: console.error,
|
264
|
+
* });
|
265
|
+
* ```
|
266
|
+
*/
|
267
|
+
function setLogger(logger) {
|
268
|
+
internalLogger.customLogger = logger;
|
269
|
+
}
|
270
|
+
/**
|
271
|
+
* Set custom log function. Use the function if it's set. Priority is lower than setLogger.
|
272
|
+
*
|
273
|
+
* @param {LogFunction} logFunction - custom log function. If it's undefined, custom log function will be cleared.
|
274
|
+
*
|
275
|
+
* @example
|
276
|
+
* ```typescript
|
277
|
+
* setLogFunction((level: LogLevel, message: string) => {
|
278
|
+
* if (level === LogLevel.Error) {
|
279
|
+
* console.log(message);
|
280
|
+
* }
|
281
|
+
* });
|
282
|
+
* ```
|
283
|
+
*/
|
284
|
+
function setLogFunction(logFunction) {
|
285
|
+
internalLogger.customLogFunction = logFunction;
|
286
|
+
}
|
287
|
+
|
288
|
+
// Copyright (c) Microsoft Corporation.
|
289
|
+
/**
|
290
|
+
* Parse jwt token payload
|
291
|
+
*
|
292
|
+
* @param token
|
293
|
+
*
|
294
|
+
* @returns Payload object
|
295
|
+
*
|
296
|
+
* @internal
|
297
|
+
*/
|
298
|
+
function parseJwt(token) {
|
299
|
+
try {
|
300
|
+
const tokenObj = jwtDecode(token);
|
301
|
+
if (!tokenObj || !tokenObj.exp) {
|
302
|
+
throw new ErrorWithCode("Decoded token is null or exp claim does not exists.", ErrorCode.InternalError);
|
303
|
+
}
|
304
|
+
return tokenObj;
|
305
|
+
}
|
306
|
+
catch (err) {
|
307
|
+
const errorMsg = "Parse jwt token failed in node env with error: " + err.message;
|
308
|
+
internalLogger.error(errorMsg);
|
309
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
|
310
|
+
}
|
311
|
+
}
|
312
|
+
/**
|
313
|
+
* @internal
|
314
|
+
*/
|
315
|
+
function getUserInfoFromSsoToken(ssoToken) {
|
316
|
+
if (!ssoToken) {
|
317
|
+
const errorMsg = "SSO token is undefined.";
|
318
|
+
internalLogger.error(errorMsg);
|
319
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
|
320
|
+
}
|
321
|
+
const tokenObject = parseJwt(ssoToken);
|
322
|
+
const userInfo = {
|
323
|
+
displayName: tokenObject.name,
|
324
|
+
objectId: tokenObject.oid,
|
325
|
+
tenantId: tokenObject.tid,
|
326
|
+
preferredUserName: "",
|
327
|
+
};
|
328
|
+
if (tokenObject.ver === "2.0") {
|
329
|
+
userInfo.preferredUserName = tokenObject.preferred_username;
|
330
|
+
}
|
331
|
+
else if (tokenObject.ver === "1.0") {
|
332
|
+
userInfo.preferredUserName = tokenObject.upn;
|
333
|
+
}
|
334
|
+
return userInfo;
|
335
|
+
}
|
336
|
+
/**
|
337
|
+
* Format string template with replacements
|
338
|
+
*
|
339
|
+
* ```typescript
|
340
|
+
* const template = "{0} and {1} are fruit. {0} is my favorite one."
|
341
|
+
* const formattedStr = formatString(template, "apple", "pear"); // formattedStr: "apple and pear are fruit. apple is my favorite one."
|
342
|
+
* ```
|
343
|
+
*
|
344
|
+
* @param str string template
|
345
|
+
* @param replacements replacement string array
|
346
|
+
* @returns Formatted string
|
347
|
+
*
|
348
|
+
* @internal
|
349
|
+
*/
|
350
|
+
function formatString(str, ...replacements) {
|
351
|
+
const args = replacements;
|
352
|
+
return str.replace(/{(\d+)}/g, function (match, number) {
|
353
|
+
return typeof args[number] != "undefined" ? args[number] : match;
|
354
|
+
});
|
355
|
+
}
|
356
|
+
/**
|
357
|
+
* @internal
|
358
|
+
*/
|
359
|
+
function validateScopesType(value) {
|
360
|
+
// string
|
361
|
+
if (typeof value === "string" || value instanceof String) {
|
362
|
+
return;
|
363
|
+
}
|
364
|
+
// empty array
|
365
|
+
if (Array.isArray(value) && value.length === 0) {
|
366
|
+
return;
|
367
|
+
}
|
368
|
+
// string array
|
369
|
+
if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string")) {
|
370
|
+
return;
|
371
|
+
}
|
372
|
+
const errorMsg = "The type of scopes is not valid, it must be string or string array";
|
373
|
+
internalLogger.error(errorMsg);
|
374
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
|
375
|
+
}
|
376
|
+
/**
|
377
|
+
* @internal
|
378
|
+
*/
|
379
|
+
function getScopesArray(scopes) {
|
380
|
+
const scopesArray = typeof scopes === "string" ? scopes.split(" ") : scopes;
|
381
|
+
return scopesArray.filter((x) => x !== null && x !== "");
|
382
|
+
}
|
383
|
+
/**
|
384
|
+
* @internal
|
385
|
+
*/
|
386
|
+
function getAuthority(authorityHost, tenantId) {
|
387
|
+
const normalizedAuthorityHost = authorityHost.replace(/\/+$/g, "");
|
388
|
+
return normalizedAuthorityHost + "/" + tenantId;
|
389
|
+
}
|
390
|
+
/**
|
391
|
+
* @internal
|
392
|
+
*/
|
393
|
+
function validateConfig(config) {
|
394
|
+
if (config.clientId &&
|
395
|
+
(config.clientSecret || config.certificateContent) &&
|
396
|
+
config.tenantId &&
|
397
|
+
config.authorityHost) {
|
398
|
+
return;
|
399
|
+
}
|
400
|
+
const missingValues = [];
|
401
|
+
if (!config.clientId) {
|
402
|
+
missingValues.push("clientId");
|
403
|
+
}
|
404
|
+
if (!config.clientSecret && !config.certificateContent) {
|
405
|
+
missingValues.push("clientSecret or certificateContent");
|
406
|
+
}
|
407
|
+
if (!config.tenantId) {
|
408
|
+
missingValues.push("tenantId");
|
409
|
+
}
|
410
|
+
if (!config.authorityHost) {
|
411
|
+
missingValues.push("authorityHost");
|
412
|
+
}
|
413
|
+
const errorMsg = formatString(ErrorMessage.InvalidConfiguration, missingValues.join(", "), "undefined");
|
414
|
+
internalLogger.error(errorMsg);
|
415
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
|
416
|
+
}
|
417
|
+
|
418
|
+
// Copyright (c) Microsoft Corporation.
|
419
|
+
/**
|
420
|
+
* @internal
|
421
|
+
*/
|
422
|
+
function createConfidentialClientApplication(authentication) {
|
423
|
+
const authority = getAuthority(authentication.authorityHost, authentication.tenantId);
|
424
|
+
const clientCertificate = parseCertificate(authentication.certificateContent);
|
425
|
+
const auth = {
|
426
|
+
clientId: authentication.clientId,
|
427
|
+
authority: authority,
|
428
|
+
};
|
429
|
+
if (clientCertificate) {
|
430
|
+
auth.clientCertificate = clientCertificate;
|
431
|
+
}
|
432
|
+
else {
|
433
|
+
auth.clientSecret = authentication.clientSecret;
|
434
|
+
}
|
435
|
+
return new ConfidentialClientApplication({
|
436
|
+
auth,
|
437
|
+
});
|
438
|
+
}
|
439
|
+
/**
|
440
|
+
* @internal
|
441
|
+
*/
|
442
|
+
function parseCertificate(certificateContent) {
|
443
|
+
if (!certificateContent) {
|
444
|
+
return undefined;
|
445
|
+
}
|
446
|
+
const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/;
|
447
|
+
const match = certificatePattern.exec(certificateContent);
|
448
|
+
if (!match) {
|
449
|
+
const errorMsg = "The certificate content does not contain a PEM-encoded certificate.";
|
450
|
+
internalLogger.error(errorMsg);
|
451
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidCertificate);
|
452
|
+
}
|
453
|
+
const thumbprint = createHash("sha256")
|
454
|
+
.update(Buffer.from(match[3], "base64"))
|
455
|
+
.digest("hex")
|
456
|
+
.toUpperCase();
|
457
|
+
return {
|
458
|
+
thumbprintSha256: thumbprint,
|
459
|
+
privateKey: certificateContent,
|
460
|
+
};
|
461
|
+
}
|
462
|
+
|
463
|
+
// Copyright (c) Microsoft Corporation.
|
464
|
+
/**
|
465
|
+
* Represent Microsoft 365 tenant identity, and it is usually used when user is not involved like time-triggered automation job.
|
466
|
+
*
|
467
|
+
* @example
|
468
|
+
* ```typescript
|
469
|
+
* loadConfiguration(); // load configuration from environment variables
|
470
|
+
* const credential = new AppCredential();
|
471
|
+
* ```
|
472
|
+
*
|
473
|
+
* @remarks
|
474
|
+
* Only works in in server side.
|
475
|
+
*/
|
476
|
+
class AppCredential {
|
477
|
+
/**
|
478
|
+
* Constructor of AppCredential.
|
479
|
+
*
|
480
|
+
* @remarks
|
481
|
+
* Only works in in server side.
|
482
|
+
*
|
483
|
+
* @param {AppCredentialAuthConfig} authConfig - The authentication configuration.
|
484
|
+
*
|
485
|
+
* @throws {@link ErrorCode|InvalidConfiguration} when client id, client secret or tenant id is not found in config.
|
486
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
|
487
|
+
*/
|
488
|
+
constructor(authConfig) {
|
489
|
+
internalLogger.info("Create M365 tenant credential");
|
490
|
+
const config = this.loadAndValidateConfig(authConfig);
|
491
|
+
this.msalClient = createConfidentialClientApplication(config);
|
492
|
+
}
|
493
|
+
/**
|
494
|
+
* Get access token for credential.
|
495
|
+
*
|
496
|
+
* @example
|
497
|
+
* ```typescript
|
498
|
+
* await credential.getToken(["User.Read.All"]) // Get Graph access token for single scope using string array
|
499
|
+
* await credential.getToken("User.Read.All") // Get Graph access token for single scope using string
|
500
|
+
* await credential.getToken(["User.Read.All", "Calendars.Read"]) // Get Graph access token for multiple scopes using string array
|
501
|
+
* await credential.getToken("User.Read.All Calendars.Read") // Get Graph access token for multiple scopes using space-separated string
|
502
|
+
* await credential.getToken("https://graph.microsoft.com/User.Read.All") // Get Graph access token with full resource URI
|
503
|
+
* await credential.getToken(["https://outlook.office.com/Mail.Read"]) // Get Outlook access token
|
504
|
+
* ```
|
505
|
+
*
|
506
|
+
* @param {string | string[]} scopes - The list of scopes for which the token will have access.
|
507
|
+
* @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make.
|
508
|
+
*
|
509
|
+
* @throws {@link ErrorCode|ServiceError} when get access token with authentication error.
|
510
|
+
* @throws {@link ErrorCode|InternalError} when get access token with unknown error.
|
511
|
+
* @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
|
512
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
|
513
|
+
*
|
514
|
+
* @returns Access token with expected scopes.
|
515
|
+
* Throw error if get access token failed.
|
516
|
+
*/
|
517
|
+
async getToken(scopes, options) {
|
518
|
+
let accessToken;
|
519
|
+
validateScopesType(scopes);
|
520
|
+
const scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
|
521
|
+
internalLogger.info("Get access token with scopes: " + scopesStr);
|
522
|
+
try {
|
523
|
+
const scopesArray = getScopesArray(scopes);
|
524
|
+
const authenticationResult = await this.msalClient.acquireTokenByClientCredential({
|
525
|
+
scopes: scopesArray,
|
526
|
+
});
|
527
|
+
if (authenticationResult) {
|
528
|
+
accessToken = {
|
529
|
+
token: authenticationResult.accessToken,
|
530
|
+
expiresOnTimestamp: authenticationResult.expiresOn.getTime(),
|
531
|
+
};
|
532
|
+
}
|
533
|
+
}
|
534
|
+
catch (err) {
|
535
|
+
const errorMsg = "Get M365 tenant credential failed with error: " + err.message;
|
536
|
+
internalLogger.error(errorMsg);
|
537
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.ServiceError);
|
538
|
+
}
|
539
|
+
if (!accessToken) {
|
540
|
+
const errorMsg = "Get M365 tenant credential access token failed with empty access token";
|
541
|
+
internalLogger.error(errorMsg);
|
542
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
|
543
|
+
}
|
544
|
+
return accessToken;
|
545
|
+
}
|
546
|
+
/**
|
547
|
+
* Load and validate authentication configuration
|
548
|
+
*
|
549
|
+
* @param {AuthenticationConfiguration} authConfig - The authentication configuration. Use environment variables if not provided.
|
550
|
+
*
|
551
|
+
* @returns Authentication configuration
|
552
|
+
*/
|
553
|
+
loadAndValidateConfig(config) {
|
554
|
+
internalLogger.verbose("Validate authentication configuration");
|
555
|
+
if (config.clientId &&
|
556
|
+
(config.clientSecret || config.certificateContent) &&
|
557
|
+
config.tenantId &&
|
558
|
+
config.authorityHost) {
|
559
|
+
return config;
|
560
|
+
}
|
561
|
+
const missingValues = [];
|
562
|
+
if (!config.clientId) {
|
563
|
+
missingValues.push("clientId");
|
564
|
+
}
|
565
|
+
if (!config.clientSecret && !config.certificateContent) {
|
566
|
+
missingValues.push("clientSecret or certificateContent");
|
567
|
+
}
|
568
|
+
if (!config.tenantId) {
|
569
|
+
missingValues.push("tenantId");
|
570
|
+
}
|
571
|
+
if (!config.authorityHost) {
|
572
|
+
missingValues.push("authorityHost");
|
573
|
+
}
|
574
|
+
const errorMsg = formatString(ErrorMessage.InvalidConfiguration, missingValues.join(", "), "undefined");
|
575
|
+
internalLogger.error(errorMsg);
|
576
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
|
577
|
+
}
|
578
|
+
}
|
579
|
+
|
580
|
+
// Copyright (c) Microsoft Corporation.
|
581
|
+
/**
|
582
|
+
* Represent on-behalf-of flow to get user identity, and it is designed to be used in server side.
|
583
|
+
*
|
584
|
+
* @example
|
585
|
+
* ```typescript
|
586
|
+
* const credential = new OnBehalfOfUserCredential(ssoToken);
|
587
|
+
* ```
|
588
|
+
*
|
589
|
+
* @remarks
|
590
|
+
* Can only be used in server side.
|
591
|
+
*/
|
592
|
+
class OnBehalfOfUserCredential {
|
593
|
+
/**
|
594
|
+
* Constructor of OnBehalfOfUserCredential
|
595
|
+
*
|
596
|
+
* @remarks
|
597
|
+
* Only works in in server side.
|
598
|
+
*
|
599
|
+
* @param {string} ssoToken - User token provided by Teams SSO feature.
|
600
|
+
* @param {OnBehalfOfCredentialAuthConfig} config - The authentication configuration.
|
601
|
+
*
|
602
|
+
* @throws {@link ErrorCode|InvalidConfiguration} when client id, client secret, certificate content, authority host or tenant id is not found in config.
|
603
|
+
* @throws {@link ErrorCode|InternalError} when SSO token is not valid.
|
604
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
605
|
+
*/
|
606
|
+
constructor(ssoToken, config) {
|
607
|
+
internalLogger.info("Get on behalf of user credential");
|
608
|
+
const missingConfigurations = [];
|
609
|
+
if (!config.clientId) {
|
610
|
+
missingConfigurations.push("clientId");
|
611
|
+
}
|
612
|
+
if (!config.authorityHost) {
|
613
|
+
missingConfigurations.push("authorityHost");
|
614
|
+
}
|
615
|
+
if (!config.clientSecret && !config.certificateContent) {
|
616
|
+
missingConfigurations.push("clientSecret or certificateContent");
|
617
|
+
}
|
618
|
+
if (!config.tenantId) {
|
619
|
+
missingConfigurations.push("tenantId");
|
620
|
+
}
|
621
|
+
if (missingConfigurations.length != 0) {
|
622
|
+
const errorMsg = formatString(ErrorMessage.InvalidConfiguration, missingConfigurations.join(", "), "undefined");
|
623
|
+
internalLogger.error(errorMsg);
|
624
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
|
625
|
+
}
|
626
|
+
this.msalClient = createConfidentialClientApplication(config);
|
627
|
+
const decodedSsoToken = parseJwt(ssoToken);
|
628
|
+
this.ssoToken = {
|
629
|
+
token: ssoToken,
|
630
|
+
expiresOnTimestamp: decodedSsoToken.exp,
|
631
|
+
};
|
632
|
+
}
|
633
|
+
/**
|
634
|
+
* Get access token from credential.
|
635
|
+
*
|
636
|
+
* @example
|
637
|
+
* ```typescript
|
638
|
+
* await credential.getToken([]) // Get SSO token using empty string array
|
639
|
+
* await credential.getToken("") // Get SSO token using empty string
|
640
|
+
* await credential.getToken([".default"]) // Get Graph access token with default scope using string array
|
641
|
+
* await credential.getToken(".default") // Get Graph access token with default scope using string
|
642
|
+
* await credential.getToken(["User.Read"]) // Get Graph access token for single scope using string array
|
643
|
+
* await credential.getToken("User.Read") // Get Graph access token for single scope using string
|
644
|
+
* await credential.getToken(["User.Read", "Application.Read.All"]) // Get Graph access token for multiple scopes using string array
|
645
|
+
* await credential.getToken("User.Read Application.Read.All") // Get Graph access token for multiple scopes using space-separated string
|
646
|
+
* await credential.getToken("https://graph.microsoft.com/User.Read") // Get Graph access token with full resource URI
|
647
|
+
* await credential.getToken(["https://outlook.office.com/Mail.Read"]) // Get Outlook access token
|
648
|
+
* ```
|
649
|
+
*
|
650
|
+
* @param {string | string[]} scopes - The list of scopes for which the token will have access.
|
651
|
+
* @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make.
|
652
|
+
*
|
653
|
+
* @throws {@link ErrorCode|InternalError} when failed to acquire access token on behalf of user with unknown error.
|
654
|
+
* @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.
|
655
|
+
* @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.
|
656
|
+
* @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.
|
657
|
+
* @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
|
658
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
659
|
+
*
|
660
|
+
* @returns Access token with expected scopes.
|
661
|
+
*
|
662
|
+
* @remarks
|
663
|
+
* If scopes is empty string or array, it returns SSO token.
|
664
|
+
* If scopes is non-empty, it returns access token for target scope.
|
665
|
+
*/
|
666
|
+
async getToken(scopes, options) {
|
667
|
+
validateScopesType(scopes);
|
668
|
+
const scopesArray = getScopesArray(scopes);
|
669
|
+
let result;
|
670
|
+
if (!scopesArray.length) {
|
671
|
+
internalLogger.info("Get SSO token.");
|
672
|
+
if (Math.floor(Date.now() / 1000) > this.ssoToken.expiresOnTimestamp) {
|
673
|
+
const errorMsg = "Sso token has already expired.";
|
674
|
+
internalLogger.error(errorMsg);
|
675
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.TokenExpiredError);
|
676
|
+
}
|
677
|
+
result = this.ssoToken;
|
678
|
+
}
|
679
|
+
else {
|
680
|
+
internalLogger.info("Get access token with scopes: " + scopesArray.join(" "));
|
681
|
+
let authenticationResult;
|
682
|
+
try {
|
683
|
+
authenticationResult = await this.msalClient.acquireTokenOnBehalfOf({
|
684
|
+
oboAssertion: this.ssoToken.token,
|
685
|
+
scopes: scopesArray,
|
686
|
+
});
|
687
|
+
}
|
688
|
+
catch (error) {
|
689
|
+
throw this.generateAuthServerError(error);
|
690
|
+
}
|
691
|
+
if (!authenticationResult) {
|
692
|
+
const errorMsg = "Access token is null";
|
693
|
+
internalLogger.error(errorMsg);
|
694
|
+
throw new ErrorWithCode(formatString(ErrorMessage.FailToAcquireTokenOnBehalfOfUser, errorMsg), ErrorCode.InternalError);
|
695
|
+
}
|
696
|
+
result = {
|
697
|
+
token: authenticationResult.accessToken,
|
698
|
+
expiresOnTimestamp: authenticationResult.expiresOn.getTime(),
|
699
|
+
};
|
700
|
+
}
|
701
|
+
return result;
|
702
|
+
}
|
703
|
+
/**
|
704
|
+
* Get basic user info from SSO token.
|
705
|
+
*
|
706
|
+
* @example
|
707
|
+
* ```typescript
|
708
|
+
* const currentUser = getUserInfo();
|
709
|
+
* ```
|
710
|
+
*
|
711
|
+
* @throws {@link ErrorCode|InternalError} when SSO token is not valid.
|
712
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
713
|
+
*
|
714
|
+
* @returns Basic user info with user displayName, objectId and preferredUserName.
|
715
|
+
*/
|
716
|
+
getUserInfo() {
|
717
|
+
internalLogger.info("Get basic user info from SSO token");
|
718
|
+
return getUserInfoFromSsoToken(this.ssoToken.token);
|
719
|
+
}
|
720
|
+
generateAuthServerError(err) {
|
721
|
+
const errorMessage = err.errorMessage;
|
722
|
+
if (err.name === "InteractionRequiredAuthError") {
|
723
|
+
const fullErrorMsg = "Failed to get access token from AAD server, interaction required: " + errorMessage;
|
724
|
+
internalLogger.warn(fullErrorMsg);
|
725
|
+
return new ErrorWithCode(fullErrorMsg, ErrorCode.UiRequiredError);
|
726
|
+
}
|
727
|
+
else if (errorMessage && errorMessage.indexOf("AADSTS50013") >= 0) {
|
728
|
+
const fullErrorMsg = "Failed to get access token from AAD server, assertion is invalid because of various reasons: " +
|
729
|
+
errorMessage;
|
730
|
+
internalLogger.error(fullErrorMsg);
|
731
|
+
return new ErrorWithCode(fullErrorMsg, ErrorCode.TokenExpiredError);
|
732
|
+
}
|
733
|
+
else {
|
734
|
+
const fullErrorMsg = formatString(ErrorMessage.FailToAcquireTokenOnBehalfOfUser, errorMessage);
|
735
|
+
internalLogger.error(fullErrorMsg);
|
736
|
+
return new ErrorWithCode(fullErrorMsg, ErrorCode.ServiceError);
|
737
|
+
}
|
738
|
+
}
|
739
|
+
}
|
740
|
+
|
741
|
+
// Copyright (c) Microsoft Corporation.
|
742
|
+
/**
|
743
|
+
* Represent Teams current user's identity, and it is used within Teams client applications.
|
744
|
+
*
|
745
|
+
* @remarks
|
746
|
+
* Can only be used within Teams.
|
747
|
+
*/
|
748
|
+
class TeamsUserCredential {
|
749
|
+
/**
|
750
|
+
* Constructor of TeamsUserCredential.
|
751
|
+
* @remarks
|
752
|
+
* Can only be used within Teams.
|
753
|
+
*/
|
754
|
+
constructor(authConfig) {
|
755
|
+
throw new ErrorWithCode(formatString(ErrorMessage.NodejsRuntimeNotSupported, "TeamsUserCredential"), ErrorCode.RuntimeNotSupported);
|
756
|
+
}
|
757
|
+
/**
|
758
|
+
* Popup login page to get user's access token with specific scopes.
|
759
|
+
*
|
760
|
+
* @param {string[]} resources - The optional list of resources for full trust Teams apps.
|
761
|
+
*
|
762
|
+
* @remarks
|
763
|
+
* Can only be used within Teams.
|
764
|
+
*/
|
765
|
+
login(scopes, resources) {
|
766
|
+
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.NodejsRuntimeNotSupported, "TeamsUserCredential"), ErrorCode.RuntimeNotSupported));
|
767
|
+
}
|
768
|
+
/**
|
769
|
+
* Get access token from credential.
|
770
|
+
* @remarks
|
771
|
+
* Can only be used within Teams.
|
772
|
+
*/
|
773
|
+
getToken(scopes, options) {
|
774
|
+
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.NodejsRuntimeNotSupported, "TeamsUserCredential"), ErrorCode.RuntimeNotSupported));
|
775
|
+
}
|
776
|
+
/**
|
777
|
+
* Get basic user info from SSO token
|
778
|
+
*
|
779
|
+
* @param {string[]} resources - The optional list of resources for full trust Teams apps.
|
780
|
+
*
|
781
|
+
* @remarks
|
782
|
+
* Can only be used within Teams.
|
783
|
+
*/
|
784
|
+
getUserInfo(resources) {
|
785
|
+
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.NodejsRuntimeNotSupported, "TeamsUserCredential"), ErrorCode.RuntimeNotSupported));
|
786
|
+
}
|
787
|
+
}
|
788
|
+
|
789
|
+
// Copyright (c) Microsoft Corporation.
|
790
|
+
const invokeResponseType = "invokeResponse";
|
791
|
+
/**
|
792
|
+
* Response body returned for a token exchange invoke activity.
|
793
|
+
*/
|
794
|
+
class TokenExchangeInvokeResponse {
|
795
|
+
constructor(id, failureDetail) {
|
796
|
+
this.id = id;
|
797
|
+
this.failureDetail = failureDetail;
|
798
|
+
}
|
799
|
+
}
|
800
|
+
/**
|
801
|
+
* Creates a new prompt that leverage Teams Single Sign On (SSO) support for bot to automatically sign in user and
|
802
|
+
* help receive oauth token, asks the user to consent if needed.
|
803
|
+
*
|
804
|
+
* @remarks
|
805
|
+
* The prompt will attempt to retrieve the users current token of the desired scopes and store it in
|
806
|
+
* the token store.
|
807
|
+
*
|
808
|
+
* User will be automatically signed in leveraging Teams support of Bot Single Sign On(SSO):
|
809
|
+
* https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots
|
810
|
+
*
|
811
|
+
* @example
|
812
|
+
* When used with your bots `DialogSet` you can simply add a new instance of the prompt as a named
|
813
|
+
* dialog using `DialogSet.add()`. You can then start the prompt from a waterfall step using either
|
814
|
+
* `DialogContext.beginDialog()` or `DialogContext.prompt()`. The user will be prompted to sign in as
|
815
|
+
* needed and their access token will be passed as an argument to the callers next waterfall step:
|
816
|
+
*
|
817
|
+
* ```JavaScript
|
818
|
+
* const { ConversationState, MemoryStorage } = require('botbuilder');
|
819
|
+
* const { DialogSet, WaterfallDialog } = require('botbuilder-dialogs');
|
820
|
+
* const { TeamsBotSsoPrompt } = require('@microsoft/teamsfx');
|
821
|
+
*
|
822
|
+
* const convoState = new ConversationState(new MemoryStorage());
|
823
|
+
* const dialogState = convoState.createProperty('dialogState');
|
824
|
+
* const dialogs = new DialogSet(dialogState);
|
825
|
+
*
|
826
|
+
* dialogs.add(new TeamsBotSsoPrompt('TeamsBotSsoPrompt', {
|
827
|
+
* scopes: ["User.Read"],
|
828
|
+
* }));
|
829
|
+
*
|
830
|
+
* dialogs.add(new WaterfallDialog('taskNeedingLogin', [
|
831
|
+
* async (step) => {
|
832
|
+
* return await step.beginDialog('TeamsBotSsoPrompt');
|
833
|
+
* },
|
834
|
+
* async (step) => {
|
835
|
+
* const token = step.result;
|
836
|
+
* if (token) {
|
837
|
+
*
|
838
|
+
* // ... continue with task needing access token ...
|
839
|
+
*
|
840
|
+
* } else {
|
841
|
+
* await step.context.sendActivity(`Sorry... We couldn't log you in. Try again later.`);
|
842
|
+
* return await step.endDialog();
|
843
|
+
* }
|
844
|
+
* }
|
845
|
+
* ]));
|
846
|
+
* ```
|
847
|
+
*/
|
848
|
+
class TeamsBotSsoPrompt extends Dialog {
|
849
|
+
/**
|
850
|
+
* Constructor of TeamsBotSsoPrompt.
|
851
|
+
*
|
852
|
+
* @param {OnBehalfOfCredentialAuthConfig} authConfig - Used to provide configuration and auth
|
853
|
+
* @param {string} initiateLoginEndpoint - Login URL for Teams to redirect to
|
854
|
+
* @param {string} dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.
|
855
|
+
* @param {TeamsBotSsoPromptSettings} settings Settings used to configure the prompt.
|
856
|
+
*
|
857
|
+
* @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
|
858
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
859
|
+
*/
|
860
|
+
constructor(authConfig, initiateLoginEndpoint, dialogId, settings) {
|
861
|
+
super(dialogId);
|
862
|
+
this.initiateLoginEndpoint = initiateLoginEndpoint;
|
863
|
+
this.authConfig = authConfig;
|
864
|
+
this.settings = settings;
|
865
|
+
validateScopesType(this.settings.scopes);
|
866
|
+
validateConfig(this.authConfig);
|
867
|
+
internalLogger.info("Create a new Teams Bot SSO Prompt");
|
868
|
+
}
|
869
|
+
/**
|
870
|
+
* Called when a prompt dialog is pushed onto the dialog stack and is being activated.
|
871
|
+
* @remarks
|
872
|
+
* If the task is successful, the result indicates whether the prompt is still
|
873
|
+
* active after the turn has been processed by the prompt.
|
874
|
+
*
|
875
|
+
* @param dc The DialogContext for the current turn of the conversation.
|
876
|
+
*
|
877
|
+
* @throws {@link ErrorCode|InvalidParameter} when timeout property in teams bot sso prompt settings is not number or is not positive.
|
878
|
+
* @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.
|
879
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
880
|
+
*
|
881
|
+
* @returns A `Promise` representing the asynchronous operation.
|
882
|
+
*/
|
883
|
+
async beginDialog(dc) {
|
884
|
+
var _a;
|
885
|
+
internalLogger.info("Begin Teams Bot SSO Prompt");
|
886
|
+
this.ensureMsTeamsChannel(dc);
|
887
|
+
// Initialize prompt state
|
888
|
+
const default_timeout = 900000;
|
889
|
+
let timeout = default_timeout;
|
890
|
+
if (this.settings.timeout) {
|
891
|
+
if (typeof this.settings.timeout != "number") {
|
892
|
+
const errorMsg = "type of timeout property in teamsBotSsoPromptSettings should be number.";
|
893
|
+
internalLogger.error(errorMsg);
|
894
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
|
895
|
+
}
|
896
|
+
if (this.settings.timeout <= 0) {
|
897
|
+
const errorMsg = "value of timeout property in teamsBotSsoPromptSettings should be positive.";
|
898
|
+
internalLogger.error(errorMsg);
|
899
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
|
900
|
+
}
|
901
|
+
timeout = this.settings.timeout;
|
902
|
+
}
|
903
|
+
if (this.settings.endOnInvalidMessage === undefined) {
|
904
|
+
this.settings.endOnInvalidMessage = true;
|
905
|
+
}
|
906
|
+
const state = (_a = dc.activeDialog) === null || _a === void 0 ? void 0 : _a.state;
|
907
|
+
state.state = {};
|
908
|
+
state.options = {};
|
909
|
+
state.expires = new Date().getTime() + timeout;
|
910
|
+
// Send OAuth card to get SSO token
|
911
|
+
await this.sendOAuthCardAsync(dc.context);
|
912
|
+
return Dialog.EndOfTurn;
|
913
|
+
}
|
914
|
+
/**
|
915
|
+
* Called when a prompt dialog is the active dialog and the user replied with a new activity.
|
916
|
+
*
|
917
|
+
* @remarks
|
918
|
+
* If the task is successful, the result indicates whether the dialog is still
|
919
|
+
* active after the turn has been processed by the dialog.
|
920
|
+
* The prompt generally continues to receive the user's replies until it accepts the
|
921
|
+
* user's reply as valid input for the prompt.
|
922
|
+
*
|
923
|
+
* @param dc The DialogContext for the current turn of the conversation.
|
924
|
+
*
|
925
|
+
* @returns A `Promise` representing the asynchronous operation.
|
926
|
+
*
|
927
|
+
* @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.
|
928
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
929
|
+
*/
|
930
|
+
async continueDialog(dc) {
|
931
|
+
var _a;
|
932
|
+
internalLogger.info("Continue Teams Bot SSO Prompt");
|
933
|
+
this.ensureMsTeamsChannel(dc);
|
934
|
+
// Check for timeout
|
935
|
+
const state = (_a = dc.activeDialog) === null || _a === void 0 ? void 0 : _a.state;
|
936
|
+
const isMessage = dc.context.activity.type === ActivityTypes.Message;
|
937
|
+
const isTimeoutActivityType = isMessage ||
|
938
|
+
this.isTeamsVerificationInvoke(dc.context) ||
|
939
|
+
this.isTokenExchangeRequestInvoke(dc.context);
|
940
|
+
// If the incoming Activity is a message, or an Activity Type normally handled by TeamsBotSsoPrompt,
|
941
|
+
// check to see if this TeamsBotSsoPrompt Expiration has elapsed, and end the dialog if so.
|
942
|
+
const hasTimedOut = isTimeoutActivityType && new Date().getTime() > state.expires;
|
943
|
+
if (hasTimedOut) {
|
944
|
+
internalLogger.warn("End Teams Bot SSO Prompt due to timeout");
|
945
|
+
return await dc.endDialog(undefined);
|
946
|
+
}
|
947
|
+
else {
|
948
|
+
if (this.isTeamsVerificationInvoke(dc.context) ||
|
949
|
+
this.isTokenExchangeRequestInvoke(dc.context)) {
|
950
|
+
// Recognize token
|
951
|
+
const recognized = await this.recognizeToken(dc);
|
952
|
+
if (recognized.succeeded) {
|
953
|
+
return await dc.endDialog(recognized.value);
|
954
|
+
}
|
955
|
+
}
|
956
|
+
else if (isMessage && this.settings.endOnInvalidMessage) {
|
957
|
+
internalLogger.warn("End Teams Bot SSO Prompt due to invalid message");
|
958
|
+
return await dc.endDialog(undefined);
|
959
|
+
}
|
960
|
+
return Dialog.EndOfTurn;
|
961
|
+
}
|
962
|
+
}
|
963
|
+
/**
|
964
|
+
* Ensure bot is running in MS Teams since TeamsBotSsoPrompt is only supported in MS Teams channel.
|
965
|
+
* @param dc dialog context
|
966
|
+
* @throws {@link ErrorCode|ChannelNotSupported} if bot channel is not MS Teams
|
967
|
+
* @internal
|
968
|
+
*/
|
969
|
+
ensureMsTeamsChannel(dc) {
|
970
|
+
if (dc.context.activity.channelId != Channels.Msteams) {
|
971
|
+
const errorMsg = formatString(ErrorMessage.OnlyMSTeamsChannelSupported, "Teams Bot SSO Prompt");
|
972
|
+
internalLogger.error(errorMsg);
|
973
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.ChannelNotSupported);
|
974
|
+
}
|
975
|
+
}
|
976
|
+
/**
|
977
|
+
* Send OAuthCard that tells Teams to obtain an authentication token for the bot application.
|
978
|
+
* For details see https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots.
|
979
|
+
*
|
980
|
+
* @internal
|
981
|
+
*/
|
982
|
+
async sendOAuthCardAsync(context) {
|
983
|
+
internalLogger.verbose("Send OAuth card to get SSO token");
|
984
|
+
const account = await TeamsInfo.getMember(context, context.activity.from.id);
|
985
|
+
internalLogger.verbose("Get Teams member account user principal name: " +
|
986
|
+
(account.userPrincipalName ? account.userPrincipalName : ""));
|
987
|
+
const loginHint = account.userPrincipalName ? account.userPrincipalName : "";
|
988
|
+
const signInResource = this.getSignInResource(loginHint);
|
989
|
+
const card = CardFactory.oauthCard("", "Teams SSO Sign In", "Sign In", signInResource.signInLink, signInResource.tokenExchangeResource);
|
990
|
+
card.content.buttons[0].type = ActionTypes.Signin;
|
991
|
+
const msg = MessageFactory.attachment(card);
|
992
|
+
// Send prompt
|
993
|
+
await context.sendActivity(msg);
|
994
|
+
}
|
995
|
+
/**
|
996
|
+
* Get sign in resource.
|
997
|
+
*
|
998
|
+
* @throws {@link ErrorCode|InvalidConfiguration} if client id, tenant id or initiate login endpoint is not found in config.
|
999
|
+
*
|
1000
|
+
* @internal
|
1001
|
+
*/
|
1002
|
+
getSignInResource(loginHint) {
|
1003
|
+
internalLogger.verbose("Get sign in authentication configuration");
|
1004
|
+
const signInLink = `${this.initiateLoginEndpoint}?scope=${encodeURI(this.settings.scopes.join(" "))}&clientId=${this.authConfig.clientId}&tenantId=${this.authConfig.tenantId}&loginHint=${loginHint}`;
|
1005
|
+
internalLogger.verbose("Sign in link: " + signInLink);
|
1006
|
+
const tokenExchangeResource = {
|
1007
|
+
id: v4(),
|
1008
|
+
};
|
1009
|
+
return {
|
1010
|
+
signInLink: signInLink,
|
1011
|
+
tokenExchangeResource: tokenExchangeResource,
|
1012
|
+
};
|
1013
|
+
}
|
1014
|
+
/**
|
1015
|
+
* @internal
|
1016
|
+
*/
|
1017
|
+
async recognizeToken(dc) {
|
1018
|
+
const context = dc.context;
|
1019
|
+
let tokenResponse;
|
1020
|
+
if (this.isTokenExchangeRequestInvoke(context)) {
|
1021
|
+
internalLogger.verbose("Receive token exchange request");
|
1022
|
+
// Received activity is not a token exchange request
|
1023
|
+
if (!(context.activity.value && this.isTokenExchangeRequest(context.activity.value))) {
|
1024
|
+
const warningMsg = "The bot received an InvokeActivity that is missing a TokenExchangeInvokeRequest value. This is required to be sent with the InvokeActivity.";
|
1025
|
+
internalLogger.warn(warningMsg);
|
1026
|
+
await context.sendActivity(this.getTokenExchangeInvokeResponse(StatusCodes.BAD_REQUEST, warningMsg));
|
1027
|
+
}
|
1028
|
+
else {
|
1029
|
+
const ssoToken = context.activity.value.token;
|
1030
|
+
const credential = new OnBehalfOfUserCredential(ssoToken, this.authConfig);
|
1031
|
+
let exchangedToken;
|
1032
|
+
try {
|
1033
|
+
exchangedToken = await credential.getToken(this.settings.scopes);
|
1034
|
+
if (exchangedToken) {
|
1035
|
+
await context.sendActivity(this.getTokenExchangeInvokeResponse(StatusCodes.OK, "", context.activity.value.id));
|
1036
|
+
const ssoTokenExpiration = parseJwt(ssoToken).exp;
|
1037
|
+
tokenResponse = {
|
1038
|
+
ssoToken: ssoToken,
|
1039
|
+
ssoTokenExpiration: new Date(ssoTokenExpiration * 1000).toISOString(),
|
1040
|
+
connectionName: "",
|
1041
|
+
token: exchangedToken.token,
|
1042
|
+
expiration: exchangedToken.expiresOnTimestamp.toString(),
|
1043
|
+
};
|
1044
|
+
}
|
1045
|
+
}
|
1046
|
+
catch (error) {
|
1047
|
+
const warningMsg = "The bot is unable to exchange token. Ask for user consent.";
|
1048
|
+
internalLogger.info(warningMsg);
|
1049
|
+
await context.sendActivity(this.getTokenExchangeInvokeResponse(StatusCodes.PRECONDITION_FAILED, warningMsg, context.activity.value.id));
|
1050
|
+
}
|
1051
|
+
}
|
1052
|
+
}
|
1053
|
+
else if (this.isTeamsVerificationInvoke(context)) {
|
1054
|
+
internalLogger.verbose("Receive Teams state verification request");
|
1055
|
+
await this.sendOAuthCardAsync(dc.context);
|
1056
|
+
await context.sendActivity({ type: invokeResponseType, value: { status: StatusCodes.OK } });
|
1057
|
+
}
|
1058
|
+
return tokenResponse !== undefined
|
1059
|
+
? { succeeded: true, value: tokenResponse }
|
1060
|
+
: { succeeded: false };
|
1061
|
+
}
|
1062
|
+
/**
|
1063
|
+
* @internal
|
1064
|
+
*/
|
1065
|
+
getTokenExchangeInvokeResponse(status, failureDetail, id) {
|
1066
|
+
const invokeResponse = {
|
1067
|
+
type: invokeResponseType,
|
1068
|
+
value: { status, body: new TokenExchangeInvokeResponse(id, failureDetail) },
|
1069
|
+
};
|
1070
|
+
return invokeResponse;
|
1071
|
+
}
|
1072
|
+
/**
|
1073
|
+
* @internal
|
1074
|
+
*/
|
1075
|
+
isTeamsVerificationInvoke(context) {
|
1076
|
+
const activity = context.activity;
|
1077
|
+
return activity.type === ActivityTypes.Invoke && activity.name === verifyStateOperationName;
|
1078
|
+
}
|
1079
|
+
/**
|
1080
|
+
* @internal
|
1081
|
+
*/
|
1082
|
+
isTokenExchangeRequestInvoke(context) {
|
1083
|
+
const activity = context.activity;
|
1084
|
+
return activity.type === ActivityTypes.Invoke && activity.name === tokenExchangeOperationName;
|
1085
|
+
}
|
1086
|
+
/**
|
1087
|
+
* @internal
|
1088
|
+
*/
|
1089
|
+
isTokenExchangeRequest(obj) {
|
1090
|
+
return obj.hasOwnProperty("token");
|
1091
|
+
}
|
1092
|
+
}
|
1093
|
+
|
1094
|
+
// Copyright (c) Microsoft Corporation.
|
1095
|
+
/**
|
1096
|
+
* Initializes new Axios instance with specific auth provider
|
1097
|
+
*
|
1098
|
+
* @param apiEndpoint - Base url of the API
|
1099
|
+
* @param authProvider - Auth provider that injects authentication info to each request
|
1100
|
+
* @returns axios instance configured with specfic auth provider
|
1101
|
+
*
|
1102
|
+
* @example
|
1103
|
+
* ```typescript
|
1104
|
+
* const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
|
1105
|
+
* ```
|
1106
|
+
*/
|
1107
|
+
function createApiClient(apiEndpoint, authProvider) {
|
1108
|
+
// Add a request interceptor
|
1109
|
+
const instance = axios.create({
|
1110
|
+
baseURL: apiEndpoint,
|
1111
|
+
});
|
1112
|
+
instance.interceptors.request.use(async function (config) {
|
1113
|
+
return (await authProvider.AddAuthenticationInfo(config));
|
1114
|
+
});
|
1115
|
+
return instance;
|
1116
|
+
}
|
1117
|
+
|
1118
|
+
// Copyright (c) Microsoft Corporation.
|
1119
|
+
/**
|
1120
|
+
* Provider that handles Bearer Token authentication
|
1121
|
+
*/
|
1122
|
+
class BearerTokenAuthProvider {
|
1123
|
+
/**
|
1124
|
+
* @param { () => Promise<string> } getToken - Function that returns the content of bearer token used in http request
|
1125
|
+
*/
|
1126
|
+
constructor(getToken) {
|
1127
|
+
this.getToken = getToken;
|
1128
|
+
}
|
1129
|
+
/**
|
1130
|
+
* Adds authentication info to http requests
|
1131
|
+
*
|
1132
|
+
* @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
|
1133
|
+
* Refer https://axios-http.com/docs/req_config for detailed document.
|
1134
|
+
*
|
1135
|
+
* @returns Updated axios request config.
|
1136
|
+
*
|
1137
|
+
* @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header already exists in request configuration.
|
1138
|
+
*/
|
1139
|
+
async AddAuthenticationInfo(config) {
|
1140
|
+
const token = await this.getToken();
|
1141
|
+
if (!config.headers) {
|
1142
|
+
config.headers = {};
|
1143
|
+
}
|
1144
|
+
if (config.headers["Authorization"]) {
|
1145
|
+
throw new ErrorWithCode(ErrorMessage.AuthorizationHeaderAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists);
|
1146
|
+
}
|
1147
|
+
config.headers["Authorization"] = `Bearer ${token}`;
|
1148
|
+
return config;
|
1149
|
+
}
|
1150
|
+
}
|
1151
|
+
|
1152
|
+
// Copyright (c) Microsoft Corporation.
|
1153
|
+
/**
|
1154
|
+
* Provider that handles Basic authentication
|
1155
|
+
*/
|
1156
|
+
class BasicAuthProvider {
|
1157
|
+
/**
|
1158
|
+
*
|
1159
|
+
* @param { string } userName - Username used in basic auth
|
1160
|
+
* @param { string } password - Password used in basic auth
|
1161
|
+
*
|
1162
|
+
* @throws {@link ErrorCode|InvalidParameter} - when username or password is empty.
|
1163
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
1164
|
+
*/
|
1165
|
+
constructor(userName, password) {
|
1166
|
+
if (!userName) {
|
1167
|
+
throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "username"), ErrorCode.InvalidParameter);
|
1168
|
+
}
|
1169
|
+
if (!password) {
|
1170
|
+
throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "password"), ErrorCode.InvalidParameter);
|
1171
|
+
}
|
1172
|
+
this.userName = userName;
|
1173
|
+
this.password = password;
|
1174
|
+
}
|
1175
|
+
/**
|
1176
|
+
* Adds authentication info to http requests
|
1177
|
+
*
|
1178
|
+
* @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
|
1179
|
+
* Refer https://axios-http.com/docs/req_config for detailed document.
|
1180
|
+
*
|
1181
|
+
* @returns Updated axios request config.
|
1182
|
+
*
|
1183
|
+
* @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header or auth property already exists in request configuration.
|
1184
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
1185
|
+
*/
|
1186
|
+
AddAuthenticationInfo(config) {
|
1187
|
+
if (config.headers && config.headers["Authorization"]) {
|
1188
|
+
return Promise.reject(new ErrorWithCode(ErrorMessage.AuthorizationHeaderAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists));
|
1189
|
+
}
|
1190
|
+
if (config.auth) {
|
1191
|
+
return Promise.reject(new ErrorWithCode(ErrorMessage.BasicCredentialAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists));
|
1192
|
+
}
|
1193
|
+
config.auth = {
|
1194
|
+
username: this.userName,
|
1195
|
+
password: this.password,
|
1196
|
+
};
|
1197
|
+
return Promise.resolve(config);
|
1198
|
+
}
|
1199
|
+
}
|
1200
|
+
|
1201
|
+
// Copyright (c) Microsoft Corporation.
|
1202
|
+
/**
|
1203
|
+
* Provider that handles API Key authentication
|
1204
|
+
*/
|
1205
|
+
class ApiKeyProvider {
|
1206
|
+
/**
|
1207
|
+
*
|
1208
|
+
* @param { string } keyName - The name of request header or query parameter that specifies API Key
|
1209
|
+
* @param { string } keyValue - The value of API Key
|
1210
|
+
* @param { ApiKeyLocation } keyLocation - The location of API Key: request header or query parameter.
|
1211
|
+
*
|
1212
|
+
* @throws {@link ErrorCode|InvalidParameter} - when key name or key value is empty.
|
1213
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
1214
|
+
*/
|
1215
|
+
constructor(keyName, keyValue, keyLocation) {
|
1216
|
+
if (!keyName) {
|
1217
|
+
throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "keyName"), ErrorCode.InvalidParameter);
|
1218
|
+
}
|
1219
|
+
if (!keyValue) {
|
1220
|
+
throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "keyVaule"), ErrorCode.InvalidParameter);
|
1221
|
+
}
|
1222
|
+
this.keyName = keyName;
|
1223
|
+
this.keyValue = keyValue;
|
1224
|
+
this.keyLocation = keyLocation;
|
1225
|
+
}
|
1226
|
+
/**
|
1227
|
+
* Adds authentication info to http requests
|
1228
|
+
*
|
1229
|
+
* @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
|
1230
|
+
* Refer https://axios-http.com/docs/req_config for detailed document.
|
1231
|
+
*
|
1232
|
+
* @returns Updated axios request config.
|
1233
|
+
*
|
1234
|
+
* @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when API key already exists in request header or url query parameter.
|
1235
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
1236
|
+
*/
|
1237
|
+
AddAuthenticationInfo(config) {
|
1238
|
+
switch (this.keyLocation) {
|
1239
|
+
case ApiKeyLocation.Header:
|
1240
|
+
if (!config.headers) {
|
1241
|
+
config.headers = {};
|
1242
|
+
}
|
1243
|
+
if (config.headers[this.keyName]) {
|
1244
|
+
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.DuplicateApiKeyInHeader, this.keyName), ErrorCode.AuthorizationInfoAlreadyExists));
|
1245
|
+
}
|
1246
|
+
config.headers[this.keyName] = this.keyValue;
|
1247
|
+
break;
|
1248
|
+
case ApiKeyLocation.QueryParams:
|
1249
|
+
if (!config.params) {
|
1250
|
+
config.params = {};
|
1251
|
+
}
|
1252
|
+
let urlHasDefinedApiKey = false;
|
1253
|
+
if (config.url) {
|
1254
|
+
const url = new URL(config.url, config.baseURL);
|
1255
|
+
urlHasDefinedApiKey = url.searchParams.has(this.keyName);
|
1256
|
+
}
|
1257
|
+
if (config.params[this.keyName] || urlHasDefinedApiKey) {
|
1258
|
+
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.DuplicateApiKeyInQueryParam, this.keyName), ErrorCode.AuthorizationInfoAlreadyExists));
|
1259
|
+
}
|
1260
|
+
config.params[this.keyName] = this.keyValue;
|
1261
|
+
break;
|
1262
|
+
}
|
1263
|
+
return Promise.resolve(config);
|
1264
|
+
}
|
1265
|
+
}
|
1266
|
+
/**
|
1267
|
+
* Define available location for API Key location
|
1268
|
+
*/
|
1269
|
+
var ApiKeyLocation;
|
1270
|
+
(function (ApiKeyLocation) {
|
1271
|
+
/**
|
1272
|
+
* The API Key is placed in request header
|
1273
|
+
*/
|
1274
|
+
ApiKeyLocation[ApiKeyLocation["Header"] = 0] = "Header";
|
1275
|
+
/**
|
1276
|
+
* The API Key is placed in query parameter
|
1277
|
+
*/
|
1278
|
+
ApiKeyLocation[ApiKeyLocation["QueryParams"] = 1] = "QueryParams";
|
1279
|
+
})(ApiKeyLocation || (ApiKeyLocation = {}));
|
1280
|
+
|
1281
|
+
// Copyright (c) Microsoft Corporation.
|
1282
|
+
/**
|
1283
|
+
* Provider that handles Certificate authentication
|
1284
|
+
*/
|
1285
|
+
class CertificateAuthProvider {
|
1286
|
+
/**
|
1287
|
+
*
|
1288
|
+
* @param { SecureContextOptions } certOption - information about the cert used in http requests
|
1289
|
+
*
|
1290
|
+
* @throws {@link ErrorCode|InvalidParameter} - when cert option is empty.
|
1291
|
+
*/
|
1292
|
+
constructor(certOption) {
|
1293
|
+
if (certOption && Object.keys(certOption).length !== 0) {
|
1294
|
+
this.certOption = certOption;
|
1295
|
+
}
|
1296
|
+
else {
|
1297
|
+
throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "certOption"), ErrorCode.InvalidParameter);
|
1298
|
+
}
|
1299
|
+
}
|
1300
|
+
/**
|
1301
|
+
* Adds authentication info to http requests.
|
1302
|
+
*
|
1303
|
+
* @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
|
1304
|
+
* Refer https://axios-http.com/docs/req_config for detailed document.
|
1305
|
+
*
|
1306
|
+
* @returns Updated axios request config.
|
1307
|
+
*
|
1308
|
+
* @throws {@link ErrorCode|InvalidParameter} - when custom httpsAgent in the request has duplicate properties with certOption provided in constructor.
|
1309
|
+
*/
|
1310
|
+
AddAuthenticationInfo(config) {
|
1311
|
+
if (!config.httpsAgent) {
|
1312
|
+
config.httpsAgent = new Agent(this.certOption);
|
1313
|
+
}
|
1314
|
+
else {
|
1315
|
+
const existingProperties = new Set(Object.keys(config.httpsAgent.options));
|
1316
|
+
for (const property of Object.keys(this.certOption)) {
|
1317
|
+
if (existingProperties.has(property)) {
|
1318
|
+
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.DuplicateHttpsOptionProperty, property), ErrorCode.InvalidParameter));
|
1319
|
+
}
|
1320
|
+
}
|
1321
|
+
Object.assign(config.httpsAgent.options, this.certOption);
|
1322
|
+
}
|
1323
|
+
return Promise.resolve(config);
|
1324
|
+
}
|
1325
|
+
}
|
1326
|
+
/**
|
1327
|
+
* Helper to create SecureContextOptions from PEM format cert
|
1328
|
+
*
|
1329
|
+
* @param { string | Buffer } cert - The cert chain in PEM format
|
1330
|
+
* @param { string | Buffer } key - The private key for the cert chain
|
1331
|
+
* @param { {passphrase?: string; ca?: string | Buffer} } options - Optional settings when create the cert options.
|
1332
|
+
*
|
1333
|
+
* @returns Instance of SecureContextOptions
|
1334
|
+
*
|
1335
|
+
* @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
|
1336
|
+
*
|
1337
|
+
*/
|
1338
|
+
function createPemCertOption(cert, key, options) {
|
1339
|
+
if (cert.length === 0) {
|
1340
|
+
throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "cert"), ErrorCode.InvalidParameter);
|
1341
|
+
}
|
1342
|
+
if (key.length === 0) {
|
1343
|
+
throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "key"), ErrorCode.InvalidParameter);
|
1344
|
+
}
|
1345
|
+
return {
|
1346
|
+
cert,
|
1347
|
+
key,
|
1348
|
+
passphrase: options === null || options === void 0 ? void 0 : options.passphrase,
|
1349
|
+
ca: options === null || options === void 0 ? void 0 : options.ca,
|
1350
|
+
};
|
1351
|
+
}
|
1352
|
+
/**
|
1353
|
+
* Helper to create SecureContextOptions from PFX format cert
|
1354
|
+
*
|
1355
|
+
* @param { string | Buffer } pfx - The content of .pfx file
|
1356
|
+
* @param { {passphrase?: string} } options - Optional settings when create the cert options.
|
1357
|
+
*
|
1358
|
+
* @returns Instance of SecureContextOptions
|
1359
|
+
*
|
1360
|
+
* @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
|
1361
|
+
*
|
1362
|
+
*/
|
1363
|
+
function createPfxCertOption(pfx, options) {
|
1364
|
+
if (pfx.length === 0) {
|
1365
|
+
throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "pfx"), ErrorCode.InvalidParameter);
|
1366
|
+
}
|
1367
|
+
return {
|
1368
|
+
pfx,
|
1369
|
+
passphrase: options === null || options === void 0 ? void 0 : options.passphrase,
|
1370
|
+
};
|
1371
|
+
}
|
1372
|
+
|
1373
|
+
// Copyright (c) Microsoft Corporation.
|
1374
|
+
// Licensed under the MIT license.
|
1375
|
+
/**
|
1376
|
+
* The target type where the notification will be sent to.
|
1377
|
+
*
|
1378
|
+
* @remarks
|
1379
|
+
* - "Channel" means to a team channel. (By default, notification to a team will be sent to its "General" channel.)
|
1380
|
+
* - "Group" means to a group chat.
|
1381
|
+
* - "Person" means to a personal chat.
|
1382
|
+
*/
|
1383
|
+
var NotificationTargetType;
|
1384
|
+
(function (NotificationTargetType) {
|
1385
|
+
/**
|
1386
|
+
* The notification will be sent to a team channel.
|
1387
|
+
* (By default, notification to a team will be sent to its "General" channel.)
|
1388
|
+
*/
|
1389
|
+
NotificationTargetType["Channel"] = "Channel";
|
1390
|
+
/**
|
1391
|
+
* The notification will be sent to a group chat.
|
1392
|
+
*/
|
1393
|
+
NotificationTargetType["Group"] = "Group";
|
1394
|
+
/**
|
1395
|
+
* The notification will be sent to a personal chat.
|
1396
|
+
*/
|
1397
|
+
NotificationTargetType["Person"] = "Person";
|
1398
|
+
})(NotificationTargetType || (NotificationTargetType = {}));
|
1399
|
+
/**
|
1400
|
+
* Options used to control how the response card will be sent to users.
|
1401
|
+
*/
|
1402
|
+
var AdaptiveCardResponse;
|
1403
|
+
(function (AdaptiveCardResponse) {
|
1404
|
+
/**
|
1405
|
+
* The response card will be replaced the current one for the interactor who trigger the action.
|
1406
|
+
*/
|
1407
|
+
AdaptiveCardResponse[AdaptiveCardResponse["ReplaceForInteractor"] = 0] = "ReplaceForInteractor";
|
1408
|
+
/**
|
1409
|
+
* The response card will be replaced the current one for all users in the chat.
|
1410
|
+
*/
|
1411
|
+
AdaptiveCardResponse[AdaptiveCardResponse["ReplaceForAll"] = 1] = "ReplaceForAll";
|
1412
|
+
/**
|
1413
|
+
* The response card will be sent as a new message for all users in the chat.
|
1414
|
+
*/
|
1415
|
+
AdaptiveCardResponse[AdaptiveCardResponse["NewForAll"] = 2] = "NewForAll";
|
1416
|
+
})(AdaptiveCardResponse || (AdaptiveCardResponse = {}));
|
1417
|
+
/**
|
1418
|
+
* Status code for an `application/vnd.microsoft.error` invoke response.
|
1419
|
+
*/
|
1420
|
+
var InvokeResponseErrorCode;
|
1421
|
+
(function (InvokeResponseErrorCode) {
|
1422
|
+
/**
|
1423
|
+
* Invalid request.
|
1424
|
+
*/
|
1425
|
+
InvokeResponseErrorCode[InvokeResponseErrorCode["BadRequest"] = 400] = "BadRequest";
|
1426
|
+
/**
|
1427
|
+
* Internal server error.
|
1428
|
+
*/
|
1429
|
+
InvokeResponseErrorCode[InvokeResponseErrorCode["InternalServerError"] = 500] = "InternalServerError";
|
1430
|
+
})(InvokeResponseErrorCode || (InvokeResponseErrorCode = {}));
|
1431
|
+
|
1432
|
+
// Copyright (c) Microsoft Corporation.
|
1433
|
+
let DIALOG_NAME = "BotSsoExecutionDialog";
|
1434
|
+
let TEAMS_SSO_PROMPT_ID = "TeamsFxSsoPrompt";
|
1435
|
+
let COMMAND_ROUTE_DIALOG = "CommandRouteDialog";
|
1436
|
+
/**
|
1437
|
+
* Sso execution dialog, use to handle sso command
|
1438
|
+
*/
|
1439
|
+
class BotSsoExecutionDialog extends ComponentDialog {
|
1440
|
+
/**
|
1441
|
+
* Creates a new instance of the BotSsoExecutionDialog.
|
1442
|
+
* @param {@link Storage} dedupStorage Helper storage to remove duplicated messages
|
1443
|
+
* @param {@link TeamsBotSsoPromptSettings} settings The list of scopes for which the token will have access
|
1444
|
+
* @param {@link OnBehalfOfCredentialAuthConfig} authConfig The authentication configuration.
|
1445
|
+
* @param {string} initiateLoginEndpoint Login URL for Teams to redirect to.
|
1446
|
+
* @param {string} dialogName custom dialog name
|
1447
|
+
*/
|
1448
|
+
constructor(dedupStorage, ssoPromptSettings, authConfig, initiateLoginEndpoint, dialogName) {
|
1449
|
+
super(dialogName !== null && dialogName !== void 0 ? dialogName : DIALOG_NAME);
|
1450
|
+
this.dedupStorageKeys = [];
|
1451
|
+
// Map to store the commandId and triggerPatterns, key: commandId, value: triggerPatterns
|
1452
|
+
this.commandMapping = new Map();
|
1453
|
+
if (dialogName) {
|
1454
|
+
DIALOG_NAME = dialogName;
|
1455
|
+
TEAMS_SSO_PROMPT_ID = dialogName + TEAMS_SSO_PROMPT_ID;
|
1456
|
+
COMMAND_ROUTE_DIALOG = dialogName + COMMAND_ROUTE_DIALOG;
|
1457
|
+
}
|
1458
|
+
const ssoDialog = new TeamsBotSsoPrompt(authConfig, initiateLoginEndpoint, TEAMS_SSO_PROMPT_ID, ssoPromptSettings);
|
1459
|
+
this.addDialog(ssoDialog);
|
1460
|
+
this.initialDialogId = COMMAND_ROUTE_DIALOG;
|
1461
|
+
this.dedupStorage = dedupStorage;
|
1462
|
+
this.dedupStorageKeys = [];
|
1463
|
+
const commandRouteDialog = new WaterfallDialog(COMMAND_ROUTE_DIALOG, [
|
1464
|
+
this.commandRouteStep.bind(this),
|
1465
|
+
]);
|
1466
|
+
this.addDialog(commandRouteDialog);
|
1467
|
+
}
|
1468
|
+
/**
|
1469
|
+
* Add TeamsFxBotSsoCommandHandler instance
|
1470
|
+
* @param handler {@link BotSsoExecutionDialogHandler} callback function
|
1471
|
+
* @param triggerPatterns The trigger pattern
|
1472
|
+
*/
|
1473
|
+
addCommand(handler, triggerPatterns) {
|
1474
|
+
const commandId = this.getCommandHash(triggerPatterns);
|
1475
|
+
const dialog = new WaterfallDialog(commandId, [
|
1476
|
+
this.ssoStep.bind(this),
|
1477
|
+
this.dedupStep.bind(this),
|
1478
|
+
async (stepContext) => {
|
1479
|
+
const tokenResponse = stepContext.result.tokenResponse;
|
1480
|
+
const context = stepContext.context;
|
1481
|
+
const message = stepContext.result.message;
|
1482
|
+
try {
|
1483
|
+
if (tokenResponse) {
|
1484
|
+
await handler(context, tokenResponse, message);
|
1485
|
+
}
|
1486
|
+
else {
|
1487
|
+
throw new Error(ErrorMessage.FailedToRetrieveSsoToken);
|
1488
|
+
}
|
1489
|
+
return await stepContext.endDialog();
|
1490
|
+
}
|
1491
|
+
catch (error) {
|
1492
|
+
const errorMsg = formatString(ErrorMessage.FailedToProcessSsoHandler, error.message);
|
1493
|
+
internalLogger.error(errorMsg);
|
1494
|
+
return await stepContext.endDialog(new ErrorWithCode(errorMsg, ErrorCode.FailedToProcessSsoHandler));
|
1495
|
+
}
|
1496
|
+
},
|
1497
|
+
]);
|
1498
|
+
this.commandMapping.set(commandId, triggerPatterns);
|
1499
|
+
this.addDialog(dialog);
|
1500
|
+
}
|
1501
|
+
getCommandHash(patterns) {
|
1502
|
+
const expressions = Array.isArray(patterns) ? patterns : [patterns];
|
1503
|
+
const patternStr = expressions.join();
|
1504
|
+
const patternStrWithoutSpecialChar = patternStr.replace(/[^a-zA-Z0-9]/g, "");
|
1505
|
+
const hash = createHash("sha256").update(patternStr).digest("hex").toLowerCase();
|
1506
|
+
return patternStrWithoutSpecialChar + hash;
|
1507
|
+
}
|
1508
|
+
/**
|
1509
|
+
* The run method handles the incoming activity (in the form of a DialogContext) and passes it through the dialog system.
|
1510
|
+
*
|
1511
|
+
* @param context The context object for the current turn.
|
1512
|
+
* @param accessor The instance of StatePropertyAccessor for dialog system.
|
1513
|
+
*/
|
1514
|
+
async run(context, accessor) {
|
1515
|
+
const dialogSet = new DialogSet(accessor);
|
1516
|
+
dialogSet.add(this);
|
1517
|
+
const dialogContext = await dialogSet.createContext(context);
|
1518
|
+
this.ensureMsTeamsChannel(dialogContext);
|
1519
|
+
const results = await dialogContext.continueDialog();
|
1520
|
+
if (results && results.status === DialogTurnStatus.empty) {
|
1521
|
+
await dialogContext.beginDialog(this.id);
|
1522
|
+
}
|
1523
|
+
else if (results &&
|
1524
|
+
results.status === DialogTurnStatus.complete &&
|
1525
|
+
results.result instanceof Error) {
|
1526
|
+
throw results.result;
|
1527
|
+
}
|
1528
|
+
}
|
1529
|
+
getActivityText(activity) {
|
1530
|
+
let text = activity.text;
|
1531
|
+
const removedMentionText = TurnContext.removeRecipientMention(activity);
|
1532
|
+
if (removedMentionText) {
|
1533
|
+
text = removedMentionText
|
1534
|
+
.toLowerCase()
|
1535
|
+
.replace(/\n|\r\n/g, "")
|
1536
|
+
.trim();
|
1537
|
+
}
|
1538
|
+
return text;
|
1539
|
+
}
|
1540
|
+
async commandRouteStep(stepContext) {
|
1541
|
+
const turnContext = stepContext.context;
|
1542
|
+
const text = this.getActivityText(turnContext.activity);
|
1543
|
+
const commandId = this.getMatchesCommandId(text);
|
1544
|
+
if (commandId) {
|
1545
|
+
return await stepContext.beginDialog(commandId);
|
1546
|
+
}
|
1547
|
+
const errorMsg = formatString(ErrorMessage.CannotFindCommand, turnContext.activity.text);
|
1548
|
+
internalLogger.error(errorMsg);
|
1549
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.CannotFindCommand);
|
1550
|
+
}
|
1551
|
+
async ssoStep(stepContext) {
|
1552
|
+
try {
|
1553
|
+
const turnContext = stepContext.context;
|
1554
|
+
const text = this.getActivityText(turnContext.activity);
|
1555
|
+
const message = {
|
1556
|
+
text,
|
1557
|
+
};
|
1558
|
+
stepContext.options.commandMessage = message;
|
1559
|
+
return await stepContext.beginDialog(TEAMS_SSO_PROMPT_ID);
|
1560
|
+
}
|
1561
|
+
catch (error) {
|
1562
|
+
const errorMsg = formatString(ErrorMessage.FailedToRunSsoStep, error.message);
|
1563
|
+
internalLogger.error(errorMsg);
|
1564
|
+
return await stepContext.endDialog(new ErrorWithCode(errorMsg, ErrorCode.FailedToRunSsoStep));
|
1565
|
+
}
|
1566
|
+
}
|
1567
|
+
async dedupStep(stepContext) {
|
1568
|
+
const tokenResponse = stepContext.result;
|
1569
|
+
if (!tokenResponse) {
|
1570
|
+
internalLogger.error(ErrorMessage.FailedToRetrieveSsoToken);
|
1571
|
+
return await stepContext.endDialog(new ErrorWithCode(ErrorMessage.FailedToRetrieveSsoToken, ErrorCode.FailedToRunSsoStep));
|
1572
|
+
}
|
1573
|
+
try {
|
1574
|
+
// Only dedup after ssoStep to make sure that all Teams client would receive the login request
|
1575
|
+
if (tokenResponse && (await this.shouldDedup(stepContext.context))) {
|
1576
|
+
return Dialog.EndOfTurn;
|
1577
|
+
}
|
1578
|
+
return await stepContext.next({
|
1579
|
+
tokenResponse,
|
1580
|
+
message: stepContext.options.commandMessage,
|
1581
|
+
});
|
1582
|
+
}
|
1583
|
+
catch (error) {
|
1584
|
+
const errorMsg = formatString(ErrorMessage.FailedToRunDedupStep, error.message);
|
1585
|
+
internalLogger.error(errorMsg);
|
1586
|
+
return await stepContext.endDialog(new ErrorWithCode(errorMsg, ErrorCode.FailedToRunDedupStep));
|
1587
|
+
}
|
1588
|
+
}
|
1589
|
+
/**
|
1590
|
+
* Called when the component is ending.
|
1591
|
+
*
|
1592
|
+
* @param context Context for the current turn of conversation.
|
1593
|
+
*/
|
1594
|
+
async onEndDialog(context) {
|
1595
|
+
const conversationId = context.activity.conversation.id;
|
1596
|
+
const currentDedupKeys = this.dedupStorageKeys.filter((key) => key.indexOf(conversationId) > 0);
|
1597
|
+
await this.dedupStorage.delete(currentDedupKeys);
|
1598
|
+
this.dedupStorageKeys = this.dedupStorageKeys.filter((key) => key.indexOf(conversationId) < 0);
|
1599
|
+
}
|
1600
|
+
/**
|
1601
|
+
* If a user is signed into multiple Teams clients, the Bot might receive a "signin/tokenExchange" from each client.
|
1602
|
+
* Each token exchange request for a specific user login will have an identical activity.value.Id.
|
1603
|
+
* Only one of these token exchange requests should be processed by the bot. For a distributed bot in production,
|
1604
|
+
* this requires a distributed storage to ensure only one token exchange is processed.
|
1605
|
+
* @param context Context for the current turn of conversation.
|
1606
|
+
* @returns boolean value indicate whether the message should be removed
|
1607
|
+
*/
|
1608
|
+
async shouldDedup(context) {
|
1609
|
+
const storeItem = {
|
1610
|
+
eTag: context.activity.value.id,
|
1611
|
+
};
|
1612
|
+
const key = this.getStorageKey(context);
|
1613
|
+
const storeItems = { [key]: storeItem };
|
1614
|
+
try {
|
1615
|
+
await this.dedupStorage.write(storeItems);
|
1616
|
+
this.dedupStorageKeys.push(key);
|
1617
|
+
}
|
1618
|
+
catch (err) {
|
1619
|
+
if (err instanceof Error && err.message.indexOf("eTag conflict")) {
|
1620
|
+
return true;
|
1621
|
+
}
|
1622
|
+
throw err;
|
1623
|
+
}
|
1624
|
+
return false;
|
1625
|
+
}
|
1626
|
+
getStorageKey(context) {
|
1627
|
+
if (!context || !context.activity || !context.activity.conversation) {
|
1628
|
+
throw new Error("Invalid context, can not get storage key!");
|
1629
|
+
}
|
1630
|
+
const activity = context.activity;
|
1631
|
+
const channelId = activity.channelId;
|
1632
|
+
const conversationId = activity.conversation.id;
|
1633
|
+
if (activity.type !== ActivityTypes.Invoke || activity.name !== tokenExchangeOperationName) {
|
1634
|
+
throw new Error("TokenExchangeState can only be used with Invokes of signin/tokenExchange.");
|
1635
|
+
}
|
1636
|
+
const value = activity.value;
|
1637
|
+
if (!value || !value.id) {
|
1638
|
+
throw new Error("Invalid signin/tokenExchange. Missing activity.value.id.");
|
1639
|
+
}
|
1640
|
+
return `${channelId}/${conversationId}/${value.id}`;
|
1641
|
+
}
|
1642
|
+
matchPattern(pattern, text) {
|
1643
|
+
if (text) {
|
1644
|
+
if (typeof pattern === "string") {
|
1645
|
+
const regExp = new RegExp(pattern, "i");
|
1646
|
+
return regExp.test(text);
|
1647
|
+
}
|
1648
|
+
if (pattern instanceof RegExp) {
|
1649
|
+
const matches = text.match(pattern);
|
1650
|
+
return matches !== null && matches !== void 0 ? matches : false;
|
1651
|
+
}
|
1652
|
+
}
|
1653
|
+
return false;
|
1654
|
+
}
|
1655
|
+
isPatternMatched(patterns, text) {
|
1656
|
+
const expressions = Array.isArray(patterns) ? patterns : [patterns];
|
1657
|
+
for (const ex of expressions) {
|
1658
|
+
const matches = this.matchPattern(ex, text);
|
1659
|
+
return !!matches;
|
1660
|
+
}
|
1661
|
+
return false;
|
1662
|
+
}
|
1663
|
+
getMatchesCommandId(text) {
|
1664
|
+
for (const command of this.commandMapping) {
|
1665
|
+
const pattern = command[1];
|
1666
|
+
if (this.isPatternMatched(pattern, text)) {
|
1667
|
+
return command[0];
|
1668
|
+
}
|
1669
|
+
}
|
1670
|
+
return undefined;
|
1671
|
+
}
|
1672
|
+
/**
|
1673
|
+
* Ensure bot is running in MS Teams since TeamsBotSsoPrompt is only supported in MS Teams channel.
|
1674
|
+
* @param dc dialog context
|
1675
|
+
* @throws {@link ErrorCode|ChannelNotSupported} if bot channel is not MS Teams
|
1676
|
+
* @internal
|
1677
|
+
*/
|
1678
|
+
ensureMsTeamsChannel(dc) {
|
1679
|
+
if (dc.context.activity.channelId != Channels.Msteams) {
|
1680
|
+
const errorMsg = formatString(ErrorMessage.OnlyMSTeamsChannelSupported, "SSO execution dialog");
|
1681
|
+
internalLogger.error(errorMsg);
|
1682
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.ChannelNotSupported);
|
1683
|
+
}
|
1684
|
+
}
|
1685
|
+
}
|
1686
|
+
|
1687
|
+
// Copyright (c) Microsoft Corporation.
|
1688
|
+
/**
|
1689
|
+
* Provides utility method to build bot message with cards that supported in Teams.
|
1690
|
+
*/
|
1691
|
+
class MessageBuilder {
|
1692
|
+
/**
|
1693
|
+
* Build a bot message activity attached with adaptive card.
|
1694
|
+
*
|
1695
|
+
* @param cardTemplate The adaptive card template.
|
1696
|
+
* @param data card data used to render the template.
|
1697
|
+
* @returns A bot message activity attached with an adaptive card.
|
1698
|
+
*
|
1699
|
+
* @example
|
1700
|
+
* ```javascript
|
1701
|
+
* const cardTemplate = {
|
1702
|
+
* type: "AdaptiveCard",
|
1703
|
+
* body: [
|
1704
|
+
* {
|
1705
|
+
* "type": "TextBlock",
|
1706
|
+
* "text": "${title}",
|
1707
|
+
* "size": "Large"
|
1708
|
+
* },
|
1709
|
+
* {
|
1710
|
+
* "type": "TextBlock",
|
1711
|
+
* "text": "${description}"
|
1712
|
+
* }],
|
1713
|
+
* $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
|
1714
|
+
* version: "1.4"
|
1715
|
+
* };
|
1716
|
+
*
|
1717
|
+
* type CardData = {
|
1718
|
+
* title: string,
|
1719
|
+
* description: string
|
1720
|
+
* };
|
1721
|
+
* const card = MessageBuilder.attachAdaptiveCard<CardData>(
|
1722
|
+
* cardTemplate, {
|
1723
|
+
* title: "sample card title",
|
1724
|
+
* description: "sample card description"
|
1725
|
+
* });
|
1726
|
+
* ```
|
1727
|
+
*/
|
1728
|
+
static attachAdaptiveCard(cardTemplate, data) {
|
1729
|
+
const context = {
|
1730
|
+
$root: data,
|
1731
|
+
};
|
1732
|
+
return {
|
1733
|
+
attachments: [CardFactory.adaptiveCard(new ACData.Template(cardTemplate).expand(context))],
|
1734
|
+
};
|
1735
|
+
}
|
1736
|
+
/**
|
1737
|
+
* Build a bot message activity attached with an adaptive card.
|
1738
|
+
*
|
1739
|
+
* @param card The adaptive card content.
|
1740
|
+
* @returns A bot message activity attached with an adaptive card.
|
1741
|
+
*/
|
1742
|
+
static attachAdaptiveCardWithoutData(card) {
|
1743
|
+
return {
|
1744
|
+
attachments: [CardFactory.adaptiveCard(card)],
|
1745
|
+
};
|
1746
|
+
}
|
1747
|
+
/**
|
1748
|
+
* Build a bot message activity attached with an hero card.
|
1749
|
+
*
|
1750
|
+
* @param title The card title.
|
1751
|
+
* @param images Optional. The array of images to include on the card.
|
1752
|
+
* @param buttons Optional. The array of buttons to include on the card. Each `string` in the array
|
1753
|
+
* is converted to an `imBack` button with a title and value set to the value of the string.
|
1754
|
+
* @param other Optional. Any additional properties to include on the card.
|
1755
|
+
*
|
1756
|
+
* @returns A bot message activity attached with a hero card.
|
1757
|
+
*
|
1758
|
+
* @example
|
1759
|
+
* ```javascript
|
1760
|
+
* const message = MessageBuilder.attachHeroCard(
|
1761
|
+
* 'sample title',
|
1762
|
+
* ['https://example.com/sample.jpg'],
|
1763
|
+
* ['action']
|
1764
|
+
* );
|
1765
|
+
* ```
|
1766
|
+
*/
|
1767
|
+
static attachHeroCard(title, images, buttons, other) {
|
1768
|
+
return MessageBuilder.attachContent(CardFactory.heroCard(title, images, buttons, other));
|
1769
|
+
}
|
1770
|
+
/**
|
1771
|
+
* Returns an attachment for a sign-in card.
|
1772
|
+
*
|
1773
|
+
* @param title The title for the card's sign-in button.
|
1774
|
+
* @param url The URL of the sign-in page to use.
|
1775
|
+
* @param text Optional. Additional text to include on the card.
|
1776
|
+
*
|
1777
|
+
* @returns A bot message activity attached with a sign-in card.
|
1778
|
+
*
|
1779
|
+
* @remarks
|
1780
|
+
* For channels that don't natively support sign-in cards, an alternative message is rendered.
|
1781
|
+
*/
|
1782
|
+
static attachSigninCard(title, url, text) {
|
1783
|
+
return MessageBuilder.attachContent(CardFactory.signinCard(title, url, text));
|
1784
|
+
}
|
1785
|
+
/**
|
1786
|
+
* Build a bot message activity attached with an Office 365 connector card.
|
1787
|
+
*
|
1788
|
+
* @param card A description of the Office 365 connector card.
|
1789
|
+
* @returns A bot message activity attached with an Office 365 connector card.
|
1790
|
+
*/
|
1791
|
+
static attachO365ConnectorCard(card) {
|
1792
|
+
return MessageBuilder.attachContent(CardFactory.o365ConnectorCard(card));
|
1793
|
+
}
|
1794
|
+
/**
|
1795
|
+
* Build a message activity attached with a receipt card.
|
1796
|
+
* @param card A description of the receipt card.
|
1797
|
+
* @returns A message activity attached with a receipt card.
|
1798
|
+
*/
|
1799
|
+
static AttachReceiptCard(card) {
|
1800
|
+
return MessageBuilder.attachContent(CardFactory.receiptCard(card));
|
1801
|
+
}
|
1802
|
+
/**
|
1803
|
+
*
|
1804
|
+
* @param title The card title.
|
1805
|
+
* @param images Optional. The array of images to include on the card.
|
1806
|
+
* @param buttons Optional. The array of buttons to include on the card. Each `string` in the array
|
1807
|
+
* is converted to an `imBack` button with a title and value set to the value of the string.
|
1808
|
+
* @param other Optional. Any additional properties to include on the card.
|
1809
|
+
* @returns A message activity attached with a thumbnail card
|
1810
|
+
*/
|
1811
|
+
static attachThumbnailCard(title, images, buttons, other) {
|
1812
|
+
return MessageBuilder.attachContent(CardFactory.thumbnailCard(title, images, buttons, other));
|
1813
|
+
}
|
1814
|
+
/**
|
1815
|
+
* Add an attachement to a bot activity.
|
1816
|
+
* @param attachement The attachment object to attach.
|
1817
|
+
* @returns A message activity with an attachment.
|
1818
|
+
*/
|
1819
|
+
static attachContent(attachement) {
|
1820
|
+
return {
|
1821
|
+
attachments: [attachement],
|
1822
|
+
};
|
1823
|
+
}
|
1824
|
+
}
|
1825
|
+
|
1826
|
+
// Copyright (c) Microsoft Corporation.
|
1827
|
+
/**
|
1828
|
+
* Available response type for an adaptive card invoke response.
|
1829
|
+
* @internal
|
1830
|
+
*/
|
1831
|
+
var InvokeResponseType;
|
1832
|
+
(function (InvokeResponseType) {
|
1833
|
+
InvokeResponseType["AdaptiveCard"] = "application/vnd.microsoft.card.adaptive";
|
1834
|
+
InvokeResponseType["Message"] = "application/vnd.microsoft.activity.message";
|
1835
|
+
InvokeResponseType["Error"] = "application/vnd.microsoft.error";
|
1836
|
+
})(InvokeResponseType || (InvokeResponseType = {}));
|
1837
|
+
/**
|
1838
|
+
* Provides methods for formatting various invoke responses a bot can send to respond to an invoke request.
|
1839
|
+
*
|
1840
|
+
* @remarks
|
1841
|
+
* All of these functions return an `InvokeResponse` object, which can be
|
1842
|
+
* passed as input to generate a new `invokeResponse` activity.
|
1843
|
+
*
|
1844
|
+
* This example sends an invoke response that contains an adaptive card.
|
1845
|
+
*
|
1846
|
+
* ```typescript
|
1847
|
+
*
|
1848
|
+
* const myCard = {
|
1849
|
+
* type: "AdaptiveCard",
|
1850
|
+
* body: [
|
1851
|
+
* {
|
1852
|
+
* "type": "TextBlock",
|
1853
|
+
* "text": "This is a sample card"
|
1854
|
+
* }],
|
1855
|
+
* $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
|
1856
|
+
* version: "1.4"
|
1857
|
+
* };
|
1858
|
+
*
|
1859
|
+
* const invokeResponse = InvokeResponseFactory.adaptiveCard(myCard);
|
1860
|
+
* await context.sendActivity({
|
1861
|
+
* type: ActivityTypes.InvokeResponse,
|
1862
|
+
* value: invokeResponse,
|
1863
|
+
* });
|
1864
|
+
* ```
|
1865
|
+
*/
|
1866
|
+
class InvokeResponseFactory {
|
1867
|
+
/**
|
1868
|
+
* Create an invoke response from a text message.
|
1869
|
+
* The type of the invoke response is `application/vnd.microsoft.activity.message`
|
1870
|
+
* indicates the request was successfully processed.
|
1871
|
+
*
|
1872
|
+
* @param message - A text message included in a invoke response.
|
1873
|
+
*
|
1874
|
+
* @returns An `InvokeResponse` object.
|
1875
|
+
*/
|
1876
|
+
static textMessage(message) {
|
1877
|
+
if (!message) {
|
1878
|
+
throw new Error("The text message cannot be null or empty");
|
1879
|
+
}
|
1880
|
+
return {
|
1881
|
+
status: StatusCodes.OK,
|
1882
|
+
body: {
|
1883
|
+
statusCode: StatusCodes.OK,
|
1884
|
+
type: InvokeResponseType.Message,
|
1885
|
+
value: message,
|
1886
|
+
},
|
1887
|
+
};
|
1888
|
+
}
|
1889
|
+
/**
|
1890
|
+
* Create an invoke response from an adaptive card.
|
1891
|
+
*
|
1892
|
+
* The type of the invoke response is `application/vnd.microsoft.card.adaptive` indicates
|
1893
|
+
* the request was successfully processed, and the response includes an adaptive card
|
1894
|
+
* that the client should display in place of the current one.
|
1895
|
+
*
|
1896
|
+
* @param card - The adaptive card JSON payload.
|
1897
|
+
*
|
1898
|
+
* @returns An `InvokeResponse` object.
|
1899
|
+
*/
|
1900
|
+
static adaptiveCard(card) {
|
1901
|
+
if (!card) {
|
1902
|
+
throw new Error("The adaptive card content cannot be null or undefined");
|
1903
|
+
}
|
1904
|
+
return {
|
1905
|
+
status: StatusCodes.OK,
|
1906
|
+
body: {
|
1907
|
+
statusCode: StatusCodes.OK,
|
1908
|
+
type: InvokeResponseType.AdaptiveCard,
|
1909
|
+
value: card,
|
1910
|
+
},
|
1911
|
+
};
|
1912
|
+
}
|
1913
|
+
/**
|
1914
|
+
* Create an invoke response with error code and message.
|
1915
|
+
*
|
1916
|
+
* The type of the invoke response is `application/vnd.microsoft.error` indicates
|
1917
|
+
* the request was failed to processed.
|
1918
|
+
*
|
1919
|
+
* @param errorCode - The status code indicates error, available values:
|
1920
|
+
* - 400 (BadRequest): indicate the incoming request was invalid.
|
1921
|
+
* - 500 (InternalServerError): indicate an unexpected error occurred.
|
1922
|
+
* @param errorMessage - The error message.
|
1923
|
+
*
|
1924
|
+
* @returns An `InvokeResponse` object.
|
1925
|
+
*/
|
1926
|
+
static errorResponse(errorCode, errorMessage) {
|
1927
|
+
return {
|
1928
|
+
status: StatusCodes.OK,
|
1929
|
+
body: {
|
1930
|
+
statusCode: errorCode,
|
1931
|
+
type: InvokeResponseType.Error,
|
1932
|
+
value: {
|
1933
|
+
code: errorCode.toString(),
|
1934
|
+
message: errorMessage,
|
1935
|
+
},
|
1936
|
+
},
|
1937
|
+
};
|
1938
|
+
}
|
1939
|
+
/**
|
1940
|
+
* Create an invoke response with status code and response value.
|
1941
|
+
* @param statusCode - The status code.
|
1942
|
+
* @param body - The value of the response body.
|
1943
|
+
*
|
1944
|
+
* @returns An `InvokeResponse` object.
|
1945
|
+
*/
|
1946
|
+
static createInvokeResponse(statusCode, body) {
|
1947
|
+
return {
|
1948
|
+
status: statusCode,
|
1949
|
+
body: body,
|
1950
|
+
};
|
1951
|
+
}
|
1952
|
+
}
|
1953
|
+
|
1954
|
+
// Copyright (c) Microsoft Corporation.
|
1955
|
+
/**
|
1956
|
+
* Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions.
|
1957
|
+
* This method only work on MessageExtension with Query now.
|
1958
|
+
*
|
1959
|
+
* @param {OnBehalfOfCredentialAuthConfig} authConfig - User custom the message extension authentication configuration.
|
1960
|
+
* @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.
|
1961
|
+
* @param {string | string[]} scopes - The list of scopes for which the token will have access.
|
1962
|
+
*
|
1963
|
+
* @returns SignIn link SilentAuth CardAction with 200 status code.
|
1964
|
+
*/
|
1965
|
+
function getSignInResponseForMessageExtensionWithSilentAuthConfig(authConfig, initiateLoginEndpoint, scopes) {
|
1966
|
+
const scopesArray = getScopesArray(scopes);
|
1967
|
+
const signInLink = `${initiateLoginEndpoint}?scope=${encodeURI(scopesArray.join(" "))}&clientId=${authConfig.clientId}&tenantId=${authConfig.tenantId}`;
|
1968
|
+
return {
|
1969
|
+
composeExtension: {
|
1970
|
+
type: "silentAuth",
|
1971
|
+
suggestedActions: {
|
1972
|
+
actions: [
|
1973
|
+
{
|
1974
|
+
type: "openUrl",
|
1975
|
+
value: signInLink,
|
1976
|
+
title: "Message Extension OAuth",
|
1977
|
+
},
|
1978
|
+
],
|
1979
|
+
},
|
1980
|
+
},
|
1981
|
+
};
|
1982
|
+
}
|
1983
|
+
/**
|
1984
|
+
* Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions.
|
1985
|
+
* This method just a workaround for link unfurling now.
|
1986
|
+
*
|
1987
|
+
* @param {OnBehalfOfCredentialAuthConfig} authConfig - User custom the message extension authentication configuration.
|
1988
|
+
* @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.
|
1989
|
+
* @param {string | string[]} scopes - The list of scopes for which the token will have access.
|
1990
|
+
*
|
1991
|
+
* @returns SignIn link Auth CardAction with 200 status code.
|
1992
|
+
*/
|
1993
|
+
function getSignInResponseForMessageExtensionWithAuthConfig(authConfig, initiateLoginEndpoint, scopes) {
|
1994
|
+
const scopesArray = getScopesArray(scopes);
|
1995
|
+
const signInLink = `${initiateLoginEndpoint}?scope=${encodeURI(scopesArray.join(" "))}&clientId=${authConfig.clientId}&tenantId=${authConfig.tenantId}`;
|
1996
|
+
return {
|
1997
|
+
composeExtension: {
|
1998
|
+
type: "auth",
|
1999
|
+
suggestedActions: {
|
2000
|
+
actions: [
|
2001
|
+
{
|
2002
|
+
type: "openUrl",
|
2003
|
+
value: signInLink,
|
2004
|
+
title: "Message Extension OAuth",
|
2005
|
+
},
|
2006
|
+
],
|
2007
|
+
},
|
2008
|
+
},
|
2009
|
+
};
|
2010
|
+
}
|
2011
|
+
/**
|
2012
|
+
* execution in message extension with SSO token.
|
2013
|
+
*
|
2014
|
+
* @param {TurnContext} context - The context object for the current turn.
|
2015
|
+
* @param {OnBehalfOfCredentialAuthConfig} authConfig - User custom the message extension authentication configuration.
|
2016
|
+
* @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.
|
2017
|
+
* @param {string[]} scopes - The list of scopes for which the token will have access.
|
2018
|
+
* @param {function} logic - Business logic when executing the query in message extension with SSO or access token.
|
2019
|
+
*
|
2020
|
+
* @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.
|
2021
|
+
* @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.
|
2022
|
+
* @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.
|
2023
|
+
* @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
|
2024
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
|
2025
|
+
*
|
2026
|
+
* @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.
|
2027
|
+
*/
|
2028
|
+
async function executionWithTokenAndConfig(context, authConfig, initiateLoginEndpoint, scopes, logic) {
|
2029
|
+
const valueObj = context.activity.value;
|
2030
|
+
if (!valueObj.authentication || !valueObj.authentication.token) {
|
2031
|
+
internalLogger.verbose("No AccessToken in request, return silentAuth for AccessToken");
|
2032
|
+
return getSignInResponseForMessageExtensionWithSilentAuthConfig(authConfig, initiateLoginEndpoint, scopes);
|
2033
|
+
}
|
2034
|
+
try {
|
2035
|
+
const credential = new OnBehalfOfUserCredential(valueObj.authentication.token, authConfig);
|
2036
|
+
const token = await credential.getToken(scopes);
|
2037
|
+
const ssoTokenExpiration = parseJwt(valueObj.authentication.token).exp;
|
2038
|
+
const tokenRes = {
|
2039
|
+
ssoToken: valueObj.authentication.token,
|
2040
|
+
ssoTokenExpiration: new Date(ssoTokenExpiration * 1000).toISOString(),
|
2041
|
+
token: token.token,
|
2042
|
+
expiration: token.expiresOnTimestamp.toString(),
|
2043
|
+
connectionName: "",
|
2044
|
+
};
|
2045
|
+
if (logic) {
|
2046
|
+
return await logic(tokenRes);
|
2047
|
+
}
|
2048
|
+
}
|
2049
|
+
catch (err) {
|
2050
|
+
if (err instanceof ErrorWithCode &&
|
2051
|
+
err.code === ErrorCode.UiRequiredError &&
|
2052
|
+
context.activity.name === "composeExtension/query") {
|
2053
|
+
internalLogger.verbose("User not consent yet, return 412 to user consent first.");
|
2054
|
+
const response = { status: 412 };
|
2055
|
+
await context.sendActivity({ value: response, type: ActivityTypes.InvokeResponse });
|
2056
|
+
return;
|
2057
|
+
}
|
2058
|
+
else if (err instanceof ErrorWithCode &&
|
2059
|
+
err.code === ErrorCode.UiRequiredError &&
|
2060
|
+
context.activity.name === "composeExtension/queryLink") {
|
2061
|
+
internalLogger.verbose("User not consent yet, return auth card for user login");
|
2062
|
+
const response = getSignInResponseForMessageExtensionWithAuthConfig(authConfig, initiateLoginEndpoint, scopes);
|
2063
|
+
await context.sendActivity({
|
2064
|
+
value: { status: 200, body: response },
|
2065
|
+
type: ActivityTypes.InvokeResponse,
|
2066
|
+
});
|
2067
|
+
return;
|
2068
|
+
}
|
2069
|
+
throw err;
|
2070
|
+
}
|
2071
|
+
}
|
2072
|
+
/**
|
2073
|
+
* Users execute query in message extension with SSO or access token.
|
2074
|
+
*
|
2075
|
+
* @param {TurnContext} context - The context object for the current turn.
|
2076
|
+
* @param {OnBehalfOfCredentialAuthConfig} config - User custom the message extension authentication configuration.
|
2077
|
+
* @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.
|
2078
|
+
* @param {string| string[]} scopes - The list of scopes for which the token will have access.
|
2079
|
+
* @param {function} logic - Business logic when executing the query in message extension with SSO or access token.
|
2080
|
+
*
|
2081
|
+
* @throws {@link ErrorCode|InternalError} when User invoke not response to message extension query.
|
2082
|
+
* @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.
|
2083
|
+
* @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.
|
2084
|
+
* @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.
|
2085
|
+
* @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
|
2086
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
|
2087
|
+
*
|
2088
|
+
* @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.
|
2089
|
+
*/
|
2090
|
+
async function handleMessageExtensionQueryWithSSO(context, config, initiateLoginEndpoint, scopes, logic) {
|
2091
|
+
if (context.activity.name != "composeExtension/query") {
|
2092
|
+
internalLogger.error(ErrorMessage.OnlySupportInQueryActivity);
|
2093
|
+
throw new ErrorWithCode(formatString(ErrorMessage.OnlySupportInQueryActivity), ErrorCode.FailedOperation);
|
2094
|
+
}
|
2095
|
+
return await executionWithTokenAndConfig(context, config !== null && config !== void 0 ? config : {}, initiateLoginEndpoint, scopes, logic);
|
2096
|
+
}
|
2097
|
+
/**
|
2098
|
+
* Users execute link query in message extension with SSO or access token.
|
2099
|
+
*
|
2100
|
+
* @param {TurnContext} context - The context object for the current turn.
|
2101
|
+
* @param {OnBehalfOfCredentialAuthConfig} config - User custom the message extension authentication configuration.
|
2102
|
+
* @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.
|
2103
|
+
* @param {string| string[]} scopes - The list of scopes for which the token will have access.
|
2104
|
+
* @param {function} logic - Business logic when executing the link query in message extension with SSO or access token.
|
2105
|
+
*
|
2106
|
+
* @throws {@link ErrorCode|InternalError} when User invoke not response to message extension link query.
|
2107
|
+
* @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.
|
2108
|
+
* @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.
|
2109
|
+
* @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.
|
2110
|
+
* @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
|
2111
|
+
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
|
2112
|
+
*
|
2113
|
+
* @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.
|
2114
|
+
*/
|
2115
|
+
async function handleMessageExtensionLinkQueryWithSSO(context, config, initiateLoginEndpoint, scopes, logic) {
|
2116
|
+
if (context.activity.name != "composeExtension/queryLink") {
|
2117
|
+
internalLogger.error(ErrorMessage.OnlySupportInLinkQueryActivity);
|
2118
|
+
throw new ErrorWithCode(formatString(ErrorMessage.OnlySupportInLinkQueryActivity), ErrorCode.FailedOperation);
|
2119
|
+
}
|
2120
|
+
return await executionWithTokenAndConfig(context, config !== null && config !== void 0 ? config : {}, initiateLoginEndpoint, scopes, logic);
|
2121
|
+
}
|
2122
|
+
|
2123
|
+
// Copyright (c) Microsoft Corporation.
|
2124
|
+
/**
|
2125
|
+
* @internal
|
2126
|
+
*/
|
2127
|
+
class CardActionMiddleware {
|
2128
|
+
constructor(handlers) {
|
2129
|
+
this.actionHandlers = [];
|
2130
|
+
this.defaultMessage = "Your response was sent to the app";
|
2131
|
+
if (handlers && handlers.length > 0) {
|
2132
|
+
this.actionHandlers.push(...handlers);
|
2133
|
+
}
|
2134
|
+
}
|
2135
|
+
async onTurn(context, next) {
|
2136
|
+
var _a, _b, _c;
|
2137
|
+
if (context.activity.name === "adaptiveCard/action") {
|
2138
|
+
const action = context.activity.value.action;
|
2139
|
+
const actionVerb = action.verb;
|
2140
|
+
for (const handler of this.actionHandlers) {
|
2141
|
+
if (((_a = handler.triggerVerb) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === (actionVerb === null || actionVerb === void 0 ? void 0 : actionVerb.toLowerCase())) {
|
2142
|
+
let response;
|
2143
|
+
try {
|
2144
|
+
response = await handler.handleActionInvoked(context, action.data);
|
2145
|
+
}
|
2146
|
+
catch (error) {
|
2147
|
+
const errorResponse = InvokeResponseFactory.errorResponse(InvokeResponseErrorCode.InternalServerError, error.message);
|
2148
|
+
await this.sendInvokeResponse(context, errorResponse);
|
2149
|
+
throw error;
|
2150
|
+
}
|
2151
|
+
const responseType = (_b = response.body) === null || _b === void 0 ? void 0 : _b.type;
|
2152
|
+
switch (responseType) {
|
2153
|
+
case InvokeResponseType.AdaptiveCard:
|
2154
|
+
const card = (_c = response.body) === null || _c === void 0 ? void 0 : _c.value;
|
2155
|
+
if (!card) {
|
2156
|
+
const errorMessage = "Adaptive card content cannot be found in the response body";
|
2157
|
+
await this.sendInvokeResponse(context, InvokeResponseFactory.errorResponse(InvokeResponseErrorCode.InternalServerError, errorMessage));
|
2158
|
+
throw new Error(errorMessage);
|
2159
|
+
}
|
2160
|
+
if (card.refresh && handler.adaptiveCardResponse !== AdaptiveCardResponse.NewForAll) {
|
2161
|
+
// Card won't be refreshed with AdaptiveCardResponse.ReplaceForInteractor.
|
2162
|
+
// So set to AdaptiveCardResponse.ReplaceForAll here.
|
2163
|
+
handler.adaptiveCardResponse = AdaptiveCardResponse.ReplaceForAll;
|
2164
|
+
}
|
2165
|
+
const activity = MessageFactory.attachment(CardFactory.adaptiveCard(card));
|
2166
|
+
if (handler.adaptiveCardResponse === AdaptiveCardResponse.NewForAll) {
|
2167
|
+
await this.sendInvokeResponse(context, InvokeResponseFactory.textMessage(this.defaultMessage));
|
2168
|
+
await context.sendActivity(activity);
|
2169
|
+
}
|
2170
|
+
else if (handler.adaptiveCardResponse === AdaptiveCardResponse.ReplaceForAll) {
|
2171
|
+
activity.id = context.activity.replyToId;
|
2172
|
+
await context.updateActivity(activity);
|
2173
|
+
await this.sendInvokeResponse(context, response);
|
2174
|
+
}
|
2175
|
+
else {
|
2176
|
+
await this.sendInvokeResponse(context, response);
|
2177
|
+
}
|
2178
|
+
break;
|
2179
|
+
case InvokeResponseType.Message:
|
2180
|
+
case InvokeResponseType.Error:
|
2181
|
+
default:
|
2182
|
+
await this.sendInvokeResponse(context, response);
|
2183
|
+
break;
|
2184
|
+
}
|
2185
|
+
break;
|
2186
|
+
}
|
2187
|
+
}
|
2188
|
+
}
|
2189
|
+
await next();
|
2190
|
+
}
|
2191
|
+
async sendInvokeResponse(context, response) {
|
2192
|
+
await context.sendActivity({
|
2193
|
+
type: ActivityTypes.InvokeResponse,
|
2194
|
+
value: response,
|
2195
|
+
});
|
2196
|
+
}
|
2197
|
+
}
|
2198
|
+
|
2199
|
+
/**
|
2200
|
+
* A card action bot to respond to adaptive card universal actions.
|
2201
|
+
*/
|
2202
|
+
class CardActionBot {
|
2203
|
+
/**
|
2204
|
+
* Create a new instance of the `CardActionBot`.
|
2205
|
+
*
|
2206
|
+
* @param adapter - The bound `CloudAdapter`.
|
2207
|
+
* @param options - The initialize options.
|
2208
|
+
*/
|
2209
|
+
constructor(adapter, options) {
|
2210
|
+
this.middleware = new CardActionMiddleware(options === null || options === void 0 ? void 0 : options.actions);
|
2211
|
+
this.adapter = adapter.use(this.middleware);
|
2212
|
+
}
|
2213
|
+
/**
|
2214
|
+
* Register a card action handler to the bot.
|
2215
|
+
*
|
2216
|
+
* @param actionHandler - A card action handler to be registered.
|
2217
|
+
*/
|
2218
|
+
registerHandler(actionHandler) {
|
2219
|
+
if (actionHandler) {
|
2220
|
+
this.middleware.actionHandlers.push(actionHandler);
|
2221
|
+
}
|
2222
|
+
}
|
2223
|
+
/**
|
2224
|
+
* Register card action handlers to the bot.
|
2225
|
+
*
|
2226
|
+
* @param actionHandlers - A set of card action handlers to be registered.
|
2227
|
+
*/
|
2228
|
+
registerHandlers(actionHandlers) {
|
2229
|
+
if (actionHandlers) {
|
2230
|
+
this.middleware.actionHandlers.push(...actionHandlers);
|
2231
|
+
}
|
2232
|
+
}
|
2233
|
+
}
|
2234
|
+
|
2235
|
+
// Copyright (c) Microsoft Corporation.
|
2236
|
+
/**
|
2237
|
+
* @internal
|
2238
|
+
*/
|
2239
|
+
class CommandResponseMiddleware {
|
2240
|
+
constructor(handlers, ssoHandlers, activityHandler) {
|
2241
|
+
this.commandHandlers = [];
|
2242
|
+
this.ssoCommandHandlers = [];
|
2243
|
+
handlers = handlers !== null && handlers !== void 0 ? handlers : [];
|
2244
|
+
ssoHandlers = ssoHandlers !== null && ssoHandlers !== void 0 ? ssoHandlers : [];
|
2245
|
+
this.hasSsoCommand = ssoHandlers.length > 0;
|
2246
|
+
this.ssoActivityHandler = activityHandler;
|
2247
|
+
if (this.hasSsoCommand && !this.ssoActivityHandler) {
|
2248
|
+
internalLogger.error(ErrorMessage.SsoActivityHandlerIsNull);
|
2249
|
+
throw new ErrorWithCode(ErrorMessage.SsoActivityHandlerIsNull, ErrorCode.SsoActivityHandlerIsUndefined);
|
2250
|
+
}
|
2251
|
+
this.commandHandlers.push(...handlers);
|
2252
|
+
for (const ssoHandler of ssoHandlers) {
|
2253
|
+
this.addSsoCommand(ssoHandler);
|
2254
|
+
}
|
2255
|
+
}
|
2256
|
+
addSsoCommand(ssoHandler) {
|
2257
|
+
var _a;
|
2258
|
+
(_a = this.ssoActivityHandler) === null || _a === void 0 ? void 0 : _a.addCommand(async (context, tokenResponse, message) => {
|
2259
|
+
const matchResult = this.shouldTrigger(ssoHandler.triggerPatterns, message.text);
|
2260
|
+
message.matches = Array.isArray(matchResult) ? matchResult : void 0;
|
2261
|
+
const response = await ssoHandler.handleCommandReceived(context, message, tokenResponse);
|
2262
|
+
await this.processResponse(context, response);
|
2263
|
+
}, ssoHandler.triggerPatterns);
|
2264
|
+
this.ssoCommandHandlers.push(ssoHandler);
|
2265
|
+
this.hasSsoCommand = true;
|
2266
|
+
}
|
2267
|
+
async onTurn(context, next) {
|
2268
|
+
var _a, _b;
|
2269
|
+
if (context.activity.type === ActivityTypes.Message) {
|
2270
|
+
// Invoke corresponding command handler for the command response
|
2271
|
+
const commandText = this.getActivityText(context.activity);
|
2272
|
+
let alreadyProcessed = false;
|
2273
|
+
for (const handler of this.commandHandlers) {
|
2274
|
+
const matchResult = this.shouldTrigger(handler.triggerPatterns, commandText);
|
2275
|
+
// It is important to note that the command bot will stop processing handlers
|
2276
|
+
// when the first command handler is matched.
|
2277
|
+
if (!!matchResult) {
|
2278
|
+
const message = {
|
2279
|
+
text: commandText,
|
2280
|
+
};
|
2281
|
+
message.matches = Array.isArray(matchResult) ? matchResult : void 0;
|
2282
|
+
const response = await handler.handleCommandReceived(context, message);
|
2283
|
+
await this.processResponse(context, response);
|
2284
|
+
alreadyProcessed = true;
|
2285
|
+
break;
|
2286
|
+
}
|
2287
|
+
}
|
2288
|
+
if (!alreadyProcessed) {
|
2289
|
+
for (const handler of this.ssoCommandHandlers) {
|
2290
|
+
const matchResult = this.shouldTrigger(handler.triggerPatterns, commandText);
|
2291
|
+
if (!!matchResult) {
|
2292
|
+
await ((_a = this.ssoActivityHandler) === null || _a === void 0 ? void 0 : _a.run(context));
|
2293
|
+
break;
|
2294
|
+
}
|
2295
|
+
}
|
2296
|
+
}
|
2297
|
+
}
|
2298
|
+
else {
|
2299
|
+
if (this.hasSsoCommand) {
|
2300
|
+
await ((_b = this.ssoActivityHandler) === null || _b === void 0 ? void 0 : _b.run(context));
|
2301
|
+
}
|
2302
|
+
}
|
2303
|
+
await next();
|
2304
|
+
}
|
2305
|
+
async processResponse(context, response) {
|
2306
|
+
if (typeof response === "string") {
|
2307
|
+
await context.sendActivity(response);
|
2308
|
+
}
|
2309
|
+
else {
|
2310
|
+
const replyActivity = response;
|
2311
|
+
if (replyActivity) {
|
2312
|
+
await context.sendActivity(replyActivity);
|
2313
|
+
}
|
2314
|
+
}
|
2315
|
+
}
|
2316
|
+
matchPattern(pattern, text) {
|
2317
|
+
if (text) {
|
2318
|
+
if (typeof pattern === "string") {
|
2319
|
+
const regExp = new RegExp(pattern, "i");
|
2320
|
+
return regExp.test(text);
|
2321
|
+
}
|
2322
|
+
if (pattern instanceof RegExp) {
|
2323
|
+
const matches = text.match(pattern);
|
2324
|
+
return matches !== null && matches !== void 0 ? matches : false;
|
2325
|
+
}
|
2326
|
+
}
|
2327
|
+
return false;
|
2328
|
+
}
|
2329
|
+
shouldTrigger(patterns, text) {
|
2330
|
+
const expressions = Array.isArray(patterns) ? patterns : [patterns];
|
2331
|
+
for (const ex of expressions) {
|
2332
|
+
const arg = this.matchPattern(ex, text);
|
2333
|
+
if (arg)
|
2334
|
+
return arg;
|
2335
|
+
}
|
2336
|
+
return false;
|
2337
|
+
}
|
2338
|
+
getActivityText(activity) {
|
2339
|
+
let text = activity.text;
|
2340
|
+
const removedMentionText = TurnContext.removeRecipientMention(activity);
|
2341
|
+
if (removedMentionText) {
|
2342
|
+
text = removedMentionText
|
2343
|
+
.toLowerCase()
|
2344
|
+
.replace(/\n|\r\n/g, "")
|
2345
|
+
.trim();
|
2346
|
+
}
|
2347
|
+
return text;
|
2348
|
+
}
|
2349
|
+
}
|
2350
|
+
|
2351
|
+
// Copyright (c) Microsoft Corporation.
|
2352
|
+
/**
|
2353
|
+
* A command bot for receiving commands and sending responses in Teams.
|
2354
|
+
*
|
2355
|
+
* @remarks
|
2356
|
+
* Ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.
|
2357
|
+
*/
|
2358
|
+
class CommandBot {
|
2359
|
+
// eslint-disable-next-line no-secrets/no-secrets
|
2360
|
+
/**
|
2361
|
+
* Create a new instance of the `CommandBot`.
|
2362
|
+
*
|
2363
|
+
* @param adapter - The bound `CloudAdapter`.
|
2364
|
+
* @param options - The initialize options
|
2365
|
+
* @param ssoCommandActivityHandler - SSO execution activity handler.
|
2366
|
+
* @param ssoConfig - SSO configuration for Bot SSO.
|
2367
|
+
*/
|
2368
|
+
constructor(adapter, options, ssoCommandActivityHandler, ssoConfig) {
|
2369
|
+
this.ssoConfig = ssoConfig;
|
2370
|
+
this.middleware = new CommandResponseMiddleware(options === null || options === void 0 ? void 0 : options.commands, options === null || options === void 0 ? void 0 : options.ssoCommands, ssoCommandActivityHandler);
|
2371
|
+
this.adapter = adapter.use(this.middleware);
|
2372
|
+
}
|
2373
|
+
/**
|
2374
|
+
* Register a command into the command bot.
|
2375
|
+
*
|
2376
|
+
* @param command - The command to be registered.
|
2377
|
+
*/
|
2378
|
+
registerCommand(command) {
|
2379
|
+
if (command) {
|
2380
|
+
this.middleware.commandHandlers.push(command);
|
2381
|
+
}
|
2382
|
+
}
|
2383
|
+
/**
|
2384
|
+
* Register commands into the command bot.
|
2385
|
+
*
|
2386
|
+
* @param commands - The commands to be registered.
|
2387
|
+
*/
|
2388
|
+
registerCommands(commands) {
|
2389
|
+
if (commands) {
|
2390
|
+
this.middleware.commandHandlers.push(...commands);
|
2391
|
+
}
|
2392
|
+
}
|
2393
|
+
/**
|
2394
|
+
* Register a sso command into the command bot.
|
2395
|
+
*
|
2396
|
+
* @param ssoCommand - The sso command to be registered.
|
2397
|
+
*/
|
2398
|
+
registerSsoCommand(ssoCommand) {
|
2399
|
+
this.validateSsoActivityHandler();
|
2400
|
+
this.middleware.addSsoCommand(ssoCommand);
|
2401
|
+
}
|
2402
|
+
/**
|
2403
|
+
* Register sso commands into the command bot.
|
2404
|
+
*
|
2405
|
+
* @param ssoCommands - The sso commands to be registered.
|
2406
|
+
*/
|
2407
|
+
registerSsoCommands(ssoCommands) {
|
2408
|
+
if (ssoCommands.length > 0) {
|
2409
|
+
this.validateSsoActivityHandler();
|
2410
|
+
for (const ssoCommand of ssoCommands) {
|
2411
|
+
this.middleware.addSsoCommand(ssoCommand);
|
2412
|
+
}
|
2413
|
+
}
|
2414
|
+
}
|
2415
|
+
validateSsoActivityHandler() {
|
2416
|
+
if (!this.middleware.ssoActivityHandler) {
|
2417
|
+
internalLogger.error(ErrorMessage.SsoActivityHandlerIsNull);
|
2418
|
+
throw new ErrorWithCode(ErrorMessage.SsoActivityHandlerIsNull, ErrorCode.SsoActivityHandlerIsUndefined);
|
2419
|
+
}
|
2420
|
+
}
|
2421
|
+
}
|
2422
|
+
|
2423
|
+
// Copyright (c) Microsoft Corporation.
|
2424
|
+
/**
|
2425
|
+
* @internal
|
2426
|
+
*/
|
2427
|
+
function cloneConversation(conversation) {
|
2428
|
+
return JSON.parse(JSON.stringify(conversation));
|
2429
|
+
}
|
2430
|
+
/**
|
2431
|
+
* @internal
|
2432
|
+
*/
|
2433
|
+
function getKey(reference) {
|
2434
|
+
var _a, _b;
|
2435
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
2436
|
+
return `_${(_a = reference.conversation) === null || _a === void 0 ? void 0 : _a.tenantId}_${(_b = reference.conversation) === null || _b === void 0 ? void 0 : _b.id}`;
|
2437
|
+
}
|
2438
|
+
/**
|
2439
|
+
* @internal
|
2440
|
+
*/
|
2441
|
+
function getTargetType(conversationReference) {
|
2442
|
+
var _a;
|
2443
|
+
const conversationType = (_a = conversationReference.conversation) === null || _a === void 0 ? void 0 : _a.conversationType;
|
2444
|
+
if (conversationType === "personal") {
|
2445
|
+
return NotificationTargetType.Person;
|
2446
|
+
}
|
2447
|
+
else if (conversationType === "groupChat") {
|
2448
|
+
return NotificationTargetType.Group;
|
2449
|
+
}
|
2450
|
+
else if (conversationType === "channel") {
|
2451
|
+
return NotificationTargetType.Channel;
|
2452
|
+
}
|
2453
|
+
else {
|
2454
|
+
return undefined;
|
2455
|
+
}
|
2456
|
+
}
|
2457
|
+
/**
|
2458
|
+
* @internal
|
2459
|
+
*/
|
2460
|
+
function getTeamsBotInstallationId(context) {
|
2461
|
+
var _a, _b, _c;
|
2462
|
+
const teamId = (_c = (_b = (_a = context.activity) === null || _a === void 0 ? void 0 : _a.channelData) === null || _b === void 0 ? void 0 : _b.team) === null || _c === void 0 ? void 0 : _c.id;
|
2463
|
+
if (teamId) {
|
2464
|
+
return teamId;
|
2465
|
+
}
|
2466
|
+
// Fallback to use conversation id.
|
2467
|
+
// The conversation id is equal to team id only when the bot app is installed into the General channel.
|
2468
|
+
if (context.activity.conversation.name === undefined) {
|
2469
|
+
return context.activity.conversation.id;
|
2470
|
+
}
|
2471
|
+
return undefined;
|
2472
|
+
}
|
2473
|
+
|
2474
|
+
// Copyright (c) Microsoft Corporation.
|
2475
|
+
/**
|
2476
|
+
* @internal
|
2477
|
+
*/
|
2478
|
+
var ActivityType;
|
2479
|
+
(function (ActivityType) {
|
2480
|
+
ActivityType[ActivityType["CurrentBotInstalled"] = 0] = "CurrentBotInstalled";
|
2481
|
+
ActivityType[ActivityType["CurrentBotMessaged"] = 1] = "CurrentBotMessaged";
|
2482
|
+
ActivityType[ActivityType["CurrentBotUninstalled"] = 2] = "CurrentBotUninstalled";
|
2483
|
+
ActivityType[ActivityType["TeamDeleted"] = 3] = "TeamDeleted";
|
2484
|
+
ActivityType[ActivityType["TeamRestored"] = 4] = "TeamRestored";
|
2485
|
+
ActivityType[ActivityType["Unknown"] = 5] = "Unknown";
|
2486
|
+
})(ActivityType || (ActivityType = {}));
|
2487
|
+
/**
|
2488
|
+
* @internal
|
2489
|
+
*/
|
2490
|
+
class NotificationMiddleware {
|
2491
|
+
constructor(options) {
|
2492
|
+
this.conversationReferenceStore = options.conversationReferenceStore;
|
2493
|
+
}
|
2494
|
+
async onTurn(context, next) {
|
2495
|
+
const type = this.classifyActivity(context.activity);
|
2496
|
+
switch (type) {
|
2497
|
+
case ActivityType.CurrentBotInstalled:
|
2498
|
+
case ActivityType.TeamRestored: {
|
2499
|
+
const reference = TurnContext.getConversationReference(context.activity);
|
2500
|
+
await this.conversationReferenceStore.add(getKey(reference), reference, {
|
2501
|
+
overwrite: true,
|
2502
|
+
});
|
2503
|
+
break;
|
2504
|
+
}
|
2505
|
+
case ActivityType.CurrentBotMessaged: {
|
2506
|
+
await this.tryAddMessagedReference(context);
|
2507
|
+
break;
|
2508
|
+
}
|
2509
|
+
case ActivityType.CurrentBotUninstalled:
|
2510
|
+
case ActivityType.TeamDeleted: {
|
2511
|
+
const reference = TurnContext.getConversationReference(context.activity);
|
2512
|
+
await this.conversationReferenceStore.remove(getKey(reference), reference);
|
2513
|
+
break;
|
2514
|
+
}
|
2515
|
+
}
|
2516
|
+
await next();
|
2517
|
+
}
|
2518
|
+
classifyActivity(activity) {
|
2519
|
+
var _a, _b;
|
2520
|
+
const activityType = activity.type;
|
2521
|
+
if (activityType === "installationUpdate") {
|
2522
|
+
const action = (_a = activity.action) === null || _a === void 0 ? void 0 : _a.toLowerCase();
|
2523
|
+
if (action === "add" || action === "add-upgrade") {
|
2524
|
+
return ActivityType.CurrentBotInstalled;
|
2525
|
+
}
|
2526
|
+
else {
|
2527
|
+
return ActivityType.CurrentBotUninstalled;
|
2528
|
+
}
|
2529
|
+
}
|
2530
|
+
else if (activityType === "conversationUpdate") {
|
2531
|
+
const eventType = (_b = activity.channelData) === null || _b === void 0 ? void 0 : _b.eventType;
|
2532
|
+
if (eventType === "teamDeleted") {
|
2533
|
+
return ActivityType.TeamDeleted;
|
2534
|
+
}
|
2535
|
+
else if (eventType === "teamRestored") {
|
2536
|
+
return ActivityType.TeamRestored;
|
2537
|
+
}
|
2538
|
+
}
|
2539
|
+
else if (activityType === "message") {
|
2540
|
+
return ActivityType.CurrentBotMessaged;
|
2541
|
+
}
|
2542
|
+
return ActivityType.Unknown;
|
2543
|
+
}
|
2544
|
+
async tryAddMessagedReference(context) {
|
2545
|
+
var _a, _b, _c, _d, _e, _f;
|
2546
|
+
const reference = TurnContext.getConversationReference(context.activity);
|
2547
|
+
const conversationType = (_a = reference === null || reference === void 0 ? void 0 : reference.conversation) === null || _a === void 0 ? void 0 : _a.conversationType;
|
2548
|
+
if (conversationType === "personal" || conversationType === "groupChat") {
|
2549
|
+
await this.conversationReferenceStore.add(getKey(reference), reference, { overwrite: false });
|
2550
|
+
}
|
2551
|
+
else if (conversationType === "channel") {
|
2552
|
+
const teamId = (_d = (_c = (_b = context.activity) === null || _b === void 0 ? void 0 : _b.channelData) === null || _c === void 0 ? void 0 : _c.team) === null || _d === void 0 ? void 0 : _d.id;
|
2553
|
+
const channelId = (_f = (_e = context.activity.channelData) === null || _e === void 0 ? void 0 : _e.channel) === null || _f === void 0 ? void 0 : _f.id;
|
2554
|
+
// `teamId === channelId` means General channel. Ignore messaging in non-General channel.
|
2555
|
+
if (teamId !== undefined && (channelId === undefined || teamId === channelId)) {
|
2556
|
+
const teamReference = cloneConversation(reference);
|
2557
|
+
teamReference.conversation.id = teamId;
|
2558
|
+
await this.conversationReferenceStore.add(getKey(teamReference), teamReference, {
|
2559
|
+
overwrite: false,
|
2560
|
+
});
|
2561
|
+
}
|
2562
|
+
}
|
2563
|
+
}
|
2564
|
+
}
|
2565
|
+
|
2566
|
+
// Copyright (c) Microsoft Corporation.
|
2567
|
+
/**
|
2568
|
+
* @internal
|
2569
|
+
*/
|
2570
|
+
class DefaultConversationReferenceStore {
|
2571
|
+
constructor(fileDir) {
|
2572
|
+
var _a;
|
2573
|
+
this.localFileName = (_a = process.env.TEAMSFX_NOTIFICATION_STORE_FILENAME) !== null && _a !== void 0 ? _a : ".notification.localstore.json";
|
2574
|
+
this.filePath = path.resolve(fileDir, this.localFileName);
|
2575
|
+
}
|
2576
|
+
async add(key, reference, options) {
|
2577
|
+
if (options.overwrite || !(await this.storeFileExists())) {
|
2578
|
+
if (!(await this.storeFileExists())) {
|
2579
|
+
await this.writeToFile({ [key]: reference });
|
2580
|
+
}
|
2581
|
+
else {
|
2582
|
+
const data = await this.readFromFile();
|
2583
|
+
await this.writeToFile(Object.assign(data, { [key]: reference }));
|
2584
|
+
}
|
2585
|
+
return true;
|
2586
|
+
}
|
2587
|
+
return false;
|
2588
|
+
}
|
2589
|
+
async remove(key, reference) {
|
2590
|
+
if (!(await this.storeFileExists())) {
|
2591
|
+
return false;
|
2592
|
+
}
|
2593
|
+
if (await this.storeFileExists()) {
|
2594
|
+
const data = await this.readFromFile();
|
2595
|
+
if (data[key] !== undefined) {
|
2596
|
+
delete data[key];
|
2597
|
+
await this.writeToFile(data);
|
2598
|
+
}
|
2599
|
+
}
|
2600
|
+
return true;
|
2601
|
+
}
|
2602
|
+
async list(pageSize, continuationToken) {
|
2603
|
+
if (!(await this.storeFileExists())) {
|
2604
|
+
return {
|
2605
|
+
data: [],
|
2606
|
+
continuationToken: "",
|
2607
|
+
};
|
2608
|
+
}
|
2609
|
+
const fileData = await this.readFromFile();
|
2610
|
+
const data = Object.entries(fileData).map((entry) => entry[1]);
|
2611
|
+
return {
|
2612
|
+
data,
|
2613
|
+
continuationToken: "",
|
2614
|
+
};
|
2615
|
+
}
|
2616
|
+
storeFileExists() {
|
2617
|
+
return new Promise((resolve) => {
|
2618
|
+
try {
|
2619
|
+
fs.access(this.filePath, (err) => {
|
2620
|
+
if (err) {
|
2621
|
+
resolve(false);
|
2622
|
+
}
|
2623
|
+
else {
|
2624
|
+
resolve(true);
|
2625
|
+
}
|
2626
|
+
});
|
2627
|
+
}
|
2628
|
+
catch (error) {
|
2629
|
+
resolve(false);
|
2630
|
+
}
|
2631
|
+
});
|
2632
|
+
}
|
2633
|
+
readFromFile() {
|
2634
|
+
return new Promise((resolve, reject) => {
|
2635
|
+
try {
|
2636
|
+
fs.readFile(this.filePath, { encoding: "utf-8" }, (err, rawData) => {
|
2637
|
+
if (err) {
|
2638
|
+
reject(err);
|
2639
|
+
}
|
2640
|
+
else {
|
2641
|
+
resolve(JSON.parse(rawData));
|
2642
|
+
}
|
2643
|
+
});
|
2644
|
+
}
|
2645
|
+
catch (error) {
|
2646
|
+
reject(error);
|
2647
|
+
}
|
2648
|
+
});
|
2649
|
+
}
|
2650
|
+
async writeToFile(data) {
|
2651
|
+
return new Promise((resolve, reject) => {
|
2652
|
+
try {
|
2653
|
+
const rawData = JSON.stringify(data, undefined, 2);
|
2654
|
+
fs.writeFile(this.filePath, rawData, { encoding: "utf-8" }, (err) => {
|
2655
|
+
if (err) {
|
2656
|
+
reject(err);
|
2657
|
+
}
|
2658
|
+
else {
|
2659
|
+
resolve();
|
2660
|
+
}
|
2661
|
+
});
|
2662
|
+
}
|
2663
|
+
catch (error) {
|
2664
|
+
reject(error);
|
2665
|
+
}
|
2666
|
+
});
|
2667
|
+
}
|
2668
|
+
}
|
2669
|
+
|
2670
|
+
// Copyright (c) Microsoft Corporation.
|
2671
|
+
/**
|
2672
|
+
* Send a plain text message to a notification target.
|
2673
|
+
*
|
2674
|
+
* @param target - The notification target.
|
2675
|
+
* @param text - The plain text message.
|
2676
|
+
* @param onError - An optional error handler that can catch exceptions during message sending.
|
2677
|
+
* If not defined, error will be handled by `BotAdapter.onTurnError`.
|
2678
|
+
*
|
2679
|
+
* @returns The response of sending message.
|
2680
|
+
*/
|
2681
|
+
function sendMessage(target, text, onError) {
|
2682
|
+
return target.sendMessage(text, onError);
|
2683
|
+
}
|
2684
|
+
/**
|
2685
|
+
* Send an adaptive card message to a notification target.
|
2686
|
+
*
|
2687
|
+
* @param target - The notification target.
|
2688
|
+
* @param card - The adaptive card raw JSON.
|
2689
|
+
* @param onError - An optional error handler that can catch exceptions during adaptive card sending.
|
2690
|
+
* If not defined, error will be handled by `BotAdapter.onTurnError`.
|
2691
|
+
*
|
2692
|
+
* @returns The response of sending adaptive card message.
|
2693
|
+
*/
|
2694
|
+
function sendAdaptiveCard(target, card, onError) {
|
2695
|
+
return target.sendAdaptiveCard(card, onError);
|
2696
|
+
}
|
2697
|
+
/**
|
2698
|
+
* A {@link NotificationTarget} that represents a team channel.
|
2699
|
+
*
|
2700
|
+
* @remarks
|
2701
|
+
* It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
|
2702
|
+
*/
|
2703
|
+
class Channel {
|
2704
|
+
/**
|
2705
|
+
* Constructor.
|
2706
|
+
*
|
2707
|
+
* @remarks
|
2708
|
+
* It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
|
2709
|
+
*
|
2710
|
+
* @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
|
2711
|
+
* @param info - Detailed channel information.
|
2712
|
+
*/
|
2713
|
+
constructor(parent, info) {
|
2714
|
+
/**
|
2715
|
+
* Notification target type. For channel it's always "Channel".
|
2716
|
+
*/
|
2717
|
+
this.type = NotificationTargetType.Channel;
|
2718
|
+
this.parent = parent;
|
2719
|
+
this.info = info;
|
2720
|
+
}
|
2721
|
+
/**
|
2722
|
+
* Send a plain text message.
|
2723
|
+
*
|
2724
|
+
* @param text - The plain text message.
|
2725
|
+
* @param onError - An optional error handler that can catch exceptions during message sending.
|
2726
|
+
* If not defined, error will be handled by `BotAdapter.onTurnError`.
|
2727
|
+
*
|
2728
|
+
* @returns The response of sending message.
|
2729
|
+
*/
|
2730
|
+
async sendMessage(text, onError) {
|
2731
|
+
const response = {};
|
2732
|
+
await this.parent.adapter.continueConversationAsync(this.parent.botAppId, this.parent.conversationReference, async (context) => {
|
2733
|
+
const conversation = await this.newConversation(context);
|
2734
|
+
await this.parent.adapter.continueConversationAsync(this.parent.botAppId, conversation, async (ctx) => {
|
2735
|
+
try {
|
2736
|
+
const res = await ctx.sendActivity(text);
|
2737
|
+
response.id = res === null || res === void 0 ? void 0 : res.id;
|
2738
|
+
}
|
2739
|
+
catch (error) {
|
2740
|
+
if (onError) {
|
2741
|
+
await onError(ctx, error);
|
2742
|
+
}
|
2743
|
+
else {
|
2744
|
+
throw error;
|
2745
|
+
}
|
2746
|
+
}
|
2747
|
+
});
|
2748
|
+
});
|
2749
|
+
return response;
|
2750
|
+
}
|
2751
|
+
/**
|
2752
|
+
* Send an adaptive card message.
|
2753
|
+
*
|
2754
|
+
* @param card - The adaptive card raw JSON.
|
2755
|
+
* @param onError - An optional error handler that can catch exceptions during adaptive card sending.
|
2756
|
+
* If not defined, error will be handled by `BotAdapter.onTurnError`.
|
2757
|
+
*
|
2758
|
+
* @returns The response of sending adaptive card message.
|
2759
|
+
*/
|
2760
|
+
async sendAdaptiveCard(card, onError) {
|
2761
|
+
const response = {};
|
2762
|
+
await this.parent.adapter.continueConversationAsync(this.parent.botAppId, this.parent.conversationReference, async (context) => {
|
2763
|
+
const conversation = await this.newConversation(context);
|
2764
|
+
await this.parent.adapter.continueConversationAsync(this.parent.botAppId, conversation, async (ctx) => {
|
2765
|
+
try {
|
2766
|
+
const res = await ctx.sendActivity({
|
2767
|
+
attachments: [CardFactory.adaptiveCard(card)],
|
2768
|
+
});
|
2769
|
+
response.id = res === null || res === void 0 ? void 0 : res.id;
|
2770
|
+
}
|
2771
|
+
catch (error) {
|
2772
|
+
if (onError) {
|
2773
|
+
await onError(ctx, error);
|
2774
|
+
}
|
2775
|
+
else {
|
2776
|
+
throw error;
|
2777
|
+
}
|
2778
|
+
}
|
2779
|
+
});
|
2780
|
+
});
|
2781
|
+
return response;
|
2782
|
+
}
|
2783
|
+
/**
|
2784
|
+
* @internal
|
2785
|
+
*/
|
2786
|
+
newConversation(context) {
|
2787
|
+
const reference = TurnContext.getConversationReference(context.activity);
|
2788
|
+
const channelConversation = cloneConversation(reference);
|
2789
|
+
channelConversation.conversation.id = this.info.id || "";
|
2790
|
+
return Promise.resolve(channelConversation);
|
2791
|
+
}
|
2792
|
+
}
|
2793
|
+
/**
|
2794
|
+
* A {@link NotificationTarget} that represents a team member.
|
2795
|
+
*
|
2796
|
+
* @remarks
|
2797
|
+
* It's recommended to get members from {@link TeamsBotInstallation.members()}.
|
2798
|
+
*/
|
2799
|
+
class Member {
|
2800
|
+
/**
|
2801
|
+
* Constructor.
|
2802
|
+
*
|
2803
|
+
* @remarks
|
2804
|
+
* It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
|
2805
|
+
*
|
2806
|
+
* @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
|
2807
|
+
* @param account - Detailed member account information.
|
2808
|
+
*/
|
2809
|
+
constructor(parent, account) {
|
2810
|
+
/**
|
2811
|
+
* Notification target type. For member it's always "Person".
|
2812
|
+
*/
|
2813
|
+
this.type = NotificationTargetType.Person;
|
2814
|
+
this.parent = parent;
|
2815
|
+
this.account = account;
|
2816
|
+
}
|
2817
|
+
/**
|
2818
|
+
* Send a plain text message.
|
2819
|
+
*
|
2820
|
+
* @param text - The plain text message.
|
2821
|
+
* @param onError - An optional error handler that can catch exceptions during message sending.
|
2822
|
+
* If not defined, error will be handled by `BotAdapter.onTurnError`.
|
2823
|
+
*
|
2824
|
+
* @returns The response of sending message.
|
2825
|
+
*/
|
2826
|
+
async sendMessage(text, onError) {
|
2827
|
+
const response = {};
|
2828
|
+
await this.parent.adapter.continueConversationAsync(this.parent.botAppId, this.parent.conversationReference, async (context) => {
|
2829
|
+
const conversation = await this.newConversation(context);
|
2830
|
+
await this.parent.adapter.continueConversationAsync(this.parent.botAppId, conversation, async (ctx) => {
|
2831
|
+
try {
|
2832
|
+
const res = await ctx.sendActivity(text);
|
2833
|
+
response.id = res === null || res === void 0 ? void 0 : res.id;
|
2834
|
+
}
|
2835
|
+
catch (error) {
|
2836
|
+
if (onError) {
|
2837
|
+
await onError(ctx, error);
|
2838
|
+
}
|
2839
|
+
else {
|
2840
|
+
throw error;
|
2841
|
+
}
|
2842
|
+
}
|
2843
|
+
});
|
2844
|
+
});
|
2845
|
+
return response;
|
2846
|
+
}
|
2847
|
+
/**
|
2848
|
+
* Send an adaptive card message.
|
2849
|
+
*
|
2850
|
+
* @param card - The adaptive card raw JSON.
|
2851
|
+
* @param onError - An optional error handler that can catch exceptions during adaptive card sending.
|
2852
|
+
* If not defined, error will be handled by `BotAdapter.onTurnError`.
|
2853
|
+
*
|
2854
|
+
* @returns The response of sending adaptive card message.
|
2855
|
+
*/
|
2856
|
+
async sendAdaptiveCard(card, onError) {
|
2857
|
+
const response = {};
|
2858
|
+
await this.parent.adapter.continueConversationAsync(this.parent.botAppId, this.parent.conversationReference, async (context) => {
|
2859
|
+
const conversation = await this.newConversation(context);
|
2860
|
+
await this.parent.adapter.continueConversationAsync(this.parent.botAppId, conversation, async (ctx) => {
|
2861
|
+
try {
|
2862
|
+
const res = await ctx.sendActivity({
|
2863
|
+
attachments: [CardFactory.adaptiveCard(card)],
|
2864
|
+
});
|
2865
|
+
response.id = res === null || res === void 0 ? void 0 : res.id;
|
2866
|
+
}
|
2867
|
+
catch (error) {
|
2868
|
+
if (onError) {
|
2869
|
+
await onError(ctx, error);
|
2870
|
+
}
|
2871
|
+
else {
|
2872
|
+
throw error;
|
2873
|
+
}
|
2874
|
+
}
|
2875
|
+
});
|
2876
|
+
});
|
2877
|
+
return response;
|
2878
|
+
}
|
2879
|
+
/**
|
2880
|
+
* @internal
|
2881
|
+
*/
|
2882
|
+
async newConversation(context) {
|
2883
|
+
const reference = TurnContext.getConversationReference(context.activity);
|
2884
|
+
const personalConversation = cloneConversation(reference);
|
2885
|
+
const connectorClient = context.turnState.get(this.parent.adapter.ConnectorClientKey);
|
2886
|
+
const conversation = await connectorClient.conversations.createConversation({
|
2887
|
+
isGroup: false,
|
2888
|
+
tenantId: context.activity.conversation.tenantId,
|
2889
|
+
bot: context.activity.recipient,
|
2890
|
+
members: [this.account],
|
2891
|
+
channelData: {},
|
2892
|
+
});
|
2893
|
+
personalConversation.conversation.id = conversation.id;
|
2894
|
+
return personalConversation;
|
2895
|
+
}
|
2896
|
+
}
|
2897
|
+
/**
|
2898
|
+
* A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
|
2899
|
+
* - Personal chat
|
2900
|
+
* - Group chat
|
2901
|
+
* - Team (by default the `General` channel)
|
2902
|
+
*
|
2903
|
+
* @remarks
|
2904
|
+
* It's recommended to get bot installations from {@link ConversationBot.installations()}.
|
2905
|
+
*/
|
2906
|
+
class TeamsBotInstallation {
|
2907
|
+
/**
|
2908
|
+
* Constructor
|
2909
|
+
*
|
2910
|
+
* @remarks
|
2911
|
+
* It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
|
2912
|
+
*
|
2913
|
+
* @param adapter - The bound `CloudAdapter`.
|
2914
|
+
* @param conversationReference - The bound `ConversationReference`.
|
2915
|
+
* @param botAppId - The bot app id.
|
2916
|
+
*/
|
2917
|
+
constructor(adapter, conversationReference, botAppId) {
|
2918
|
+
this.adapter = adapter;
|
2919
|
+
this.conversationReference = conversationReference;
|
2920
|
+
this.type = getTargetType(conversationReference);
|
2921
|
+
this.botAppId = botAppId;
|
2922
|
+
}
|
2923
|
+
/**
|
2924
|
+
* Send a plain text message.
|
2925
|
+
*
|
2926
|
+
* @param text - The plain text message.
|
2927
|
+
* @param onError - An optional error handler that can catch exceptions during message sending.
|
2928
|
+
* If not defined, error will be handled by `BotAdapter.onTurnError`.
|
2929
|
+
*
|
2930
|
+
* @returns The response of sending message.
|
2931
|
+
*/
|
2932
|
+
async sendMessage(text, onError) {
|
2933
|
+
const response = {};
|
2934
|
+
await this.adapter.continueConversationAsync(this.botAppId, this.conversationReference, async (context) => {
|
2935
|
+
try {
|
2936
|
+
const res = await context.sendActivity(text);
|
2937
|
+
response.id = res === null || res === void 0 ? void 0 : res.id;
|
2938
|
+
}
|
2939
|
+
catch (error) {
|
2940
|
+
if (onError) {
|
2941
|
+
await onError(context, error);
|
2942
|
+
}
|
2943
|
+
else {
|
2944
|
+
throw error;
|
2945
|
+
}
|
2946
|
+
}
|
2947
|
+
});
|
2948
|
+
return response;
|
2949
|
+
}
|
2950
|
+
/**
|
2951
|
+
* Send an adaptive card message.
|
2952
|
+
*
|
2953
|
+
* @param card - The adaptive card raw JSON.
|
2954
|
+
* @param onError - An optional error handler that can catch exceptions during adaptive card sending.
|
2955
|
+
* If not defined, error will be handled by `BotAdapter.onTurnError`.
|
2956
|
+
*
|
2957
|
+
* @returns The response of sending adaptive card message.
|
2958
|
+
*/
|
2959
|
+
async sendAdaptiveCard(card, onError) {
|
2960
|
+
const response = {};
|
2961
|
+
await this.adapter.continueConversationAsync(this.botAppId, this.conversationReference, async (context) => {
|
2962
|
+
try {
|
2963
|
+
const res = await context.sendActivity({
|
2964
|
+
attachments: [CardFactory.adaptiveCard(card)],
|
2965
|
+
});
|
2966
|
+
response.id = res === null || res === void 0 ? void 0 : res.id;
|
2967
|
+
}
|
2968
|
+
catch (error) {
|
2969
|
+
if (onError) {
|
2970
|
+
await onError(context, error);
|
2971
|
+
}
|
2972
|
+
else {
|
2973
|
+
throw error;
|
2974
|
+
}
|
2975
|
+
}
|
2976
|
+
});
|
2977
|
+
return response;
|
2978
|
+
}
|
2979
|
+
/**
|
2980
|
+
* Get channels from this bot installation.
|
2981
|
+
*
|
2982
|
+
* @returns An array of channels if bot is installed into a team, otherwise returns an empty array.
|
2983
|
+
*/
|
2984
|
+
async channels() {
|
2985
|
+
const channels = [];
|
2986
|
+
if (this.type !== NotificationTargetType.Channel) {
|
2987
|
+
return channels;
|
2988
|
+
}
|
2989
|
+
let teamsChannels = [];
|
2990
|
+
await this.adapter.continueConversationAsync(this.botAppId, this.conversationReference, async (context) => {
|
2991
|
+
const teamId = getTeamsBotInstallationId(context);
|
2992
|
+
if (teamId !== undefined) {
|
2993
|
+
teamsChannels = await TeamsInfo.getTeamChannels(context, teamId);
|
2994
|
+
}
|
2995
|
+
});
|
2996
|
+
for (const channel of teamsChannels) {
|
2997
|
+
channels.push(new Channel(this, channel));
|
2998
|
+
}
|
2999
|
+
return channels;
|
3000
|
+
}
|
3001
|
+
/**
|
3002
|
+
* Gets a pagined list of members from this bot installation.
|
3003
|
+
*
|
3004
|
+
* @param pageSize - Suggested number of entries on a page.
|
3005
|
+
* @param continuationToken - A continuation token.
|
3006
|
+
* @returns An array of members from where the bot is installed.
|
3007
|
+
*/
|
3008
|
+
async getPagedMembers(pageSize, continuationToken) {
|
3009
|
+
let result = {
|
3010
|
+
data: [],
|
3011
|
+
continuationToken: "",
|
3012
|
+
};
|
3013
|
+
await this.adapter.continueConversationAsync(this.botAppId, this.conversationReference, async (context) => {
|
3014
|
+
const pagedMembers = await TeamsInfo.getPagedMembers(context, pageSize, continuationToken);
|
3015
|
+
result = {
|
3016
|
+
data: pagedMembers.members.map((m) => new Member(this, m)),
|
3017
|
+
continuationToken: pagedMembers.continuationToken,
|
3018
|
+
};
|
3019
|
+
});
|
3020
|
+
return result;
|
3021
|
+
}
|
3022
|
+
/**
|
3023
|
+
* Get team details from this bot installation
|
3024
|
+
*
|
3025
|
+
* @returns The team details if bot is installed into a team, otherwise returns `undefined`.
|
3026
|
+
*/
|
3027
|
+
async getTeamDetails() {
|
3028
|
+
if (this.type !== NotificationTargetType.Channel) {
|
3029
|
+
return undefined;
|
3030
|
+
}
|
3031
|
+
let teamDetails;
|
3032
|
+
await this.adapter.continueConversationAsync(this.botAppId, this.conversationReference, async (context) => {
|
3033
|
+
const teamId = getTeamsBotInstallationId(context);
|
3034
|
+
if (teamId !== undefined) {
|
3035
|
+
teamDetails = await TeamsInfo.getTeamDetails(context, teamId);
|
3036
|
+
}
|
3037
|
+
});
|
3038
|
+
return teamDetails;
|
3039
|
+
}
|
3040
|
+
}
|
3041
|
+
/**
|
3042
|
+
* Provide utilities to send notification to varies targets (e.g., member, group, channel).
|
3043
|
+
*/
|
3044
|
+
class NotificationBot {
|
3045
|
+
/**
|
3046
|
+
* Constructor of the notification bot.
|
3047
|
+
*
|
3048
|
+
* @remarks
|
3049
|
+
* To ensure accuracy, it's recommended to initialize before handling any message.
|
3050
|
+
*
|
3051
|
+
* @param adapter - The bound `CloudAdapter`
|
3052
|
+
* @param options - The initialize options
|
3053
|
+
*/
|
3054
|
+
constructor(adapter, options) {
|
3055
|
+
var _a, _b;
|
3056
|
+
if (options === null || options === void 0 ? void 0 : options.store) {
|
3057
|
+
this.conversationReferenceStore = options.store;
|
3058
|
+
}
|
3059
|
+
else {
|
3060
|
+
this.conversationReferenceStore = new DefaultConversationReferenceStore(path.resolve(process.env.RUNNING_ON_AZURE === "1" ? (_a = process.env.TEMP) !== null && _a !== void 0 ? _a : "./" : "./"));
|
3061
|
+
}
|
3062
|
+
this.adapter = adapter.use(new NotificationMiddleware({
|
3063
|
+
conversationReferenceStore: this.conversationReferenceStore,
|
3064
|
+
}));
|
3065
|
+
this.botAppId = ((_b = options === null || options === void 0 ? void 0 : options.botAppId) !== null && _b !== void 0 ? _b : process.env.BOT_ID);
|
3066
|
+
}
|
3067
|
+
/**
|
3068
|
+
* Create a {@link TeamsBotInstallation} instance with conversation reference.
|
3069
|
+
*
|
3070
|
+
* @param conversationReference - The bound `ConversationReference`.
|
3071
|
+
* @returns - The {@link TeamsBotInstallation} instance or null.
|
3072
|
+
*/
|
3073
|
+
buildTeamsBotInstallation(conversationReference) {
|
3074
|
+
if (!conversationReference) {
|
3075
|
+
throw new Error("conversationReference is required.");
|
3076
|
+
}
|
3077
|
+
return new TeamsBotInstallation(this.adapter, conversationReference, this.botAppId);
|
3078
|
+
}
|
3079
|
+
/**
|
3080
|
+
* Validate the installation by getting paged memebers.
|
3081
|
+
*
|
3082
|
+
* @param conversationReference The bound `ConversationReference`.
|
3083
|
+
* @returns Returns false if recieves `BotNotInConversationRoster` error, otherwise returns true.
|
3084
|
+
*/
|
3085
|
+
async validateInstallation(conversationReference) {
|
3086
|
+
let isValid = true;
|
3087
|
+
await this.adapter.continueConversationAsync(this.botAppId, conversationReference, async (context) => {
|
3088
|
+
try {
|
3089
|
+
// try get member to see if the installation is still valid
|
3090
|
+
await TeamsInfo.getPagedMembers(context, 1);
|
3091
|
+
}
|
3092
|
+
catch (error) {
|
3093
|
+
if (error.code === "BotNotInConversationRoster") {
|
3094
|
+
isValid = false;
|
3095
|
+
}
|
3096
|
+
}
|
3097
|
+
});
|
3098
|
+
return isValid;
|
3099
|
+
}
|
3100
|
+
/**
|
3101
|
+
* Gets a pagined list of targets where the bot is installed.
|
3102
|
+
*
|
3103
|
+
* @remarks
|
3104
|
+
* The result is retrieving from the persisted storage.
|
3105
|
+
*
|
3106
|
+
* @param pageSize - Suggested number of entries on a page.
|
3107
|
+
* @param continuationToken - A continuation token.
|
3108
|
+
*
|
3109
|
+
* @returns An array of {@link TeamsBotInstallation} with paged data and continuation token.
|
3110
|
+
*/
|
3111
|
+
async getPagedInstallations(pageSize, continuationToken, validationEnabled = true) {
|
3112
|
+
if (this.conversationReferenceStore === undefined || this.adapter === undefined) {
|
3113
|
+
throw new Error("NotificationBot has not been initialized.");
|
3114
|
+
}
|
3115
|
+
const references = await this.conversationReferenceStore.list(pageSize, continuationToken);
|
3116
|
+
const targets = [];
|
3117
|
+
for (const reference of references.data) {
|
3118
|
+
// validate connection
|
3119
|
+
let valid;
|
3120
|
+
if (validationEnabled) {
|
3121
|
+
// try get member to see if the installation is still valid
|
3122
|
+
valid = await this.validateInstallation(reference);
|
3123
|
+
}
|
3124
|
+
if (!validationEnabled || (validationEnabled && valid)) {
|
3125
|
+
targets.push(new TeamsBotInstallation(this.adapter, reference, this.botAppId));
|
3126
|
+
}
|
3127
|
+
else {
|
3128
|
+
await this.conversationReferenceStore.remove(getKey(reference), reference);
|
3129
|
+
}
|
3130
|
+
}
|
3131
|
+
return {
|
3132
|
+
data: targets,
|
3133
|
+
continuationToken: references.continuationToken,
|
3134
|
+
};
|
3135
|
+
}
|
3136
|
+
/**
|
3137
|
+
* Return the first {@link Member} where predicate is true, and undefined otherwise.
|
3138
|
+
*
|
3139
|
+
* @param predicate - Find calls predicate once for each member of the installation,
|
3140
|
+
* until it finds one where predicate returns true. If such a member is found, find
|
3141
|
+
* immediately returns that member. Otherwise, find returns undefined.
|
3142
|
+
* @param scope - The scope to find members from the installations
|
3143
|
+
* (personal chat, group chat, Teams channel).
|
3144
|
+
*
|
3145
|
+
* @returns The first {@link Member} where predicate is true, and `undefined` otherwise.
|
3146
|
+
*/
|
3147
|
+
async findMember(predicate, scope) {
|
3148
|
+
for (const target of await this.installations()) {
|
3149
|
+
if (this.matchSearchScope(target, scope)) {
|
3150
|
+
const members = [];
|
3151
|
+
let continuationToken;
|
3152
|
+
do {
|
3153
|
+
const pagedData = await target.getPagedMembers(undefined, continuationToken);
|
3154
|
+
continuationToken = pagedData.continuationToken;
|
3155
|
+
members.push(...pagedData.data);
|
3156
|
+
} while (continuationToken);
|
3157
|
+
for (const member of members) {
|
3158
|
+
if (await predicate(member)) {
|
3159
|
+
return member;
|
3160
|
+
}
|
3161
|
+
}
|
3162
|
+
}
|
3163
|
+
}
|
3164
|
+
return;
|
3165
|
+
}
|
3166
|
+
/**
|
3167
|
+
* Return the first {@link Channel} where predicate is true, and undefined otherwise.
|
3168
|
+
* (Ensure the bot app is installed into the `General` channel, otherwise undefined will be returned.)
|
3169
|
+
*
|
3170
|
+
* @param predicate - Find calls predicate once for each channel of the installation,
|
3171
|
+
* until it finds one where predicate returns true. If such a channel is found, find
|
3172
|
+
* immediately returns that channel. Otherwise, find returns `undefined`.
|
3173
|
+
*
|
3174
|
+
* @returns The first {@link Channel} where predicate is true, and `undefined` otherwise.
|
3175
|
+
*/
|
3176
|
+
async findChannel(predicate) {
|
3177
|
+
for (const target of await this.installations()) {
|
3178
|
+
if (target.type === NotificationTargetType.Channel) {
|
3179
|
+
const teamDetails = await target.getTeamDetails();
|
3180
|
+
for (const channel of await target.channels()) {
|
3181
|
+
if (await predicate(channel, teamDetails)) {
|
3182
|
+
return channel;
|
3183
|
+
}
|
3184
|
+
}
|
3185
|
+
}
|
3186
|
+
}
|
3187
|
+
return;
|
3188
|
+
}
|
3189
|
+
/**
|
3190
|
+
* Return all {@link Member} where predicate is true, and empty array otherwise.
|
3191
|
+
*
|
3192
|
+
* @param predicate - Find calls predicate for each member of the installation.
|
3193
|
+
* @param scope - The scope to find members from the installations
|
3194
|
+
* (personal chat, group chat, Teams channel).
|
3195
|
+
*
|
3196
|
+
* @returns An array of {@link Member} where predicate is true, and empty array otherwise.
|
3197
|
+
*/
|
3198
|
+
async findAllMembers(predicate, scope) {
|
3199
|
+
const members = [];
|
3200
|
+
for (const target of await this.installations()) {
|
3201
|
+
if (this.matchSearchScope(target, scope)) {
|
3202
|
+
const targetMembers = [];
|
3203
|
+
let continuationToken;
|
3204
|
+
do {
|
3205
|
+
const pagedData = await target.getPagedMembers(undefined, continuationToken);
|
3206
|
+
continuationToken = pagedData.continuationToken;
|
3207
|
+
targetMembers.push(...pagedData.data);
|
3208
|
+
} while (continuationToken);
|
3209
|
+
for (const member of targetMembers) {
|
3210
|
+
if (await predicate(member)) {
|
3211
|
+
members.push(member);
|
3212
|
+
}
|
3213
|
+
}
|
3214
|
+
}
|
3215
|
+
}
|
3216
|
+
return members;
|
3217
|
+
}
|
3218
|
+
/**
|
3219
|
+
* Return all {@link Channel} where predicate is true, and empty array otherwise.
|
3220
|
+
* (Ensure the bot app is installed into the `General` channel, otherwise empty array will be returned.)
|
3221
|
+
*
|
3222
|
+
* @param predicate - Find calls predicate for each channel of the installation.
|
3223
|
+
*
|
3224
|
+
* @returns An array of {@link Channel} where predicate is true, and empty array otherwise.
|
3225
|
+
*/
|
3226
|
+
async findAllChannels(predicate) {
|
3227
|
+
const channels = [];
|
3228
|
+
for (const target of await this.installations()) {
|
3229
|
+
if (target.type === NotificationTargetType.Channel) {
|
3230
|
+
const teamDetails = await target.getTeamDetails();
|
3231
|
+
for (const channel of await target.channels()) {
|
3232
|
+
if (await predicate(channel, teamDetails)) {
|
3233
|
+
channels.push(channel);
|
3234
|
+
}
|
3235
|
+
}
|
3236
|
+
}
|
3237
|
+
}
|
3238
|
+
return channels;
|
3239
|
+
}
|
3240
|
+
matchSearchScope(target, scope) {
|
3241
|
+
scope = scope !== null && scope !== void 0 ? scope : SearchScope.All;
|
3242
|
+
return ((target.type === NotificationTargetType.Channel && (scope & SearchScope.Channel) !== 0) ||
|
3243
|
+
(target.type === NotificationTargetType.Group && (scope & SearchScope.Group) !== 0) ||
|
3244
|
+
(target.type === NotificationTargetType.Person && (scope & SearchScope.Person) !== 0));
|
3245
|
+
}
|
3246
|
+
/**
|
3247
|
+
* @internal
|
3248
|
+
* Get all targets where the bot is installed.
|
3249
|
+
*
|
3250
|
+
* @remarks
|
3251
|
+
* The result is retrieving from the persisted storage.
|
3252
|
+
*
|
3253
|
+
* @returns An array of {@link TeamsBotInstallation}
|
3254
|
+
*/
|
3255
|
+
async installations() {
|
3256
|
+
let continuationToken;
|
3257
|
+
const targets = [];
|
3258
|
+
do {
|
3259
|
+
const result = await this.getPagedInstallations(undefined, continuationToken);
|
3260
|
+
continuationToken = result.continuationToken;
|
3261
|
+
targets.push(...result.data);
|
3262
|
+
} while (continuationToken);
|
3263
|
+
return targets;
|
3264
|
+
}
|
3265
|
+
}
|
3266
|
+
/**
|
3267
|
+
* The search scope when calling {@link NotificationBot.findMember} and {@link NotificationBot.findAllMembers}.
|
3268
|
+
* The search scope is a flagged enum and it can be combined with `|`.
|
3269
|
+
* For example, to search from personal chat and group chat, use `SearchScope.Person | SearchScope.Group`.
|
3270
|
+
*/
|
3271
|
+
var SearchScope;
|
3272
|
+
(function (SearchScope) {
|
3273
|
+
/**
|
3274
|
+
* Search members from the installations in personal chat only.
|
3275
|
+
*/
|
3276
|
+
SearchScope[SearchScope["Person"] = 1] = "Person";
|
3277
|
+
/**
|
3278
|
+
* Search members from the installations in group chat only.
|
3279
|
+
*/
|
3280
|
+
SearchScope[SearchScope["Group"] = 2] = "Group";
|
3281
|
+
/**
|
3282
|
+
* Search members from the installations in Teams channel only.
|
3283
|
+
*/
|
3284
|
+
SearchScope[SearchScope["Channel"] = 4] = "Channel";
|
3285
|
+
/**
|
3286
|
+
* Search members from all installations including personal chat, group chat and Teams channel.
|
3287
|
+
*/
|
3288
|
+
SearchScope[SearchScope["All"] = 7] = "All";
|
3289
|
+
})(SearchScope || (SearchScope = {}));
|
3290
|
+
|
3291
|
+
/******************************************************************************
|
3292
|
+
Copyright (c) Microsoft Corporation.
|
3293
|
+
|
3294
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
3295
|
+
purpose with or without fee is hereby granted.
|
3296
|
+
|
3297
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
3298
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
3299
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
3300
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
3301
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
3302
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
3303
|
+
PERFORMANCE OF THIS SOFTWARE.
|
3304
|
+
***************************************************************************** */
|
3305
|
+
|
3306
|
+
function __rest(s, e) {
|
3307
|
+
var t = {};
|
3308
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
3309
|
+
t[p] = s[p];
|
3310
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
3311
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
3312
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
3313
|
+
t[p[i]] = s[p[i]];
|
3314
|
+
}
|
3315
|
+
return t;
|
3316
|
+
}
|
3317
|
+
|
3318
|
+
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
3319
|
+
var e = new Error(message);
|
3320
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
3321
|
+
};
|
3322
|
+
|
3323
|
+
// Copyright (c) Microsoft Corporation.
|
3324
|
+
/**
|
3325
|
+
* Default SSO execution activity handler
|
3326
|
+
*/
|
3327
|
+
class DefaultBotSsoExecutionActivityHandler extends TeamsActivityHandler {
|
3328
|
+
/**
|
3329
|
+
* Creates a new instance of the DefaultBotSsoExecutionActivityHandler.
|
3330
|
+
* @param ssoConfig configuration for SSO command bot
|
3331
|
+
*
|
3332
|
+
* @remarks
|
3333
|
+
* In the constructor, it uses BotSsoConfig parameter which from {@link ConversationBot} options to initialize {@link BotSsoExecutionDialog}.
|
3334
|
+
* It also need to register an event handler for the message event which trigger {@link BotSsoExecutionDialog} instance.
|
3335
|
+
*/
|
3336
|
+
constructor(ssoConfig) {
|
3337
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
|
3338
|
+
super();
|
3339
|
+
const memoryStorage = new MemoryStorage();
|
3340
|
+
const userState = (_b = (_a = ssoConfig.dialog) === null || _a === void 0 ? void 0 : _a.userState) !== null && _b !== void 0 ? _b : new UserState(memoryStorage);
|
3341
|
+
const conversationState = (_d = (_c = ssoConfig.dialog) === null || _c === void 0 ? void 0 : _c.conversationState) !== null && _d !== void 0 ? _d : new ConversationState(memoryStorage);
|
3342
|
+
const dedupStorage = (_f = (_e = ssoConfig.dialog) === null || _e === void 0 ? void 0 : _e.dedupStorage) !== null && _f !== void 0 ? _f : memoryStorage;
|
3343
|
+
const _l = ssoConfig.aad, { scopes } = _l, customConfig = __rest(_l, ["scopes"]);
|
3344
|
+
const settings = {
|
3345
|
+
scopes: scopes,
|
3346
|
+
timeout: (_h = (_g = ssoConfig.dialog) === null || _g === void 0 ? void 0 : _g.ssoPromptConfig) === null || _h === void 0 ? void 0 : _h.timeout,
|
3347
|
+
endOnInvalidMessage: (_k = (_j = ssoConfig.dialog) === null || _j === void 0 ? void 0 : _j.ssoPromptConfig) === null || _k === void 0 ? void 0 : _k.endOnInvalidMessage,
|
3348
|
+
};
|
3349
|
+
this.ssoExecutionDialog = new BotSsoExecutionDialog(dedupStorage, settings, customConfig, customConfig.initiateLoginEndpoint);
|
3350
|
+
this.conversationState = conversationState;
|
3351
|
+
this.dialogState = conversationState.createProperty("DialogState");
|
3352
|
+
this.userState = userState;
|
3353
|
+
this.onMessage(async (context, next) => {
|
3354
|
+
await this.ssoExecutionDialog.run(context, this.dialogState);
|
3355
|
+
await next();
|
3356
|
+
});
|
3357
|
+
}
|
3358
|
+
/**
|
3359
|
+
* Add TeamsFxBotSsoCommandHandler instance to SSO execution dialog
|
3360
|
+
* @param handler {@link BotSsoExecutionDialogHandler} callback function
|
3361
|
+
* @param triggerPatterns The trigger pattern
|
3362
|
+
*
|
3363
|
+
* @remarks
|
3364
|
+
* This function is used to add SSO command to {@link BotSsoExecutionDialog} instance.
|
3365
|
+
*/
|
3366
|
+
addCommand(handler, triggerPatterns) {
|
3367
|
+
this.ssoExecutionDialog.addCommand(handler, triggerPatterns);
|
3368
|
+
}
|
3369
|
+
/**
|
3370
|
+
* Called to initiate the event emission process.
|
3371
|
+
* @param context The context object for the current turn.
|
3372
|
+
*/
|
3373
|
+
async run(context) {
|
3374
|
+
try {
|
3375
|
+
await super.run(context);
|
3376
|
+
}
|
3377
|
+
finally {
|
3378
|
+
await this.conversationState.saveChanges(context, false);
|
3379
|
+
await this.userState.saveChanges(context, false);
|
3380
|
+
}
|
3381
|
+
}
|
3382
|
+
/**
|
3383
|
+
* Receives invoke activities with Activity name of 'signin/verifyState'.
|
3384
|
+
* @param context A context object for this turn.
|
3385
|
+
* @param query Signin state (part of signin action auth flow) verification invoke query.
|
3386
|
+
* @returns A promise that represents the work queued.
|
3387
|
+
*
|
3388
|
+
* @remarks
|
3389
|
+
* It should trigger {@link BotSsoExecutionDialog} instance to handle signin process
|
3390
|
+
*/
|
3391
|
+
async handleTeamsSigninVerifyState(context, query) {
|
3392
|
+
await this.ssoExecutionDialog.run(context, this.dialogState);
|
3393
|
+
}
|
3394
|
+
/**
|
3395
|
+
* Receives invoke activities with Activity name of 'signin/tokenExchange'
|
3396
|
+
* @param context A context object for this turn.
|
3397
|
+
* @param query Signin state (part of signin action auth flow) verification invoke query
|
3398
|
+
* @returns A promise that represents the work queued.
|
3399
|
+
*
|
3400
|
+
* @remarks
|
3401
|
+
* It should trigger {@link BotSsoExecutionDialog} instance to handle signin process
|
3402
|
+
*/
|
3403
|
+
async handleTeamsSigninTokenExchange(context, query) {
|
3404
|
+
await this.ssoExecutionDialog.run(context, this.dialogState);
|
3405
|
+
}
|
3406
|
+
}
|
3407
|
+
|
3408
|
+
// Copyright (c) Microsoft Corporation.
|
3409
|
+
/**
|
3410
|
+
* Provide utilities for bot conversation, including:
|
3411
|
+
* - handle command and response.
|
3412
|
+
* - send notification to varies targets (e.g., member, group, channel).
|
3413
|
+
*
|
3414
|
+
* @example
|
3415
|
+
* For command and response, you can register your commands through the constructor, or use the `registerCommand` and `registerCommands` API to add commands later.
|
3416
|
+
*
|
3417
|
+
* ```typescript
|
3418
|
+
* import { BotBuilderCloudAdapter } from "@microsoft/teamsfx";
|
3419
|
+
* import ConversationBot = BotBuilderCloudAdapter.ConversationBot;
|
3420
|
+
*
|
3421
|
+
* // register through constructor
|
3422
|
+
* const conversationBot = new ConversationBot({
|
3423
|
+
* command: {
|
3424
|
+
* enabled: true,
|
3425
|
+
* commands: [ new HelloWorldCommandHandler() ],
|
3426
|
+
* },
|
3427
|
+
* });
|
3428
|
+
*
|
3429
|
+
* // register through `register*` API
|
3430
|
+
* conversationBot.command.registerCommand(new HelpCommandHandler());
|
3431
|
+
* ```
|
3432
|
+
*
|
3433
|
+
* For notification, you can enable notification at initialization, then send notifications at any time.
|
3434
|
+
*
|
3435
|
+
* ```typescript
|
3436
|
+
* import { BotBuilderCloudAdapter } from "@microsoft/teamsfx";
|
3437
|
+
* import ConversationBot = BotBuilderCloudAdapter.ConversationBot;
|
3438
|
+
*
|
3439
|
+
* // enable through constructor
|
3440
|
+
* const conversationBot = new ConversationBot({
|
3441
|
+
* notification: {
|
3442
|
+
* enabled: true,
|
3443
|
+
* },
|
3444
|
+
* });
|
3445
|
+
*
|
3446
|
+
* // get all bot installations and send message
|
3447
|
+
* for (const target of await conversationBot.notification.installations()) {
|
3448
|
+
* await target.sendMessage("Hello Notification");
|
3449
|
+
* }
|
3450
|
+
*
|
3451
|
+
* // alternative - send message to all members
|
3452
|
+
* for (const target of await conversationBot.notification.installations()) {
|
3453
|
+
* for (const member of await target.members()) {
|
3454
|
+
* await member.sendMessage("Hello Notification");
|
3455
|
+
* }
|
3456
|
+
* }
|
3457
|
+
* ```
|
3458
|
+
*
|
3459
|
+
* @remarks
|
3460
|
+
* Set `adapter` in {@link ConversationOptions} to use your own bot adapter.
|
3461
|
+
*
|
3462
|
+
* For command and response, ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.
|
3463
|
+
*
|
3464
|
+
* For notification, set `notification.storage` in {@link ConversationOptions} to use your own storage implementation.
|
3465
|
+
*/
|
3466
|
+
class ConversationBot {
|
3467
|
+
/**
|
3468
|
+
* Create new instance of the `ConversationBot`.
|
3469
|
+
*
|
3470
|
+
* @remarks
|
3471
|
+
* It's recommended to create your own adapter and storage for production environment instead of the default one.
|
3472
|
+
*
|
3473
|
+
* @param options - The initialize options.
|
3474
|
+
*/
|
3475
|
+
constructor(options) {
|
3476
|
+
var _a, _b, _c, _d;
|
3477
|
+
if (options.adapter) {
|
3478
|
+
this.adapter = options.adapter;
|
3479
|
+
}
|
3480
|
+
else {
|
3481
|
+
this.adapter = this.createDefaultAdapter(options.adapterConfig);
|
3482
|
+
}
|
3483
|
+
let ssoCommandActivityHandler;
|
3484
|
+
if (options === null || options === void 0 ? void 0 : options.ssoConfig) {
|
3485
|
+
if ((_a = options.ssoConfig.dialog) === null || _a === void 0 ? void 0 : _a.CustomBotSsoExecutionActivityHandler) {
|
3486
|
+
ssoCommandActivityHandler =
|
3487
|
+
new options.ssoConfig.dialog.CustomBotSsoExecutionActivityHandler(options.ssoConfig);
|
3488
|
+
}
|
3489
|
+
else {
|
3490
|
+
ssoCommandActivityHandler = new DefaultBotSsoExecutionActivityHandler(options.ssoConfig);
|
3491
|
+
}
|
3492
|
+
}
|
3493
|
+
if ((_b = options.command) === null || _b === void 0 ? void 0 : _b.enabled) {
|
3494
|
+
this.command = new CommandBot(this.adapter, options.command, ssoCommandActivityHandler, options.ssoConfig);
|
3495
|
+
}
|
3496
|
+
if ((_c = options.notification) === null || _c === void 0 ? void 0 : _c.enabled) {
|
3497
|
+
this.notification = new NotificationBot(this.adapter, options.notification);
|
3498
|
+
}
|
3499
|
+
if ((_d = options.cardAction) === null || _d === void 0 ? void 0 : _d.enabled) {
|
3500
|
+
this.cardAction = new CardActionBot(this.adapter, options.cardAction);
|
3501
|
+
}
|
3502
|
+
}
|
3503
|
+
createDefaultAdapter(adapterConfig) {
|
3504
|
+
const credentialsFactory = adapterConfig === undefined
|
3505
|
+
? new ConfigurationServiceClientCredentialFactory({
|
3506
|
+
MicrosoftAppId: process.env.BOT_ID,
|
3507
|
+
MicrosoftAppPassword: process.env.BOT_PASSWORD,
|
3508
|
+
MicrosoftAppType: "MultiTenant",
|
3509
|
+
})
|
3510
|
+
: new ConfigurationServiceClientCredentialFactory(adapterConfig);
|
3511
|
+
const botFrameworkAuthentication = new ConfigurationBotFrameworkAuthentication({}, credentialsFactory);
|
3512
|
+
const adapter = new CloudAdapter(botFrameworkAuthentication);
|
3513
|
+
// the default error handler
|
3514
|
+
adapter.onTurnError = async (context, error) => {
|
3515
|
+
// This check writes out errors to console.
|
3516
|
+
console.error(`[onTurnError] unhandled error`, error);
|
3517
|
+
// Only send error message for user messages, not for other message types so the bot doesn't spam a channel or chat.
|
3518
|
+
if (context.activity.type === "message") {
|
3519
|
+
// Send a trace activity, which will be displayed in Bot Framework Emulator
|
3520
|
+
await context.sendTraceActivity("OnTurnError Trace", error instanceof Error ? error.message : error, "https://www.botframework.com/schemas/error", "TurnError");
|
3521
|
+
// Send a message to the user
|
3522
|
+
await context.sendActivity(`The bot encountered unhandled error: ${error.message}`);
|
3523
|
+
await context.sendActivity("To continue to run this bot, please fix the bot source code.");
|
3524
|
+
}
|
3525
|
+
};
|
3526
|
+
return adapter;
|
3527
|
+
}
|
3528
|
+
/**
|
3529
|
+
* The request handler to integrate with web request.
|
3530
|
+
*
|
3531
|
+
* @param req - An incoming HTTP [Request](xref:botbuilder.Request).
|
3532
|
+
* @param res - The corresponding HTTP [Response](xref:botbuilder.Response).
|
3533
|
+
* @param logic - The additional function to handle bot context.
|
3534
|
+
*
|
3535
|
+
* @example
|
3536
|
+
* For example, to use with Express:
|
3537
|
+
* ``` typescript
|
3538
|
+
* // The default/empty behavior
|
3539
|
+
* const expressApp = express();
|
3540
|
+
* expressApp.use(express.json());
|
3541
|
+
* expressApp.post("/api/notification", conversationBot.requestHandler);
|
3542
|
+
*
|
3543
|
+
* // Or, add your own logic
|
3544
|
+
* const expressApp = express();
|
3545
|
+
* expressApp.use(express.json());
|
3546
|
+
* expressApp.post("/api/notification", async (req, res) => {
|
3547
|
+
* await conversationBot.requestHandler(req, res, async (context) => {
|
3548
|
+
* // your-own-context-logic
|
3549
|
+
* });
|
3550
|
+
* });
|
3551
|
+
* ```
|
3552
|
+
*/
|
3553
|
+
async requestHandler(req, res, logic) {
|
3554
|
+
if (logic === undefined) {
|
3555
|
+
// create empty logic
|
3556
|
+
logic = async () => { };
|
3557
|
+
}
|
3558
|
+
await this.adapter.process(req, res, logic);
|
3559
|
+
}
|
3560
|
+
}
|
3561
|
+
|
3562
|
+
var conversationWithCloudAdapter = /*#__PURE__*/Object.freeze({
|
3563
|
+
__proto__: null,
|
3564
|
+
ConversationBot: ConversationBot,
|
3565
|
+
BotSsoExecutionDialog: BotSsoExecutionDialog,
|
3566
|
+
Channel: Channel,
|
3567
|
+
Member: Member,
|
3568
|
+
NotificationBot: NotificationBot,
|
3569
|
+
sendAdaptiveCard: sendAdaptiveCard,
|
3570
|
+
sendMessage: sendMessage,
|
3571
|
+
TeamsBotInstallation: TeamsBotInstallation,
|
3572
|
+
get SearchScope () { return SearchScope; },
|
3573
|
+
CommandBot: CommandBot,
|
3574
|
+
CardActionBot: CardActionBot
|
3575
|
+
});
|
3576
|
+
|
3577
|
+
export { AdaptiveCardResponse, ApiKeyLocation, ApiKeyProvider, AppCredential, BasicAuthProvider, BearerTokenAuthProvider, conversationWithCloudAdapter as BotBuilderCloudAdapter, BotSsoExecutionDialog, CertificateAuthProvider, ErrorCode, ErrorWithCode, InvokeResponseErrorCode, InvokeResponseFactory, LogLevel, MessageBuilder, NotificationTargetType, OnBehalfOfUserCredential, TeamsBotSsoPrompt, TeamsUserCredential, createApiClient, createPemCertOption, createPfxCertOption, getLogLevel, handleMessageExtensionLinkQueryWithSSO, handleMessageExtensionQueryWithSSO, setLogFunction, setLogLevel, setLogger };
|
17
3578
|
//# sourceMappingURL=index.esm2017.mjs.map
|