@azure/identity-cache-persistence 1.1.2-alpha.20240618.4 → 1.1.2-alpha.20240620.2

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.
@@ -10,6 +10,7 @@ import { IdentityClient } from "../../client/identityClient";
10
10
  import { calculateRegionalAuthority } from "../../regionalAuthority";
11
11
  import { getLogLevel } from "@azure/logger";
12
12
  import { resolveTenantId } from "../../util/tenantIdUtils";
13
+ import { interactiveBrowserMockable } from "./msalOpenBrowser";
13
14
  /**
14
15
  * The default logger used if no logger was passed in by the credential.
15
16
  */
@@ -334,6 +335,111 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
334
335
  });
335
336
  });
336
337
  }
338
+ function getTokenOnBehalfOf(scopes_1, userAssertionToken_1, clientSecretOrCertificate_1) {
339
+ return __awaiter(this, arguments, void 0, function* (scopes, userAssertionToken, clientSecretOrCertificate, options = {}) {
340
+ msalLogger.getToken.info(`Attempting to acquire token on behalf of another user`);
341
+ if (typeof clientSecretOrCertificate === "string") {
342
+ // Client secret
343
+ msalLogger.getToken.info(`Using client secret for on behalf of flow`);
344
+ state.msalConfig.auth.clientSecret = clientSecretOrCertificate;
345
+ }
346
+ else {
347
+ // Client certificate
348
+ msalLogger.getToken.info(`Using client certificate for on behalf of flow`);
349
+ state.msalConfig.auth.clientCertificate = clientSecretOrCertificate;
350
+ }
351
+ const msalApp = yield getConfidentialApp(options);
352
+ try {
353
+ const response = yield msalApp.acquireTokenOnBehalfOf({
354
+ scopes,
355
+ authority: state.msalConfig.auth.authority,
356
+ claims: options.claims,
357
+ oboAssertion: userAssertionToken,
358
+ });
359
+ ensureValidMsalToken(scopes, response, options);
360
+ msalLogger.getToken.info(formatSuccess(scopes));
361
+ return {
362
+ token: response.accessToken,
363
+ expiresOnTimestamp: response.expiresOn.getTime(),
364
+ };
365
+ }
366
+ catch (err) {
367
+ throw handleMsalError(scopes, err, options);
368
+ }
369
+ });
370
+ }
371
+ function getTokenByInteractiveRequest(scopes_1) {
372
+ return __awaiter(this, arguments, void 0, function* (scopes, options = {}) {
373
+ msalLogger.getToken.info(`Attempting to acquire token interactively`);
374
+ const app = yield getPublicApp(options);
375
+ /**
376
+ * A helper function that supports brokered authentication through the MSAL's public application.
377
+ *
378
+ * When options.useDefaultBrokerAccount is true, the method will attempt to authenticate using the default broker account.
379
+ * If the default broker account is not available, the method will fall back to interactive authentication.
380
+ */
381
+ function getBrokeredToken(useDefaultBrokerAccount) {
382
+ return __awaiter(this, void 0, void 0, function* () {
383
+ var _a;
384
+ msalLogger.verbose("Authentication will resume through the broker");
385
+ const interactiveRequest = createBaseInteractiveRequest();
386
+ if (state.pluginConfiguration.broker.parentWindowHandle) {
387
+ interactiveRequest.windowHandle = Buffer.from(state.pluginConfiguration.broker.parentWindowHandle);
388
+ }
389
+ else {
390
+ // this is a bug, as the pluginConfiguration handler should validate this case.
391
+ msalLogger.warning("Parent window handle is not specified for the broker. This may cause unexpected behavior. Please provide the parentWindowHandle.");
392
+ }
393
+ if (state.pluginConfiguration.broker.enableMsaPassthrough) {
394
+ ((_a = interactiveRequest.tokenQueryParameters) !== null && _a !== void 0 ? _a : (interactiveRequest.tokenQueryParameters = {}))["msal_request_type"] =
395
+ "consumer_passthrough";
396
+ }
397
+ if (useDefaultBrokerAccount) {
398
+ interactiveRequest.prompt = "none";
399
+ msalLogger.verbose("Attempting broker authentication using the default broker account");
400
+ }
401
+ else {
402
+ msalLogger.verbose("Attempting broker authentication without the default broker account");
403
+ }
404
+ try {
405
+ return yield app.acquireTokenInteractive(interactiveRequest);
406
+ }
407
+ catch (e) {
408
+ msalLogger.verbose(`Failed to authenticate through the broker: ${e.message}`);
409
+ // If we tried to use the default broker account and failed, fall back to interactive authentication
410
+ if (useDefaultBrokerAccount) {
411
+ return getBrokeredToken(/* useDefaultBrokerAccount: */ false);
412
+ }
413
+ else {
414
+ throw e;
415
+ }
416
+ }
417
+ });
418
+ }
419
+ function createBaseInteractiveRequest() {
420
+ var _a, _b;
421
+ return {
422
+ openBrowser: (url) => __awaiter(this, void 0, void 0, function* () {
423
+ yield interactiveBrowserMockable.open(url, { wait: true, newInstance: true });
424
+ }),
425
+ scopes,
426
+ authority: state.msalConfig.auth.authority,
427
+ claims: options === null || options === void 0 ? void 0 : options.claims,
428
+ loginHint: options === null || options === void 0 ? void 0 : options.loginHint,
429
+ errorTemplate: (_a = options === null || options === void 0 ? void 0 : options.browserCustomizationOptions) === null || _a === void 0 ? void 0 : _a.errorMessage,
430
+ successTemplate: (_b = options === null || options === void 0 ? void 0 : options.browserCustomizationOptions) === null || _b === void 0 ? void 0 : _b.successMessage,
431
+ };
432
+ }
433
+ return withSilentAuthentication(app, scopes, options, () => __awaiter(this, void 0, void 0, function* () {
434
+ var _a;
435
+ const interactiveRequest = createBaseInteractiveRequest();
436
+ if (state.pluginConfiguration.broker.isEnabled) {
437
+ return getBrokeredToken((_a = state.pluginConfiguration.broker.useDefaultBrokerAccount) !== null && _a !== void 0 ? _a : false);
438
+ }
439
+ return app.acquireTokenInteractive(interactiveRequest);
440
+ }));
441
+ });
442
+ }
337
443
  return {
338
444
  getActiveAccount,
339
445
  getTokenByClientSecret,
@@ -342,6 +448,8 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
342
448
  getTokenByDeviceCode,
343
449
  getTokenByUsernamePassword,
344
450
  getTokenByAuthorizationCode,
451
+ getTokenOnBehalfOf,
452
+ getTokenByInteractiveRequest,
345
453
  };
346
454
  }
