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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
 
import { CustomAuthApiError } from "../../core/error/CustomAuthApiError.js";
import * as CustomAuthApiErrorCode from "../../core/network_client/custom_auth_api/types/ApiErrorCodes.js";
import { UnexpectedError } from "../../core/error/UnexpectedError.js";
import { CustomAuthInteractionClientBase } from "../../core/interaction_client/CustomAuthInteractionClientBase.js";
import * as PublicApiId from "../../core/telemetry/PublicApiId.js";
import {
    ChallengeType,
    DefaultCustomAuthApiCodeLength,
    DefaultCustomAuthApiCodeResendIntervalInSec,
} from "../../CustomAuthConstants.js";
import {
    SignUpParamsBase,
    SignUpResendCodeParams,
    SignUpStartParams,
    SignUpSubmitCodeParams,
    SignUpSubmitPasswordParams,
    SignUpSubmitUserAttributesParams,
} from "./parameter/SignUpParams.js";
import {
    createSignUpAttributesRequiredResult,
    createSignUpCodeRequiredResult,
    createSignUpCompletedResult,
    createSignUpPasswordRequiredResult,
    SIGN_UP_ATTRIBUTES_REQUIRED_RESULT_TYPE,
    SIGN_UP_CODE_REQUIRED_RESULT_TYPE,
    SIGN_UP_PASSWORD_REQUIRED_RESULT_TYPE,
    SignUpAttributesRequiredResult,
    SignUpCodeRequiredResult,
    SignUpCompletedResult,
    SignUpPasswordRequiredResult,
} from "./result/SignUpActionResult.js";
import {
    SignUpChallengeRequest,
    SignUpContinueWithAttributesRequest,
    SignUpContinueWithOobRequest,
    SignUpContinueWithPasswordRequest,
    SignUpStartRequest,
} from "../../core/network_client/custom_auth_api/types/ApiRequestTypes.js";
import { SignUpContinueResponse } from "../../core/network_client/custom_auth_api/types/ApiResponseTypes.js";
import { ServerTelemetryManager } from "@azure/msal-common/browser";
import { initializeServerTelemetryManager } from "../../../interaction_client/BaseInteractionClient.js";
 
export class SignUpClient extends CustomAuthInteractionClientBase {
    /**
     * Starts the sign up flow.
     * @param parameters The parameters for the sign up start action.
     * @returns The result of the sign up start action.
     */
    async start(
        parameters: SignUpStartParams
    ): Promise<SignUpPasswordRequiredResult | SignUpCodeRequiredResult> {
        const correlationId = parameters.correlationId || this.correlationId;
        const apiId = !parameters.password
            ? PublicApiId.SIGN_UP_START
            : PublicApiId.SIGN_UP_WITH_PASSWORD_START;
        const telemetryManager = initializeServerTelemetryManager(
            apiId,
            this.config.auth.clientId,
            correlationId,
            this.browserStorage,
            this.logger
        );
 
        const startRequest: SignUpStartRequest = {
            username: parameters.username,
            password: parameters.password,
            attributes: parameters.attributes,
            challenge_type: this.getChallengeTypes(parameters.challengeType),
            telemetryManager,
            correlationId: correlationId,
        };
 
        this.logger.verbose(
            "Calling start endpoint for sign up.",
            correlationId
        );
 
        const startResponse = await this.customAuthApiClient.signUpApi.start(
            startRequest
        );
 
        this.logger.verbose(
            "Start endpoint called for sign up.",
            startResponse.correlation_id || correlationId
        );
 
        const challengeRequest: SignUpChallengeRequest = {
            continuation_token: startResponse.continuation_token ?? "",
            challenge_type: this.getChallengeTypes(parameters.challengeType),
            telemetryManager,
            correlationId: startResponse.correlation_id || correlationId,
        };
 
        return this.performChallengeRequest(challengeRequest);
    }
 
