All files / lib/icloud icloud.ts

100% Statements 618/618
97.12% Branches 135/139
100% Functions 23/23
100% Lines 618/618

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 6181x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 455x 455x 455x 455x 1x 1x 1x 1x 1x 1x 1x 1x 455x 455x 455x 455x 455x 455x 455x 455x 455x 2x 2x 2x 2x 455x 455x 1x 455x 455x 1x 455x 455x 1x 455x 455x 1x 455x 455x 1x 455x 455x 1x 1x 1x 1x 1x 1x 117x 117x 117x 117x 117x 117x 117x 117x 6x 6x 117x 117x 1x 1x 117x 117x 111x 111x 117x 117x 117x 1x 1x 1x 1x 1x 1x 1x 1x 1x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 26x 26x 20x 20x 20x 20x 52x 12x 12x 8x 8x 8x 8x 52x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 52x 52x 52x 52x 36x 8x 8x 8x 28x 36x 24x 24x 4x 4x 24x 12x 12x 12x 12x 24x 4x 4x 24x 4x 24x 24x 24x 24x 4x 4x 4x 52x 52x 52x 52x 52x 52x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 12x 8x 8x 12x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 18x 18x 18x 18x 18x 18x 18x 18x 18x 20x 20x 20x 20x 20x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 18x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 16x 8x 8x 8x 6x 6x 6x 6x 6x 6x 22x 12x 12x 22x 1x 1x 1x 1x 1x 1x 1x 1x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 48x 74x 42x 42x 42x 18x 18x 18x 6x 6x 18x 18x 18x 24x 24x 24x 42x 4x 2x 42x 28x 28x 28x 28x 28x 28x 28x 28x 74x 46x 20x 20x 20x 26x 46x 20x 20x 20x 20x 20x 20x 20x 20x 6x 6x 6x 74x 1x 1x 1x 1x 1x 1x 1x 46x 46x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 8x 6x 6x 8x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 1x 1x 1x 1x 1x 1x 1x 32x 32x 32x 32x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x 2x 2x 2x 6x 4x 4x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 10x 10x 10x 16x 6x 6x 6x 6x 6x 4x 16x 2x 2x 2x 2x 2x 2x 2x 16x 12x 2x 2x 2x 2x 10x 10x 10x 16x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 8x 14x 2x 2x 2x 2x 2x 6x 6x 14x 4x 4x 2x 2x 2x 14x 10x 10x 10x 2x 2x 10x 10x 10x 14x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x 2x 6x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 6x 6x 10x 1x
import {jsonc} from 'jsonc';
import {AUTH_ERR, ICLOUD_PHOTOS_ERR, MFA_ERR} from '../../app/error/error-codes.js';
import {iCPSError} from '../../app/error/error.js';
import {iCPSEventCloud, iCPSEventMFA, iCPSEventPhotos, iCPSEventRuntimeWarning} from '../resources/events-types.js';
import {HttpRequestConfig, HttpResponse, isHttpError} from '../resources/http-client.js';
import {Resources} from '../resources/main.js';
import {COOKIE_KEYS, ENDPOINTS, TrustedPhoneNumber} from '../resources/network-types.js';
import {iCloudPhotos} from './icloud-photos/icloud-photos.js';
import {iCloudCrypto} from './icloud.crypto.js';
import {MFAMethod} from './mfa/mfa-method.js';
 
/**
 * This class holds the iCloud connection
 */
/**
 * The service error code returned by the backend, if an incorrect MFA code was entered
 */
const MFA_INCORRECT_CODE_ERROR = `-21669`;
 
/**
 * The service error code returned by the backend, if the account has been locked for security reasons
 */
const ACCOUNT_LOCKED_ERROR = `-20209`;
 
export class iCloud {
    /**
     * Access to the iCloud Photos service
     */
    photos: iCloudPhotos;
 
    /**
     * Timeout for MFA code submission - set while waiting for an MFA code
     */
    mfaTimeout?: NodeJS.Timeout;
 
