Репозитории /
AiRouter /
airouter/auth.py
auth.py
| 1 | """Credential discovery. |
| 2 | |
| 3 | AiRouter never writes tokens to disk. By default it can reuse the credentials |
| 4 | already stored by OpenCode (`opencode auth export`), which makes OpenCode Go work |
| 5 | out of the box. Explicit environment variables take priority. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import json |
| 11 | import os |
| 12 | import shutil |
| 13 | import subprocess |
| 14 | import time |
| 15 | from dataclasses import dataclass, field |
| 16 | |
| 17 | from .config import Config |
| 18 | |
| 19 | |
| 20 | @dataclass |
| 21 | class Token: |
| 22 | value: str = field(repr=False) |
| 23 | source: str |
| 24 | kind: str = "key" # key | oauth |
| 25 | expired: bool = False |
| 26 | |
| 27 | |
| 28 | def _from_env(names: list[str]) -> list[Token]: |
| 29 | out: list[Token] = [] |
| 30 | for name in names: |
| 31 | value = os.environ.get(name) |
| 32 | if value: |
| 33 | out.append(Token(value=value, source=f"env:{name}", kind="key")) |
| 34 | return out |
| 35 | |
| 36 | |
| 37 | def _from_opencode_export() -> list[Token]: |
| 38 | binary = shutil.which("opencode") |
| 39 | if not binary: |
| 40 | return [] |
| 41 | try: |
| 42 | proc = subprocess.run( |
| 43 | [binary, "auth", "export"], |
| 44 | capture_output=True, |
| 45 | text=True, |
| 46 | timeout=20, |
| 47 | check=False, |
| 48 | ) |
| 49 | except (OSError, subprocess.TimeoutExpired): |
| 50 | return [] |
| 51 | if proc.returncode != 0 or not proc.stdout.strip(): |
| 52 | return [] |
| 53 | try: |
| 54 | data = json.loads(proc.stdout) |
| 55 | except json.JSONDecodeError: |
| 56 | return [] |
| 57 | |
| 58 | items = data if isinstance(data, list) else data.get("credentials", []) |
| 59 | go_keys: list[Token] = [] |
| 60 | oauth: list[Token] = [] |
| 61 | console_keys: list[Token] = [] |
| 62 | for item in items: |
| 63 | if not isinstance(item, dict) or not item.get("active"): |
| 64 | continue |
| 65 | integration = str(item.get("integrationID", "")) |
| 66 | label = str(item.get("label", integration)) |
| 67 | value = item.get("value") or {} |
| 68 | kind = value.get("type") |
| 69 | if kind == "key" and value.get("key"): |
| 70 | token = Token( |
| 71 | value=value["key"], |
| 72 | source=f"opencode:{integration}/{label}", |
| 73 | kind="key", |
| 74 | ) |
| 75 | if integration == "opencode-go": |
| 76 | go_keys.append(token) |
| 77 | elif integration == "opencode": |
| 78 | console_keys.append(token) |
| 79 | elif kind == "oauth" and value.get("access"): |
| 80 | expires = value.get("expires") |
| 81 | expired = bool(expires and float(expires) / 1000 < time.time()) |
| 82 | token = Token( |
| 83 | value=value["access"], |
| 84 | source=f"opencode:{integration}/{label} (OAuth)", |
| 85 | kind="oauth", |
| 86 | expired=expired, |
| 87 | ) |
| 88 | if integration == "opencode": |
| 89 | oauth.append(token) |
| 90 | return go_keys + oauth + console_keys |
| 91 | |
| 92 | |
| 93 | def resolve_tokens(config: Config) -> list[Token]: |
| 94 | candidates: list[Token] = [] |
| 95 | if config.provider.token: |
| 96 | candidates.append(Token(value=config.provider.token, source="config", kind="key")) |
| 97 | env_names = ["AIROUTER_TOKEN"] |
| 98 | if config.provider.token_env: |
| 99 | env_names.append(config.provider.token_env) |
| 100 | env_names += ["OPENCODE_API_KEY", "OPENCODE_GO_API_KEY"] |
| 101 | # Preserve order while removing duplicates. |
| 102 | seen_names: set[str] = set() |
| 103 | for name in env_names: |
| 104 | if name in seen_names: |
| 105 | continue |
| 106 | seen_names.add(name) |
| 107 | value = os.environ.get(name) |
| 108 | if value: |
| 109 | candidates.append(Token(value=value, source=f"env:{name}", kind="key")) |
| 110 | |
| 111 | if config.provider.auto_auth and "opencode.ai" in config.provider.base_url: |
| 112 | candidates.extend(_from_opencode_export()) |
| 113 | |
| 114 | out: list[Token] = [] |
| 115 | seen: set[str] = set() |
| 116 | for token in candidates: |
| 117 | if token.value in seen: |
| 118 | continue |
| 119 | seen.add(token.value) |
| 120 | out.append(token) |
| 121 | return out |
| 122 | |
| 123 | |
| 124 | def token_hint(config: Config) -> str: |
| 125 | return ( |
| 126 | "Не найден токен для OpenCode Go.\n" |
| 127 | "Варианты:\n" |
| 128 | " 1. opencode auth login — и выберите OpenCode Go / OpenCode Console\n" |
| 129 | " 2. export OPENCODE_API_KEY=oc_sk_...\n" |
| 130 | f" 3. укажите token_env в {config.project_config_path or '~/.config/airouter/config.toml'}" |
| 131 | ) |
| 132 | |
| 133 | |
| 134 | def describe_auth(tokens: list[Token]) -> str: |
| 135 | if not tokens: |
| 136 | return "нет токена" |
| 137 | current = tokens[0] |
| 138 | suffix = " (просрочен)" if current.expired else "" |
| 139 | extra = f" +{len(tokens) - 1} fallback" if len(tokens) > 1 else "" |
| 140 | return f"{current.source}{suffix}{extra}" |