    /**
     * Submits the code for the sign up flow.
     * @param parameters The parameters for the sign up submit code action.
     * @returns The result of the sign up submit code action.
     */
    async submitCode(
        parameters: SignUpSubmitCodeParams
    ): Promise<
        | SignUpCompletedResult
        | SignUpPasswordRequiredResult
        | SignUpAttributesRequiredResult
    > {
        const correlationId = parameters.correlationId || this.correlationId;
        const apiId = PublicApiId.SIGN_UP_SUBMIT_CODE;
        const telemetryManager = initializeServerTelemetryManager(
            apiId,
            this.config.auth.clientId,
            correlationId,
            this.browserStorage,
            this.logger
        );
 
        const requestSubmitCode: SignUpContinueWithOobRequest = {
            continuation_token: parameters.continuationToken,
            oob: parameters.code,
            telemetryManager,
            correlationId: correlationId,
        };
 
        const result = await this.performContinueRequest(
            "SignUpClient.submitCode",
            parameters,
            telemetryManager,
            () =>
                this.customAuthApiClient.signUpApi.continueWithCode(
                    requestSubmitCode
                ),
            correlationId
        );
 
        if (result.type === SIGN_UP_CODE_REQUIRED_RESULT_TYPE) {
            throw new CustomAuthApiError(
                CustomAuthApiErrorCode.UNSUPPORTED_CHALLENGE_TYPE,
                "The challenge type 'oob' is invalid after submtting code for sign up.",
                result.correlationId || correlationId
            );
        }
 
        return result;
    }
 
    /**
     * Submits the password for the sign up flow.
     * @param parameters The parameters for the sign up submit password action.
     * @returns The result of the sign up submit password action.
     */
    async submitPassword(
        parameters: SignUpSubmitPasswordParams
    ): Promise<
        | SignUpCompletedResult
        | SignUpCodeRequiredResult
        | SignUpAttributesRequiredResult
    > {
        const correlationId = parameters.correlationId || this.correlationId;
        const apiId = PublicApiId.SIGN_UP_SUBMIT_PASSWORD;
        const telemetryManager = initializeServerTelemetryManager(
            apiId,
            this.config.auth.clientId,
            correlationId,
            this.browserStorage,
            this.logger
        );
 
        const requestSubmitPwd: SignUpContinueWithPasswordRequest = {
            continuation_token: parameters.continuationToken,
            password: parameters.password,
            telemetryManager,
            correlationId: correlationId,
        };
 
        const result = await this.performContinueRequest(
            "SignUpClient.submitPassword",
            parameters,
            telemetryManager,
            () =>
                this.customAuthApiClient.signUpApi.continueWithPassword(
                    requestSubmitPwd
                ),
            correlationId
        );
 
        if (result.type === SIGN_UP_PASSWORD_REQUIRED_RESULT_TYPE) {
            throw new CustomAuthApiError(
                CustomAuthApiErrorCode.UNSUPPORTED_CHALLENGE_TYPE,
                "The challenge type 'password' is invalid after submtting password for sign up.",
                result.correlationId || correlationId
            );
        }
 
        return result;
    }
 
    /**
     * Submits the attributes for the sign up flow.
     * @param parameters The parameters for the sign up submit attributes action.
     * @returns The result of the sign up submit attributes action.
     */
    async submitAttributes(
        parameters: SignUpSubmitUserAttributesParams
    ): Promise<
        | SignUpCompletedResult
        | SignUpPasswordRequiredResult
        | SignUpCodeRequiredResult
    > {
        const correlationId = parameters.correlationId || this.correlationId;
        const apiId = PublicApiId.SIGN_UP_SUBMIT_ATTRIBUTES;
        const telemetryManager = initializeServerTelemetryManager(
            apiId,
            this.config.auth.clientId,
            correlationId,
            this.browserStorage,
            this.logger
        );
        const reqWithAttr: SignUpContinueWithAttributesRequest = {
            continuation_token: parameters.continuationToken,
            attributes: parameters.attributes,
            telemetryManager,
            correlationId: correlationId,
        };
 
        const result = await this.performContinueRequest(
            "SignUpClient.submitAttributes",
            parameters,
            telemetryManager,
            () =>
                this.customAuthApiClient.signUpApi.continueWithAttributes(
                    reqWithAttr
                ),
            correlationId
        );
 
        if (result.type === SIGN_UP_ATTRIBUTES_REQUIRED_RESULT_TYPE) {
            throw new CustomAuthApiError(
                CustomAuthApiErrorCode.ATTRIBUTES_REQUIRED,
                "User attributes required",
                result.correlationId || correlationId,
                [],
                "",
                result.requiredAttributes,
                result.continuationToken
            );
        }
 
        return result;
    }
 