    /**
     * Creates a new iCloud Object
     * @param ignoreFailOnMfa - If set to true, the authentication will still continue even if MFA is required and the failOnMfa flag is set
     * @emits iCPSEventCloud.ERROR - If the MFA code is required and the failOnMfa flag is set - the iCPSError is provided as argument
     */
    constructor() {
        Resources.events(this)
            .on(iCPSEventMFA.MFA_RECEIVED, this.submitMFA.bind(this))
            .on(iCPSEventMFA.MFA_RESEND, this.resendMFA.bind(this));
 
        this.photos = new iCloudPhotos();
 
        // ICloud lifecycle management
        Resources.events(this)
            .on(iCPSEventCloud.MFA_REQUIRED, () => {
                // MFA code needs to be provided within timeout period
                this.mfaTimeout = setTimeout(() => {
                    Resources.emit(iCPSEventMFA.MFA_NOT_PROVIDED, new iCPSError(MFA_ERR.MFA_TIMEOUT));
                }, Resources.manager().mfaTimeout * 1000);
            })
            .on(iCPSEventCloud.TRUSTED, async () => {
                await this.setupAccount();
            })
            .on(iCPSEventCloud.AUTHENTICATED, async () => {
                await this.getTokens();
            })
            .on(iCPSEventCloud.ACCOUNT_READY, async () => {
                await this.getPhotosReady();
            })
            .on(iCPSEventCloud.SESSION_EXPIRED, async () => {
                await this.authenticate();
            })
            .on(iCPSEventCloud.PCS_REQUIRED, async () => {
                await this.acquirePCSCookies();
            });
    }
 
    /**
     *
     * @returns A promise that will resolve to true, if the connection was established successfully, false in case the MFA code was not provided in time or reject, in case there is an error
     */
    getReady(): Promise<boolean> {
        return new Promise<boolean>((resolve, reject) => {
            const timeout = setTimeout(
                () => reject(new iCPSError(AUTH_ERR.SETUP_TIMEOUT)),
                (Resources.manager().mfaTimeout * 1000) + (1000 * 60 * 5), // 5 minutes on top of mfa timeout (in seconds) should be sufficient
            );
 
            Resources.events(this)
                .once(iCPSEventPhotos.READY, () => {
                    clearTimeout(timeout);
                    resolve(true);
                })
                .once(iCPSEventMFA.MFA_NOT_PROVIDED, () => {
                    clearTimeout(timeout);
                    resolve(false);
                })
                .once(iCPSEventCloud.ERROR, err => {
                    clearTimeout(timeout);
                    reject(err);
                });
        });
    }
 
    /**
     * Initiates authentication flow. Tries to directly login using trustToken, otherwise starts MFA flow
     * @emits iCPSEventCloud.AUTHENTICATION_STARTED - When authentication is started
     * @emits iCPSEventCloud.MFA_REQUIRED - When MFA is required
     * @emits iCPSEventCloud.TRUSTED - When device is trusted - provides trust token as argument
     * @emits iCPSEventCloud.ERROR - When an error occurs - provides iCPSError as argument
     */
    async authenticate(): Promise<boolean> {
        const ready = this.getReady();
        Resources.logger(this).info(`Authenticating user`);
        Resources.emit(iCPSEventCloud.AUTHENTICATION_STARTED);
 
        const config: HttpRequestConfig = {
            params: {
                isRememberMeEnabled: `true`,
            },
            // 409 is expected, if MFA is required - 200 is expected, if authentication succeeds immediately
            validateStatus: status => status === 409 || status === 200,
        };
 
        try {
            const [url, data] = Resources.manager().legacyLogin
                ? this.getLegacyLogin()
                : await this.getSRPLogin();
 
            const response = await Resources.network().post(url, data, Resources.validator().response.signin, config);
            Resources.network().applySigninResponse(response);
 
            Resources.logger(this).debug(`Acquired signin secrets`);
 
            if (response.status === 409 && this.requiresEscrow(response)) {
                Resources.logger(this).debug(`Response status is 409, trust token accepted but escrow required`);
                await this.completeEscrow();
                Resources.emit(iCPSEventCloud.TRUSTED, Resources.manager().trustToken);
                return ready;
            }
 
            if (response.status === 409) {
                Resources.logger(this).debug(`Response status is 409, requiring MFA`);
                const trustedPhoneNumbers = await this.getTrustedPhoneNumbers();
                // Since iOS 26.4 the MFA code is no longer pushed to trusted devices automatically
                await this.resendMFA(new MFAMethod(`device`));
                Resources.emit(iCPSEventCloud.MFA_REQUIRED, trustedPhoneNumbers);
                return ready;
            }
 
            if (response.status === 200) {
                Resources.logger(this).debug(`Response status is 200, authentication successful - device trusted`);
                Resources.emit(iCPSEventCloud.TRUSTED, Resources.manager().trustToken);
            }
 
            // This should never happen
            // Resources.emit(iCPSEventCloud.ERROR, new iCPSError(AUTH_ERR.ACQUIRE_AUTH_SECRETS));
        } catch (err) {
            if (err instanceof iCPSError) {
                Resources.emit(iCPSEventCloud.ERROR, err);
                return ready;
            }
 
            if (isHttpError(err)) {
                switch (err.response?.status) {
                case 401:
                    Resources.emit(iCPSEventCloud.ERROR, new iCPSError(AUTH_ERR.UNAUTHORIZED).addCause(err));
                    break;
                case 403:
                    Resources.emit(iCPSEventCloud.ERROR, new iCPSError(this.hasServiceError(err.response?.data, ACCOUNT_LOCKED_ERROR) ? AUTH_ERR.ACCOUNT_LOCKED : AUTH_ERR.FORBIDDEN)
                        .addMessage(...this.getServiceErrors(err.response?.data).map(serviceError => serviceError?.message))
                        .addCause(err));
                    break;
                case 412:
                    Resources.emit(iCPSEventCloud.ERROR, new iCPSError(AUTH_ERR.PRECONDITION_FAILED).addCause(err));
                    break;
                default:
                    Resources.emit(iCPSEventCloud.ERROR, new iCPSError(AUTH_ERR.UNEXPECTED_RESPONSE).addCause(err));
                }
 
                return ready;
            }
 
            Resources.emit(iCPSEventCloud.ERROR, new iCPSError(AUTH_ERR.UNKNOWN).addCause(err));
            return ready;
        } finally {
            // Return in finally is required because control flow of try/catch block is complicated
            // eslint-disable-next-line no-unsafe-finally
            return ready;
        }
    }
 
