Skip to content

PyiCloudService

The main entry point for interacting with iCloud. Every iCloud service is reached through a property on a PyiCloudService instance (for example api.photos, api.drive, or api.devices).

from pyicloud import PyiCloudService

api = PyiCloudService("jappleseed@apple.com", "password")

See the Authentication guide for the full two-step / two-factor (2SA/2FA) flow.

A base authentication class for the iCloud service. Handles the authentication required to access iCloud services.

Usage

from pyicloud import PyiCloudService pyicloud = PyiCloudService('username@apple.com', 'password') pyicloud.iphone.location()

Source code in pyicloud/base.py
 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
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
class PyiCloudService:
    """
    A base authentication class for the iCloud service. Handles the
    authentication required to access iCloud services.

    Usage:
        from pyicloud import PyiCloudService
        pyicloud = PyiCloudService('username@apple.com', 'password')
        pyicloud.iphone.location()
    """

    def _setup_endpoints(self) -> None:
        """Set up the endpoints for the service."""
        # If the country or region setting of your Apple ID is China mainland.
        # See https://support.apple.com/en-us/HT208351
        icloud_china: str = ".cn" if self._is_china_mainland else ""
        self._idmsa_endpoint: str = "https://idmsa.apple.com"
        self._auth_endpoint: str = f"{self._idmsa_endpoint}/appleauth/auth"
        self._home_endpoint: str = f"https://www.icloud.com{icloud_china}"
        self._setup_endpoint: str = f"https://setup.icloud.com{icloud_china}/setup/ws/1"

    def _setup_cookie_directory(self, cookie_directory: str | None = None) -> str:
        """Set up the cookie directory for the service."""
        _cookie_directory = resolve_cookie_directory(cookie_directory)
        if not cookie_directory:
            topdir = path.dirname(_cookie_directory)
            makedirs(topdir, exist_ok=True)
            chmod(topdir, 0o1777)  # noqa: S2612

        old_umask = umask(0o077)
        try:
            makedirs(_cookie_directory, exist_ok=True)
        finally:
            umask(old_umask)
        return _cookie_directory

    def __init__(
        self,  # noqa: S107 - public entry point intentionally exposes many options
        apple_id: str,
        password: str | None = None,
        cookie_directory: str | None = None,
        verify: bool = True,
        client_id: str | None = None,
        with_family: bool = True,
        china_mainland: bool | None = None,
        accept_terms: bool = False,
        refresh_interval: float | None = DEFAULT_REFRESH_INTERVAL,
        family_poll_delay: float = 0.5,
        family_poll_max_retries: int = 5,
        locate: bool = False,
        *,
        authenticate: bool = True,
        cloudkit_validation_extra: CloudKitExtraMode | None = None,
        pause_2fa: bool = False,
        upload_hydration_timeout: float = UPLOAD_HYDRATION_TIMEOUT,
        upload_hydration_interval: float = UPLOAD_HYDRATION_INTERVAL,
    ) -> None:
        """Initialize a service session for one Apple ID account."""
        self._is_china_mainland: bool = (
            environ.get("ICLOUD_CHINA", "0") == "1"
            if china_mainland is None
            else china_mainland
        )
        self._setup_endpoints()

        self._password_raw: str | None = password

        self._apple_id: str = apple_id
        self._accept_terms: bool = accept_terms
        self._refresh_interval: float | None = refresh_interval
        self._upload_hydration_timeout: float = upload_hydration_timeout
        self._upload_hydration_interval: float = upload_hydration_interval

        if self._password_raw is None and authenticate:
            self._password_raw = get_password_from_keyring(apple_id)

        self.data: dict[str, Any] = {}
        self._auth_data: dict[str, Any] = {}
        self._hsa2_boot_context: Hsa2BootContext | None = None
        self._trusted_device_bridge_state: TrustedDeviceBridgeState | None = None
        self._trusted_device_bridge = TrustedDeviceBridgeBootstrapper()
        self._two_factor_delivery_method: str = "unknown"
        self._two_factor_delivery_notice: str | None = None

        self.params: dict[str, Any] = {}
        self._client_id: str = client_id or str(uuid1()).lower()
        self._with_family: bool = with_family
        self._family_poll_delay: float = family_poll_delay
        self._family_poll_max_retries: int = family_poll_max_retries
        self._locate: bool = locate
        self._cloudkit_validation_extra = cloudkit_validation_extra

        _cookie_directory: str = self._setup_cookie_directory(cookie_directory)
        _headers: dict[str, str] = _HEADERS.copy()
        _headers.update({
            "Origin": self._home_endpoint,
            "Referer": f"{self._home_endpoint}/",
        })

        self._session: PyiCloudSession = PyiCloudSession(
            self,
            verify=verify,
            headers=_headers,
            client_id=self._client_id,
            cookie_directory=_cookie_directory,
        )

        self._client_id = self.session.data.get("client_id", self._client_id)

        _params: dict[str, str] = _PARAMS.copy()
        _params.update({
            "clientId": self._client_id,
        })
        self.params = _params

        self._webservices: dict[str, dict[str, Any]] | None = None
        self._pcs_granted: dict[str, float] = {}

        self._account: AccountService | None = None
        self._calendar: CalendarService | None = None
        self._contacts: ContactsService | None = None
        self._devices: FindMyiPhoneServiceManager | None = None
        self._drive: DriveService | None = None
        self._files: UbiquityService | None = None
        self._hidemyemail: HideMyEmailService | None = None
        self._photos: PhotosService | None = None
        self._reminders: RemindersService | None = None
        self._notes: NotesService | None = None
        self._invites: InvitesService | None = None
        self._mail: MailService | None = None

        self._requires_mfa: bool = False
        self._two_factor_code_requested: bool = False
        self._pause_2fa: bool = pause_2fa

        if authenticate:
            self.authenticate(pause_2fa=pause_2fa)

    @property
    def is_china_mainland(self) -> bool:
        """Return whether the current service uses China mainland endpoints."""

        return self._is_china_mainland

    def authenticate(
        self,
        force_refresh: bool = False,
        service: str | None = None,
        pause_2fa: bool | None = None,
    ) -> None:
        """
        Handles authentication, and persists cookies so that
        subsequent logins will not cause additional e-mails from Apple.
        """

        if pause_2fa is None:
            pause_2fa = self._pause_2fa

        self._pcs_granted.clear()
        login_successful = False
        if self._try_reuse_cached_session(force_refresh, pause_2fa):
            login_successful = True

        if not login_successful and self._try_service_one_factor_login(service):
            login_successful = True

        if not login_successful:
            try:
                self._authenticate(pause_2fa=pause_2fa)
                LOGGER.debug("Authentication completed successfully")
            except PyiCloud2FARequiredException:
                self._requires_mfa = True
                LOGGER.debug("2FA is required")

        self._update_state()

    def _try_reuse_cached_session(self, force_refresh: bool, pause_2fa: bool) -> bool:
        """Validate and reuse a cached session token when it is allowed.

        An intentionally untrusted (paused) session is only reused when the
        caller explicitly opted into a paused 2FA flow; a trusted session is
        always reusable so cookie/session persistence keeps working.
        """
        if not self.session.data.get("session_token") or force_refresh:
            return False
        try:
            self.data = self._validate_token()
        except PyiCloudAPIResponseException as error:
            # A 5xx from /validate says nothing about the cached token. Reusing
            # it after an outage is preferable to a full reauthentication storm.
            if _is_auth_server_error(error):
                _raise_auth_server_error(error)
            LOGGER.debug("Invalid authentication token, will log in from scratch.")
            return False
        except PyiCloudAuthRequiredException:
            LOGGER.debug("Invalid authentication token, will log in from scratch.")
            return False
        if not self.is_trusted_session and not pause_2fa:
            LOGGER.debug("Cached session is untrusted; requiring full authentication.")
            return False
        return True

    def _try_service_one_factor_login(self, service: str | None) -> bool:
        """Attempt a one-factor login for the requested service."""
        if (
            service is None
            or not self.data.get("apps")
            or service not in self.data["apps"]
        ):
            return False
        app: dict[str, Any] = self.data["apps"][service]
        if "canLaunchWithOneFactor" not in app or not app["canLaunchWithOneFactor"]:
            return False
        LOGGER.debug("Authenticating as %s for %s", self.account_name, service)
        try:
            self._authenticate_with_credentials_service(service)
            return True
        except PyiCloudAccountLockedException:
            raise
        except PyiCloudFailedLoginException:
            LOGGER.debug("Could not log into service. Attempting brand new login.")
            return False

    def _handle_accept_terms(self, login_data: dict[str, Any]) -> None:
        """Handle accepting updated terms of service."""
        if self.data.get("termsUpdateNeeded"):
            if not self._accept_terms:
                raise PyiCloudAcceptTermsException(
                    "You must accept the updated terms of service to continue. "
                    "Set --accept-terms to accept them."
                )
            resp: Response = self.session.get(
                f"{self._setup_endpoint}/getTerms",
                params=self.params,
                json={
                    "locale": self.data.get("dsInfo", {}).get("languageCode", "en_US")
                },
            )
            resp.raise_for_status()
            terms_info: dict[str, Any] = resp.json()
            version: int | None = terms_info.get("iCloudTerms", {}).get("version")
            if version is None:
                raise PyiCloudAcceptTermsException("Could not get terms version")
            resp = self.session.get(
                f"{self._setup_endpoint}/repairDone",
                params=self.params,
                json={"acceptedICloudTerms": version},
            )
            resp.raise_for_status()

            resp = self.session.post(
                f"{self._setup_endpoint}/accountLogin", json=login_data
            )
            resp.raise_for_status()

            self.data = resp.json()

    def _update_state(self) -> None:
        """Update the state of the service."""
        if (
            "dsInfo" in self.data
            and isinstance(self.data["dsInfo"], dict)
            and "dsid" in self.data["dsInfo"]
        ):
            self.params.update({"dsid": self.data["dsInfo"]["dsid"]})

        if "webservices" in self.data:
            self._webservices = self.data["webservices"]

    def _clear_authenticated_state(self) -> None:
        """Clear in-memory auth-derived state."""

        self.data = {}
        self._auth_data = {}
        self._hsa2_boot_context = None
        self._clear_trusted_device_bridge_state()
        self._two_factor_delivery_method = "unknown"
        self._two_factor_delivery_notice = None
        self._webservices = None
        self._pcs_granted.clear()
        self._account = None
        self._calendar = None
        self._contacts = None
        self._devices = None
        self._drive = None
        self._files = None
        self._hidemyemail = None
        self._mail = None
        self._photos = None
        self._reminders = None
        self._invites = None
        self._requires_mfa = False
        self._two_factor_code_requested = False
        self.params.pop("dsid", None)

    def _clear_trusted_device_bridge_state(self) -> None:
        """Close any active trusted-device bridge session and clear in-memory state."""

        self._two_factor_code_requested = False
        if self._trusted_device_bridge_state is not None:
            state = self._trusted_device_bridge_state
            self._trusted_device_bridge_state = None
            self._trusted_device_bridge.close(state)
        self._trusted_device_bridge_state = None

    def get_auth_status(self) -> dict[str, Any]:
        """Probe current authentication state without prompting for login."""

        status: dict[str, Any] = {
            "authenticated": False,
            "trusted_session": False,
            "requires_2fa": False,
            "requires_2sa": False,
        }

        if not self.session.data.get("session_token"):
            self._clear_authenticated_state()
            return status

        if not self.session.cookies.get("X-APPLE-WEBAUTH-TOKEN"):
            self._clear_authenticated_state()
            return status

        try:
            self.data = self._validate_token()
            self._update_state()
        except PyiCloudAPIResponseException:
            self._clear_authenticated_state()
            return status

        status.update({
            "authenticated": True,
            "trusted_session": self.is_trusted_session,
            "requires_2fa": self.requires_2fa,
            "requires_2sa": self.requires_2sa,
        })
        return status

    def logout(
        self,
        *,
        keep_trusted: bool = False,
        all_sessions: bool = False,
        clear_local_session: bool = True,
    ) -> dict[str, Any]:
        """Log out of the current session and optionally clear local persistence."""

        payload: dict[str, bool] = {
            "trustBrowser": keep_trusted,
            "allBrowsers": all_sessions,
        }
        remote_logout_confirmed = False

        if self.params.get("dsid") and self.session.cookies.get(
            "X-APPLE-WEBAUTH-TOKEN"
        ):
            try:
                response = self.session.post(
                    f"{self._setup_endpoint}/logout",
                    params=dict(self.params),
                    data=json.dumps(payload),
                    headers={"Content-Type": "text/plain;charset=UTF-8"},
                )
                remote_logout_confirmed = bool(response.json().get("success"))
            except (PyiCloudAPIResponseException, ValueError):
                LOGGER.debug("Remote logout was not confirmed.", exc_info=True)

        local_session_cleared = False
        if clear_local_session:
            self.session.clear_persistence(remove_files=True)
            self._clear_authenticated_state()
            local_session_cleared = True

        return {
            "payload": payload,
            "remote_logout_confirmed": remote_logout_confirmed,
            "local_session_cleared": local_session_cleared,
        }

    def _authenticate(self, pause_2fa: bool = False) -> None:
        """Authenticate with either the cached session token or fresh credentials."""
        LOGGER.debug("Authenticating as %s", self.account_name)

        try:
            self._authenticate_with_token()
        except PyiCloudAccountLockedException:
            raise
        except (
            PyiCloudFailedLoginException,
            PyiCloud2FARequiredException,
            PyiCloudAuthRequiredException,
        ):
            paused_login_succeeded = self._srp_authentication(pause_2fa=pause_2fa)
            if self._requires_mfa:
                LOGGER.debug(
                    "MFA is required; session-token authentication is deferred "
                    "until the 2FA challenge is completed."
                )
                return
            if not pause_2fa or not paused_login_succeeded:
                self._authenticate_with_token(require_trust=not pause_2fa)

    def _srp_authentication(self, pause_2fa: bool = False) -> bool:
        """SRP authentication; returns True when a paused token login succeeded."""
        if self._password_raw is None:
            raise PyiCloudFailedLoginException("No password set")

        auth_headers = self._get_auth_headers()

        response: Response = self.session.get(
            f"{self._auth_endpoint}/authorize/signin",
            params={
                "frame_id": auth_headers["X-Apple-OAuth-State"],
                "skVersion": "7",
                "iframeid": auth_headers["X-Apple-OAuth-State"],
                "client_id": auth_headers["X-Apple-Widget-Key"],
                "response_type": auth_headers["X-Apple-OAuth-Response-Type"],
                "redirect_uri": auth_headers["X-Apple-OAuth-Redirect-URI"],
                "response_mode": auth_headers["X-Apple-OAuth-Response-Mode"],
                "state": auth_headers["X-Apple-OAuth-State"],
                "authVersion": "latest",
            },
        )
        response.raise_for_status()

        srp_password: SrpPassword = SrpPassword(self._password_raw)
        srp.rfc5054_enable()
        srp.no_username_in_x()
        try:
            usr = srp.User(
                self.account_name,
                srp_password,
                hash_alg=srp.SHA256,
                ng_type=srp.NG_2048,
            )
            uname, A = usr.start_authentication()  # pylint: disable=invalid-name
            data: dict[str, Any] = {
                "a": b64_encode(A),
                ACCOUNT_NAME: uname,
                "protocols": [protocol.value for protocol in SrpProtocolType],
            }

            response = self.session.post(
                f"{self._auth_endpoint}/signin/init",
                json=data,
                headers=self._get_auth_headers(),
            )
            response.raise_for_status()
        except PyiCloudConnectionException:
            # Not a credentials problem; let it through as itself.
            raise
        except (
            PyiCloudAPIResponseException,
            HTTPError,
            PyiCloudPasswordException,
        ) as error:
            msg = "Failed to initiate srp authentication."
            raise PyiCloudFailedLoginException(msg, error) from error

        body: dict[str, Any] = response.json()
        salt: bytes = base64.b64decode(body["salt"])
        b: bytes = base64.b64decode(body["b"])
        c: Any = body["c"]
        iterations: int = body["iteration"]
        protocol: SrpProtocolType = SrpProtocolType(body["protocol"])
        key_length: int = 32

        srp_password.set_encrypt_info(salt, iterations, key_length, protocol)

        m1: None | Any = usr.process_challenge(salt, b)
        m2: None | bytes = usr.H_AMK
        if m1 and m2:
            data = {
                ACCOUNT_NAME: uname,
                "c": c,
                "m1": b64_encode(m1),
                "m2": b64_encode(m2),
                "rememberMe": True,
                "trustTokens": [],
            }
        if self.session.data.get("trust_token"):
            data["trustTokens"] = [self.session.data.get("trust_token")]
        if pause_2fa:
            data["pause2FA"] = True

        try:
            self.session.post(
                f"{self._auth_endpoint}/signin/complete",
                params={
                    "isRememberMeEnabled": "true",
                },
                json=data,
                headers=self._get_auth_headers(),
            )
        except PyiCloud2FARequiredException:
            if (
                pause_2fa
                and self.session.data.get("session_token")
                and self._login_with_paused_token()
            ):
                LOGGER.debug("Paused session-token login succeeded.")
                return True
            LOGGER.debug("2FA required to complete authentication.")
            self._requires_mfa = True
            self._auth_data = self._get_mfa_auth_options()
            try:
                self.request_2fa_code()
            except (
                PyiCloudAPIResponseException,
                PyiCloudNoTrustedNumberAvailable,
            ) as error:
                LOGGER.debug("Automatic 2FA code delivery failed: %s", error)
        except PyiCloudConnectionException:
            # Not a credentials problem; let it through as itself.
            raise
        except PyiCloudAPIResponseException as error:
            msg = "Invalid email/password combination."
            raise PyiCloudFailedLoginException(msg) from error
        return False

    def _login_with_paused_token(self) -> bool:
        """Attempt an untrusted session-token login for a paused 2FA session."""
        if not self.session.data.get("session_token"):
            return False
        LOGGER.debug(
            "2FA required but pause2FA is enabled; attempting session-token login."
        )
        try:
            self._authenticate_with_token(require_trust=False)
        except PyiCloudAccountLockedException:
            raise
        except PyiCloudAPIResponseException as error:
            if _is_auth_server_error(error):
                _raise_auth_server_error(error)
            LOGGER.debug("Paused session-token login failed; falling back to MFA flow.")
            return False
        except PyiCloudFailedLoginException:
            LOGGER.debug("Paused session-token login failed; falling back to MFA flow.")
            return False
        return True

    def _authenticate_with_token(self, require_trust: bool = True) -> None:
        """Authenticate using session token."""
        self._pcs_granted.clear()
        if not self.session.data.get("session_token"):
            raise PyiCloudFailedLoginException("No session token available")

        try:
            login_data: dict[str, Any] = {
                "accountCountryCode": self.session.data.get("account_country"),
                "dsWebAuthToken": self.session.data.get("session_token"),
                "extended_login": True,
                "trustToken": self.session.data.get("trust_token", ""),
            }

            resp: Response = self.session.post(
                f"{self._setup_endpoint}/accountLogin", json=login_data
            )
            resp.raise_for_status()

            self.data = resp.json()

            self._handle_accept_terms(login_data)

            if require_trust and not self.is_trusted_session:
                raise PyiCloud2FARequiredException(self.account_name, resp)

            # accountLogin returns a fresh webservices map, so derived state has
            # to be refreshed here rather than only in authenticate(). Reached
            # via trust_session() after 2FA, which otherwise leaves
            # `_webservices` holding the reduced map from the pre-2FA login and
            # makes get_webservice_url() raise for services that are present in
            # `self.data`. Deliberately after the trust check, so the paths that
            # raise keep deferring to authenticate()'s own _update_state() and
            # this stays a no-op for them.
            self._update_state()

            self._auth_data = {}
            self._hsa2_boot_context = None
            self._clear_trusted_device_bridge_state()
            self._set_two_factor_delivery_state("unknown")
        except PyiCloudConnectionException:
            # Not a credentials problem; let it through as itself.
            raise
        except (PyiCloudAPIResponseException, HTTPError) as error:
            if _is_auth_server_error(error):
                _raise_auth_server_error(error)
            msg = "Invalid authentication token."
            raise PyiCloudFailedLoginException(msg, error) from error

    def _authenticate_with_credentials_service(self, service: str | None) -> None:
        """Authenticate to a specific service using credentials."""
        login_data: dict[str, Any] = {
            "appName": service,
            "apple_id": self.account_name,
            "password": self._password_raw,
        }

        try:
            self.session.post(f"{self._setup_endpoint}/accountLogin", json=login_data)

            self._handle_accept_terms(login_data)

            self.data = self._validate_token()
        except PyiCloudConnectionException:
            # Not a credentials problem; let it through as itself.
            raise
        except PyiCloudAPIResponseException as error:
            if _is_auth_server_error(error):
                _raise_auth_server_error(error)
            msg = "Invalid email/password combination."
            raise PyiCloudFailedLoginException(msg, error) from error

    def _validate_token(self) -> Any:
        """Checks if the current access token is still valid."""
        LOGGER.debug("Checking session token validity")
        if not self.session.cookies.get("X-APPLE-WEBAUTH-TOKEN"):
            raise PyiCloudAPIResponseException(
                "Missing X-APPLE-WEBAUTH-TOKEN cookie", None
            )
        try:
            req: Response = self.session.post(
                f"{self._setup_endpoint}/validate", data="null"
            )
            LOGGER.debug("Session token is still valid")
            return req.json()
        except PyiCloudAPIResponseException:
            LOGGER.debug("Invalid authentication token")
            raise

    def _get_auth_headers(
        self, overrides: dict[str, Any] | None = None
    ) -> dict[str, Any]:
        """Build Apple auth headers for IDMS, bridge, and verification requests."""
        return build_auth_headers(
            _AUTH_HEADERS_JSON,
            self._idmsa_endpoint,
            self._home_endpoint,
            self._client_id,
            self.session.data,
            overrides,
        )

    @property
    def session(self) -> PyiCloudSession:
        """Return the session."""
        return self._session

    def _is_mfa_required(self) -> bool:
        """Return whether the current auth state still requires MFA completion."""
        return (
            self.data.get("hsaChallengeRequired", False)
            or not self.is_trusted_session
            or self._requires_mfa
        )

    @property
    def requires_2sa(self) -> bool:
        """Returns True if two-step authentication is required."""
        return (
            self._is_mfa_required()
            and self.data.get("dsInfo", {}).get("hsaVersion", 0) >= 1
        )

    @property
    def requires_2fa(self) -> bool:
        """Returns True if two-factor authentication is required."""
        return self._is_mfa_required() and (
            self.data.get("dsInfo", {}).get("hsaVersion", 0) == 2
            or self._requires_mfa
            or bool(self._auth_data)
        )

    @property
    def is_trusted_session(self) -> bool:
        """Returns True if the session is trusted."""
        return cast(bool, self.data.get("hsaTrustedBrowser", False))

    @property
    def trusted_devices(self) -> list[dict[str, Any]]:
        """Returns devices trusted for two-step authentication."""
        request: Response = self.session.get(
            f"{self._setup_endpoint}/listDevices", params=self.params
        )
        return cast(list[dict[str, Any]], request.json().get("devices"))

    def send_verification_code(self, device: dict[str, Any]) -> bool:
        """Requests that a verification code is sent to the given device."""
        request: Response = self.session.post(
            f"{self._setup_endpoint}/sendVerificationCode",
            params=self.params,
            json=device,
        )
        return cast(bool, request.json().get("success", False))

    def validate_verification_code(self, device: dict[str, Any], code: str) -> bool:
        """Verifies a verification code received on a trusted device."""

        device.update({"verificationCode": code, "trustBrowser": True})

        try:
            self.session.post(
                f"{self._setup_endpoint}/validateVerificationCode",
                params=self.params,
                json=device,
            )
        except PyiCloudAPIResponseException as error:
            if error.code == -21669:
                # Wrong verification code
                return False
            raise

        self.trust_session()

        return not self.requires_2sa

    def _get_mfa_auth_options(self) -> dict[str, Any]:
        """Retrieve auth request options for assertion."""
        # Apple exposes the HSA2 bridge bootstrap in the HTML auth shell.
        # Requesting JSON here tends to collapse the response to the SMS-oriented shape.
        headers = self._get_auth_headers({"Accept": "text/html"})
        try:
            response = self.session.get(self._auth_endpoint, headers=headers)
        except PyiCloudAPIResponseException as error:
            if (
                error.code != AppleAuthError.TWO_FACTOR_REQUIRED
                or error.response is None
                or error.response.headers
                .get("Content-Type", "")
                .split(";")[0]
                .strip()
                .lower()
                != "text/html"
            ):
                raise
            # Apple can return the MFA bootstrap HTML with a challenge status.
            response = error.response

        auth_options: dict[str, Any] = {}
        try:
            response_json = response.json()
        except (AttributeError, TypeError, ValueError):
            response_json = None

        if isinstance(response_json, dict):
            auth_options.update(response_json)
            boot_context = Hsa2BootContext.from_auth_options(auth_options)
        else:
            boot_context = parse_boot_args_html(getattr(response, "text", ""))

        boot_auth_data = boot_context.as_auth_data()
        auth_options.update(boot_auth_data)
        self._hsa2_boot_context = boot_context
        self._clear_trusted_device_bridge_state()
        self._set_two_factor_delivery_state("unknown")

        self._augment_auth_options_from_json(auth_options)

        return auth_options

    def _augment_auth_options_from_json(self, auth_options: dict[str, Any]) -> None:
        """Probe the JSON endpoint for options the HTML shell omitted.

        The probe is skipped when complete WebAuthn options are already present,
        since security-key challenges never use SMS delivery. Otherwise the JSON
        response supplies the WebAuthn options and, when the HTML exposed no
        usable trusted phone number (accounts without trusted devices), the SMS
        options. Phone data from the HTML is never overwritten.
        """
        fsa_challenge = auth_options.get("fsaChallenge")
        if (
            isinstance(fsa_challenge, dict)
            and all(
                fsa_challenge.get(key) for key in ("challenge", "keyHandles", "rpId")
            )
            and auth_options.get("keyNames")
        ):
            return

        try:
            json_response = self.session.get(
                self._auth_endpoint,
                headers=self._get_auth_headers({"Accept": CONTENT_TYPE_JSON}),
            ).json()
        except (
            PyiCloudAPIResponseException,
            PyiCloud2FARequiredException,
            PyiCloudAuthRequiredException,
            TypeError,
            ValueError,
        ):
            return

        if not isinstance(json_response, dict):
            return

        for webauthn_key in ("fsaChallenge", "keyNames"):
            if webauthn_key in json_response:
                auth_options[webauthn_key] = json_response[webauthn_key]

        if self._best_trusted_phone_number(auth_options) is not None:
            return

        # The guard above confirms the HTML shell exposed no usable phone, so
        # JSON phone data can fill the gap without displacing a working number.
        for sms_key in (
            "trustedPhoneNumber",
            "trustedPhoneNumbers",
            "phoneNumberVerification",
        ):
            sms_value = json_response.get(sms_key)
            if sms_value is not None:
                auth_options[sms_key] = sms_value

        if auth_options.get("mode") is None:
            json_mode = json_response.get("mode")
            if json_mode is not None:
                auth_options["mode"] = json_mode

    def _set_two_factor_delivery_state(
        self, method: str, notice: str | None = None
    ) -> None:
        """Track the active MFA delivery route for the current auth challenge."""

        self._two_factor_delivery_method = method
        self._two_factor_delivery_notice = notice
        if method == "unknown":
            self._two_factor_code_requested = False

    def use_existing_trusted_device_code(self) -> None:
        """Validate the next 2FA code as one already shown on a trusted device."""

        self._two_factor_code_requested = False
        self._clear_trusted_device_bridge_state()
        self._set_two_factor_delivery_state("trusted_device")

    def _current_hsa2_boot_context(self) -> Hsa2BootContext:
        """Return the best available HSA2 boot context for the active challenge."""

        if self._hsa2_boot_context is not None:
            return self._hsa2_boot_context

        boot_context = Hsa2BootContext.from_auth_options(self._auth_data)
        self._hsa2_boot_context = boot_context
        return boot_context

    def _supports_trusted_device_bridge(self) -> bool:
        """Return whether Apple's HSA2 boot data prefers the bridge flow."""

        boot_context = self._current_hsa2_boot_context()
        return (
            boot_context.auth_initial_route == "auth/bridge/step"
            and boot_context.has_trusted_devices
            and bool(boot_context.bridge_initiate_data)
        )

    def _can_request_sms_2fa_code(self) -> bool:
        """Return whether SMS delivery is currently available."""

        return (
            self._two_factor_mode() == "sms"
            and self._trusted_phone_number() is not None
        )

    def _request_sms_2fa_code(self, notice: str | None = None) -> bool:
        """Trigger SMS delivery for the current HSA2 challenge."""

        trusted_phone_number = self._trusted_phone_number()
        if not trusted_phone_number:
            raise PyiCloudNoTrustedNumberAvailable()

        data: dict[str, Any] = {
            "phoneNumber": trusted_phone_number.as_phone_number_payload(),
            "mode": "sms",
        }
        headers = self._get_auth_headers({"Accept": CONTENT_TYPE_JSON})

        self.session.put(
            f"{self._auth_endpoint}/verify/phone",
            json=data,
            headers=headers,
        )
        self._clear_trusted_device_bridge_state()
        self._set_two_factor_delivery_state("sms", notice)
        self._two_factor_code_requested = True
        return True

    @property
    def two_factor_delivery_method(self) -> str:
        """Return the current HSA2 delivery method without exposing auth internals."""

        if self._two_factor_delivery_method != "unknown":
            return self._two_factor_delivery_method

        if self._auth_data.get("fsaChallenge") or self.security_key_names:
            return "security_key"

        if self._supports_trusted_device_bridge():
            return "trusted_device"

        if self._two_factor_mode() == "sms":
            return "sms"

        return "unknown"

    @property
    def two_factor_delivery_notice(self) -> str | None:
        """Return an optional user-facing note about the active 2FA delivery path."""

        return self._two_factor_delivery_notice

    @property
    def security_key_names(self) -> list[str] | None:
        """Security key names which can be used for the WebAuthn assertion."""
        return self._auth_data.get("keyNames")

    def _submit_webauthn_assertion_response(self, data: dict[str, Any]) -> None:
        """Submit the WebAuthn assertion response for authentication."""
        headers = self._get_auth_headers({"Accept": CONTENT_TYPE_JSON})

        self.session.post(
            f"{self._auth_endpoint}/verify/security/key", json=data, headers=headers
        )

    def _trusted_phone_number(self) -> TrustedPhoneNumber | None:
        """Return the best available trusted phone number description."""

        return self._best_trusted_phone_number(self._auth_data)

    @staticmethod
    def _best_trusted_phone_number(
        auth_options: Mapping[str, Any],
    ) -> TrustedPhoneNumber | None:
        """Return the best trusted phone number described by auth options."""

        trusted_phone_number = TrustedPhoneNumber.from_mapping(
            auth_options.get("trustedPhoneNumber")
        )
        if trusted_phone_number is not None:
            return trusted_phone_number

        verification_number = PhoneNumberVerification.from_mapping(
            auth_options.get("phoneNumberVerification")
        ).best_trusted_phone_number()
        if verification_number is not None:
            return verification_number

        trusted_phone_numbers = auth_options.get("trustedPhoneNumbers")
        if isinstance(trusted_phone_numbers, list):
            for entry in trusted_phone_numbers:
                phone_number = TrustedPhoneNumber.from_mapping(entry)
                if phone_number is not None:
                    return phone_number
        return None

    def _two_factor_mode(self) -> str | None:
        """Return the current 2FA delivery mode reported by Apple."""

        mode = self._auth_data.get("mode")
        if isinstance(mode, str):
            return mode

        trusted_phone_number = self._trusted_phone_number()
        if trusted_phone_number is None:
            return None

        return trusted_phone_number.push_mode

    def request_2fa_code(self) -> bool:
        """Trigger the active HSA2 delivery route for the current challenge."""

        if self._auth_data.get("fsaChallenge") or self.security_key_names:
            self._set_two_factor_delivery_state("security_key")
            return False

        if self._two_factor_code_requested:
            LOGGER.debug(
                "2FA code delivery for the current challenge is already in flight."
            )
            return True

        self._clear_trusted_device_bridge_state()

        if self._supports_trusted_device_bridge():
            try:
                self._trusted_device_bridge_state = self._trusted_device_bridge.start(
                    session=self.session,
                    auth_endpoint=self._auth_endpoint,
                    headers=self._get_auth_headers({"Accept": CONTENT_TYPE_JSON}),
                    boot_context=self._current_hsa2_boot_context(),
                    user_agent=cast(
                        str,
                        self.session.headers.get("User-Agent", _HEADERS["User-Agent"]),
                    ),
                )
                self._set_two_factor_delivery_state("trusted_device")
                self._two_factor_code_requested = True
                return True
            except PyiCloudTrustedDevicePromptException:
                LOGGER.debug(
                    "Trusted-device bridge bootstrap failed; falling back to "
                    "SMS when available.",
                    exc_info=True,
                )
                if self._can_request_sms_2fa_code():
                    return self._request_sms_2fa_code(
                        notice="Trusted-device prompt failed; falling back to SMS."
                    )
                raise

        if self._can_request_sms_2fa_code():
            return self._request_sms_2fa_code()

        return False

    @property
    def fido2_devices(self) -> list[CtapHidDevice]:
        """List the available FIDO2 devices."""
        return list(CtapHidDevice.list_devices())

    def confirm_security_key(
        self,
        device: CtapHidDevice | None = None,
        *,
        event: Event | None = None,
    ) -> None:
        """Conduct the WebAuthn assertion ceremony with user's FIDO2 device.

        The call blocks until the security key is touched. Set ``event`` from
        another thread to stop waiting; when the wait is aborted through it, a
        ``PyiCloudSecurityKeyTimeoutException`` is raised. Missing challenge
        data raises ``PyiCloudAPIResponseException``; no available device or
        any other failure of the ceremony raises
        ``PyiCloudSecurityKeyException``. The security key exceptions derive
        from ``PyiCloudException``, with the underlying fido2 error chained
        as ``__cause__``.
        """
        fsa: dict[str, Any] = self._auth_data.get("fsaChallenge", {})
        try:
            challenge = fsa["challenge"]
            allowed_credentials = fsa["keyHandles"]
            rp_id = fsa["rpId"]
        except KeyError as error:
            raise PyiCloudAPIResponseException(
                "Missing WebAuthn challenge data"
            ) from error

        if not device:
            devices: list[CtapHidDevice] = list(CtapHidDevice.list_devices())

            if not devices:
                raise PyiCloudSecurityKeyException("No FIDO2 devices found")

            device = devices[0]

        client = Fido2Client(
            device,
            client_data_collector=DefaultClientDataCollector("https://apple.com"),
        )
        credentials: list[PublicKeyCredentialDescriptor] = [
            PublicKeyCredentialDescriptor(
                id=b64url_decode(cred_id), type=PublicKeyCredentialType("public-key")
            )
            for cred_id in allowed_credentials
        ]
        assertion_options = PublicKeyCredentialRequestOptions(
            challenge=b64url_decode(challenge),
            rp_id=rp_id,
            allow_credentials=credentials,
            user_verification=UserVerificationRequirement("discouraged"),
        )
        try:
            result: AuthenticationResponse = client.get_assertion(
                assertion_options, event=event
            ).get_response(0)
        except ClientError as error:
            if (
                error.code == ClientError.ERR.TIMEOUT
                and event is not None
                and event.is_set()
            ):
                raise PyiCloudSecurityKeyTimeoutException(
                    "Security key confirmation was cancelled or timed out "
                    "before the key was touched"
                ) from error
            raise PyiCloudSecurityKeyException(
                "Security key confirmation failed"
            ) from error

        self._submit_webauthn_assertion_response({
            "challenge": challenge,
            "clientData": b64_encode(result.response.client_data),
            "signatureData": b64_encode(result.response.signature),
            "authenticatorData": b64_encode(result.response.authenticator_data),
            "userHandle": b64_encode(result.response.user_handle)
            if result.response.user_handle
            else None,
            "credentialID": b64_encode(result.raw_id),
            "rpId": rp_id,
        })

        self.trust_session()

    def _check_pcs_consent(self) -> dict[str, Any]:
        """Check if the user has consented to PCS access."""
        LOGGER.debug("Querying web access state")
        resp = self.session.post(
            f"{self._setup_endpoint}/requestWebAccessState", params=self.params
        ).json()

        return cast(dict[str, Any], resp)

    def _send_pcs_request(
        self, app_name: str, derived_from_user_action: bool
    ) -> dict[str, Any]:
        """Send a request to the PCS endpoint to check the status of PCS access."""
        LOGGER.debug("Querying PCS status")

        return cast(
            dict[str, Any],
            self.session.post(
                f"{self._setup_endpoint}/requestPCS",
                json={
                    "appName": app_name,
                    "derivedFromUserAction": derived_from_user_action,
                },
                params=self.params,
            ).json(),
        )

    def _request_pcs_for_service(self, app_name: str) -> None:
        """Reuse successful PCS queries for a service for up to six hours."""
        granted_at = self._pcs_granted.get(app_name)
        if granted_at is not None and time.monotonic() - granted_at < PCS_GRANT_TTL:
            return
        self._pcs_granted.pop(app_name, None)
        _check_pcs_resp: dict[str, Any] = self._check_pcs_consent()

        if not _check_pcs_resp.get("isICDRSDisabled", False):
            LOGGER.debug("Skipping PCS request because Apple reports ICDRS is enabled")
            self._pcs_granted[app_name] = time.monotonic()
            return

        if not _check_pcs_resp.get("isDeviceConsentedForPCS", True):
            LOGGER.debug("Requesting PCS consent")

            consent_resp = self.session.post(
                f"{self._setup_endpoint}/enableDeviceConsentForPCS", params=self.params
            ).json()

            if not consent_resp.get("isDeviceConsentNotificationSent"):
                raise PyiCloudAPIResponseException(PCS_ACCESS_ERROR)

        LOGGER.debug("Waiting for PCS consent")
        for _ in range(PCS_MAX_RETRIES):
            if _check_pcs_resp.get("isDeviceConsentedForPCS", True):
                LOGGER.debug("PCS consent granted")
                break

            LOGGER.debug("PCS consent not granted yet, waiting...")
            time.sleep(PCS_SLEEP_TIME)
            _check_pcs_resp = self._check_pcs_consent()

        for attempt in range(PCS_MAX_RETRIES):
            resp: dict[str, Any] = self._send_pcs_request(
                app_name,
                derived_from_user_action=attempt == 0,
            )

            if resp["status"] == "success":
                LOGGER.debug("PCS access was granted")
                self._pcs_granted[app_name] = time.monotonic()
                return

            if resp["message"] in (
                "Requested the device to upload cookies.",
                "Cookies not available yet on server.",
            ):
                LOGGER.debug("PCS access couldn't be obtained: %s", resp["message"])
                time.sleep(PCS_SLEEP_TIME)
            else:
                LOGGER.error("Unknown PCS state: %s", resp["message"])
                raise PyiCloudAPIResponseException(PCS_ACCESS_ERROR)

        LOGGER.error("PCS retries exhausted: %s", resp["message"])
        raise PyiCloudPCSTimeoutException(PCS_ACCESS_ERROR)

    def validate_2fa_code(self, code: str) -> bool:
        """Verifies a verification code received via Apple's 2FA system (HSA2).

        A bridge challenge is single-use: a rejected code, a consumed
        challenge, or an ambiguous transport failure retires it and raises
        ``PyiCloudTrustedDeviceChallengeRequiredException`` so callers request
        a fresh code instead of falling back to the legacy verifier.
        """
        bridge_state = self._trusted_device_bridge_state
        bridge_active = (
            bridge_state is not None
            and not bridge_state.uses_legacy_trusted_device_verifier
        )
        if not bridge_active:
            # SMS and deliberately selected legacy routes do not keep a
            # reusable bridge challenge.
            self._two_factor_code_requested = False
        try:
            if self.two_factor_delivery_method == "sms":
                self._validate_sms_code(code)
            elif bridge_active:
                assert bridge_state is not None
                self._validate_bridge_code(code, bridge_state)
            else:
                self._validate_trusted_device_code(code)
        except KeyboardInterrupt:
            # The interrupt may have landed after Apple accepted the step-2
            # POST, so the captured challenge is not safe to replay.
            self._discard_bridge_challenge(bridge_state)
            raise
        except (
            PyiCloudTrustedDeviceVerificationException,
            PyiCloudConnectionException,
        ):
            # A legacy-routed bridge POST can fail at transport while its
            # websocket is still open; retire the challenge instead of
            # leaking it. Bridge-path exits above already cleared the state.
            self._clear_trusted_device_bridge_state()
            raise
        except (PyiCloudAPIResponseException, PyiCloud2FARequiredException):
            # A legacy-routed bridge challenge is spent once the verifier
            # rejects the code; close it instead of leaking the socket.
            self._discard_bridge_challenge(bridge_state)
            LOGGER.error("Code verification failed.")
            return False
        except Exception:
            # Unexpected failures (e.g. a malformed push frame decoding to a
            # ValueError) can escape after Apple accepted the step-2 POST.
            # Retire the challenge instead of leaking the websocket or let
            # request_2fa_code() skip the replacement it would report.
            self._discard_bridge_challenge(bridge_state)
            raise

        if bridge_state is not None:
            self._clear_trusted_device_bridge_state()
        self._two_factor_code_requested = False
        LOGGER.debug("Code verification successful.")

        self.trust_session()
        return not self.requires_2sa

    def _validate_bridge_code(
        self, code: str, bridge_state: TrustedDeviceBridgeState
    ) -> None:
        """Verify a code against one single-use bridge challenge."""

        try:
            verified = self._trusted_device_bridge.validate_code(
                session=self.session,
                auth_endpoint=self._auth_endpoint,
                headers=self._get_auth_headers({"Accept": CONTENT_TYPE_JSON}),
                bridge_state=bridge_state,
                code=code,
            )
        except (
            PyiCloudAPIResponseException,
            PyiCloud2FARequiredException,
        ) as error:
            # The challenge cannot be reused: it was consumed, the rejected
            # code advanced the protocol, or a transport failure leaves it
            # ambiguous whether Apple accepted the step-2 POST. request_raw()
            # also raises a plain API exception for non-connection transport
            # faults, and answering False would let the next retry fall back
            # to the legacy verifier. Retire the challenge and ask the caller
            # for a fresh code instead of replaying it. Preserving retries for
            # proven pre-transmission failures is tracked in issue #557.
            self._clear_trusted_device_bridge_state()
            raise PyiCloudTrustedDeviceChallengeRequiredException(
                f"{error}; request a new verification code"
            ) from error
        if not verified:
            # The rejected code consumed the challenge: the bridge has
            # advanced past step 2 and cannot verify another code.
            self._clear_trusted_device_bridge_state()
            raise PyiCloudTrustedDeviceChallengeRequiredException(
                "Code verification failed; request a new verification code"
            )

    def _discard_bridge_challenge(
        self, bridge_state: TrustedDeviceBridgeState | None
    ) -> None:
        """Close the captured bridge challenge when one is still held."""

        if bridge_state is not None:
            self._clear_trusted_device_bridge_state()

    def _validate_trusted_device_code(self, code: str) -> None:
        """Verifies a verification code received via Apple's legacy device endpoint."""

        data: dict[str, Any] = {"securityCode": {"code": code}}
        headers: dict[str, Any] = self._get_auth_headers({"Accept": CONTENT_TYPE_JSON})
        try:
            self.session.post(
                f"{self._auth_endpoint}/verify/trusteddevice/securitycode",
                json=data,
                headers=headers,
            )
        except (PyiCloudAPIResponseException, PyiCloud2FARequiredException) as error:
            # For `_W` bridge challenges Apple accepts the code but still answers
            # 409; the body's `securityCode.valid` flag is the real verdict. The
            # session raises an HSA2 409 as PyiCloud2FARequiredException.
            if not self._is_accepted_security_code_conflict(error.response):
                raise
            LOGGER.debug(
                "Apple accepted the trusted-device code with a 409 response; "
                "continuing to session trust."
            )

    @staticmethod
    def _is_accepted_security_code_conflict(response: Response | None) -> bool:
        """Return whether a 409 verify response reports the code as valid."""

        return accepted_security_code_conflict(response)

    @staticmethod
    def _is_accepted_security_code_repair(response: Response | None) -> bool:
        """Return whether a 412 verify response opened a repair session."""

        return accepted_security_code_repair(response)

    def _validate_sms_code(self, code: str) -> None:
        """Verifies a verification code received via Apple's SMS system."""
        trusted_phone_number = self._trusted_phone_number()
        if not trusted_phone_number:
            raise PyiCloudNoTrustedNumberAvailable()

        data: dict[str, Any] = {
            "phoneNumber": trusted_phone_number.as_phone_number_payload(),
            "securityCode": {"code": code},
            "mode": trusted_phone_number.push_mode or "sms",
        }
        headers: dict[str, Any] = self._get_auth_headers({
            "Accept": f"{CONTENT_TYPE_JSON}, {CONTENT_TYPE_TEXT}"
        })

        try:
            self.session.post(
                f"{self._auth_endpoint}/verify/phone/securitycode",
                json=data,
                headers=headers,
            )
        except (PyiCloudAPIResponseException, PyiCloud2FARequiredException) as error:
            # Apple accepts the SMS code but still answers 409; the body's
            # `securityCode.valid` flag is the real verdict. The session raises
            # an HSA2 409 as PyiCloud2FARequiredException. With pending account
            # repair it answers 412 instead.
            if not (
                self._is_accepted_security_code_conflict(error.response)
                or self._is_accepted_security_code_repair(error.response)
            ):
                raise
            LOGGER.debug(
                "Apple accepted the SMS code with a 409 or 412 response; "
                "continuing to session trust."
            )

    def trust_session(self) -> bool:
        """Request session trust to avoid user log in going forward."""
        self._requires_mfa = False

        headers: dict[str, Any] = self._get_auth_headers()

        try:
            self.session.get(
                f"{self._auth_endpoint}/2sv/trust",
                headers=headers,
            )
            self._authenticate_with_token()
            LOGGER.debug("Session trust successful.")
            return True
        except PyiCloudConnectionException:
            # Apple never answered, so the session was not refused.
            raise
        except PyiCloudAPIResponseException as error:
            if _is_auth_server_error(error):
                _raise_auth_server_error(error)
            LOGGER.error("Session trust failed.")
            return False
        except PyiCloud2FARequiredException:
            LOGGER.error("Session trust failed.")
            return False

    @property
    def webservices(self) -> dict[str, dict[str, Any]] | None:
        """Return the webservices map resolved during authentication."""
        return self._webservices

    @webservices.setter
    def webservices(self, value: dict[str, dict[str, Any]]) -> None:
        """Set the webservices map (used when hydrating from session probes)."""
        self._webservices = value

    def _optional_webservice_url(self, ws_key: str) -> str | None:
        """Return a webservice URL, or None when the account does not offer it.

        Apple adds and withdraws hosts over time, so a service that can work
        without a particular endpoint should degrade that feature rather than
        fail to construct at all.
        """

        try:
            return self.get_webservice_url(ws_key)
        except PyiCloudServiceNotActivatedException:
            return None

    def get_webservice_url(self, ws_key: str) -> str:
        """Get webservice URL, raise an exception if not exists."""
        # The map is Apple's JSON, and the `webservices` setter takes it
        # unvalidated, so nothing guarantees either level is really a mapping.
        # Checking rather than trusting the annotation keeps every shape
        # arriving here as one library exception instead of an AttributeError.
        webservices: Any = self._webservices
        entry: Any = (
            webservices.get(ws_key) if isinstance(webservices, Mapping) else None
        )
        if entry is None:
            raise PyiCloudServiceNotActivatedException(
                f"Webservice not available: {ws_key}"
            )

        # Apple sometimes advertises a key with an empty entry -- `schoolwork:
        # {}` is a live example. Indexing ["url"] there raised a bare
        # KeyError('url'), which is not a PyiCloudException and names neither
        # the service nor the reason, so callers could not handle it and users
        # could not act on it. An entry without a usable url means the same
        # thing to a caller as one that was never advertised.
        url: Any = entry.get("url") if isinstance(entry, Mapping) else None
        if not isinstance(url, str) or not url.strip():
            raise PyiCloudServiceNotActivatedException(
                f"Webservice not available: {ws_key} "
                "(Apple advertised it without a usable url)"
            )

        try:
            endpoint = urlparse(url)
            secure = endpoint.scheme.lower() == "https" and bool(endpoint.hostname)
        except ValueError:
            secure = False
        if not secure:
            raise PyiCloudServiceNotActivatedException(
                f"Webservice not available: {ws_key} (expected an HTTPS endpoint)"
            )
        return url

    @property
    def devices(self) -> FindMyiPhoneServiceManager:
        """Returns all devices.

        The manager is built lazily from this account's Find My webservice.
        It starts a background monitor only when ``refresh_interval`` is a
        positive number; ``locate`` decides whether its automatic refreshes
        ask the devices to report their location.
        """
        if not self._devices:
            try:
                self._devices = FindMyiPhoneServiceManager(
                    service_root=self.get_webservice_url("findme"),
                    token_endpoint=self._setup_endpoint,
                    session=self.session,
                    params=self.params,
                    with_family=self._with_family,
                    refresh_interval=self._refresh_interval,
                    family_poll_delay=self._family_poll_delay,
                    family_poll_max_retries=self._family_poll_max_retries,
                    locate=self._locate,
                )
            except PyiCloudServiceNotActivatedException as error:
                raise PyiCloudServiceUnavailable(
                    "Find My iPhone service not available"
                ) from error
        return self._devices

    @property
    def hidemyemail(self) -> HideMyEmailService:
        """Gets the 'HME' service."""
        if not self._hidemyemail:
            service_root: str = self.get_webservice_url("premiummailsettings")
            try:
                self._hidemyemail = HideMyEmailService(
                    service_root=service_root,
                    session=self.session,
                    params=self.params,
                )
            except PyiCloudAPIResponseException as error:
                raise PyiCloudServiceUnavailable(
                    "Hide My Email service not available"
                ) from error
        return self._hidemyemail

    @property
    def iphone(self) -> AppleDevice:
        """Returns the iPhone."""
        return self.devices[0]

    @property
    def account(self) -> AccountService:
        """Gets the 'Account' service."""
        if not self._account:
            service_root: str = self.get_webservice_url("account")
            try:
                self._account = AccountService(
                    service_root=service_root,
                    session=self.session,
                    china_mainland=self._is_china_mainland,
                    params=self.params,
                )
            except PyiCloudAPIResponseException as error:
                raise PyiCloudServiceUnavailable(
                    "Account service not available"
                ) from error
        return self._account

    @property
    def files(self) -> UbiquityService:
        """Gets the 'File' service."""
        if not self._files:
            service_root: str = self.get_webservice_url("ubiquity")
            try:
                self._files = UbiquityService(
                    service_root=service_root,
                    session=self.session,
                    params=self.params,
                )
            except PyiCloudAPIResponseException as error:
                if error.reason == "Account migrated":
                    raise PyiCloudServiceUnavailable(
                        "Files service not available use `api.drive` instead"
                    ) from error
                raise PyiCloudServiceUnavailable(
                    "Files service not available"
                ) from error
        return self._files

    @property
    def photos(self) -> PhotosService:
        """Gets the 'Photo' service."""
        self._request_pcs_for_service("photos")

        if not self._photos:
            service_root: str = self.get_webservice_url("ckdatabasews")
            # Only ckdatabasews is load-bearing here. The upload hosts and the
            # legacy shared-streams host each power one feature, so a missing
            # one disables that feature rather than the whole service: Apple has
            # already withdrawn what uploadimagews points at and may stop
            # advertising it, and not every account advertises the others.
            shared_streams_url: str | None = self._optional_webservice_url(
                "sharedstreams"
            )
            upload_url: str | None = self._optional_webservice_url("uploadimagews")
            photos_upload_url: str | None = self._optional_webservice_url(
                "photosupload"
            )
            self.params["dsid"] = self.data["dsInfo"]["dsid"]

            try:
                self._photos = PhotosService(
                    service_root=service_root,
                    session=self.session,
                    params=self.params,
                    upload_url=upload_url,
                    shared_streams_url=shared_streams_url,
                    photos_upload_url=photos_upload_url,
                    upload_hydration_timeout=self._upload_hydration_timeout,
                    upload_hydration_interval=self._upload_hydration_interval,
                )
            except PyiCloudAPIResponseException as error:
                raise PyiCloudServiceUnavailable(
                    "Photos service not available"
                ) from error
        return self._photos

    @property
    def calendar(self) -> CalendarService:
        """Gets the 'Calendar' service."""
        if not self._calendar:
            service_root: str = self.get_webservice_url("calendar")
            try:
                self._calendar = CalendarService(
                    service_root=service_root, session=self.session, params=self.params
                )
            except PyiCloudAPIResponseException as error:
                raise PyiCloudServiceUnavailable(
                    "Calendar service not available"
                ) from error
        return self._calendar

    @property
    def contacts(self) -> ContactsService:
        """Gets the 'Contacts' service."""
        if not self._contacts:
            service_root: str = self.get_webservice_url("contacts")
            try:
                self._contacts = ContactsService(
                    service_root=service_root, session=self.session, params=self.params
                )
            except PyiCloudAPIResponseException as error:
                raise PyiCloudServiceUnavailable(
                    "Contacts service not available"
                ) from error
        return self._contacts

    @property
    def reminders(self) -> RemindersService:
        """Gets the 'Reminders' service."""
        self._request_pcs_for_service("reminders")

        if not self._reminders:
            try:
                service_root: str = self.get_webservice_url("ckdatabasews")
                self._reminders = RemindersService(
                    service_root=service_root,
                    session=self.session,
                    params=self.params,
                    cloudkit_validation_extra=self._cloudkit_validation_extra,
                )
            except PyiCloudAPIResponseException as error:
                raise PyiCloudServiceUnavailable(
                    "Reminders service not available"
                ) from error
        return self._reminders

    @property
    def drive(self) -> DriveService:
        """Gets the 'Drive' service."""
        self._request_pcs_for_service("iclouddrive")

        if not self._drive:
            try:
                self._drive = DriveService(
                    service_root=self.get_webservice_url("drivews"),
                    document_root=self.get_webservice_url("docws"),
                    session=self.session,
                    params=self.params,
                )
            except PyiCloudAPIResponseException as error:
                raise PyiCloudServiceUnavailable(
                    "Drive service not available"
                ) from error
        return self._drive

    @property
    def notes(self) -> NotesService:
        """Gets the 'Notes' service."""
        # The PCS appName for Notes is "notes3"; "notes" is rejected by the
        # server with "Unknown app requested".
        self._request_pcs_for_service("notes3")

        if not self._notes:
            try:
                service_root: str = self.get_webservice_url("ckdatabasews")
                self._notes = NotesService(
                    service_root=service_root,
                    session=self.session,
                    params=self.params,
                    cloudkit_validation_extra=self._cloudkit_validation_extra,
                )
            except PyiCloudAPIResponseException as error:
                raise PyiCloudServiceUnavailable(
                    "Notes service not available"
                ) from error
        return self._notes

    @property
    def invites(self) -> InvitesService:
        """Gets the 'Invites' service."""
        if not self._invites:
            try:
                service_root: str = self.get_webservice_url("ckdatabasews")
                self._invites = InvitesService(
                    service_root=service_root,
                    session=self.session,
                    params=self.params,
                    cloudkit_validation_extra=self._cloudkit_validation_extra,
                )
            except PyiCloudAPIResponseException as error:
                raise PyiCloudServiceUnavailable(
                    "Invites service not available"
                ) from error
        return self._invites

    @property
    def mail(self) -> MailService:
        """Experimental Mail reads and explicit writes via the discovered gateway."""
        if self._mail is None:
            service_root: str = self.get_webservice_url("mccgateway")
            settings_root = self._optional_webservice_url("mcc")
            try:
                self._mail = MailService(
                    service_root=service_root,
                    session=self.session,
                    params=self.params,
                    settings_root=settings_root,
                )
            except ValueError as error:
                # A discovered URL Mail's stricter validation rejects (query,
                # fragment, or credentials) is an unusable endpoint, not a
                # caller error: surface it as the library's own exception.
                raise PyiCloudServiceUnavailable(
                    "Mail service not available"
                ) from error
        return self._mail

    @property
    def account_name(self) -> str:
        """Retrieves the account name associated with the Apple ID."""

        return self._apple_id

    def __str__(self) -> str:
        """Return a concise human-readable service description."""
        return f"iCloud API: {self.account_name}"

    def __repr__(self) -> str:
        """Mirror ``__str__`` for interactive inspection."""
        return f"<{self}>"