    /**
     * Resends the code for the sign up flow.
     * @param parameters The parameters for the sign up resend code action.
     * @returns The result of the sign up resend code action.
     */
    async resendCode(
        parameters: SignUpResendCodeParams
    ): Promise<SignUpCodeRequiredResult> {
        const correlationId = parameters.correlationId || this.correlationId;
        const apiId = PublicApiId.SIGN_UP_RESEND_CODE;
        const telemetryManager = initializeServerTelemetryManager(
            apiId,
            this.config.auth.clientId,
            correlationId,
            this.browserStorage,
            this.logger
        );
 
        const challengeRequest: SignUpChallengeRequest = {
            continuation_token: parameters.continuationToken ?? "",
            challenge_type: this.getChallengeTypes(parameters.challengeType),
            telemetryManager,
            correlationId: correlationId,
        };
 
        const result = await this.performChallengeRequest(challengeRequest);
 
        if (result.type === SIGN_UP_PASSWORD_REQUIRED_RESULT_TYPE) {
            throw new CustomAuthApiError(
                CustomAuthApiErrorCode.UNSUPPORTED_CHALLENGE_TYPE,
                "The challenge type 'password' is invalid after resending code for sign up.",
                result.correlationId || correlationId
            );
        }
 
        return result;
    }
 
    private async performChallengeRequest(
        request: SignUpChallengeRequest
    ): Promise<SignUpPasswordRequiredResult | SignUpCodeRequiredResult> {
        this.logger.verbose(
            "Calling challenge endpoint for sign up.",
            request.correlationId
        );
 
        const challengeResponse =
            await this.customAuthApiClient.signUpApi.requestChallenge(request);
 
        this.logger.verbose(
            "Challenge endpoint called for sign up.",
            challengeResponse.correlation_id || request.correlationId
        );
 
        if (challengeResponse.challenge_type === ChallengeType.OOB) {
            // Code is required
            this.logger.verbose(
                "Challenge type is oob for sign up.",
                challengeResponse.correlation_id || request.correlationId
            );
 
            return createSignUpCodeRequiredResult({
                correlationId:
                    challengeResponse.correlation_id || request.correlationId,
                continuationToken: challengeResponse.continuation_token ?? "",
                challengeChannel: challengeResponse.challenge_channel ?? "",
                challengeTargetLabel:
                    challengeResponse.challenge_target_label ?? "",
                codeLength:
                    challengeResponse.code_length ??
                    DefaultCustomAuthApiCodeLength,
                interval:
                    challengeResponse.interval ??
                    DefaultCustomAuthApiCodeResendIntervalInSec,
                bindingMethod: challengeResponse.binding_method ?? "",
            });
        }
 
        if (challengeResponse.challenge_type === ChallengeType.PASSWORD) {
            // Password is required
            this.logger.verbose(
                "Challenge type is password for sign up.",
                challengeResponse.correlation_id || request.correlationId
            );
 
            return createSignUpPasswordRequiredResult({
                correlationId:
                    challengeResponse.correlation_id || request.correlationId,
                continuationToken: challengeResponse.continuation_token ?? "",
            });
        }
 
        this.logger.error(
            `Unsupported challenge type '${challengeResponse.challenge_type}' for sign up.`,
            challengeResponse.correlation_id || request.correlationId
        );
 
        throw new CustomAuthApiError(
            CustomAuthApiErrorCode.UNSUPPORTED_CHALLENGE_TYPE,
            `Unsupported challenge type '${challengeResponse.challenge_type}'.`,
            challengeResponse.correlation_id || request.correlationId
        );
    }
 
    private async performContinueRequest(
        callerName: string,
        requestParams: SignUpParamsBase,
        telemetryManager: ServerTelemetryManager,
        responseGetter: () => Promise<SignUpContinueResponse>,
        requestCorrelationId: string
    ): Promise<
        | SignUpCompletedResult
        | SignUpPasswordRequiredResult
        | SignUpCodeRequiredResult
        | SignUpAttributesRequiredResult
    > {
        this.logger.verbose(
            `'${callerName}' is calling continue endpoint for sign up.`,
            requestCorrelationId
        );
 
        try {
            const response = await responseGetter();
 
            this.logger.verbose(
                `Continue endpoint called by '${callerName}' for sign up.`,
                response.correlation_id || requestCorrelationId
            );
 
            return createSignUpCompletedResult({
                correlationId: response.correlation_id || requestCorrelationId,
                continuationToken: response.continuation_token ?? "",
            });
        } catch (error) {
            if (error instanceof CustomAuthApiError) {
                return this.handleContinueResponseError(
                    error,
                    error.correlationId || requestCorrelationId,
                    requestParams,
                    telemetryManager
                );
            } else {
                this.logger.errorPii(
                    `'${callerName}' is failed to call continue endpoint for sign up. Error: '${error}'`,
                    requestCorrelationId
                );
 
                throw new UnexpectedError(error, requestCorrelationId);
            }
        }
    }
 