    /**
     * Generates the legacy plain-text login payload and url
     * @returns A tuple containing the url and payload required for the legacy login method
     */
    getLegacyLogin(): [url: string, payload: any] {
        Resources.logger(this).info(`Generating plain text login payload`);
        return [
            ENDPOINTS.AUTH.BASE + ENDPOINTS.AUTH.PATH.SIGNIN.LEGACY,
            {
                accountName: Resources.manager().username,
                password: Resources.manager().password,
                trustTokens: [
                    Resources.manager().trustToken,
                ],
            },
        ];
    }
 
    /**
     * Generates the SRP login payload and url from the iCloud server challenge
     * @param authenticator - The authenticator crypto instance for generating the SRP proof - parameterized for testing purposes, will be initiated by default
     * @returns A tuple containing the url and payload required for the SRP login method
     */
    async getSRPLogin(authenticator: iCloudCrypto = new iCloudCrypto()): Promise<[url: string, payload: any]> {
        Resources.logger(this).info(`Generating SRP challenge`);
        try {
            const validatedInitResponse = await Resources.network().post(ENDPOINTS.AUTH.BASE + ENDPOINTS.AUTH.PATH.SIGNIN.INIT, {
                a: await authenticator.getClientEphemeral(),
                accountName: Resources.manager().username,
                protocols: [
                    `s2k`,
                    `s2k_fo`,
                ],
            }, Resources.validator().response.signinInit);
 
            const derivedPassword = await authenticator.derivePassword(validatedInitResponse.data.protocol, validatedInitResponse.data.salt, validatedInitResponse.data.iteration);
            const [m1Proof, m2Proof] = await authenticator.getProofValues(derivedPassword, validatedInitResponse.data.b, validatedInitResponse.data.salt);
 
            return [
                ENDPOINTS.AUTH.BASE + ENDPOINTS.AUTH.PATH.SIGNIN.COMPLETE,
                {
                    accountName: Resources.manager().username,
                    trustTokens: [
                        Resources.manager().trustToken,
                    ],
                    m1: m1Proof,
                    m2: m2Proof,
                    c: validatedInitResponse.data.c,
                },
            ];
        } catch (err) {
            throw new iCPSError(AUTH_ERR.SRP_INIT_FAILED).addCause(err);
        }
    }
 