is_china_mainland property

Return whether the current service uses China mainland endpoints.

session property

Return the session.

requires_2sa property

Returns True if two-step authentication is required.

requires_2fa property

Returns True if two-factor authentication is required.

is_trusted_session property

Returns True if the session is trusted.

trusted_devices property

Returns devices trusted for two-step authentication.

two_factor_delivery_method property

Return the current HSA2 delivery method without exposing auth internals.

two_factor_delivery_notice property

Return an optional user-facing note about the active 2FA delivery path.

security_key_names property

Security key names which can be used for the WebAuthn assertion.

fido2_devices property

List the available FIDO2 devices.

webservices property writable

Return the webservices map resolved during authentication.

devices property

Returns all devices.

The manager is built lazily from this account's Find My webservice. It starts a background monitor only when refresh_interval is a positive number; locate decides whether its automatic refreshes ask the devices to report their location.

hidemyemail property

Gets the 'HME' service.

iphone property

Returns the iPhone.

account property

Gets the 'Account' service.

files property

Gets the 'File' service.

photos property

Gets the 'Photo' service.

calendar property

Gets the 'Calendar' service.

contacts property

Gets the 'Contacts' service.

reminders property

Gets the 'Reminders' service.

drive property

Gets the 'Drive' service.

notes property

Gets the 'Notes' service.

