Skip to content

key_manager

key_manager

SuperCell Developer Portal Key Manager

Automates API key management for the Clash of Clans developer portal.

Handles login, IP detection, key creation/revocation, and automatic IP-based key rotation. Ported to httpx from the aiohttp reference implementation (coc.py's http.py / marsidev/get-sc-key).

Developer Portal Internal API Endpoints

Base URL: https://developer.clashofclans.com/api

POST /login - Authenticate with email/password (session cookie) POST /apikey/list - List all keys for the authenticated account POST /apikey/create - Create a new API key POST /apikey/revoke - Delete/revoke an existing API key

KeyManagerError

Bases: Exception

Base exception for key manager errors.

InvalidCredentials

Bases: KeyManagerError

Raised when email/password login fails.

KeyLimitReached

Bases: KeyManagerError

Raised when the 10 key per account limit is hit.

SyncKeyManager

SyncKeyManager(
    email: str,
    password: str,
    key_name: str = "cocapi_auto",
    key_count: int = 1,
    key_description: str = "Auto-generated by cocapi KeyManager",
    key_scopes: str = "clash",
    persist_keys: bool = False,
    key_storage_path: str | None = None,
)

Synchronous key manager for the SuperCell developer portal.

Handles login, IP detection, and API key lifecycle management using httpx.Client with cookie persistence.

Usage::

with SyncKeyManager("email", "password") as km:
    tokens = km.manage_keys()
    # Use tokens[0] with CocApi

Or via CocApi integration::

api = CocApi.from_credentials("email@example.com", "password")
Source code in cocapi/key_manager.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def __init__(
    self,
    email: str,
    password: str,
    key_name: str = "cocapi_auto",
    key_count: int = 1,
    key_description: str = "Auto-generated by cocapi KeyManager",
    key_scopes: str = "clash",
    persist_keys: bool = False,
    key_storage_path: str | None = None,
) -> None:
    self.email = email
    self.password = password
    self.key_name = key_name
    self.key_count = min(key_count, _MAX_KEYS_PER_ACCOUNT)
    self.key_description = key_description
    self.key_scopes = key_scopes
    self.persist_keys = persist_keys
    self._cache_path = (
        Path(key_storage_path) if key_storage_path else _DEFAULT_KEY_STORAGE_PATH
    )

    self._client = httpx.Client(follow_redirects=True)
    self._logged_in = False
    self._current_ip: str | None = None

close

close() -> None

Close the underlying HTTP client.

Source code in cocapi/key_manager.py
292
293
294
def close(self) -> None:
    """Close the underlying HTTP client."""
    self._client.close()

manage_keys

manage_keys() -> list[str]

Main orchestration: ensure we have valid keys for the current IP.

If persist_keys is enabled, checks the local cache first. When the cached IP matches the current IP, returns cached tokens immediately without contacting the developer portal.

  1. (Optional) Check local cache
  2. Login to developer portal
  3. Detect current public IP
  4. List existing keys
  5. Revoke stale keys (wrong IP), keep valid ones
  6. Create new keys if needed
  7. (Optional) Save tokens to local cache
  8. Return list of usable API token strings
Source code in cocapi/key_manager.py
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
def manage_keys(self) -> list[str]:
    """
    Main orchestration: ensure we have valid keys for the current IP.

    If persist_keys is enabled, checks the local cache first. When the
    cached IP matches the current IP, returns cached tokens immediately
    without contacting the developer portal.

    1. (Optional) Check local cache
    2. Login to developer portal
    3. Detect current public IP
    4. List existing keys
    5. Revoke stale keys (wrong IP), keep valid ones
    6. Create new keys if needed
    7. (Optional) Save tokens to local cache
    8. Return list of usable API token strings
    """
    # Try local cache first (avoids login entirely)
    if self.persist_keys:
        cached = _load_cached_keys(self._cache_path, self.key_name)
        if cached:
            cached_tokens, cached_ip = cached
            current_ip = self._detect_ip()
            self._current_ip = current_ip
            if cached_ip == current_ip:
                logger.info(
                    "Using %d cached token(s) (IP unchanged: %s)",
                    len(cached_tokens),
                    current_ip,
                )
                return cached_tokens
            logger.info(
                "IP changed (%s -> %s), cached tokens invalidated",
                cached_ip,
                current_ip,
            )

    self._login()

    if not self._current_ip:
        self._current_ip = self._detect_ip()

    existing_keys = self._list_keys()
    valid, stale, unmanaged = _filter_managed_keys(
        existing_keys, self._current_ip, self.key_name
    )

    logger.info(
        "Key audit: %d valid, %d stale (wrong IP), %d unmanaged",
        len(valid),
        len(stale),
        len(unmanaged),
    )

    # Revoke stale keys (wrong IP)
    for key in stale:
        self._revoke_key(key["id"])

    # Collect tokens from valid keys
    tokens = [k["key"] for k in valid]

    # Determine how many new keys to create
    keys_needed = self.key_count - len(tokens)
    total_after_revoke = len(unmanaged) + len(valid)
    available_slots = _MAX_KEYS_PER_ACCOUNT - total_after_revoke

    if keys_needed > 0:
        keys_to_create = min(keys_needed, available_slots)

        if keys_to_create < keys_needed:
            logger.warning(
                "Account has %d keys (max %d). Can only create %d of %d needed. "
                "Delete some keys at https://developer.clashofclans.com "
                "or lower key_count.",
                total_after_revoke,
                _MAX_KEYS_PER_ACCOUNT,
                keys_to_create,
                keys_needed,
            )

        for _i in range(keys_to_create):
            suffix = f" #{len(tokens) + 1}" if self.key_count > 1 else ""
            new_key = self._create_key(
                name=self.key_name,
                description=f"{self.key_description}{suffix}",
            )
            tokens.append(new_key["key"])

    if not tokens:
        raise KeyManagerError(
            "No usable API keys available. The account may have reached "
            "the 10-key limit with keys from other applications. "
            "Please delete unused keys at https://developer.clashofclans.com"
        )

    # Save to local cache if persistence is enabled
    if self.persist_keys:
        _save_cached_keys(self._cache_path, self.key_name, tokens, self._current_ip)

    logger.info("Key manager ready with %d token(s)", len(tokens))
    return tokens

refresh_keys

refresh_keys() -> list[str]

Re-detect IP and re-initialize keys.

Call this when the API returns accessDenied.invalidIp.

Source code in cocapi/key_manager.py
533
534
535
536
537
538
539
540
541
542
543
544
def refresh_keys(self) -> list[str]:
    """
    Re-detect IP and re-initialize keys.

    Call this when the API returns accessDenied.invalidIp.
    """
    logger.info("Refreshing keys due to IP change...")
    if self.persist_keys:
        _invalidate_cached_keys(self._cache_path, self.key_name)
    self._current_ip = None
    self._logged_in = False
    return self.manage_keys()

AsyncKeyManager

AsyncKeyManager(
    email: str,
    password: str,
    key_name: str = "cocapi_auto",
    key_count: int = 1,
    key_description: str = "Auto-generated by cocapi KeyManager",
    key_scopes: str = "clash",
    persist_keys: bool = False,
    key_storage_path: str | None = None,
)

Async key manager for the SuperCell developer portal.

Same functionality as SyncKeyManager but using httpx.AsyncClient.

Usage::

async with AsyncKeyManager("email", "password") as km:
    tokens = await km.manage_keys()
Source code in cocapi/key_manager.py
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
def __init__(
    self,
    email: str,
    password: str,
    key_name: str = "cocapi_auto",
    key_count: int = 1,
    key_description: str = "Auto-generated by cocapi KeyManager",
    key_scopes: str = "clash",
    persist_keys: bool = False,
    key_storage_path: str | None = None,
) -> None:
    self.email = email
    self.password = password
    self.key_name = key_name
    self.key_count = min(key_count, _MAX_KEYS_PER_ACCOUNT)
    self.key_description = key_description
    self.key_scopes = key_scopes
    self.persist_keys = persist_keys
    self._cache_path = (
        Path(key_storage_path) if key_storage_path else _DEFAULT_KEY_STORAGE_PATH
    )

    self._client: httpx.AsyncClient | None = None
    self._logged_in = False
    self._current_ip: str | None = None

close async

close() -> None

Close the underlying async HTTP client.

Source code in cocapi/key_manager.py
597
598
599
600
601
async def close(self) -> None:
    """Close the underlying async HTTP client."""
    if self._client:
        await self._client.aclose()
        self._client = None

manage_keys async

manage_keys() -> list[str]

Main orchestration: ensure we have valid keys for the current IP. Same logic as SyncKeyManager.manage_keys() but async.

Source code in cocapi/key_manager.py
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
async def manage_keys(self) -> list[str]:
    """
    Main orchestration: ensure we have valid keys for the current IP.
    Same logic as SyncKeyManager.manage_keys() but async.
    """
    # Try local cache first (avoids login entirely)
    if self.persist_keys:
        cached = _load_cached_keys(self._cache_path, self.key_name)
        if cached:
            cached_tokens, cached_ip = cached
            current_ip = await self._detect_ip()
            self._current_ip = current_ip
            if cached_ip == current_ip:
                logger.info(
                    "Using %d cached token(s) (IP unchanged: %s)",
                    len(cached_tokens),
                    current_ip,
                )
                return cached_tokens
            logger.info(
                "IP changed (%s -> %s), cached tokens invalidated",
                cached_ip,
                current_ip,
            )

    await self._login()

    if not self._current_ip:
        self._current_ip = await self._detect_ip()

    existing_keys = await self._list_keys()
    valid, stale, unmanaged = _filter_managed_keys(
        existing_keys, self._current_ip, self.key_name
    )

    logger.info(
        "Key audit: %d valid, %d stale (wrong IP), %d unmanaged",
        len(valid),
        len(stale),
        len(unmanaged),
    )

    for key in stale:
        await self._revoke_key(key["id"])

    tokens = [k["key"] for k in valid]

    keys_needed = self.key_count - len(tokens)
    total_after_revoke = len(unmanaged) + len(valid)
    available_slots = _MAX_KEYS_PER_ACCOUNT - total_after_revoke

    if keys_needed > 0:
        keys_to_create = min(keys_needed, available_slots)

        if keys_to_create < keys_needed:
            logger.warning(
                "Account has %d keys (max %d). Can only create %d of %d needed.",
                total_after_revoke,
                _MAX_KEYS_PER_ACCOUNT,
                keys_to_create,
                keys_needed,
            )

        for _i in range(keys_to_create):
            suffix = f" #{len(tokens) + 1}" if self.key_count > 1 else ""
            new_key = await self._create_key(
                name=self.key_name,
                description=f"{self.key_description}{suffix}",
            )
            tokens.append(new_key["key"])

    if not tokens:
        raise KeyManagerError(
            "No usable API keys available. The account may have reached "
            "the 10-key limit with keys from other applications. "
            "Please delete unused keys at https://developer.clashofclans.com"
        )

    if self.persist_keys:
        _save_cached_keys(self._cache_path, self.key_name, tokens, self._current_ip)

    logger.info("Key manager ready with %d token(s)", len(tokens))
    return tokens

refresh_keys async

refresh_keys() -> list[str]

Re-detect IP and re-initialize keys.

Source code in cocapi/key_manager.py
818
819
820
821
822
823
824
825
async def refresh_keys(self) -> list[str]:
    """Re-detect IP and re-initialize keys."""
    logger.info("Refreshing keys due to IP change...")
    if self.persist_keys:
        _invalidate_cached_keys(self._cache_path, self.key_name)
    self._current_ip = None
    self._logged_in = False
    return await self.manage_keys()