    /**
     * Fetches the trusted phone numbers of the account, which can be used to receive MFA codes via sms or voice
     * The backend either provides the information as JSON, or embedded in the HTML 'boot_args' of the iCloud web frontend
     * @returns The list of trusted phone numbers, or an empty array if they could not be retrieved
     * @emits iCPSEventRuntimeWarning.TRUSTED_PHONE_NUMBERS_ERROR - When the phone numbers could not be retrieved - provides iCPSError as argument
     */
    async getTrustedPhoneNumbers(): Promise<TrustedPhoneNumber[]> {
        Resources.logger(this).info(`Getting trusted phone numbers`);
 
        try {
            const validatedAuthInformationResponse = await Resources.network().get(ENDPOINTS.AUTH.BASE, Resources.validator().response.authInformation(response => {
                const authInformation = typeof response.data === `string`
                    ? this.extractBootArgsFromHTML(response.data)?.direct?.twoSV
                    : response.data;
 
                return {
                    data: {
                        trustedPhoneNumbers: this.findTrustedPhoneNumbers(authInformation),
                    },
                };
            }), {
                headers: {
                    Accept: `application/json`,
                },
            });
            Resources.logger(this).debug(`Found ${validatedAuthInformationResponse.data.trustedPhoneNumbers.length} trusted phone number(s)`);
            return validatedAuthInformationResponse.data.trustedPhoneNumbers;
        } catch (err) {
            Resources.emit(iCPSEventRuntimeWarning.TRUSTED_PHONE_NUMBERS_ERROR, new iCPSError(MFA_ERR.NO_PHONE_NUMBERS).addCause(err));
        }
 
        return [];
    }
 
    /**
     * Locates the list of trusted phone numbers within the auth information provided by the backend
     * Depending on the account and flow, the list is provided on top level, nested in the phone number verification object or (since iOS 26.4) nested in the bridge's initiate data
     * @param authInformation - The auth information object provided by the backend
     * @returns The list of trusted phone numbers, or undefined if it could not be found
     */
    findTrustedPhoneNumbers(authInformation: any): unknown {
        return authInformation?.trustedPhoneNumbers
            ?? authInformation?.phoneNumberVerification?.trustedPhoneNumbers
            ?? authInformation?.bridgeInitiateData?.phoneNumberVerification?.trustedPhoneNumbers;
    }
 
    /**
     * Extracts the 'boot_args' object from the HTML document of the iCloud web frontend
     * @param html - The HTML document returned by the backend
     * @returns The parsed 'boot_args' object, or undefined if it could not be found
     */
    extractBootArgsFromHTML(html: string): any {
        const bootArgs = html.match(/<script[^>]*class="boot_args"[^>]*>([\s\S]*?)<\/script>/)?.[1];
        return bootArgs ? JSON.parse(bootArgs) : undefined;
    }
 
    /**
     * This function will ask the iCloud backend, to re-send the MFA token, using the provided method and number
     * @param method - The method to be used
     * @returns A promise that resolves once all activity has been completed
     * @emits iCPSEventRuntimeWarning.MFA_ERROR - When the resend failed - provides iCPSError as argument
     */
    async resendMFA(method: MFAMethod) {
        Resources.logger(this).info(`Resending MFA code with ${method}`);
 
        const url = method.getResendURL();
        const config: HttpRequestConfig = {
            validateStatus: method.resendSuccessful.bind(method),
        };
        const data = method.getResendPayload();
 
        Resources.logger(this).debug(`Requesting MFA code via PUT ${url} with data ${jsonc.stringify(data)}`);
 
        try {
            if (method.isSMS || method.isVoice) {
                const validatedResponse = await Resources.network().put(url, data, Resources.validator().response.resendMFAPhone, config);
                Resources.logger(this).info(`Successfully requested new MFA code using phone ${validatedResponse.data.trustedPhoneNumber.numberWithDialCode}`);
                return;
            }
 
            if (method.isDevice) {
                const validatedResponse = await Resources.network().put(url, data, Resources.validator().response.resendMFADevice, config);
                const trustedDeviceCount = validatedResponse.data ? validatedResponse.data.trustedDeviceCount : undefined;
                Resources.logger(this).info(`Successfully requested new MFA code using ${trustedDeviceCount ?? `all`} trusted device(s)`);
            }
        } catch (err) {
            Resources.emit(iCPSEventRuntimeWarning.MFA_ERROR, new iCPSError(MFA_ERR.RESEND_FAILED).addCause(err));
        }
    }
 