    private async handleContinueResponseError(
        responseError: CustomAuthApiError,
        correlationId: string,
        requestParams: SignUpParamsBase,
        telemetryManager: ServerTelemetryManager
    ): Promise<
        | SignUpPasswordRequiredResult
        | SignUpCodeRequiredResult
        | SignUpAttributesRequiredResult
    > {
        if (
            responseError.error ===
                CustomAuthApiErrorCode.CREDENTIAL_REQUIRED &&
            !!responseError.errorCodes &&
            responseError.errorCodes.includes(55103)
        ) {
            // Credential is required
            this.logger.verbose(
                "The credential is required in the sign up flow.",
                correlationId
            );
 
            const continuationToken =
                this.readContinuationTokenFromResponeError(
                    responseError,
                    correlationId
                );
 
            // Call the challenge endpoint to ensure the password challenge type is supported.
            const challengeRequest: SignUpChallengeRequest = {
                continuation_token: continuationToken,
                challenge_type: this.getChallengeTypes(
                    requestParams.challengeType
                ),
                telemetryManager,
                correlationId,
            };
 
            const challengeResult = await this.performChallengeRequest(
                challengeRequest
            );
 
            if (
                challengeResult.type === SIGN_UP_PASSWORD_REQUIRED_RESULT_TYPE
            ) {
                return createSignUpPasswordRequiredResult({
                    correlationId:
                        challengeResult.correlationId || correlationId,
                    continuationToken: challengeResult.continuationToken,
                });
            }
 
            if (challengeResult.type === SIGN_UP_CODE_REQUIRED_RESULT_TYPE) {
                return createSignUpCodeRequiredResult({
                    correlationId:
                        challengeResult.correlationId || correlationId,
                    continuationToken: challengeResult.continuationToken,
                    challengeChannel: challengeResult.challengeChannel,
                    challengeTargetLabel: challengeResult.challengeTargetLabel,
                    codeLength: challengeResult.codeLength,
                    interval: challengeResult.interval,
                    bindingMethod: challengeResult.bindingMethod,
                });
            }
 
            throw new CustomAuthApiError(
                CustomAuthApiErrorCode.UNSUPPORTED_CHALLENGE_TYPE,
                "The challenge type is not supported.",
                correlationId
            );
        }
 
        if (this.isAttributesRequiredError(responseError, correlationId)) {
            // Attributes are required
            this.logger.verbose(
                "Attributes are required in the sign up flow.",
                correlationId
            );
 
            const continuationToken =
                this.readContinuationTokenFromResponeError(
                    responseError,
                    correlationId
                );
 
            return createSignUpAttributesRequiredResult({
                correlationId: correlationId,
                continuationToken: continuationToken,
                requiredAttributes: responseError.attributes ?? [],
            });
        }
 
        throw responseError;
    }
 
    private isAttributesRequiredError(
        responseError: CustomAuthApiError,
        correlationId: string
    ): boolean {
        if (
            responseError.error === CustomAuthApiErrorCode.ATTRIBUTES_REQUIRED
        ) {
            if (
                !responseError.attributes ||
                responseError.attributes.length === 0
            ) {
                throw new CustomAuthApiError(
                    CustomAuthApiErrorCode.INVALID_RESPONSE_BODY,
                    "Attributes are required but required_attributes field is missing in the response body.",
                    correlationId
                );
            }
 
            return true;
        }
 
        return false;
    }
 
    private readContinuationTokenFromResponeError(
        responseError: CustomAuthApiError,
        correlationId: string
    ): string {
        if (!responseError.continuationToken) {
            throw new CustomAuthApiError(
                CustomAuthApiErrorCode.CONTINUATION_TOKEN_MISSING,
                "Continuation token is missing in the response body",
                correlationId
            );
        }
 
        return responseError.continuationToken;
    }
}