invites property

Gets the 'Invites' service.

mail property

Experimental Mail reads and explicit writes via the discovered gateway.

account_name property

Retrieves the account name associated with the Apple ID.

authenticate(force_refresh=False, service=None, pause_2fa=None)

Handles authentication, and persists cookies so that subsequent logins will not cause additional e-mails from Apple.

Source code in pyicloud/base.py
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
def authenticate(
    self,
    force_refresh: bool = False,
    service: str | None = None,
    pause_2fa: bool | None = None,
) -> None:
    """
    Handles authentication, and persists cookies so that
    subsequent logins will not cause additional e-mails from Apple.
    """

    if pause_2fa is None:
        pause_2fa = self._pause_2fa

    self._pcs_granted.clear()
    login_successful = False
    if self._try_reuse_cached_session(force_refresh, pause_2fa):
        login_successful = True

    if not login_successful and self._try_service_one_factor_login(service):
        login_successful = True

    if not login_successful:
        try:
            self._authenticate(pause_2fa=pause_2fa)
            LOGGER.debug("Authentication completed successfully")
        except PyiCloud2FARequiredException:
            self._requires_mfa = True
            LOGGER.debug("2FA is required")

    self._update_state()

get_auth_status()

Probe current authentication state without prompting for login.

Source code in pyicloud/base.py
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
def get_auth_status(self) -> dict[str, Any]:
    """Probe current authentication state without prompting for login."""

    status: dict[str, Any] = {
        "authenticated": False,
        "trusted_session": False,
        "requires_2fa": False,
        "requires_2sa": False,
    }

    if not self.session.data.get("session_token"):
        self._clear_authenticated_state()
        return status

    if not self.session.cookies.get("X-APPLE-WEBAUTH-TOKEN"):
        self._clear_authenticated_state()
        return status

    try:
        self.data = self._validate_token()
        self._update_state()
    except PyiCloudAPIResponseException:
        self._clear_authenticated_state()
        return status

    status.update({
        "authenticated": True,
        "trusted_session": self.is_trusted_session,
        "requires_2fa": self.requires_2fa,
        "requires_2sa": self.requires_2sa,
    })
    return status

