wangzhibo
2026-05-09 53418655c061ac26f66058253f39200aced1ab1d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
 
import * as Constants from "../../utils/Constants.js";
import { Authority } from "../../authority/Authority.js";
import { ICrypto } from "../../crypto/ICrypto.js";
import { ClientInfo, buildClientInfo } from "../../account/ClientInfo.js";
import {
    AccountInfo,
    TenantProfile,
    buildTenantProfile,
    DataBoundary,
} from "../../account/AccountInfo.js";
import {
    createClientAuthError,
    ClientAuthErrorCodes,
} from "../../error/ClientAuthError.js";
import { AuthorityType } from "../../authority/AuthorityType.js";
import { Logger } from "../../logger/Logger.js";
import {
    TokenClaims,
    getTenantIdFromIdTokenClaims,
} from "../../account/TokenClaims.js";
import { ProtocolMode } from "../../authority/ProtocolMode.js";
import { AccountEntity } from "../entities/AccountEntity.js";
 
/**
 * Generate Account Id key component as per the schema: <home_account_id>-<environment>
 */
export function generateAccountId(accountEntity: AccountEntity): string {
    const accountId: Array<string> = [
        accountEntity.homeAccountId,
        accountEntity.environment,
    ];
    return accountId.join(Constants.CACHE_KEY_SEPARATOR).toLowerCase();
}
 
/**
 * Returns the AccountInfo interface for this account.
 */
export function getAccountInfo(accountEntity: AccountEntity): AccountInfo {
    const tenantProfiles = accountEntity.tenantProfiles || [];
    // Ensure at least the home tenant profile exists
    if (
        tenantProfiles.length === 0 &&
        accountEntity.realm &&
        accountEntity.localAccountId
    ) {
        tenantProfiles.push(
            buildTenantProfile(
                accountEntity.homeAccountId,
                accountEntity.localAccountId,
                accountEntity.realm
            )
        );
    }
    return {
        homeAccountId: accountEntity.homeAccountId,
        environment: accountEntity.environment,
        tenantId: accountEntity.realm,
        username: accountEntity.username,
        localAccountId: accountEntity.localAccountId,
        loginHint: accountEntity.loginHint,
        name: accountEntity.name,
        nativeAccountId: accountEntity.nativeAccountId,
        authorityType: accountEntity.authorityType,
        // Deserialize tenant profiles array into a Map
        tenantProfiles: new Map(
            tenantProfiles.map((tenantProfile) => {
                return [tenantProfile.tenantId, tenantProfile];
            })
        ),
        dataBoundary: accountEntity.dataBoundary,
    };
}
 
/**
 * Returns true if the account entity is in single tenant format (outdated), false otherwise
 */
export function isSingleTenant(accountEntity: AccountEntity): boolean {
    return !accountEntity.tenantProfiles;
}
 
/**
 * Build Account cache from IdToken, clientInfo and authority/policy. Associated with AAD.
 * @param accountDetails
 */
export function createAccountEntity(
    accountDetails: {
        homeAccountId: string;
        idTokenClaims?: TokenClaims;
        clientInfo?: string;
        cloudGraphHostName?: string;
        msGraphHost?: string;
        environment?: string;
        nativeAccountId?: string;
        tenantProfiles?: Array<TenantProfile>;
    },
    authority: Authority,
    base64Decode?: (input: string) => string
): AccountEntity {
    let authorityType;
    if (authority.authorityType === AuthorityType.Adfs) {
        authorityType = Constants.CACHE_ACCOUNT_TYPE_ADFS;
    } else if (authority.protocolMode === ProtocolMode.OIDC) {
        authorityType = Constants.CACHE_ACCOUNT_TYPE_GENERIC;
    } else {
        authorityType = Constants.CACHE_ACCOUNT_TYPE_MSSTS;
    }
 
    let clientInfo: ClientInfo | undefined;
    let dataBoundary: DataBoundary | undefined;
 
    if (accountDetails.clientInfo && base64Decode) {
        clientInfo = buildClientInfo(accountDetails.clientInfo, base64Decode);
        if (clientInfo.xms_tdbr) {
            dataBoundary = clientInfo.xms_tdbr === "EU" ? "EU" : "None";
        }
    }
 
    const env =
        accountDetails.environment ||
        (authority && authority.getPreferredCache());
 
    if (!env) {
        throw createClientAuthError(
            ClientAuthErrorCodes.invalidCacheEnvironment
        );
    }
 
    /*
     * In B2C scenarios the emails claim is used instead of preferred_username and it is an array.
     * In most cases it will contain a single email. This field should not be relied upon if a custom
     * policy is configured to return more than 1 email.
     */
    const preferredUsername =
        accountDetails.idTokenClaims?.preferred_username ||
        accountDetails.idTokenClaims?.upn;
    const email = accountDetails.idTokenClaims?.emails
        ? accountDetails.idTokenClaims.emails[0]
        : null;
 
    const username = preferredUsername || email || "";
 
    const loginHint = accountDetails.idTokenClaims?.login_hint;
 
    const realm =
        clientInfo?.utid ||
        getTenantIdFromIdTokenClaims(accountDetails.idTokenClaims) ||
        ""; // non-AAD scenarios can have empty realm
    // How do you account for MSA CID here?
    const localAccountId =
        clientInfo?.uid ||
        accountDetails.idTokenClaims?.oid ||
        accountDetails.idTokenClaims?.sub ||
        "";
    let tenantProfiles;
    if (accountDetails.tenantProfiles) {
        tenantProfiles = accountDetails.tenantProfiles;
    } else {
        const tenantProfile = buildTenantProfile(
            accountDetails.homeAccountId,
            localAccountId,
            realm,
            accountDetails.idTokenClaims
        );
        tenantProfiles = [tenantProfile];
    }
 
    return {
        homeAccountId: accountDetails.homeAccountId,
        environment: env,
        realm: realm,
        localAccountId: localAccountId,
        username: username,
        authorityType: authorityType,
        loginHint: loginHint,
        clientInfo: accountDetails.clientInfo,
        name: accountDetails.idTokenClaims?.name || "",
        lastModificationTime: undefined,
        lastModificationApp: undefined,
        cloudGraphHostName: accountDetails.cloudGraphHostName,
        msGraphHost: accountDetails.msGraphHost,
        nativeAccountId: accountDetails.nativeAccountId,
        tenantProfiles: tenantProfiles,
        dataBoundary,
    } as AccountEntity;
}
 
