@azure/identity-cache-persistence 1.1.2-alpha.20241112.1 → 1.1.2-alpha.20241113.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.
Files changed (151) hide show
  1. package/dist/index.js.map +1 -1
  2. package/dist-esm/src/index.js.map +1 -0
  3. package/dist-esm/src/platforms.js.map +1 -0
  4. package/dist-esm/src/provider.js.map +1 -0
  5. package/package.json +3 -4
  6. package/dist-esm/identity/src/client/identityClient.js +0 -257
  7. package/dist-esm/identity/src/client/identityClient.js.map +0 -1
  8. package/dist-esm/identity/src/constants.js +0 -70
  9. package/dist-esm/identity/src/constants.js.map +0 -1
  10. package/dist-esm/identity/src/credentials/authorityValidationOptions.js +0 -4
  11. package/dist-esm/identity/src/credentials/authorityValidationOptions.js.map +0 -1
  12. package/dist-esm/identity/src/credentials/authorizationCodeCredential.js +0 -63
  13. package/dist-esm/identity/src/credentials/authorizationCodeCredential.js.map +0 -1
  14. package/dist-esm/identity/src/credentials/authorizationCodeCredentialOptions.js +0 -4
  15. package/dist-esm/identity/src/credentials/authorizationCodeCredentialOptions.js.map +0 -1
  16. package/dist-esm/identity/src/credentials/azureCliCredential.js +0 -194
  17. package/dist-esm/identity/src/credentials/azureCliCredential.js.map +0 -1
  18. package/dist-esm/identity/src/credentials/azureCliCredentialOptions.js +0 -4
  19. package/dist-esm/identity/src/credentials/azureCliCredentialOptions.js.map +0 -1
  20. package/dist-esm/identity/src/credentials/azureDeveloperCliCredential.js +0 -176
  21. package/dist-esm/identity/src/credentials/azureDeveloperCliCredential.js.map +0 -1
  22. package/dist-esm/identity/src/credentials/azureDeveloperCliCredentialOptions.js +0 -4
  23. package/dist-esm/identity/src/credentials/azureDeveloperCliCredentialOptions.js.map +0 -1
  24. package/dist-esm/identity/src/credentials/azurePipelinesCredential.js +0 -146
  25. package/dist-esm/identity/src/credentials/azurePipelinesCredential.js.map +0 -1
  26. package/dist-esm/identity/src/credentials/azurePipelinesCredentialOptions.js +0 -4
  27. package/dist-esm/identity/src/credentials/azurePipelinesCredentialOptions.js.map +0 -1
  28. package/dist-esm/identity/src/credentials/azurePowerShellCredential.js +0 -238
  29. package/dist-esm/identity/src/credentials/azurePowerShellCredential.js.map +0 -1
  30. package/dist-esm/identity/src/credentials/azurePowerShellCredentialOptions.js +0 -4
  31. package/dist-esm/identity/src/credentials/azurePowerShellCredentialOptions.js.map +0 -1
  32. package/dist-esm/identity/src/credentials/brokerAuthOptions.js +0 -2
  33. package/dist-esm/identity/src/credentials/brokerAuthOptions.js.map +0 -1
  34. package/dist-esm/identity/src/credentials/browserCustomizationOptions.js +0 -4
  35. package/dist-esm/identity/src/credentials/browserCustomizationOptions.js.map +0 -1
  36. package/dist-esm/identity/src/credentials/chainedTokenCredential.js +0 -95
  37. package/dist-esm/identity/src/credentials/chainedTokenCredential.js.map +0 -1
  38. package/dist-esm/identity/src/credentials/clientAssertionCredential.js +0 -58
  39. package/dist-esm/identity/src/credentials/clientAssertionCredential.js.map +0 -1
  40. package/dist-esm/identity/src/credentials/clientAssertionCredentialOptions.js +0 -4
  41. package/dist-esm/identity/src/credentials/clientAssertionCredentialOptions.js.map +0 -1
  42. package/dist-esm/identity/src/credentials/clientCertificateCredential.js +0 -126
  43. package/dist-esm/identity/src/credentials/clientCertificateCredential.js.map +0 -1
  44. package/dist-esm/identity/src/credentials/clientCertificateCredentialOptions.js +0 -4
  45. package/dist-esm/identity/src/credentials/clientCertificateCredentialOptions.js.map +0 -1
  46. package/dist-esm/identity/src/credentials/clientSecretCredential.js +0 -63
  47. package/dist-esm/identity/src/credentials/clientSecretCredential.js.map +0 -1
  48. package/dist-esm/identity/src/credentials/clientSecretCredentialOptions.js +0 -4
  49. package/dist-esm/identity/src/credentials/clientSecretCredentialOptions.js.map +0 -1
  50. package/dist-esm/identity/src/credentials/credentialPersistenceOptions.js +0 -4
  51. package/dist-esm/identity/src/credentials/credentialPersistenceOptions.js.map +0 -1
  52. package/dist-esm/identity/src/credentials/defaultAzureCredential.js +0 -164
  53. package/dist-esm/identity/src/credentials/defaultAzureCredential.js.map +0 -1
  54. package/dist-esm/identity/src/credentials/defaultAzureCredentialOptions.js +0 -4
  55. package/dist-esm/identity/src/credentials/defaultAzureCredentialOptions.js.map +0 -1
  56. package/dist-esm/identity/src/credentials/deviceCodeCredential.js +0 -96
  57. package/dist-esm/identity/src/credentials/deviceCodeCredential.js.map +0 -1
  58. package/dist-esm/identity/src/credentials/deviceCodeCredentialOptions.js +0 -4
  59. package/dist-esm/identity/src/credentials/deviceCodeCredentialOptions.js.map +0 -1
  60. package/dist-esm/identity/src/credentials/environmentCredential.js +0 -133
  61. package/dist-esm/identity/src/credentials/environmentCredential.js.map +0 -1
  62. package/dist-esm/identity/src/credentials/environmentCredentialOptions.js +0 -4
  63. package/dist-esm/identity/src/credentials/environmentCredentialOptions.js.map +0 -1
  64. package/dist-esm/identity/src/credentials/interactiveBrowserCredential.js +0 -96
  65. package/dist-esm/identity/src/credentials/interactiveBrowserCredential.js.map +0 -1
  66. package/dist-esm/identity/src/credentials/interactiveBrowserCredentialOptions.js +0 -4
  67. package/dist-esm/identity/src/credentials/interactiveBrowserCredentialOptions.js.map +0 -1
  68. package/dist-esm/identity/src/credentials/interactiveCredentialOptions.js +0 -4
  69. package/dist-esm/identity/src/credentials/interactiveCredentialOptions.js.map +0 -1
  70. package/dist-esm/identity/src/credentials/managedIdentityCredential/imdsMsi.js +0 -125
  71. package/dist-esm/identity/src/credentials/managedIdentityCredential/imdsMsi.js.map +0 -1
  72. package/dist-esm/identity/src/credentials/managedIdentityCredential/imdsRetryPolicy.js +0 -33
  73. package/dist-esm/identity/src/credentials/managedIdentityCredential/imdsRetryPolicy.js.map +0 -1
  74. package/dist-esm/identity/src/credentials/managedIdentityCredential/index.js +0 -220
  75. package/dist-esm/identity/src/credentials/managedIdentityCredential/index.js.map +0 -1
  76. package/dist-esm/identity/src/credentials/managedIdentityCredential/models.js +0 -4
  77. package/dist-esm/identity/src/credentials/managedIdentityCredential/models.js.map +0 -1
  78. package/dist-esm/identity/src/credentials/managedIdentityCredential/tokenExchangeMsi.js +0 -37
  79. package/dist-esm/identity/src/credentials/managedIdentityCredential/tokenExchangeMsi.js.map +0 -1
  80. package/dist-esm/identity/src/credentials/managedIdentityCredential/utils.js +0 -77
  81. package/dist-esm/identity/src/credentials/managedIdentityCredential/utils.js.map +0 -1
  82. package/dist-esm/identity/src/credentials/multiTenantTokenCredentialOptions.js +0 -4
  83. package/dist-esm/identity/src/credentials/multiTenantTokenCredentialOptions.js.map +0 -1
  84. package/dist-esm/identity/src/credentials/onBehalfOfCredential.js +0 -119
  85. package/dist-esm/identity/src/credentials/onBehalfOfCredential.js.map +0 -1
  86. package/dist-esm/identity/src/credentials/onBehalfOfCredentialOptions.js +0 -4
  87. package/dist-esm/identity/src/credentials/onBehalfOfCredentialOptions.js.map +0 -1
  88. package/dist-esm/identity/src/credentials/usernamePasswordCredential.js +0 -70
  89. package/dist-esm/identity/src/credentials/usernamePasswordCredential.js.map +0 -1
  90. package/dist-esm/identity/src/credentials/usernamePasswordCredentialOptions.js +0 -4
  91. package/dist-esm/identity/src/credentials/usernamePasswordCredentialOptions.js.map +0 -1
  92. package/dist-esm/identity/src/credentials/visualStudioCodeCredential.js +0 -195
  93. package/dist-esm/identity/src/credentials/visualStudioCodeCredential.js.map +0 -1
  94. package/dist-esm/identity/src/credentials/visualStudioCodeCredentialOptions.js +0 -4
  95. package/dist-esm/identity/src/credentials/visualStudioCodeCredentialOptions.js.map +0 -1
  96. package/dist-esm/identity/src/credentials/visualStudioCodeCredentialPlugin.js +0 -4
  97. package/dist-esm/identity/src/credentials/visualStudioCodeCredentialPlugin.js.map +0 -1
  98. package/dist-esm/identity/src/credentials/workloadIdentityCredential.js +0 -119
  99. package/dist-esm/identity/src/credentials/workloadIdentityCredential.js.map +0 -1
  100. package/dist-esm/identity/src/credentials/workloadIdentityCredentialOptions.js +0 -4
  101. package/dist-esm/identity/src/credentials/workloadIdentityCredentialOptions.js.map +0 -1
  102. package/dist-esm/identity/src/errors.js +0 -123
  103. package/dist-esm/identity/src/errors.js.map +0 -1
  104. package/dist-esm/identity/src/index.js +0 -34
  105. package/dist-esm/identity/src/index.js.map +0 -1
  106. package/dist-esm/identity/src/msal/msal.js +0 -5
  107. package/dist-esm/identity/src/msal/msal.js.map +0 -1
  108. package/dist-esm/identity/src/msal/nodeFlows/brokerOptions.js +0 -2
  109. package/dist-esm/identity/src/msal/nodeFlows/brokerOptions.js.map +0 -1
  110. package/dist-esm/identity/src/msal/nodeFlows/msalClient.js +0 -511
  111. package/dist-esm/identity/src/msal/nodeFlows/msalClient.js.map +0 -1
  112. package/dist-esm/identity/src/msal/nodeFlows/msalPlugins.js +0 -87
  113. package/dist-esm/identity/src/msal/nodeFlows/msalPlugins.js.map +0 -1
  114. package/dist-esm/identity/src/msal/nodeFlows/tokenCachePersistenceOptions.js +0 -4
  115. package/dist-esm/identity/src/msal/nodeFlows/tokenCachePersistenceOptions.js.map +0 -1
  116. package/dist-esm/identity/src/msal/types.js +0 -4
  117. package/dist-esm/identity/src/msal/types.js.map +0 -1
  118. package/dist-esm/identity/src/msal/utils.js +0 -232
  119. package/dist-esm/identity/src/msal/utils.js.map +0 -1
  120. package/dist-esm/identity/src/plugins/consumer.js +0 -43
  121. package/dist-esm/identity/src/plugins/consumer.js.map +0 -1
  122. package/dist-esm/identity/src/plugins/provider.js +0 -4
  123. package/dist-esm/identity/src/plugins/provider.js.map +0 -1
  124. package/dist-esm/identity/src/regionalAuthority.js +0 -140
  125. package/dist-esm/identity/src/regionalAuthority.js.map +0 -1
  126. package/dist-esm/identity/src/tokenCredentialOptions.js +0 -4
  127. package/dist-esm/identity/src/tokenCredentialOptions.js.map +0 -1
  128. package/dist-esm/identity/src/tokenProvider.js +0 -55
  129. package/dist-esm/identity/src/tokenProvider.js.map +0 -1
  130. package/dist-esm/identity/src/util/identityTokenEndpoint.js +0 -11
  131. package/dist-esm/identity/src/util/identityTokenEndpoint.js.map +0 -1
  132. package/dist-esm/identity/src/util/logging.js +0 -94
  133. package/dist-esm/identity/src/util/logging.js.map +0 -1
  134. package/dist-esm/identity/src/util/processMultiTenantRequest.js +0 -35
  135. package/dist-esm/identity/src/util/processMultiTenantRequest.js.map +0 -1
  136. package/dist-esm/identity/src/util/processUtils.js +0 -32
  137. package/dist-esm/identity/src/util/processUtils.js.map +0 -1
  138. package/dist-esm/identity/src/util/scopeUtils.js +0 -29
  139. package/dist-esm/identity/src/util/scopeUtils.js.map +0 -1
  140. package/dist-esm/identity/src/util/subscriptionUtils.js +0 -14
  141. package/dist-esm/identity/src/util/subscriptionUtils.js.map +0 -1
  142. package/dist-esm/identity/src/util/tenantIdUtils.js +0 -44
  143. package/dist-esm/identity/src/util/tenantIdUtils.js.map +0 -1
  144. package/dist-esm/identity/src/util/tracing.js +0 -14
  145. package/dist-esm/identity/src/util/tracing.js.map +0 -1
  146. package/dist-esm/identity-cache-persistence/src/index.js.map +0 -1
  147. package/dist-esm/identity-cache-persistence/src/platforms.js.map +0 -1
  148. package/dist-esm/identity-cache-persistence/src/provider.js.map +0 -1
  149. /package/dist-esm/{identity-cache-persistence/src → src}/index.js +0 -0
  150. /package/dist-esm/{identity-cache-persistence/src → src}/platforms.js +0 -0
  151. /package/dist-esm/{identity-cache-persistence/src → src}/provider.js +0 -0
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/platforms.ts","../src/provider.ts","../src/index.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/* eslint-disable tsdoc/syntax */\n\nimport * as path from \"path\";\nimport type { IPersistence as Persistence } from \"@azure/msal-node-extensions\";\nimport {\n DataProtectionScope,\n FilePersistence,\n FilePersistenceWithDataProtection,\n KeychainPersistence,\n LibSecretPersistence,\n} from \"@azure/msal-node-extensions\";\nimport type { TokenCachePersistenceOptions } from \"@azure/identity\";\n\n/**\n * Local application data folder\n * Expected values:\n * - Darwin: '/Users/user/'\n * - Windows 8+: 'C:\\Users\\user\\AppData\\Local'\n * - Linux: '/home/user/.local/share'\n * @internal\n */\nconst localApplicationDataFolder =\n process.env.APPDATA?.replace?.(/(.Roaming)*$/, \"\\\\Local\") ?? process.env.HOME!;\n\n/**\n * Dictionary of values that we use as default as we discover, pick and enable the persistence layer.\n * @internal\n */\nexport const defaultMsalValues = {\n tokenCache: {\n name: \"msal.cache\",\n // Expected values:\n // - Darwin: '/Users/user/.IdentityService'\n // - Windows 8+: 'C:\\Users\\user\\AppData\\Local\\.IdentityService'\n // - Linux: '/home/user/.IdentityService'\n directory: path.join(localApplicationDataFolder, \".IdentityService\"),\n },\n keyRing: {\n label: \"MSALCache\",\n schema: \"msal.cache\",\n collection: \"default\",\n attributes: {\n MsalClientID: \"Microsoft.Developer.IdentityService\",\n \"Microsoft.Developer.IdentityService\": \"1.0.0.0\",\n },\n service: \"Microsoft.Developer.IdentityService\",\n account: \"MSALCache\",\n },\n keyChain: {\n service: \"Microsoft.Developer.IdentityService\",\n account: \"MSALCache\",\n },\n};\n\n/**\n * Options that are used by the underlying MSAL cache provider.\n * @internal\n */\nexport type MsalPersistenceOptions = Omit<TokenCachePersistenceOptions, \"enabled\">;\n\n/**\n * A function that returns a persistent token cache instance.\n * @internal\n */\ntype MsalPersistenceFactory = (options?: MsalPersistenceOptions) => Promise<Persistence>;\n\n/**\n * Expected responses:\n * - Darwin: '/Users/user/.IdentityService/<name>'\n * - Windows 8+: 'C:\\Users\\user\\AppData\\Local\\.IdentityService\\<name>'\n * - Linux: '/home/user/.IdentityService/<name>'\n * @internal\n */\nfunction getPersistencePath(name: string): string {\n return path.join(defaultMsalValues.tokenCache.directory, name);\n}\n\n/**\n * Set of the platforms we attempt to deliver persistence on.\n *\n * - On Windows we use DPAPI.\n * - On OSX (Darwin), we try to use the system's Keychain, otherwise if the property `unsafeAllowUnencryptedStorage` is set to true, we use an unencrypted file.\n * - On Linux, we try to use the system's Keyring, otherwise if the property `unsafeAllowUnencryptedStorage` is set to true, we use an unencrypted file.\n *\n * Other platforms _are not supported_ at this time.\n *\n * @internal\n */\nexport const msalPersistencePlatforms: Partial<Record<NodeJS.Platform, MsalPersistenceFactory>> = {\n win32: ({ name = defaultMsalValues.tokenCache.name } = {}): Promise<Persistence> =>\n FilePersistenceWithDataProtection.create(\n getPersistencePath(name),\n DataProtectionScope.CurrentUser,\n ),\n\n darwin: async (options: MsalPersistenceOptions = {}): Promise<Persistence> => {\n const { name, unsafeAllowUnencryptedStorage } = options;\n const { service, account } = defaultMsalValues.keyChain;\n const persistencePath = getPersistencePath(name || defaultMsalValues.tokenCache.name);\n\n try {\n const persistence = await KeychainPersistence.create(persistencePath, service, account);\n // If we don't encounter an error when trying to read from the keychain, then we should be good to go.\n await persistence.load();\n return persistence;\n } catch (e: any) {\n // If we got an error while trying to read from the keyring,\n // we will proceed only if the user has specified that unencrypted storage is allowed.\n if (!unsafeAllowUnencryptedStorage) {\n throw new Error(\"Unable to read from the macOS Keychain.\");\n }\n return FilePersistence.create(persistencePath);\n }\n },\n\n linux: async (options: MsalPersistenceOptions = {}): Promise<Persistence> => {\n const { name, unsafeAllowUnencryptedStorage } = options;\n const { service, account } = defaultMsalValues.keyRing;\n const persistencePath = getPersistencePath(name || defaultMsalValues.tokenCache.name);\n\n try {\n const persistence = await LibSecretPersistence.create(persistencePath, service, account);\n // If we don't encounter an error when trying to read from the keyring, then we should be good to go.\n await persistence.load();\n return persistence;\n } catch (e: any) {\n // If we got an error while trying to read from the keyring,\n // we will proceed only if the user has specified that unencrypted storage is allowed.\n if (!unsafeAllowUnencryptedStorage) {\n throw new Error(\"Unable to read from the system keyring (libsecret).\");\n }\n return FilePersistence.create(persistencePath);\n }\n },\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { MsalPersistenceOptions } from \"./platforms\";\nimport { msalPersistencePlatforms } from \"./platforms\";\nimport type { IPersistence as Persistence } from \"@azure/msal-node-extensions\";\nimport { PersistenceCachePlugin } from \"@azure/msal-node-extensions\";\nimport type { ICachePlugin as CachePlugin } from \"@azure/msal-node\";\n\n/**\n * This is used to gain access to the underlying Persistence instance, which we use for testing\n *\n * @returns a raw persistence instance\n * @internal\n */\nexport async function createPersistence(options: MsalPersistenceOptions): Promise<Persistence> {\n const persistence = await msalPersistencePlatforms[process.platform]?.(options);\n\n if (persistence === undefined) {\n throw new Error(\"no persistence providers are available on this platform\");\n }\n\n return persistence;\n}\n\nexport async function createPersistenceCachePlugin(\n options?: MsalPersistenceOptions,\n): Promise<CachePlugin> {\n const persistence = await createPersistence(options ?? {});\n\n return new PersistenceCachePlugin(persistence, {\n retryNumber: 100,\n retryDelay: 50,\n });\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AzurePluginContext } from \"../../identity/src/plugins/provider\";\nimport type { IdentityPlugin } from \"@azure/identity\";\nimport { createPersistenceCachePlugin } from \"./provider\";\n\n/**\n * A plugin that provides persistent token caching for `@azure/identity`\n * credentials. The plugin API is compatible with `@azure/identity` versions\n * 2.0.0 and later. Load this plugin using the `useIdentityPlugin`\n * function, imported from `@azure/identity`.\n *\n * In order to enable this functionality, you must also pass\n * `tokenCachePersistenceOptions` to your credential constructors with an\n * `enabled` property set to true.\n *\n * Example:\n *\n * ```ts snippet:device_code_credential_example\n * import { DeviceCodeCredential } from \"@azure/identity\";\n *\n * const credential = new DeviceCodeCredential({\n * tokenCachePersistenceOptions: {\n * enabled: true,\n * },\n * });\n * // We'll use the Microsoft Graph scope as an example\n * const scope = \"https://graph.microsoft.com/.default\";\n * // Print out part of the access token\n * console.log((await credential.getToken(scope)).token.substring(0, 10), \"...\");\n * ```\n */\n\nexport const cachePersistencePlugin: IdentityPlugin = (context) => {\n const { cachePluginControl } = context as AzurePluginContext;\n\n cachePluginControl.setPersistence(createPersistenceCachePlugin);\n};\n"],"names":["path","FilePersistenceWithDataProtection","DataProtectionScope","__awaiter","KeychainPersistence","FilePersistence","LibSecretPersistence","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AAA;AAAA;;AClCD;AACA;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;AAyBG;AAEU,MAAA,sBAAsB,GAAmB,CAAC,OAAO,KAAI;AAChE,IAAA,MAAM,EAAE,kBAAkB,EAAE,GAAG,OAA6B;AAE5D,IAAA,kBAAkB,CAAC,cAAc,CAAC,4BAA4B,CAAC;AACjE;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../src/platforms.ts","../src/provider.ts","../src/index.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/* eslint-disable tsdoc/syntax */\n\nimport * as path from \"path\";\nimport type { IPersistence as Persistence } from \"@azure/msal-node-extensions\";\nimport {\n DataProtectionScope,\n FilePersistence,\n FilePersistenceWithDataProtection,\n KeychainPersistence,\n LibSecretPersistence,\n} from \"@azure/msal-node-extensions\";\nimport type { TokenCachePersistenceOptions } from \"@azure/identity\";\n\n/**\n * Local application data folder\n * Expected values:\n * - Darwin: '/Users/user/'\n * - Windows 8+: 'C:\\Users\\user\\AppData\\Local'\n * - Linux: '/home/user/.local/share'\n * @internal\n */\nconst localApplicationDataFolder =\n process.env.APPDATA?.replace?.(/(.Roaming)*$/, \"\\\\Local\") ?? process.env.HOME!;\n\n/**\n * Dictionary of values that we use as default as we discover, pick and enable the persistence layer.\n * @internal\n */\nexport const defaultMsalValues = {\n tokenCache: {\n name: \"msal.cache\",\n // Expected values:\n // - Darwin: '/Users/user/.IdentityService'\n // - Windows 8+: 'C:\\Users\\user\\AppData\\Local\\.IdentityService'\n // - Linux: '/home/user/.IdentityService'\n directory: path.join(localApplicationDataFolder, \".IdentityService\"),\n },\n keyRing: {\n label: \"MSALCache\",\n schema: \"msal.cache\",\n collection: \"default\",\n attributes: {\n MsalClientID: \"Microsoft.Developer.IdentityService\",\n \"Microsoft.Developer.IdentityService\": \"1.0.0.0\",\n },\n service: \"Microsoft.Developer.IdentityService\",\n account: \"MSALCache\",\n },\n keyChain: {\n service: \"Microsoft.Developer.IdentityService\",\n account: \"MSALCache\",\n },\n};\n\n/**\n * Options that are used by the underlying MSAL cache provider.\n * @internal\n */\nexport type MsalPersistenceOptions = Omit<TokenCachePersistenceOptions, \"enabled\">;\n\n/**\n * A function that returns a persistent token cache instance.\n * @internal\n */\ntype MsalPersistenceFactory = (options?: MsalPersistenceOptions) => Promise<Persistence>;\n\n/**\n * Expected responses:\n * - Darwin: '/Users/user/.IdentityService/<name>'\n * - Windows 8+: 'C:\\Users\\user\\AppData\\Local\\.IdentityService\\<name>'\n * - Linux: '/home/user/.IdentityService/<name>'\n * @internal\n */\nfunction getPersistencePath(name: string): string {\n return path.join(defaultMsalValues.tokenCache.directory, name);\n}\n\n/**\n * Set of the platforms we attempt to deliver persistence on.\n *\n * - On Windows we use DPAPI.\n * - On OSX (Darwin), we try to use the system's Keychain, otherwise if the property `unsafeAllowUnencryptedStorage` is set to true, we use an unencrypted file.\n * - On Linux, we try to use the system's Keyring, otherwise if the property `unsafeAllowUnencryptedStorage` is set to true, we use an unencrypted file.\n *\n * Other platforms _are not supported_ at this time.\n *\n * @internal\n */\nexport const msalPersistencePlatforms: Partial<Record<NodeJS.Platform, MsalPersistenceFactory>> = {\n win32: ({ name = defaultMsalValues.tokenCache.name } = {}): Promise<Persistence> =>\n FilePersistenceWithDataProtection.create(\n getPersistencePath(name),\n DataProtectionScope.CurrentUser,\n ),\n\n darwin: async (options: MsalPersistenceOptions = {}): Promise<Persistence> => {\n const { name, unsafeAllowUnencryptedStorage } = options;\n const { service, account } = defaultMsalValues.keyChain;\n const persistencePath = getPersistencePath(name || defaultMsalValues.tokenCache.name);\n\n try {\n const persistence = await KeychainPersistence.create(persistencePath, service, account);\n // If we don't encounter an error when trying to read from the keychain, then we should be good to go.\n await persistence.load();\n return persistence;\n } catch (e: any) {\n // If we got an error while trying to read from the keyring,\n // we will proceed only if the user has specified that unencrypted storage is allowed.\n if (!unsafeAllowUnencryptedStorage) {\n throw new Error(\"Unable to read from the macOS Keychain.\");\n }\n return FilePersistence.create(persistencePath);\n }\n },\n\n linux: async (options: MsalPersistenceOptions = {}): Promise<Persistence> => {\n const { name, unsafeAllowUnencryptedStorage } = options;\n const { service, account } = defaultMsalValues.keyRing;\n const persistencePath = getPersistencePath(name || defaultMsalValues.tokenCache.name);\n\n try {\n const persistence = await LibSecretPersistence.create(persistencePath, service, account);\n // If we don't encounter an error when trying to read from the keyring, then we should be good to go.\n await persistence.load();\n return persistence;\n } catch (e: any) {\n // If we got an error while trying to read from the keyring,\n // we will proceed only if the user has specified that unencrypted storage is allowed.\n if (!unsafeAllowUnencryptedStorage) {\n throw new Error(\"Unable to read from the system keyring (libsecret).\");\n }\n return FilePersistence.create(persistencePath);\n }\n },\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { MsalPersistenceOptions } from \"./platforms\";\nimport { msalPersistencePlatforms } from \"./platforms\";\nimport type { IPersistence as Persistence } from \"@azure/msal-node-extensions\";\nimport { PersistenceCachePlugin } from \"@azure/msal-node-extensions\";\nimport type { ICachePlugin as CachePlugin } from \"@azure/msal-node\";\n\n/**\n * This is used to gain access to the underlying Persistence instance, which we use for testing\n *\n * @returns a raw persistence instance\n * @internal\n */\nexport async function createPersistence(options: MsalPersistenceOptions): Promise<Persistence> {\n const persistence = await msalPersistencePlatforms[process.platform]?.(options);\n\n if (persistence === undefined) {\n throw new Error(\"no persistence providers are available on this platform\");\n }\n\n return persistence;\n}\n\nexport async function createPersistenceCachePlugin(\n options?: MsalPersistenceOptions,\n): Promise<CachePlugin> {\n const persistence = await createPersistence(options ?? {});\n\n return new PersistenceCachePlugin(persistence, {\n retryNumber: 100,\n retryDelay: 50,\n });\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { IdentityPlugin, TokenCachePersistenceOptions } from \"@azure/identity\";\nimport { createPersistenceCachePlugin } from \"./provider\";\n\n/**\n * Plugin context entries for controlling cache plugins.\n */\ninterface CachePluginControl {\n setPersistence(\n persistenceFactory: (\n options?: TokenCachePersistenceOptions,\n ) => Promise<import(\"@azure/msal-node\").ICachePlugin>,\n ): void;\n}\n/**\n * Context options passed to a plugin during initialization.\n *\n * Represents a subset of the context defined in `@azure/identity`\n *\n */\ninterface AzurePluginContext {\n cachePluginControl: CachePluginControl;\n}\n\n/**\n * A plugin that provides persistent token caching for `@azure/identity`\n * credentials. The plugin API is compatible with `@azure/identity` versions\n * 2.0.0 and later. Load this plugin using the `useIdentityPlugin`\n * function, imported from `@azure/identity`.\n *\n * In order to enable this functionality, you must also pass\n * `tokenCachePersistenceOptions` to your credential constructors with an\n * `enabled` property set to true.\n *\n * Example:\n *\n * ```ts snippet:device_code_credential_example\n * import { DeviceCodeCredential } from \"@azure/identity\";\n *\n * const credential = new DeviceCodeCredential({\n * tokenCachePersistenceOptions: {\n * enabled: true,\n * },\n * });\n * // We'll use the Microsoft Graph scope as an example\n * const scope = \"https://graph.microsoft.com/.default\";\n * // Print out part of the access token\n * console.log((await credential.getToken(scope)).token.substring(0, 10), \"...\");\n * ```\n */\n\nexport const cachePersistencePlugin: IdentityPlugin = (context) => {\n const { cachePluginControl } = context as AzurePluginContext;\n\n cachePluginControl.setPersistence(createPersistenceCachePlugin);\n};\n"],"names":["path","FilePersistenceWithDataProtection","DataProtectionScope","__awaiter","KeychainPersistence","FilePersistence","LibSecretPersistence","PersistenceCachePlugin"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;;AAeA;;;;;;;AAOG;AACH,MAAM,0BAA0B,GAC9B,CAAA,EAAA,GAAA,CAAA,EAAA,GAAA,MAAA,OAAO,CAAC,GAAG,CAAC,OAAO,MAAA,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAE,OAAO,MAAG,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,IAAA,CAAA,EAAA,EAAA,cAAc,EAAE,SAAS,CAAC,MAAA,I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;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,MAAM,CAAC,MAAM,sBAAsB,GAAmB,CAAC,OAAO,EAAE,EAAE;IAChE,MAAM,EAAE,kBAAkB,EAAE,GAAG,OAA6B,CAAC;IAE7D,kBAAkB,CAAC,cAAc,CAAC,4BAA4B,CAAC,CAAC;AAClE,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { IdentityPlugin, TokenCachePersistenceOptions } from \"@azure/identity\";\nimport { createPersistenceCachePlugin } from \"./provider\";\n\n/**\n * Plugin context entries for controlling cache plugins.\n */\ninterface CachePluginControl {\n setPersistence(\n persistenceFactory: (\n options?: TokenCachePersistenceOptions,\n ) => Promise<import(\"@azure/msal-node\").ICachePlugin>,\n ): void;\n}\n/**\n * Context options passed to a plugin during initialization.\n *\n * Represents a subset of the context defined in `@azure/identity`\n *\n */\ninterface AzurePluginContext {\n cachePluginControl: CachePluginControl;\n}\n\n/**\n * A plugin that provides persistent token caching for `@azure/identity`\n * credentials. The plugin API is compatible with `@azure/identity` versions\n * 2.0.0 and later. Load this plugin using the `useIdentityPlugin`\n * function, imported from `@azure/identity`.\n *\n * In order to enable this functionality, you must also pass\n * `tokenCachePersistenceOptions` to your credential constructors with an\n * `enabled` property set to true.\n *\n * Example:\n *\n * ```ts snippet:device_code_credential_example\n * import { DeviceCodeCredential } from \"@azure/identity\";\n *\n * const credential = new DeviceCodeCredential({\n * tokenCachePersistenceOptions: {\n * enabled: true,\n * },\n * });\n * // We'll use the Microsoft Graph scope as an example\n * const scope = \"https://graph.microsoft.com/.default\";\n * // Print out part of the access token\n * console.log((await credential.getToken(scope)).token.substring(0, 10), \"...\");\n * ```\n */\n\nexport const cachePersistencePlugin: IdentityPlugin = (context) => {\n const { cachePluginControl } = context as AzurePluginContext;\n\n cachePluginControl.setPersistence(createPersistenceCachePlugin);\n};\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platforms.js","sourceRoot":"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Ae,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;YACzF,qGAAqG;YACrG,MAAM,WAAW,CAAC,IAAI,EAAE,CAAC;YACzB,OAAO,WAAW,CAAC;QACrB,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,4DAA4D;YAC5D,sFAAsF;YACtF,IAAI,CAAC,6BAA6B,EAAE,CAAC;gBACnC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;YACzE,CAAC;YACD,OAAO,eAAe,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;QACjD,CAAC;IACH,CAAC,CAAA;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/* eslint-disable tsdoc/syntax */\n\nimport * as path from \"path\";\nimport type { IPersistence as Persistence } from \"@azure/msal-node-extensions\";\nimport {\n DataProtectionScope,\n FilePersistence,\n FilePersistenceWithDataProtection,\n KeychainPersistence,\n LibSecretPersistence,\n} from \"@azure/msal-node-extensions\";\nimport type { TokenCachePersistenceOptions } from \"@azure/identity\";\n\n/**\n * Local application data folder\n * Expected values:\n * - Darwin: '/Users/user/'\n * - Windows 8+: 'C:\\Users\\user\\AppData\\Local'\n * - Linux: '/home/user/.local/share'\n * @internal\n */\nconst localApplicationDataFolder =\n process.env.APPDATA?.replace?.(/(.Roaming)*$/, \"\\\\Local\") ?? process.env.HOME!;\n\n/**\n * Dictionary of values that we use as default as we discover, pick and enable the persistence layer.\n * @internal\n */\nexport const defaultMsalValues = {\n tokenCache: {\n name: \"msal.cache\",\n // Expected values:\n // - Darwin: '/Users/user/.IdentityService'\n // - Windows 8+: 'C:\\Users\\user\\AppData\\Local\\.IdentityService'\n // - Linux: '/home/user/.IdentityService'\n directory: path.join(localApplicationDataFolder, \".IdentityService\"),\n },\n keyRing: {\n label: \"MSALCache\",\n schema: \"msal.cache\",\n collection: \"default\",\n attributes: {\n MsalClientID: \"Microsoft.Developer.IdentityService\",\n \"Microsoft.Developer.IdentityService\": \"1.0.0.0\",\n },\n service: \"Microsoft.Developer.IdentityService\",\n account: \"MSALCache\",\n },\n keyChain: {\n service: \"Microsoft.Developer.IdentityService\",\n account: \"MSALCache\",\n },\n};\n\n/**\n * Options that are used by the underlying MSAL cache provider.\n * @internal\n */\nexport type MsalPersistenceOptions = Omit<TokenCachePersistenceOptions, \"enabled\">;\n\n/**\n * A function that returns a persistent token cache instance.\n * @internal\n */\ntype MsalPersistenceFactory = (options?: MsalPersistenceOptions) => Promise<Persistence>;\n\n/**\n * Expected responses:\n * - Darwin: '/Users/user/.IdentityService/<name>'\n * - Windows 8+: 'C:\\Users\\user\\AppData\\Local\\.IdentityService\\<name>'\n * - Linux: '/home/user/.IdentityService/<name>'\n * @internal\n */\nfunction getPersistencePath(name: string): string {\n return path.join(defaultMsalValues.tokenCache.directory, name);\n}\n\n/**\n * Set of the platforms we attempt to deliver persistence on.\n *\n * - On Windows we use DPAPI.\n * - On OSX (Darwin), we try to use the system's Keychain, otherwise if the property `unsafeAllowUnencryptedStorage` is set to true, we use an unencrypted file.\n * - On Linux, we try to use the system's Keyring, otherwise if the property `unsafeAllowUnencryptedStorage` is set to true, we use an unencrypted file.\n *\n * Other platforms _are not supported_ at this time.\n *\n * @internal\n */\nexport const msalPersistencePlatforms: Partial<Record<NodeJS.Platform, MsalPersistenceFactory>> = {\n win32: ({ name = defaultMsalValues.tokenCache.name } = {}): Promise<Persistence> =>\n FilePersistenceWithDataProtection.create(\n getPersistencePath(name),\n DataProtectionScope.CurrentUser,\n ),\n\n darwin: async (options: MsalPersistenceOptions = {}): Promise<Persistence> => {\n const { name, unsafeAllowUnencryptedStorage } = options;\n const { service, account } = defaultMsalValues.keyChain;\n const persistencePath = getPersistencePath(name || defaultMsalValues.tokenCache.name);\n\n try {\n const persistence = await KeychainPersistence.create(persistencePath, service, account);\n // If we don't encounter an error when trying to read from the keychain, then we should be good to go.\n await persistence.load();\n return persistence;\n } catch (e: any) {\n // If we got an error while trying to read from the keyring,\n // we will proceed only if the user has specified that unencrypted storage is allowed.\n if (!unsafeAllowUnencryptedStorage) {\n throw new Error(\"Unable to read from the macOS Keychain.\");\n }\n return FilePersistence.create(persistencePath);\n }\n },\n\n linux: async (options: MsalPersistenceOptions = {}): Promise<Persistence> => {\n const { name, unsafeAllowUnencryptedStorage } = options;\n const { service, account } = defaultMsalValues.keyRing;\n const persistencePath = getPersistencePath(name || defaultMsalValues.tokenCache.name);\n\n try {\n const persistence = await LibSecretPersistence.create(persistencePath, service, account);\n // If we don't encounter an error when trying to read from the keyring, then we should be good to go.\n await persistence.load();\n return persistence;\n } catch (e: any) {\n // If we got an error while trying to read from the keyring,\n // we will proceed only if the user has specified that unencrypted storage is allowed.\n if (!unsafeAllowUnencryptedStorage) {\n throw new Error(\"Unable to read from the system keyring (libsecret).\");\n }\n return FilePersistence.create(persistencePath);\n }\n },\n};\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/provider.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAGlC,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAEvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAGrE;;;;;GAKG;AACH,MAAM,UAAgB,iBAAiB,CAAC,OAA+B;;;QACrE,MAAM,WAAW,GAAG,MAAM,CAAA,MAAA,wBAAwB,CAAC,OAAO,CAAC,QAAQ,CAAC,yEAAG,OAAO,CAAC,CAAA,CAAC;QAEhF,IAAI,WAAW,KAAK,SAAS,EAAE,CAAC;YAC9B,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;QAC7E,CAAC;QAED,OAAO,WAAW,CAAC;IACrB,CAAC;CAAA;AAED,MAAM,UAAgB,4BAA4B,CAChD,OAAgC;;QAEhC,MAAM,WAAW,GAAG,MAAM,iBAAiB,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC,CAAC;QAE3D,OAAO,IAAI,sBAAsB,CAAC,WAAW,EAAE;YAC7C,WAAW,EAAE,GAAG;YAChB,UAAU,EAAE,EAAE;SACf,CAAC,CAAC;IACL,CAAC;CAAA","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { MsalPersistenceOptions } from \"./platforms\";\nimport { msalPersistencePlatforms } from \"./platforms\";\nimport type { IPersistence as Persistence } from \"@azure/msal-node-extensions\";\nimport { PersistenceCachePlugin } from \"@azure/msal-node-extensions\";\nimport type { ICachePlugin as CachePlugin } from \"@azure/msal-node\";\n\n/**\n * This is used to gain access to the underlying Persistence instance, which we use for testing\n *\n * @returns a raw persistence instance\n * @internal\n */\nexport async function createPersistence(options: MsalPersistenceOptions): Promise<Persistence> {\n const persistence = await msalPersistencePlatforms[process.platform]?.(options);\n\n if (persistence === undefined) {\n throw new Error(\"no persistence providers are available on this platform\");\n }\n\n return persistence;\n}\n\nexport async function createPersistenceCachePlugin(\n options?: MsalPersistenceOptions,\n): Promise<CachePlugin> {\n const persistence = await createPersistence(options ?? {});\n\n return new PersistenceCachePlugin(persistence, {\n retryNumber: 100,\n retryDelay: 50,\n });\n}\n"]}
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@azure/identity-cache-persistence",
3
- "version": "1.1.2-alpha.20241112.1",
3
+ "version": "1.1.2-alpha.20241113.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",
7
- "module": "dist-esm/identity-cache-persistence/src/index.js",
7
+ "module": "dist-esm/src/index.js",
8
8
  "types": "./types/identity-cache-persistence.d.ts",
