@microsoft/teamsfx 0.4.1 → 0.4.2-alpha.01a113d2.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.
- package/README.md +3 -0
- package/dist/index.esm2017.js +163 -377
- package/dist/index.esm2017.js.map +1 -1
- package/dist/index.esm2017.mjs +32 -11
- package/dist/index.esm2017.mjs.map +1 -1
- package/dist/index.esm5.js +212 -485
- package/dist/index.esm5.js.map +1 -1
- package/dist/index.node.cjs.js +32 -11
- package/dist/index.node.cjs.js.map +1 -1
- package/package.json +9 -7
- package/types/teamsfx.d.ts +8 -2
package/dist/index.esm2017.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import jwt_decode from 'jwt-decode';
|
|
2
2
|
import * as microsoftTeams from '@microsoft/teams-js';
|
|
3
|
-
import
|
|
3
|
+
import { PublicClientApplication } from '@azure/msal-browser';
|
|
4
4
|
import { Client } from '@microsoft/microsoft-graph-client';
|
|
5
|
-
import { ManagedIdentityCredential } from '@azure/identity';
|
|
6
5
|
|
|
7
6
|
// Copyright (c) Microsoft Corporation.
|
|
8
7
|
// Licensed under the MIT license.
|
|
@@ -56,6 +55,10 @@ var ErrorCode;
|
|
|
56
55
|
* Operation failed.
|
|
57
56
|
*/
|
|
58
57
|
ErrorCode["FailedOperation"] = "FailedOperation";
|
|
58
|
+
/**
|
|
59
|
+
* Version of SDK and project does not match.
|
|
60
|
+
*/
|
|
61
|
+
ErrorCode["ProjectNeedUpgrade"] = "ProjectNeedUpgrade";
|
|
59
62
|
})(ErrorCode || (ErrorCode = {}));
|
|
60
63
|
/**
|
|
61
64
|
* @internal
|
|
@@ -168,7 +171,7 @@ function getLogLevel() {
|
|
|
168
171
|
return internalLogger.level;
|
|
169
172
|
}
|
|
170
173
|
class InternalLogger {
|
|
171
|
-
constructor() {
|
|
174
|
+
constructor(name, logLevel) {
|
|
172
175
|
this.level = undefined;
|
|
173
176
|
this.defaultLogger = {
|
|
174
177
|
verbose: console.debug,
|
|
@@ -176,6 +179,8 @@ class InternalLogger {
|
|
|
176
179
|
warn: console.warn,
|
|
177
180
|
error: console.error,
|
|
178
181
|
};
|
|
182
|
+
this.name = name;
|
|
183
|
+
this.level = logLevel;
|
|
179
184
|
}
|
|
180
185
|
error(message) {
|
|
181
186
|
this.log(LogLevel.Error, (x) => x.error, message);
|
|
@@ -194,7 +199,13 @@ class InternalLogger {
|
|
|
194
199
|
return;
|
|
195
200
|
}
|
|
196
201
|
const timestamp = new Date().toUTCString();
|
|
197
|
-
|
|
202
|
+
let logHeader;
|
|
203
|
+
if (this.name) {
|
|
204
|
+
logHeader = `[${timestamp}] : @microsoft/teamsfx - ${this.name} : ${LogLevel[logLevel]} - `;
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;
|
|
208
|
+
}
|
|
198
209
|
const logMessage = `${logHeader}${message}`;
|
|
199
210
|
if (this.level !== undefined && this.level <= logLevel) {
|
|
200
211
|
if (this.customLogger) {
|
|
@@ -302,6 +313,57 @@ function getUserInfoFromSsoToken(ssoToken) {
|
|
|
302
313
|
}
|
|
303
314
|
return userInfo;
|
|
304
315
|
}
|
|
316
|
+
/**
|
|
317
|
+
* @internal
|
|
318
|
+
*/
|
|
319
|
+
function getTenantIdAndLoginHintFromSsoToken(ssoToken) {
|
|
320
|
+
if (!ssoToken) {
|
|
321
|
+
const errorMsg = "SSO token is undefined.";
|
|
322
|
+
internalLogger.error(errorMsg);
|
|
323
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
|
|
324
|
+
}
|
|
325
|
+
const tokenObject = parseJwt(ssoToken);
|
|
326
|
+
const userInfo = {
|
|
327
|
+
tid: tokenObject.tid,
|
|
328
|
+
loginHint: tokenObject.ver === "2.0"
|
|
329
|
+
? tokenObject.preferred_username
|
|
330
|
+
: tokenObject.upn,
|
|
331
|
+
};
|
|
332
|
+
return userInfo;
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* @internal
|
|
336
|
+
*/
|
|
337
|
+
function parseAccessTokenFromAuthCodeTokenResponse(tokenResponse) {
|
|
338
|
+
try {
|
|
339
|
+
const tokenResponseObject = typeof tokenResponse == "string"
|
|
340
|
+
? JSON.parse(tokenResponse)
|
|
341
|
+
: tokenResponse;
|
|
342
|
+
if (!tokenResponseObject || !tokenResponseObject.accessToken) {
|
|
343
|
+
const errorMsg = "Get empty access token from Auth Code token response.";
|
|
344
|
+
internalLogger.error(errorMsg);
|
|
345
|
+
throw new Error(errorMsg);
|
|
346
|
+
}
|
|
347
|
+
const token = tokenResponseObject.accessToken;
|
|
348
|
+
const tokenObject = parseJwt(token);
|
|
349
|
+
if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
|
|
350
|
+
const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
|
|
351
|
+
internalLogger.error(errorMsg);
|
|
352
|
+
throw new Error(errorMsg);
|
|
353
|
+
}
|
|
354
|
+
const accessToken = {
|
|
355
|
+
token: token,
|
|
356
|
+
expiresOnTimestamp: tokenObject.exp * 1000,
|
|
357
|
+
};
|
|
358
|
+
return accessToken;
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
const errorMsg = "Parse access token failed from Auth Code token response in node env with error: " +
|
|
362
|
+
error.message;
|
|
363
|
+
internalLogger.error(errorMsg);
|
|
364
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
305
367
|
/**
|
|
306
368
|
* Format string template with replacements
|
|
307
369
|
*
|
|
@@ -541,43 +603,10 @@ class OnBehalfOfUserCredential {
|
|
|
541
603
|
}
|
|
542
604
|
|
|
543
605
|
// Copyright (c) Microsoft Corporation.
|
|
544
|
-
// Licensed under the MIT license.
|
|
545
|
-
/**
|
|
546
|
-
* Configuration used in initialization.
|
|
547
|
-
* @internal
|
|
548
|
-
*/
|
|
549
|
-
class Cache {
|
|
550
|
-
static get(key) {
|
|
551
|
-
return sessionStorage.getItem(key);
|
|
552
|
-
}
|
|
553
|
-
static set(key, value) {
|
|
554
|
-
sessionStorage.setItem(key, value);
|
|
555
|
-
}
|
|
556
|
-
static remove(key) {
|
|
557
|
-
sessionStorage.removeItem(key);
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
// Copyright (c) Microsoft Corporation.
|
|
562
|
-
// Licensed under the MIT license.
|
|
563
|
-
/**
|
|
564
|
-
* @internal
|
|
565
|
-
*/
|
|
566
|
-
var GrantType;
|
|
567
|
-
(function (GrantType) {
|
|
568
|
-
GrantType["authCode"] = "authorization_code";
|
|
569
|
-
GrantType["ssoToken"] = "sso_token";
|
|
570
|
-
})(GrantType || (GrantType = {}));
|
|
571
|
-
|
|
572
|
-
// Copyright (c) Microsoft Corporation.
|
|
573
|
-
const accessTokenCacheKeyPrefix = "accessToken";
|
|
574
|
-
const separator = "-";
|
|
575
606
|
const tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;
|
|
576
607
|
const initializeTeamsSdkTimeoutInMillisecond = 5000;
|
|
577
608
|
const loginPageWidth = 600;
|
|
578
609
|
const loginPageHeight = 535;
|
|
579
|
-
const maxRetryCount = 3;
|
|
580
|
-
const retryTimeSpanInMillisecond = 3000;
|
|
581
610
|
/**
|
|
582
611
|
* Represent Teams current user's identity, and it is used within Teams tab application.
|
|
583
612
|
*
|
|
@@ -595,7 +624,6 @@ class TeamsUserCredential {
|
|
|
595
624
|
* ```typescript
|
|
596
625
|
* const config = {
|
|
597
626
|
* authentication: {
|
|
598
|
-
* runtimeConnectorEndpoint: "https://xxx.xxx.com",
|
|
599
627
|
* initiateLoginEndpoint: "https://localhost:3000/auth-start.html",
|
|
600
628
|
* clientId: "xxx"
|
|
601
629
|
* }
|
|
@@ -613,6 +641,7 @@ class TeamsUserCredential {
|
|
|
613
641
|
internalLogger.info("Create teams user credential");
|
|
614
642
|
this.config = this.loadAndValidateConfig();
|
|
615
643
|
this.ssoToken = null;
|
|
644
|
+
this.initialized = false;
|
|
616
645
|
}
|
|
617
646
|
/**
|
|
618
647
|
* Popup login page to get user's access token with specific scopes.
|
|
@@ -630,7 +659,6 @@ class TeamsUserCredential {
|
|
|
630
659
|
* @param scopes - The list of scopes for which the token will have access, before that, we will request user to consent.
|
|
631
660
|
*
|
|
632
661
|
* @throws {@link ErrorCode|InternalError} when failed to login with unknown error.
|
|
633
|
-
* @throws {@link ErrorCode|ServiceError} when simple auth server failed to exchange access token.
|
|
634
662
|
* @throws {@link ErrorCode|ConsentFailed} when user canceled or failed to consent.
|
|
635
663
|
* @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
|
|
636
664
|
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
|
|
@@ -641,27 +669,46 @@ class TeamsUserCredential {
|
|
|
641
669
|
validateScopesType(scopes);
|
|
642
670
|
const scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
|
|
643
671
|
internalLogger.info(`Popup login page to get user's access token with scopes: ${scopesStr}`);
|
|
672
|
+
if (!this.initialized) {
|
|
673
|
+
await this.init();
|
|
674
|
+
}
|
|
644
675
|
return new Promise((resolve, reject) => {
|
|
645
676
|
microsoftTeams.initialize(() => {
|
|
646
677
|
microsoftTeams.authentication.authenticate({
|
|
647
|
-
url: `${this.config.initiateLoginEndpoint}?clientId=${this.config.clientId}&scope=${encodeURI(scopesStr)}`,
|
|
678
|
+
url: `${this.config.initiateLoginEndpoint}?clientId=${this.config.clientId}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint}`,
|
|
648
679
|
width: loginPageWidth,
|
|
649
680
|
height: loginPageHeight,
|
|
650
681
|
successCallback: async (result) => {
|
|
651
682
|
if (!result) {
|
|
652
|
-
const errorMsg = "Get empty authentication result from
|
|
683
|
+
const errorMsg = "Get empty authentication result from MSAL";
|
|
653
684
|
internalLogger.error(errorMsg);
|
|
654
685
|
reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
|
|
655
686
|
return;
|
|
656
687
|
}
|
|
657
|
-
|
|
688
|
+
let resultJson = {};
|
|
658
689
|
try {
|
|
659
|
-
|
|
690
|
+
resultJson = JSON.parse(result);
|
|
691
|
+
}
|
|
692
|
+
catch (error) {
|
|
693
|
+
// If can not parse result as Json, will NOT throw error since user may return other info in auth-end page.
|
|
694
|
+
// TODO: resolve the result.
|
|
695
|
+
const failedToParseResult = "Failed to parse result to Json.";
|
|
696
|
+
internalLogger.verbose(failedToParseResult);
|
|
660
697
|
resolve();
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
// If code exists in result, user may using previous auth-start and auth-end page.
|
|
701
|
+
if (resultJson.code) {
|
|
702
|
+
const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
|
|
703
|
+
const usingPreviousAuthPage = "Found auth code in response. You may be using the latest TeamsFx SDK on an old project." +
|
|
704
|
+
`Please refer to the help link for how to fix the issue: ${helpLink}.`;
|
|
705
|
+
reject(new ErrorWithCode(usingPreviousAuthPage, ErrorCode.ProjectNeedUpgrade));
|
|
661
706
|
}
|
|
662
|
-
|
|
663
|
-
|
|
707
|
+
// If sessionStorage exists in result, set the values in current session storage.
|
|
708
|
+
if (resultJson.sessionStorage) {
|
|
709
|
+
this.setSessionStorage(resultJson.sessionStorage);
|
|
664
710
|
}
|
|
711
|
+
resolve();
|
|
665
712
|
},
|
|
666
713
|
failureCallback: (reason) => {
|
|
667
714
|
const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${reason}`;
|
|
@@ -696,7 +743,6 @@ class TeamsUserCredential {
|
|
|
696
743
|
*
|
|
697
744
|
* @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.
|
|
698
745
|
* @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.
|
|
699
|
-
* @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.
|
|
700
746
|
* @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
|
|
701
747
|
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
|
|
702
748
|
*
|
|
@@ -717,21 +763,47 @@ class TeamsUserCredential {
|
|
|
717
763
|
}
|
|
718
764
|
else {
|
|
719
765
|
internalLogger.info("Get access token with scopes: " + scopeStr);
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
766
|
+
if (!this.initialized) {
|
|
767
|
+
await this.init();
|
|
768
|
+
}
|
|
769
|
+
let tokenResponse;
|
|
770
|
+
const scopesArray = typeof scopes === "string" ? scopes.split(" ") : scopes;
|
|
771
|
+
const domain = window.location.origin;
|
|
772
|
+
// First try to get Access Token from cache.
|
|
773
|
+
try {
|
|
774
|
+
const account = this.msalInstance.getAccountByUsername(this.loginHint);
|
|
775
|
+
const scopesRequestForAcquireTokenSilent = {
|
|
776
|
+
scopes: scopesArray,
|
|
777
|
+
account: account !== null && account !== void 0 ? account : undefined,
|
|
778
|
+
redirectUri: `${domain}/blank-auth-end.html`,
|
|
779
|
+
};
|
|
780
|
+
tokenResponse = await this.msalInstance.acquireTokenSilent(scopesRequestForAcquireTokenSilent);
|
|
781
|
+
}
|
|
782
|
+
catch (error) {
|
|
783
|
+
const acquireTokenSilentFailedMessage = `Failed to call acquireTokenSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
|
|
784
|
+
internalLogger.verbose(acquireTokenSilentFailedMessage);
|
|
785
|
+
}
|
|
786
|
+
if (!tokenResponse) {
|
|
787
|
+
// If fail to get Access Token from cache, try to get Access token by silent login.
|
|
788
|
+
try {
|
|
789
|
+
const scopesRequestForSsoSilent = {
|
|
790
|
+
scopes: scopesArray,
|
|
791
|
+
loginHint: this.loginHint,
|
|
792
|
+
redirectUri: `${domain}/blank-auth-end.html`,
|
|
793
|
+
};
|
|
794
|
+
tokenResponse = await this.msalInstance.ssoSilent(scopesRequestForSsoSilent);
|
|
726
795
|
}
|
|
727
|
-
|
|
728
|
-
|
|
796
|
+
catch (error) {
|
|
797
|
+
const ssoSilentFailedMessage = `Failed to call ssoSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
|
|
798
|
+
internalLogger.verbose(ssoSilentFailedMessage);
|
|
729
799
|
}
|
|
730
800
|
}
|
|
731
|
-
|
|
732
|
-
|
|
801
|
+
if (!tokenResponse) {
|
|
802
|
+
const errorMsg = `Failed to get access token cache silently, please login first: you need login first before get access token.`;
|
|
803
|
+
internalLogger.error(errorMsg);
|
|
804
|
+
throw new ErrorWithCode(errorMsg, ErrorCode.UiRequiredError);
|
|
733
805
|
}
|
|
734
|
-
const accessToken =
|
|
806
|
+
const accessToken = parseAccessTokenFromAuthCodeTokenResponse(tokenResponse);
|
|
735
807
|
return accessToken;
|
|
736
808
|
}
|
|
737
809
|
}
|
|
@@ -756,65 +828,22 @@ class TeamsUserCredential {
|
|
|
756
828
|
const ssoToken = await this.getSSOToken();
|
|
757
829
|
return getUserInfoFromSsoToken(ssoToken.token);
|
|
758
830
|
}
|
|
759
|
-
async
|
|
760
|
-
|
|
761
|
-
const
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
this.setTokenCache(key, {
|
|
776
|
-
token: tokenResult.access_token,
|
|
777
|
-
expiresOnTimestamp: tokenResult.expires_on,
|
|
778
|
-
});
|
|
779
|
-
return;
|
|
780
|
-
}
|
|
781
|
-
catch (err) {
|
|
782
|
-
if (((_b = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.type) && err.response.data.type === "AadUiRequiredException") {
|
|
783
|
-
internalLogger.warn("Exchange access token failed, retry...");
|
|
784
|
-
if (retryCount < maxRetryCount) {
|
|
785
|
-
await this.sleep(retryTimeSpanInMillisecond);
|
|
786
|
-
retryCount++;
|
|
787
|
-
continue;
|
|
788
|
-
}
|
|
789
|
-
}
|
|
790
|
-
throw err;
|
|
791
|
-
}
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
/**
|
|
795
|
-
* Get access token cache from authentication server
|
|
796
|
-
* @returns Access token
|
|
797
|
-
*/
|
|
798
|
-
async getAndCacheAccessTokenFromSimpleAuthServer(scopesStr) {
|
|
799
|
-
try {
|
|
800
|
-
internalLogger.verbose("Get access token from authentication server with scopes: " + scopesStr);
|
|
801
|
-
const axiosInstance = await this.getAxiosInstance();
|
|
802
|
-
const response = await axiosInstance.post("/auth/token", {
|
|
803
|
-
scope: scopesStr,
|
|
804
|
-
grant_type: GrantType.ssoToken,
|
|
805
|
-
});
|
|
806
|
-
const accessTokenResult = response.data;
|
|
807
|
-
const accessToken = {
|
|
808
|
-
token: accessTokenResult.access_token,
|
|
809
|
-
expiresOnTimestamp: accessTokenResult.expires_on,
|
|
810
|
-
};
|
|
811
|
-
const cacheKey = await this.getAccessTokenCacheKey(scopesStr);
|
|
812
|
-
this.setTokenCache(cacheKey, accessToken);
|
|
813
|
-
return accessToken;
|
|
814
|
-
}
|
|
815
|
-
catch (err) {
|
|
816
|
-
throw this.generateAuthServerError(err);
|
|
817
|
-
}
|
|
831
|
+
async init() {
|
|
832
|
+
const ssoToken = await this.getSSOToken();
|
|
833
|
+
const info = getTenantIdAndLoginHintFromSsoToken(ssoToken.token);
|
|
834
|
+
this.loginHint = info.loginHint;
|
|
835
|
+
this.tid = info.tid;
|
|
836
|
+
const msalConfig = {
|
|
837
|
+
auth: {
|
|
838
|
+
clientId: this.config.clientId,
|
|
839
|
+
authority: `https://login.microsoftonline.com/${this.tid}`,
|
|
840
|
+
},
|
|
841
|
+
cache: {
|
|
842
|
+
cacheLocation: "sessionStorage",
|
|
843
|
+
},
|
|
844
|
+
};
|
|
845
|
+
this.msalInstance = new PublicClientApplication(msalConfig);
|
|
846
|
+
this.initialized = true;
|
|
818
847
|
}
|
|
819
848
|
/**
|
|
820
849
|
* Get SSO token using teams SDK
|
|
@@ -884,16 +913,13 @@ class TeamsUserCredential {
|
|
|
884
913
|
internalLogger.error(ErrorMessage.AuthenticationConfigurationNotExists);
|
|
885
914
|
throw new ErrorWithCode(ErrorMessage.AuthenticationConfigurationNotExists, ErrorCode.InvalidConfiguration);
|
|
886
915
|
}
|
|
887
|
-
if (config.initiateLoginEndpoint && config.
|
|
916
|
+
if (config.initiateLoginEndpoint && config.clientId) {
|
|
888
917
|
return config;
|
|
889
918
|
}
|
|
890
919
|
const missingValues = [];
|
|
891
920
|
if (!config.initiateLoginEndpoint) {
|
|
892
921
|
missingValues.push("initiateLoginEndpoint");
|
|
893
922
|
}
|
|
894
|
-
if (!config.simpleAuthEndpoint) {
|
|
895
|
-
missingValues.push("simpleAuthEndpoint");
|
|
896
|
-
}
|
|
897
923
|
if (!config.clientId) {
|
|
898
924
|
missingValues.push("clientId");
|
|
899
925
|
}
|
|
@@ -901,111 +927,20 @@ class TeamsUserCredential {
|
|
|
901
927
|
internalLogger.error(errorMsg);
|
|
902
928
|
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
|
|
903
929
|
}
|
|
904
|
-
|
|
905
|
-
* Get axios instance with sso token bearer header
|
|
906
|
-
* @returns AxiosInstance
|
|
907
|
-
*/
|
|
908
|
-
async getAxiosInstance() {
|
|
909
|
-
const ssoToken = await this.getSSOToken();
|
|
910
|
-
const axiosInstance = axios.create({
|
|
911
|
-
baseURL: this.config.simpleAuthEndpoint,
|
|
912
|
-
});
|
|
913
|
-
axiosInstance.interceptors.request.use((config) => {
|
|
914
|
-
config.headers.Authorization = "Bearer " + ssoToken.token;
|
|
915
|
-
return config;
|
|
916
|
-
});
|
|
917
|
-
return axiosInstance;
|
|
918
|
-
}
|
|
919
|
-
/**
|
|
920
|
-
* Set access token to cache
|
|
921
|
-
* @param key
|
|
922
|
-
* @param token
|
|
923
|
-
*/
|
|
924
|
-
setTokenCache(key, token) {
|
|
925
|
-
Cache.set(key, JSON.stringify(token));
|
|
926
|
-
}
|
|
927
|
-
/**
|
|
928
|
-
* Get access token from cache.
|
|
929
|
-
* If there is no cache or cannot be parsed, then it will return null
|
|
930
|
-
* @param key
|
|
931
|
-
* @returns Access token or null
|
|
932
|
-
*/
|
|
933
|
-
getTokenCache(key) {
|
|
934
|
-
const value = Cache.get(key);
|
|
935
|
-
if (value === null) {
|
|
936
|
-
return null;
|
|
937
|
-
}
|
|
938
|
-
const accessToken = this.validateAndParseJson(value);
|
|
939
|
-
return accessToken;
|
|
940
|
-
}
|
|
941
|
-
/**
|
|
942
|
-
* Parses passed value as JSON access token, if value is not a valid json string JSON.parse() will throw an error.
|
|
943
|
-
* @param jsonValue
|
|
944
|
-
*/
|
|
945
|
-
validateAndParseJson(jsonValue) {
|
|
930
|
+
setSessionStorage(sessonStorageValues) {
|
|
946
931
|
try {
|
|
947
|
-
const
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
* of the parsed value is necessary in order to be certain that the string represents a valid JSON object.
|
|
952
|
-
*
|
|
953
|
-
*/
|
|
954
|
-
return parsedJson && typeof parsedJson === "object" ? parsedJson : null;
|
|
932
|
+
const sessionStorageKeys = Object.keys(sessonStorageValues);
|
|
933
|
+
sessionStorageKeys.forEach((key) => {
|
|
934
|
+
sessionStorage.setItem(key, sessonStorageValues[key]);
|
|
935
|
+
});
|
|
955
936
|
}
|
|
956
937
|
catch (error) {
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
* @param scopesStr
|
|
963
|
-
* @returns Access token cache key, a key example: accessToken-userId-clientId-tenantId-scopes
|
|
964
|
-
*/
|
|
965
|
-
async getAccessTokenCacheKey(scopesStr) {
|
|
966
|
-
const ssoToken = await this.getSSOToken();
|
|
967
|
-
const ssoTokenObj = parseJwt(ssoToken.token);
|
|
968
|
-
const clientId = this.config.clientId;
|
|
969
|
-
const userObjectId = ssoTokenObj.oid;
|
|
970
|
-
const tenantId = ssoTokenObj.tid;
|
|
971
|
-
const key = [accessTokenCacheKeyPrefix, userObjectId, clientId, tenantId, scopesStr]
|
|
972
|
-
.join(separator)
|
|
973
|
-
.replace(/" "/g, "_");
|
|
974
|
-
return key;
|
|
975
|
-
}
|
|
976
|
-
/**
|
|
977
|
-
* Check whether the token is about to expire (within 5 minutes)
|
|
978
|
-
* @returns Boolean value indicate whether the token is about to expire
|
|
979
|
-
*/
|
|
980
|
-
isAccessTokenNearExpired(token) {
|
|
981
|
-
const expireDate = new Date(token.expiresOnTimestamp);
|
|
982
|
-
if (expireDate.getTime() - Date.now() > tokenRefreshTimeSpanInMillisecond) {
|
|
983
|
-
return false;
|
|
938
|
+
// Values in result.sessionStorage can not be set into session storage.
|
|
939
|
+
// Throw error since this may block user.
|
|
940
|
+
const errorMessage = `Failed to set values in session storage. Error: ${error.message}`;
|
|
941
|
+
internalLogger.error(errorMessage);
|
|
942
|
+
throw new ErrorWithCode(errorMessage, ErrorCode.InternalError);
|
|
984
943
|
}
|
|
985
|
-
return true;
|
|
986
|
-
}
|
|
987
|
-
generateAuthServerError(err) {
|
|
988
|
-
var _a, _b;
|
|
989
|
-
let errorMessage = err.message;
|
|
990
|
-
if ((_b = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.type) {
|
|
991
|
-
errorMessage = err.response.data.detail;
|
|
992
|
-
if (err.response.data.type === "AadUiRequiredException") {
|
|
993
|
-
const fullErrorMsg = "Failed to get access token from authentication server, please login first: " +
|
|
994
|
-
errorMessage;
|
|
995
|
-
internalLogger.warn(fullErrorMsg);
|
|
996
|
-
return new ErrorWithCode(fullErrorMsg, ErrorCode.UiRequiredError);
|
|
997
|
-
}
|
|
998
|
-
else {
|
|
999
|
-
const fullErrorMsg = "Failed to get access token from authentication server: " + errorMessage;
|
|
1000
|
-
internalLogger.error(fullErrorMsg);
|
|
1001
|
-
return new ErrorWithCode(fullErrorMsg, ErrorCode.ServiceError);
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
|
-
const fullErrorMsg = "Failed to get access token with error: " + errorMessage;
|
|
1005
|
-
return new ErrorWithCode(fullErrorMsg, ErrorCode.InternalError);
|
|
1006
|
-
}
|
|
1007
|
-
sleep(ms) {
|
|
1008
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1009
944
|
}
|
|
1010
945
|
}
|
|
1011
946
|
|
|
@@ -1133,174 +1068,25 @@ function createMicrosoftGraphClient(credential, scopes) {
|
|
|
1133
1068
|
|
|
1134
1069
|
// Copyright (c) Microsoft Corporation.
|
|
1135
1070
|
/**
|
|
1136
|
-
*
|
|
1071
|
+
* Generate connection configuration consumed by tedious.
|
|
1137
1072
|
* @remarks
|
|
1138
1073
|
* Only works in in server side.
|
|
1139
|
-
*
|
|
1140
1074
|
* @beta
|
|
1141
|
-
*
|
|
1142
1075
|
*/
|
|
1143
1076
|
class DefaultTediousConnectionConfiguration {
|
|
1144
1077
|
constructor() {
|
|
1145
|
-
|
|
1146
|
-
* MSSQL default scope
|
|
1147
|
-
* https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi
|
|
1148
|
-
*/
|
|
1149
|
-
this.defaultSQLScope = "https://database.windows.net/";
|
|
1078
|
+
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "DefaultTediousConnectionConfiguration"), ErrorCode.RuntimeNotSupported);
|
|
1150
1079
|
}
|
|
1151
1080
|
/**
|
|
1152
1081
|
* Generate connection configuration consumed by tedious.
|
|
1153
|
-
*
|
|
1154
|
-
*
|
|
1155
|
-
*
|
|
1156
|
-
* @throws {@link ErrorCode|InvalidConfiguration} when SQL config resource configuration is invalid.
|
|
1157
|
-
* @throws {@link ErrorCode|InternalError} when get user MSI token failed or MSI token is invalid.
|
|
1158
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
|
1159
|
-
*
|
|
1082
|
+
* @remarks
|
|
1083
|
+
* Only works in in server side.
|
|
1160
1084
|
* @beta
|
|
1161
1085
|
*/
|
|
1162
|
-
async getConfig() {
|
|
1163
|
-
|
|
1164
|
-
const configuration = getResourceConfiguration(ResourceType.SQL);
|
|
1165
|
-
if (!configuration) {
|
|
1166
|
-
const errMsg = "SQL resource configuration not exist";
|
|
1167
|
-
internalLogger.error(errMsg);
|
|
1168
|
-
throw new ErrorWithCode(errMsg, ErrorCode.InvalidConfiguration);
|
|
1169
|
-
}
|
|
1170
|
-
try {
|
|
1171
|
-
this.isSQLConfigurationValid(configuration);
|
|
1172
|
-
}
|
|
1173
|
-
catch (err) {
|
|
1174
|
-
throw err;
|
|
1175
|
-
}
|
|
1176
|
-
if (!this.isMsiAuthentication()) {
|
|
1177
|
-
const configWithUPS = this.generateDefaultConfig(configuration);
|
|
1178
|
-
internalLogger.verbose("SQL configuration with username and password generated");
|
|
1179
|
-
return configWithUPS;
|
|
1180
|
-
}
|
|
1181
|
-
try {
|
|
1182
|
-
const configWithToken = await this.generateTokenConfig(configuration);
|
|
1183
|
-
internalLogger.verbose("SQL configuration with MSI token generated");
|
|
1184
|
-
return configWithToken;
|
|
1185
|
-
}
|
|
1186
|
-
catch (error) {
|
|
1187
|
-
throw error;
|
|
1188
|
-
}
|
|
1189
|
-
}
|
|
1190
|
-
/**
|
|
1191
|
-
* Check SQL use MSI identity or username and password.
|
|
1192
|
-
*
|
|
1193
|
-
* @returns false - login with SQL MSI identity, true - login with username and password.
|
|
1194
|
-
* @internal
|
|
1195
|
-
*/
|
|
1196
|
-
isMsiAuthentication() {
|
|
1197
|
-
internalLogger.verbose("Check connection config using MSI access token or username and password");
|
|
1198
|
-
const configuration = getResourceConfiguration(ResourceType.SQL);
|
|
1199
|
-
if ((configuration === null || configuration === void 0 ? void 0 : configuration.sqlUsername) != null && (configuration === null || configuration === void 0 ? void 0 : configuration.sqlPassword) != null) {
|
|
1200
|
-
internalLogger.verbose("Login with username and password");
|
|
1201
|
-
return false;
|
|
1202
|
-
}
|
|
1203
|
-
internalLogger.verbose("Login with MSI identity");
|
|
1204
|
-
return true;
|
|
1205
|
-
}
|
|
1206
|
-
/**
|
|
1207
|
-
* check configuration is an available configurations.
|
|
1208
|
-
* @param { SqlConfiguration } sqlConfig
|
|
1209
|
-
*
|
|
1210
|
-
* @returns true - SQL configuration has a valid SQL endpoints, SQL username with password or identity ID.
|
|
1211
|
-
* false - configuration is not valid.
|
|
1212
|
-
* @internal
|
|
1213
|
-
*/
|
|
1214
|
-
isSQLConfigurationValid(sqlConfig) {
|
|
1215
|
-
internalLogger.verbose("Check SQL configuration if valid");
|
|
1216
|
-
if (!sqlConfig.sqlServerEndpoint) {
|
|
1217
|
-
internalLogger.error("SQL configuration is not valid without SQL server endpoint exist");
|
|
1218
|
-
throw new ErrorWithCode("SQL configuration error without SQL server endpoint exist", ErrorCode.InvalidConfiguration);
|
|
1219
|
-
}
|
|
1220
|
-
if (!(sqlConfig.sqlUsername && sqlConfig.sqlPassword) && !sqlConfig.sqlIdentityId) {
|
|
1221
|
-
const errMsg = `SQL configuration is not valid without ${sqlConfig.sqlIdentityId ? "" : "identity id "} ${sqlConfig.sqlUsername ? "" : "SQL username "} ${sqlConfig.sqlPassword ? "" : "SQL password"} exist`;
|
|
1222
|
-
internalLogger.error(errMsg);
|
|
1223
|
-
throw new ErrorWithCode(errMsg, ErrorCode.InvalidConfiguration);
|
|
1224
|
-
}
|
|
1225
|
-
internalLogger.verbose("SQL configuration is valid");
|
|
1226
|
-
}
|
|
1227
|
-
/**
|
|
1228
|
-
* Generate tedious connection configuration with default authentication type.
|
|
1229
|
-
*
|
|
1230
|
-
* @param { SqlConfiguration } SQL configuration with username and password.
|
|
1231
|
-
*
|
|
1232
|
-
* @returns Tedious connection configuration with username and password.
|
|
1233
|
-
* @internal
|
|
1234
|
-
*/
|
|
1235
|
-
generateDefaultConfig(sqlConfig) {
|
|
1236
|
-
internalLogger.verbose(`SQL server ${sqlConfig.sqlServerEndpoint}, user name ${sqlConfig.sqlUsername}, database name ${sqlConfig.sqlDatabaseName}`);
|
|
1237
|
-
const config = {
|
|
1238
|
-
server: sqlConfig.sqlServerEndpoint,
|
|
1239
|
-
authentication: {
|
|
1240
|
-
type: TediousAuthenticationType.default,
|
|
1241
|
-
options: {
|
|
1242
|
-
userName: sqlConfig.sqlUsername,
|
|
1243
|
-
password: sqlConfig.sqlPassword,
|
|
1244
|
-
},
|
|
1245
|
-
},
|
|
1246
|
-
options: {
|
|
1247
|
-
database: sqlConfig.sqlDatabaseName,
|
|
1248
|
-
encrypt: true,
|
|
1249
|
-
},
|
|
1250
|
-
};
|
|
1251
|
-
return config;
|
|
1252
|
-
}
|
|
1253
|
-
/**
|
|
1254
|
-
* Generate tedious connection configuration with azure-active-directory-access-token authentication type.
|
|
1255
|
-
*
|
|
1256
|
-
* @param { SqlConfiguration } SQL configuration with AAD access token.
|
|
1257
|
-
*
|
|
1258
|
-
* @returns Tedious connection configuration with access token.
|
|
1259
|
-
* @internal
|
|
1260
|
-
*/
|
|
1261
|
-
async generateTokenConfig(sqlConfig) {
|
|
1262
|
-
internalLogger.verbose("Generate tedious config with MSI token");
|
|
1263
|
-
let token;
|
|
1264
|
-
try {
|
|
1265
|
-
const credential = new ManagedIdentityCredential(sqlConfig.sqlIdentityId);
|
|
1266
|
-
token = await credential.getToken(this.defaultSQLScope);
|
|
1267
|
-
}
|
|
1268
|
-
catch (error) {
|
|
1269
|
-
const errMsg = "Get user MSI token failed";
|
|
1270
|
-
internalLogger.error(errMsg);
|
|
1271
|
-
throw new ErrorWithCode(errMsg, ErrorCode.InternalError);
|
|
1272
|
-
}
|
|
1273
|
-
if (token) {
|
|
1274
|
-
const config = {
|
|
1275
|
-
server: sqlConfig.sqlServerEndpoint,
|
|
1276
|
-
authentication: {
|
|
1277
|
-
type: TediousAuthenticationType.MSI,
|
|
1278
|
-
options: {
|
|
1279
|
-
token: token.token,
|
|
1280
|
-
},
|
|
1281
|
-
},
|
|
1282
|
-
options: {
|
|
1283
|
-
database: sqlConfig.sqlDatabaseName,
|
|
1284
|
-
encrypt: true,
|
|
1285
|
-
},
|
|
1286
|
-
};
|
|
1287
|
-
internalLogger.verbose(`Generate token configuration success, server endpoint is ${sqlConfig.sqlServerEndpoint}, database name is ${sqlConfig.sqlDatabaseName}`);
|
|
1288
|
-
return config;
|
|
1289
|
-
}
|
|
1290
|
-
internalLogger.error(`Generate token configuration, server endpoint is ${sqlConfig.sqlServerEndpoint}, MSI token is not valid`);
|
|
1291
|
-
throw new ErrorWithCode("MSI token is not valid", ErrorCode.InternalError);
|
|
1086
|
+
async getConfig(databaseName) {
|
|
1087
|
+
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "DefaultTediousConnectionConfiguration"), ErrorCode.RuntimeNotSupported);
|
|
1292
1088
|
}
|
|
1293
|
-
}
|
|
1294
|
-
/**
|
|
1295
|
-
* tedious connection config authentication type.
|
|
1296
|
-
* https://tediousjs.github.io/tedious/api-connection.html
|
|
1297
|
-
* @internal
|
|
1298
|
-
*/
|
|
1299
|
-
var TediousAuthenticationType;
|
|
1300
|
-
(function (TediousAuthenticationType) {
|
|
1301
|
-
TediousAuthenticationType["default"] = "default";
|
|
1302
|
-
TediousAuthenticationType["MSI"] = "azure-active-directory-access-token";
|
|
1303
|
-
})(TediousAuthenticationType || (TediousAuthenticationType = {}));
|
|
1089
|
+
}
|
|
1304
1090
|
|
|
1305
1091
|
// Copyright (c) Microsoft Corporation.
|
|
1306
1092
|
/**
|