    /**
     * Enters and validates the MFA code in order to acquire necessary account tokens
     * @param mfa - The MFA code
     * @emits iCPSEventCloud.AUTHENTICATED - When authentication is successful
     * @emits iCPSEventCloud.ERROR - When an error occurs - provides iCPSError as argument
     */
    async submitMFA(method: MFAMethod, mfa: string) {
        try {
            Resources.logger(this).info(`Authenticating MFA with code ${mfa}`);
 
            const url = method.getEnterURL();
            const config: HttpRequestConfig = {
                validateStatus: method.enterSuccessful.bind(method),
            };
            const data = method.getEnterPayload(mfa);
 
            Resources.logger(this).debug(`Entering MFA code via URL ${url} with data ${jsonc.stringify(data)}`);
            const response = await Resources.network().post(url, data, Resources.validator().response.mfaSubmit, config);
 
            if (response.status === 409) {
                // Since iOS 26.4 the backend acknowledges a valid code with status 409
                const result = response.data === `` ? undefined : response.data;
                if (result?.securityCode?.valid !== true && !response.headers[`x-apple-session-token`]) {
                    const rejectedErr = new iCPSError(MFA_ERR.CODE_REJECTED)
                        .addContext(`responseData`, response.data);
                    if (Array.isArray(result?.service_errors)) {
                        rejectedErr.addMessage(...result.service_errors.flatMap(serviceError => serviceError?.message ?? []));
                    }
 
                    throw rejectedErr;
                }
 
                Resources.network().applySessionTokenUpdate(response);
 
                if (this.requiresEscrow(response)) {
                    await this.completeEscrow();
                }
            }
 
            Resources.logger(this).info(`MFA code correct!`);
            Resources.emit(iCPSEventCloud.AUTHENTICATED);
 
            if (this.mfaTimeout) {
                clearTimeout(this.mfaTimeout);
                this.mfaTimeout = undefined
            }
        } catch (err) {
            if (err instanceof iCPSError) {
                Resources.emit(iCPSEventCloud.ERROR, err);
                return;
            }
 
            if (isHttpError(err) && (err.response?.status === 400 || this.hasServiceError(err.response?.data, MFA_INCORRECT_CODE_ERROR))) {
                const augmentedErr = new iCPSError(MFA_ERR.CODE_REJECTED).addCause(err);
                if (Array.isArray(err.response?.data?.service_errors)) {
                    augmentedErr.addMessage(...err.response!.data.service_errors.map((serviceError: any) => serviceError?.message));
                }
 
                Resources.emit(iCPSEventCloud.ERROR, augmentedErr);
                return;
            }
 
            Resources.emit(iCPSEventCloud.ERROR, new iCPSError(MFA_ERR.SUBMIT_FAILED).addCause(err));
        }
    }
 
    /**
     * Checks if the backend requires the escrow flow - signaled through the 'X-Apple-EDP' or 'X-Apple-PDP' header on a 409 response
     * @param response - The response received from the backend
     * @returns True, if the escrow flow needs to be completed
     */
    requiresEscrow(response: Pick<HttpResponse, `headers`>): boolean {
        return Boolean(response.headers[`x-apple-edp`] || response.headers[`x-apple-pdp`]);
    }
 
    /**
     * Completes the escrow flow, which is a second SRP-based password proof (using an empty account name), required by the backend since iOS 26.4
     * The backend issues an updated session token upon completion
     * @param authenticator - The authenticator crypto instance for generating the SRP proof - parameterized for testing purposes, will be initiated by default
     * @throws An iCPSError, if the escrow flow could not be completed
     */
    async completeEscrow(authenticator: iCloudCrypto = new iCloudCrypto(``)) {
        Resources.logger(this).info(`Completing escrow password verification`);
        try {
            const validatedInitResponse = await Resources.network().post(ENDPOINTS.AUTH.BASE + ENDPOINTS.AUTH.PATH.ESCROW.INIT, {
                a: await authenticator.getClientEphemeral(),
                accountName: ``,
                protocols: [
                    `s2k`,
                    `s2k_fo`,
                ],
            }, Resources.validator().response.escrowInit);
 
            const derivedPassword = await authenticator.derivePassword(validatedInitResponse.data.protocol, validatedInitResponse.data.salt, validatedInitResponse.data.iteration);
            const [m1Proof, m2Proof] = await authenticator.getProofValues(derivedPassword, validatedInitResponse.data.b, validatedInitResponse.data.salt);
 
            const completeResponse = await Resources.network().post(ENDPOINTS.AUTH.BASE + ENDPOINTS.AUTH.PATH.ESCROW.COMPLETE, {
                m1: m1Proof,
                m2: m2Proof,
                c: validatedInitResponse.data.c,
                k: await authenticator.getSessionKey(),
            }, Resources.validator().response.escrowComplete);
 
            Resources.network().applySessionTokenUpdate(completeResponse);
            Resources.logger(this).debug(`Escrow completed`);
        } catch (err) {
            throw new iCPSError(AUTH_ERR.ESCROW_FAILED).addCause(err);
        }
    }
 