logout(*, keep_trusted=False, all_sessions=False, clear_local_session=True)

Log out of the current session and optionally clear local persistence.

Source code in pyicloud/base.py
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
def logout(
    self,
    *,
    keep_trusted: bool = False,
    all_sessions: bool = False,
    clear_local_session: bool = True,
) -> dict[str, Any]:
    """Log out of the current session and optionally clear local persistence."""

    payload: dict[str, bool] = {
        "trustBrowser": keep_trusted,
        "allBrowsers": all_sessions,
    }
    remote_logout_confirmed = False

    if self.params.get("dsid") and self.session.cookies.get(
        "X-APPLE-WEBAUTH-TOKEN"
    ):
        try:
            response = self.session.post(
                f"{self._setup_endpoint}/logout",
                params=dict(self.params),
                data=json.dumps(payload),
                headers={"Content-Type": "text/plain;charset=UTF-8"},
            )
            remote_logout_confirmed = bool(response.json().get("success"))
        except (PyiCloudAPIResponseException, ValueError):
            LOGGER.debug("Remote logout was not confirmed.", exc_info=True)

    local_session_cleared = False
    if clear_local_session:
        self.session.clear_persistence(remove_files=True)
        self._clear_authenticated_state()
        local_session_cleared = True

    return {
        "payload": payload,
        "remote_logout_confirmed": remote_logout_confirmed,
        "local_session_cleared": local_session_cleared,
    }

