Spaces:
Running
Running
sync: upstream 8dfff832 (v6.18.5) + custom addons (KeyRotator, 401/403 rotation, sol/terra/luna, ScannerTrap, health, Py3.12 compat)
2e7b8ca Download src/free_claude_code/providers/credential_validation.py from dherain24/claude-proxy: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/spaces/dherain24/claude-proxy/resolve/main/src/free_claude_code/providers/credential_validation.py
- Command line
-
hf download hf://spaces/dherain24/claude-proxy/src/free_claude_code/providers/credential_validation.py
-
curl -L -o credential_validation.py https://huggingface.co/spaces/dherain24/claude-proxy/resolve/main/src/free_claude_code/providers/credential_validation.py
13 kB
| from __future__ import annotations | |
| """Non-generating credential checks for Admin Apply, independent of inference. | |
| Only documented authenticated endpoints belong here. Public model catalogs and | |
| management endpoints requiring a different key cannot validate inference keys. | |
| Failure defaults to unverified; rejection requires provider-specific evidence. | |
| """ | |
| import asyncio | |
| from collections.abc import Callable, Mapping | |
| from dataclasses import dataclass, replace | |
| from enum import StrEnum | |
| import httpx | |
| from free_claude_code.config.admin.credentials import CredentialSubmission | |
| from free_claude_code.config.provider_catalog import PROVIDER_CATALOG | |
| from free_claude_code.config.settings import Settings | |
| from free_claude_code.core.json_types import JsonValue | |
| from free_claude_code.providers.runtime.config import string_setting | |
| REQUEST_TIMEOUT = 5.0 | |
| MAX_CONCURRENCY = 8 | |
| class CredentialStatus(StrEnum): | |
| VERIFIED = "verified" | |
| REJECTED = "rejected" | |
| UNVERIFIED = "unverified" | |
| class CredentialCheck: | |
| key: str | |
| status: CredentialStatus | |
| message: str | |
| index: int = 0 | |
| provider_id: str | None = None | |
| def _field(payload: JsonValue, name: str) -> JsonValue: | |
| return payload.get(name) if isinstance(payload, Mapping) else None | |
| def _list_field(name: str) -> Callable[[JsonValue], bool]: | |
| return lambda payload: isinstance(_field(payload, name), list) | |
| def _identity(name: str) -> Callable[[JsonValue], bool]: | |
| return lambda payload: isinstance(_field(payload, name), str) | |
| class _Probe: | |
| provider_id: str | |
| path: str | |
| accepts: Callable[[JsonValue], bool] | |
| rejected_statuses: frozenset[int] = frozenset() | |
| _AUTH_401 = frozenset({401}) | |
| _MODELS = _list_field("data") | |
| # Sources document both authenticated reads and (where enabled) rejection codes. | |
| # https://openrouter.ai/docs/api/api-reference/api-keys/get-current-key | |
| # https://console.groq.com/docs/errors | |
| # https://docs.together.ai/reference/models | |
| # https://api-docs.deepseek.com/quick_start/error_codes/ | |
| # https://api.x.ai/api-docs/openapi.json | |
| # https://docs.siliconflow.com/cn/api-reference/userinfo/get-user-info | |
| # https://ai.google.dev/gemini-api/docs/generate-content/api-errors | |
| # https://github.com/nebius/nebius-physical-ai/blob/main/docs/workbench/token-factory.md | |
| # https://www.scaleway.com/en/docs/generative-apis/ | |
| # https://docs.opper.ai/build/chat/drop-in-sdks | |
| # https://vercel.com/docs/ai-gateway/sdks-and-apis/rest-api | |
| # https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/hf_api.py | |
| # https://docs.cohere.com/reference/list-models | |
| # https://docs.wafer.ai/serverless/usage-api | |
| # https://platform.kimi.ai/docs/api/errors | |
| # https://router.bynara.id/id/docs | |
| # https://platform.experientiallabs.ai/docs/authentication | |
| _PROBES = ( | |
| # https://platform.claude.com/docs/en/api/models/list | |
| _Probe("anthropic", "/models?limit=1", _MODELS, _AUTH_401), | |
| _Probe( | |
| "open_router", | |
| "/key", | |
| lambda p: isinstance(_field(p, "data"), Mapping), | |
| _AUTH_401, | |
| ), | |
| _Probe("groq", "/models", _MODELS, _AUTH_401), | |
| _Probe("together", "/models", lambda p: isinstance(p, list), _AUTH_401), | |
| _Probe( | |
| "deepseek", | |
| "/user/balance", | |
| lambda p: ( | |
| isinstance(_field(p, "is_available"), bool) | |
| and isinstance(_field(p, "balance_infos"), list) | |
| ), | |
| _AUTH_401, | |
| ), | |
| _Probe("xai", "/api-key", _identity("api_key_id"), _AUTH_401), | |
| _Probe( | |
| "siliconflow", | |
| "/user/info", | |
| lambda p: ( | |
| _field(p, "code") == 20000 | |
| and _field(p, "status") is True | |
| and isinstance(_field(p, "data"), Mapping) | |
| ), | |
| _AUTH_401, | |
| ), | |
| _Probe( | |
| "gemini", | |
| "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1", | |
| _list_field("models"), | |
| ), | |
| _Probe("nebius", "/models", _MODELS, _AUTH_401), | |
| _Probe("scaleway", "/models", _MODELS, _AUTH_401), | |
| _Probe("opper", "/models", _MODELS, _AUTH_401), | |
| _Probe( | |
| "vercel", | |
| "/credits", | |
| lambda p: isinstance(_field(p, "balance"), str | int | float), | |
| _AUTH_401, | |
| ), | |
| _Probe( | |
| "huggingface", | |
| "https://huggingface.co/api/whoami-v2", | |
| _identity("name"), | |
| _AUTH_401, | |
| ), | |
| _Probe( | |
| "cohere", | |
| "https://api.cohere.com/v1/models?page_size=1", | |
| _list_field("models"), | |
| frozenset({401, 498}), | |
| ), | |
| _Probe( | |
| "wafer", | |
| "https://api.wafer.ai/v1/usage/me?period=1d&endpoint=pass.wafer.ai", | |
| _identity("user_id"), | |
| _AUTH_401, | |
| ), | |
| _Probe( | |
| "kimi", | |
| "/users/me/balance", | |
| lambda p: isinstance( | |
| _field(_field(p, "data"), "available_balance"), int | float | |
| ), | |
| _AUTH_401, | |
| ), | |
| _Probe("nararoute", "/models", _MODELS, _AUTH_401), | |
| _Probe("experiential", "/models", _MODELS, _AUTH_401), | |
| _Probe("orcarouter", "/models", _MODELS, _AUTH_401), | |
| # xKiro's /models is public; /usage requires the inference API key. | |
| # https://docs.xkiro.com/api/usage/ | |
| _Probe( | |
| "xkiro", | |
| "/usage", | |
| lambda p: ( | |
| _field(p, "object") == "usage" | |
| and isinstance(_field(p, "windows"), list) | |
| and isinstance(_field(p, "free_tokens"), Mapping) | |
| ), | |
| _AUTH_401, | |
| ), | |
| # Positive evidence only: these errors can also reflect permissions, budget, | |
| # token type, or an undocumented response contract. Never reject on failure. | |
| # https://docs.deepinfra.com/api-reference/account/me | |
| # https://docs.mistral.ai/api/endpoint/models | |
| # https://docs.wandb.ai/inference/api-reference | |
| # https://docs.github.com/en/rest/users/users#get-the-authenticated-user | |
| # https://platform.minimax.io/docs/api-reference/models/openai/list-models | |
| # https://novita.ai/docs/api-reference/basic-get-user-balance | |
| # https://inference-docs.cerebras.ai/api-reference/models/list-models | |
| # https://docs.sambanova.ai/docs/api-reference/models/get-environments-available-model-list-metadata | |
| # https://docs.fireworks.ai/api-reference/list-accounts | |
| # https://cheaperinference.com/docs | |
| _Probe("deepinfra", "https://api.deepinfra.com/v1/me", _identity("uid")), | |
| _Probe("mistral", "/models", _MODELS), | |
| _Probe("wandb", "/models", _MODELS), | |
| _Probe("minimax", "/models", _MODELS), | |
| _Probe( | |
| "novita", | |
| "https://api.novita.ai/openapi/v1/billing/balance/detail", | |
| _identity("availableBalance"), | |
| ), | |
| _Probe("cerebras", "/models", _MODELS), | |
| _Probe("sambanova", "/models", _MODELS), | |
| _Probe("cheaperinference", "/models", _MODELS), | |
| _Probe( | |
| "fireworks", | |
| "https://api.fireworks.ai/v1/accounts?pageSize=1", | |
| _list_field("accounts"), | |
| ), | |
| ) | |
| _PROBE_BY_KEY = { | |
| PROVIDER_CATALOG[probe.provider_id].credential_env: probe for probe in _PROBES | |
| } | |
| def _unverified(key: str, message: str) -> CredentialCheck: | |
| return CredentialCheck(key, CredentialStatus.UNVERIFIED, message) | |
| def _invalid_google_key(payload: JsonValue) -> bool: | |
| details = _field(_field(payload, "error"), "details") | |
| return isinstance(details, list) and any( | |
| _field(detail, "reason") == "API_KEY_INVALID" for detail in details | |
| ) | |
| def _interpret(key: str, probe: _Probe, response: httpx.Response) -> CredentialCheck: | |
| try: | |
| payload: JsonValue = response.json() | |
| except ValueError: | |
| return _unverified( | |
| key, "Could not verify this key: unexpected provider response." | |
| ) | |
| if response.is_success and probe.accepts(payload): | |
| if ( | |
| probe.provider_id == "deepseek" and _field(payload, "is_available") is False | |
| ) or ( | |
| probe.provider_id == "xai" | |
| and any( | |
| _field(payload, flag) is True | |
| for flag in ("api_key_disabled", "api_key_blocked", "team_blocked") | |
| ) | |
| ): | |
| return _unverified( | |
| key, | |
| "The key was recognized, but the provider reports a billing or access restriction.", | |
| ) | |
| return CredentialCheck(key, CredentialStatus.VERIFIED, "API key accepted.") | |
| # Require an API error body; an HTML intermediary's auth challenge is not | |
| # evidence that the provider rejected the submitted credential. | |
| api_error = isinstance(payload, Mapping) and bool( | |
| payload.get("error") or payload.get("message") or payload.get("detail") | |
| ) | |
| # SiliconFlow's /user/info OpenAPI defines 401 JSON as StringData. | |
| if probe.provider_id == "siliconflow" and isinstance(payload, str): | |
| api_error = True | |
| if (api_error and response.status_code in probe.rejected_statuses) or ( | |
| probe.provider_id == "gemini" | |
| and response.status_code == 400 | |
| and _invalid_google_key(payload) | |
| ): | |
| return CredentialCheck( | |
| key, | |
| CredentialStatus.REJECTED, | |
| "The provider rejected this API key. Check it or create a new key.", | |
| ) | |
| if probe.provider_id == "anthropic": | |
| return _unverified( | |
| key, | |
| "Could not verify this key. Check the Workspace ID, API permissions, billing, or rate limits. You can still save it.", | |
| ) | |
| if response.status_code in {402, 403}: | |
| return _unverified( | |
| key, | |
| "Could not verify this key: check the provider's billing or permissions.", | |
| ) | |
| return _unverified( | |
| key, "Could not verify this key with the provider. You can still save it." | |
| ) | |
| async def _check_one( | |
| settings: Settings, key: str, probe: _Probe, credential: str | |
| ) -> CredentialCheck: | |
| descriptor = PROVIDER_CATALOG[probe.provider_id] | |
| base = ( | |
| string_setting(settings, descriptor.base_url_attr) | |
| or descriptor.default_base_url | |
| ) | |
| if base != descriptor.default_base_url: | |
| return _unverified( | |
| key, "Key verification is unavailable for this custom endpoint." | |
| ) | |
| assert base is not None | |
| url = ( | |
| probe.path | |
| if probe.path.startswith("https://") | |
| else base.rstrip("/") + probe.path | |
| ) | |
| headers = {"Accept": "application/json"} | |
| if probe.provider_id == "gemini": | |
| headers["x-goog-api-key"] = credential | |
| else: | |
| headers["Authorization"] = f"Bearer {credential}" | |
| if probe.provider_id == "anthropic": | |
| from free_claude_code.providers.anthropic.headers import api_headers | |
| headers.update(api_headers(credential, settings.anthropic_workspace_id)) | |
| if probe.provider_id == "novita": | |
| headers["Content-Type"] = "application/json" | |
| try: | |
| async with asyncio.timeout(REQUEST_TIMEOUT): | |
| async with httpx.AsyncClient( | |
| proxy=string_setting(settings, descriptor.proxy_attr), | |
| timeout=REQUEST_TIMEOUT, | |
| follow_redirects=False, | |
| ) as client: | |
| response = await client.get(url, headers=headers) | |
| return _interpret(key, probe, response) | |
| except (TimeoutError, httpx.RequestError, UnicodeError): | |
| return _unverified(key, "Could not reach the provider to verify this key.") | |
| async def check_credentials( | |
| settings: Settings, submissions: tuple[CredentialSubmission, ...] | |
| ) -> tuple[CredentialCheck, ...]: | |
| """Check every submitted entry with bounded workers and per-attempt timeouts.""" | |
| entries = [ | |
| (submission, index, credential) | |
| for submission in submissions | |
| for index, credential in enumerate(submission.credentials) | |
| ] | |
| results = [ | |
| CredentialCheck( | |
| submission.key, | |
| CredentialStatus.UNVERIFIED, | |
| "Automatic verification is unavailable for " | |
| + ( | |
| " and ".join( | |
| descriptor.display_name | |
| for descriptor in PROVIDER_CATALOG.values() | |
| if descriptor.credential_env == submission.key | |
| ) | |
| or "this provider" | |
| ) | |
| + ".", | |
| index, | |
| submission.provider_id, | |
| ) | |
| for submission, index, _ in entries | |
| ] | |
| pending = iter(enumerate(entries)) | |
| async def run() -> None: | |
| for result_index, (submission, index, credential) in pending: | |
| probe = ( | |
| _PROBE_BY_KEY.get(submission.key) | |
| if submission.provider_id is None | |
| else None | |
| ) | |
| if probe is not None: | |
| check = await _check_one( | |
| settings, submission.key, probe, credential.get_secret_value() | |
| ) | |
| results[result_index] = replace( | |
| check, index=index, provider_id=submission.provider_id | |
| ) | |
| async with asyncio.TaskGroup() as group: | |
| for _ in range(min(MAX_CONCURRENCY, len(entries))): | |
| group.create_task(run()) | |
| return tuple(results) | |