    /**
     * Checks if the response data contains a specific service error code
     * @param data - The response data
     * @param code - The service error code to look for
     * @returns True, if the service error is present
     */
    hasServiceError(data: any, code: string): boolean {
        return this.getServiceErrors(data).some(serviceError => serviceError?.code === code);
    }
 
    /**
     * Extracts the service errors from the response data - the backend uses both `service_errors` and `serviceErrors` as key
     * @param data - The response data
     * @returns The list of service errors, empty if none are present
     */
    getServiceErrors(data: any): any[] {
        return [data?.service_errors, data?.serviceErrors]
            .filter(serviceErrors => Array.isArray(serviceErrors))
            .flat();
    }
 
    /**
     * Acquires sessionToken and two factor trust token after successful authentication
     * @emits iCPSEventCloud.TRUSTED - When trust token has been acquired - provides trust token as argument
     * @emits iCPSEventCloud.ERROR - When an error occurs - provides iCPSError as argument
     */
    async getTokens() {
        try {
            Resources.logger(this).info(`Trusting device and acquiring trust tokens`);
 
            const url = ENDPOINTS.AUTH.BASE + ENDPOINTS.AUTH.PATH.TRUST;
            const config: HttpRequestConfig = {
                validateStatus: status => status === 204,
            };
 
            const validatedResponse = await Resources.network().get(url, Resources.validator().response.trust, config);
            Resources.network().applyTrustResponse(validatedResponse);
 
            Resources.logger(this).debug(`Acquired account tokens`);
            Resources.emit(iCPSEventCloud.TRUSTED, Resources.manager().trustToken);
        } catch (err) {
            Resources.emit(iCPSEventCloud.ERROR, new iCPSError(AUTH_ERR.ACQUIRE_ACCOUNT_TOKENS).addCause(err));
        }
    }
 
    /**
     * Acquiring necessary cookies from trust and auth token for further processing. Also gets the user specific domain to interact with the Photos backend
     * @emits iCPSEventCloud.ACCOUNT_READY - When account is ready to be used
     * @emits iCPSEventCloud.SESSION_EXPIRED - When the session token has expired
     * @emits iCPSEventCloud.PCS_REQUIRED - When the account is setup using ADP and PCS cookies are required
     * @emits iCPSEventCloud.ERROR - When an error occurs (including an account that requires an action through the iCloud web frontend) - provides iCPSError as argument
     */
    async setupAccount() {
        try {
            Resources.logger(this).info(`Setting up iCloud connection`);
 
            const url = ENDPOINTS.SETUP.BASE() + ENDPOINTS.SETUP.PATH.ACCOUNT_LOGIN;
            // Matching the iCloud web frontend, which provides the trust token in order to register this client as trusted browser
            const data = {
                dsWebAuthToken: Resources.manager().sessionSecret,
                accountCountryCode: Resources.network().accountCountry,
                extended_login: true,
                trustToken: Resources.manager().trustToken,
            };
 
            const validatedResponse = await Resources.network().post(url, data, Resources.validator().response.setup);
 
            // In case the account requires an action through the iCloud web frontend (e.g. accepting updated terms), the backend only provides a 'repair' session without web auth token
            const webAuthTokenProvided = validatedResponse.headers[`set-cookie`].some(cookieString => cookieString.startsWith(`${COOKIE_KEYS.WEBAUTH_TOKEN}=`));
            if (validatedResponse.data.isRepairNeeded || validatedResponse.data.termsUpdateNeeded || !webAuthTokenProvided) {
                throw new iCPSError(AUTH_ERR.ACCOUNT_SETUP_INCOMPLETE)
                    .addContext(`isRepairNeeded`, validatedResponse.data.isRepairNeeded)
                    .addContext(`termsUpdateNeeded`, validatedResponse.data.termsUpdateNeeded)
                    .addContext(`webAuthTokenProvided`, webAuthTokenProvided);
            }
 
            if (!Resources.network().applySetupResponse(validatedResponse)) {
                Resources.logger(this).debug(`PCS required, acquiring...`);
                Resources.emit(iCPSEventCloud.PCS_REQUIRED);
                return;
            }
 
            Resources.logger(this).debug(`Account ready`);
            Resources.emit(iCPSEventCloud.ACCOUNT_READY);
        } catch (err) {
            if (isHttpError(err) && err.response?.status === 421) {
                Resources.logger(this).debug(`Session token expired, re-acquiring...`);
                Resources.emit(iCPSEventCloud.SESSION_EXPIRED);
                return;
            }
 
            Resources.emit(iCPSEventCloud.ERROR, new iCPSError(AUTH_ERR.ACCOUNT_SETUP).addCause(err));
        }
    }
 