9
9
  "scripts": {
10
10
  "build": "npm run clean && npm run extract-api && tsc -p . && dev-tool run bundle",
@@ -31,8 +31,7 @@
31
31
  },
32
32
  "files": [
33
33
  "dist/",
34
- "dist-esm/identity/src",
35
- "dist-esm/identity-cache-persistence/src",
34
+ "dist-esm/src",
36
35
  "types/identity-cache-persistence.d.ts",
37
36
  "README.md",
38
37
  "LICENSE"
@@ -1,257 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- import { __awaiter } from "tslib";
4
- import { ServiceClient } from "@azure/core-client";
5
- import { isNode } from "@azure/core-util";
6
- import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline";
7
- import { AuthenticationError, AuthenticationErrorName } from "../errors";
8
- import { getIdentityTokenEndpointSuffix } from "../util/identityTokenEndpoint";
9
- import { DefaultAuthorityHost, SDK_VERSION } from "../constants";
10
- import { tracingClient } from "../util/tracing";
11
- import { logger } from "../util/logging";
12
- import { parseExpirationTimestamp, parseRefreshTimestamp, } from "../credentials/managedIdentityCredential/utils";
13
- const noCorrelationId = "noCorrelationId";
14
- /**
15
- * @internal
16
- */
17
- export function getIdentityClientAuthorityHost(options) {
18
- // The authorityHost can come from options or from the AZURE_AUTHORITY_HOST environment variable.
19
- let authorityHost = options === null || options === void 0 ? void 0 : options.authorityHost;
20
- // The AZURE_AUTHORITY_HOST environment variable can only be provided in Node.js.
21
- if (isNode) {
22
- authorityHost = authorityHost !== null && authorityHost !== void 0 ? authorityHost : process.env.AZURE_AUTHORITY_HOST;
23
- }
24
- // If the authorityHost is not provided, we use the default one from the public cloud: https://login.microsoftonline.com
25
- return authorityHost !== null && authorityHost !== void 0 ? authorityHost : DefaultAuthorityHost;
26
- }
27
- /**
28
- * The network module used by the Identity credentials.
29
- *
30
- * It allows for credentials to abort any pending request independently of the MSAL flow,
31
- * by calling to the `abortRequests()` method.
32
- *
33
- */
34
- export class IdentityClient extends ServiceClient {
35
- constructor(options) {
36
- var _a, _b;
37
- const packageDetails = `azsdk-js-identity/${SDK_VERSION}`;
38
- const userAgentPrefix = ((_a = options === null || options === void 0 ? void 0 : options.userAgentOptions) === null || _a === void 0 ? void 0 : _a.userAgentPrefix)
39
- ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
40
- : `${packageDetails}`;
41
- const baseUri = getIdentityClientAuthorityHost(options);
42
- if (!baseUri.startsWith("https:")) {
43
- throw new Error("The authorityHost address must use the 'https' protocol.");
44
- }
45
- super(Object.assign(Object.assign({ requestContentType: "application/json; charset=utf-8", retryOptions: {
46
- maxRetries: 3,
47
- } }, options), { userAgentOptions: {
48
- userAgentPrefix,
49
- }, baseUri }));
50
- this.allowInsecureConnection = false;
51
- this.authorityHost = baseUri;
52
- this.abortControllers = new Map();
53
- this.allowLoggingAccountIdentifiers = (_b = options === null || options === void 0 ? void 0 : options.loggingOptions) === null || _b === void 0 ? void 0 : _b.allowLoggingAccountIdentifiers;
54
- // used for WorkloadIdentity
55
- this.tokenCredentialOptions = Object.assign({}, options);
56
- // used for ManagedIdentity
57
- if (options === null || options === void 0 ? void 0 : options.allowInsecureConnection) {
58
- this.allowInsecureConnection = options.allowInsecureConnection;
59
- }
60
- }
61
- sendTokenRequest(request) {
62
- return __awaiter(this, void 0, void 0, function* () {
63
- logger.info(`IdentityClient: sending token request to [${request.url}]`);
64
- const response = yield this.sendRequest(request);
65
- if (response.bodyAsText && (response.status === 200 || response.status === 201)) {
66
- const parsedBody = JSON.parse(response.bodyAsText);
67
- if (!parsedBody.access_token) {
68
- return null;
69
- }
70
- this.logIdentifiers(response);
71
- const token = {
72
- accessToken: {
73
- token: parsedBody.access_token,
74
- expiresOnTimestamp: parseExpirationTimestamp(parsedBody),
75
- refreshAfterTimestamp: parseRefreshTimestamp(parsedBody),
76
- tokenType: "Bearer",
77
- },
78
- refreshToken: parsedBody.refresh_token,
79
- };
80
- logger.info(`IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`);
81
- return token;
82
- }
83
- else {
84
- const error = new AuthenticationError(response.status, response.bodyAsText);
85
- logger.warning(`IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`);
86
- throw error;
87
- }
88
- });
89
- }
90
- refreshAccessToken(tenantId_1, clientId_1, scopes_1, refreshToken_1, clientSecret_1) {
91
- return __awaiter(this, arguments, void 0, function* (tenantId, clientId, scopes, refreshToken, clientSecret, options = {}) {
92
- if (refreshToken === undefined) {
93
- return null;
94
- }
95
- logger.info(`IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`);
96
- const refreshParams = {
97
- grant_type: "refresh_token",
98
- client_id: clientId,
99
- refresh_token: refreshToken,
100
- scope: scopes,
101
- };
102
- if (clientSecret !== undefined) {
103
- refreshParams.client_secret = clientSecret;
104
- }
105
- const query = new URLSearchParams(refreshParams);
106
- return tracingClient.withSpan("IdentityClient.refreshAccessToken", options, (updatedOptions) => __awaiter(this, void 0, void 0, function* () {
107
- try {
108
- const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);
109
- const request = createPipelineRequest({
110
- url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,
111
- method: "POST",
112
- body: query.toString(),
113
- abortSignal: options.abortSignal,
114
- headers: createHttpHeaders({
115
- Accept: "application/json",
116
- "Content-Type": "application/x-www-form-urlencoded",
117
- }),
118
- tracingOptions: updatedOptions.tracingOptions,
119
- });
120
- const response = yield this.sendTokenRequest(request);
121
- logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`);
122
- return response;
123
- }
124
- catch (err) {
125
- if (err.name === AuthenticationErrorName &&
126
- err.errorResponse.error === "interaction_required") {
127
- // It's likely that the refresh token has expired, so
128
- // return null so that the credential implementation will
129
- // initiate the authentication flow again.
130
- logger.info(`IdentityClient: interaction required for client ID: ${clientId}`);
131
- return null;
132
- }
133
- else {
134
- logger.warning(`IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`);
135
- throw err;
136
- }
137
- }
138
- }));
139
- });
140
- }
141
- // Here is a custom layer that allows us to abort requests that go through MSAL,
142
- // since MSAL doesn't allow us to pass options all the way through.
143
- generateAbortSignal(correlationId) {
144
- const controller = new AbortController();
145
- const controllers = this.abortControllers.get(correlationId) || [];
146
- controllers.push(controller);
147
- this.abortControllers.set(correlationId, controllers);
148
- const existingOnAbort = controller.signal.onabort;
149
- controller.signal.onabort = (...params) => {
150
- this.abortControllers.set(correlationId, undefined);
151
- if (existingOnAbort) {
152
- existingOnAbort.apply(controller.signal, params);
153
- }
154
- };
155
- return controller.signal;
156
- }
157
- abortRequests(correlationId) {
158
- const key = correlationId || noCorrelationId;
159
- const controllers = [
160
- ...(this.abortControllers.get(key) || []),
161
- // MSAL passes no correlation ID to the get requests...
162
- ...(this.abortControllers.get(noCorrelationId) || []),
163
- ];
164
- if (!controllers.length) {
165
- return;
166
- }
167
- for (const controller of controllers) {
168
- controller.abort();
169
- }
170
- this.abortControllers.set(key, undefined);
171
- }
172
- getCorrelationId(options) {
173
- var _a;
174
- const parameter = (_a = options === null || options === void 0 ? void 0 : options.body) === null || _a === void 0 ? void 0 : _a.split("&").map((part) => part.split("=")).find(([key]) => key === "client-request-id");
175
- return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId;
176
- }
177
- // The MSAL network module methods follow
178
- sendGetRequestAsync(url, options) {
179
- return __awaiter(this, void 0, void 0, function* () {
180
- const request = createPipelineRequest({
181
- url,
182
- method: "GET",
183
- body: options === null || options === void 0 ? void 0 : options.body,
184
- allowInsecureConnection: this.allowInsecureConnection,
185
- headers: createHttpHeaders(options === null || options === void 0 ? void 0 : options.headers),
186
- abortSignal: this.generateAbortSignal(noCorrelationId),
187
- });
188
- const response = yield this.sendRequest(request);
189
- this.logIdentifiers(response);
190
- return {
191
- body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,
192
- headers: response.headers.toJSON(),
193
- status: response.status,
194
- };
195
- });
196
- }
197
- sendPostRequestAsync(url, options) {
198
- return __awaiter(this, void 0, void 0, function* () {
199
- const request = createPipelineRequest({
200
- url,
201
- method: "POST",
202
- body: options === null || options === void 0 ? void 0 : options.body,
203
- headers: createHttpHeaders(options === null || options === void 0 ? void 0 : options.headers),
204
- allowInsecureConnection: this.allowInsecureConnection,
205
- // MSAL doesn't send the correlation ID on the get requests.
206
- abortSignal: this.generateAbortSignal(this.getCorrelationId(options)),
207
- });
208
- const response = yield this.sendRequest(request);
209
- this.logIdentifiers(response);
210
- return {
211
- body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,
212
- headers: response.headers.toJSON(),
213
- status: response.status,
214
- };
215
- });
216
- }
217
- /**
218
- *
219
- * @internal
220
- */
221
- getTokenCredentialOptions() {
222
- return this.tokenCredentialOptions;
223
- }
224
- /**
225
- * If allowLoggingAccountIdentifiers was set on the constructor options
226
- * we try to log the account identifiers by parsing the received access token.
227
- *
228
- * The account identifiers we try to log are:
229
- * - `appid`: The application or Client Identifier.
230
- * - `upn`: User Principal Name.
231
- * - It might not be available in some authentication scenarios.
232
- * - If it's not available, we put a placeholder: "No User Principal Name available".
233
- * - `tid`: Tenant Identifier.
234
- * - `oid`: Object Identifier of the authenticated user.
235
- */
236
- logIdentifiers(response) {
237
- if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) {
238
- return;
239
- }
240
- const unavailableUpn = "No User Principal Name available";
241
- try {
242
- const parsed = response.parsedBody || JSON.parse(response.bodyAsText);
243
- const accessToken = parsed.access_token;
244
- if (!accessToken) {
245
- // Without an access token allowLoggingAccountIdentifiers isn't useful.
246
- return;
247
- }
248
- const base64Metadata = accessToken.split(".")[1];
249
- const { appid, upn, tid, oid } = JSON.parse(Buffer.from(base64Metadata, "base64").toString("utf8"));
250
- logger.info(`[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${upn || unavailableUpn}. Object ID (user): ${oid}`);
251
- }
252
- catch (e) {
253
- logger.warning("allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:", e.message);
254
- }
255
- }
256
- }
257
- //# sourceMappingURL=identityClient.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"identityClient.js","sourceRoot":"","sources":["../../../../../identity/src/client/identityClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAIlC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,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IAAI,CAAC;YACH,MAAM,MAAM,GAAI,QAAgB,CAAC,UAAU,IAAI,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;YAC/E,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC;YACxC,IAAI,CAAC,WAAW,EAAE,CAAC;gBACjB,uEAAuE;gBACvE,OAAO;YACT,CAAC;YACD,MAAM,cAAc,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACjD,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,CACzC,MAAM,CAAC,IAAI,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CACvD,CAAC;YAEF,MAAM,CAAC,IAAI,CACT,sCAAsC,KAAK,gBAAgB,GAAG,0BAC5D,GAAG,IAAI,cACT,uBAAuB,GAAG,EAAE,CAC7B,CAAC;QACJ,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,MAAM,CAAC,OAAO,CACZ,6FAA6F,EAC7F,CAAC,CAAC,OAAO,CACV,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { INetworkModule, NetworkRequestOptions, NetworkResponse } from \"@azure/msal-node\";\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { ServiceClient } from \"@azure/core-client\";\nimport { isNode } from \"@azure/core-util\";\nimport type { PipelineRequest, PipelineResponse } from \"@azure/core-rest-pipeline\";\nimport { createHttpHeaders, createPipelineRequest } from \"@azure/core-rest-pipeline\";\nimport type { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AuthenticationError, AuthenticationErrorName } from \"../errors\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\nimport { DefaultAuthorityHost, SDK_VERSION } from \"../constants\";\nimport { tracingClient } from \"../util/tracing\";\nimport { logger } from \"../util/logging\";\nimport type { TokenCredentialOptions } from \"../tokenCredentialOptions\";\nimport type { TokenResponseParsedBody } from \"../credentials/managedIdentityCredential/utils\";\nimport {\n parseExpirationTimestamp,\n parseRefreshTimestamp,\n} from \"../credentials/managedIdentityCredential/utils\";\n\nconst noCorrelationId = \"noCorrelationId\";\n\n/**\n * An internal type used to communicate details of a token request's\n * response that should not be sent back as part of the access token.\n */\nexport interface TokenResponse {\n /**\n * The AccessToken to be returned from getToken.\n */\n accessToken: AccessToken;\n /**\n * The refresh token if the 'offline_access' scope was used.\n */\n refreshToken?: string;\n}\n\n/**\n * @internal\n */\nexport function getIdentityClientAuthorityHost(options?: TokenCredentialOptions): string {\n // The authorityHost can come from options or from the AZURE_AUTHORITY_HOST environment variable.\n let authorityHost = options?.authorityHost;\n\n // The AZURE_AUTHORITY_HOST environment variable can only be provided in Node.js.\n if (isNode) {\n authorityHost = authorityHost ?? process.env.AZURE_AUTHORITY_HOST;\n }\n\n // If the authorityHost is not provided, we use the default one from the public cloud: https://login.microsoftonline.com\n return authorityHost ?? DefaultAuthorityHost;\n}\n\n/**\n * The network module used by the Identity credentials.\n *\n * It allows for credentials to abort any pending request independently of the MSAL flow,\n * by calling to the `abortRequests()` method.\n *\n */\nexport class IdentityClient extends ServiceClient implements INetworkModule {\n public authorityHost: string;\n private allowLoggingAccountIdentifiers?: boolean;\n private abortControllers: Map<string, AbortController[] | undefined>;\n private allowInsecureConnection: boolean = false;\n // used for WorkloadIdentity\n private tokenCredentialOptions: TokenCredentialOptions;\n\n constructor(options?: TokenCredentialOptions) {\n const packageDetails = `azsdk-js-identity/${SDK_VERSION}`;\n const userAgentPrefix = options?.userAgentOptions?.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const baseUri = getIdentityClientAuthorityHost(options);\n if (!baseUri.startsWith(\"https:\")) {\n throw new Error(\"The authorityHost address must use the 'https' protocol.\");\n }\n\n super({\n requestContentType: \"application/json; charset=utf-8\",\n retryOptions: {\n maxRetries: 3,\n },\n ...options,\n userAgentOptions: {\n userAgentPrefix,\n },\n baseUri,\n });\n\n this.authorityHost = baseUri;\n this.abortControllers = new Map();\n this.allowLoggingAccountIdentifiers = options?.loggingOptions?.allowLoggingAccountIdentifiers;\n // used for WorkloadIdentity\n this.tokenCredentialOptions = { ...options };\n\n // used for ManagedIdentity\n if (options?.allowInsecureConnection) {\n this.allowInsecureConnection = options.allowInsecureConnection;\n }\n }\n\n async sendTokenRequest(request: PipelineRequest): Promise<TokenResponse | null> {\n logger.info(`IdentityClient: sending token request to [${request.url}]`);\n const response = await this.sendRequest(request);\n if (response.bodyAsText && (response.status === 200 || response.status === 201)) {\n const parsedBody: TokenResponseParsedBody = JSON.parse(response.bodyAsText);\n\n if (!parsedBody.access_token) {\n return null;\n }\n\n this.logIdentifiers(response);\n\n const token = {\n accessToken: {\n token: parsedBody.access_token,\n expiresOnTimestamp: parseExpirationTimestamp(parsedBody),\n refreshAfterTimestamp: parseRefreshTimestamp(parsedBody),\n tokenType: \"Bearer\",\n } as AccessToken,\n refreshToken: parsedBody.refresh_token,\n };\n\n logger.info(\n `IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`,\n );\n return token;\n } else {\n const error = new AuthenticationError(response.status, response.bodyAsText);\n logger.warning(\n `IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`,\n );\n throw error;\n }\n }\n\n async refreshAccessToken(\n tenantId: string,\n clientId: string,\n scopes: string,\n refreshToken: string | undefined,\n clientSecret: string | undefined,\n options: GetTokenOptions = {},\n ): Promise<TokenResponse | null> {\n if (refreshToken === undefined) {\n return null;\n }\n logger.info(\n `IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`,\n );\n\n const refreshParams = {\n grant_type: \"refresh_token\",\n client_id: clientId,\n refresh_token: refreshToken,\n scope: scopes,\n };\n\n if (clientSecret !== undefined) {\n (refreshParams as any).client_secret = clientSecret;\n }\n\n const query = new URLSearchParams(refreshParams);\n\n return tracingClient.withSpan(\n \"IdentityClient.refreshAccessToken\",\n options,\n async (updatedOptions) => {\n try {\n const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);\n const request = createPipelineRequest({\n url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,\n method: \"POST\",\n body: query.toString(),\n abortSignal: options.abortSignal,\n headers: createHttpHeaders({\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }),\n tracingOptions: updatedOptions.tracingOptions,\n });\n\n const response = await this.sendTokenRequest(request);\n logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`);\n return response;\n } catch (err: any) {\n if (\n err.name === AuthenticationErrorName &&\n err.errorResponse.error === \"interaction_required\"\n ) {\n // It's likely that the refresh token has expired, so\n // return null so that the credential implementation will\n // initiate the authentication flow again.\n logger.info(`IdentityClient: interaction required for client ID: ${clientId}`);\n return null;\n } else {\n logger.warning(\n `IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`,\n );\n throw err;\n }\n }\n },\n );\n }\n\n // Here is a custom layer that allows us to abort requests that go through MSAL,\n // since MSAL doesn't allow us to pass options all the way through.\n\n generateAbortSignal(correlationId: string): AbortSignalLike {\n const controller = new AbortController();\n const controllers = this.abortControllers.get(correlationId) || [];\n controllers.push(controller);\n this.abortControllers.set(correlationId, controllers);\n const existingOnAbort = controller.signal.onabort;\n controller.signal.onabort = (...params) => {\n this.abortControllers.set(correlationId, undefined);\n if (existingOnAbort) {\n existingOnAbort.apply(controller.signal, params);\n }\n };\n return controller.signal;\n }\n\n abortRequests(correlationId?: string): void {\n const key = correlationId || noCorrelationId;\n const controllers = [\n ...(this.abortControllers.get(key) || []),\n // MSAL passes no correlation ID to the get requests...\n ...(this.abortControllers.get(noCorrelationId) || []),\n ];\n if (!controllers.length) {\n return;\n }\n for (const controller of controllers) {\n controller.abort();\n }\n this.abortControllers.set(key, undefined);\n }\n\n getCorrelationId(options?: NetworkRequestOptions): string {\n const parameter = options?.body\n ?.split(\"&\")\n .map((part) => part.split(\"=\"))\n .find(([key]) => key === \"client-request-id\");\n return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId;\n }\n\n // The MSAL network module methods follow\n\n async sendGetRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions,\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"GET\",\n body: options?.body,\n allowInsecureConnection: this.allowInsecureConnection,\n headers: createHttpHeaders(options?.headers),\n abortSignal: this.generateAbortSignal(noCorrelationId),\n });\n\n const response = await this.sendRequest(request);\n\n this.logIdentifiers(response);\n\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n async sendPostRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions,\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"POST\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n allowInsecureConnection: this.allowInsecureConnection,\n // MSAL doesn't send the correlation ID on the get requests.\n abortSignal: this.generateAbortSignal(this.getCorrelationId(options)),\n });\n\n const response = await this.sendRequest(request);\n\n this.logIdentifiers(response);\n\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n /**\n *\n * @internal\n */\n getTokenCredentialOptions(): TokenCredentialOptions {\n return this.tokenCredentialOptions;\n }\n /**\n * If allowLoggingAccountIdentifiers was set on the constructor options\n * we try to log the account identifiers by parsing the received access token.\n *\n * The account identifiers we try to log are:\n * - `appid`: The application or Client Identifier.\n * - `upn`: User Principal Name.\n * - It might not be available in some authentication scenarios.\n * - If it's not available, we put a placeholder: \"No User Principal Name available\".\n * - `tid`: Tenant Identifier.\n * - `oid`: Object Identifier of the authenticated user.\n */\n private logIdentifiers(response: PipelineResponse): void {\n if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) {\n return;\n }\n const unavailableUpn = \"No User Principal Name available\";\n try {\n const parsed = (response as any).parsedBody || JSON.parse(response.bodyAsText);\n const accessToken = parsed.access_token;\n if (!accessToken) {\n // Without an access token allowLoggingAccountIdentifiers isn't useful.\n return;\n }\n const base64Metadata = accessToken.split(\".\")[1];\n const { appid, upn, tid, oid } = JSON.parse(\n Buffer.from(base64Metadata, \"base64\").toString(\"utf8\"),\n );\n\n logger.info(\n `[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${\n upn || unavailableUpn\n }. Object ID (user): ${oid}`,\n );\n } catch (e: any) {\n logger.warning(\n \"allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:\",\n e.message,\n );\n }\n }\n}\n"]}
@@ -1,70 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- /**
4
- * Current version of the `@azure/identity` package.
5
- */
6
- export const SDK_VERSION = `4.5.1`;
7
- /**
8
- * The default client ID for authentication
9
- * @internal
10
- */
11
- // TODO: temporary - this is the Azure CLI clientID - we'll replace it when
12
- // Developer Sign On application is available
13
- // https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/Constants.cs#L9
14
- export const DeveloperSignOnClientId = "04b07795-8ddb-461a-bbee-02f9e1bf7b46";
15
- /**
16
- * The default tenant for authentication
17
- * @internal
18
- */
19
- export const DefaultTenantId = "common";
20
- /**
21
- * A list of known Azure authority hosts
22
- */
23
- export var AzureAuthorityHosts;
24
- (function (AzureAuthorityHosts) {
25
- /**
26
- * China-based Azure Authority Host
27
- */
28
- AzureAuthorityHosts["AzureChina"] = "https://login.chinacloudapi.cn";
29
- /**
30
- * Germany-based Azure Authority Host
31
- *
32
- * @deprecated Microsoft Cloud Germany was closed on October 29th, 2021.
33
- *
34
- * */
35
- AzureAuthorityHosts["AzureGermany"] = "https://login.microsoftonline.de";
36
- /**
37
- * US Government Azure Authority Host
38
- */
39
- AzureAuthorityHosts["AzureGovernment"] = "https://login.microsoftonline.us";
40
- /**
41
- * Public Cloud Azure Authority Host
42
- */
43
- AzureAuthorityHosts["AzurePublicCloud"] = "https://login.microsoftonline.com";
44
- })(AzureAuthorityHosts || (AzureAuthorityHosts = {}));
45
- /**
46
- * @internal
47
- * The default authority host.
48
- */
49
- export const DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud;
50
- /**
51
- * @internal
52
- * Allow acquiring tokens for any tenant for multi-tentant auth.
53
- */
54
- export const ALL_TENANTS = ["*"];
55
- /**
56
- * @internal
57
- */
58
- export const CACHE_CAE_SUFFIX = "cae";
59
- /**
60
- * @internal
61
- */
62
- export const CACHE_NON_CAE_SUFFIX = "nocae";
63
- /**
64
- * @internal
65
- *
66
- * The default name for the cache persistence plugin.
67
- * Matches the constant defined in the cache persistence package.
68
- */
69
- export const DEFAULT_TOKEN_CACHE_NAME = "msal.cache";
70
- //# sourceMappingURL=constants.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../identity/src/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,CAAC;AAEnC;;;GAGG;AACH,2EAA2E;AAC3E,6CAA6C;AAC7C,uGAAuG;AACvG,MAAM,CAAC,MAAM,uBAAuB,GAAG,sCAAsC,CAAC;AAE9E;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAC;AAExC;;GAEG;AACH,MAAM,CAAN,IAAY,mBAoBX;AApBD,WAAY,mBAAmB;IAC7B;;OAEG;IACH,oEAA6C,CAAA;IAC7C;;;;;SAKK;IACL,wEAAiD,CAAA;IACjD;;OAEG;IACH,2EAAoD,CAAA;IACpD;;OAEG;IACH,6EAAsD,CAAA;AACxD,CAAC,EApBW,mBAAmB,KAAnB,mBAAmB,QAoB9B;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,mBAAmB,CAAC,gBAAgB,CAAC;AAEzE;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAa,CAAC,GAAG,CAAC,CAAC;AAE3C;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAEtC;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAC;AAE5C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,YAAY,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Current version of the `@azure/identity` package.\n */\nexport const SDK_VERSION = `4.5.1`;\n\n/**\n * The default client ID for authentication\n * @internal\n */\n// TODO: temporary - this is the Azure CLI clientID - we'll replace it when\n// Developer Sign On application is available\n// https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/Constants.cs#L9\nexport const DeveloperSignOnClientId = \"04b07795-8ddb-461a-bbee-02f9e1bf7b46\";\n\n/**\n * The default tenant for authentication\n * @internal\n */\nexport const DefaultTenantId = \"common\";\n\n/**\n * A list of known Azure authority hosts\n */\nexport enum AzureAuthorityHosts {\n /**\n * China-based Azure Authority Host\n */\n AzureChina = \"https://login.chinacloudapi.cn\",\n /**\n * Germany-based Azure Authority Host\n *\n * @deprecated Microsoft Cloud Germany was closed on October 29th, 2021.\n *\n * */\n AzureGermany = \"https://login.microsoftonline.de\",\n /**\n * US Government Azure Authority Host\n */\n AzureGovernment = \"https://login.microsoftonline.us\",\n /**\n * Public Cloud Azure Authority Host\n */\n AzurePublicCloud = \"https://login.microsoftonline.com\",\n}\n\n/**\n * @internal\n * The default authority host.\n */\nexport const DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud;\n\n/**\n * @internal\n * Allow acquiring tokens for any tenant for multi-tentant auth.\n */\nexport const ALL_TENANTS: string[] = [\"*\"];\n\n/**\n * @internal\n */\nexport const CACHE_CAE_SUFFIX = \"cae\";\n\n/**\n * @internal\n */\nexport const CACHE_NON_CAE_SUFFIX = \"nocae\";\n\n/**\n * @internal\n *\n * The default name for the cache persistence plugin.\n * Matches the constant defined in the cache persistence package.\n */\nexport const DEFAULT_TOKEN_CACHE_NAME = \"msal.cache\";\n"]}
@@ -1,4 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- export {};
4
- //# sourceMappingURL=authorityValidationOptions.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"authorityValidationOptions.js","sourceRoot":"","sources":["../../../../../identity/src/credentials/authorityValidationOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Provides options to configure how the Identity library\n * does authority validation during authentication requests\n * to Microsoft Entra ID.\n */\nexport interface AuthorityValidationOptions {\n /**\n * The field determines whether instance discovery is performed when attempting to authenticate.\n * Setting this to `true` will completely disable both instance discovery and authority validation.\n * As a result, it's crucial to ensure that the configured authority host is valid and trustworthy.\n * This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in private clouds or Azure Stack.\n * The process of instance discovery entails retrieving authority metadata from https://login.microsoft.com/ to validate the authority.\n */\n disableInstanceDiscovery?: boolean;\n}\n"]}
@@ -1,63 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- import { __awaiter } from "tslib";
4
- import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
5
- import { checkTenantId } from "../util/tenantIdUtils";
6
- import { credentialLogger } from "../util/logging";
7
- import { ensureScopes } from "../util/scopeUtils";
8
- import { tracingClient } from "../util/tracing";
9
- import { createMsalClient } from "../msal/nodeFlows/msalClient";
10
- const logger = credentialLogger("AuthorizationCodeCredential");
11
- /**
12
- * Enables authentication to Microsoft Entra ID using an authorization code
13
- * that was obtained through the authorization code flow, described in more detail
14
- * in the Microsoft Entra ID documentation:
15
- *
16
- * https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow
17
- */
18
- export class AuthorizationCodeCredential {
19
- /**
20
- * @hidden
21
- * @internal
22
- */
23
- constructor(tenantId, clientId, clientSecretOrAuthorizationCode, authorizationCodeOrRedirectUri, redirectUriOrOptions, options) {
24
- checkTenantId(logger, tenantId);
25
- this.clientSecret = clientSecretOrAuthorizationCode;
26
- if (typeof redirectUriOrOptions === "string") {
27
- // the clientId+clientSecret constructor
28
- this.authorizationCode = authorizationCodeOrRedirectUri;
29
- this.redirectUri = redirectUriOrOptions;
30
- // in this case, options are good as they come
31
- }
32
- else {
33
- // clientId only
34
- this.authorizationCode = clientSecretOrAuthorizationCode;
35
- this.redirectUri = authorizationCodeOrRedirectUri;
36
- this.clientSecret = undefined;
37
- options = redirectUriOrOptions;
38
- }
39
- // TODO: Validate tenant if provided
40
- this.tenantId = tenantId;
41
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
42
- this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options !== null && options !== void 0 ? options : {} }));
43
- }
44
- /**
45
- * Authenticates with Microsoft Entra ID and returns an access token if successful.
46
- * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
47
- *
48
- * @param scopes - The list of scopes for which the token will have access.
49
- * @param options - The options used to configure any requests this
50
- * TokenCredential implementation might make.
51
- */
52
- getToken(scopes_1) {
53
- return __awaiter(this, arguments, void 0, function* (scopes, options = {}) {
54
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, (newOptions) => __awaiter(this, void 0, void 0, function* () {
55
- const tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds);
56
- newOptions.tenantId = tenantId;
57
- const arrayScopes = ensureScopes(scopes);
58
- return this.msalClient.getTokenByAuthorizationCode(arrayScopes, this.redirectUri, this.authorizationCode, this.clientSecret, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication }));
59
- }));
60
- });
61
- }
62
- }
63
- //# sourceMappingURL=authorizationCodeCredential.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"authorizationCodeCredential.js","sourceRoot":"","sources":["../../../../../identity/src/credentials/authorizationCodeCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAGlC,OAAO,EACL,yBAAyB,EACzB,mCAAmC,GACpC,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAEhE,MAAM,MAAM,GAAG,gBAAgB,CAAC,6BAA6B,CAAC,CAAC;AAE/D;;;;;;GAMG;AACH,MAAM,OAAO,2BAA2B;IAmEtC;;;OAGG;IACH,YACE,QAA2B,EAC3B,QAAgB,EAChB,+BAAuC,EACvC,8BAAsC,EACtC,oBAA6E,EAC7E,OAA4C;QAE5C,aAAa,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAChC,IAAI,CAAC,YAAY,GAAG,+BAA+B,CAAC;QAEpD,IAAI,OAAO,oBAAoB,KAAK,QAAQ,EAAE,CAAC;YAC7C,wCAAwC;YACxC,IAAI,CAAC,iBAAiB,GAAG,8BAA8B,CAAC;YACxD,IAAI,CAAC,WAAW,GAAG,oBAAoB,CAAC;YACxC,8CAA8C;QAChD,CAAC;aAAM,CAAC;YACN,gBAAgB;YAChB,IAAI,CAAC,iBAAiB,GAAG,+BAA+B,CAAC;YACzD,IAAI,CAAC,WAAW,GAAG,8BAAwC,CAAC;YAC5D,IAAI,CAAC,YAAY,GAAG,SAAS,CAAC;YAC9B,OAAO,GAAG,oBAA0D,CAAC;QACvE,CAAC;QAED,oCAAoC;QACpC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,4BAA4B,GAAG,mCAAmC,CACrE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,0BAA0B,CACpC,CAAC;QAEF,IAAI,CAAC,UAAU,GAAG,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,kCAChD,OAAO,KACV,MAAM,EACN,sBAAsB,EAAE,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,IACrC,CAAC;IACL,CAAC;IAED;;;;;;;OAOG;IACG,QAAQ;6DAAC,MAAyB,EAAE,UAA2B,EAAE;YACrE,OAAO,aAAa,CAAC,QAAQ,CAC3B,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,WAAW,EACnC,OAAO,EACP,CAAO,UAAU,EAAE,EAAE;gBACnB,MAAM,QAAQ,GAAG,yBAAyB,CACxC,IAAI,CAAC,QAAQ,EACb,UAAU,EACV,IAAI,CAAC,4BAA4B,CAClC,CAAC;gBACF,UAAU,CAAC,QAAQ,GAAG,QAAQ,CAAC;gBAE/B,MAAM,WAAW,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;gBACzC,OAAO,IAAI,CAAC,UAAU,CAAC,2BAA2B,CAChD,WAAW,EACX,IAAI,CAAC,WAAW,EAChB,IAAI,CAAC,iBAAiB,EACtB,IAAI,CAAC,YAAY,kCAEZ,UAAU,KACb,8BAA8B,EAAE,IAAI,CAAC,8BAA8B,IAEtE,CAAC;YACJ,CAAC,CAAA,CACF,CAAC;QACJ,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport type { AuthorizationCodeCredentialOptions } from \"./authorizationCodeCredentialOptions\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\nimport type { MsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { createMsalClient } from \"../msal/nodeFlows/msalClient\";\n\nconst logger = credentialLogger(\"AuthorizationCodeCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID using an authorization code\n * that was obtained through the authorization code flow, described in more detail\n * in the Microsoft Entra ID documentation:\n *\n * https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow\n */\nexport class AuthorizationCodeCredential implements TokenCredential {\n private msalClient: MsalClient;\n private disableAutomaticAuthentication?: boolean;\n private authorizationCode: string;\n private redirectUri: string;\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private clientSecret?: string;\n\n /**\n * Creates an instance of AuthorizationCodeCredential with the details needed\n * to request an access token using an authentication that was obtained\n * from Microsoft Entra ID.\n *\n * It is currently necessary for the user of this credential to initiate\n * the authorization code flow to obtain an authorization code to be used\n * with this credential. A full example of this flow is provided here:\n *\n * https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/v2/manual/authorizationCodeSample.ts\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID or name.\n * 'common' may be used when dealing with multi-tenant scenarios.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param clientSecret - A client secret that was generated for the App Registration\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 options - Options for configuring the client which makes the access token request.\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n clientSecret: string,\n authorizationCode: string,\n redirectUri: string,\n options?: AuthorizationCodeCredentialOptions,\n );\n /**\n * Creates an instance of AuthorizationCodeCredential with the details needed\n * to request an access token using an authentication that was obtained\n * from Microsoft Entra ID.\n *\n * It is currently necessary for the user of this credential to initiate\n * the authorization code flow to obtain an authorization code to be used\n * with this credential. A full example of this flow is provided here:\n *\n * https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/v2/manual/authorizationCodeSample.ts\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID or name.\n * 'common' may be used when dealing with multi-tenant scenarios.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\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 options - Options for configuring the client which makes the access token request.\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n authorizationCode: string,\n redirectUri: string,\n options?: AuthorizationCodeCredentialOptions,\n );\n /**\n * @hidden\n * @internal\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n clientSecretOrAuthorizationCode: string,\n authorizationCodeOrRedirectUri: string,\n redirectUriOrOptions: string | AuthorizationCodeCredentialOptions | undefined,\n options?: AuthorizationCodeCredentialOptions,\n ) {\n checkTenantId(logger, tenantId);\n this.clientSecret = clientSecretOrAuthorizationCode;\n\n if (typeof redirectUriOrOptions === \"string\") {\n // the clientId+clientSecret constructor\n this.authorizationCode = authorizationCodeOrRedirectUri;\n this.redirectUri = redirectUriOrOptions;\n // in this case, options are good as they come\n } else {\n // clientId only\n this.authorizationCode = clientSecretOrAuthorizationCode;\n this.redirectUri = authorizationCodeOrRedirectUri as string;\n this.clientSecret = undefined;\n options = redirectUriOrOptions as AuthorizationCodeCredentialOptions;\n }\n\n // TODO: Validate tenant if provided\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: options ?? {},\n });\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n );\n newOptions.tenantId = tenantId;\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalClient.getTokenByAuthorizationCode(\n arrayScopes,\n this.redirectUri,\n this.authorizationCode,\n this.clientSecret,\n {\n ...newOptions,\n disableAutomaticAuthentication: this.disableAutomaticAuthentication,\n },\n );\n },\n );\n }\n}\n"]}
@@ -1,4 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- export {};
4
- //# sourceMappingURL=authorizationCodeCredentialOptions.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"authorizationCodeCredentialOptions.js","sourceRoot":"","sources":["../../../../../identity/src/credentials/authorizationCodeCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AuthorityValidationOptions } from \"./authorityValidationOptions\";\nimport type { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Options for the {@link AuthorizationCodeCredential}\n */\nexport interface AuthorizationCodeCredentialOptions\n extends MultiTenantTokenCredentialOptions,\n AuthorityValidationOptions {}\n"]}