send_verification_code(device)

Requests that a verification code is sent to the given device.

Source code in pyicloud/base.py
951
952
953
954
955
956
957
958
def send_verification_code(self, device: dict[str, Any]) -> bool:
    """Requests that a verification code is sent to the given device."""
    request: Response = self.session.post(
        f"{self._setup_endpoint}/sendVerificationCode",
        params=self.params,
        json=device,
    )
    return cast(bool, request.json().get("success", False))

validate_verification_code(device, code)

Verifies a verification code received on a trusted device.

Source code in pyicloud/base.py
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
def validate_verification_code(self, device: dict[str, Any], code: str) -> bool:
    """Verifies a verification code received on a trusted device."""

    device.update({"verificationCode": code, "trustBrowser": True})

    try:
        self.session.post(
            f"{self._setup_endpoint}/validateVerificationCode",
            params=self.params,
            json=device,
        )
    except PyiCloudAPIResponseException as error:
        if error.code == -21669:
            # Wrong verification code
            return False
        raise

    self.trust_session()

    return not self.requires_2sa

use_existing_trusted_device_code()

Validate the next 2FA code as one already shown on a trusted device.

Source code in pyicloud/base.py
1094
1095
1096
1097
1098
1099
def use_existing_trusted_device_code(self) -> None:
    """Validate the next 2FA code as one already shown on a trusted device."""

    self._two_factor_code_requested = False
    self._clear_trusted_device_bridge_state()
    self._set_two_factor_delivery_state("trusted_device")

