@azure/msal-node-extensions 1.1.0 → 1.2.0

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 (120) hide show
  1. package/bin/arm64/dpapi.node +0 -0
  2. package/bin/ia32/dpapi.node +0 -0
  3. package/bin/x64/dpapi.node +0 -0
  4. package/dist/Dpapi.mjs +1 -1
  5. package/dist/broker/NativeBrokerPlugin.d.ts +2 -2
  6. package/dist/broker/NativeBrokerPlugin.mjs +19 -10
  7. package/dist/broker/NativeBrokerPlugin.mjs.map +1 -1
  8. package/dist/error/NativeAuthError.d.ts +1 -1
  9. package/dist/error/NativeAuthError.mjs +2 -2
  10. package/dist/error/PersistenceError.mjs +1 -1
  11. package/dist/index.d.ts +12 -12
  12. package/dist/index.mjs +1 -1
  13. package/dist/lib/msal-common/dist/constants/AADServerParamKeys.mjs +7 -0
  14. package/dist/lib/msal-common/dist/constants/AADServerParamKeys.mjs.map +1 -0
  15. package/dist/lib/msal-common/dist/error/AuthError.mjs +27 -0
  16. package/dist/lib/msal-common/dist/error/AuthError.mjs.map +1 -0
  17. package/dist/lib/msal-common/dist/error/ClientAuthError.mjs +81 -0
  18. package/dist/lib/msal-common/dist/error/ClientAuthError.mjs.map +1 -0
  19. package/dist/lib/msal-common/dist/error/ClientAuthErrorCodes.mjs +54 -0
  20. package/dist/lib/msal-common/dist/error/ClientAuthErrorCodes.mjs.map +1 -0
  21. package/dist/lib/msal-common/dist/error/ClientConfigurationError.mjs +51 -0
  22. package/dist/lib/msal-common/dist/error/ClientConfigurationError.mjs.map +1 -0
  23. package/dist/lib/msal-common/dist/error/ClientConfigurationErrorCodes.mjs +32 -0
  24. package/dist/lib/msal-common/dist/error/ClientConfigurationErrorCodes.mjs.map +1 -0
  25. package/dist/lib/msal-common/dist/error/InteractionRequiredAuthError.mjs +24 -0
  26. package/dist/lib/msal-common/dist/error/InteractionRequiredAuthError.mjs.map +1 -0
  27. package/dist/lib/msal-common/dist/error/ServerError.mjs +25 -0
  28. package/dist/lib/msal-common/dist/error/ServerError.mjs.map +1 -0
  29. package/dist/lib/msal-common/dist/logger/Logger.mjs +197 -0
  30. package/dist/lib/msal-common/dist/logger/Logger.mjs.map +1 -0
  31. package/dist/lib/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs +270 -0
  32. package/dist/lib/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs.map +1 -0
  33. package/dist/lib/msal-common/dist/utils/Constants.mjs +124 -0
  34. package/dist/lib/msal-common/dist/utils/Constants.mjs.map +1 -0
  35. package/dist/lock/CrossPlatformLock.d.ts +2 -2
  36. package/dist/lock/CrossPlatformLock.mjs +1 -1
  37. package/dist/packageMetadata.d.ts +1 -1
  38. package/dist/packageMetadata.mjs +2 -2
  39. package/dist/persistence/BasePersistence.d.ts +1 -1
  40. package/dist/persistence/BasePersistence.mjs +1 -1
  41. package/dist/persistence/DataProtectionScope.mjs +1 -1
  42. package/dist/persistence/FilePersistence.d.ts +3 -3
  43. package/dist/persistence/FilePersistence.mjs +2 -2
  44. package/dist/persistence/FilePersistenceWithDataProtection.d.ts +4 -4
  45. package/dist/persistence/FilePersistenceWithDataProtection.mjs +1 -1
  46. package/dist/persistence/IPersistence.d.ts +1 -1
  47. package/dist/persistence/IPersistenceConfiguration.d.ts +2 -2
  48. package/dist/persistence/KeychainPersistence.d.ts +3 -3
  49. package/dist/persistence/KeychainPersistence.mjs +1 -1
  50. package/dist/persistence/LibSecretPersistence.d.ts +3 -3
  51. package/dist/persistence/LibSecretPersistence.mjs +1 -1
  52. package/dist/persistence/PersistenceCachePlugin.d.ts +3 -3
  53. package/dist/persistence/PersistenceCachePlugin.mjs +1 -1
  54. package/dist/persistence/PersistenceCachePlugin.mjs.map +1 -1
  55. package/dist/persistence/PersistenceCreator.d.ts +2 -2
  56. package/dist/persistence/PersistenceCreator.mjs +1 -1
  57. package/dist/utils/Constants.mjs +1 -1
  58. package/dist/utils/Environment.mjs +1 -1
  59. package/dist/utils/TypeGuards.d.ts +1 -1
  60. package/dist/utils/TypeGuards.mjs +1 -1
  61. package/lib/msal-node-extensions.cjs +2230 -0
  62. package/lib/msal-node-extensions.cjs.map +1 -0
  63. package/lib/package.json +1 -0
  64. package/lib/types/Dpapi.d.ts +6 -0
  65. package/lib/types/broker/NativeBrokerPlugin.d.ts +20 -0
  66. package/lib/types/error/NativeAuthError.d.ts +6 -0
  67. package/lib/types/error/PersistenceError.d.ts +57 -0
  68. package/lib/types/index.d.ts +12 -0
  69. package/lib/types/lock/CrossPlatformLock.d.ts +24 -0
  70. package/lib/types/lock/CrossPlatformLockOptions.d.ts +10 -0
  71. package/lib/types/packageMetadata.d.ts +2 -0
  72. package/lib/types/persistence/BasePersistence.d.ts +5 -0
  73. package/{dist/persistence/DataProtectionScope.cjs → lib/types/persistence/DataProtectionScope.d.ts} +5 -15
  74. package/lib/types/persistence/FilePersistence.d.ts +29 -0
  75. package/lib/types/persistence/FilePersistenceWithDataProtection.d.ts +24 -0
  76. package/lib/types/persistence/IPersistence.d.ts +11 -0
  77. package/lib/types/persistence/IPersistenceConfiguration.d.ts +10 -0
  78. package/lib/types/persistence/KeychainPersistence.d.ts +23 -0
  79. package/lib/types/persistence/LibSecretPersistence.d.ts +24 -0
  80. package/lib/types/persistence/PersistenceCachePlugin.d.ts +38 -0
  81. package/lib/types/persistence/PersistenceCreator.d.ts +5 -0
  82. package/lib/types/utils/Constants.d.ts +54 -0
  83. package/lib/types/utils/Environment.d.ts +16 -0
  84. package/lib/types/utils/TypeGuards.d.ts +5 -0
  85. package/package.json +16 -9
  86. package/dist/Dpapi.cjs +0 -31
  87. package/dist/Dpapi.cjs.map +0 -1
  88. package/dist/broker/NativeBrokerPlugin.cjs +0 -426
  89. package/dist/broker/NativeBrokerPlugin.cjs.map +0 -1
  90. package/dist/error/NativeAuthError.cjs +0 -22
  91. package/dist/error/NativeAuthError.cjs.map +0 -1
  92. package/dist/error/PersistenceError.cjs +0 -93
  93. package/dist/error/PersistenceError.cjs.map +0 -1
  94. package/dist/index.cjs +0 -26
  95. package/dist/index.cjs.map +0 -1
  96. package/dist/lock/CrossPlatformLock.cjs +0 -97
  97. package/dist/lock/CrossPlatformLock.cjs.map +0 -1
  98. package/dist/packageMetadata.cjs +0 -11
  99. package/dist/packageMetadata.cjs.map +0 -1
  100. package/dist/persistence/BasePersistence.cjs +0 -38
  101. package/dist/persistence/BasePersistence.cjs.map +0 -1
  102. package/dist/persistence/DataProtectionScope.cjs.map +0 -1
  103. package/dist/persistence/FilePersistence.cjs +0 -175
  104. package/dist/persistence/FilePersistence.cjs.map +0 -1
  105. package/dist/persistence/FilePersistenceWithDataProtection.cjs +0 -92
  106. package/dist/persistence/FilePersistenceWithDataProtection.cjs.map +0 -1
  107. package/dist/persistence/KeychainPersistence.cjs +0 -92
  108. package/dist/persistence/KeychainPersistence.cjs.map +0 -1
  109. package/dist/persistence/LibSecretPersistence.cjs +0 -93
  110. package/dist/persistence/LibSecretPersistence.cjs.map +0 -1
  111. package/dist/persistence/PersistenceCachePlugin.cjs +0 -101
  112. package/dist/persistence/PersistenceCachePlugin.cjs.map +0 -1
  113. package/dist/persistence/PersistenceCreator.cjs +0 -70
  114. package/dist/persistence/PersistenceCreator.cjs.map +0 -1
  115. package/dist/utils/Constants.cjs +0 -66
  116. package/dist/utils/Constants.cjs.map +0 -1
  117. package/dist/utils/Environment.cjs +0 -96
  118. package/dist/utils/Environment.cjs.map +0 -1
  119. package/dist/utils/TypeGuards.cjs +0 -17
  120. package/dist/utils/TypeGuards.cjs.map +0 -1