/**
 * Creates an AccountEntity object from AccountInfo
 * @param accountInfo
 * @param cloudGraphHostName
 * @param msGraphHost
 * @returns
 */
export function createAccountEntityFromAccountInfo(
    accountInfo: AccountInfo,
    cloudGraphHostName?: string,
    msGraphHost?: string
): AccountEntity {
    // Serialize tenant profiles map into an array
    const tenantProfiles = Array.from(
        accountInfo.tenantProfiles?.values() || []
    );
    // Ensure at least the home tenant profile exists
    if (
        tenantProfiles.length === 0 &&
        accountInfo.tenantId &&
        accountInfo.localAccountId
    ) {
        tenantProfiles.push(
            buildTenantProfile(
                accountInfo.homeAccountId,
                accountInfo.localAccountId,
                accountInfo.tenantId,
                accountInfo.idTokenClaims
            )
        );
    }
    return {
        authorityType:
            accountInfo.authorityType || Constants.CACHE_ACCOUNT_TYPE_GENERIC,
        homeAccountId: accountInfo.homeAccountId,
        localAccountId: accountInfo.localAccountId,
        nativeAccountId: accountInfo.nativeAccountId,
        realm: accountInfo.tenantId,
        environment: accountInfo.environment,
        username: accountInfo.username,
        loginHint: accountInfo.loginHint,
        name: accountInfo.name,
        cloudGraphHostName: cloudGraphHostName,
        msGraphHost: msGraphHost,
        tenantProfiles: tenantProfiles,
        dataBoundary: accountInfo.dataBoundary,
    } as AccountEntity;
}
 
/**
 * Generate HomeAccountId from server response
 * @param serverClientInfo
 * @param authType
 */
export function generateHomeAccountId(
    serverClientInfo: string,
    authType: AuthorityType,
    logger: Logger,
    cryptoObj: ICrypto,
    correlationId: string,
    idTokenClaims?: TokenClaims
): string {
    // since ADFS/DSTS do not have tid and does not set client_info
    if (!(authType === AuthorityType.Adfs || authType === AuthorityType.Dsts)) {
        // for cases where there is clientInfo
        if (serverClientInfo) {
            try {
                const clientInfo = buildClientInfo(
                    serverClientInfo,
                    cryptoObj.base64Decode
                );
                if (clientInfo.uid && clientInfo.utid) {
                    return `${clientInfo.uid}.${clientInfo.utid}`;
                }
            } catch (e) {}
        }
        logger.warning("No client info in response", correlationId);
    }
 
    // default to "sub" claim
    return idTokenClaims?.sub || "";
}
 
/**
 * Validates an entity: checks for all expected params
 * @param entity
 */
export function isAccountEntity(entity: object): entity is AccountEntity {
    if (!entity) {
        return false;
    }
 
    return (
        entity.hasOwnProperty("homeAccountId") &&
        entity.hasOwnProperty("environment") &&
        entity.hasOwnProperty("realm") &&
        entity.hasOwnProperty("localAccountId") &&
        entity.hasOwnProperty("username") &&
        entity.hasOwnProperty("authorityType")
    );
}