request_2fa_code()

Trigger the active HSA2 delivery route for the current challenge.

Source code in pyicloud/base.py
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
def request_2fa_code(self) -> bool:
    """Trigger the active HSA2 delivery route for the current challenge."""

    if self._auth_data.get("fsaChallenge") or self.security_key_names:
        self._set_two_factor_delivery_state("security_key")
        return False

    if self._two_factor_code_requested:
        LOGGER.debug(
            "2FA code delivery for the current challenge is already in flight."
        )
        return True

    self._clear_trusted_device_bridge_state()

    if self._supports_trusted_device_bridge():
        try:
            self._trusted_device_bridge_state = self._trusted_device_bridge.start(
                session=self.session,
                auth_endpoint=self._auth_endpoint,
                headers=self._get_auth_headers({"Accept": CONTENT_TYPE_JSON}),
                boot_context=self._current_hsa2_boot_context(),
                user_agent=cast(
                    str,
                    self.session.headers.get("User-Agent", _HEADERS["User-Agent"]),
                ),
            )
            self._set_two_factor_delivery_state("trusted_device")
            self._two_factor_code_requested = True
            return True
        except PyiCloudTrustedDevicePromptException:
            LOGGER.debug(
                "Trusted-device bridge bootstrap failed; falling back to "
                "SMS when available.",
                exc_info=True,
            )
            if self._can_request_sms_2fa_code():
                return self._request_sms_2fa_code(
                    notice="Trusted-device prompt failed; falling back to SMS."
                )
            raise

    if self._can_request_sms_2fa_code():
        return self._request_sms_2fa_code()

    return False