347
455
  //# sourceMappingURL=msalClient.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"msalClient.js","sourceRoot":"","sources":["../../../../../../identity/src/msal/nodeFlows/msalClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AAIzC,OAAO,EAAoB,gBAAgB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACvF,OAAO,EAAuB,WAAW,EAAE,MAAM,e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oBAC1C,MAAM,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM;iBACxB,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC;KAAA;IAED,OAAO;QACL,gBAAgB;QAChB,sBAAsB;QACtB,yBAAyB;QACzB,2BAA2B;QAC3B,oBAAoB;QACpB,0BAA0B;QAC1B,2BAA2B;KAC5B,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msal from \"@azure/msal-node\";\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRecord, CertificateParts } from \"../types\";\nimport { CredentialLogger, credentialLogger, formatSuccess } from \"../../util/logging\";\nimport { PluginConfiguration, msalPlugins } from \"./msalPlugins\";\nimport {\n defaultLoggerCallback,\n ensureValidMsalToken,\n getAuthority,\n getKnownAuthorities,\n getMSALLogLevel,\n handleMsalError,\n msalToPublic,\n publicToMsal,\n} from \"../utils\";\n\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { BrokerOptions } from \"./brokerOptions\";\nimport { DeviceCodePromptCallback } from \"../../credentials/deviceCodeCredentialOptions\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\nimport { calculateRegionalAuthority } from \"../../regionalAuthority\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { resolveTenantId } from \"../../util/tenantIdUtils\";\n\n/**\n * The default logger used if no logger was passed in by the credential.\n */\nconst msalLogger = credentialLogger(\"MsalClient\");\n\nexport interface GetTokenWithSilentAuthOptions extends GetTokenOptions {\n /**\n * Disables automatic authentication. If set to true, the method will throw an error if the user needs to authenticate.\n *\n * @remarks\n *\n * This option will be set to `false` when the user calls `authenticate` directly on a credential that supports it.\n */\n disableAutomaticAuthentication?: boolean;\n}\n\n/**\n * Represents a client for interacting with the Microsoft Authentication Library (MSAL).\n */\nexport interface MsalClient {\n /**\n * Retrieves an access token by using a user's username and password.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param username - The username provided by the developer.\n * @param password - The user's password provided by the developer.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByUsernamePassword(\n scopes: string[],\n username: string,\n password: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by prompting the user to authenticate using a device code.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param userPromptCallback - The callback function that allows developers to customize the prompt message.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByDeviceCode(\n scopes: string[],\n userPromptCallback: DeviceCodePromptCallback,\n options?: GetTokenWithSilentAuthOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by using a client certificate.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param certificate - The client certificate used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientCertificate(\n scopes: string[],\n certificate: CertificateParts,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using a client assertion.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param clientAssertion - The client assertion used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientAssertion(\n scopes: string[],\n clientAssertion: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using a client secret.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param clientSecret - The client secret of the application. This is a credential that the application can use to authenticate itself.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientSecret(\n scopes: string[],\n clientSecret: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using an authorization code flow.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param authorizationCode - An authorization code that was received from following the\n authorization code flow. This authorization code must not\n have already been used to obtain an access token.\n * @param redirectUri - The redirect URI that was used to request the authorization code.\n Must be the same URI that is configured for the App Registration.\n * @param clientSecret - An optional client secret that was generated for the App Registration.\n * @param options - Additional options that may be provided to the method.\n */\n getTokenByAuthorizationCode(\n scopes: string[],\n redirectUri: string,\n authorizationCode: string,\n clientSecret?: string,\n options?: GetTokenWithSilentAuthOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves the last authenticated account. This method expects an authentication record to have been previously loaded.\n *\n * An authentication record could be loaded by calling the `getToken` method, or by providing an `authenticationRecord` when creating a credential.\n */\n getActiveAccount(): AuthenticationRecord | undefined;\n}\n\n/**\n * Represents the options for configuring the MsalClient.\n */\nexport interface MsalClientOptions {\n /**\n * Parameters that enable WAM broker authentication in the InteractiveBrowserCredential.\n */\n brokerOptions?: BrokerOptions;\n\n /**\n * Parameters that enable token cache persistence in the Identity credentials.\n */\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n\n /**\n * A custom authority host.\n */\n authorityHost?: IdentityClient[\"tokenCredentialOptions\"][\"authorityHost\"];\n\n /**\n * Allows users to configure settings for logging policy options, allow logging account information and personally identifiable information for customer support.\n */\n loggingOptions?: IdentityClient[\"tokenCredentialOptions\"][\"loggingOptions\"];\n\n /**\n * The token credential options for the MsalClient.\n */\n tokenCredentialOptions?: IdentityClient[\"tokenCredentialOptions\"];\n\n /**\n * Determines whether instance discovery is disabled.\n */\n disableInstanceDiscovery?: boolean;\n\n /**\n * The logger for the MsalClient.\n */\n logger?: CredentialLogger;\n\n /**\n * The authentication record for the MsalClient.\n */\n authenticationRecord?: AuthenticationRecord;\n}\n\n/**\n * Generates the configuration for MSAL (Microsoft Authentication Library).\n *\n * @param clientId - The client ID of the application.\n * @param tenantId - The tenant ID of the Azure Active Directory.\n * @param msalClientOptions - Optional. Additional options for creating the MSAL client.\n * @returns The MSAL configuration object.\n */\nexport function generateMsalConfiguration(\n clientId: string,\n tenantId: string,\n msalClientOptions: MsalClientOptions = {},\n): msal.Configuration {\n const resolvedTenant = resolveTenantId(\n msalClientOptions.logger ?? msalLogger,\n tenantId,\n clientId,\n );\n\n // TODO: move and reuse getIdentityClientAuthorityHost\n const authority = getAuthority(\n resolvedTenant,\n msalClientOptions.authorityHost ?? process.env.AZURE_AUTHORITY_HOST,\n );\n\n const httpClient = new IdentityClient({\n ...msalClientOptions.tokenCredentialOptions,\n authorityHost: authority,\n loggingOptions: msalClientOptions.loggingOptions,\n });\n\n const msalConfig: msal.Configuration = {\n auth: {\n clientId,\n authority,\n knownAuthorities: getKnownAuthorities(\n resolvedTenant,\n authority,\n msalClientOptions.disableInstanceDiscovery,\n ),\n },\n system: {\n networkClient: httpClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(msalClientOptions.logger ?? msalLogger),\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: msalClientOptions.loggingOptions?.enableUnsafeSupportLogging,\n },\n },\n };\n return msalConfig;\n}\n\n/**\n * Represents the state necessary for the MSAL (Microsoft Authentication Library) client to operate.\n * This includes the MSAL configuration, cached account information, Azure region, and a flag to disable automatic authentication.\n *\n * @internal\n */\ninterface MsalClientState {\n /** The configuration for the MSAL client. */\n msalConfig: msal.Configuration;\n\n /** The cached account information, or null if no account information is cached. */\n cachedAccount: msal.AccountInfo | null;\n\n /** Configured plugins */\n pluginConfiguration: PluginConfiguration;\n\n /** Claims received from challenges, cached for the next request */\n cachedClaims?: string;\n\n /** The logger instance */\n logger: CredentialLogger;\n}\n\n/**\n * Creates an instance of the MSAL (Microsoft Authentication Library) client.\n *\n * @param clientId - The client ID of the application.\n * @param tenantId - The tenant ID of the Azure Active Directory.\n * @param createMsalClientOptions - Optional. Additional options for creating the MSAL client.\n * @returns An instance of the MSAL client.\n *\n * @public\n */\nexport function createMsalClient(\n clientId: string,\n tenantId: string,\n createMsalClientOptions: MsalClientOptions = {},\n): MsalClient {\n const state: MsalClientState = {\n msalConfig: generateMsalConfiguration(clientId, tenantId, createMsalClientOptions),\n cachedAccount: createMsalClientOptions.authenticationRecord\n ? publicToMsal(createMsalClientOptions.authenticationRecord)\n : null,\n pluginConfiguration: msalPlugins.generatePluginConfiguration(createMsalClientOptions),\n logger: createMsalClientOptions.logger ?? msalLogger,\n };\n\n const publicApps: Map<string, msal.PublicClientApplication> = new Map();\n async function getPublicApp(\n options: GetTokenOptions = {},\n ): Promise<msal.PublicClientApplication> {\n const appKey = options.enableCae ? \"CAE\" : \"default\";\n\n let publicClientApp = publicApps.get(appKey);\n if (publicClientApp) {\n state.logger.getToken.info(\"Existing PublicClientApplication found in cache, returning it.\");\n return publicClientApp;\n }\n\n // Initialize a new app and cache it\n state.logger.getToken.info(\n `Creating new PublicClientApplication with CAE ${options.enableCae ? \"enabled\" : \"disabled\"}.`,\n );\n\n const cachePlugin = options.enableCae\n ? state.pluginConfiguration.cache.cachePluginCae\n : state.pluginConfiguration.cache.cachePlugin;\n\n state.msalConfig.auth.clientCapabilities = options.enableCae ? [\"cp1\"] : undefined;\n\n publicClientApp = new msal.PublicClientApplication({\n ...state.msalConfig,\n broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },\n cache: { cachePlugin: await cachePlugin },\n });\n\n publicApps.set(appKey, publicClientApp);\n\n return publicClientApp;\n }\n\n const confidentialApps: Map<string, msal.ConfidentialClientApplication> = new Map();\n async function getConfidentialApp(\n options: GetTokenOptions = {},\n ): Promise<msal.ConfidentialClientApplication> {\n const appKey = options.enableCae ? \"CAE\" : \"default\";\n\n let confidentialClientApp = confidentialApps.get(appKey);\n if (confidentialClientApp) {\n state.logger.getToken.info(\n \"Existing ConfidentialClientApplication found in cache, returning it.\",\n );\n return confidentialClientApp;\n }\n\n // Initialize a new app and cache it\n state.logger.getToken.info(\n `Creating new ConfidentialClientApplication with CAE ${options.enableCae ? \"enabled\" : \"disabled\"}.`,\n );\n\n const cachePlugin = options.enableCae\n ? state.pluginConfiguration.cache.cachePluginCae\n : state.pluginConfiguration.cache.cachePlugin;\n\n state.msalConfig.auth.clientCapabilities = options.enableCae ? [\"cp1\"] : undefined;\n\n confidentialClientApp = new msal.ConfidentialClientApplication({\n ...state.msalConfig,\n broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },\n cache: { cachePlugin: await cachePlugin },\n });\n\n confidentialApps.set(appKey, confidentialClientApp);\n\n return confidentialClientApp;\n }\n\n async function getTokenSilent(\n app: msal.ConfidentialClientApplication | msal.PublicClientApplication,\n scopes: string[],\n options: GetTokenOptions = {},\n ): Promise<msal.AuthenticationResult> {\n if (state.cachedAccount === null) {\n state.logger.getToken.info(\n \"No cached account found in local state, attempting to load it from MSAL cache.\",\n );\n const cache = app.getTokenCache();\n const accounts = await cache.getAllAccounts();\n\n if (accounts === undefined || accounts.length === 0) {\n throw new AuthenticationRequiredError({ scopes });\n }\n\n if (accounts.length > 1) {\n state.logger\n .info(`More than one account was found authenticated for this Client ID and Tenant ID.\nHowever, no \"authenticationRecord\" has been provided for this credential,\ntherefore we're unable to pick between these accounts.\nA new login attempt will be requested, to ensure the correct account is picked.\nTo work with multiple accounts for the same Client ID and Tenant ID, please provide an \"authenticationRecord\" when initializing a credential to prevent this from happening.`);\n throw new AuthenticationRequiredError({ scopes });\n }\n\n state.cachedAccount = accounts[0];\n }\n\n // Keep track and reuse the claims we received across challenges\n if (options.claims) {\n state.cachedClaims = options.claims;\n }\n\n const silentRequest: msal.SilentFlowRequest = {\n account: state.cachedAccount,\n scopes,\n claims: state.cachedClaims,\n };\n\n if (state.pluginConfiguration.broker.isEnabled) {\n silentRequest.tokenQueryParameters ||= {};\n if (state.pluginConfiguration.broker.enableMsaPassthrough) {\n silentRequest.tokenQueryParameters[\"msal_request_type\"] = \"consumer_passthrough\";\n }\n }\n\n state.logger.getToken.info(\"Attempting to acquire token silently\");\n return app.acquireTokenSilent(silentRequest);\n }\n\n /**\n * Performs silent authentication using MSAL to acquire an access token.\n * If silent authentication fails, falls back to interactive authentication.\n *\n * @param msalApp - The MSAL application instance.\n * @param scopes - The scopes for which to acquire the access token.\n * @param options - The options for acquiring the access token.\n * @param onAuthenticationRequired - A callback function to handle interactive authentication when silent authentication fails.\n * @returns A promise that resolves to an AccessToken object containing the access token and its expiration timestamp.\n */\n async function withSilentAuthentication(\n msalApp: msal.ConfidentialClientApplication | msal.PublicClientApplication,\n scopes: Array<string>,\n options: GetTokenWithSilentAuthOptions,\n onAuthenticationRequired: () => Promise<msal.AuthenticationResult | null>,\n ): Promise<AccessToken> {\n let response: msal.AuthenticationResult | null = null;\n try {\n response = await getTokenSilent(msalApp, scopes, options);\n } catch (e: any) {\n if (e.name !== \"AuthenticationRequiredError\") {\n throw e;\n }\n if (options.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n }\n\n // Silent authentication failed\n if (response === null) {\n try {\n response = await onAuthenticationRequired();\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n // At this point we should have a token, process it\n ensureValidMsalToken(scopes, response, options);\n state.cachedAccount = response?.account ?? null;\n\n state.logger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n }\n\n async function getTokenByClientSecret(\n scopes: string[],\n clientSecret: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client secret`);\n\n state.msalConfig.auth.clientSecret = clientSecret;\n\n const msalApp = await getConfidentialApp(options);\n\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: state.msalConfig.auth.authority,\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByClientAssertion(\n scopes: string[],\n clientAssertion: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client assertion`);\n\n state.msalConfig.auth.clientAssertion = clientAssertion;\n\n const msalApp = await getConfidentialApp(options);\n\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: state.msalConfig.auth.authority,\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n clientAssertion,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByClientCertificate(\n scopes: string[],\n certificate: CertificateParts,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client certificate`);\n\n state.msalConfig.auth.clientCertificate = certificate;\n\n const msalApp = await getConfidentialApp(options);\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: state.msalConfig.auth.authority,\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByDeviceCode(\n scopes: string[],\n deviceCodeCallback: DeviceCodePromptCallback,\n options: GetTokenWithSilentAuthOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using device code`);\n\n const msalApp = await getPublicApp(options);\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n const requestOptions: msal.DeviceCodeRequest = {\n scopes,\n cancel: options?.abortSignal?.aborted ?? false,\n deviceCodeCallback,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n };\n const deviceCodeRequest = msalApp.acquireTokenByDeviceCode(requestOptions);\n if (options.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n requestOptions.cancel = true;\n });\n }\n\n return deviceCodeRequest;\n });\n }\n\n async function getTokenByUsernamePassword(\n scopes: string[],\n username: string,\n password: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using username and password`);\n\n const msalApp = await getPublicApp(options);\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n const requestOptions: msal.UsernamePasswordRequest = {\n scopes,\n username,\n password,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n };\n\n return msalApp.acquireTokenByUsernamePassword(requestOptions);\n });\n }\n\n function getActiveAccount(): AuthenticationRecord | undefined {\n if (!state.cachedAccount) {\n return undefined;\n }\n return msalToPublic(clientId, state.cachedAccount);\n }\n\n async function getTokenByAuthorizationCode(\n scopes: string[],\n redirectUri: string,\n authorizationCode: string,\n clientSecret?: string,\n options: GetTokenWithSilentAuthOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using authorization code`);\n\n let msalApp: msal.ConfidentialClientApplication | msal.PublicClientApplication;\n if (clientSecret) {\n // If a client secret is provided, we need to use a confidential client application\n // See https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow#request-an-access-token-with-a-client_secret\n state.msalConfig.auth.clientSecret = clientSecret;\n msalApp = await getConfidentialApp(options);\n } else {\n msalApp = await getPublicApp(options);\n }\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n return msalApp.acquireTokenByCode({\n scopes,\n redirectUri,\n code: authorizationCode,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n });\n });\n }\n\n return {\n getActiveAccount,\n getTokenByClientSecret,\n getTokenByClientAssertion,\n getTokenByClientCertificate,\n getTokenByDeviceCode,\n getTokenByUsernamePassword,\n getTokenByAuthorizationCode,\n };\n}\n"]}