    /**
     * Acquires PCS cookies for ADP accounts
     * @emits iCPSEventCloud.ACCOUNT_READY - When account is ready to be used
     * @emits iCPSEventCloud.PCS_NOT_READY - When PCS cookies are not ready yet
     * @emits iCPSEventCloud.PCS_REQUIRED - When the account is setup using ADP and PCS cookies are still required
     * @emits iCPSEventCloud.ERROR - When an error occurs - provides iCPSError as argument
     */
    async acquirePCSCookies() {
        try {
            Resources.logger(this).info(`Acquiring PCS cookies`);
 
            const url = ENDPOINTS.SETUP.BASE() + ENDPOINTS.SETUP.PATH.REQUEST_PCS;
            const data = {
                appName: `photos`,
                derivedFromUserAction: true,
            };
 
            const validatedResponse = await Resources.network().post(url, data, Resources.validator().response.pcs);
 
            if (validatedResponse.data.status === `failure`) {
                Resources.logger(this).info(`Failed to acquire PCS cookies: ${validatedResponse.data.message}`);
                Resources.emit(iCPSEventCloud.PCS_NOT_READY);
                setTimeout(() => Resources.emit(iCPSEventCloud.PCS_REQUIRED), 10000);
                return;
            }
 
            if (!validatedResponse.headers[`set-cookie`]
                || validatedResponse.headers[`set-cookie`].filter(cookieString => cookieString.startsWith(COOKIE_KEYS.PCS_PHOTOS) || cookieString.startsWith(COOKIE_KEYS.PCS_SHARING)).length !== 2) {
                throw new iCPSError(AUTH_ERR.PCS_COOKIE_MISSING).addContext(`response`, validatedResponse);
            }
 
            Resources.logger(this).debug(`Account ready with PCS cookies`);
            Resources.emit(iCPSEventCloud.ACCOUNT_READY);
        } catch (err) {
            const pcsError = new iCPSError(AUTH_ERR.PCS_REQUEST_FAILED).addCause(err);
            // The backend explains the failure in the response body, e.g. 412 'User has not disabled iCloud DRS.'
            if (isHttpError(err) && typeof err.response?.data?.message === `string`) {
                pcsError.addMessage(err.response.data.message);
            }
 
            Resources.emit(iCPSEventCloud.ERROR, pcsError);
        }
    }
 
    /**
     * Performs a logout, while retaining the trust token
     */
    async logout() {
        try {
            const url = ENDPOINTS.SETUP.BASE() + ENDPOINTS.SETUP.PATH.LOGOUT;
            const data = {
                trustBrowser: true,
                allBrowsers: false,
            };
 
            const config: HttpRequestConfig = {
                // 421 is expected, if user was not logged in - 200 is expected, if logout was successful
                validateStatus: status => status === 421 || status === 200,
            };
 
            Resources.logger(this).info(`Logging current account out`);
 
            await Resources.network().post(url, data, Resources.validator().response.logout, config);
        } catch (err) {
            throw new iCPSError(AUTH_ERR.LOGOUT_FAILED).addCause(err);
        }
    }
 
    /**
     * Creating iCloud Photos sub-class and linking it
     * @emits iCPSEventCloud.ERROR - When an error occurs - provides iCPSError as argument
    */
    async getPhotosReady() {
        try {
            Resources.logger(this).info(`Getting iCloud Photos Service ready`);
            await this.photos.setup();
        } catch (err) {
            Resources.emit(iCPSEventCloud.ERROR, new iCPSError(ICLOUD_PHOTOS_ERR.SETUP_FAILED).addCause(err));
        }
    }
}