confirm_security_key(device=None, *, event=None)

Conduct the WebAuthn assertion ceremony with user's FIDO2 device.

The call blocks until the security key is touched. Set event from another thread to stop waiting; when the wait is aborted through it, a PyiCloudSecurityKeyTimeoutException is raised. Missing challenge data raises PyiCloudAPIResponseException; no available device or any other failure of the ceremony raises PyiCloudSecurityKeyException. The security key exceptions derive from PyiCloudException, with the underlying fido2 error chained as __cause__.

Source code in pyicloud/base.py
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
def confirm_security_key(
    self,
    device: CtapHidDevice | None = None,
    *,
    event: Event | None = None,
) -> None:
    """Conduct the WebAuthn assertion ceremony with user's FIDO2 device.

    The call blocks until the security key is touched. Set ``event`` from
    another thread to stop waiting; when the wait is aborted through it, a
    ``PyiCloudSecurityKeyTimeoutException`` is raised. Missing challenge
    data raises ``PyiCloudAPIResponseException``; no available device or
    any other failure of the ceremony raises
    ``PyiCloudSecurityKeyException``. The security key exceptions derive
    from ``PyiCloudException``, with the underlying fido2 error chained
    as ``__cause__``.
    """
    fsa: dict[str, Any] = self._auth_data.get("fsaChallenge", {})
    try:
        challenge = fsa["challenge"]
        allowed_credentials = fsa["keyHandles"]
        rp_id = fsa["rpId"]
    except KeyError as error:
        raise PyiCloudAPIResponseException(
            "Missing WebAuthn challenge data"
        ) from error

    if not device:
        devices: list[CtapHidDevice] = list(CtapHidDevice.list_devices())

        if not devices:
            raise PyiCloudSecurityKeyException("No FIDO2 devices found")

        device = devices[0]

    client = Fido2Client(
        device,
        client_data_collector=DefaultClientDataCollector("https://apple.com"),
    )
    credentials: list[PublicKeyCredentialDescriptor] = [
        PublicKeyCredentialDescriptor(
            id=b64url_decode(cred_id), type=PublicKeyCredentialType("public-key")
        )
        for cred_id in allowed_credentials
    ]
    assertion_options = PublicKeyCredentialRequestOptions(
        challenge=b64url_decode(challenge),
        rp_id=rp_id,
        allow_credentials=credentials,
        user_verification=UserVerificationRequirement("discouraged"),
    )
    try:
        result: AuthenticationResponse = client.get_assertion(
            assertion_options, event=event
        ).get_response(0)
    except ClientError as error:
        if (
            error.code == ClientError.ERR.TIMEOUT
            and event is not None
            and event.is_set()
        ):
            raise PyiCloudSecurityKeyTimeoutException(
                "Security key confirmation was cancelled or timed out "
                "before the key was touched"
            ) from error
        raise PyiCloudSecurityKeyException(
            "Security key confirmation failed"
        ) from error

    self._submit_webauthn_assertion_response({
        "challenge": challenge,
        "clientData": b64_encode(result.response.client_data),
        "signatureData": b64_encode(result.response.signature),
        "authenticatorData": b64_encode(result.response.authenticator_data),
        "userHandle": b64_encode(result.response.user_handle)
        if result.response.user_handle
        else None,
        "credentialID": b64_encode(result.raw_id),
        "rpId": rp_id,
    })

    self.trust_session()