@@ -0,0 +1,2230 @@
1
+ /*! @azure/msal-node-extensions v1.2.0 2024-09-20 */
2
+ 'use strict';
3
+ 'use strict';
4
+
5
+ var fs = require('fs');
6
+ var process$1 = require('process');
7
+ var path = require('path');
8
+ var module$1 = require('module');
9
+ var keytar = require('keytar');
10
+ var msalNodeRuntime = require('@azure/msal-node-runtime');
11
+
12
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
13
+ /*
14
+ * Copyright (c) Microsoft Corporation. All rights reserved.
15
+ * Licensed under the MIT License.
16
+ */
17
+ const Constants$1 = {
18
+ /**
19
+ * An existing file was the target of an operation that required that the target not exist
20
+ */
21
+ EEXIST_ERROR: "EEXIST",
22
+ /**
23
+ * No such file or directory: Commonly raised by fs operations to indicate that a component
24
+ * of the specified pathname does not exist. No entity (file or directory) could be found
25
+ * by the given path
26
+ */
27
+ ENOENT_ERROR: "ENOENT",
28
+ /**
29
+ * Operation not permitted. An attempt was made to perform an operation that requires
30
+ * elevated privileges.
31
+ */
32
+ EPERM_ERROR: "EPERM",
33
+ /**
34
+ * Default service name for using MSAL Keytar
35
+ */
36
+ DEFAULT_SERVICE_NAME: "msal-node-extensions",
37
+ /**
38
+ * Test data used to verify underlying persistence mechanism
39
+ */
40
+ PERSISTENCE_TEST_DATA: "Dummy data to verify underlying persistence mechanism",
41
+ /**
42
+ * This is the value of a the guid if the process is being ran by the root user
43
+ */
44
+ LINUX_ROOT_USER_GUID: 0,
45
+ /**
46
+ * List of environment variables
47
+ */
48
+ ENVIRONMENT: {
49
+ HOME: "HOME",
50
+ LOGNAME: "LOGNAME",
51
+ USER: "USER",
52
+ LNAME: "LNAME",
53
+ USERNAME: "USERNAME",
54
+ PLATFORM: "platform",
55
+ LOCAL_APPLICATION_DATA: "LOCALAPPDATA",
56
+ },
57
+ // Name of the default cache file
58
+ DEFAULT_CACHE_FILE_NAME: "cache.json",
59
+ };
60
+ const Platform = {
61
+ WINDOWS: "win32",
62
+ LINUX: "linux",
63
+ MACOS: "darwin",
64
+ };
65
+ const ErrorCodes = {
66
+ INTERATION_REQUIRED_ERROR_CODE: "interaction_required",
67
+ SERVER_UNAVAILABLE: "server_unavailable",
68
+ UNKNOWN: "unknown_error",
69
+ };
70
+
71
+ /*
72
+ * Copyright (c) Microsoft Corporation. All rights reserved.
73
+ * Licensed under the MIT License.
74
+ */
75
+ /**
76
+ * Error thrown when trying to write MSAL cache to persistence.
77
+ */
78
+ class PersistenceError extends Error {
79
+ constructor(errorCode, errorMessage) {
80
+ const errorString = errorMessage
81
+ ? `${errorCode}: ${errorMessage}`
82
+ : errorCode;
83
+ super(errorString);
84
+ Object.setPrototypeOf(this, PersistenceError.prototype);
85
+ this.errorCode = errorCode;
86
+ this.errorMessage = errorMessage;
87
+ this.name = "PersistenceError";
88
+ }
89
+ /**
90
+ * Error thrown when trying to access the file system.
91
+ */
92
+ static createFileSystemError(errorCode, errorMessage) {
93
+ return new PersistenceError(errorCode, errorMessage);
94
+ }
95
+ /**
96
+ * Error thrown when trying to write, load, or delete data from secret service on linux.
97
+ * Libsecret is used to access secret service.
98
+ */
99
+ static createLibSecretError(errorMessage) {
100
+ return new PersistenceError("GnomeKeyringError", errorMessage);
101
+ }
102
+ /**
103
+ * Error thrown when trying to write, load, or delete data from keychain on macOs.
104
+ */
105
+ static createKeychainPersistenceError(errorMessage) {
106
+ return new PersistenceError("KeychainError", errorMessage);
107
+ }
108
+ /**
109
+ * Error thrown when trying to encrypt or decrypt data using DPAPI on Windows.
110
+ */
111
+ static createFilePersistenceWithDPAPIError(errorMessage) {
112
+ return new PersistenceError("DPAPIEncryptedFileError", errorMessage);
113
+ }
114
+ /**
115
+ * Error thrown when using the cross platform lock.
116
+ */
117
+ static createCrossPlatformLockError(errorMessage) {
118
+ return new PersistenceError("CrossPlatformLockError", errorMessage);
119
+ }
120
+ /**
121
+ * Throw cache persistence error
122
+ *
123
+ * @param errorMessage string
124
+ * @returns PersistenceError
125
+ */
126
+ static createCachePersistenceError(errorMessage) {
127
+ return new PersistenceError("CachePersistenceError", errorMessage);
128
+ }
129
+ /**
130
+ * Throw unsupported error
131
+ *
132
+ * @param errorMessage string
133
+ * @returns PersistenceError
134
+ */
135
+ static createNotSupportedError(errorMessage) {
136
+ return new PersistenceError("NotSupportedError", errorMessage);
137
+ }
138
+ /**
139
+ * Throw persistence not verified error
140
+ *
141
+ * @param errorMessage string
142
+ * @returns PersistenceError
143
+ */
144
+ static createPersistenceNotVerifiedError(errorMessage) {
145
+ return new PersistenceError("PersistenceNotVerifiedError", errorMessage);
146
+ }
147
+ /**
148
+ * Throw persistence creation validation error
149
+ *
150
+ * @param errorMessage string
151
+ * @returns PersistenceError
152
+ */
153
+ static createPersistenceNotValidatedError(errorMessage) {
154
+ return new PersistenceError("PersistenceNotValidatedError", errorMessage);
155
+ }
156
+ }
157
+
158
+ /*
159
+ * Copyright (c) Microsoft Corporation. All rights reserved.
160
+ * Licensed under the MIT License.
161
+ */
162
+ /**
163
+ * Returns whether or not the given object is a Node.js error
164
+ */
165
+ const isNodeError = (error) => {
166
+ return !!error && typeof error === "object" && error.hasOwnProperty("code");
167
+ };
168
+
169
+ /*
170
+ * Copyright (c) Microsoft Corporation. All rights reserved.
171
+ * Licensed under the MIT License.
172
+ */
173
+ /**
174
+ * Cross-process lock that works on all platforms.
175
+ */
176
+ class CrossPlatformLock {
177
+ constructor(lockFilePath, logger, lockOptions) {
178
+ this.lockFilePath = lockFilePath;
179
+ this.retryNumber = lockOptions ? lockOptions.retryNumber : 500;
180
+ this.retryDelay = lockOptions ? lockOptions.retryDelay : 100;
181
+ this.logger = logger;
182
+ }
183
+ /**
184
+ * Locks cache from read or writes by creating file with same path and name as
185
+ * cache file but with .lockfile extension. If another process has already created
186
+ * the lockfile, will back off and retry based on configuration settings set by CrossPlatformLockOptions
187
+ */
188
+ async lock() {
189
+ for (let tryCount = 0; tryCount < this.retryNumber; tryCount++) {
190
+ try {
191
+ this.logger.info(`Pid ${process$1.pid} trying to acquire lock`);
192
+ this.lockFileHandle = await fs.promises.open(this.lockFilePath, "wx+");
193
+ this.logger.info(`Pid ${process$1.pid} acquired lock`);
194
+ await this.lockFileHandle.write(process$1.pid.toString());
195
+ return;
196
+ }
197
+ catch (err) {
198
+ if (isNodeError(err)) {
199
+ if (err.code === Constants$1.EEXIST_ERROR ||
200
+ err.code === Constants$1.EPERM_ERROR) {
201
+ this.logger.info(err.message);
202
+ await this.sleep(this.retryDelay);
203
+ }
204
+ else {
205
+ this.logger.error(`${process$1.pid} was not able to acquire lock. Ran into error: ${err.message}`);
206
+ throw PersistenceError.createCrossPlatformLockError(err.message);
207
+ }
208
+ }
209
+ else {
210
+ throw err;
211
+ }
212
+ }
213
+ }
214
+ this.logger.error(`${process$1.pid} was not able to acquire lock. Exceeded amount of retries set in the options`);
215
+ throw PersistenceError.createCrossPlatformLockError("Not able to acquire lock. Exceeded amount of retries set in options");
216
+ }
217
+ /**
218
+ * unlocks cache file by deleting .lockfile.
219
+ */
220
+ async unlock() {
221
+ try {
222
+ if (this.lockFileHandle) {
223
+ // if we have a file handle to the .lockfile, delete lock file
224
+ await fs.promises.unlink(this.lockFilePath);
225
+ await this.lockFileHandle.close();
226
+ this.logger.info("lockfile deleted");
227
+ }
228
+ else {
229
+ this.logger.warning("lockfile handle does not exist, so lockfile could not be deleted");
230
+ }
231
+ }
232
+ catch (err) {
233
+ if (isNodeError(err)) {
234
+ if (err.code === Constants$1.ENOENT_ERROR) {
235
+ this.logger.info("Tried to unlock but lockfile does not exist");
236
+ }
237
+ else {
238
+ this.logger.error(`${process$1.pid} was not able to release lock. Ran into error: ${err.message}`);
239
+ throw PersistenceError.createCrossPlatformLockError(err.message);
240
+ }
241
+ }
242
+ else {
243
+ throw err;
244
+ }
245
+ }
246
+ }
247
+ sleep(ms) {
248
+ return new Promise((resolve) => {
249
+ setTimeout(resolve, ms);
250
+ });
251
+ }
252
+ }
253
+
254
+ /*
255
+ * Copyright (c) Microsoft Corporation. All rights reserved.
256
+ * Licensed under the MIT License.
257
+ */
258
+ /**
259
+ * MSAL cache plugin which enables callers to write the MSAL cache to disk on Windows,
260
+ * macOs, and Linux.
261
+ *
262
+ * - Persistence can be one of:
263
+ * - FilePersistence: Writes and reads from an unencrypted file. Can be used on Windows,
264
+ * macOs, or Linux.
265
+ * - FilePersistenceWithDataProtection: Used on Windows, writes and reads from file encrypted
266
+ * with windows dpapi-addon.
267
+ * - KeychainPersistence: Used on macOs, writes and reads from keychain.
268
+ * - LibSecretPersistence: Used on linux, writes and reads from secret service API. Requires
269
+ * libsecret be installed.
270
+ */
271
+ class PersistenceCachePlugin {
272
+ constructor(persistence, lockOptions) {
273
+ this.persistence = persistence;
274
+ // initialize logger
275
+ this.logger = persistence.getLogger();
276
+ // create file lock
277
+ this.lockFilePath = `${this.persistence.getFilePath()}.lockfile`;
278
+ this.crossPlatformLock = new CrossPlatformLock(this.lockFilePath, this.logger, lockOptions);
279
+ // initialize default values
280
+ this.lastSync = 0;
281
+ this.currentCache = null;
282
+ }
283
+ /**
284
+ * Reads from storage and saves an in-memory copy. If persistence has not been updated
285
+ * since last time data was read, in memory copy is used.
286
+ *
287
+ * If cacheContext.cacheHasChanged === true, then file lock is created and not deleted until
288
+ * afterCacheAccess() is called, to prevent the cache file from changing in between
289
+ * beforeCacheAccess() and afterCacheAccess().
290
+ */
291
+ async beforeCacheAccess(cacheContext) {
292
+ this.logger.info("Executing before cache access");
293
+ const reloadNecessary = await this.persistence.reloadNecessary(this.lastSync);
294
+ if (!reloadNecessary && this.currentCache !== null) {
295
+ if (cacheContext.cacheHasChanged) {
296
+ this.logger.verbose("Cache context has changed");
297
+ await this.crossPlatformLock.lock();
298
+ }
299
+ return;
300
+ }
301
+ try {
302
+ this.logger.info(`Reload necessary. Last sync time: ${this.lastSync}`);
303
+ await this.crossPlatformLock.lock();
304
+ this.currentCache = await this.persistence.load();
305
+ this.lastSync = new Date().getTime();
306
+ if (this.currentCache) {
307
+ cacheContext.tokenCache.deserialize(this.currentCache);
308
+ }
309
+ else {
310
+ this.logger.info("Cache empty.");
311
+ }
312
+ this.logger.info(`Last sync time updated to: ${this.lastSync}`);
313
+ }
314
+ finally {
315
+ if (!cacheContext.cacheHasChanged) {
316
+ await this.crossPlatformLock.unlock();
317
+ this.logger.info(`Pid ${process$1.pid} released lock`);
318
+ }
319
+ else {
320
+ this.logger.info(`Pid ${process$1.pid} beforeCacheAccess did not release lock`);
321
+ }
322
+ }
323
+ }
324
+ /**
325
+ * Writes to storage if MSAL in memory copy of cache has been changed.
326
+ */
327
+ async afterCacheAccess(cacheContext) {
328
+ this.logger.info("Executing after cache access");
329
+ try {
330
+ if (cacheContext.cacheHasChanged) {
331
+ this.logger.info("Msal in-memory cache has changed. Writing changes to persistence");
332
+ this.currentCache = cacheContext.tokenCache.serialize();
333
+ await this.persistence.save(this.currentCache);
334
+ }
335
+ else {
336
+ this.logger.info("Msal in-memory cache has not changed. Did not write to persistence");
337
+ }
338
+ }
339
+ finally {
340
+ await this.crossPlatformLock.unlock();
341
+ this.logger.info(`Pid ${process$1.pid} afterCacheAccess released lock`);
342
+ }
343
+ }
344
+ }
345
+
346
+ /*! @azure/msal-common v14.15.0 2024-09-20 */
347
+ /*
348
+ * Copyright (c) Microsoft Corporation. All rights reserved.
349
+ * Licensed under the MIT License.
350
+ */
351
+ const Constants = {
352
+ LIBRARY_NAME: "MSAL.JS",
353
+ SKU: "msal.js.common",
354
+ // Prefix for all library cache entries
355
+ CACHE_PREFIX: "msal",
356
+ // default authority
357
+ DEFAULT_AUTHORITY: "https://login.microsoftonline.com/common/",
358
+ DEFAULT_AUTHORITY_HOST: "login.microsoftonline.com",
359
+ DEFAULT_COMMON_TENANT: "common",
360
+ // ADFS String
361
+ ADFS: "adfs",
362
+ DSTS: "dstsv2",
363
+ // Default AAD Instance Discovery Endpoint
364
+ AAD_INSTANCE_DISCOVERY_ENDPT: "https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=",
365
+ // CIAM URL
366
+ CIAM_AUTH_URL: ".ciamlogin.com",
367
+ AAD_TENANT_DOMAIN_SUFFIX: ".onmicrosoft.com",
368
+ // Resource delimiter - used for certain cache entries
369
+ RESOURCE_DELIM: "|",
370
+ // Placeholder for non-existent account ids/objects
371
+ NO_ACCOUNT: "NO_ACCOUNT",
372
+ // Claims
373
+ CLAIMS: "claims",
374
+ // Consumer UTID
375
+ CONSUMER_UTID: "9188040d-6c67-4c5b-b112-36a304b66dad",
376
+ // Default scopes
377
+ OPENID_SCOPE: "openid",
378
+ PROFILE_SCOPE: "profile",
379
+ OFFLINE_ACCESS_SCOPE: "offline_access",
380
+ EMAIL_SCOPE: "email",
381
+ // Default response type for authorization code flow
382
+ CODE_RESPONSE_TYPE: "code",
383
+ CODE_GRANT_TYPE: "authorization_code",
384
+ RT_GRANT_TYPE: "refresh_token",
385
+ FRAGMENT_RESPONSE_MODE: "fragment",
386
+ S256_CODE_CHALLENGE_METHOD: "S256",
387
+ URL_FORM_CONTENT_TYPE: "application/x-www-form-urlencoded;charset=utf-8",
388
+ AUTHORIZATION_PENDING: "authorization_pending",
389
+ NOT_DEFINED: "not_defined",
390
+ EMPTY_STRING: "",
391
+ NOT_APPLICABLE: "N/A",
392
+ NOT_AVAILABLE: "Not Available",
393
+ FORWARD_SLASH: "/",
394
+ IMDS_ENDPOINT: "http://169.254.169.254/metadata/instance/compute/location",
395
+ IMDS_VERSION: "2020-06-01",
396
+ IMDS_TIMEOUT: 2000,
397
+ AZURE_REGION_AUTO_DISCOVER_FLAG: "TryAutoDetect",
398
+ REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX: "login.microsoft.com",
399
+ KNOWN_PUBLIC_CLOUDS: [
400
+ "login.microsoftonline.com",
401
+ "login.windows.net",
402
+ "login.microsoft.com",
403
+ "sts.windows.net",
404
+ ],
405
+ TOKEN_RESPONSE_TYPE: "token",
406
+ ID_TOKEN_RESPONSE_TYPE: "id_token",
407
+ SHR_NONCE_VALIDITY: 240,
408
+ INVALID_INSTANCE: "invalid_instance",
409
+ };
410
+ /**
411
+ * we considered making this "enum" in the request instead of string, however it looks like the allowed list of
412
+ * prompt values kept changing over past couple of years. There are some undocumented prompt values for some
413
+ * internal partners too, hence the choice of generic "string" type instead of the "enum"
414
+ */
415
+ const PromptValue = {
416
+ LOGIN: "login",
417
+ SELECT_ACCOUNT: "select_account",
418
+ CONSENT: "consent",
419
+ NONE: "none",
420
+ CREATE: "create",
421
+ NO_SESSION: "no_session",
422
+ };
423
+ /**
424
+ * Separators used in cache
425
+ */
426
+ const Separators = {
427
+ CACHE_KEY_SEPARATOR: "-",
428
+ CLIENT_INFO_SEPARATOR: ".",
429
+ };
430
+ const SERVER_TELEM_CONSTANTS = {
431
+ SCHEMA_VERSION: 5,
432
+ MAX_CUR_HEADER_BYTES: 80,
433
+ MAX_LAST_HEADER_BYTES: 330,
434
+ MAX_CACHED_ERRORS: 50,
435
+ CACHE_KEY: "server-telemetry",
436
+ CATEGORY_SEPARATOR: "|",
437
+ VALUE_SEPARATOR: ",",
438
+ OVERFLOW_TRUE: "1",
439
+ OVERFLOW_FALSE: "0",
440
+ UNKNOWN_ERROR: "unknown_error",
441
+ };
442
+ /**
443
+ * Type of the authentication request
444
+ */
445
+ const AuthenticationScheme = {
446
+ BEARER: "Bearer",
447
+ POP: "pop",
448
+ SSH: "ssh-cert",
449
+ };
450
+ /**
451
+ * Specifies the reason for fetching the access token from the identity provider
452
+ */
453
+ const CacheOutcome = {
454
+ // When a token is found in the cache or the cache is not supposed to be hit when making the request
455
+ NOT_APPLICABLE: "0",
456
+ // When the token request goes to the identity provider because force_refresh was set to true. Also occurs if claims were requested
457
+ FORCE_REFRESH_OR_CLAIMS: "1",
458
+ // When the token request goes to the identity provider because no cached access token exists
459
+ NO_CACHED_ACCESS_TOKEN: "2",
460
+ // When the token request goes to the identity provider because cached access token expired
461
+ CACHED_ACCESS_TOKEN_EXPIRED: "3",
462
+ // When the token request goes to the identity provider because refresh_in was used and the existing token needs to be refreshed
463
+ PROACTIVELY_REFRESHED: "4",
464
+ };
465
+
466
+ /*! @azure/msal-common v14.15.0 2024-09-20 */
467
+ /**
468
+ * General error class thrown by the MSAL.js library.
469
+ */
470
+ class AuthError extends Error {
471
+ constructor(errorCode, errorMessage, suberror) {
472
+ const errorString = errorMessage
473
+ ? `${errorCode}: ${errorMessage}`
474
+ : errorCode;
475
+ super(errorString);
476
+ Object.setPrototypeOf(this, AuthError.prototype);
477
+ this.errorCode = errorCode || Constants.EMPTY_STRING;
478
+ this.errorMessage = errorMessage || Constants.EMPTY_STRING;
479
+ this.subError = suberror || Constants.EMPTY_STRING;
480
+ this.name = "AuthError";
481
+ }
482
+ setCorrelationId(correlationId) {
483
+ this.correlationId = correlationId;
484
+ }
485
+ }
486
+
487
+ /*! @azure/msal-common v14.15.0 2024-09-20 */
488
+ /*
489
+ * Copyright (c) Microsoft Corporation. All rights reserved.
490
+ * Licensed under the MIT License.
491
+ */
492
+ const clientInfoDecodingError = "client_info_decoding_error";
493
+ const clientInfoEmptyError = "client_info_empty_error";
494
+ const tokenParsingError = "token_parsing_error";
495
+ const nullOrEmptyToken = "null_or_empty_token";
496
+ const endpointResolutionError = "endpoints_resolution_error";
497
+ const networkError = "network_error";
498
+ const openIdConfigError = "openid_config_error";
499
+ const hashNotDeserialized = "hash_not_deserialized";
500
+ const invalidState = "invalid_state";
501
+ const stateMismatch = "state_mismatch";
502
+ const stateNotFound = "state_not_found";
503
+ const nonceMismatch = "nonce_mismatch";
504
+ const authTimeNotFound = "auth_time_not_found";
505
+ const maxAgeTranspired = "max_age_transpired";
506
+ const multipleMatchingTokens = "multiple_matching_tokens";
507
+ const multipleMatchingAccounts = "multiple_matching_accounts";
508
+ const multipleMatchingAppMetadata = "multiple_matching_appMetadata";
509
+ const requestCannotBeMade = "request_cannot_be_made";
510
+ const cannotRemoveEmptyScope = "cannot_remove_empty_scope";
511
+ const cannotAppendScopeSet = "cannot_append_scopeset";
512
+ const emptyInputScopeSet = "empty_input_scopeset";
513
+ const deviceCodePollingCancelled = "device_code_polling_cancelled";
514
+ const deviceCodeExpired = "device_code_expired";
515
+ const deviceCodeUnknownError = "device_code_unknown_error";
516
+ const noAccountInSilentRequest = "no_account_in_silent_request";
517
+ const invalidCacheRecord = "invalid_cache_record";
518
+ const invalidCacheEnvironment = "invalid_cache_environment";
519
+ const noAccountFound = "no_account_found";
520
+ const noCryptoObject = "no_crypto_object";
521
+ const unexpectedCredentialType = "unexpected_credential_type";
522
+ const invalidAssertion = "invalid_assertion";
523
+ const invalidClientCredential = "invalid_client_credential";
524
+ const tokenRefreshRequired = "token_refresh_required";
525
+ const userTimeoutReached = "user_timeout_reached";
526
+ const tokenClaimsCnfRequiredForSignedJwt = "token_claims_cnf_required_for_signedjwt";
527
+ const authorizationCodeMissingFromServerResponse = "authorization_code_missing_from_server_response";
528
+ const bindingKeyNotRemoved = "binding_key_not_removed";
529
+ const endSessionEndpointNotSupported = "end_session_endpoint_not_supported";
530
+ const keyIdMissing = "key_id_missing";
531
+ const noNetworkConnectivity = "no_network_connectivity";
532
+ const userCanceled = "user_canceled";
533
+ const missingTenantIdError = "missing_tenant_id_error";
534
+ const methodNotImplemented = "method_not_implemented";
535
+ const nestedAppAuthBridgeDisabled = "nested_app_auth_bridge_disabled";
536
+
537
+ /*! @azure/msal-common v14.15.0 2024-09-20 */
538
+
539
+ /*
540
+ * Copyright (c) Microsoft Corporation. All rights reserved.
541
+ * Licensed under the MIT License.
542
+ */
543
+ /**
544
+ * ClientAuthErrorMessage class containing string constants used by error codes and messages.
545
+ */
546
+ const ClientAuthErrorMessages = {
547
+ [clientInfoDecodingError]: "The client info could not be parsed/decoded correctly",
548
+ [clientInfoEmptyError]: "The client info was empty",
549
+ [tokenParsingError]: "Token cannot be parsed",
550
+ [nullOrEmptyToken]: "The token is null or empty",
551
+ [endpointResolutionError]: "Endpoints cannot be resolved",
552
+ [networkError]: "Network request failed",
553
+ [openIdConfigError]: "Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints.",
554
+ [hashNotDeserialized]: "The hash parameters could not be deserialized",
555
+ [invalidState]: "State was not the expected format",
556
+ [stateMismatch]: "State mismatch error",
557
+ [stateNotFound]: "State not found",
558
+ [nonceMismatch]: "Nonce mismatch error",
559
+ [authTimeNotFound]: "Max Age was requested and the ID token is missing the auth_time variable." +
560
+ " auth_time is an optional claim and is not enabled by default - it must be enabled." +
561
+ " See https://aka.ms/msaljs/optional-claims for more information.",
562
+ [maxAgeTranspired]: "Max Age is set to 0, or too much time has elapsed since the last end-user authentication.",
563
+ [multipleMatchingTokens]: "The cache contains multiple tokens satisfying the requirements. " +
564
+ "Call AcquireToken again providing more requirements such as authority or account.",
565
+ [multipleMatchingAccounts]: "The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account",
566
+ [multipleMatchingAppMetadata]: "The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata",
567
+ [requestCannotBeMade]: "Token request cannot be made without authorization code or refresh token.",
568
+ [cannotRemoveEmptyScope]: "Cannot remove null or empty scope from ScopeSet",
569
+ [cannotAppendScopeSet]: "Cannot append ScopeSet",
570
+ [emptyInputScopeSet]: "Empty input ScopeSet cannot be processed",
571
+ [deviceCodePollingCancelled]: "Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true.",
572
+ [deviceCodeExpired]: "Device code is expired.",
573
+ [deviceCodeUnknownError]: "Device code stopped polling for unknown reasons.",
574
+ [noAccountInSilentRequest]: "Please pass an account object, silent flow is not supported without account information",
575
+ [invalidCacheRecord]: "Cache record object was null or undefined.",
576
+ [invalidCacheEnvironment]: "Invalid environment when attempting to create cache entry",
577
+ [noAccountFound]: "No account found in cache for given key.",
578
+ [noCryptoObject]: "No crypto object detected.",
579
+ [unexpectedCredentialType]: "Unexpected credential type.",
580
+ [invalidAssertion]: "Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515",
581
+ [invalidClientCredential]: "Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential",
582
+ [tokenRefreshRequired]: "Cannot return token from cache because it must be refreshed. This may be due to one of the following reasons: forceRefresh parameter is set to true, claims have been requested, there is no cached access token or it is expired.",
583
+ [userTimeoutReached]: "User defined timeout for device code polling reached",
584
+ [tokenClaimsCnfRequiredForSignedJwt]: "Cannot generate a POP jwt if the token_claims are not populated",
585
+ [authorizationCodeMissingFromServerResponse]: "Server response does not contain an authorization code to proceed",
586
+ [bindingKeyNotRemoved]: "Could not remove the credential's binding key from storage.",
587
+ [endSessionEndpointNotSupported]: "The provided authority does not support logout",
588
+ [keyIdMissing]: "A keyId value is missing from the requested bound token's cache record and is required to match the token to it's stored binding key.",
589
+ [noNetworkConnectivity]: "No network connectivity. Check your internet connection.",
590
+ [userCanceled]: "User cancelled the flow.",
591
+ [missingTenantIdError]: "A tenant id - not common, organizations, or consumers - must be specified when using the client_credentials flow.",
592
+ [methodNotImplemented]: "This method has not been implemented",
593
+ [nestedAppAuthBridgeDisabled]: "The nested app auth bridge is disabled",
594
+ };
595
+ /**
596
+ * Error thrown when there is an error in the client code running on the browser.
597
+ */
598
+ class ClientAuthError extends AuthError {
599
+ constructor(errorCode, additionalMessage) {
600
+ super(errorCode, additionalMessage
601
+ ? `${ClientAuthErrorMessages[errorCode]}: ${additionalMessage}`
602
+ : ClientAuthErrorMessages[errorCode]);
603
+ this.name = "ClientAuthError";
604
+ Object.setPrototypeOf(this, ClientAuthError.prototype);
605
+ }
606
+ }
607
+ function createClientAuthError(errorCode, additionalMessage) {
608
+ return new ClientAuthError(errorCode, additionalMessage);
609
+ }
610
+
611
+ /*! @azure/msal-common v14.15.0 2024-09-20 */
612
+
613
+ /*
614
+ * Copyright (c) Microsoft Corporation. All rights reserved.
615
+ * Licensed under the MIT License.
616
+ */
617
+ /**
618
+ * Log message level.
619
+ */
620
+ var LogLevel;
621
+ (function (LogLevel) {
622
+ LogLevel[LogLevel["Error"] = 0] = "Error";
623
+ LogLevel[LogLevel["Warning"] = 1] = "Warning";
624
+ LogLevel[LogLevel["Info"] = 2] = "Info";
625
+ LogLevel[LogLevel["Verbose"] = 3] = "Verbose";
626
+ LogLevel[LogLevel["Trace"] = 4] = "Trace";
627
+ })(LogLevel || (LogLevel = {}));
628
+ /**
629
+ * Class which facilitates logging of messages to a specific place.
630
+ */
631
+ class Logger {
632
+ constructor(loggerOptions, packageName, packageVersion) {
633
+ // Current log level, defaults to info.
634
+ this.level = LogLevel.Info;
635
+ const defaultLoggerCallback = () => {
636
+ return;
637
+ };
638
+ const setLoggerOptions = loggerOptions || Logger.createDefaultLoggerOptions();
639
+ this.localCallback =
640
+ setLoggerOptions.loggerCallback || defaultLoggerCallback;
641
+ this.piiLoggingEnabled = setLoggerOptions.piiLoggingEnabled || false;
642
+ this.level =
643
+ typeof setLoggerOptions.logLevel === "number"
644
+ ? setLoggerOptions.logLevel
645
+ : LogLevel.Info;
646
+ this.correlationId =
647
+ setLoggerOptions.correlationId || Constants.EMPTY_STRING;
648
+ this.packageName = packageName || Constants.EMPTY_STRING;
649
+ this.packageVersion = packageVersion || Constants.EMPTY_STRING;
650
+ }
651
+ static createDefaultLoggerOptions() {
652
+ return {
653
+ loggerCallback: () => {
654
+ // allow users to not set loggerCallback
655
+ },
656
+ piiLoggingEnabled: false,
657
+ logLevel: LogLevel.Info,
658
+ };
659
+ }
660
+ /**
661
+ * Create new Logger with existing configurations.
662
+ */
663
+ clone(packageName, packageVersion, correlationId) {
664
+ return new Logger({
665
+ loggerCallback: this.localCallback,
666
+ piiLoggingEnabled: this.piiLoggingEnabled,
667
+ logLevel: this.level,
668
+ correlationId: correlationId || this.correlationId,
669
+ }, packageName, packageVersion);
670
+ }
671
+ /**
672
+ * Log message with required options.
673
+ */
674
+ logMessage(logMessage, options) {
675
+ if (options.logLevel > this.level ||
676
+ (!this.piiLoggingEnabled && options.containsPii)) {
677
+ return;
678
+ }
679
+ const timestamp = new Date().toUTCString();
680
+ // Add correlationId to logs if set, correlationId provided on log messages take precedence
681
+ const logHeader = `[${timestamp}] : [${options.correlationId || this.correlationId || ""}]`;
682
+ const log = `${logHeader} : ${this.packageName}@${this.packageVersion} : ${LogLevel[options.logLevel]} - ${logMessage}`;
683
+ // debug(`msal:${LogLevel[options.logLevel]}${options.containsPii ? "-Pii": Constants.EMPTY_STRING}${options.context ? `:${options.context}` : Constants.EMPTY_STRING}`)(logMessage);
684
+ this.executeCallback(options.logLevel, log, options.containsPii || false);
685
+ }
686
+ /**
687
+ * Execute callback with message.
688
+ */
689
+ executeCallback(level, message, containsPii) {
690
+ if (this.localCallback) {
691
+ this.localCallback(level, message, containsPii);
692
+ }
693
+ }
694
+ /**
695
+ * Logs error messages.
696
+ */
697
+ error(message, correlationId) {
698
+ this.logMessage(message, {
699
+ logLevel: LogLevel.Error,
700
+ containsPii: false,
701
+ correlationId: correlationId || Constants.EMPTY_STRING,
702
+ });
703
+ }
704
+ /**
705
+ * Logs error messages with PII.
706
+ */
707
+ errorPii(message, correlationId) {
708
+ this.logMessage(message, {
709
+ logLevel: LogLevel.Error,
710
+ containsPii: true,
711
+ correlationId: correlationId || Constants.EMPTY_STRING,
712
+ });
713
+ }
714
+ /**
715
+ * Logs warning messages.
716
+ */
717
+ warning(message, correlationId) {
718
+ this.logMessage(message, {
719
+ logLevel: LogLevel.Warning,
720
+ containsPii: false,
721
+ correlationId: correlationId || Constants.EMPTY_STRING,
722
+ });
723
+ }
724
+ /**
725
+ * Logs warning messages with PII.
726
+ */
727
+ warningPii(message, correlationId) {
728
+ this.logMessage(message, {
729
+ logLevel: LogLevel.Warning,
730
+ containsPii: true,
731
+ correlationId: correlationId || Constants.EMPTY_STRING,
732
+ });
733
+ }
734
+ /**
735
+ * Logs info messages.
736
+ */
737
+ info(message, correlationId) {
738
+ this.logMessage(message, {
739
+ logLevel: LogLevel.Info,
740
+ containsPii: false,
741
+ correlationId: correlationId || Constants.EMPTY_STRING,
742
+ });
743
+ }
744
+ /**
745
+ * Logs info messages with PII.
746
+ */
747
+ infoPii(message, correlationId) {
748
+ this.logMessage(message, {
749
+ logLevel: LogLevel.Info,
750
+ containsPii: true,
751
+ correlationId: correlationId || Constants.EMPTY_STRING,
752
+ });
753
+ }
754
+ /**
755
+ * Logs verbose messages.
756
+ */
757
+ verbose(message, correlationId) {
758
+ this.logMessage(message, {
759
+ logLevel: LogLevel.Verbose,
760
+ containsPii: false,
761
+ correlationId: correlationId || Constants.EMPTY_STRING,
762
+ });
763
+ }
764
+ /**
765
+ * Logs verbose messages with PII.
766
+ */
767
+ verbosePii(message, correlationId) {
768
+ this.logMessage(message, {
769
+ logLevel: LogLevel.Verbose,
770
+ containsPii: true,
771
+ correlationId: correlationId || Constants.EMPTY_STRING,
772
+ });
773
+ }
774
+ /**
775
+ * Logs trace messages.
776
+ */
777
+ trace(message, correlationId) {
778
+ this.logMessage(message, {
779
+ logLevel: LogLevel.Trace,
780
+ containsPii: false,
781
+ correlationId: correlationId || Constants.EMPTY_STRING,
782
+ });
783
+ }
784
+ /**
785
+ * Logs trace messages with PII.
786
+ */
787
+ tracePii(message, correlationId) {
788
+ this.logMessage(message, {
789
+ logLevel: LogLevel.Trace,
790
+ containsPii: true,
791
+ correlationId: correlationId || Constants.EMPTY_STRING,
792
+ });
793
+ }
794
+ /**
795
+ * Returns whether PII Logging is enabled or not.
796
+ */
797
+ isPiiLoggingEnabled() {
798
+ return this.piiLoggingEnabled || false;
799
+ }
800
+ }
801
+
802
+ /*! @azure/msal-common v14.15.0 2024-09-20 */
803
+ /*
804
+ * Copyright (c) Microsoft Corporation. All rights reserved.
805
+ * Licensed under the MIT License.
806
+ */
807
+ const redirectUriEmpty = "redirect_uri_empty";
808
+ const claimsRequestParsingError = "claims_request_parsing_error";
809
+ const authorityUriInsecure = "authority_uri_insecure";
810
+ const urlParseError = "url_parse_error";
811
+ const urlEmptyError = "empty_url_error";
812
+ const emptyInputScopesError = "empty_input_scopes_error";
813
+ const invalidPromptValue = "invalid_prompt_value";
814
+ const invalidClaims = "invalid_claims";
815
+ const tokenRequestEmpty = "token_request_empty";
816
+ const logoutRequestEmpty = "logout_request_empty";
817
+ const invalidCodeChallengeMethod = "invalid_code_challenge_method";
818
+ const pkceParamsMissing = "pkce_params_missing";
819
+ const invalidCloudDiscoveryMetadata = "invalid_cloud_discovery_metadata";
820
+ const invalidAuthorityMetadata = "invalid_authority_metadata";
821
+ const untrustedAuthority = "untrusted_authority";
822
+ const missingSshJwk = "missing_ssh_jwk";
823
+ const missingSshKid = "missing_ssh_kid";
824
+ const missingNonceAuthenticationHeader = "missing_nonce_authentication_header";
825
+ const invalidAuthenticationHeader = "invalid_authentication_header";
826
+ const cannotSetOIDCOptions = "cannot_set_OIDCOptions";
827
+ const cannotAllowNativeBroker = "cannot_allow_native_broker";
828
+ const authorityMismatch = "authority_mismatch";
829
+
830
+ /*! @azure/msal-common v14.15.0 2024-09-20 */
831
+
832
+ /*
833
+ * Copyright (c) Microsoft Corporation. All rights reserved.
834
+ * Licensed under the MIT License.
835
+ */
836
+ const ClientConfigurationErrorMessages = {
837
+ [redirectUriEmpty]: "A redirect URI is required for all calls, and none has been set.",
838
+ [claimsRequestParsingError]: "Could not parse the given claims request object.",
839
+ [authorityUriInsecure]: "Authority URIs must use https. Please see here for valid authority configuration options: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications#configuration-options",
840
+ [urlParseError]: "URL could not be parsed into appropriate segments.",
841
+ [urlEmptyError]: "URL was empty or null.",
842
+ [emptyInputScopesError]: "Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token.",
843
+ [invalidPromptValue]: "Please see here for valid configuration options: https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal_common.html#commonauthorizationurlrequest",
844
+ [invalidClaims]: "Given claims parameter must be a stringified JSON object.",
845
+ [tokenRequestEmpty]: "Token request was empty and not found in cache.",
846
+ [logoutRequestEmpty]: "The logout request was null or undefined.",
847
+ [invalidCodeChallengeMethod]: 'code_challenge_method passed is invalid. Valid values are "plain" and "S256".',
848
+ [pkceParamsMissing]: "Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request",
849
+ [invalidCloudDiscoveryMetadata]: "Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields",
850
+ [invalidAuthorityMetadata]: "Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields.",
851
+ [untrustedAuthority]: "The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.",
852
+ [missingSshJwk]: "Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme.",
853
+ [missingSshKid]: "Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme.",
854
+ [missingNonceAuthenticationHeader]: "Unable to find an authentication header containing server nonce. Either the Authentication-Info or WWW-Authenticate headers must be present in order to obtain a server nonce.",
855
+ [invalidAuthenticationHeader]: "Invalid authentication header provided",
856
+ [cannotSetOIDCOptions]: "Cannot set OIDCOptions parameter. Please change the protocol mode to OIDC or use a non-Microsoft authority.",
857
+ [cannotAllowNativeBroker]: "Cannot set allowNativeBroker parameter to true when not in AAD protocol mode.",
858
+ [authorityMismatch]: "Authority mismatch error. Authority provided in login request or PublicClientApplication config does not match the environment of the provided account. Please use a matching account or make an interactive request to login to this authority.",
859
+ };
860
+ /**
861
+ * Error thrown when there is an error in configuration of the MSAL.js library.
862
+ */
863
+ class ClientConfigurationError extends AuthError {
864
+ constructor(errorCode) {
865
+ super(errorCode, ClientConfigurationErrorMessages[errorCode]);
866
+ this.name = "ClientConfigurationError";
867
+ Object.setPrototypeOf(this, ClientConfigurationError.prototype);
868
+ }
869
+ }
870
+ function createClientConfigurationError(errorCode) {
871
+ return new ClientConfigurationError(errorCode);
872
+ }
873
+
874
+ /*! @azure/msal-common v14.15.0 2024-09-20 */
875
+
876
+ /*
877
+ * Copyright (c) Microsoft Corporation. All rights reserved.
878
+ * Licensed under the MIT License.
879
+ */
880
+ /**
881
+ * Error thrown when there is an error with the server code, for example, unavailability.
882
+ */
883
+ class ServerError extends AuthError {
884
+ constructor(errorCode, errorMessage, subError, errorNo, status) {
885
+ super(errorCode, errorMessage, subError);
886
+ this.name = "ServerError";
887
+ this.errorNo = errorNo;
888
+ this.status = status;
889
+ Object.setPrototypeOf(this, ServerError.prototype);
890
+ }
891
+ }
892
+
893
+ /*! @azure/msal-common v14.15.0 2024-09-20 */
894
+ const X_CLIENT_EXTRA_SKU = "x-client-xtra-sku";
895
+
896
+ /*! @azure/msal-common v14.15.0 2024-09-20 */
897
+ /**
898
+ * Error thrown when user interaction is required.
899
+ */
900
+ class InteractionRequiredAuthError extends AuthError {
901
+ constructor(errorCode, errorMessage, subError, timestamp, traceId, correlationId, claims, errorNo) {
902
+ super(errorCode, errorMessage, subError);
903
+ Object.setPrototypeOf(this, InteractionRequiredAuthError.prototype);
904
+ this.timestamp = timestamp || Constants.EMPTY_STRING;
905
+ this.traceId = traceId || Constants.EMPTY_STRING;
906
+ this.correlationId = correlationId || Constants.EMPTY_STRING;
907
+ this.claims = claims || Constants.EMPTY_STRING;
908
+ this.name = "InteractionRequiredAuthError";
909
+ this.errorNo = errorNo;
910
+ }
911
+ }
912
+
913
+ /*! @azure/msal-common v14.15.0 2024-09-20 */
914
+
915
+ /*
916
+ * Copyright (c) Microsoft Corporation. All rights reserved.
917
+ * Licensed under the MIT License.
918
+ */
919
+ const skuGroupSeparator = ",";
920
+ const skuValueSeparator = "|";
921
+ function makeExtraSkuString(params) {
922
+ const { skus, libraryName, libraryVersion, extensionName, extensionVersion, } = params;
923
+ const skuMap = new Map([
924
+ [0, [libraryName, libraryVersion]],
925
+ [2, [extensionName, extensionVersion]],
926
+ ]);
927
+ let skuArr = [];
928
+ if (skus?.length) {
929
+ skuArr = skus.split(skuGroupSeparator);
930
+ // Ignore invalid input sku param
931
+ if (skuArr.length < 4) {
932
+ return skus;
933
+ }
934
+ }
935
+ else {
936
+ skuArr = Array.from({ length: 4 }, () => skuValueSeparator);
937
+ }
938
+ skuMap.forEach((value, key) => {
939
+ if (value.length === 2 && value[0]?.length && value[1]?.length) {
940
+ setSku({
941
+ skuArr,
942
+ index: key,
943
+ skuName: value[0],
944
+ skuVersion: value[1],
945
+ });
946
+ }
947
+ });
948
+ return skuArr.join(skuGroupSeparator);
949
+ }
950
+ function setSku(params) {
951
+ const { skuArr, index, skuName, skuVersion } = params;
952
+ if (index >= skuArr.length) {
953
+ return;
954
+ }
955
+ skuArr[index] = [skuName, skuVersion].join(skuValueSeparator);
956
+ }
957
+ /** @internal */
958
+ class ServerTelemetryManager {
959
+ constructor(telemetryRequest, cacheManager) {
960
+ this.cacheOutcome = CacheOutcome.NOT_APPLICABLE;
961
+ this.cacheManager = cacheManager;
962
+ this.apiId = telemetryRequest.apiId;
963
+ this.correlationId = telemetryRequest.correlationId;
964
+ this.wrapperSKU = telemetryRequest.wrapperSKU || Constants.EMPTY_STRING;
965
+ this.wrapperVer = telemetryRequest.wrapperVer || Constants.EMPTY_STRING;
966
+ this.telemetryCacheKey =
967
+ SERVER_TELEM_CONSTANTS.CACHE_KEY +
968
+ Separators.CACHE_KEY_SEPARATOR +
969
+ telemetryRequest.clientId;
970
+ }
971
+ /**
972
+ * API to add MSER Telemetry to request
973
+ */
974
+ generateCurrentRequestHeaderValue() {
975
+ const request = `${this.apiId}${SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR}${this.cacheOutcome}`;
976
+ const platformFieldsArr = [this.wrapperSKU, this.wrapperVer];
977
+ const nativeBrokerErrorCode = this.getNativeBrokerErrorCode();
978
+ if (nativeBrokerErrorCode?.length) {
979
+ platformFieldsArr.push(`broker_error=${nativeBrokerErrorCode}`);
980
+ }
981
+ const platformFields = platformFieldsArr.join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
982
+ const regionDiscoveryFields = this.getRegionDiscoveryFields();
983
+ const requestWithRegionDiscoveryFields = [
984
+ request,
985
+ regionDiscoveryFields,
986
+ ].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
987
+ return [
988
+ SERVER_TELEM_CONSTANTS.SCHEMA_VERSION,
989
+ requestWithRegionDiscoveryFields,
990
+ platformFields,
991
+ ].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR);
992
+ }
993
+ /**
994
+ * API to add MSER Telemetry for the last failed request
995
+ */
996
+ generateLastRequestHeaderValue() {
997
+ const lastRequests = this.getLastRequests();
998
+ const maxErrors = ServerTelemetryManager.maxErrorsToSend(lastRequests);
999
+ const failedRequests = lastRequests.failedRequests
1000
+ .slice(0, 2 * maxErrors)
1001
+ .join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
1002
+ const errors = lastRequests.errors
1003
+ .slice(0, maxErrors)
1004
+ .join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
1005
+ const errorCount = lastRequests.errors.length;
1006
+ // Indicate whether this header contains all data or partial data
1007
+ const overflow = maxErrors < errorCount
1008
+ ? SERVER_TELEM_CONSTANTS.OVERFLOW_TRUE
1009
+ : SERVER_TELEM_CONSTANTS.OVERFLOW_FALSE;
1010
+ const platformFields = [errorCount, overflow].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
1011
+ return [
1012
+ SERVER_TELEM_CONSTANTS.SCHEMA_VERSION,
1013
+ lastRequests.cacheHits,
1014
+ failedRequests,
1015
+ errors,
1016
+ platformFields,
1017
+ ].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR);
1018
+ }
1019
+ /**
1020
+ * API to cache token failures for MSER data capture
1021
+ * @param error
1022
+ */
1023
+ cacheFailedRequest(error) {
1024
+ const lastRequests = this.getLastRequests();
1025
+ if (lastRequests.errors.length >=
1026
+ SERVER_TELEM_CONSTANTS.MAX_CACHED_ERRORS) {
1027
+ // Remove a cached error to make room, first in first out
1028
+ lastRequests.failedRequests.shift(); // apiId
1029
+ lastRequests.failedRequests.shift(); // correlationId
1030
+ lastRequests.errors.shift();
1031
+ }
1032
+ lastRequests.failedRequests.push(this.apiId, this.correlationId);
1033
+ if (error instanceof Error && !!error && error.toString()) {
1034
+ if (error instanceof AuthError) {
1035
+ if (error.subError) {
1036
+ lastRequests.errors.push(error.subError);
1037
+ }
1038
+ else if (error.errorCode) {
1039
+ lastRequests.errors.push(error.errorCode);
1040
+ }
1041
+ else {
1042
+ lastRequests.errors.push(error.toString());
1043
+ }
1044
+ }
1045
+ else {
1046
+ lastRequests.errors.push(error.toString());
1047
+ }
1048
+ }
1049
+ else {
1050
+ lastRequests.errors.push(SERVER_TELEM_CONSTANTS.UNKNOWN_ERROR);
1051
+ }
1052
+ this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests);
1053
+ return;
1054
+ }
1055
+ /**
1056
+ * Update server telemetry cache entry by incrementing cache hit counter
1057
+ */
1058
+ incrementCacheHits() {
1059
+ const lastRequests = this.getLastRequests();
1060
+ lastRequests.cacheHits += 1;
1061
+ this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests);
1062
+ return lastRequests.cacheHits;
1063
+ }
1064
+ /**
1065
+ * Get the server telemetry entity from cache or initialize a new one
1066
+ */
1067
+ getLastRequests() {
1068
+ const initialValue = {
1069
+ failedRequests: [],
1070
+ errors: [],
1071
+ cacheHits: 0,
1072
+ };
1073
+ const lastRequests = this.cacheManager.getServerTelemetry(this.telemetryCacheKey);
1074
+ return lastRequests || initialValue;
1075
+ }
1076
+ /**
1077
+ * Remove server telemetry cache entry
1078
+ */
1079
+ clearTelemetryCache() {
1080
+ const lastRequests = this.getLastRequests();
1081
+ const numErrorsFlushed = ServerTelemetryManager.maxErrorsToSend(lastRequests);
1082
+ const errorCount = lastRequests.errors.length;
1083
+ if (numErrorsFlushed === errorCount) {
1084
+ // All errors were sent on last request, clear Telemetry cache
1085
+ this.cacheManager.removeItem(this.telemetryCacheKey);
1086
+ }
1087
+ else {
1088
+ // Partial data was flushed to server, construct a new telemetry cache item with errors that were not flushed
1089
+ const serverTelemEntity = {
1090
+ failedRequests: lastRequests.failedRequests.slice(numErrorsFlushed * 2),
1091
+ errors: lastRequests.errors.slice(numErrorsFlushed),
1092
+ cacheHits: 0,
1093
+ };
1094
+ this.cacheManager.setServerTelemetry(this.telemetryCacheKey, serverTelemEntity);
1095
+ }
1096
+ }
1097
+ /**
1098
+ * Returns the maximum number of errors that can be flushed to the server in the next network request
1099
+ * @param serverTelemetryEntity
1100
+ */
1101
+ static maxErrorsToSend(serverTelemetryEntity) {
1102
+ let i;
1103
+ let maxErrors = 0;
1104
+ let dataSize = 0;
1105
+ const errorCount = serverTelemetryEntity.errors.length;
1106
+ for (i = 0; i < errorCount; i++) {
1107
+ // failedRequests parameter contains pairs of apiId and correlationId, multiply index by 2 to preserve pairs
1108
+ const apiId = serverTelemetryEntity.failedRequests[2 * i] ||
1109
+ Constants.EMPTY_STRING;
1110
+ const correlationId = serverTelemetryEntity.failedRequests[2 * i + 1] ||
1111
+ Constants.EMPTY_STRING;
1112
+ const errorCode = serverTelemetryEntity.errors[i] || Constants.EMPTY_STRING;
1113
+ // Count number of characters that would be added to header, each character is 1 byte. Add 3 at the end to account for separators
1114
+ dataSize +=
1115
+ apiId.toString().length +
1116
+ correlationId.toString().length +
1117
+ errorCode.length +
1118
+ 3;
1119
+ if (dataSize < SERVER_TELEM_CONSTANTS.MAX_LAST_HEADER_BYTES) {
1120
+ // Adding this entry to the header would still keep header size below the limit
1121
+ maxErrors += 1;
1122
+ }
1123
+ else {
1124
+ break;
1125
+ }
1126
+ }
1127
+ return maxErrors;
1128
+ }
1129
+ /**
1130
+ * Get the region discovery fields
1131
+ *
1132
+ * @returns string
1133
+ */
1134
+ getRegionDiscoveryFields() {
1135
+ const regionDiscoveryFields = [];
1136
+ regionDiscoveryFields.push(this.regionUsed || Constants.EMPTY_STRING);
1137
+ regionDiscoveryFields.push(this.regionSource || Constants.EMPTY_STRING);
1138
+ regionDiscoveryFields.push(this.regionOutcome || Constants.EMPTY_STRING);
1139
+ return regionDiscoveryFields.join(",");
1140
+ }
1141
+ /**
1142
+ * Update the region discovery metadata
1143
+ *
1144
+ * @param regionDiscoveryMetadata
1145
+ * @returns void
1146
+ */
1147
+ updateRegionDiscoveryMetadata(regionDiscoveryMetadata) {
1148
+ this.regionUsed = regionDiscoveryMetadata.region_used;
1149
+ this.regionSource = regionDiscoveryMetadata.region_source;
1150
+ this.regionOutcome = regionDiscoveryMetadata.region_outcome;
1151
+ }
1152
+ /**
1153
+ * Set cache outcome
1154
+ */
1155
+ setCacheOutcome(cacheOutcome) {
1156
+ this.cacheOutcome = cacheOutcome;
1157
+ }
1158
+ setNativeBrokerErrorCode(errorCode) {
1159
+ const lastRequests = this.getLastRequests();
1160
+ lastRequests.nativeBrokerErrorCode = errorCode;
1161
+ this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests);
1162
+ }
1163
+ getNativeBrokerErrorCode() {
1164
+ return this.getLastRequests().nativeBrokerErrorCode;
1165
+ }
1166
+ clearNativeBrokerErrorCode() {
1167
+ const lastRequests = this.getLastRequests();
1168
+ delete lastRequests.nativeBrokerErrorCode;
1169
+ this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests);
1170
+ }
1171
+ static makeExtraSkuString(params) {
1172
+ return makeExtraSkuString(params);
1173
+ }
1174
+ }
1175
+
1176
+ /*
1177
+ * Copyright (c) Microsoft Corporation. All rights reserved.
1178
+ * Licensed under the MIT License.
1179
+ */
1180
+ class BasePersistence {
1181
+ async verifyPersistence() {
1182
+ // We are using a different location for the test to avoid overriding the functional cache
1183
+ const persistenceValidator = await this.createForPersistenceValidation();
1184
+ try {
1185
+ await persistenceValidator.save(Constants$1.PERSISTENCE_TEST_DATA);
1186
+ const retrievedDummyData = await persistenceValidator.load();
1187
+ if (!retrievedDummyData) {
1188
+ throw PersistenceError.createCachePersistenceError("Persistence check failed. Data was written but it could not be read. " +
1189
+ "Possible cause: on Linux, LibSecret is installed but D-Bus isn't running \
1190
+ because it cannot be started over SSH.");
1191
+ }
1192
+ if (retrievedDummyData !== Constants$1.PERSISTENCE_TEST_DATA) {
1193
+ throw PersistenceError.createCachePersistenceError(`Persistence check failed. Data written ${Constants$1.PERSISTENCE_TEST_DATA} is different \
1194
+ from data read ${retrievedDummyData}`);
1195
+ }
1196
+ await persistenceValidator.delete();
1197
+ return true;
1198
+ }
1199
+ catch (e) {
1200
+ throw PersistenceError.createCachePersistenceError(`Verifing persistence failed with the error: ${e}`);
1201
+ }
1202
+ }
1203
+ }
1204
+
1205
+ /*
1206
+ * Copyright (c) Microsoft Corporation. All rights reserved.
1207
+ * Licensed under the MIT License.
1208
+ */
1209
+ /**
1210
+ * Reads and writes data to file specified by file location. File contents are not
1211
+ * encrypted.
1212
+ *
1213
+ * If file or directory has not been created, it FilePersistence.create() will create
1214
+ * file and any directories in the path recursively.
1215
+ */
1216
+ class FilePersistence extends BasePersistence {
1217
+ constructor(fileLocation, loggerOptions) {
1218
+ super();
1219
+ this.logger = new Logger(loggerOptions || FilePersistence.createDefaultLoggerOptions());
1220
+ this.filePath = fileLocation;
1221
+ }
1222
+ static async create(fileLocation, loggerOptions) {
1223
+ const filePersistence = new FilePersistence(fileLocation, loggerOptions);
1224
+ await filePersistence.createCacheFile();
1225
+ return filePersistence;
1226
+ }
1227
+ async save(contents) {
1228
+ try {
1229
+ await fs.promises.writeFile(this.getFilePath(), contents, "utf-8");
1230
+ }
1231
+ catch (err) {
1232
+ if (isNodeError(err)) {
1233
+ throw PersistenceError.createFileSystemError(err.code || ErrorCodes.UNKNOWN, err.message);
1234
+ }
1235
+ else {
1236
+ throw err;
1237
+ }
1238
+ }
1239
+ }
1240
+ async saveBuffer(contents) {
1241
+ try {
1242
+ await fs.promises.writeFile(this.getFilePath(), contents);
1243
+ }
1244
+ catch (err) {
1245
+ if (isNodeError(err)) {
1246
+ throw PersistenceError.createFileSystemError(err.code || ErrorCodes.UNKNOWN, err.message);
1247
+ }
1248
+ else {
1249
+ throw err;
1250
+ }
1251
+ }
1252
+ }
1253
+ async load() {
1254
+ try {
1255
+ return await fs.promises.readFile(this.getFilePath(), "utf-8");
1256
+ }
1257
+ catch (err) {
1258
+ if (isNodeError(err)) {
1259
+ throw PersistenceError.createFileSystemError(err.code || ErrorCodes.UNKNOWN, err.message);
1260
+ }
1261
+ else {
1262
+ throw err;
1263
+ }
1264
+ }
1265
+ }
1266
+ async loadBuffer() {
1267
+ try {
1268
+ return await fs.promises.readFile(this.getFilePath());
1269
+ }
1270
+ catch (err) {
1271
+ if (isNodeError(err)) {
1272
+ throw PersistenceError.createFileSystemError(err.code || ErrorCodes.UNKNOWN, err.message);
1273
+ }
1274
+ else {
1275
+ throw err;
1276
+ }
1277
+ }
1278
+ }
1279
+ async delete() {
1280
+ try {
1281
+ await fs.promises.unlink(this.getFilePath());
1282
+ return true;
1283
+ }
1284
+ catch (err) {
1285
+ if (isNodeError(err)) {
1286
+ if (err.code === Constants$1.ENOENT_ERROR) {
1287
+ // file does not exist, so it was not deleted
1288
+ this.logger.warning("Cache file does not exist, so it could not be deleted");
1289
+ return false;
1290
+ }
1291
+ throw PersistenceError.createFileSystemError(err.code || ErrorCodes.UNKNOWN, err.message);
1292
+ }
1293
+ else {
1294
+ throw err;
1295
+ }
1296
+ }
1297
+ }
1298
+ getFilePath() {
1299
+ return this.filePath;
1300
+ }
1301
+ async reloadNecessary(lastSync) {
1302
+ return lastSync < (await this.timeLastModified());
1303
+ }
1304
+ getLogger() {
1305
+ return this.logger;
1306
+ }
1307
+ createForPersistenceValidation() {
1308
+ const testCacheFileLocation = `${path.dirname(this.filePath)}/test.cache`;
1309
+ return FilePersistence.create(testCacheFileLocation);
1310
+ }
1311
+ static createDefaultLoggerOptions() {
1312
+ return {
1313
+ loggerCallback: () => {
1314
+ // allow users to not set loggerCallback
1315
+ },
1316
+ piiLoggingEnabled: false,
1317
+ logLevel: LogLevel.Info,
1318
+ };
1319
+ }
1320
+ async timeLastModified() {
1321
+ try {
1322
+ const stats = await fs.promises.stat(this.filePath);
1323
+ return stats.mtime.getTime();
1324
+ }
1325
+ catch (err) {
1326
+ if (isNodeError(err)) {
1327
+ if (err.code === Constants$1.ENOENT_ERROR) {
1328
+ // file does not exist, so it's never been modified
1329
+ this.logger.verbose("Cache file does not exist");
1330
+ return 0;
1331
+ }
1332
+ throw PersistenceError.createFileSystemError(err.code || ErrorCodes.UNKNOWN, err.message);
1333
+ }
1334
+ else {
1335
+ throw err;
1336
+ }
1337
+ }
1338
+ }
1339
+ async createCacheFile() {
1340
+ await this.createFileDirectory();
1341
+ // File is created only if it does not exist
1342
+ const fileHandle = await fs.promises.open(this.filePath, "a");
1343
+ await fileHandle.close();
1344
+ this.logger.info(`File created at ${this.filePath}`);
1345
+ }
1346
+ async createFileDirectory() {
1347
+ try {
1348
+ await fs.promises.mkdir(path.dirname(this.filePath), { recursive: true });
1349
+ }
1350
+ catch (err) {
1351
+ if (isNodeError(err)) {
1352
+ if (err.code === Constants$1.EEXIST_ERROR) {
1353
+ this.logger.info(`Directory ${path.dirname(this.filePath)} already exists`);
1354
+ }
1355
+ else {
1356
+ throw PersistenceError.createFileSystemError(err.code || ErrorCodes.UNKNOWN, err.message);
1357
+ }
1358
+ }
1359
+ else {
1360
+ throw err;
1361
+ }
1362
+ }
1363
+ }
1364
+ }
1365
+
1366
+ /*
1367
+ * Copyright (c) Microsoft Corporation. All rights reserved.
1368
+ * Licensed under the MIT License.
1369
+ */
1370
+ class defaultDpapi {
1371
+ protectData() {
1372
+ throw new Error("Dpapi is not supported on this platform");
1373
+ }
1374
+ unprotectData() {
1375
+ throw new Error("Dpapi is not supported on this platform");
1376
+ }
1377
+ }
1378
+ let Dpapi;
1379
+ if (process.platform !== "win32") {
1380
+ Dpapi = new defaultDpapi();
1381
+ }
1382
+ else {
1383
+ // In .mjs files, require is not defined. We need to use createRequire to get a require function
1384
+ const safeRequire = typeof require !== "undefined"
1385
+ ? require
1386
+ : module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('msal-node-extensions.cjs', document.baseURI).href)));
1387
+ Dpapi = safeRequire(`../bin/${process.arch}/dpapi`);
1388
+ }
1389
+
1390
+ /*
1391
+ * Copyright (c) Microsoft Corporation. All rights reserved.
1392
+ * Licensed under the MIT License.
1393
+ */
1394
+ /**
1395
+ * Specifies the scope of the data protection - either the current user or the local
1396
+ * machine.
1397
+ *
1398
+ * You do not need a key to protect or unprotect the data.
1399
+ * If you set the Scope to CurrentUser, only applications running on your credentials can
1400
+ * unprotect the data; however, that means that any application running on your credentials
1401
+ * can access the protected data. If you set the Scope to LocalMachine, any full-trust
1402
+ * application on the computer can unprotect, access, and modify the data.
1403
+ *
1404
+ */
1405
+ const DataProtectionScope = {
1406
+ CurrentUser: "CurrentUser",
1407
+ LocalMachine: "LocalMachine",
1408
+ };
1409
+
1410
+ /*
1411
+ * Copyright (c) Microsoft Corporation. All rights reserved.
1412
+ * Licensed under the MIT License.
1413
+ */
1414
+ /**
1415
+ * Uses CryptProtectData and CryptUnprotectData on Windows to encrypt and decrypt file contents.
1416
+ *
1417
+ * scope: Scope of the data protection. Either local user or the current machine
1418
+ * optionalEntropy: Password or other additional entropy used to encrypt the data
1419
+ */
1420
+ class FilePersistenceWithDataProtection extends BasePersistence {
1421
+ constructor(filePersistence, scope, optionalEntropy) {
1422
+ super();
1423
+ this.scope = scope;
1424
+ this.optionalEntropy = optionalEntropy
1425
+ ? Buffer.from(optionalEntropy, "utf-8")
1426
+ : null;
1427
+ this.filePersistence = filePersistence;
1428
+ }
1429
+ static async create(fileLocation, scope, optionalEntropy, loggerOptions) {
1430
+ const filePersistence = await FilePersistence.create(fileLocation, loggerOptions);
1431
+ const persistence = new FilePersistenceWithDataProtection(filePersistence, scope, optionalEntropy);
1432
+ return persistence;
1433
+ }
1434
+ async save(contents) {
1435
+ try {
1436
+ const encryptedContents = Dpapi.protectData(Buffer.from(contents, "utf-8"), this.optionalEntropy, this.scope.toString());
1437
+ await this.filePersistence.saveBuffer(encryptedContents);
1438
+ }
1439
+ catch (err) {
1440
+ if (isNodeError(err)) {
1441
+ throw PersistenceError.createFilePersistenceWithDPAPIError(err.message);
1442
+ }
1443
+ else {
1444
+ throw err;
1445
+ }
1446
+ }
1447
+ }
1448
+ async load() {
1449
+ try {
1450
+ const encryptedContents = await this.filePersistence.loadBuffer();
1451
+ if (typeof encryptedContents === "undefined" ||
1452
+ !encryptedContents ||
1453
+ 0 === encryptedContents.length) {
1454
+ this.filePersistence
1455
+ .getLogger()
1456
+ .info("Encrypted contents loaded from file were null or empty");
1457
+ return null;
1458
+ }
1459
+ return Dpapi.unprotectData(encryptedContents, this.optionalEntropy, this.scope.toString()).toString();
1460
+ }
1461
+ catch (err) {
1462
+ if (isNodeError(err)) {
1463
+ throw PersistenceError.createFilePersistenceWithDPAPIError(err.message);
1464
+ }
1465
+ else {
1466
+ throw err;
1467
+ }
1468
+ }
1469
+ }
1470
+ async delete() {
1471
+ return this.filePersistence.delete();
1472
+ }
1473
+ async reloadNecessary(lastSync) {
1474
+ return this.filePersistence.reloadNecessary(lastSync);
1475
+ }
1476
+ getFilePath() {
1477
+ return this.filePersistence.getFilePath();
1478
+ }
1479
+ getLogger() {
1480
+ return this.filePersistence.getLogger();
1481
+ }
1482
+ createForPersistenceValidation() {
1483
+ const testCacheFileLocation = `${path.dirname(this.filePersistence.getFilePath())}/test.cache`;
1484
+ return FilePersistenceWithDataProtection.create(testCacheFileLocation, DataProtectionScope.CurrentUser);
1485
+ }
1486
+ }
1487
+
1488
+ /*
1489
+ * Copyright (c) Microsoft Corporation. All rights reserved.
1490
+ * Licensed under the MIT License.
1491
+ */
1492
+ /**
1493
+ * Uses reads and writes passwords to macOS keychain
1494
+ *
1495
+ * serviceName: Identifier used as key for whatever value is stored
1496
+ * accountName: Account under which password should be stored
1497
+ */
1498
+ class KeychainPersistence extends BasePersistence {
1499
+ constructor(filePersistence, serviceName, accountName) {
1500
+ super();
1501
+ this.filePersistence = filePersistence;
1502
+ this.serviceName = serviceName;
1503
+ this.accountName = accountName;
1504
+ }
1505
+ static async create(fileLocation, serviceName, accountName, loggerOptions) {
1506
+ const filePersistence = await FilePersistence.create(fileLocation, loggerOptions);
1507
+ const persistence = new KeychainPersistence(filePersistence, serviceName, accountName);
1508
+ return persistence;
1509
+ }
1510
+ async save(contents) {
1511
+ try {
1512
+ await keytar.setPassword(this.serviceName, this.accountName, contents);
1513
+ }
1514
+ catch (err) {
1515
+ if (isNodeError(err)) {
1516
+ throw PersistenceError.createKeychainPersistenceError(err.message);
1517
+ }
1518
+ else {
1519
+ throw err;
1520
+ }
1521
+ }
1522
+ // Write dummy data to update file mtime
1523
+ await this.filePersistence.save("{}");
1524
+ }
1525
+ async load() {
1526
+ try {
1527
+ return await keytar.getPassword(this.serviceName, this.accountName);
1528
+ }
1529
+ catch (err) {
1530
+ if (isNodeError(err)) {
1531
+ throw PersistenceError.createKeychainPersistenceError(err.message);
1532
+ }
1533
+ else {
1534
+ throw err;
1535
+ }
1536
+ }
1537
+ }
1538
+ async delete() {
1539
+ try {
1540
+ await this.filePersistence.delete();
1541
+ return await keytar.deletePassword(this.serviceName, this.accountName);
1542
+ }
1543
+ catch (err) {
1544
+ if (isNodeError(err)) {
1545
+ throw PersistenceError.createKeychainPersistenceError(err.message);
1546
+ }
1547
+ else {
1548
+ throw err;
1549
+ }
1550
+ }
1551
+ }
1552
+ async reloadNecessary(lastSync) {
1553
+ return this.filePersistence.reloadNecessary(lastSync);
1554
+ }
1555
+ getFilePath() {
1556
+ return this.filePersistence.getFilePath();
1557
+ }
1558
+ getLogger() {
1559
+ return this.filePersistence.getLogger();
1560
+ }
1561
+ createForPersistenceValidation() {
1562
+ const testCacheFileLocation = `${path.dirname(this.filePersistence.getFilePath())}/test.cache`;
1563
+ return KeychainPersistence.create(testCacheFileLocation, "persistenceValidationServiceName", "persistencValidationAccountName");
1564
+ }
1565
+ }
1566
+
1567
+ /*
1568
+ * Copyright (c) Microsoft Corporation. All rights reserved.
1569
+ * Licensed under the MIT License.
1570
+ */
1571
+ /**
1572
+ * Uses reads and writes passwords to Secret Service API/libsecret. Requires libsecret
1573
+ * to be installed.
1574
+ *
1575
+ * serviceName: Identifier used as key for whatever value is stored
1576
+ * accountName: Account under which password should be stored
1577
+ */
1578
+ class LibSecretPersistence extends BasePersistence {
1579
+ constructor(filePersistence, serviceName, accountName) {
1580
+ super();
1581
+ this.filePersistence = filePersistence;
1582
+ this.serviceName = serviceName;
1583
+ this.accountName = accountName;
1584
+ }
1585
+ static async create(fileLocation, serviceName, accountName, loggerOptions) {
1586
+ const filePersistence = await FilePersistence.create(fileLocation, loggerOptions);
1587
+ const persistence = new LibSecretPersistence(filePersistence, serviceName, accountName);
1588
+ return persistence;
1589
+ }
1590
+ async save(contents) {
1591
+ try {
1592
+ await keytar.setPassword(this.serviceName, this.accountName, contents);
1593
+ }
1594
+ catch (err) {
1595
+ if (isNodeError(err)) {
1596
+ throw PersistenceError.createLibSecretError(err.message);
1597
+ }
1598
+ else {
1599
+ throw err;
1600
+ }
1601
+ }
1602
+ // Write dummy data to update file mtime
1603
+ await this.filePersistence.save("{}");
1604
+ }
1605
+ async load() {
1606
+ try {
1607
+ return await keytar.getPassword(this.serviceName, this.accountName);
1608
+ }
1609
+ catch (err) {
1610
+ if (isNodeError(err)) {
1611
+ throw PersistenceError.createLibSecretError(err.message);
1612
+ }
1613
+ else {
1614
+ throw err;
1615
+ }
1616
+ }
1617
+ }
1618
+ async delete() {
1619
+ try {
1620
+ await this.filePersistence.delete();
1621
+ return await keytar.deletePassword(this.serviceName, this.accountName);
1622
+ }
1623
+ catch (err) {
1624
+ if (isNodeError(err)) {
1625
+ throw PersistenceError.createLibSecretError(err.message);
1626
+ }
1627
+ else {
1628
+ throw err;
1629
+ }
1630
+ }
1631
+ }
1632
+ async reloadNecessary(lastSync) {
1633
+ return this.filePersistence.reloadNecessary(lastSync);
1634
+ }
1635
+ getFilePath() {
1636
+ return this.filePersistence.getFilePath();
1637
+ }
1638
+ getLogger() {
1639
+ return this.filePersistence.getLogger();
1640
+ }
1641
+ createForPersistenceValidation() {
1642
+ const testCacheFileLocation = `${path.dirname(this.filePersistence.getFilePath())}/test.cache`;
1643
+ return LibSecretPersistence.create(testCacheFileLocation, "persistenceValidationServiceName", "persistencValidationAccountName");
1644
+ }
1645
+ }
1646
+
1647
+ /*
1648
+ * Copyright (c) Microsoft Corporation. All rights reserved.
1649
+ * Licensed under the MIT License.
1650
+ */
1651
+ class Environment {
1652
+ static get homeEnvVar() {
1653
+ return this.getEnvironmentVariable(Constants$1.ENVIRONMENT.HOME);
1654
+ }
1655
+ static get lognameEnvVar() {
1656
+ return this.getEnvironmentVariable(Constants$1.ENVIRONMENT.LOGNAME);
1657
+ }
1658
+ static get userEnvVar() {
1659
+ return this.getEnvironmentVariable(Constants$1.ENVIRONMENT.USER);
1660
+ }
1661
+ static get lnameEnvVar() {
1662
+ return this.getEnvironmentVariable(Constants$1.ENVIRONMENT.LNAME);
1663
+ }
1664
+ static get usernameEnvVar() {
1665
+ return this.getEnvironmentVariable(Constants$1.ENVIRONMENT.USERNAME);
1666
+ }
1667
+ static getEnvironmentVariable(name) {
1668
+ return process.env[name] || "";
1669
+ }
1670
+ static getEnvironmentPlatform() {
1671
+ return process.platform;
1672
+ }
1673
+ static isWindowsPlatform() {
1674
+ return this.getEnvironmentPlatform() === Platform.WINDOWS;
1675
+ }
1676
+ static isLinuxPlatform() {
1677
+ return this.getEnvironmentPlatform() === Platform.LINUX;
1678
+ }
1679
+ static isMacPlatform() {
1680
+ return this.getEnvironmentPlatform() === Platform.MACOS;
1681
+ }
1682
+ static isLinuxRootUser() {
1683
+ if (typeof process.getuid !== "function") {
1684
+ return false;
1685
+ }
1686
+ return process.getuid() === Constants$1.LINUX_ROOT_USER_GUID;
1687
+ }
1688
+ static getUserRootDirectory() {
1689
+ return !this.isWindowsPlatform()
1690
+ ? this.getUserHomeDirOnUnix()
1691
+ : this.getUserHomeDirOnWindows();
1692
+ }
1693
+ static getUserHomeDirOnWindows() {
1694
+ return this.getEnvironmentVariable(Constants$1.ENVIRONMENT.LOCAL_APPLICATION_DATA);
1695
+ }
1696
+ static getUserHomeDirOnUnix() {
1697
+ if (this.isWindowsPlatform()) {
1698
+ throw PersistenceError.createNotSupportedError("Getting the user home directory for unix is not supported in windows");
1699
+ }
1700
+ if (this.homeEnvVar) {
1701
+ return this.homeEnvVar;
1702
+ }
1703
+ let username = null;
1704
+ if (this.lognameEnvVar) {
1705
+ username = this.lognameEnvVar;
1706
+ }
1707
+ else if (this.userEnvVar) {
1708
+ username = this.userEnvVar;
1709
+ }
1710
+ else if (this.lnameEnvVar) {
1711
+ username = this.lnameEnvVar;
1712
+ }
1713
+ else if (this.usernameEnvVar) {
1714
+ username = this.usernameEnvVar;
1715
+ }
1716
+ if (this.isMacPlatform()) {
1717
+ return username ? path.join("/Users", username) : null;
1718
+ }
1719
+ else if (this.isLinuxPlatform()) {
1720
+ if (this.isLinuxRootUser()) {
1721
+ return "/root";
1722
+ }
1723
+ else {
1724
+ return username ? path.join("/home", username) : null;
1725
+ }
1726
+ }
1727
+ else {
1728
+ throw PersistenceError.createNotSupportedError("Getting the user home directory for unix is not supported in windows");
1729
+ }
1730
+ }
1731
+ }
1732
+
1733
+ /*
1734
+ * Copyright (c) Microsoft Corporation. All rights reserved.
1735
+ * Licensed under the MIT License.
1736
+ */
1737
+ class PersistenceCreator {
1738
+ static async createPersistence(config) {
1739
+ let peristence;
1740
+ // On Windows, uses a DPAPI encrypted file
1741
+ if (Environment.isWindowsPlatform()) {
1742
+ if (!config.cachePath || !config.dataProtectionScope) {
1743
+ throw PersistenceError.createPersistenceNotValidatedError("Cache path and/or data protection scope not provided for the FilePersistenceWithDataProtection cache plugin");
1744
+ }
1745
+ peristence = await FilePersistenceWithDataProtection.create(config.cachePath, DataProtectionScope.CurrentUser, undefined, config.loggerOptions);
1746
+ }
1747
+ // On Mac, uses keychain.
1748
+ else if (Environment.isMacPlatform()) {
1749
+ if (!config.cachePath ||
1750
+ !config.serviceName ||
1751
+ !config.accountName) {
1752
+ throw PersistenceError.createPersistenceNotValidatedError("Cache path, service name and/or account name not provided for the KeychainPersistence cache plugin");
1753
+ }
1754
+ peristence = await KeychainPersistence.create(config.cachePath, config.serviceName, config.accountName, config.loggerOptions);
1755
+ }
1756
+ // On Linux, uses libsecret to store to secret service. Libsecret has to be installed.
1757
+ else if (Environment.isLinuxPlatform()) {
1758
+ if (!config.cachePath ||
1759
+ !config.serviceName ||
1760
+ !config.accountName) {
1761
+ throw PersistenceError.createPersistenceNotValidatedError("Cache path, service name and/or account name not provided for the LibSecretPersistence cache plugin");
1762
+ }
1763
+ peristence = await LibSecretPersistence.create(config.cachePath, config.serviceName, config.accountName, config.loggerOptions);
1764
+ }
1765
+ else {
1766
+ throw PersistenceError.createNotSupportedError("The current environment is not supported by msal-node-extensions yet.");
1767
+ }
1768
+ await peristence.verifyPersistence().catch(async (e) => {
1769
+ if (Environment.isLinuxPlatform() &&
1770
+ config.usePlaintextFileOnLinux) {
1771
+ if (!config.cachePath) {
1772
+ throw PersistenceError.createPersistenceNotValidatedError("Cache path not provided for the FilePersistence cache plugin");
1773
+ }
1774
+ peristence = await FilePersistence.create(config.cachePath, config.loggerOptions);
1775
+ const isFilePersistenceVerified = await peristence.verifyPersistence();
1776
+ if (isFilePersistenceVerified) {
1777
+ return peristence;
1778
+ }
1779
+ throw PersistenceError.createPersistenceNotVerifiedError("Persistence could not be verified");
1780
+ }
1781
+ else {
1782
+ throw e;
1783
+ }
1784
+ });
1785
+ return peristence;
1786
+ }
1787
+ }
1788
+
1789
+ /*
1790
+ * Copyright (c) Microsoft Corporation. All rights reserved.
1791
+ * Licensed under the MIT License.
1792
+ */
1793
+ class NativeAuthError extends AuthError {
1794
+ constructor(errorStatus, errorContext, errorCode, errorTag) {
1795
+ super(errorStatus, errorContext);
1796
+ this.name = "NativeAuthError";
1797
+ this.statusCode = errorCode;
1798
+ this.tag = errorTag;
1799
+ Object.setPrototypeOf(this, NativeAuthError.prototype);
1800
+ }
1801
+ }
1802
+
1803
+ /* eslint-disable header/header */
1804
+ const name = "@azure/msal-node-extensions";
1805
+ const version = "1.2.0";
1806
+
1807
+ /*
1808
+ * Copyright (c) Microsoft Corporation. All rights reserved.
1809
+ * Licensed under the MIT License.
1810
+ */
1811
+ class NativeBrokerPlugin {
1812
+ constructor() {
1813
+ const defaultLoggerOptions = {
1814
+ loggerCallback: () => {
1815
+ // Empty logger callback
1816
+ },
1817
+ piiLoggingEnabled: false,
1818
+ };
1819
+ this.logger = new Logger(defaultLoggerOptions, name, version); // Default logger
1820
+ this.isBrokerAvailable = msalNodeRuntime.msalNodeRuntime.StartupError ? false : true;
1821
+ }
1822
+ setLogger(loggerOptions) {
1823
+ this.logger = new Logger(loggerOptions, name, version);
1824
+ const logCallback = (message, logLevel, containsPii) => {
1825
+ switch (logLevel) {
1826
+ case msalNodeRuntime.LogLevel.Trace:
1827
+ if (containsPii) {
1828
+ this.logger.tracePii(message);
1829
+ }
1830
+ else {
1831
+ this.logger.trace(message);
1832
+ }
1833
+ break;
1834
+ case msalNodeRuntime.LogLevel.Debug:
1835
+ if (containsPii) {
1836
+ this.logger.tracePii(message);
1837
+ }
1838
+ else {
1839
+ this.logger.trace(message);
1840
+ }
1841
+ break;
1842
+ case msalNodeRuntime.LogLevel.Info:
1843
+ if (containsPii) {
1844
+ this.logger.infoPii(message);
1845
+ }
1846
+ else {
1847
+ this.logger.info(message);
1848
+ }
1849
+ break;
1850
+ case msalNodeRuntime.LogLevel.Warning:
1851
+ if (containsPii) {
1852
+ this.logger.warningPii(message);
1853
+ }
1854
+ else {
1855
+ this.logger.warning(message);
1856
+ }
1857
+ break;
1858
+ case msalNodeRuntime.LogLevel.Error:
1859
+ if (containsPii) {
1860
+ this.logger.errorPii(message);
1861
+ }
1862
+ else {
1863
+ this.logger.error(message);
1864
+ }
1865
+ break;
1866
+ case msalNodeRuntime.LogLevel.Fatal:
1867
+ if (containsPii) {
1868
+ this.logger.errorPii(message);
1869
+ }
1870
+ else {
1871
+ this.logger.error(message);
1872
+ }
1873
+ break;
1874
+ default:
1875
+ if (containsPii) {
1876
+ this.logger.infoPii(message);
1877
+ }
1878
+ else {
1879
+ this.logger.info(message);
1880
+ }
1881
+ break;
1882
+ }
1883
+ };
1884
+ try {
1885
+ msalNodeRuntime.msalNodeRuntime.RegisterLogger(logCallback, loggerOptions.piiLoggingEnabled || false);
1886
+ }
1887
+ catch (e) {
1888
+ const wrappedError = this.wrapError(e);
1889
+ if (wrappedError) {
1890
+ throw wrappedError;
1891
+ }
1892
+ }
1893
+ }
1894
+ async getAccountById(accountId, correlationId) {
1895
+ this.logger.trace("NativeBrokerPlugin - getAccountById called", correlationId);
1896
+ const readAccountResult = await this.readAccountById(accountId, correlationId);
1897
+ return this.generateAccountInfo(readAccountResult.account);
1898
+ }
1899
+ async getAllAccounts(clientId, correlationId) {
1900
+ this.logger.trace("NativeBrokerPlugin - getAllAccounts called", correlationId);
1901
+ return new Promise((resolve, reject) => {
1902
+ const resultCallback = (result) => {
1903
+ try {
1904
+ result.CheckError();
1905
+ }
1906
+ catch (e) {
1907
+ const wrappedError = this.wrapError(e);
1908
+ if (wrappedError) {
1909
+ reject(wrappedError);
1910
+ return;
1911
+ }
1912
+ }
1913
+ const accountInfoResult = [];
1914
+ result.accounts.forEach((account) => {
1915
+ accountInfoResult.push(this.generateAccountInfo(account));
1916
+ });
1917
+ resolve(accountInfoResult);
1918
+ };
1919
+ try {
1920
+ msalNodeRuntime.msalNodeRuntime.DiscoverAccountsAsync(clientId, correlationId, resultCallback);
1921
+ }
1922
+ catch (e) {
1923
+ const wrappedError = this.wrapError(e);
1924
+ if (wrappedError) {
1925
+ reject(wrappedError);
1926
+ }
1927
+ }
1928
+ });
1929
+ }
1930
+ async acquireTokenSilent(request) {
1931
+ this.logger.trace("NativeBrokerPlugin - acquireTokenSilent called", request.correlationId);
1932
+ const authParams = this.generateRequestParameters(request);
1933
+ const account = await this.getAccount(request);
1934
+ return new Promise((resolve, reject) => {
1935
+ const resultCallback = (result) => {
1936
+ try {
1937
+ result.CheckError();
1938
+ }
1939
+ catch (e) {
1940
+ const wrappedError = this.wrapError(e);
1941
+ if (wrappedError) {
1942
+ reject(wrappedError);
1943
+ return;
1944
+ }
1945
+ }
1946
+ const authenticationResult = this.getAuthenticationResult(request, result);
1947
+ resolve(authenticationResult);
1948
+ };
1949
+ try {
1950
+ if (account) {
1951
+ msalNodeRuntime.msalNodeRuntime.AcquireTokenSilentlyAsync(authParams, request.correlationId, account, resultCallback);
1952
+ }
1953
+ else {
1954
+ msalNodeRuntime.msalNodeRuntime.SignInSilentlyAsync(authParams, request.correlationId, resultCallback);
1955
+ }
1956
+ }
1957
+ catch (e) {
1958
+ const wrappedError = this.wrapError(e);
1959
+ if (wrappedError) {
1960
+ reject(wrappedError);
1961
+ }
1962
+ }
1963
+ });
1964
+ }
1965
+ async acquireTokenInteractive(request, providedWindowHandle) {
1966
+ this.logger.trace("NativeBrokerPlugin - acquireTokenInteractive called", request.correlationId);
1967
+ const authParams = this.generateRequestParameters(request);
1968
+ const account = await this.getAccount(request);
1969
+ const windowHandle = providedWindowHandle || Buffer.from([0]);
1970
+ return new Promise((resolve, reject) => {
1971
+ const resultCallback = (result) => {
1972
+ try {
1973
+ result.CheckError();
1974
+ }
1975
+ catch (e) {
1976
+ const wrappedError = this.wrapError(e);
1977
+ if (wrappedError) {
1978
+ reject(wrappedError);
1979
+ return;
1980
+ }
1981
+ }
1982
+ const authenticationResult = this.getAuthenticationResult(request, result);
1983
+ resolve(authenticationResult);
1984
+ };
1985
+ try {
1986
+ switch (request.prompt) {
1987
+ case PromptValue.LOGIN:
1988
+ case PromptValue.SELECT_ACCOUNT:
1989
+ case PromptValue.CREATE:
1990
+ this.logger.info("Calling native interop SignInInteractively API", request.correlationId);
1991
+ const loginHint = request.loginHint || Constants.EMPTY_STRING;
1992
+ msalNodeRuntime.msalNodeRuntime.SignInInteractivelyAsync(windowHandle, authParams, request.correlationId, loginHint, resultCallback);
1993
+ break;
1994
+ case PromptValue.NONE:
1995
+ if (account) {
1996
+ this.logger.info("Calling native interop AcquireTokenSilently API", request.correlationId);
1997
+ msalNodeRuntime.msalNodeRuntime.AcquireTokenSilentlyAsync(authParams, request.correlationId, account, resultCallback);
1998
+ }
1999
+ else {
2000
+ this.logger.info("Calling native interop SignInSilently API", request.correlationId);
2001
+ msalNodeRuntime.msalNodeRuntime.SignInSilentlyAsync(authParams, request.correlationId, resultCallback);
2002
+ }
2003
+ break;
2004
+ default:
2005
+ if (account) {
2006
+ this.logger.info("Calling native interop AcquireTokenInteractively API", request.correlationId);
2007
+ msalNodeRuntime.msalNodeRuntime.AcquireTokenInteractivelyAsync(windowHandle, authParams, request.correlationId, account, resultCallback);
2008
+ }
2009
+ else {
2010
+ this.logger.info("Calling native interop SignIn API", request.correlationId);
2011
+ const loginHint = request.loginHint || Constants.EMPTY_STRING;
2012
+ msalNodeRuntime.msalNodeRuntime.SignInAsync(windowHandle, authParams, request.correlationId, loginHint, resultCallback);
2013
+ }
2014
+ break;
2015
+ }
2016
+ }
2017
+ catch (e) {
2018
+ const wrappedError = this.wrapError(e);
2019
+ if (wrappedError) {
2020
+ reject(wrappedError);
2021
+ }
2022
+ }
2023
+ });
2024
+ }
2025
+ async signOut(request) {
2026
+ this.logger.trace("NativeBrokerPlugin - signOut called", request.correlationId);
2027
+ const account = await this.getAccount(request);
2028
+ if (!account) {
2029
+ throw createClientAuthError(noAccountFound);
2030
+ }
2031
+ return new Promise((resolve, reject) => {
2032
+ const resultCallback = (result) => {
2033
+ try {
2034
+ result.CheckError();
2035
+ }
2036
+ catch (e) {
2037
+ const wrappedError = this.wrapError(e);
2038
+ if (wrappedError) {
2039
+ reject(wrappedError);
2040
+ return;
2041
+ }
2042
+ }
2043
+ resolve();
2044
+ };
2045
+ try {
2046
+ msalNodeRuntime.msalNodeRuntime.SignOutSilentlyAsync(request.clientId, request.correlationId, account, resultCallback);
2047
+ }
2048
+ catch (e) {
2049
+ const wrappedError = this.wrapError(e);
2050
+ if (wrappedError) {
2051
+ reject(wrappedError);
2052
+ }
2053
+ }
2054
+ });
2055
+ }
2056
+ async getAccount(request) {
2057
+ if (request.accountId) {
2058
+ const readAccountResult = await this.readAccountById(request.accountId, request.correlationId);
2059
+ return readAccountResult.account;
2060
+ }
2061
+ return null;
2062
+ }
2063
+ async readAccountById(accountId, correlationId) {
2064
+ this.logger.trace("NativeBrokerPlugin - readAccountById called", correlationId);
2065
+ return new Promise((resolve, reject) => {
2066
+ const resultCallback = (result) => {
2067
+ try {
2068
+ result.CheckError();
2069
+ }
2070
+ catch (e) {
2071
+ const wrappedError = this.wrapError(e);
2072
+ if (wrappedError) {
2073
+ reject(wrappedError);
2074
+ return;
2075
+ }
2076
+ }
2077
+ resolve(result);
2078
+ };
2079
+ try {
2080
+ msalNodeRuntime.msalNodeRuntime.ReadAccountByIdAsync(accountId, correlationId, resultCallback);
2081
+ }
2082
+ catch (e) {
2083
+ const wrappedError = this.wrapError(e);
2084
+ if (wrappedError) {
2085
+ reject(wrappedError);
2086
+ }
2087
+ }
2088
+ });
2089
+ }
2090
+ generateRequestParameters(request) {
2091
+ this.logger.trace("NativeBrokerPlugin - generateRequestParameters called", request.correlationId);
2092
+ const authParams = new msalNodeRuntime.msalNodeRuntime.AuthParameters();
2093
+ try {
2094
+ authParams.CreateAuthParameters(request.clientId, request.authority);
2095
+ authParams.SetRedirectUri(request.redirectUri);
2096
+ authParams.SetRequestedScopes(request.scopes.join(" "));
2097
+ if (request.claims) {
2098
+ authParams.SetDecodedClaims(request.claims);
2099
+ }
2100
+ if (request.authenticationScheme === AuthenticationScheme.POP) {
2101
+ if (!request.resourceRequestMethod ||
2102
+ !request.resourceRequestUri ||
2103
+ !request.shrNonce) {
2104
+ throw new Error("Authentication Scheme set to POP but one or more of the following parameters are missing: resourceRequestMethod, resourceRequestUri, shrNonce");
2105
+ }
2106
+ const resourceUrl = new URL(request.resourceRequestUri);
2107
+ authParams.SetPopParams(request.resourceRequestMethod, resourceUrl.host, resourceUrl.pathname, request.shrNonce);
2108
+ }
2109
+ if (request.extraParameters) {
2110
+ Object.entries(request.extraParameters).forEach(([key, value]) => {
2111
+ authParams.SetAdditionalParameter(key, value);
2112
+ });
2113
+ }
2114
+ const skus = request.extraParameters &&
2115
+ request.extraParameters[X_CLIENT_EXTRA_SKU]
2116
+ ?.length
2117
+ ? request.extraParameters[X_CLIENT_EXTRA_SKU]
2118
+ : "";
2119
+ authParams.SetAdditionalParameter(X_CLIENT_EXTRA_SKU, ServerTelemetryManager.makeExtraSkuString({
2120
+ skus,
2121
+ extensionName: "msal.node.ext",
2122
+ extensionVersion: version,
2123
+ }));
2124
+ }
2125
+ catch (e) {
2126
+ const wrappedError = this.wrapError(e);
2127
+ if (wrappedError) {
2128
+ throw wrappedError;
2129
+ }
2130
+ }
2131
+ return authParams;
2132
+ }
2133
+ getAuthenticationResult(request, authResult) {
2134
+ this.logger.trace("NativeBrokerPlugin - getAuthenticationResult called", request.correlationId);
2135
+ let fromCache = false;
2136
+ try {
2137
+ const telemetryJSON = JSON.parse(authResult.telemetryData);
2138
+ fromCache = !!telemetryJSON["is_cache"];
2139
+ }
2140
+ catch (e) {
2141
+ this.logger.error("NativeBrokerPlugin: getAuthenticationResult - Error parsing telemetry data. Could not determine if response came from cache.", request.correlationId);
2142
+ }
2143
+ let idTokenClaims;
2144
+ try {
2145
+ idTokenClaims = JSON.parse(authResult.idToken);
2146
+ }
2147
+ catch (e) {
2148
+ throw new Error("Unable to parse idToken claims");
2149
+ }
2150
+ const accountInfo = this.generateAccountInfo(authResult.account, idTokenClaims);
2151
+ const result = {
2152
+ authority: request.authority,
2153
+ uniqueId: idTokenClaims.oid || idTokenClaims.sub || "",
2154
+ tenantId: idTokenClaims.tid || "",
2155
+ scopes: authResult.grantedScopes.split(" "),
2156
+ account: accountInfo,
2157
+ idToken: authResult.rawIdToken,
2158
+ idTokenClaims: idTokenClaims,
2159
+ accessToken: authResult.accessToken,
2160
+ fromCache: fromCache,
2161
+ expiresOn: new Date(authResult.expiresOn),
2162
+ tokenType: authResult.isPopAuthorization
2163
+ ? AuthenticationScheme.POP
2164
+ : AuthenticationScheme.BEARER,
2165
+ correlationId: request.correlationId,
2166
+ fromNativeBroker: true,
2167
+ };
2168
+ return result;
2169
+ }
2170
+ generateAccountInfo(account, idTokenClaims) {
2171
+ this.logger.trace("NativeBrokerPlugin - generateAccountInfo called");
2172
+ const accountInfo = {
2173
+ homeAccountId: account.homeAccountId,
2174
+ environment: account.environment,
2175
+ tenantId: account.realm,
2176
+ username: account.username,
2177
+ localAccountId: account.localAccountId,
2178
+ name: account.displayName,
2179
+ idTokenClaims: idTokenClaims,
2180
+ nativeAccountId: account.accountId,
2181
+ };
2182
+ return accountInfo;
2183
+ }
2184
+ isMsalRuntimeError(result) {
2185
+ return (result.hasOwnProperty("errorCode") ||
2186
+ result.hasOwnProperty("errorStatus") ||
2187
+ result.hasOwnProperty("errorContext") ||
2188
+ result.hasOwnProperty("errorTag"));
2189
+ }
2190
+ wrapError(error) {
2191
+ if (error &&
2192
+ typeof error === "object" &&
2193
+ this.isMsalRuntimeError(error)) {
2194
+ const { errorCode, errorStatus, errorContext, errorTag } = error;
2195
+ switch (errorStatus) {
2196
+ case msalNodeRuntime.ErrorStatus.InteractionRequired:
2197
+ case msalNodeRuntime.ErrorStatus.AccountUnusable:
2198
+ return new InteractionRequiredAuthError(ErrorCodes.INTERATION_REQUIRED_ERROR_CODE, errorContext);
2199
+ case msalNodeRuntime.ErrorStatus.NoNetwork:
2200
+ case msalNodeRuntime.ErrorStatus.NetworkTemporarilyUnavailable:
2201
+ return createClientAuthError(noNetworkConnectivity);
2202
+ case msalNodeRuntime.ErrorStatus.ServerTemporarilyUnavailable:
2203
+ return new ServerError(ErrorCodes.SERVER_UNAVAILABLE, errorContext);
2204
+ case msalNodeRuntime.ErrorStatus.UserCanceled:
2205
+ return createClientAuthError(userCanceled);
2206
+ case msalNodeRuntime.ErrorStatus.AuthorityUntrusted:
2207
+ return createClientConfigurationError(untrustedAuthority);
2208
+ case msalNodeRuntime.ErrorStatus.UserSwitched:
2209
+ // Not an error case, if there's customer demand we can surface this as a response property
2210
+ return null;
2211
+ case msalNodeRuntime.ErrorStatus.AccountNotFound:
2212
+ return createClientAuthError(noAccountFound);
2213
+ default:
2214
+ return new NativeAuthError(msalNodeRuntime.ErrorStatus[errorStatus], errorContext, errorCode, errorTag);
2215
+ }
2216
+ }
2217
+ throw error;
2218
+ }
2219
+ }
2220
+
2221
+ exports.DataProtectionScope = DataProtectionScope;
2222
+ exports.Environment = Environment;
2223
+ exports.FilePersistence = FilePersistence;
2224
+ exports.FilePersistenceWithDataProtection = FilePersistenceWithDataProtection;
2225
+ exports.KeychainPersistence = KeychainPersistence;
2226
+ exports.LibSecretPersistence = LibSecretPersistence;
2227
+ exports.NativeBrokerPlugin = NativeBrokerPlugin;
2228
+ exports.PersistenceCachePlugin = PersistenceCachePlugin;
2229
+ exports.PersistenceCreator = PersistenceCreator;
2230
+ //# sourceMappingURL=msal-node-extensions.cjs.map