233 lines
7.8 KiB
Python
233 lines
7.8 KiB
Python
"""Credential discovery with isolation between provider profiles.
|
|
|
|
AiRouter never writes tokens to disk. OpenCode credentials are only offered to
|
|
OpenCode profiles; other providers use their own explicit or conventional key.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
from urllib.parse import urlsplit
|
|
|
|
from .config import Config, ProviderProfile
|
|
|
|
_OPENCODE_ENV_NAMES = {"OPENCODE_API_KEY", "OPENCODE_GO_API_KEY"}
|
|
_CONVENTIONAL_ENV_NAMES = {
|
|
"opencode": ("OPENCODE_API_KEY", "OPENCODE_GO_API_KEY"),
|
|
"openai": ("OPENAI_API_KEY",),
|
|
"openrouter": ("OPENROUTER_API_KEY",),
|
|
"groq": ("GROQ_API_KEY",),
|
|
"together": ("TOGETHER_API_KEY", "TOGETHERAI_API_KEY"),
|
|
"deepseek": ("DEEPSEEK_API_KEY",),
|
|
"mistral": ("MISTRAL_API_KEY",),
|
|
"ollama": ("OLLAMA_API_KEY",),
|
|
"lmstudio": ("LMSTUDIO_API_KEY",),
|
|
"vllm": ("VLLM_API_KEY",),
|
|
"llamacpp": ("LLAMACPP_API_KEY",),
|
|
"custom": ("CUSTOM_API_KEY",),
|
|
}
|
|
_HOST_ENV_NAMES = {
|
|
"api.openai.com": ("OPENAI_API_KEY",),
|
|
"openrouter.ai": ("OPENROUTER_API_KEY",),
|
|
"api.groq.com": ("GROQ_API_KEY",),
|
|
"api.together.xyz": ("TOGETHER_API_KEY", "TOGETHERAI_API_KEY"),
|
|
"api.deepseek.com": ("DEEPSEEK_API_KEY",),
|
|
"api.mistral.ai": ("MISTRAL_API_KEY",),
|
|
}
|
|
|
|
|
|
@dataclass
|
|
class Token:
|
|
value: str = field(repr=False)
|
|
source: str
|
|
kind: str = "key" # key | oauth
|
|
expired: bool = False
|
|
|
|
|
|
def _from_env(names: list[str]) -> list[Token]:
|
|
out: list[Token] = []
|
|
for name in names:
|
|
value = os.environ.get(name)
|
|
if value:
|
|
out.append(Token(value=value, source=f"env:{name}", kind="key"))
|
|
return out
|
|
|
|
|
|
def _from_opencode_export() -> list[Token]:
|
|
binary = shutil.which("opencode")
|
|
if not binary:
|
|
return []
|
|
try:
|
|
proc = subprocess.run(
|
|
[binary, "auth", "export"],
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=20,
|
|
check=False,
|
|
)
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
return []
|
|
if proc.returncode != 0 or not proc.stdout.strip():
|
|
return []
|
|
try:
|
|
data = json.loads(proc.stdout)
|
|
except json.JSONDecodeError:
|
|
return []
|
|
|
|
items = data if isinstance(data, list) else data.get("credentials", [])
|
|
if not isinstance(items, list):
|
|
return []
|
|
go_keys: list[Token] = []
|
|
oauth: list[Token] = []
|
|
console_keys: list[Token] = []
|
|
for item in items:
|
|
if not isinstance(item, dict) or not item.get("active"):
|
|
continue
|
|
integration = str(item.get("integrationID", ""))
|
|
label = str(item.get("label", integration))
|
|
value = item.get("value") or {}
|
|
kind = value.get("type")
|
|
if kind == "key" and value.get("key"):
|
|
token = Token(
|
|
value=value["key"],
|
|
source=f"opencode:{integration}/{label}",
|
|
kind="key",
|
|
)
|
|
if integration == "opencode-go":
|
|
go_keys.append(token)
|
|
elif integration == "opencode":
|
|
console_keys.append(token)
|
|
elif kind == "oauth" and value.get("access"):
|
|
expires = value.get("expires")
|
|
expired = bool(expires and float(expires) / 1000 < time.time())
|
|
token = Token(
|
|
value=value["access"],
|
|
source=f"opencode:{integration}/{label} (OAuth)",
|
|
kind="oauth",
|
|
expired=expired,
|
|
)
|
|
if integration == "opencode":
|
|
oauth.append(token)
|
|
return go_keys + oauth + console_keys
|
|
|
|
|
|
def _hostname(base_url: str) -> str:
|
|
try:
|
|
return (urlsplit(base_url).hostname or "").lower()
|
|
except ValueError:
|
|
return ""
|
|
|
|
|
|
def _is_opencode(profile: ProviderProfile) -> bool:
|
|
host = _hostname(profile.base_url)
|
|
# Provider IDs/kinds are user-editable. Only the actual OpenCode host may
|
|
# receive OpenCode's conventional credentials or exported OAuth tokens.
|
|
return host == "opencode.ai" or host.endswith(".opencode.ai")
|
|
|
|
|
|
def _is_local(profile: ProviderProfile) -> bool:
|
|
host = _hostname(profile.base_url)
|
|
return host in {"localhost", "127.0.0.1", "::1"} or host.endswith(".localhost")
|
|
|
|
|
|
def _deduplicate(candidates: list[Token]) -> list[Token]:
|
|
out: list[Token] = []
|
|
seen: set[str] = set()
|
|
for token in candidates:
|
|
if token.value in seen:
|
|
continue
|
|
seen.add(token.value)
|
|
out.append(token)
|
|
return out
|
|
|
|
|
|
def _conventional_env_names(profile: ProviderProfile) -> list[str]:
|
|
if profile.id == "opencode":
|
|
return []
|
|
names = list(_CONVENTIONAL_ENV_NAMES.get(profile.id, ()))
|
|
if not names:
|
|
names = list(_HOST_ENV_NAMES.get(_hostname(profile.base_url), ()))
|
|
if not names and profile.id != "default":
|
|
normalized = re.sub(r"[^A-Za-z0-9]+", "_", profile.id).strip("_").upper()
|
|
if normalized:
|
|
names = [f"{normalized}_API_KEY"]
|
|
return names
|
|
|
|
|
|
def resolve_profile_tokens(config: Config, profile: ProviderProfile) -> list[Token]:
|
|
"""Resolve credentials for one profile without borrowing another provider's key."""
|
|
del config # Kept in the public signature for symmetry with resolve_tokens().
|
|
is_opencode = _is_opencode(profile)
|
|
|
|
# A default local profile is normally unauthenticated. In particular, do
|
|
# not send a generic/OpenCode credential merely because a local server is
|
|
# running. Set token/token_env explicitly to opt into local authentication.
|
|
if _is_local(profile) and not profile.token and not profile.token_env:
|
|
return []
|
|
|
|
candidates: list[Token] = []
|
|
if profile.token:
|
|
candidates.append(Token(value=profile.token, source="config", kind="key"))
|
|
|
|
env_names: list[str] = ["AIROUTER_TOKEN"]
|
|
if profile.token_env:
|
|
if not is_opencode and profile.token_env in _OPENCODE_ENV_NAMES:
|
|
# Even an accidental token_env setting must not export OpenCode
|
|
# credentials to a third-party endpoint.
|
|
pass
|
|
else:
|
|
env_names.append(profile.token_env)
|
|
|
|
if is_opencode:
|
|
env_names.extend(_OPENCODE_ENV_NAMES)
|
|
else:
|
|
env_names.extend(_conventional_env_names(profile))
|
|
|
|
candidates.extend(_from_env(env_names))
|
|
if is_opencode and profile.auto_auth:
|
|
candidates.extend(_from_opencode_export())
|
|
return _deduplicate(candidates)
|
|
|
|
|
|
def resolve_tokens(config: Config) -> list[Token]:
|
|
"""Backward-compatible credential resolution for the legacy provider."""
|
|
profile = ProviderProfile(
|
|
id="opencode" if config.provider.base_url.rstrip("/") == (
|
|
"https://opencode.ai/inference/go/openai/v1"
|
|
) else "default",
|
|
name="Default",
|
|
kind="opencode" if "opencode.ai" in _hostname(config.provider.base_url) else "openai",
|
|
base_url=config.provider.base_url,
|
|
token=config.provider.token,
|
|
token_env=config.provider.token_env,
|
|
auto_auth=config.provider.auto_auth,
|
|
max_retries=config.provider.max_retries,
|
|
request_timeout=config.provider.request_timeout,
|
|
)
|
|
return resolve_profile_tokens(config, profile)
|
|
|
|
|
|
def token_hint(config: Config) -> str:
|
|
return (
|
|
"Не найден токен для OpenCode Go.\n"
|
|
"Варианты:\n"
|
|
" 1. opencode auth login — и выберите OpenCode Go / OpenCode Console\n"
|
|
" 2. export OPENCODE_API_KEY=oc_sk_...\n"
|
|
f" 3. укажите token_env в {config.project_config_path or '~/.config/airouter/config.toml'}"
|
|
)
|
|
|
|
|
|
def describe_auth(tokens: list[Token]) -> str:
|
|
if not tokens:
|
|
return "нет токена"
|
|
current = tokens[0]
|
|
suffix = " (просрочен)" if current.expired else ""
|
|
extra = f" +{len(tokens) - 1} fallback" if len(tokens) > 1 else ""
|
|
return f"{current.source}{suffix}{extra}"
|