validate_2fa_code(code)

Verifies a verification code received via Apple's 2FA system (HSA2).

A bridge challenge is single-use: a rejected code, a consumed challenge, or an ambiguous transport failure retires it and raises PyiCloudTrustedDeviceChallengeRequiredException so callers request a fresh code instead of falling back to the legacy verifier.

Source code in pyicloud/base.py
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
def validate_2fa_code(self, code: str) -> bool:
    """Verifies a verification code received via Apple's 2FA system (HSA2).

    A bridge challenge is single-use: a rejected code, a consumed
    challenge, or an ambiguous transport failure retires it and raises
    ``PyiCloudTrustedDeviceChallengeRequiredException`` so callers request
    a fresh code instead of falling back to the legacy verifier.
    """
    bridge_state = self._trusted_device_bridge_state
    bridge_active = (
        bridge_state is not None
        and not bridge_state.uses_legacy_trusted_device_verifier
    )
    if not bridge_active:
        # SMS and deliberately selected legacy routes do not keep a
        # reusable bridge challenge.
        self._two_factor_code_requested = False
    try:
        if self.two_factor_delivery_method == "sms":
            self._validate_sms_code(code)
        elif bridge_active:
            assert bridge_state is not None
            self._validate_bridge_code(code, bridge_state)
        else:
            self._validate_trusted_device_code(code)
    except KeyboardInterrupt:
        # The interrupt may have landed after Apple accepted the step-2
        # POST, so the captured challenge is not safe to replay.
        self._discard_bridge_challenge(bridge_state)
        raise
    except (
        PyiCloudTrustedDeviceVerificationException,
        PyiCloudConnectionException,
    ):
        # A legacy-routed bridge POST can fail at transport while its
        # websocket is still open; retire the challenge instead of
        # leaking it. Bridge-path exits above already cleared the state.
        self._clear_trusted_device_bridge_state()
        raise
    except (PyiCloudAPIResponseException, PyiCloud2FARequiredException):
        # A legacy-routed bridge challenge is spent once the verifier
        # rejects the code; close it instead of leaking the socket.
        self._discard_bridge_challenge(bridge_state)
        LOGGER.error("Code verification failed.")
        return False
    except Exception:
        # Unexpected failures (e.g. a malformed push frame decoding to a
        # ValueError) can escape after Apple accepted the step-2 POST.
        # Retire the challenge instead of leaking the websocket or let
        # request_2fa_code() skip the replacement it would report.
        self._discard_bridge_challenge(bridge_state)
        raise

    if bridge_state is not None:
        self._clear_trusted_device_bridge_state()
    self._two_factor_code_requested = False
    LOGGER.debug("Code verification successful.")

    self.trust_session()
    return not self.requires_2sa

trust_session()

Request session trust to avoid user log in going forward.

Source code in pyicloud/base.py
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
def trust_session(self) -> bool:
    """Request session trust to avoid user log in going forward."""
    self._requires_mfa = False

    headers: dict[str, Any] = self._get_auth_headers()

    try:
        self.session.get(
            f"{self._auth_endpoint}/2sv/trust",
            headers=headers,
        )
        self._authenticate_with_token()
        LOGGER.debug("Session trust successful.")
        return True
    except PyiCloudConnectionException:
        # Apple never answered, so the session was not refused.
        raise
    except PyiCloudAPIResponseException as error:
        if _is_auth_server_error(error):
            _raise_auth_server_error(error)
        LOGGER.error("Session trust failed.")
        return False
    except PyiCloud2FARequiredException:
        LOGGER.error("Session trust failed.")
        return False

get_webservice_url(ws_key)

Get webservice URL, raise an exception if not exists.

Source code in pyicloud/base.py
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
def get_webservice_url(self, ws_key: str) -> str:
    """Get webservice URL, raise an exception if not exists."""
    # The map is Apple's JSON, and the `webservices` setter takes it
    # unvalidated, so nothing guarantees either level is really a mapping.
    # Checking rather than trusting the annotation keeps every shape
    # arriving here as one library exception instead of an AttributeError.
    webservices: Any = self._webservices
    entry: Any = (
        webservices.get(ws_key) if isinstance(webservices, Mapping) else None
    )
    if entry is None:
        raise PyiCloudServiceNotActivatedException(
            f"Webservice not available: {ws_key}"
        )

    # Apple sometimes advertises a key with an empty entry -- `schoolwork:
    # {}` is a live example. Indexing ["url"] there raised a bare
    # KeyError('url'), which is not a PyiCloudException and names neither
    # the service nor the reason, so callers could not handle it and users
    # could not act on it. An entry without a usable url means the same
    # thing to a caller as one that was never advertised.
    url: Any = entry.get("url") if isinstance(entry, Mapping) else None
    if not isinstance(url, str) or not url.strip():
        raise PyiCloudServiceNotActivatedException(
            f"Webservice not available: {ws_key} "
            "(Apple advertised it without a usable url)"
        )

    try:
        endpoint = urlparse(url)
        secure = endpoint.scheme.lower() == "https" and bool(endpoint.hostname)
    except ValueError:
        secure = False
    if not secure:
        raise PyiCloudServiceNotActivatedException(
            f"Webservice not available: {ws_key} (expected an HTTPS endpoint)"
        )
    return url

Internal ownership

PyiCloudService remains defined in pyicloud.base and owns authentication orchestration, lazy service creation, endpoints and shared session state. Private pyicloud._auth_protocol helpers build request-local header dictionaries and classify verification responses. They do not send requests, create sessions, persist state or retry authentication. Public imports and method signatures are unchanged; private helper modules are not consumer contracts.