@microsoft/teams.client 2.0.12 → 2.0.14

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/app.d.mts CHANGED
@@ -25,6 +25,10 @@ type MsalOptions = ({
25
25
  * If no value is provided, the default scope (i.e. ".default") is pre-warmed. If a set of scopes is
26
26
  * provided, the specified scopes are pre-warmed. The scopes should be for a single resource, and they
27
27
  * should not mix the .default scope with named scopes.
28
+ *
29
+ * **Important:** On Teams Desktop (NAA via OneAuth broker), `.default` is not supported for Graph
30
+ * token requests. You must provide explicit Graph scopes (e.g., `['User.Read', 'Mail.Read']`) for
31
+ * your app to work on Desktop.
28
32
  */
29
33
  readonly prewarmScopes?: false | string[];
30
34
  };
package/dist/app.d.ts CHANGED
@@ -25,6 +25,10 @@ type MsalOptions = ({
25
25
  * If no value is provided, the default scope (i.e. ".default") is pre-warmed. If a set of scopes is
26
26
  * provided, the specified scopes are pre-warmed. The scopes should be for a single resource, and they
27
27
  * should not mix the .default scope with named scopes.
28
+ *
29
+ * **Important:** On Teams Desktop (NAA via OneAuth broker), `.default` is not supported for Graph
30
+ * token requests. You must provide explicit Graph scopes (e.g., `['User.Read', 'Mail.Read']`) for
31
+ * your app to work on Desktop.
28
32
  */
29
33
  readonly prewarmScopes?: false | string[];
30
34
  };
package/dist/app.js CHANGED
@@ -39,7 +39,11 @@ class App {
39
39
  this.http = new teams_common.Client({
40
40
  baseUrl: options?.remoteApiOptions?.baseUrl
41
41
  });
42
- this.graph = graphUtils.buildGraphClient(() => this.appStateGuard(), this._log);
42
+ this.graph = graphUtils.buildGraphClient(
43
+ () => this.appStateGuard(),
44
+ this._log,
45
+ this.options.msalOptions?.prewarmScopes ? () => this.options.msalOptions.prewarmScopes : void 0
46
+ );
43
47
  }
44
48
  /**
45
49
  * Starts the library and initializes the dependent teams-js and MSAL libraries.
package/dist/app.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/app.ts"],"names":["ConsoleLogger","HttpClient","buildGraphClient","app","buildMsalConfig","createNestablePublicClientApplication","acquireMsalAccessToken","getStandardExecSilentRequest","hasConsentForScopes"],"mappings":";;;;;;;;AAiHO,MAAM,GAAA,CAAI;AAAA,EACN,OAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,QAAA;AAAA,EACC,MAAA,GAAmB,EAAE,KAAA,EAAO,SAAA,EAAU;AAAA;AAAA;AAAA;AAAA,EAKhD,IAAI,GAAA,GAAgB;AAClB,IAAA,OAAO,IAAA,CAAK,IAAA;AAAA,EACd;AAAA,EACU,IAAA;AAAA;AAAA;AAAA;AAAA,EAKV,IAAI,SAAA,GAA+B;AACjC,IAAA,OAAO,KAAK,MAAA,EAAQ,SAAA;AAAA,EACtB;AAAA;AAAA,EAGA,IAAI,YAAA,GAAsD;AACxD,IAAA,OAAO,KAAK,MAAA,CAAO,YAAA;AAAA,EACrB;AAAA,EAEA,WAAA,CAAY,QAAA,EAAkB,OAAA,GAAsB,EAAC,EAAG;AACtD,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,MAAM,IAAI,MAAM,oBAAoB,CAAA;AAAA,IACtC;AAEA,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,IAAA,GAAO,OAAA,EAAS,MAAA,IAAU,IAAIA,2BAAc,eAAe,CAAA;AAChE,IAAA,IAAA,CAAK,IAAA,GAAO,IAAIC,mBAAA,CAAW;AAAA,MACzB,OAAA,EAAS,SAAS,gBAAA,EAAkB;AAAA,KACrC,CAAA;AACD,IAAA,IAAA,CAAK,QAAQC,2BAAA,CAAiB,MAAM,KAAK,aAAA,EAAc,EAAG,KAAK,IAAI,CAAA;AAAA,EACrE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,KAAA,GAAuB;AAC3B,IAAA,IAAI,IAAA,CAAK,MAAA,CAAO,KAAA,K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AA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,oBAAoB,MAAA,EAAoC;AAC5D,IAAA,MAAM,EAAE,YAAA,EAAa,GAAI,IAAA,CAAK,aAAA,EAAc;AAE5C,IAAA,OAAO,MAAMC,6BAAA,CAAoB,YAAA,EAAc,MAAA,EAAQ,KAAK,GAAG,CAAA;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,uBAAuB,MAAA,EAAoC;AAC/D,IAAA,MAAM,EAAE,YAAA,EAAa,GAAI,IAAA,CAAK,aAAA,EAAc;AAE5C,IAAA,IAAI;AACF,MAAA,MAAM,QAAQ,MAAMF,gCAAA;AAAA,QAClB,YAAA;AAAA,QACA,EAAE,MAAA,EAAO;AAAA,QACT,IAAA,CAAK;AAAA,OACP;AACA,MAAA,OAAO,CAAC,CAAC,KAAA;AAAA,IACX,SAAS,EAAA,EAAI;AACX,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAAA,EAEQ,aAAA,GAAiD;AACvD,IAAA,IAAI,IAAA,CAAK,MAAA,CAAO,KAAA,KAAU,SAAA,EAAW;AACnC,MAAA,MAAM,IAAI,MAAM,iBAAiB,CAAA;AAAA,IACnC;AACA,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AACF","file":"app.js","sourcesContent":["import {\n createNestablePublicClientApplication,\n type Configuration,\n type IPublicClientApplication,\n type SilentRequest,\n} from '@azure/msal-browser';\n\nimport { app } from '@microsoft/teams-js';\nimport type { ILogger } from '@microsoft/teams.common';\nimport { ConsoleLogger, Client as HttpClient } from '@microsoft/teams.common';\nimport type { Client as GraphClient } from '@microsoft/teams.graph';\n\nimport { buildGraphClient } from './graph-utils';\nimport {\n acquireMsalAccessToken,\n buildMsalConfig,\n getStandardExecSilentRequest,\n hasConsentForScopes,\n} from './msal-utils';\n\n/**\n * Options to control how MSAL is initialized and used.\n */\nexport type MsalOptions = (\n | {\n /**\n * MSAL instance to use when making authenticated function calls to remote endpoints.\n * This is useful if you want to use a custom MSAL instance or if you want to share the\n * same MSAL instance across multiple apps.\n */\n readonly msalInstance?: IPublicClientApplication;\n readonly configuration?: never;\n }\n | {\n readonly msalInstance?: never;\n /**\n * MSAL configuration to use when constructing an MSAL instance used\n * to make authenticated function calls to remote endpoints. */\n readonly configuration?: Configuration;\n }\n) & {\n /**\n * Options to control scope consent pre-warming. If explicitly set to false, no pre-warming is performed.\n * If no value is provided, the default scope (i.e. \".default\") is pre-warmed. If a set of scopes is\n * provided, the specified scopes are pre-warmed. The scopes should be for a single resource, and they\n * should not mix the .default scope with named scopes.\n */\n readonly prewarmScopes?: false | string[];\n};\n\nexport type RemoteApiOptions = {\n /**\n * The remote API base URL. If omitted, it's assumed that the remote API is hosted in the same domain as the app.\n */\n readonly baseUrl?: string;\n\n /**\n * The default resource name when building a token request for the Entra token to include when invoking\n * a remote function. This is useful when the API is hosted in an different AAD app from\n * the caller and is typically in the format 'api://<remoteAppClientId>'.\n * When invoking @see exec with default options or a permission name,\n * this value is used to build a token request in the format of '<remoteAppResource>/<permission>'.\n * If omitted, it's assumed that the API is hosted in the same AAD app as the caller, and the\n * token request is made for 'api://<clientId>/permission'.\n */\n readonly remoteAppResource?: string;\n};\n\nexport type AppOptions = {\n /**\n * Logger instance to use.\n */\n readonly logger?: ILogger;\n\n /**\n * Options to control how MSAL is initialized and used.\n */\n readonly msalOptions?: MsalOptions;\n\n /** Options to control how remote APIs are invoked. */\n readonly remoteApiOptions?: RemoteApiOptions;\n};\n\ntype AppState =\n | {\n phase: 'stopped' | 'starting';\n startedAt?: never;\n msalInstance?: never;\n }\n | {\n phase: 'started';\n startedAt: Date;\n msalInstance: IPublicClientApplication;\n };\n\n/**\n * ExecOptions is used to specify options for the exec method.\n */\nexport type ExecOptions = (\n | {\n readonly msalTokenRequest?: SilentRequest;\n readonly permission?: never;\n }\n | { readonly msalTokenRequest?: never; readonly permission?: string }\n) & {\n readonly requestHeaders?: Record<string, string>;\n};\n\n/**\n * The main entry point for this library. This class streamlines Microsoft Teams app development\n * by simplifying the process of managing authentication, interacting with Microsoft Graph APIs,\n * and executing server-side functions.\n */\nexport class App {\n readonly options: AppOptions;\n readonly http: HttpClient;\n readonly graph: GraphClient;\n readonly clientId: string;\n protected _state: AppState = { phase: 'stopped' };\n\n /**\n * The apps logger\n */\n get log() : ILogger {\n return this._log;\n }\n protected _log: ILogger;\n\n /**\n * The date/time when the app was successfully started.\n */\n get startedAt() : Date | undefined {\n return this._state?.startedAt;\n }\n\n /** The msal instance used in this app. undefined until the app is started. */\n get msalInstance() : IPublicClientApplication | undefined {\n return this._state.msalInstance;\n }\n\n constructor(clientId: string, options: AppOptions = {}) {\n if (!clientId) {\n throw new Error('Invalid client ID.');\n }\n\n this.clientId = clientId;\n this.options = options;\n this._log = options?.logger || new ConsoleLogger('@teams/client');\n this.http = new HttpClient({\n baseUrl: options?.remoteApiOptions?.baseUrl,\n });\n this.graph = buildGraphClient(() => this.appStateGuard(), this._log);\n }\n\n /**\n * Starts the library and initializes the dependent teams-js and MSAL libraries.\n * @returns A promise that will be fulfilled when the app has started, or\n * rejected if the initialization fails or times out.\n */\n async start(): Promise<void> {\n if (this._state.phase !== 'stopped') {\n this._log.debug(`app already ${this._state.phase}`);\n return;\n }\n\n this._log.debug('app starting');\n this._state = { phase: 'starting' };\n\n await app.initialize();\n\n let msalInstance = this.options.msalOptions?.msalInstance;\n if (!msalInstance) {\n const msalConfig =\n this.options.msalOptions?.configuration ??\n buildMsalConfig(this.clientId, this._log);\n msalInstance = await createNestablePublicClientApplication(\n msalConfig\n );\n }\n\n this._state = { phase: 'started', msalInstance, startedAt: new Date() };\n\n // pre-warm consent for the specified scopes\n if (this.options.msalOptions?.prewarmScopes !== false) {\n const scopes = this.options.msalOptions?.prewarmScopes ?? ['.default'];\n this._log.debug(`prewarming consent for scopes: ${scopes.join(', ')}`);\n await this.ensureConsentForScopes(scopes);\n }\n\n this._log.debug('app started');\n }\n\n /**\n * Execute a server-side function\n * @param name The unique function name\n * @param data The data to send\n * @param options Options\n * @param options.msalTokenRequest Optional MSAL token request.\n * If omitted, a default token request is used.\n * @param options.requestHeaders Optional additional request headers.\n * @returns The function response\n */\n async exec<T = unknown>(\n name: string,\n data?: unknown,\n options?: ExecOptions\n ): Promise<T> {\n const { msalInstance } = this.appStateGuard();\n const context = await app.getContext();\n\n const remoteAppResource =\n this.options.remoteApiOptions?.remoteAppResource ??\n `api://${this.clientId}`;\n const accessToken = await acquireMsalAccessToken(\n msalInstance,\n options?.msalTokenRequest ??\n getStandardExecSilentRequest(remoteAppResource, options?.permission),\n this._log\n );\n\n const res = await this.http.post<T>(`/api/functions/${name}`, data, {\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'x-teams-app-session-id': context.app.sessionId,\n 'x-teams-channel-id': context.channel?.id,\n 'x-teams-chat-id': context.chat?.id,\n 'x-teams-meeting-id': context.meeting?.id,\n 'x-teams-message-id': context.app.parentMessageId || undefined,\n 'x-teams-page-id': context.page.id || undefined,\n 'x-teams-sub-page-id': context.page.subPageId || undefined,\n 'x-teams-team-id': context.team?.internalId,\n ...(options?.requestHeaders ?? {}),\n },\n });\n\n return res.data;\n }\n\n /**\n * Tests whether the user has consented to the specified scopes without prompting the user for consent.\n * @param scopes The scopes to check consent for.The scopes should be for a single resource, and they\n * should not mix the .default scope with named scopes.\n * @returns A promise that resolves to a boolean indicating whether the user has consented to the scopes.\n */\n async hasConsentForScopes(scopes: string[]): Promise<boolean> {\n const { msalInstance } = this.appStateGuard();\n\n return await hasConsentForScopes(msalInstance, scopes, this.log);\n }\n\n /**\n * Tests whether the user has consented to the specified scopes, and prompts them if not. This is useful for ensuring\n * that the user has consented to the required scopes before calling a graph API or other resource.\n * @param scopes - The scopes to prewarm consent for. The scopes should be for a single resource, and they\n * should not mix the .default scope with named scopes.\n * @returns A value indicating whether consent has been acquired for the specified scopes.\n */\n async ensureConsentForScopes(scopes: string[]): Promise<boolean> {\n const { msalInstance } = this.appStateGuard();\n\n try {\n const token = await acquireMsalAccessToken(\n msalInstance,\n { scopes },\n this.log\n );\n return !!token;\n } catch (ex) {\n return false;\n }\n }\n\n private appStateGuard(): AppState & { phase: 'started' } {\n if (this._state.phase !== 'started') {\n throw new Error('App not started');\n }\n return this._state;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/app.ts"],"names":["ConsoleLogger","HttpClient","buildGraphClient","app","buildMsalConfig","createNestablePublicClientApplication","acquireMsalAccessToken","getStandardExecSilentRequest","hasConsentForScopes"],"mappings":";;;;;;;;AAqHO,MAAM,GAAA,CAAI;AAAA,EACN,OAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,QAAA;AAAA,EACC,MAAA,GAAmB,EAAE,KAAA,EAAO,SAAA,EAAU;AAAA;AAAA;AAAA;AAAA,EAKhD,IAAI,GAAA,GAAgB;AAClB,IAAA,OAAO,IAAA,CAAK,IAAA;AAAA,EACd;AAAA,EACU,IAAA;AAAA;AAAA;AAAA;AAAA,EAKV,IAAI,SAAA,GAA+B;AACjC,IAAA,OAAO,KAAK,MAAA,EAAQ,SAAA;AAAA,EACtB;AAAA;AAAA,EAGA,IAAI,YAAA,GAAsD;AACxD,IAAA,OAAO,KAAK,MAAA,CAAO,YAAA;AAAA,EACrB;AAAA,EAEA,WAAA,CAAY,QAAA,EAAkB,OAAA,GAAsB,EAAC,EAAG;AACtD,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,MAAM,IAAI,MAAM,oBAAoB,CAAA;AAAA,IACtC;AAEA,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,IAAA,GAAO,OAAA,EAAS,MAAA,IAAU,IAAIA,2BAAc,eAAe,CAAA;AAChE,IAAA,IAAA,CAAK,IAAA,GAAO,IAAIC,mBAAA,CAAW;AAAA,MACzB,OAAA,EAAS,SAAS,gBAAA,EAAkB;AAAA,KACrC,CAA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AAA,CAAI,eAAA,IAAmB,MAAA;AAAA,QACrD,iBAAA,EAAmB,OAAA,CAAQ,IAAA,CAAK,EAAA,IAAM,MAAA;AAAA,QACtC,qBAAA,EAAuB,OAAA,CAAQ,IAAA,CAAK,SAAA,IAAa,MAAA;AAAA,QACjD,iBAAA,EAAmB,QAAQ,IAAA,EAAM,UAAA;AAAA,QACjC,GAAI,OAAA,EAAS,cAAA,IAAkB;AAAC;AAClC,KACD,CAAA;AAED,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,oBAAoB,MAAA,EAAoC;AAC5D,IAAA,MAAM,EAAE,YAAA,EAAa,GAAI,IAAA,CAAK,aAAA,EAAc;AAE5C,IAAA,OAAO,MAAMC,6BAAA,CAAoB,YAAA,EAAc,MAAA,EAAQ,KAAK,GAAG,CAAA;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,uBAAuB,MAAA,EAAoC;AAC/D,IAAA,MAAM,EAAE,YAAA,EAAa,GAAI,IAAA,CAAK,aAAA,EAAc;AAE5C,IAAA,IAAI;AACF,MAAA,MAAM,QAAQ,MAAMF,gCAAA;AAAA,QAClB,YAAA;AAAA,QACA,EAAE,MAAA,EAAO;AAAA,QACT,IAAA,CAAK;AAAA,OACP;AACA,MAAA,OAAO,CAAC,CAAC,KAAA;AAAA,IACX,SAAS,EAAA,EAAI;AACX,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAAA,EAEQ,aAAA,GAAiD;AACvD,IAAA,IAAI,IAAA,CAAK,MAAA,CAAO,KAAA,KAAU,SAAA,EAAW;AACnC,MAAA,MAAM,IAAI,MAAM,iBAAiB,CAAA;AAAA,IACnC;AACA,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AACF","file":"app.js","sourcesContent":["import {\n createNestablePublicClientApplication,\n type Configuration,\n type IPublicClientApplication,\n type SilentRequest,\n} from '@azure/msal-browser';\n\nimport { app } from '@microsoft/teams-js';\nimport type { ILogger } from '@microsoft/teams.common';\nimport { ConsoleLogger, Client as HttpClient } from '@microsoft/teams.common';\nimport type { Client as GraphClient } from '@microsoft/teams.graph';\n\nimport { buildGraphClient } from './graph-utils';\nimport {\n acquireMsalAccessToken,\n buildMsalConfig,\n getStandardExecSilentRequest,\n hasConsentForScopes,\n} from './msal-utils';\n\n/**\n * Options to control how MSAL is initialized and used.\n */\nexport type MsalOptions = (\n | {\n /**\n * MSAL instance to use when making authenticated function calls to remote endpoints.\n * This is useful if you want to use a custom MSAL instance or if you want to share the\n * same MSAL instance across multiple apps.\n */\n readonly msalInstance?: IPublicClientApplication;\n readonly configuration?: never;\n }\n | {\n readonly msalInstance?: never;\n /**\n * MSAL configuration to use when constructing an MSAL instance used\n * to make authenticated function calls to remote endpoints. */\n readonly configuration?: Configuration;\n }\n) & {\n /**\n * Options to control scope consent pre-warming. If explicitly set to false, no pre-warming is performed.\n * If no value is provided, the default scope (i.e. \".default\") is pre-warmed. If a set of scopes is\n * provided, the specified scopes are pre-warmed. The scopes should be for a single resource, and they\n * should not mix the .default scope with named scopes.\n *\n * **Important:** On Teams Desktop (NAA via OneAuth broker), `.default` is not supported for Graph\n * token requests. You must provide explicit Graph scopes (e.g., `['User.Read', 'Mail.Read']`) for\n * your app to work on Desktop.\n */\n readonly prewarmScopes?: false | string[];\n};\n\nexport type RemoteApiOptions = {\n /**\n * The remote API base URL. If omitted, it's assumed that the remote API is hosted in the same domain as the app.\n */\n readonly baseUrl?: string;\n\n /**\n * The default resource name when building a token request for the Entra token to include when invoking\n * a remote function. This is useful when the API is hosted in an different AAD app from\n * the caller and is typically in the format 'api://<remoteAppClientId>'.\n * When invoking @see exec with default options or a permission name,\n * this value is used to build a token request in the format of '<remoteAppResource>/<permission>'.\n * If omitted, it's assumed that the API is hosted in the same AAD app as the caller, and the\n * token request is made for 'api://<clientId>/permission'.\n */\n readonly remoteAppResource?: string;\n};\n\nexport type AppOptions = {\n /**\n * Logger instance to use.\n */\n readonly logger?: ILogger;\n\n /**\n * Options to control how MSAL is initialized and used.\n */\n readonly msalOptions?: MsalOptions;\n\n /** Options to control how remote APIs are invoked. */\n readonly remoteApiOptions?: RemoteApiOptions;\n};\n\ntype AppState =\n | {\n phase: 'stopped' | 'starting';\n startedAt?: never;\n msalInstance?: never;\n }\n | {\n phase: 'started';\n startedAt: Date;\n msalInstance: IPublicClientApplication;\n };\n\n/**\n * ExecOptions is used to specify options for the exec method.\n */\nexport type ExecOptions = (\n | {\n readonly msalTokenRequest?: SilentRequest;\n readonly permission?: never;\n }\n | { readonly msalTokenRequest?: never; readonly permission?: string }\n) & {\n readonly requestHeaders?: Record<string, string>;\n};\n\n/**\n * The main entry point for this library. This class streamlines Microsoft Teams app development\n * by simplifying the process of managing authentication, interacting with Microsoft Graph APIs,\n * and executing server-side functions.\n */\nexport class App {\n readonly options: AppOptions;\n readonly http: HttpClient;\n readonly graph: GraphClient;\n readonly clientId: string;\n protected _state: AppState = { phase: 'stopped' };\n\n /**\n * The apps logger\n */\n get log() : ILogger {\n return this._log;\n }\n protected _log: ILogger;\n\n /**\n * The date/time when the app was successfully started.\n */\n get startedAt() : Date | undefined {\n return this._state?.startedAt;\n }\n\n /** The msal instance used in this app. undefined until the app is started. */\n get msalInstance() : IPublicClientApplication | undefined {\n return this._state.msalInstance;\n }\n\n constructor(clientId: string, options: AppOptions = {}) {\n if (!clientId) {\n throw new Error('Invalid client ID.');\n }\n\n this.clientId = clientId;\n this.options = options;\n this._log = options?.logger || new ConsoleLogger('@teams/client');\n this.http = new HttpClient({\n baseUrl: options?.remoteApiOptions?.baseUrl,\n });\n this.graph = buildGraphClient(\n () => this.appStateGuard(),\n this._log,\n this.options.msalOptions?.prewarmScopes\n ? () => this.options.msalOptions!.prewarmScopes as string[]\n : undefined\n );\n }\n\n /**\n * Starts the library and initializes the dependent teams-js and MSAL libraries.\n * @returns A promise that will be fulfilled when the app has started, or\n * rejected if the initialization fails or times out.\n */\n async start(): Promise<void> {\n if (this._state.phase !== 'stopped') {\n this._log.debug(`app already ${this._state.phase}`);\n return;\n }\n\n this._log.debug('app starting');\n this._state = { phase: 'starting' };\n\n await app.initialize();\n\n let msalInstance = this.options.msalOptions?.msalInstance;\n if (!msalInstance) {\n const msalConfig =\n this.options.msalOptions?.configuration ??\n buildMsalConfig(this.clientId, this._log);\n msalInstance = await createNestablePublicClientApplication(\n msalConfig\n );\n }\n\n this._state = { phase: 'started', msalInstance, startedAt: new Date() };\n\n // pre-warm consent for the specified scopes\n if (this.options.msalOptions?.prewarmScopes !== false) {\n const scopes = this.options.msalOptions?.prewarmScopes ?? ['.default'];\n this._log.debug(`prewarming consent for scopes: ${scopes.join(', ')}`);\n await this.ensureConsentForScopes(scopes);\n }\n\n this._log.debug('app started');\n }\n\n /**\n * Execute a server-side function\n * @param name The unique function name\n * @param data The data to send\n * @param options Options\n * @param options.msalTokenRequest Optional MSAL token request.\n * If omitted, a default token request is used.\n * @param options.requestHeaders Optional additional request headers.\n * @returns The function response\n */\n async exec<T = unknown>(\n name: string,\n data?: unknown,\n options?: ExecOptions\n ): Promise<T> {\n const { msalInstance } = this.appStateGuard();\n const context = await app.getContext();\n\n const remoteAppResource =\n this.options.remoteApiOptions?.remoteAppResource ??\n `api://${this.clientId}`;\n const accessToken = await acquireMsalAccessToken(\n msalInstance,\n options?.msalTokenRequest ??\n getStandardExecSilentRequest(remoteAppResource, options?.permission),\n this._log\n );\n\n const res = await this.http.post<T>(`/api/functions/${name}`, data, {\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'x-teams-app-session-id': context.app.sessionId,\n 'x-teams-channel-id': context.channel?.id,\n 'x-teams-chat-id': context.chat?.id,\n 'x-teams-meeting-id': context.meeting?.id,\n 'x-teams-message-id': context.app.parentMessageId || undefined,\n 'x-teams-page-id': context.page.id || undefined,\n 'x-teams-sub-page-id': context.page.subPageId || undefined,\n 'x-teams-team-id': context.team?.internalId,\n ...(options?.requestHeaders ?? {}),\n },\n });\n\n return res.data;\n }\n\n /**\n * Tests whether the user has consented to the specified scopes without prompting the user for consent.\n * @param scopes The scopes to check consent for.The scopes should be for a single resource, and they\n * should not mix the .default scope with named scopes.\n * @returns A promise that resolves to a boolean indicating whether the user has consented to the scopes.\n */\n async hasConsentForScopes(scopes: string[]): Promise<boolean> {\n const { msalInstance } = this.appStateGuard();\n\n return await hasConsentForScopes(msalInstance, scopes, this.log);\n }\n\n /**\n * Tests whether the user has consented to the specified scopes, and prompts them if not. This is useful for ensuring\n * that the user has consented to the required scopes before calling a graph API or other resource.\n * @param scopes - The scopes to prewarm consent for. The scopes should be for a single resource, and they\n * should not mix the .default scope with named scopes.\n * @returns A value indicating whether consent has been acquired for the specified scopes.\n */\n async ensureConsentForScopes(scopes: string[]): Promise<boolean> {\n const { msalInstance } = this.appStateGuard();\n\n try {\n const token = await acquireMsalAccessToken(\n msalInstance,\n { scopes },\n this.log\n );\n return !!token;\n } catch (ex) {\n return false;\n }\n }\n\n private appStateGuard(): AppState & { phase: 'started' } {\n if (this._state.phase !== 'started') {\n throw new Error('App not started');\n }\n return this._state;\n }\n}\n"]}
package/dist/app.mjs CHANGED
@@ -37,7 +37,11 @@ class App {
37
37
  this.http = new Client({
38
38
  baseUrl: options?.remoteApiOptions?.baseUrl
39
39
  });
40
- this.graph = buildGraphClient(() => this.appStateGuard(), this._log);
40
+ this.graph = buildGraphClient(
41
+ () => this.appStateGuard(),
42
+ this._log,
43
+ this.options.msalOptions?.prewarmScopes ? () => this.options.msalOptions.prewarmScopes : void 0
44
+ );
41
45
  }
42
46
  /**
43
47
  * Starts the library and initializes the dependent teams-js and MSAL libraries.
package/dist/app.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/app.ts"],"names":["HttpClient"],"mappings":";;;;;;AAiHO,MAAM,GAAA,CAAI;AAAA,EACN,OAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,QAAA;A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E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,uBAAuB,MAAA,EAAoC;AAC/D,IAAA,MAAM,EAAE,YAAA,EAAa,GAAI,IAAA,CAAK,aAAA,EAAc;AAE5C,IAAA,IAAI;AACF,MAAA,MAAM,QAAQ,MAAM,sBAAA;AAAA,QAClB,YAAA;AAAA,QACA,EAAE,MAAA,EAAO;AAAA,QACT,IAAA,CAAK;AAAA,OACP;AACA,MAAA,OAAO,CAAC,CAAC,KAAA;AAAA,IACX,SAAS,EAAA,EAAI;AACX,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAAA,EAEQ,aAAA,GAAiD;AACvD,IAAA,IAAI,IAAA,CAAK,MAAA,CAAO,KAAA,KAAU,SAAA,EAAW;AACnC,MAAA,MAAM,IAAI,MAAM,iBAAiB,CAAA;AAAA,IACnC;AACA,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AACF","file":"app.mjs","sourcesContent":["import {\n createNestablePublicClientApplication,\n type Configuration,\n type IPublicClientApplication,\n type SilentRequest,\n} from '@azure/msal-browser';\n\nimport { app } from '@microsoft/teams-js';\nimport type { ILogger } from '@microsoft/teams.common';\nimport { ConsoleLogger, Client as HttpClient } from '@microsoft/teams.common';\nimport type { Client as GraphClient } from '@microsoft/teams.graph';\n\nimport { buildGraphClient } from './graph-utils';\nimport {\n acquireMsalAccessToken,\n buildMsalConfig,\n getStandardExecSilentRequest,\n hasConsentForScopes,\n} from './msal-utils';\n\n/**\n * Options to control how MSAL is initialized and used.\n */\nexport type MsalOptions = (\n | {\n /**\n * MSAL instance to use when making authenticated function calls to remote endpoints.\n * This is useful if you want to use a custom MSAL instance or if you want to share the\n * same MSAL instance across multiple apps.\n */\n readonly msalInstance?: IPublicClientApplication;\n readonly configuration?: never;\n }\n | {\n readonly msalInstance?: never;\n /**\n * MSAL configuration to use when constructing an MSAL instance used\n * to make authenticated function calls to remote endpoints. */\n readonly configuration?: Configuration;\n }\n) & {\n /**\n * Options to control scope consent pre-warming. If explicitly set to false, no pre-warming is performed.\n * If no value is provided, the default scope (i.e. \".default\") is pre-warmed. If a set of scopes is\n * provided, the specified scopes are pre-warmed. The scopes should be for a single resource, and they\n * should not mix the .default scope with named scopes.\n */\n readonly prewarmScopes?: false | string[];\n};\n\nexport type RemoteApiOptions = {\n /**\n * The remote API base URL. If omitted, it's assumed that the remote API is hosted in the same domain as the app.\n */\n readonly baseUrl?: string;\n\n /**\n * The default resource name when building a token request for the Entra token to include when invoking\n * a remote function. This is useful when the API is hosted in an different AAD app from\n * the caller and is typically in the format 'api://<remoteAppClientId>'.\n * When invoking @see exec with default options or a permission name,\n * this value is used to build a token request in the format of '<remoteAppResource>/<permission>'.\n * If omitted, it's assumed that the API is hosted in the same AAD app as the caller, and the\n * token request is made for 'api://<clientId>/permission'.\n */\n readonly remoteAppResource?: string;\n};\n\nexport type AppOptions = {\n /**\n * Logger instance to use.\n */\n readonly logger?: ILogger;\n\n /**\n * Options to control how MSAL is initialized and used.\n */\n readonly msalOptions?: MsalOptions;\n\n /** Options to control how remote APIs are invoked. */\n readonly remoteApiOptions?: RemoteApiOptions;\n};\n\ntype AppState =\n | {\n phase: 'stopped' | 'starting';\n startedAt?: never;\n msalInstance?: never;\n }\n | {\n phase: 'started';\n startedAt: Date;\n msalInstance: IPublicClientApplication;\n };\n\n/**\n * ExecOptions is used to specify options for the exec method.\n */\nexport type ExecOptions = (\n | {\n readonly msalTokenRequest?: SilentRequest;\n readonly permission?: never;\n }\n | { readonly msalTokenRequest?: never; readonly permission?: string }\n) & {\n readonly requestHeaders?: Record<string, string>;\n};\n\n/**\n * The main entry point for this library. This class streamlines Microsoft Teams app development\n * by simplifying the process of managing authentication, interacting with Microsoft Graph APIs,\n * and executing server-side functions.\n */\nexport class App {\n readonly options: AppOptions;\n readonly http: HttpClient;\n readonly graph: GraphClient;\n readonly clientId: string;\n protected _state: AppState = { phase: 'stopped' };\n\n /**\n * The apps logger\n */\n get log() : ILogger {\n return this._log;\n }\n protected _log: ILogger;\n\n /**\n * The date/time when the app was successfully started.\n */\n get startedAt() : Date | undefined {\n return this._state?.startedAt;\n }\n\n /** The msal instance used in this app. undefined until the app is started. */\n get msalInstance() : IPublicClientApplication | undefined {\n return this._state.msalInstance;\n }\n\n constructor(clientId: string, options: AppOptions = {}) {\n if (!clientId) {\n throw new Error('Invalid client ID.');\n }\n\n this.clientId = clientId;\n this.options = options;\n this._log = options?.logger || new ConsoleLogger('@teams/client');\n this.http = new HttpClient({\n baseUrl: options?.remoteApiOptions?.baseUrl,\n });\n this.graph = buildGraphClient(() => this.appStateGuard(), this._log);\n }\n\n /**\n * Starts the library and initializes the dependent teams-js and MSAL libraries.\n * @returns A promise that will be fulfilled when the app has started, or\n * rejected if the initialization fails or times out.\n */\n async start(): Promise<void> {\n if (this._state.phase !== 'stopped') {\n this._log.debug(`app already ${this._state.phase}`);\n return;\n }\n\n this._log.debug('app starting');\n this._state = { phase: 'starting' };\n\n await app.initialize();\n\n let msalInstance = this.options.msalOptions?.msalInstance;\n if (!msalInstance) {\n const msalConfig =\n this.options.msalOptions?.configuration ??\n buildMsalConfig(this.clientId, this._log);\n msalInstance = await createNestablePublicClientApplication(\n msalConfig\n );\n }\n\n this._state = { phase: 'started', msalInstance, startedAt: new Date() };\n\n // pre-warm consent for the specified scopes\n if (this.options.msalOptions?.prewarmScopes !== false) {\n const scopes = this.options.msalOptions?.prewarmScopes ?? ['.default'];\n this._log.debug(`prewarming consent for scopes: ${scopes.join(', ')}`);\n await this.ensureConsentForScopes(scopes);\n }\n\n this._log.debug('app started');\n }\n\n /**\n * Execute a server-side function\n * @param name The unique function name\n * @param data The data to send\n * @param options Options\n * @param options.msalTokenRequest Optional MSAL token request.\n * If omitted, a default token request is used.\n * @param options.requestHeaders Optional additional request headers.\n * @returns The function response\n */\n async exec<T = unknown>(\n name: string,\n data?: unknown,\n options?: ExecOptions\n ): Promise<T> {\n const { msalInstance } = this.appStateGuard();\n const context = await app.getContext();\n\n const remoteAppResource =\n this.options.remoteApiOptions?.remoteAppResource ??\n `api://${this.clientId}`;\n const accessToken = await acquireMsalAccessToken(\n msalInstance,\n options?.msalTokenRequest ??\n getStandardExecSilentRequest(remoteAppResource, options?.permission),\n this._log\n );\n\n const res = await this.http.post<T>(`/api/functions/${name}`, data, {\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'x-teams-app-session-id': context.app.sessionId,\n 'x-teams-channel-id': context.channel?.id,\n 'x-teams-chat-id': context.chat?.id,\n 'x-teams-meeting-id': context.meeting?.id,\n 'x-teams-message-id': context.app.parentMessageId || undefined,\n 'x-teams-page-id': context.page.id || undefined,\n 'x-teams-sub-page-id': context.page.subPageId || undefined,\n 'x-teams-team-id': context.team?.internalId,\n ...(options?.requestHeaders ?? {}),\n },\n });\n\n return res.data;\n }\n\n /**\n * Tests whether the user has consented to the specified scopes without prompting the user for consent.\n * @param scopes The scopes to check consent for.The scopes should be for a single resource, and they\n * should not mix the .default scope with named scopes.\n * @returns A promise that resolves to a boolean indicating whether the user has consented to the scopes.\n */\n async hasConsentForScopes(scopes: string[]): Promise<boolean> {\n const { msalInstance } = this.appStateGuard();\n\n return await hasConsentForScopes(msalInstance, scopes, this.log);\n }\n\n /**\n * Tests whether the user has consented to the specified scopes, and prompts them if not. This is useful for ensuring\n * that the user has consented to the required scopes before calling a graph API or other resource.\n * @param scopes - The scopes to prewarm consent for. The scopes should be for a single resource, and they\n * should not mix the .default scope with named scopes.\n * @returns A value indicating whether consent has been acquired for the specified scopes.\n */\n async ensureConsentForScopes(scopes: string[]): Promise<boolean> {\n const { msalInstance } = this.appStateGuard();\n\n try {\n const token = await acquireMsalAccessToken(\n msalInstance,\n { scopes },\n this.log\n );\n return !!token;\n } catch (ex) {\n return false;\n }\n }\n\n private appStateGuard(): AppState & { phase: 'started' } {\n if (this._state.phase !== 'started') {\n throw new Error('App not started');\n }\n return this._state;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/app.ts"],"names":["Htt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,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,oBAAoB,MAAA,EAAoC;AAC5D,IAAA,MAAM,EAAE,YAAA,EAAa,GAAI,IAAA,CAAK,aAAA,EAAc;AAE5C,IAAA,OAAO,MAAM,mBAAA,CAAoB,YAAA,EAAc,MAAA,EAAQ,KAAK,GAAG,CAAA;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,uBAAuB,MAAA,EAAoC;AAC/D,IAAA,MAAM,EAAE,YAAA,EAAa,GAAI,IAAA,CAAK,aAAA,EAAc;AAE5C,IAAA,IAAI;AACF,MAAA,MAAM,QAAQ,MAAM,sBAAA;AAAA,QAClB,YAAA;AAAA,QACA,EAAE,MAAA,EAAO;AAAA,QACT,IAAA,CAAK;AAAA,OACP;AACA,MAAA,OAAO,CAAC,CAAC,KAAA;AAAA,IACX,SAAS,EAAA,EAAI;AACX,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAAA,EAEQ,aAAA,GAAiD;AACvD,IAAA,IAAI,IAAA,CAAK,MAAA,CAAO,KAAA,KAAU,SAAA,EAAW;AACnC,MAAA,MAAM,IAAI,MAAM,iBAAiB,CAAA;AAAA,IACnC;AACA,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AACF","file":"app.mjs","sourcesContent":["import {\n createNestablePublicClientApplication,\n type Configuration,\n type IPublicClientApplication,\n type SilentRequest,\n} from '@azure/msal-browser';\n\nimport { app } from '@microsoft/teams-js';\nimport type { ILogger } from '@microsoft/teams.common';\nimport { ConsoleLogger, Client as HttpClient } from '@microsoft/teams.common';\nimport type { Client as GraphClient } from '@microsoft/teams.graph';\n\nimport { buildGraphClient } from './graph-utils';\nimport {\n acquireMsalAccessToken,\n buildMsalConfig,\n getStandardExecSilentRequest,\n hasConsentForScopes,\n} from './msal-utils';\n\n/**\n * Options to control how MSAL is initialized and used.\n */\nexport type MsalOptions = (\n | {\n /**\n * MSAL instance to use when making authenticated function calls to remote endpoints.\n * This is useful if you want to use a custom MSAL instance or if you want to share the\n * same MSAL instance across multiple apps.\n */\n readonly msalInstance?: IPublicClientApplication;\n readonly configuration?: never;\n }\n | {\n readonly msalInstance?: never;\n /**\n * MSAL configuration to use when constructing an MSAL instance used\n * to make authenticated function calls to remote endpoints. */\n readonly configuration?: Configuration;\n }\n) & {\n /**\n * Options to control scope consent pre-warming. If explicitly set to false, no pre-warming is performed.\n * If no value is provided, the default scope (i.e. \".default\") is pre-warmed. If a set of scopes is\n * provided, the specified scopes are pre-warmed. The scopes should be for a single resource, and they\n * should not mix the .default scope with named scopes.\n *\n * **Important:** On Teams Desktop (NAA via OneAuth broker), `.default` is not supported for Graph\n * token requests. You must provide explicit Graph scopes (e.g., `['User.Read', 'Mail.Read']`) for\n * your app to work on Desktop.\n */\n readonly prewarmScopes?: false | string[];\n};\n\nexport type RemoteApiOptions = {\n /**\n * The remote API base URL. If omitted, it's assumed that the remote API is hosted in the same domain as the app.\n */\n readonly baseUrl?: string;\n\n /**\n * The default resource name when building a token request for the Entra token to include when invoking\n * a remote function. This is useful when the API is hosted in an different AAD app from\n * the caller and is typically in the format 'api://<remoteAppClientId>'.\n * When invoking @see exec with default options or a permission name,\n * this value is used to build a token request in the format of '<remoteAppResource>/<permission>'.\n * If omitted, it's assumed that the API is hosted in the same AAD app as the caller, and the\n * token request is made for 'api://<clientId>/permission'.\n */\n readonly remoteAppResource?: string;\n};\n\nexport type AppOptions = {\n /**\n * Logger instance to use.\n */\n readonly logger?: ILogger;\n\n /**\n * Options to control how MSAL is initialized and used.\n */\n readonly msalOptions?: MsalOptions;\n\n /** Options to control how remote APIs are invoked. */\n readonly remoteApiOptions?: RemoteApiOptions;\n};\n\ntype AppState =\n | {\n phase: 'stopped' | 'starting';\n startedAt?: never;\n msalInstance?: never;\n }\n | {\n phase: 'started';\n startedAt: Date;\n msalInstance: IPublicClientApplication;\n };\n\n/**\n * ExecOptions is used to specify options for the exec method.\n */\nexport type ExecOptions = (\n | {\n readonly msalTokenRequest?: SilentRequest;\n readonly permission?: never;\n }\n | { readonly msalTokenRequest?: never; readonly permission?: string }\n) & {\n readonly requestHeaders?: Record<string, string>;\n};\n\n/**\n * The main entry point for this library. This class streamlines Microsoft Teams app development\n * by simplifying the process of managing authentication, interacting with Microsoft Graph APIs,\n * and executing server-side functions.\n */\nexport class App {\n readonly options: AppOptions;\n readonly http: HttpClient;\n readonly graph: GraphClient;\n readonly clientId: string;\n protected _state: AppState = { phase: 'stopped' };\n\n /**\n * The apps logger\n */\n get log() : ILogger {\n return this._log;\n }\n protected _log: ILogger;\n\n /**\n * The date/time when the app was successfully started.\n */\n get startedAt() : Date | undefined {\n return this._state?.startedAt;\n }\n\n /** The msal instance used in this app. undefined until the app is started. */\n get msalInstance() : IPublicClientApplication | undefined {\n return this._state.msalInstance;\n }\n\n constructor(clientId: string, options: AppOptions = {}) {\n if (!clientId) {\n throw new Error('Invalid client ID.');\n }\n\n this.clientId = clientId;\n this.options = options;\n this._log = options?.logger || new ConsoleLogger('@teams/client');\n this.http = new HttpClient({\n baseUrl: options?.remoteApiOptions?.baseUrl,\n });\n this.graph = buildGraphClient(\n () => this.appStateGuard(),\n this._log,\n this.options.msalOptions?.prewarmScopes\n ? () => this.options.msalOptions!.prewarmScopes as string[]\n : undefined\n );\n }\n\n /**\n * Starts the library and initializes the dependent teams-js and MSAL libraries.\n * @returns A promise that will be fulfilled when the app has started, or\n * rejected if the initialization fails or times out.\n */\n async start(): Promise<void> {\n if (this._state.phase !== 'stopped') {\n this._log.debug(`app already ${this._state.phase}`);\n return;\n }\n\n this._log.debug('app starting');\n this._state = { phase: 'starting' };\n\n await app.initialize();\n\n let msalInstance = this.options.msalOptions?.msalInstance;\n if (!msalInstance) {\n const msalConfig =\n this.options.msalOptions?.configuration ??\n buildMsalConfig(this.clientId, this._log);\n msalInstance = await createNestablePublicClientApplication(\n msalConfig\n );\n }\n\n this._state = { phase: 'started', msalInstance, startedAt: new Date() };\n\n // pre-warm consent for the specified scopes\n if (this.options.msalOptions?.prewarmScopes !== false) {\n const scopes = this.options.msalOptions?.prewarmScopes ?? ['.default'];\n this._log.debug(`prewarming consent for scopes: ${scopes.join(', ')}`);\n await this.ensureConsentForScopes(scopes);\n }\n\n this._log.debug('app started');\n }\n\n /**\n * Execute a server-side function\n * @param name The unique function name\n * @param data The data to send\n * @param options Options\n * @param options.msalTokenRequest Optional MSAL token request.\n * If omitted, a default token request is used.\n * @param options.requestHeaders Optional additional request headers.\n * @returns The function response\n */\n async exec<T = unknown>(\n name: string,\n data?: unknown,\n options?: ExecOptions\n ): Promise<T> {\n const { msalInstance } = this.appStateGuard();\n const context = await app.getContext();\n\n const remoteAppResource =\n this.options.remoteApiOptions?.remoteAppResource ??\n `api://${this.clientId}`;\n const accessToken = await acquireMsalAccessToken(\n msalInstance,\n options?.msalTokenRequest ??\n getStandardExecSilentRequest(remoteAppResource, options?.permission),\n this._log\n );\n\n const res = await this.http.post<T>(`/api/functions/${name}`, data, {\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'x-teams-app-session-id': context.app.sessionId,\n 'x-teams-channel-id': context.channel?.id,\n 'x-teams-chat-id': context.chat?.id,\n 'x-teams-meeting-id': context.meeting?.id,\n 'x-teams-message-id': context.app.parentMessageId || undefined,\n 'x-teams-page-id': context.page.id || undefined,\n 'x-teams-sub-page-id': context.page.subPageId || undefined,\n 'x-teams-team-id': context.team?.internalId,\n ...(options?.requestHeaders ?? {}),\n },\n });\n\n return res.data;\n }\n\n /**\n * Tests whether the user has consented to the specified scopes without prompting the user for consent.\n * @param scopes The scopes to check consent for.The scopes should be for a single resource, and they\n * should not mix the .default scope with named scopes.\n * @returns A promise that resolves to a boolean indicating whether the user has consented to the scopes.\n */\n async hasConsentForScopes(scopes: string[]): Promise<boolean> {\n const { msalInstance } = this.appStateGuard();\n\n return await hasConsentForScopes(msalInstance, scopes, this.log);\n }\n\n /**\n * Tests whether the user has consented to the specified scopes, and prompts them if not. This is useful for ensuring\n * that the user has consented to the required scopes before calling a graph API or other resource.\n * @param scopes - The scopes to prewarm consent for. The scopes should be for a single resource, and they\n * should not mix the .default scope with named scopes.\n * @returns A value indicating whether consent has been acquired for the specified scopes.\n */\n async ensureConsentForScopes(scopes: string[]): Promise<boolean> {\n const { msalInstance } = this.appStateGuard();\n\n try {\n const token = await acquireMsalAccessToken(\n msalInstance,\n { scopes },\n this.log\n );\n return !!token;\n } catch (ex) {\n return false;\n }\n }\n\n private appStateGuard(): AppState & { phase: 'started' } {\n if (this._state.phase !== 'started') {\n throw new Error('App not started');\n }\n return this._state;\n }\n}\n"]}
@@ -5,6 +5,6 @@ import '@azure/msal-browser';
5
5
 
6
6
  declare function buildGraphClient(getMsalInstance: () => {
7
7
  msalInstance: Parameters<typeof acquireMsalAccessToken>[0];
8
- }, logger: ILogger): Client;
8
+ }, logger: ILogger, getGraphScopes?: () => string[]): Client;
9
9
 
10
10
  export { buildGraphClient };
@@ -5,6 +5,6 @@ import '@azure/msal-browser';
5
5
 
6
6
  declare function buildGraphClient(getMsalInstance: () => {
7
7
  msalInstance: Parameters<typeof acquireMsalAccessToken>[0];
8
- }, logger: ILogger): Client;
8
+ }, logger: ILogger, getGraphScopes?: () => string[]): Client;
9
9
 
10
10
  export { buildGraphClient };
@@ -4,13 +4,15 @@ var teams_common = require('@microsoft/teams.common');
4
4
  var teams_graph = require('@microsoft/teams.graph');
5
5
  var msalUtils = require('./msal-utils');
6
6
 
7
- function buildGraphClient(getMsalInstance, logger) {
7
+ function buildGraphClient(getMsalInstance, logger, getGraphScopes) {
8
8
  {
9
9
  const graphRequestAccessTokenInterceptor = async (ctx) => {
10
10
  const { msalInstance } = getMsalInstance();
11
+ const providedScopes = getGraphScopes?.();
12
+ const scopes = providedScopes && providedScopes.length > 0 ? providedScopes : [".default"];
11
13
  const accessToken = await msalUtils.acquireMsalAccessToken(
12
14
  msalInstance,
13
- { scopes: [".default"] },
15
+ { scopes },
14
16
  logger
15
17
  );
16
18
  ctx.config.headers.set("Authorization", `Bearer ${accessToken}`);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/graph-utils.ts"],"names":["acquireMsalAccessToken","GraphClient","HttpClient"],"mappings":";;;;;;AAKO,SAAS,gBAAA,CACd,iBACA,MAAA,EACa;AACb,EAAA;AACE,IAAA,MAAM,kCAAA,GAAqC,OAAO,GAAA,KAAwB;AACxE,MAAA,MAAM,EAAE,YAAA,EAAa,GAAI,eAAA,EAAgB;AAIzC,MAAA,MAAM,cAAc,MAAMA,gCAAA;AAAA,QACxB,YAAA;AAAA,QACA,EAAE,MAAA,EAAQ,CAAC,UAAU,CAAA,EAAE;AAAA,QACvB;AAAA,OACF;AAEA,MAAA,GAAA,CAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,eAAA,EAAiB,CAAA,OAAA,EAAU,WAAW,CAAA,CAAE,CAAA;AAC/D,MAAA,OAAO,GAAA,CAAI,MAAA;AAAA,IACb,CAAA;AAEA,IAAA,OAAO,IAAIC,kBAAA;AAAA,MACT,IAAIC,mBAAA,CAAW;AAAA,QACb,YAAA,EAAc,CAAC,EAAE,OAAA,EAAS,oCAAoC;AAAA,OAC/D;AAAA,KACH;AAAA,EACF;AACF","file":"graph-utils.js","sourcesContent":["import { Client as HttpClient, type ILogger, type RequestContext } from '@microsoft/teams.common';\nimport { Client as GraphClient } from '@microsoft/teams.graph';\n\nimport { acquireMsalAccessToken } from './msal-utils';\n\nexport function buildGraphClient(\n getMsalInstance: () => { msalInstance: Parameters<typeof acquireMsalAccessToken>[0] },\n logger: ILogger\n): GraphClient {\n {\n const graphRequestAccessTokenInterceptor = async (ctx: RequestContext) => {\n const { msalInstance } = getMsalInstance();\n\n // The developer should already have made sure that the user has consented to the scope\n // needed for the graph API they're calling, so requesting '.default' should be sufficient.\n const accessToken = await acquireMsalAccessToken(\n msalInstance,\n { scopes: ['.default'] },\n logger\n );\n\n ctx.config.headers.set('Authorization', `Bearer ${accessToken}`);\n return ctx.config;\n };\n\n return new GraphClient(\n new HttpClient({\n interceptors: [{ request: graphRequestAccessTokenInterceptor }],\n })\n );\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/graph-utils.ts"],"names":["acquireMsalAccessToken","GraphClient","HttpClient"],"mappings":";;;;;;AAKO,SAAS,gBAAA,CACd,eAAA,EACA,MAAA,EACA,cAAA,EACa;AACb,EAAA;AACE,IAAA,MAAM,kCAAA,GAAqC,OAAO,GAAA,KAAwB;AACxE,MAAA,MAAM,EAAE,YAAA,EAAa,GAAI,eAAA,EAAgB;AAIzC,MAAA,MAAM,iBAAiB,cAAA,IAAiB;AACxC,MAAA,MAAM,SAAU,cAAA,IAAkB,cAAA,CAAe,SAAS,CAAA,GAAK,cAAA,GAAiB,CAAC,UAAU,CAAA;AAE3F,MAAA,MAAM,cAAc,MAAMA,gCAAA;AAAA,QACxB,YAAA;AAAA,QACA,EAAE,MAAA,EAAO;AAAA,QACT;AAAA,OACF;AAEA,MAAA,GAAA,CAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,eAAA,EAAiB,CAAA,OAAA,EAAU,WAAW,CAAA,CAAE,CAAA;AAC/D,MAAA,OAAO,GAAA,CAAI,MAAA;AAAA,IACb,CAAA;AAEA,IAAA,OAAO,IAAIC,kBAAA;AAAA,MACT,IAAIC,mBAAA,CAAW;AAAA,QACb,YAAA,EAAc,CAAC,EAAE,OAAA,EAAS,oCAAoC;AAAA,OAC/D;AAAA,KACH;AAAA,EACF;AACF","file":"graph-utils.js","sourcesContent":["import { Client as HttpClient, type ILogger, type RequestContext } from '@microsoft/teams.common';\nimport { Client as GraphClient } from '@microsoft/teams.graph';\n\nimport { acquireMsalAccessToken } from './msal-utils';\n\nexport function buildGraphClient(\n getMsalInstance: () => { msalInstance: Parameters<typeof acquireMsalAccessToken>[0] },\n logger: ILogger,\n getGraphScopes?: () => string[]\n): GraphClient {\n {\n const graphRequestAccessTokenInterceptor = async (ctx: RequestContext) => {\n const { msalInstance } = getMsalInstance();\n\n // On Teams Desktop (NAA via OneAuth broker), the '.default' scope is not resolved\n // the same way as on Web. Use explicit Graph scopes when available.\n const providedScopes = getGraphScopes?.();\n const scopes = (providedScopes && providedScopes.length > 0) ? providedScopes : ['.default'];\n\n const accessToken = await acquireMsalAccessToken(\n msalInstance,\n { scopes },\n logger\n );\n\n ctx.config.headers.set('Authorization', `Bearer ${accessToken}`);\n return ctx.config;\n };\n\n return new GraphClient(\n new HttpClient({\n interceptors: [{ request: graphRequestAccessTokenInterceptor }],\n })\n );\n }\n}\n"]}
@@ -2,13 +2,15 @@ import { Client as Client$1 } from '@microsoft/teams.common';
2
2
  import { Client } from '@microsoft/teams.graph';
3
3
  import { acquireMsalAccessToken } from './msal-utils.mjs';
4
4
 
5
- function buildGraphClient(getMsalInstance, logger) {
5
+ function buildGraphClient(getMsalInstance, logger, getGraphScopes) {
6
6
  {
7
7
  const graphRequestAccessTokenInterceptor = async (ctx) => {
8
8
  const { msalInstance } = getMsalInstance();
9
+ const providedScopes = getGraphScopes?.();
10
+ const scopes = providedScopes && providedScopes.length > 0 ? providedScopes : [".default"];
9
11
  const accessToken = await acquireMsalAccessToken(
10
12
  msalInstance,
11
- { scopes: [".default"] },
13
+ { scopes },
12
14
  logger
13
15
  );
14
16
  ctx.config.headers.set("Authorization", `Bearer ${accessToken}`);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/graph-utils.ts"],"names":["GraphClient","HttpClient"],"mappings":";;;;AAKO,SAAS,gBAAA,CACd,iBACA,MAAA,EACa;AACb,EAAA;AACE,IAAA,MAAM,kCAAA,GAAqC,OAAO,GAAA,KAAwB;AACxE,MAAA,MAAM,EAAE,YAAA,EAAa,GAAI,eAAA,EAAgB;AAIzC,MAAA,MAAM,cAAc,MAAM,sBAAA;AAAA,QACxB,YAAA;AAAA,QACA,EAAE,MAAA,EAAQ,CAAC,UAAU,CAAA,EAAE;AAAA,QACvB;AAAA,OACF;AAEA,MAAA,GAAA,CAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,eAAA,EAAiB,CAAA,OAAA,EAAU,WAAW,CAAA,CAAE,CAAA;AAC/D,MAAA,OAAO,GAAA,CAAI,MAAA;AAAA,IACb,CAAA;AAEA,IAAA,OAAO,IAAIA,MAAA;AAAA,MACT,IAAIC,QAAA,CAAW;AAAA,QACb,YAAA,EAAc,CAAC,EAAE,OAAA,EAAS,oCAAoC;AAAA,OAC/D;AAAA,KACH;AAAA,EACF;AACF","file":"graph-utils.mjs","sourcesContent":["import { Client as HttpClient, type ILogger, type RequestContext } from '@microsoft/teams.common';\nimport { Client as GraphClient } from '@microsoft/teams.graph';\n\nimport { acquireMsalAccessToken } from './msal-utils';\n\nexport function buildGraphClient(\n getMsalInstance: () => { msalInstance: Parameters<typeof acquireMsalAccessToken>[0] },\n logger: ILogger\n): GraphClient {\n {\n const graphRequestAccessTokenInterceptor = async (ctx: RequestContext) => {\n const { msalInstance } = getMsalInstance();\n\n // The developer should already have made sure that the user has consented to the scope\n // needed for the graph API they're calling, so requesting '.default' should be sufficient.\n const accessToken = await acquireMsalAccessToken(\n msalInstance,\n { scopes: ['.default'] },\n logger\n );\n\n ctx.config.headers.set('Authorization', `Bearer ${accessToken}`);\n return ctx.config;\n };\n\n return new GraphClient(\n new HttpClient({\n interceptors: [{ request: graphRequestAccessTokenInterceptor }],\n })\n );\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/graph-utils.ts"],"names":["GraphClient","HttpClient"],"mappings":";;;;AAKO,SAAS,gBAAA,CACd,eAAA,EACA,MAAA,EACA,cAAA,EACa;AACb,EAAA;AACE,IAAA,MAAM,kCAAA,GAAqC,OAAO,GAAA,KAAwB;AACxE,MAAA,MAAM,EAAE,YAAA,EAAa,GAAI,eAAA,EAAgB;AAIzC,MAAA,MAAM,iBAAiB,cAAA,IAAiB;AACxC,MAAA,MAAM,SAAU,cAAA,IAAkB,cAAA,CAAe,SAAS,CAAA,GAAK,cAAA,GAAiB,CAAC,UAAU,CAAA;AAE3F,MAAA,MAAM,cAAc,MAAM,sBAAA;AAAA,QACxB,YAAA;AAAA,QACA,EAAE,MAAA,EAAO;AAAA,QACT;AAAA,OACF;AAEA,MAAA,GAAA,CAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,eAAA,EAAiB,CAAA,OAAA,EAAU,WAAW,CAAA,CAAE,CAAA;AAC/D,MAAA,OAAO,GAAA,CAAI,MAAA;AAAA,IACb,CAAA;AAEA,IAAA,OAAO,IAAIA,MAAA;AAAA,MACT,IAAIC,QAAA,CAAW;AAAA,QACb,YAAA,EAAc,CAAC,EAAE,OAAA,EAAS,oCAAoC;AAAA,OAC/D;AAAA,KACH;AAAA,EACF;AACF","file":"graph-utils.mjs","sourcesContent":["import { Client as HttpClient, type ILogger, type RequestContext } from '@microsoft/teams.common';\nimport { Client as GraphClient } from '@microsoft/teams.graph';\n\nimport { acquireMsalAccessToken } from './msal-utils';\n\nexport function buildGraphClient(\n getMsalInstance: () => { msalInstance: Parameters<typeof acquireMsalAccessToken>[0] },\n logger: ILogger,\n getGraphScopes?: () => string[]\n): GraphClient {\n {\n const graphRequestAccessTokenInterceptor = async (ctx: RequestContext) => {\n const { msalInstance } = getMsalInstance();\n\n // On Teams Desktop (NAA via OneAuth broker), the '.default' scope is not resolved\n // the same way as on Web. Use explicit Graph scopes when available.\n const providedScopes = getGraphScopes?.();\n const scopes = (providedScopes && providedScopes.length > 0) ? providedScopes : ['.default'];\n\n const accessToken = await acquireMsalAccessToken(\n msalInstance,\n { scopes },\n logger\n );\n\n ctx.config.headers.set('Authorization', `Bearer ${accessToken}`);\n return ctx.config;\n };\n\n return new GraphClient(\n new HttpClient({\n interceptors: [{ request: graphRequestAccessTokenInterceptor }],\n })\n );\n }\n}\n"]}
@@ -2,6 +2,16 @@
2
2
 
3
3
  var msalBrowser = require('@azure/msal-browser');
4
4
 
5
+ const shouldTryPopup = (ex) => {
6
+ if (ex instanceof msalBrowser.InteractionRequiredAuthError) {
7
+ return true;
8
+ }
9
+ const errorCode = ex?.errorCode ?? "";
10
+ if (errorCode === "ApiContractViolation") {
11
+ return true;
12
+ }
13
+ return false;
14
+ };
5
15
  const getStandardExecSilentRequest = (resource, permission = "access_as_user") => ({
6
16
  scopes: [`${resource}/${permission}`]
7
17
  });
@@ -9,7 +19,7 @@ const buildMsalConfig = (clientId, logger) => {
9
19
  return {
10
20
  auth: {
11
21
  clientId,
12
- authority: "",
22
+ supportsNestedAppAuth: true,
13
23
  redirectUri: "/",
14
24
  postLogoutRedirectUri: "/"
15
25
  },
@@ -43,8 +53,7 @@ const acquireMsalAccessToken = async (msalInstance, request, logger) => {
43
53
  const response = await msalInstance.acquireTokenSilent(request);
44
54
  return response.accessToken;
45
55
  } catch (ex) {
46
- const tryAcquireTokenPopup = ex instanceof msalBrowser.InteractionRequiredAuthError;
47
- if (!tryAcquireTokenPopup) {
56
+ if (!shouldTryPopup(ex)) {
48
57
  logger.error("acquireTokenSilent failed", ex);
49
58
  throw ex;
50
59
  }
@@ -54,7 +63,15 @@ const acquireMsalAccessToken = async (msalInstance, request, logger) => {
54
63
  const response = await msalInstance.acquireTokenPopup(request);
55
64
  return response.accessToken;
56
65
  } catch (ex) {
57
- logger.error("acquireTokenPopup failed", ex);
66
+ const errorCode = ex?.errorCode ?? "";
67
+ if (errorCode === "ApiContractViolation") {
68
+ logger.error(
69
+ "acquireTokenPopup failed with ApiContractViolation. On Teams Desktop, the OneAuth broker cannot resolve the '.default' scope. Set explicit scopes in msalOptions.prewarmScopes (e.g., ['User.Read']) for Desktop compatibility.",
70
+ ex
71
+ );
72
+ } else {
73
+ logger.error("acquireTokenPopup failed", ex);
74
+ }
58
75
  throw ex;
59
76
  }
60
77
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/msal-utils.ts"],"names":["LogLevel","InteractionRequiredAuthError"],"mappings":";;;;AAgBO,MAAM,4BAAA,GAA+B,CAC1C,QAAA,EACA,UAAA,GAAa,gBAAA,MACM;AAAA,EACnB,QAAQ,CAAC,CAAA,EAAG,QAAQ,CAAA,CA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AAAA,IACR;AAAA,EACF;AAEA,EAAA,IAAI;AACF,IAAA,MAAA,CAAO,MAAM,qDAAqD,CAAA;AAClE,IAAA,MAAM,QAAA,GAAW,MAAM,YAAA,CAAa,iBAAA,CAAkB,OAAO,CAAA;AAC7D,IAAA,OAAO,QAAA,CAAS,WAAA;AAAA,EAClB,SAAS,EAAA,EAAI;AACX,IAAA,MAAA,CAAO,KAAA,CAAM,4BAA4B,EAAE,CAAA;AAC3C,IAAA,MAAM,EAAA;AAAA,EACR;AACF;AAWO,MAAM,mBAAA,GAAsB,OACjC,YAAA,EACA,MAAA,EACA,MAAA,KACqB;AACrB,EAAA,IAAI;AACF,IAAA,MAAM,aAAa,kBAAA,CAAmB;AAAA,MACpC;AAAA,KACD,CAAA;AAED,IAAA,OAAO,IAAA;AAAA,EACT,SAAS,EAAA,EAAI;AAGX,IAAA,MAAM,0BAA0B,EAAA,YAAcA,wCAAA;AAC9C,IAAA,MAAM,QAAA,GAAW,0BAA0B,OAAA,GAAU,OAAA;AACrD,IAAA,MAAA,CAAO,GAAA,CAAI,QAAA,EAAU,4BAAA,EAA8B,EAAE,CAAA;AACrD,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"msal-utils.js","sourcesContent":["import {\n type Configuration,\n type IPublicClientApplication,\n InteractionRequiredAuthError,\n LogLevel,\n type SilentRequest,\n} from '@azure/msal-browser';\n\nimport type { ILogger } from '@microsoft/teams.common';\n\n/**\n * Gets a silent request used to acquire an Entra access token for invoking remote functions on behalf of a user.\n * @param resource The resource to use, e.g 'api://<clientId>'.\n * @param permission The permission to request. Defaults to 'access_as_user'.\n * @returns\n */\nexport const getStandardExecSilentRequest = (\n resource: string,\n permission = 'access_as_user'\n): SilentRequest => ({\n scopes: [`${resource}/${permission}`],\n});\n\n/**\n * Builds a default MSAL configuration for the specified client ID.\n * @param clientId The application client ID.\n * @param logger The logger instance to use for logging MSAL events.\n * @returns A default MSAL configuration object suitable for creating a\n * @see{IPublicClientApplication} instance for a multi-tenant application.\n */\nexport const buildMsalConfig = (clientId: string, logger: ILogger): Configuration => {\n return {\n auth: {\n clientId,\n authority: '',\n redirectUri: '/',\n postLogoutRedirectUri: '/',\n },\n system: {\n loggerOptions: {\n piiLoggingEnabled: false,\n loggerCallback: (level, message) => {\n switch (level) {\n case LogLevel.Error:\n logger.error(message);\n return;\n case LogLevel.Info:\n logger.info(message);\n return;\n case LogLevel.Verbose:\n logger.debug(message);\n return;\n case LogLevel.Warning:\n logger.warn(message);\n return;\n default:\n return;\n }\n },\n },\n },\n };\n};\n\n/**\n * Acquires an access token using MSAL. It first attempts to acquire the token silently,\n * and if that fails with an InteractionRequiredAuthError, it falls back to acquiring the\n * token via a popup.\n * @param msalInstance The MSAL instance to use for acquiring the token.\n * @param request The token request object.\n * @param logger The logger instance to use for logging errors.\n * @returns A promise that resolves to the acquired access token.\n */\nexport const acquireMsalAccessToken = async (\n msalInstance: Pick<IPublicClientApplication, 'acquireTokenSilent' | 'acquireTokenPopup'>,\n request: SilentRequest,\n logger: ILogger\n): Promise<string> => {\n try {\n const response = await msalInstance.acquireTokenSilent(request);\n return response.accessToken;\n } catch (ex) {\n // InteractionRequiredAuthError indicates that the user may not have consented to the requested\n // scope yet -- for this, we can fall back on acquireTokenPopup instead.\n const tryAcquireTokenPopup = ex instanceof InteractionRequiredAuthError;\n if (!tryAcquireTokenPopup) {\n logger.error('acquireTokenSilent failed', ex);\n throw ex;\n }\n }\n\n try {\n logger.debug('acquireTokenSilent failed; trying acquireTokenPopup');\n const response = await msalInstance.acquireTokenPopup(request);\n return response.accessToken;\n } catch (ex) {\n logger.error('acquireTokenPopup failed', ex);\n throw ex;\n }\n};\n\n/**\n * Tests whether the user has consented to the specified scopes by attempting to acquire a token silently.\n * If the token acquisition is successful, it indicates that the user has consented to the scopes.\n * If it fails, it indicates that the user has not consented to the scopes.\n * @param msalInstance The MSAL instance to use.\n * @param scopes The scopes to check consent for. The scopes should not mix resources, or mix default scope with non-default scopes.\n * @param logger The logger instance to use.\n * @returns A promise that resolves to a boolean indicating whether the user has consented to the scopes.\n */\nexport const hasConsentForScopes = async (\n msalInstance: Pick<IPublicClientApplication, 'acquireTokenSilent'>,\n scopes: string[],\n logger: ILogger\n): Promise<boolean> => {\n try {\n await msalInstance.acquireTokenSilent({\n scopes,\n });\n\n return true;\n } catch (ex) {\n // InteractionRequiredAuthError indicates that the user has not consented to the requested scope yet.\n // This is not an error, but may be interesting when trouble shooting.\n const acquireTokenPopupNeeded = ex instanceof InteractionRequiredAuthError;\n const logLevel = acquireTokenPopupNeeded ? 'debug' : 'error';\n logger.log(logLevel, 'hasConsentForScopes failed', ex);\n return false;\n }\n};\n"]}
1
+ {"version":3,"sources":["../src/msal-utils.ts"],"names":["InteractionRequiredAuthError","LogLevel"],"mappings":";;;;AAiBA,MAAM,cAAA,GAAiB,CAAC,EAAA,KAAyB;AAC/C,EAAA,IAAI,cAAcA,wCAAA,EAA8B;AAC9C,IAAA,OAAO,IAAA;AAAA,EACT;AAIA,EAAA,MAAM,SAAA,GAAa,IAAkB,SAAA,IAAa,EAAA;AAClD,EAAA,IAAI,cAAc,sBAAA,EAAwB;AACxC,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO,KAAA;AACT,CAAA;AAQO,MAAM,4BAAA,GAA+B,CAC1C,QAAA,EACA,UAAA,GAAa,gBAAA,MACM;AAAA,EACnB,QAAQ,CAAC,CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,UAAU,CAAA,CAAE;AACtC,CAAA;AASO,MAAM,eAAA,GAAkB,CAAC,QAAA,EAAkB,MAAA,KAAmC;AACnF,EAAA,OAAO;AAAA,IACL,IAAA,EAAM;AAAA,MACJ,QAAA;AAAA,MACA,qBAAA,EAAuB,IAAA;AAAA,MACvB,WAAA,EAAa,GAAA;AAAA,MACb,qBAAA,EAAuB;AAAA,KACzB;AAAA,IACA,MAAA,EAAQ;AAAA,MACN,aAAA,EAAe;AAAA,QACb,iBAAA,EAAmB,KAAA;AAA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;AAAA,QAGA;AAAA,OACF;AAAA,IACF,CAAA,MAAO;AACL,MAAA,MAAA,CAAO,KAAA,CAAM,4BAA4B,EAAE,CAAA;AAAA,IAC7C;AACA,IAAA,MAAM,EAAA;AAAA,EACR;AACF;AAWO,MAAM,mBAAA,GAAsB,OACjC,YAAA,EACA,MAAA,EACA,MAAA,KACqB;AACrB,EAAA,IAAI;AACF,IAAA,MAAM,aAAa,kBAAA,CAAmB;AAAA,MACpC;AAAA,KACD,CAAA;AAED,IAAA,OAAO,IAAA;AAAA,EACT,SAAS,EAAA,EAAI;AAGX,IAAA,MAAM,0BAA0B,EAAA,YAAcD,wCAAA;AAC9C,IAAA,MAAM,QAAA,GAAW,0BAA0B,OAAA,GAAU,OAAA;AACrD,IAAA,MAAA,CAAO,GAAA,CAAI,QAAA,EAAU,4BAAA,EAA8B,EAAE,CAAA;AACrD,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"msal-utils.js","sourcesContent":["import {\n type AuthError,\n type Configuration,\n type IPublicClientApplication,\n InteractionRequiredAuthError,\n LogLevel,\n type SilentRequest,\n} from '@azure/msal-browser';\n\nimport type { ILogger } from '@microsoft/teams.common';\n\n/**\n * Checks if an error from the NAA bridge should be treated as requiring user interaction.\n * On Teams Desktop, the OneAuth/WAM broker may return errors like `ApiContractViolation`\n * (e.g., \"declined scopes\") that are not mapped to `InteractionRequiredAuthError` by MSAL,\n * but should still trigger a popup-based consent attempt.\n */\nconst shouldTryPopup = (ex: unknown): boolean => {\n if (ex instanceof InteractionRequiredAuthError) {\n return true;\n }\n\n // On Desktop (NAA via OneAuth), \"ApiContractViolation\" with declined scopes\n // indicates the broker couldn't silently satisfy the request -- try interactive.\n const errorCode = (ex as AuthError)?.errorCode ?? '';\n if (errorCode === 'ApiContractViolation') {\n return true;\n }\n\n return false;\n};\n\n/**\n * Gets a silent request used to acquire an Entra access token for invoking remote functions on behalf of a user.\n * @param resource The resource to use, e.g 'api://<clientId>'.\n * @param permission The permission to request. Defaults to 'access_as_user'.\n * @returns\n */\nexport const getStandardExecSilentRequest = (\n resource: string,\n permission = 'access_as_user'\n): SilentRequest => ({\n scopes: [`${resource}/${permission}`],\n});\n\n/**\n * Builds a default MSAL configuration for the specified client ID.\n * @param clientId The application client ID.\n * @param logger The logger instance to use for logging MSAL events.\n * @returns A default MSAL configuration object suitable for creating a\n * @see{IPublicClientApplication} instance for a multi-tenant application.\n */\nexport const buildMsalConfig = (clientId: string, logger: ILogger): Configuration => {\n return {\n auth: {\n clientId,\n supportsNestedAppAuth: true,\n redirectUri: '/',\n postLogoutRedirectUri: '/',\n },\n system: {\n loggerOptions: {\n piiLoggingEnabled: false,\n loggerCallback: (level, message) => {\n switch (level) {\n case LogLevel.Error:\n logger.error(message);\n return;\n case LogLevel.Info:\n logger.info(message);\n return;\n case LogLevel.Verbose:\n logger.debug(message);\n return;\n case LogLevel.Warning:\n logger.warn(message);\n return;\n default:\n return;\n }\n },\n },\n },\n };\n};\n\n/**\n * Acquires an access token using MSAL. It first attempts to acquire the token silently,\n * and if that fails with an InteractionRequiredAuthError, it falls back to acquiring the\n * token via a popup.\n * @param msalInstance The MSAL instance to use for acquiring the token.\n * @param request The token request object.\n * @param logger The logger instance to use for logging errors.\n * @returns A promise that resolves to the acquired access token.\n */\nexport const acquireMsalAccessToken = async (\n msalInstance: Pick<IPublicClientApplication, 'acquireTokenSilent' | 'acquireTokenPopup'>,\n request: SilentRequest,\n logger: ILogger\n): Promise<string> => {\n try {\n const response = await msalInstance.acquireTokenSilent(request);\n return response.accessToken;\n } catch (ex) {\n // InteractionRequiredAuthError or broker-level errors (e.g., ApiContractViolation on\n // Teams Desktop) indicate that the user may not have consented to the requested scope,\n // or the broker couldn't satisfy it silently -- fall back on acquireTokenPopup.\n if (!shouldTryPopup(ex)) {\n logger.error('acquireTokenSilent failed', ex);\n throw ex;\n }\n }\n\n try {\n logger.debug('acquireTokenSilent failed; trying acquireTokenPopup');\n const response = await msalInstance.acquireTokenPopup(request);\n return response.accessToken;\n } catch (ex) {\n const errorCode = (ex as AuthError)?.errorCode ?? '';\n if (errorCode === 'ApiContractViolation') {\n logger.error(\n 'acquireTokenPopup failed with ApiContractViolation. On Teams Desktop, the OneAuth broker ' +\n 'cannot resolve the \\'.default\\' scope. Set explicit scopes in msalOptions.prewarmScopes ' +\n '(e.g., [\\'User.Read\\']) for Desktop compatibility.',\n ex\n );\n } else {\n logger.error('acquireTokenPopup failed', ex);\n }\n throw ex;\n }\n};\n\n/**\n * Tests whether the user has consented to the specified scopes by attempting to acquire a token silently.\n * If the token acquisition is successful, it indicates that the user has consented to the scopes.\n * If it fails, it indicates that the user has not consented to the scopes.\n * @param msalInstance The MSAL instance to use.\n * @param scopes The scopes to check consent for. The scopes should not mix resources, or mix default scope with non-default scopes.\n * @param logger The logger instance to use.\n * @returns A promise that resolves to a boolean indicating whether the user has consented to the scopes.\n */\nexport const hasConsentForScopes = async (\n msalInstance: Pick<IPublicClientApplication, 'acquireTokenSilent'>,\n scopes: string[],\n logger: ILogger\n): Promise<boolean> => {\n try {\n await msalInstance.acquireTokenSilent({\n scopes,\n });\n\n return true;\n } catch (ex) {\n // InteractionRequiredAuthError indicates that the user has not consented to the requested scope yet.\n // This is not an error, but may be interesting when trouble shooting.\n const acquireTokenPopupNeeded = ex instanceof InteractionRequiredAuthError;\n const logLevel = acquireTokenPopupNeeded ? 'debug' : 'error';\n logger.log(logLevel, 'hasConsentForScopes failed', ex);\n return false;\n }\n};\n"]}
@@ -1,5 +1,15 @@
1
1
  import { LogLevel, InteractionRequiredAuthError } from '@azure/msal-browser';
2
2
 
3
+ const shouldTryPopup = (ex) => {
4
+ if (ex instanceof InteractionRequiredAuthError) {
5
+ return true;
6
+ }
7
+ const errorCode = ex?.errorCode ?? "";
8
+ if (errorCode === "ApiContractViolation") {
9
+ return true;
10
+ }
11
+ return false;
12
+ };
3
13
  const getStandardExecSilentRequest = (resource, permission = "access_as_user") => ({
4
14
  scopes: [`${resource}/${permission}`]
5
15
  });
@@ -7,7 +17,7 @@ const buildMsalConfig = (clientId, logger) => {
7
17
  return {
8
18
  auth: {
9
19
  clientId,
10
- authority: "",
20
+ supportsNestedAppAuth: true,
11
21
  redirectUri: "/",
12
22
  postLogoutRedirectUri: "/"
13
23
  },
@@ -41,8 +51,7 @@ const acquireMsalAccessToken = async (msalInstance, request, logger) => {
41
51
  const response = await msalInstance.acquireTokenSilent(request);
42
52
  return response.accessToken;
43
53
  } catch (ex) {
44
- const tryAcquireTokenPopup = ex instanceof InteractionRequiredAuthError;
45
- if (!tryAcquireTokenPopup) {
54
+ if (!shouldTryPopup(ex)) {
46
55
  logger.error("acquireTokenSilent failed", ex);
47
56
  throw ex;
48
57
  }
@@ -52,7 +61,15 @@ const acquireMsalAccessToken = async (msalInstance, request, logger) => {
52
61
  const response = await msalInstance.acquireTokenPopup(request);
53
62
  return response.accessToken;
54
63
  } catch (ex) {
55
- logger.error("acquireTokenPopup failed", ex);
64
+ const errorCode = ex?.errorCode ?? "";
65
+ if (errorCode === "ApiContractViolation") {
66
+ logger.error(
67
+ "acquireTokenPopup failed with ApiContractViolation. On Teams Desktop, the OneAuth broker cannot resolve the '.default' scope. Set explicit scopes in msalOptions.prewarmScopes (e.g., ['User.Read']) for Desktop compatibility.",
68
+ ex
69
+ );
70
+ } else {
71
+ logger.error("acquireTokenPopup failed", ex);
72
+ }
56
73
  throw ex;
57
74
  }
58
75
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/msal-utils.ts"],"names":[],"mappings":";;AAgBO,MAAM,4BAAA,GAA+B,CAC1C,QAAA,EACA,UAAA,GAAa,gBAAA,MACM;AAAA,EACnB,QAAQ,CAAC,CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,UAAU,CAAA,CAAE;AACtC,CAAA;AASO,MAAM,eAAA,GAAkB,CAAC,QAAA,EAAkB,MAAA,KAAmC;AACnF,EAAA,OAAO;AAAA,IACL,IAAA,EAAM;AAAA,MACJ,QAAA;AAAA,MACA,SAAA,EAAW,EAA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A;AAAA,EAClB,SAAS,EAAA,EAAI;AACX,IAAA,MAAA,CAAO,KAAA,CAAM,4BAA4B,EAAE,CAAA;AAC3C,IAAA,MAAM,EAAA;AAAA,EACR;AACF;AAWO,MAAM,mBAAA,GAAsB,OACjC,YAAA,EACA,MAAA,EACA,MAAA,KACqB;AACrB,EAAA,IAAI;AACF,IAAA,MAAM,aAAa,kBAAA,CAAmB;AAAA,MACpC;AAAA,KACD,CAAA;AAED,IAAA,OAAO,IAAA;AAAA,EACT,SAAS,EAAA,EAAI;AAGX,IAAA,MAAM,0BAA0B,EAAA,YAAc,4BAAA;AAC9C,IAAA,MAAM,QAAA,GAAW,0BAA0B,OAAA,GAAU,OAAA;AACrD,IAAA,MAAA,CAAO,GAAA,CAAI,QAAA,EAAU,4BAAA,EAA8B,EAAE,CAAA;AACrD,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"msal-utils.mjs","sourcesContent":["import {\n type Configuration,\n type IPublicClientApplication,\n InteractionRequiredAuthError,\n LogLevel,\n type SilentRequest,\n} from '@azure/msal-browser';\n\nimport type { ILogger } from '@microsoft/teams.common';\n\n/**\n * Gets a silent request used to acquire an Entra access token for invoking remote functions on behalf of a user.\n * @param resource The resource to use, e.g 'api://<clientId>'.\n * @param permission The permission to request. Defaults to 'access_as_user'.\n * @returns\n */\nexport const getStandardExecSilentRequest = (\n resource: string,\n permission = 'access_as_user'\n): SilentRequest => ({\n scopes: [`${resource}/${permission}`],\n});\n\n/**\n * Builds a default MSAL configuration for the specified client ID.\n * @param clientId The application client ID.\n * @param logger The logger instance to use for logging MSAL events.\n * @returns A default MSAL configuration object suitable for creating a\n * @see{IPublicClientApplication} instance for a multi-tenant application.\n */\nexport const buildMsalConfig = (clientId: string, logger: ILogger): Configuration => {\n return {\n auth: {\n clientId,\n authority: '',\n redirectUri: '/',\n postLogoutRedirectUri: '/',\n },\n system: {\n loggerOptions: {\n piiLoggingEnabled: false,\n loggerCallback: (level, message) => {\n switch (level) {\n case LogLevel.Error:\n logger.error(message);\n return;\n case LogLevel.Info:\n logger.info(message);\n return;\n case LogLevel.Verbose:\n logger.debug(message);\n return;\n case LogLevel.Warning:\n logger.warn(message);\n return;\n default:\n return;\n }\n },\n },\n },\n };\n};\n\n/**\n * Acquires an access token using MSAL. It first attempts to acquire the token silently,\n * and if that fails with an InteractionRequiredAuthError, it falls back to acquiring the\n * token via a popup.\n * @param msalInstance The MSAL instance to use for acquiring the token.\n * @param request The token request object.\n * @param logger The logger instance to use for logging errors.\n * @returns A promise that resolves to the acquired access token.\n */\nexport const acquireMsalAccessToken = async (\n msalInstance: Pick<IPublicClientApplication, 'acquireTokenSilent' | 'acquireTokenPopup'>,\n request: SilentRequest,\n logger: ILogger\n): Promise<string> => {\n try {\n const response = await msalInstance.acquireTokenSilent(request);\n return response.accessToken;\n } catch (ex) {\n // InteractionRequiredAuthError indicates that the user may not have consented to the requested\n // scope yet -- for this, we can fall back on acquireTokenPopup instead.\n const tryAcquireTokenPopup = ex instanceof InteractionRequiredAuthError;\n if (!tryAcquireTokenPopup) {\n logger.error('acquireTokenSilent failed', ex);\n throw ex;\n }\n }\n\n try {\n logger.debug('acquireTokenSilent failed; trying acquireTokenPopup');\n const response = await msalInstance.acquireTokenPopup(request);\n return response.accessToken;\n } catch (ex) {\n logger.error('acquireTokenPopup failed', ex);\n throw ex;\n }\n};\n\n/**\n * Tests whether the user has consented to the specified scopes by attempting to acquire a token silently.\n * If the token acquisition is successful, it indicates that the user has consented to the scopes.\n * If it fails, it indicates that the user has not consented to the scopes.\n * @param msalInstance The MSAL instance to use.\n * @param scopes The scopes to check consent for. The scopes should not mix resources, or mix default scope with non-default scopes.\n * @param logger The logger instance to use.\n * @returns A promise that resolves to a boolean indicating whether the user has consented to the scopes.\n */\nexport const hasConsentForScopes = async (\n msalInstance: Pick<IPublicClientApplication, 'acquireTokenSilent'>,\n scopes: string[],\n logger: ILogger\n): Promise<boolean> => {\n try {\n await msalInstance.acquireTokenSilent({\n scopes,\n });\n\n return true;\n } catch (ex) {\n // InteractionRequiredAuthError indicates that the user has not consented to the requested scope yet.\n // This is not an error, but may be interesting when trouble shooting.\n const acquireTokenPopupNeeded = ex instanceof InteractionRequiredAuthError;\n const logLevel = acquireTokenPopupNeeded ? 'debug' : 'error';\n logger.log(logLevel, 'hasConsentForScopes failed', ex);\n return false;\n }\n};\n"]}
1
+ {"version":3,"sources":["../src/msal-utils.ts"],"names":[],"mappings":";;AAiBA,MAAM,cAAA,GAAiB,CAAC,EAAA,KAAyB;AAC/C,EAAA,IAAI,cAAc,4BAAA,EAA8B;AAC9C,IAAA,OAAO,IAAA;AAAA,EACT;AAIA,EAAA,MAAM,SAAA,GAAa,IAAkB,SAAA,IAAa,EAAA;AAClD,EAAA,IAAI,cAAc,sBAAA,EAAwB;AACxC,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO,KAAA;AACT,CAAA;AAQO,MAAM,4BAAA,GAA+B,CAC1C,QAAA,EACA,UAAA,GAAa,gBAAA,MACM;AAAA,EACnB,QAAQ,CAAC,CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,UAAU,CAAA,CAAE;AACtC,CAAA;AASO,MAAM,eAAA,GAAkB,CAAC,QAAA,EAAkB,MAAA,KAAmC;AACnF,EAAA,OAAO;AAAA,IACL,IAAA,EAAM;AAAA,MACJ,QAAA;AAAA,MACA,qBAAA,EAAuB,IAAA;AAAA,MACvB,WAAA,EAAa,GAAA;AAAA,MACb,qBAAA,EAAuB;AAAA,KACzB;AAAA,IACA,MAAA,EAAQ;AAAA,MACN,aAAA,EAAe;AAAA,QACb,iBAAA,EAAmB,KAAA;AAAA,QACnB,cAAA,EAAgB,CAAC,KAAA,EAAO,OAAA,KAAY;AAClC,UAAA,QAAQ,KAAA;AAAO,YACb,KAAK,QAAA,CAAS,KAAA;AACZ,cAAA,MAAA,CAAO,MAAM,OAAO,CAAA;AACpB,cAAA;AAAA,YACF,KAAK,QAAA,CAAS,IAAA;AACZ,cAAA,MAAA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AAA,IAAI;AACF,IAAA,MAAM,aAAa,kBAAA,CAAmB;AAAA,MACpC;AAAA,KACD,CAAA;AAED,IAAA,OAAO,IAAA;AAAA,EACT,SAAS,EAAA,EAAI;AAGX,IAAA,MAAM,0BAA0B,EAAA,YAAc,4BAAA;AAC9C,IAAA,MAAM,QAAA,GAAW,0BAA0B,OAAA,GAAU,OAAA;AACrD,IAAA,MAAA,CAAO,GAAA,CAAI,QAAA,EAAU,4BAAA,EAA8B,EAAE,CAAA;AACrD,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"msal-utils.mjs","sourcesContent":["import {\n type AuthError,\n type Configuration,\n type IPublicClientApplication,\n InteractionRequiredAuthError,\n LogLevel,\n type SilentRequest,\n} from '@azure/msal-browser';\n\nimport type { ILogger } from '@microsoft/teams.common';\n\n/**\n * Checks if an error from the NAA bridge should be treated as requiring user interaction.\n * On Teams Desktop, the OneAuth/WAM broker may return errors like `ApiContractViolation`\n * (e.g., \"declined scopes\") that are not mapped to `InteractionRequiredAuthError` by MSAL,\n * but should still trigger a popup-based consent attempt.\n */\nconst shouldTryPopup = (ex: unknown): boolean => {\n if (ex instanceof InteractionRequiredAuthError) {\n return true;\n }\n\n // On Desktop (NAA via OneAuth), \"ApiContractViolation\" with declined scopes\n // indicates the broker couldn't silently satisfy the request -- try interactive.\n const errorCode = (ex as AuthError)?.errorCode ?? '';\n if (errorCode === 'ApiContractViolation') {\n return true;\n }\n\n return false;\n};\n\n/**\n * Gets a silent request used to acquire an Entra access token for invoking remote functions on behalf of a user.\n * @param resource The resource to use, e.g 'api://<clientId>'.\n * @param permission The permission to request. Defaults to 'access_as_user'.\n * @returns\n */\nexport const getStandardExecSilentRequest = (\n resource: string,\n permission = 'access_as_user'\n): SilentRequest => ({\n scopes: [`${resource}/${permission}`],\n});\n\n/**\n * Builds a default MSAL configuration for the specified client ID.\n * @param clientId The application client ID.\n * @param logger The logger instance to use for logging MSAL events.\n * @returns A default MSAL configuration object suitable for creating a\n * @see{IPublicClientApplication} instance for a multi-tenant application.\n */\nexport const buildMsalConfig = (clientId: string, logger: ILogger): Configuration => {\n return {\n auth: {\n clientId,\n supportsNestedAppAuth: true,\n redirectUri: '/',\n postLogoutRedirectUri: '/',\n },\n system: {\n loggerOptions: {\n piiLoggingEnabled: false,\n loggerCallback: (level, message) => {\n switch (level) {\n case LogLevel.Error:\n logger.error(message);\n return;\n case LogLevel.Info:\n logger.info(message);\n return;\n case LogLevel.Verbose:\n logger.debug(message);\n return;\n case LogLevel.Warning:\n logger.warn(message);\n return;\n default:\n return;\n }\n },\n },\n },\n };\n};\n\n/**\n * Acquires an access token using MSAL. It first attempts to acquire the token silently,\n * and if that fails with an InteractionRequiredAuthError, it falls back to acquiring the\n * token via a popup.\n * @param msalInstance The MSAL instance to use for acquiring the token.\n * @param request The token request object.\n * @param logger The logger instance to use for logging errors.\n * @returns A promise that resolves to the acquired access token.\n */\nexport const acquireMsalAccessToken = async (\n msalInstance: Pick<IPublicClientApplication, 'acquireTokenSilent' | 'acquireTokenPopup'>,\n request: SilentRequest,\n logger: ILogger\n): Promise<string> => {\n try {\n const response = await msalInstance.acquireTokenSilent(request);\n return response.accessToken;\n } catch (ex) {\n // InteractionRequiredAuthError or broker-level errors (e.g., ApiContractViolation on\n // Teams Desktop) indicate that the user may not have consented to the requested scope,\n // or the broker couldn't satisfy it silently -- fall back on acquireTokenPopup.\n if (!shouldTryPopup(ex)) {\n logger.error('acquireTokenSilent failed', ex);\n throw ex;\n }\n }\n\n try {\n logger.debug('acquireTokenSilent failed; trying acquireTokenPopup');\n const response = await msalInstance.acquireTokenPopup(request);\n return response.accessToken;\n } catch (ex) {\n const errorCode = (ex as AuthError)?.errorCode ?? '';\n if (errorCode === 'ApiContractViolation') {\n logger.error(\n 'acquireTokenPopup failed with ApiContractViolation. On Teams Desktop, the OneAuth broker ' +\n 'cannot resolve the \\'.default\\' scope. Set explicit scopes in msalOptions.prewarmScopes ' +\n '(e.g., [\\'User.Read\\']) for Desktop compatibility.',\n ex\n );\n } else {\n logger.error('acquireTokenPopup failed', ex);\n }\n throw ex;\n }\n};\n\n/**\n * Tests whether the user has consented to the specified scopes by attempting to acquire a token silently.\n * If the token acquisition is successful, it indicates that the user has consented to the scopes.\n * If it fails, it indicates that the user has not consented to the scopes.\n * @param msalInstance The MSAL instance to use.\n * @param scopes The scopes to check consent for. The scopes should not mix resources, or mix default scope with non-default scopes.\n * @param logger The logger instance to use.\n * @returns A promise that resolves to a boolean indicating whether the user has consented to the scopes.\n */\nexport const hasConsentForScopes = async (\n msalInstance: Pick<IPublicClientApplication, 'acquireTokenSilent'>,\n scopes: string[],\n logger: ILogger\n): Promise<boolean> => {\n try {\n await msalInstance.acquireTokenSilent({\n scopes,\n });\n\n return true;\n } catch (ex) {\n // InteractionRequiredAuthError indicates that the user has not consented to the requested scope yet.\n // This is not an error, but may be interesting when trouble shooting.\n const acquireTokenPopupNeeded = ex instanceof InteractionRequiredAuthError;\n const logLevel = acquireTokenPopupNeeded ? 'debug' : 'error';\n logger.log(logLevel, 'hasConsentForScopes failed', ex);\n return false;\n }\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@microsoft/teams.client",
3
- "version": "2.0.12",
3
+ "version": "2.0.14",
4
4
  "license": "MIT",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -38,15 +38,15 @@
38
38
  },
39
39
  "dependencies": {
40
40
  "@azure/msal-browser": "^4.9.1",
41
- "@microsoft/teams.api": "2.0.12",
42
- "@microsoft/teams.common": "2.0.12",
43
- "@microsoft/teams.graph": "2.0.12"
41
+ "@microsoft/teams.api": "2.0.14",
42
+ "@microsoft/teams.common": "2.0.14",
43
+ "@microsoft/teams.graph": "2.0.14"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "@microsoft/teams-js": "^2.35.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@microsoft/teams.config": "2.0.12",
49
+ "@microsoft/teams.config": "2.0.14",
50
50
  "@types/jest": "^29.5.12",
51
51
  "jest": "^29.7.0",
52
52
  "rimraf": "^6.0.1",