1
+ {"version":3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AP,OAAO,uBAAP,OAAO,CAAE,2BAA2B,0CAAE,cAAc;iBACtE,CAAC;YACJ,CAAC;YAED,OAAO,wBAAwB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,GAAS,EAAE;;gBAC/D,MAAM,kBAAkB,GAAG,4BAA4B,EAAE,CAAC;gBAE1D,IAAI,KAAK,CAAC,mBAAmB,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;oBAC/C,OAAO,gBAAgB,CAAC,MAAA,KAAK,CAAC,mBAAmB,CAAC,MAAM,CAAC,uBAAuB,mCAAI,KAAK,CAAC,CAAC;gBAC7F,CAAC;gBAED,OAAO,GAAG,CAAC,uBAAuB,CAAC,kBAAkB,CAAC,CAAC;YACzD,CAAC,CAAA,CAAC,CAAC;QACL,CAAC;KAAA;IAED,OAAO;QACL,gBAAgB;QAChB,sBAAsB;QACtB,yBAAyB;QACzB,2BAA2B;QAC3B,oBAAoB;QACpB,0BAA0B;QAC1B,2BAA2B;QAC3B,kBAAkB;QAClB,4BAA4B;KAC7B,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msal from \"@azure/msal-node\";\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRecord, CertificateParts } from \"../types\";\nimport { CredentialLogger, credentialLogger, formatSuccess } from \"../../util/logging\";\nimport { PluginConfiguration, msalPlugins } from \"./msalPlugins\";\nimport {\n defaultLoggerCallback,\n ensureValidMsalToken,\n getAuthority,\n getKnownAuthorities,\n getMSALLogLevel,\n handleMsalError,\n msalToPublic,\n publicToMsal,\n} from \"../utils\";\n\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { BrokerOptions } from \"./brokerOptions\";\nimport { DeviceCodePromptCallback } from \"../../credentials/deviceCodeCredentialOptions\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\nimport { calculateRegionalAuthority } from \"../../regionalAuthority\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { resolveTenantId } from \"../../util/tenantIdUtils\";\nimport { interactiveBrowserMockable } from \"./msalOpenBrowser\";\nimport { InteractiveBrowserCredentialNodeOptions } from \"../../credentials/interactiveBrowserCredentialOptions\";\n\n/**\n * The default logger used if no logger was passed in by the credential.\n */\nconst msalLogger = credentialLogger(\"MsalClient\");\n\n/**\n * Represents the options for acquiring a token using flows that support silent authentication.\n */\nexport interface GetTokenWithSilentAuthOptions extends GetTokenOptions {\n /**\n * Disables automatic authentication. If set to true, the method will throw an error if the user needs to authenticate.\n *\n * @remarks\n *\n * This option will be set to `false` when the user calls `authenticate` directly on a credential that supports it.\n */\n disableAutomaticAuthentication?: boolean;\n}\n\n/**\n * Represents the options for acquiring a token interactively.\n */\nexport interface GetTokenInteractiveOptions extends GetTokenWithSilentAuthOptions {\n /**\n * Window handle for parent window, required for WAM authentication.\n */\n parentWindowHandle?: Buffer;\n /**\n * Shared configuration options for browser customization\n */\n browserCustomizationOptions?: InteractiveBrowserCredentialNodeOptions[\"browserCustomizationOptions\"];\n /**\n * loginHint allows a user name to be pre-selected for interactive logins.\n * Setting this option skips the account selection prompt and immediately attempts to login with the specified account.\n */\n loginHint?: string;\n}\n\n/**\n * Represents a client for interacting with the Microsoft Authentication Library (MSAL).\n */\nexport interface MsalClient {\n /**\n * Retrieves an access token by using the on-behalf-of flow and a client certificate of the calling service.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param userAssertionToken - The access token that was sent to the middle-tier API. This token must have an audience of the app making this OBO request.\n * @param clientCertificate - The client certificate used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenOnBehalfOf(\n scopes: string[],\n userAssertionToken: string,\n clientCertificate: CertificateParts,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n /**\n *\n * Retrieves an access token by using the on-behalf-of flow and a client secret of the calling service.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param userAssertionToken - The access token that was sent to the middle-tier API. This token must have an audience of the app making this OBO request.\n * @param clientSecret - The client secret used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenOnBehalfOf(\n scopes: string[],\n userAssertionToken: string,\n clientSecret: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by using an interactive prompt (InteractiveBrowserCredential).\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByInteractiveRequest(\n scopes: string[],\n options: GetTokenInteractiveOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by using a user's username and password.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param username - The username provided by the developer.\n * @param password - The user's password provided by the developer.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByUsernamePassword(\n scopes: string[],\n username: string,\n password: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by prompting the user to authenticate using a device code.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param userPromptCallback - The callback function that allows developers to customize the prompt message.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByDeviceCode(\n scopes: string[],\n userPromptCallback: DeviceCodePromptCallback,\n options?: GetTokenWithSilentAuthOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by using a client certificate.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param certificate - The client certificate used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientCertificate(\n scopes: string[],\n certificate: CertificateParts,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using a client assertion.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param clientAssertion - The client assertion used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientAssertion(\n scopes: string[],\n clientAssertion: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using a client secret.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param clientSecret - The client secret of the application. This is a credential that the application can use to authenticate itself.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientSecret(\n scopes: string[],\n clientSecret: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using an authorization code flow.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param authorizationCode - An authorization code that was received from following the\n authorization code flow. This authorization code must not\n have already been used to obtain an access token.\n * @param redirectUri - The redirect URI that was used to request the authorization code.\n Must be the same URI that is configured for the App Registration.\n * @param clientSecret - An optional client secret that was generated for the App Registration.\n * @param options - Additional options that may be provided to the method.\n */\n getTokenByAuthorizationCode(\n scopes: string[],\n redirectUri: string,\n authorizationCode: string,\n clientSecret?: string,\n options?: GetTokenWithSilentAuthOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves the last authenticated account. This method expects an authentication record to have been previously loaded.\n *\n * An authentication record could be loaded by calling the `getToken` method, or by providing an `authenticationRecord` when creating a credential.\n */\n getActiveAccount(): AuthenticationRecord | undefined;\n}\n\n/**\n * Represents the options for configuring the MsalClient.\n */\nexport interface MsalClientOptions {\n /**\n * Parameters that enable WAM broker authentication in the InteractiveBrowserCredential.\n */\n brokerOptions?: BrokerOptions;\n\n /**\n * Parameters that enable token cache persistence in the Identity credentials.\n */\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n\n /**\n * A custom authority host.\n */\n authorityHost?: IdentityClient[\"tokenCredentialOptions\"][\"authorityHost\"];\n\n /**\n * Allows users to configure settings for logging policy options, allow logging account information and personally identifiable information for customer support.\n */\n loggingOptions?: IdentityClient[\"tokenCredentialOptions\"][\"loggingOptions\"];\n\n /**\n * The token credential options for the MsalClient.\n */\n tokenCredentialOptions?: IdentityClient[\"tokenCredentialOptions\"];\n\n /**\n * Determines whether instance discovery is disabled.\n */\n disableInstanceDiscovery?: boolean;\n\n /**\n * The logger for the MsalClient.\n */\n logger?: CredentialLogger;\n\n /**\n * The authentication record for the MsalClient.\n */\n authenticationRecord?: AuthenticationRecord;\n}\n\n/**\n * Generates the configuration for MSAL (Microsoft Authentication Library).\n *\n * @param clientId - The client ID of the application.\n * @param tenantId - The tenant ID of the Azure Active Directory.\n * @param msalClientOptions - Optional. Additional options for creating the MSAL client.\n * @returns The MSAL configuration object.\n */\nexport function generateMsalConfiguration(\n clientId: string,\n tenantId: string,\n msalClientOptions: MsalClientOptions = {},\n): msal.Configuration {\n const resolvedTenant = resolveTenantId(\n msalClientOptions.logger ?? msalLogger,\n tenantId,\n clientId,\n );\n\n // TODO: move and reuse getIdentityClientAuthorityHost\n const authority = getAuthority(\n resolvedTenant,\n msalClientOptions.authorityHost ?? process.env.AZURE_AUTHORITY_HOST,\n );\n\n const httpClient = new IdentityClient({\n ...msalClientOptions.tokenCredentialOptions,\n authorityHost: authority,\n loggingOptions: msalClientOptions.loggingOptions,\n });\n\n const msalConfig: msal.Configuration = {\n auth: {\n clientId,\n authority,\n knownAuthorities: getKnownAuthorities(\n resolvedTenant,\n authority,\n msalClientOptions.disableInstanceDiscovery,\n ),\n },\n system: {\n networkClient: httpClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(msalClientOptions.logger ?? msalLogger),\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: msalClientOptions.loggingOptions?.enableUnsafeSupportLogging,\n },\n },\n };\n return msalConfig;\n}\n\n/**\n * Represents the state necessary for the MSAL (Microsoft Authentication Library) client to operate.\n * This includes the MSAL configuration, cached account information, Azure region, and a flag to disable automatic authentication.\n *\n * @internal\n */\ninterface MsalClientState {\n /** The configuration for the MSAL client. */\n msalConfig: msal.Configuration;\n\n /** The cached account information, or null if no account information is cached. */\n cachedAccount: msal.AccountInfo | null;\n\n /** Configured plugins */\n pluginConfiguration: PluginConfiguration;\n\n /** Claims received from challenges, cached for the next request */\n cachedClaims?: string;\n\n /** The logger instance */\n logger: CredentialLogger;\n}\n\n/**\n * Creates an instance of the MSAL (Microsoft Authentication Library) client.\n *\n * @param clientId - The client ID of the application.\n * @param tenantId - The tenant ID of the Azure Active Directory.\n * @param createMsalClientOptions - Optional. Additional options for creating the MSAL client.\n * @returns An instance of the MSAL client.\n *\n * @public\n */\nexport function createMsalClient(\n clientId: string,\n tenantId: string,\n createMsalClientOptions: MsalClientOptions = {},\n): MsalClient {\n const state: MsalClientState = {\n msalConfig: generateMsalConfiguration(clientId, tenantId, createMsalClientOptions),\n cachedAccount: createMsalClientOptions.authenticationRecord\n ? publicToMsal(createMsalClientOptions.authenticationRecord)\n : null,\n pluginConfiguration: msalPlugins.generatePluginConfiguration(createMsalClientOptions),\n logger: createMsalClientOptions.logger ?? msalLogger,\n };\n\n const publicApps: Map<string, msal.PublicClientApplication> = new Map();\n async function getPublicApp(\n options: GetTokenOptions = {},\n ): Promise<msal.PublicClientApplication> {\n const appKey = options.enableCae ? \"CAE\" : \"default\";\n\n let publicClientApp = publicApps.get(appKey);\n if (publicClientApp) {\n state.logger.getToken.info(\"Existing PublicClientApplication found in cache, returning it.\");\n return publicClientApp;\n }\n\n // Initialize a new app and cache it\n state.logger.getToken.info(\n `Creating new PublicClientApplication with CAE ${options.enableCae ? \"enabled\" : \"disabled\"}.`,\n );\n\n const cachePlugin = options.enableCae\n ? state.pluginConfiguration.cache.cachePluginCae\n : state.pluginConfiguration.cache.cachePlugin;\n\n state.msalConfig.auth.clientCapabilities = options.enableCae ? [\"cp1\"] : undefined;\n\n publicClientApp = new msal.PublicClientApplication({\n ...state.msalConfig,\n broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },\n cache: { cachePlugin: await cachePlugin },\n });\n\n publicApps.set(appKey, publicClientApp);\n\n return publicClientApp;\n }\n\n const confidentialApps: Map<string, msal.ConfidentialClientApplication> = new Map();\n async function getConfidentialApp(\n options: GetTokenOptions = {},\n ): Promise<msal.ConfidentialClientApplication> {\n const appKey = options.enableCae ? \"CAE\" : \"default\";\n\n let confidentialClientApp = confidentialApps.get(appKey);\n if (confidentialClientApp) {\n state.logger.getToken.info(\n \"Existing ConfidentialClientApplication found in cache, returning it.\",\n );\n return confidentialClientApp;\n }\n\n // Initialize a new app and cache it\n state.logger.getToken.info(\n `Creating new ConfidentialClientApplication with CAE ${options.enableCae ? \"enabled\" : \"disabled\"}.`,\n );\n\n const cachePlugin = options.enableCae\n ? state.pluginConfiguration.cache.cachePluginCae\n : state.pluginConfiguration.cache.cachePlugin;\n\n state.msalConfig.auth.clientCapabilities = options.enableCae ? [\"cp1\"] : undefined;\n\n confidentialClientApp = new msal.ConfidentialClientApplication({\n ...state.msalConfig,\n broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },\n cache: { cachePlugin: await cachePlugin },\n });\n\n confidentialApps.set(appKey, confidentialClientApp);\n\n return confidentialClientApp;\n }\n\n async function getTokenSilent(\n app: msal.ConfidentialClientApplication | msal.PublicClientApplication,\n scopes: string[],\n options: GetTokenOptions = {},\n ): Promise<msal.AuthenticationResult> {\n if (state.cachedAccount === null) {\n state.logger.getToken.info(\n \"No cached account found in local state, attempting to load it from MSAL cache.\",\n );\n const cache = app.getTokenCache();\n const accounts = await cache.getAllAccounts();\n\n if (accounts === undefined || accounts.length === 0) {\n throw new AuthenticationRequiredError({ scopes });\n }\n\n if (accounts.length > 1) {\n state.logger\n .info(`More than one account was found authenticated for this Client ID and Tenant ID.\nHowever, no \"authenticationRecord\" has been provided for this credential,\ntherefore we're unable to pick between these accounts.\nA new login attempt will be requested, to ensure the correct account is picked.\nTo work with multiple accounts for the same Client ID and Tenant ID, please provide an \"authenticationRecord\" when initializing a credential to prevent this from happening.`);\n throw new AuthenticationRequiredError({ scopes });\n }\n\n state.cachedAccount = accounts[0];\n }\n\n // Keep track and reuse the claims we received across challenges\n if (options.claims) {\n state.cachedClaims = options.claims;\n }\n\n const silentRequest: msal.SilentFlowRequest = {\n account: state.cachedAccount,\n scopes,\n claims: state.cachedClaims,\n };\n\n if (state.pluginConfiguration.broker.isEnabled) {\n silentRequest.tokenQueryParameters ||= {};\n if (state.pluginConfiguration.broker.enableMsaPassthrough) {\n silentRequest.tokenQueryParameters[\"msal_request_type\"] = \"consumer_passthrough\";\n }\n }\n\n state.logger.getToken.info(\"Attempting to acquire token silently\");\n return app.acquireTokenSilent(silentRequest);\n }\n\n /**\n * Performs silent authentication using MSAL to acquire an access token.\n * If silent authentication fails, falls back to interactive authentication.\n *\n * @param msalApp - The MSAL application instance.\n * @param scopes - The scopes for which to acquire the access token.\n * @param options - The options for acquiring the access token.\n * @param onAuthenticationRequired - A callback function to handle interactive authentication when silent authentication fails.\n * @returns A promise that resolves to an AccessToken object containing the access token and its expiration timestamp.\n */\n async function withSilentAuthentication(\n msalApp: msal.ConfidentialClientApplication | msal.PublicClientApplication,\n scopes: Array<string>,\n options: GetTokenWithSilentAuthOptions,\n onAuthenticationRequired: () => Promise<msal.AuthenticationResult | null>,\n ): Promise<AccessToken> {\n let response: msal.AuthenticationResult | null = null;\n try {\n response = await getTokenSilent(msalApp, scopes, options);\n } catch (e: any) {\n if (e.name !== \"AuthenticationRequiredError\") {\n throw e;\n }\n if (options.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n }\n\n // Silent authentication failed\n if (response === null) {\n try {\n response = await onAuthenticationRequired();\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n // At this point we should have a token, process it\n ensureValidMsalToken(scopes, response, options);\n state.cachedAccount = response?.account ?? null;\n\n state.logger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n }\n\n async function getTokenByClientSecret(\n scopes: string[],\n clientSecret: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client secret`);\n\n state.msalConfig.auth.clientSecret = clientSecret;\n\n const msalApp = await getConfidentialApp(options);\n\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: state.msalConfig.auth.authority,\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByClientAssertion(\n scopes: string[],\n clientAssertion: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client assertion`);\n\n state.msalConfig.auth.clientAssertion = clientAssertion;\n\n const msalApp = await getConfidentialApp(options);\n\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: state.msalConfig.auth.authority,\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n clientAssertion,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByClientCertificate(\n scopes: string[],\n certificate: CertificateParts,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client certificate`);\n\n state.msalConfig.auth.clientCertificate = certificate;\n\n const msalApp = await getConfidentialApp(options);\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: state.msalConfig.auth.authority,\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByDeviceCode(\n scopes: string[],\n deviceCodeCallback: DeviceCodePromptCallback,\n options: GetTokenWithSilentAuthOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using device code`);\n\n const msalApp = await getPublicApp(options);\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n const requestOptions: msal.DeviceCodeRequest = {\n scopes,\n cancel: options?.abortSignal?.aborted ?? false,\n deviceCodeCallback,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n };\n const deviceCodeRequest = msalApp.acquireTokenByDeviceCode(requestOptions);\n if (options.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n requestOptions.cancel = true;\n });\n }\n\n return deviceCodeRequest;\n });\n }\n\n async function getTokenByUsernamePassword(\n scopes: string[],\n username: string,\n password: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using username and password`);\n\n const msalApp = await getPublicApp(options);\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n const requestOptions: msal.UsernamePasswordRequest = {\n scopes,\n username,\n password,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n };\n\n return msalApp.acquireTokenByUsernamePassword(requestOptions);\n });\n }\n\n function getActiveAccount(): AuthenticationRecord | undefined {\n if (!state.cachedAccount) {\n return undefined;\n }\n return msalToPublic(clientId, state.cachedAccount);\n }\n\n async function getTokenByAuthorizationCode(\n scopes: string[],\n redirectUri: string,\n authorizationCode: string,\n clientSecret?: string,\n options: GetTokenWithSilentAuthOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using authorization code`);\n\n let msalApp: msal.ConfidentialClientApplication | msal.PublicClientApplication;\n if (clientSecret) {\n // If a client secret is provided, we need to use a confidential client application\n // See https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow#request-an-access-token-with-a-client_secret\n state.msalConfig.auth.clientSecret = clientSecret;\n msalApp = await getConfidentialApp(options);\n } else {\n msalApp = await getPublicApp(options);\n }\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n return msalApp.acquireTokenByCode({\n scopes,\n redirectUri,\n code: authorizationCode,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n });\n });\n }\n\n function getTokenOnBehalfOf(\n scopes: string[],\n userAssertionToken: string,\n clientSecret: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n function getTokenOnBehalfOf(\n scopes: string[],\n userAssertionToken: string,\n clientCertificate: CertificateParts,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n async function getTokenOnBehalfOf(\n scopes: string[],\n userAssertionToken: string,\n clientSecretOrCertificate: string | CertificateParts,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(`Attempting to acquire token on behalf of another user`);\n\n if (typeof clientSecretOrCertificate === \"string\") {\n // Client secret\n msalLogger.getToken.info(`Using client secret for on behalf of flow`);\n state.msalConfig.auth.clientSecret = clientSecretOrCertificate;\n } else {\n // Client certificate\n msalLogger.getToken.info(`Using client certificate for on behalf of flow`);\n state.msalConfig.auth.clientCertificate = clientSecretOrCertificate;\n }\n\n const msalApp = await getConfidentialApp(options);\n try {\n const response = await msalApp.acquireTokenOnBehalfOf({\n scopes,\n authority: state.msalConfig.auth.authority,\n claims: options.claims,\n oboAssertion: userAssertionToken,\n });\n ensureValidMsalToken(scopes, response, options);\n\n msalLogger.getToken.info(formatSuccess(scopes));\n\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n };\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByInteractiveRequest(\n scopes: string[],\n options: GetTokenInteractiveOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(`Attempting to acquire token interactively`);\n\n const app = await getPublicApp(options);\n\n /**\n * A helper function that supports brokered authentication through the MSAL's public application.\n *\n * When options.useDefaultBrokerAccount is true, the method will attempt to authenticate using the default broker account.\n * If the default broker account is not available, the method will fall back to interactive authentication.\n */\n async function getBrokeredToken(\n useDefaultBrokerAccount: boolean,\n ): Promise<msal.AuthenticationResult> {\n msalLogger.verbose(\"Authentication will resume through the broker\");\n const interactiveRequest = createBaseInteractiveRequest();\n if (state.pluginConfiguration.broker.parentWindowHandle) {\n interactiveRequest.windowHandle = Buffer.from(\n state.pluginConfiguration.broker.parentWindowHandle,\n );\n } else {\n // this is a bug, as the pluginConfiguration handler should validate this case.\n msalLogger.warning(\n \"Parent window handle is not specified for the broker. This may cause unexpected behavior. Please provide the parentWindowHandle.\",\n );\n }\n\n if (state.pluginConfiguration.broker.enableMsaPassthrough) {\n (interactiveRequest.tokenQueryParameters ??= {})[\"msal_request_type\"] =\n \"consumer_passthrough\";\n }\n if (useDefaultBrokerAccount) {\n interactiveRequest.prompt = \"none\";\n msalLogger.verbose(\"Attempting broker authentication using the default broker account\");\n } else {\n msalLogger.verbose(\"Attempting broker authentication without the default broker account\");\n }\n\n try {\n return await app.acquireTokenInteractive(interactiveRequest);\n } catch (e: any) {\n msalLogger.verbose(`Failed to authenticate through the broker: ${e.message}`);\n // If we tried to use the default broker account and failed, fall back to interactive authentication\n if (useDefaultBrokerAccount) {\n return getBrokeredToken(/* useDefaultBrokerAccount: */ false);\n } else {\n throw e;\n }\n }\n }\n\n function createBaseInteractiveRequest(): msal.InteractiveRequest {\n return {\n openBrowser: async (url) => {\n await interactiveBrowserMockable.open(url, { wait: true, newInstance: true });\n },\n scopes,\n authority: state.msalConfig.auth.authority,\n claims: options?.claims,\n loginHint: options?.loginHint,\n errorTemplate: options?.browserCustomizationOptions?.errorMessage,\n successTemplate: options?.browserCustomizationOptions?.successMessage,\n };\n }\n\n return withSilentAuthentication(app, scopes, options, async () => {\n const interactiveRequest = createBaseInteractiveRequest();\n\n if (state.pluginConfiguration.broker.isEnabled) {\n return getBrokeredToken(state.pluginConfiguration.broker.useDefaultBrokerAccount ?? false);\n }\n\n return app.acquireTokenInteractive(interactiveRequest);\n });\n }\n\n return {\n getActiveAccount,\n getTokenByClientSecret,\n getTokenByClientAssertion,\n getTokenByClientCertificate,\n getTokenByDeviceCode,\n getTokenByUsernamePassword,\n getTokenByAuthorizationCode,\n getTokenOnBehalfOf,\n getTokenByInteractiveRequest,\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"msalPlugins.js","sourceRoot":"","sources":["../../../../../../identity/src/msal/nodeFlows/msalPlugins.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAgDnG;;;GAGG;AACH,MAAM,CAAC,IAAI,mBAAmB,GAEd,SAAS,CAAC;AAE1B;;;GAGG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACtC,cAAc,CAAC,cAA8D;QAC3E,mBAAmB,GAAG,cAAc,CAAC;IACvC,CAAC;CACF,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,IAAI,gBAAgB,GAIX,SAAS,CAAC;AAE1B,MAAM,UAAU,eAAe;IAC7B,OAAO,gBAAgB,KAAK,SAAS,CAAC;AACxC,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,+BAA+B,GAA8B;IACxE,eAAe,CAAC,MAAM;QACpB,gBAAgB,GAAG;YACjB,MAAM;SACP,CAAC;IACJ,CAAC;CACF,CAAC;AAEF;;;;;;;GAOG;AACH,SAAS,2BAA2B,CAAC,OAA0B;;IAC7D,MAAM,MAAM,GAAwB;QAClC,KAAK,EAAE,EAAE;QACT,MAAM,EAAE;YACN,SAAS,EAAE,MAAA,MAAA,OAAO,CAAC,aAAa,0CAAE,OAAO,mCAAI,KAAK;YAClD,oBAAoB,EAAE,MAAA,MA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oft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\n\nimport { CACHE_CAE_SUFFIX, CACHE_NON_CAE_SUFFIX, DEFAULT_TOKEN_CACHE_NAME } from \"../../constants\";\n\nimport { MsalClientOptions } from \"./msalClient\";\nimport { NativeBrokerPluginControl } from \"../../plugins/provider\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\n\n/**\n * Configuration for the plugins used by the MSAL node client.\n */\nexport interface PluginConfiguration {\n /**\n * Configuration for the cache plugin.\n */\n cache: {\n /**\n * The non-CAE cache plugin handler.\n */\n cachePlugin?: Promise<msalNode.ICachePlugin>;\n /**\n * The CAE cache plugin handler - persisted to a different file.\n */\n cachePluginCae?: Promise<msalNode.ICachePlugin>;\n };\n /**\n * Configuration for the broker plugin.\n */\n broker: {\n /**\n * True if the broker plugin is enabled and available. False otherwise.\n *\n * It is a bug if this is true and the broker plugin is not available.\n */\n isEnabled: boolean;\n /**\n * If true, MSA account will be passed through, required for WAM authentication.\n */\n enableMsaPassthrough: boolean;\n /**\n * The parent window handle for the broker.\n */\n parentWindowHandle?: Uint8Array;\n /**\n * The native broker plugin handler.\n */\n nativeBrokerPlugin?: msalNode.INativeBrokerPlugin;\n };\n}\n\n/**\n * The current persistence provider, undefined by default.\n * @internal\n */\nexport let persistenceProvider:\n | ((options?: TokenCachePersistenceOptions) => Promise<msalNode.ICachePlugin>)\n | undefined = undefined;\n\n/**\n * An object that allows setting the persistence provider.\n * @internal\n */\nexport const msalNodeFlowCacheControl = {\n setPersistence(pluginProvider: Exclude<typeof persistenceProvider, undefined>): void {\n persistenceProvider = pluginProvider;\n },\n};\n\n/**\n * The current native broker provider, undefined by default.\n * @internal\n */\nexport let nativeBrokerInfo:\n | {\n broker: msalNode.INativeBrokerPlugin;\n }\n | undefined = undefined;\n\nexport function hasNativeBroker(): boolean {\n return nativeBrokerInfo !== undefined;\n}\n\n/**\n * An object that allows setting the native broker provider.\n * @internal\n */\nexport const msalNodeFlowNativeBrokerControl: NativeBrokerPluginControl = {\n setNativeBroker(broker): void {\n nativeBrokerInfo = {\n broker,\n };\n },\n};\n\n/**\n * Configures plugins, validating that required plugins are available and enabled.\n *\n * Does not create the plugins themselves, but rather returns the configuration that will be used to create them.\n *\n * @param options - options for creating the MSAL client\n * @returns plugin configuration\n */\nfunction generatePluginConfiguration(options: MsalClientOptions): PluginConfiguration {\n const config: PluginConfiguration = {\n cache: {},\n broker: {\n isEnabled: options.brokerOptions?.enabled ?? false,\n enableMsaPassthrough: options.brokerOptions?.legacyEnableMsaPassthrough ?? false,\n parentWindowHandle: options.brokerOptions?.parentWindowHandle,\n },\n };\n\n if (options.tokenCachePersistenceOptions?.enabled) {\n if (persistenceProvider === undefined) {\n throw new Error(\n [\n \"Persistent token caching was requested, but no persistence provider was configured.\",\n \"You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.\",\n ].join(\" \"),\n );\n }\n\n const cacheBaseName = options.tokenCachePersistenceOptions.name || DEFAULT_TOKEN_CACHE_NAME;\n config.cache.cachePlugin = persistenceProvider({\n name: `${cacheBaseName}.${CACHE_NON_CAE_SUFFIX}`,\n ...options.tokenCachePersistenceOptions,\n });\n config.cache.cachePluginCae = persistenceProvider({\n name: `${cacheBaseName}.${CACHE_CAE_SUFFIX}`,\n ...options.tokenCachePersistenceOptions,\n });\n }\n\n if (options.brokerOptions?.enabled) {\n if (nativeBrokerInfo === undefined) {\n throw new Error(\n [\n \"Broker for WAM was requested to be enabled, but no native broker was configured.\",\n \"You must install the identity-broker plugin package (`npm install --save @azure/identity-broker`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(createNativeBrokerPlugin())` before using `enableBroker`.\",\n ].join(\" \"),\n );\n }\n config.broker.nativeBrokerPlugin = nativeBrokerInfo!.broker;\n }\n\n return config;\n}\n\n/**\n * Wraps generatePluginConfiguration as a writeable property for test stubbing purposes.\n */\nexport const msalPlugins = {\n generatePluginConfiguration,\n};\n"]}
1
+ {"version":3,"file":"msalPlugins.js","sourceRoot":"","sources":["../../../../../../identity/src/msal/nodeFlows/msalPlugins.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAoDnG;;;GAGG;AACH,MAAM,CAAC,IAAI,mBAAmB,GAEd,SAAS,CAAC;AAE1B;;;GAGG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACtC,cAAc,CAAC,cAA8D;QAC3E,mBAAmB,GAAG,cAAc,CAAC;IACvC,CAAC;CACF,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,IAAI,gBAAgB,GAIX,SAAS,CAAC;AAE1B,MAAM,UAAU,eAAe;IAC7B,OAAO,gBAAgB,KAAK,SAAS,CAAC;AACxC,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,+BAA+B,GAA8B;IACxE,eAAe,CAAC,MAAM;QACpB,gBAAgB,GAAG;YACjB,MAAM;SACP,CAAC;IACJ,CAAC;CACF,CAAC;AAEF;;;;;;;GAOG;AACH,SAAS,2BAA2B,CAAC,OAA0B;;IAC7D,MAAM,MAAM,GAAwB;QAClC,KAAK,EAAE,EAAE;QACT,MAAM,EAAE;YACN,SAAS,EAAE,MAAA,MAAA,OAAO,CAAC,aAAa,0CAAE,OAAO,mCAAI,KAAK;YAClD,oBAAoB,EAAE,MAAA,MAAA,OAAO,CAAC,aAAa,0CAAE,0BAA0B,mCAAI,KAAK;YAChF,kBAAkB,EAAE,MAAA,OAAO,CAAC,aAAa,0CAAE,kBAAkB;SAC9D;KACF,CAAC;IAEF,IAAI,MAAA,OAAO,CAAC,4BAA4B,0CAAE,OAAO,EAAE,CAAC;QAClD,IAAI,mBAAmB,KAAK,SAAS,EAAE,CAAC;YACtC,MAAM,IAAI,KAAK,CACb;gBACE,qFAAqF;gBACrF,yHAAyH;gBACzH,mFAAmF;gBACnF,0FAA0F;aAC3F,CAAC,IAAI,CAAC,GAAG,CAAC,CACZ,CAAC;QACJ,CAAC;QAED,MAAM,aAAa,GAAG,OAAO,CAAC,4BAA4B,CAAC,IAAI,IAAI,wBAAwB,CAAC;QAC5F,MAAM,CAAC,KAAK,CAAC,WAAW,GAAG,mBAAmB,iBAC5C,IAAI,EAAE,GAAG,aAAa,IAAI,oBAAoB,EAAE,IAC7C,OAAO,CAAC,4BAA4B,EACvC,CAAC;QACH,MAAM,CAAC,KAAK,CAAC,cAAc,GAAG,mBAAmB,iBAC/C,IAAI,EAAE,GAAG,aAAa,IAAI,gBAAgB,EAAE,IACzC,OAAO,CAAC,4BAA4B,EACvC,CAAC;IACL,CAAC;IAED,IAAI,MAAA,OAAO,CAAC,aAAa,0CAAE,OAAO,EAAE,CAAC;QACnC,IAAI,gBAAgB,KAAK,SAAS,EAAE,CAAC;YACnC,MAAM,IAAI,KAAK,CACb;gBACE,kFAAkF;gBAClF,mGAAmG;gBACnG,mFAAmF;gBACnF,8EAA8E;aAC/E,CAAC,IAAI,CAAC,GAAG,CAAC,CACZ,CAAC;QACJ,CAAC;QACD,MAAM,CAAC,MAAM,CAAC,kBAAkB,GAAG,gBAAiB,CAAC,MAAM,CAAC;IAC9D,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,2BAA2B;CAC5B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\n\nimport { CACHE_CAE_SUFFIX, CACHE_NON_CAE_SUFFIX, DEFAULT_TOKEN_CACHE_NAME } from \"../../constants\";\n\nimport { MsalClientOptions } from \"./msalClient\";\nimport { NativeBrokerPluginControl } from \"../../plugins/provider\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\n\n/**\n * Configuration for the plugins used by the MSAL node client.\n */\nexport interface PluginConfiguration {\n /**\n * Configuration for the cache plugin.\n */\n cache: {\n /**\n * The non-CAE cache plugin handler.\n */\n cachePlugin?: Promise<msalNode.ICachePlugin>;\n /**\n * The CAE cache plugin handler - persisted to a different file.\n */\n cachePluginCae?: Promise<msalNode.ICachePlugin>;\n };\n /**\n * Configuration for the broker plugin.\n */\n broker: {\n /**\n * True if the broker plugin is enabled and available. False otherwise.\n *\n * It is a bug if this is true and the broker plugin is not available.\n */\n isEnabled: boolean;\n /**\n * If true, MSA account will be passed through, required for WAM authentication.\n */\n enableMsaPassthrough: boolean;\n /**\n * The parent window handle for the broker.\n */\n parentWindowHandle?: Uint8Array;\n /**\n * The native broker plugin handler.\n */\n nativeBrokerPlugin?: msalNode.INativeBrokerPlugin;\n /**\n * If set to true, the credential will attempt to use the default broker account for authentication before falling back to interactive authentication. Default is set to false.\n */\n useDefaultBrokerAccount?: boolean;\n };\n}\n\n/**\n * The current persistence provider, undefined by default.\n * @internal\n */\nexport let persistenceProvider:\n | ((options?: TokenCachePersistenceOptions) => Promise<msalNode.ICachePlugin>)\n | undefined = undefined;\n\n/**\n * An object that allows setting the persistence provider.\n * @internal\n */\nexport const msalNodeFlowCacheControl = {\n setPersistence(pluginProvider: Exclude<typeof persistenceProvider, undefined>): void {\n persistenceProvider = pluginProvider;\n },\n};\n\n/**\n * The current native broker provider, undefined by default.\n * @internal\n */\nexport let nativeBrokerInfo:\n | {\n broker: msalNode.INativeBrokerPlugin;\n }\n | undefined = undefined;\n\nexport function hasNativeBroker(): boolean {\n return nativeBrokerInfo !== undefined;\n}\n\n/**\n * An object that allows setting the native broker provider.\n * @internal\n */\nexport const msalNodeFlowNativeBrokerControl: NativeBrokerPluginControl = {\n setNativeBroker(broker): void {\n nativeBrokerInfo = {\n broker,\n };\n },\n};\n\n/**\n * Configures plugins, validating that required plugins are available and enabled.\n *\n * Does not create the plugins themselves, but rather returns the configuration that will be used to create them.\n *\n * @param options - options for creating the MSAL client\n * @returns plugin configuration\n */\nfunction generatePluginConfiguration(options: MsalClientOptions): PluginConfiguration {\n const config: PluginConfiguration = {\n cache: {},\n broker: {\n isEnabled: options.brokerOptions?.enabled ?? false,\n enableMsaPassthrough: options.brokerOptions?.legacyEnableMsaPassthrough ?? false,\n parentWindowHandle: options.brokerOptions?.parentWindowHandle,\n },\n };\n\n if (options.tokenCachePersistenceOptions?.enabled) {\n if (persistenceProvider === undefined) {\n throw new Error(\n [\n \"Persistent token caching was requested, but no persistence provider was configured.\",\n \"You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.\",\n ].join(\" \"),\n );\n }\n\n const cacheBaseName = options.tokenCachePersistenceOptions.name || DEFAULT_TOKEN_CACHE_NAME;\n config.cache.cachePlugin = persistenceProvider({\n name: `${cacheBaseName}.${CACHE_NON_CAE_SUFFIX}`,\n ...options.tokenCachePersistenceOptions,\n });\n config.cache.cachePluginCae = persistenceProvider({\n name: `${cacheBaseName}.${CACHE_CAE_SUFFIX}`,\n ...options.tokenCachePersistenceOptions,\n });\n }\n\n if (options.brokerOptions?.enabled) {\n if (nativeBrokerInfo === undefined) {\n throw new Error(\n [\n \"Broker for WAM was requested to be enabled, but no native broker was configured.\",\n \"You must install the identity-broker plugin package (`npm install --save @azure/identity-broker`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(createNativeBrokerPlugin())` before using `enableBroker`.\",\n ].join(\" \"),\n );\n }\n config.broker.nativeBrokerPlugin = nativeBrokerInfo!.broker;\n }\n\n return config;\n}\n\n/**\n * Wraps generatePluginConfiguration as a writeable property for test stubbing purposes.\n */\nexport const msalPlugins = {\n generatePluginConfiguration,\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@azure/identity-cache-persistence",
3
- "version": "1.1.2-alpha.20240618.4",
3
+ "version": "1.1.2-alpha.20240620.2",
4
4
  "sdk-type": "client",
5
5
  "description": "A secure, persistent token cache for Azure Identity credentials that uses the OS secret-management API",
6
6
  "main": "dist/index.js",
@@ -1,122 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
3
- import { __awaiter } from "tslib";
4
- import { MsalNode } from "./msalNodeCommon";
5
- import { createHash, createPrivateKey } from "crypto";
6
- import { formatError } from "../../util/logging";
7
- import { handleMsalError } from "../utils";
8
- import { promisify } from "util";
9
- import { readFile } from "fs";
10
- const readFileAsync = promisify(readFile);
11
- /**
12
- * Tries to asynchronously load a certificate from the given path.
13
- *
14
- * @param configuration - Either the PEM value or the path to the certificate.
15
- * @param sendCertificateChain - Option to include x5c header for SubjectName and Issuer name authorization.
16
- * @returns - The certificate parts, or `undefined` if the certificate could not be loaded.
17
- * @internal
18
- */
19
- export function parseCertificate(configuration, sendCertificateChain) {
20
- return __awaiter(this, void 0, void 0, function* () {
21
- const certificateParts = {};
22
- const certificate = configuration
23
- .certificate;
24
- const certificatePath = configuration
25
- .certificatePath;
26
- certificateParts.certificateContents =
27
- certificate || (yield readFileAsync(certificatePath, "utf8"));
28
- if (sendCertificateChain) {
29
- certificateParts.x5c = certificateParts.certificateContents;
30
- }
31
- const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/g;
32
- const publicKeys = [];
33
- // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c
34
- let match;
35
- do {
36
- match = certificatePattern.exec(certificateParts.certificateContents);
37
- if (match) {
38
- publicKeys.push(match[3]);
39
- }
40
- } while (match);
41
- if (publicKeys.length === 0) {
42
- throw new Error("The file at the specified path does not contain a PEM-encoded certificate.");
43
- }
44
- certificateParts.thumbprint = createHash("sha1")
45
- .update(Buffer.from(publicKeys[0], "base64"))
46
- .digest("hex")
47
- .toUpperCase();
48
- return certificateParts;
49
- });
50
- }
51
- /**
52
- * MSAL client certificate client. Calls to MSAL's confidential application's `acquireTokenByClientCredential` during `doGetToken`.
53
- * @internal
54
- */
55
- export class MsalClientCertificate extends MsalNode {
56
- constructor(options) {
57
- super(options);
58
- this.requiresConfidential = true;
59
- this.configuration = options.configuration;
60
- this.sendCertificateChain = options.sendCertificateChain;
61
- }
62
- // Changing the MSAL configuration asynchronously
63
- init(options) {
64
- const _super = Object.create(null, {
65
- init: { get: () => super.init }
66
- });
67
- return __awaiter(this, void 0, void 0, function* () {
68
- try {
69
- const parts = yield parseCertificate(this.configuration, this.sendCertificateChain);
70
- let privateKey;
71
- if (this.configuration.certificatePassword !== undefined) {
72
- const privateKeyObject = createPrivateKey({
73
- key: parts.certificateContents,
74
- passphrase: this.configuration.certificatePassword,
75
- format: "pem",
76
- });
77
- privateKey = privateKeyObject
78
- .export({
79
- format: "pem",
80
- type: "pkcs8",
81
- })
82
- .toString();
83
- }
84
- else {
85
- privateKey = parts.certificateContents;
86
- }
87
- this.msalConfig.auth.clientCertificate = {
88
- thumbprint: parts.thumbprint,
89
- privateKey: privateKey,
90
- x5c: parts.x5c,
91
- };
92
- }
93
- catch (error) {
94
- this.logger.info(formatError("", error));
95
- throw error;
96
- }
97
- return _super.init.call(this, options);
98
- });
99
- }
100
- doGetToken(scopes_1) {
101
- return __awaiter(this, arguments, void 0, function* (scopes, options = {}) {
102
- try {
103
- const clientCredReq = {
104
- scopes,
105
- correlationId: options.correlationId,
106
- azureRegion: this.azureRegion,
107
- authority: options.authority,
108
- claims: options.claims,
109
- };
110
- const result = yield this.getApp("confidential", options.enableCae).acquireTokenByClientCredential(clientCredReq);
111
- // Even though we're providing the same default in memory persistence cache that we use for DeviceCodeCredential,
112
- // The Client Credential flow does not return the account information from the authentication service,
113
- // so each time getToken gets called, we will have to acquire a new token through the service.
114
- return this.handleResult(scopes, result || undefined);
115
- }
116
- catch (err) {
117
- throw handleMsalError(scopes, err, options);
118
- }
119
- });
120
- }
121
- }
122
- //# sourceMappingURL=msalClientCertificate.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"msalClientCertificate.js","sourceRoot":"","sources":["../../../../../../identity/src/msal/nodeFlows/msalClientCertificate.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAOlC,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAKtD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAE9B,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;AAqC1C;;;;;;;GAOG;AACH,MAAM,UAAgB,gBAAgB,CACpC,aAA0D,EAC1D,oBAA8B;;QAE9B,MAAM,gBAAgB,GAA8B,EAAE,CAAC;QAEvD,MAAM,WAAW,GAAwB,aAAiD;aACvF,WAAW,CAAC;QACf,MAAM,eAAe,GAAwB,aAAqD;aAC/F,eAAe,CAAC;QACnB,gBAAgB,CAAC,mBAAmB;YAClC,WAAW,IAAI,CAAC,MAAM,aAAa,CAAC,eAAgB,EAAE,MAAM,CAAC,CAAC,CAAC;QACjE,IAAI,oBAAoB,EAAE,CAAC;YACzB,gBAAgB,CAAC,GAAG,GAAG,gBAAgB,CAAC,mBAAmB,CAAC;QAC9D,CAAC;QAED,MAAM,kBAAkB,GACtB,+FAA+F,CAAC;QAClG,MAAM,UAAU,GAAa,EAAE,CAAC;QAEhC,qHAAqH;QACrH,IAAI,KAAK,CAAC;QACV,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D,CAAC;YAAC,OAAO,GAAQ,EAAE,CAAC;gBAClB,MAAM,eAAe,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;YAC9C,CAAC;QACH,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n ClientCertificateCredentialPEMConfiguration,\n ClientCertificatePEMCertificate,\n ClientCertificatePEMCertificatePath,\n} from \"../../credentials/clientCertificateCredential\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { createHash, createPrivateKey } from \"crypto\";\n\nimport { AccessToken } from \"@azure/core-auth\";\nimport { ClientCredentialRequest } from \"@azure/msal-node\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { formatError } from \"../../util/logging\";\nimport { handleMsalError } from \"../utils\";\nimport { promisify } from \"util\";\nimport { readFile } from \"fs\";\n\nconst readFileAsync = promisify(readFile);\n\n/**\n * Options that can be passed to configure MSAL to handle client certificates.\n * @internal\n */\nexport interface MsalClientCertificateOptions extends MsalNodeOptions {\n /**\n * Location of the PEM certificate.\n */\n configuration: ClientCertificateCredentialPEMConfiguration;\n /**\n * Option to include x5c header for SubjectName and Issuer name authorization.\n * Set this option to send base64 encoded public certificate in the client assertion header as an x5c claim\n */\n sendCertificateChain?: boolean;\n}\n\n/**\n * Parts of a certificate, as understood by MSAL.\n * @internal\n */\ninterface CertificateParts {\n /**\n * Hex encoded X.509 SHA-1 thumbprint of the certificate\n */\n thumbprint: string;\n /**\n * The PEM encoded private key (string should contain -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY-----\n */\n certificateContents: string;\n /**\n * x5c header.\n */\n x5c: string;\n}\n\n/**\n * Tries to asynchronously load a certificate from the given path.\n *\n * @param configuration - Either the PEM value or the path to the certificate.\n * @param sendCertificateChain - Option to include x5c header for SubjectName and Issuer name authorization.\n * @returns - The certificate parts, or `undefined` if the certificate could not be loaded.\n * @internal\n */\nexport async function parseCertificate(\n configuration: ClientCertificateCredentialPEMConfiguration,\n sendCertificateChain?: boolean,\n): Promise<CertificateParts> {\n const certificateParts: Partial<CertificateParts> = {};\n\n const certificate: string | undefined = (configuration as ClientCertificatePEMCertificate)\n .certificate;\n const certificatePath: string | undefined = (configuration as ClientCertificatePEMCertificatePath)\n .certificatePath;\n certificateParts.certificateContents =\n certificate || (await readFileAsync(certificatePath!, \"utf8\"));\n if (sendCertificateChain) {\n certificateParts.x5c = certificateParts.certificateContents;\n }\n\n const certificatePattern =\n /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/g;\n const publicKeys: string[] = [];\n\n // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c\n let match;\n do {\n match = certificatePattern.exec(certificateParts.certificateContents);\n if (match) {\n publicKeys.push(match[3]);\n }\n } while (match);\n\n if (publicKeys.length === 0) {\n throw new Error(\"The file at the specified path does not contain a PEM-encoded certificate.\");\n }\n\n certificateParts.thumbprint = createHash(\"sha1\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n return certificateParts as CertificateParts;\n}\n\n/**\n * MSAL client certificate client. Calls to MSAL's confidential application's `acquireTokenByClientCredential` during `doGetToken`.\n * @internal\n */\nexport class MsalClientCertificate extends MsalNode {\n private configuration: ClientCertificateCredentialPEMConfiguration;\n private sendCertificateChain?: boolean;\n\n constructor(options: MsalClientCertificateOptions) {\n super(options);\n this.requiresConfidential = true;\n this.configuration = options.configuration;\n this.sendCertificateChain = options.sendCertificateChain;\n }\n\n // Changing the MSAL configuration asynchronously\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n try {\n const parts = await parseCertificate(this.configuration, this.sendCertificateChain);\n\n let privateKey: string | undefined;\n if (this.configuration.certificatePassword !== undefined) {\n const privateKeyObject = createPrivateKey({\n key: parts.certificateContents,\n passphrase: this.configuration.certificatePassword,\n format: \"pem\",\n });\n\n privateKey = privateKeyObject\n .export({\n format: \"pem\",\n type: \"pkcs8\",\n })\n .toString();\n } else {\n privateKey = parts.certificateContents;\n }\n\n this.msalConfig.auth.clientCertificate = {\n thumbprint: parts.thumbprint,\n privateKey: privateKey,\n x5c: parts.x5c,\n };\n } catch (error: any) {\n this.logger.info(formatError(\"\", error));\n throw error;\n }\n return super.init(options);\n }\n\n protected async doGetToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {},\n ): Promise<AccessToken> {\n try {\n const clientCredReq: ClientCredentialRequest = {\n scopes,\n correlationId: options.correlationId,\n azureRegion: this.azureRegion,\n authority: options.authority,\n claims: options.claims,\n };\n const result = await this.getApp(\n \"confidential\",\n options.enableCae,\n ).acquireTokenByClientCredential(clientCredReq);\n // Even though we're providing the same default in memory persistence cache that we use for DeviceCodeCredential,\n // The Client Credential flow does not return the account information from the authentication service,\n // so each time getToken gets called, we will have to acquire a new token through the service.\n return this.handleResult(scopes, result || undefined);\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n}\n"]}
@@ -1,66 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
3
- import { __awaiter } from "tslib";
4
- import { MsalNode } from "./msalNodeCommon";
5
- import { formatError } from "../../util/logging";
6
- import { handleMsalError } from "../utils";
7
- import { parseCertificate } from "./msalClientCertificate";
8
- /**
9
- * MSAL on behalf of flow. Calls to MSAL's confidential application's `acquireTokenOnBehalfOf` during `doGetToken`.
10
- * @internal
11
- */
12
- export class MsalOnBehalfOf extends MsalNode {
13
- constructor(options) {
14
- super(options);
15
- this.logger.info("Initialized MSAL's On-Behalf-Of flow");
16
- this.requiresConfidential = true;
17
- this.userAssertionToken = options.userAssertionToken;
18
- this.certificatePath = options.certificatePath;
19
- this.sendCertificateChain = options.sendCertificateChain;
20
- this.clientSecret = options.clientSecret;
21
- }
22
- // Changing the MSAL configuration asynchronously
23
- init(options) {
24
- const _super = Object.create(null, {
25
- init: { get: () => super.init }
26
- });
27
- return __awaiter(this, void 0, void 0, function* () {
28
- if (this.certificatePath) {
29
- try {
30
- const parts = yield parseCertificate({ certificatePath: this.certificatePath }, this.sendCertificateChain);
31
- this.msalConfig.auth.clientCertificate = {
32
- thumbprint: parts.thumbprint,
33
- privateKey: parts.certificateContents,
34
- x5c: parts.x5c,
35
- };
36
- }
37
- catch (error) {
38
- this.logger.info(formatError("", error));
39
- throw error;
40
- }
41
- }
42
- else {
43
- this.msalConfig.auth.clientSecret = this.clientSecret;
44
- }
45
- return _super.init.call(this, options);
46
- });
47
- }
48
- doGetToken(scopes_1) {
49
- return __awaiter(this, arguments, void 0, function* (scopes, options = {}) {
50
- try {
51
- const result = yield this.getApp("confidential", options.enableCae).acquireTokenOnBehalfOf({
52
- scopes,
53
- correlationId: options.correlationId,
54
- authority: options.authority,
55
- claims: options.claims,
56
- oboAssertion: this.userAssertionToken,
57
- });
58
- return this.handleResult(scopes, result || undefined);
59
- }
60
- catch (err) {
61
- throw handleMsalError(scopes, err, options);
62
- }
63
- });
64
- }
65
- }
66
- //# sourceMappingURL=msalOnBehalfOf.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"msalOnBehalfOf.js","sourceRoot":"","sources":["../../../../../../identity/src/msal/nodeFlows/msalOnBehalfOf.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAI7D,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AA0B3D;;;GAGG;AACH,MAAM,OAAO,cAAe,SAAQ,QAAQ;IAM1C,YAAY,OAA8B;QACxC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,sCAAsC,CAAC,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BACzF,MAAM;oBACN,aAAa,EAAE,OAAO,CAAC,aAAa;oBACpC,SAAS,EAAE,OAAO,CAAC,SAAS;oBAC5B,MAAM,EAAE,OAAO,CAAC,MAAM;oBACtB,YAAY,EAAE,IAAI,CAAC,kBAAkB;iBACtC,CAAC,CAAC;gBACH,OAAO,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,MAAM,IAAI,SAAS,CAAC,CAAC;YACxD,CAAC;YAAC,OAAO,GAAQ,EAAE,CAAC;gBAClB,MAAM,eAAe,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;YAC9C,CAAC;QACH,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\n\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { formatError } from \"../../util/logging\";\nimport { handleMsalError } from \"../utils\";\nimport { parseCertificate } from \"./msalClientCertificate\";\n\n/**\n * Options that can be passed to configure MSAL to handle On-Behalf-Of authentication requests.\n * @internal\n */\nexport interface MsalOnBehalfOfOptions extends MsalNodeOptions {\n /**\n * A client secret that was generated for the App Registration.\n */\n clientSecret?: string;\n /**\n * Location of the PEM certificate.\n */\n certificatePath?: string;\n /**\n * Option to include x5c header for SubjectName and Issuer name authorization.\n * Set this option to send base64 encoded public certificate in the client assertion header as an x5c claim\n */\n sendCertificateChain?: boolean;\n /**\n * The user assertion for the On-Behalf-Of flow.\n */\n userAssertionToken: string;\n}\n\n/**\n * MSAL on behalf of flow. Calls to MSAL's confidential application's `acquireTokenOnBehalfOf` during `doGetToken`.\n * @internal\n */\nexport class MsalOnBehalfOf extends MsalNode {\n private userAssertionToken: string;\n private certificatePath?: string;\n private sendCertificateChain?: boolean;\n private clientSecret?: string;\n\n constructor(options: MsalOnBehalfOfOptions) {\n super(options);\n this.logger.info(\"Initialized MSAL's On-Behalf-Of flow\");\n this.requiresConfidential = true;\n this.userAssertionToken = options.userAssertionToken;\n this.certificatePath = options.certificatePath;\n this.sendCertificateChain = options.sendCertificateChain;\n this.clientSecret = options.clientSecret;\n }\n\n // Changing the MSAL configuration asynchronously\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n if (this.certificatePath) {\n try {\n const parts = await parseCertificate(\n { certificatePath: this.certificatePath },\n this.sendCertificateChain,\n );\n this.msalConfig.auth.clientCertificate = {\n thumbprint: parts.thumbprint,\n privateKey: parts.certificateContents,\n x5c: parts.x5c,\n };\n } catch (error: any) {\n this.logger.info(formatError(\"\", error));\n throw error;\n }\n } else {\n this.msalConfig.auth.clientSecret = this.clientSecret;\n }\n return super.init(options);\n }\n\n protected async doGetToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {},\n ): Promise<AccessToken> {\n try {\n const result = await this.getApp(\"confidential\", options.enableCae).acquireTokenOnBehalfOf({\n scopes,\n correlationId: options.correlationId,\n authority: options.authority,\n claims: options.claims,\n oboAssertion: this.userAssertionToken,\n });\n return this.handleResult(scopes, result || undefined);\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n}\n"]}