coding-proxy 0.5.2a8__py3-none-any.whl → 0.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- coding/proxy/auth/runtime.py +8 -0
- coding/proxy/auth/store.py +4 -4
- coding/proxy/cli/__init__.py +148 -44
- coding/proxy/cli/auth_commands.py +47 -8
- coding/proxy/cli/config_commands.py +232 -0
- coding/proxy/config/auth_schema.py +6 -2
- coding/proxy/config/config.default.yaml +40 -19
- coding/proxy/config/defaults.py +34 -0
- coding/proxy/config/home.py +188 -0
- coding/proxy/config/importer.py +812 -0
- coding/proxy/config/loader.py +16 -47
- coding/proxy/config/normalize.py +300 -0
- coding/proxy/config/resolver.py +412 -0
- coding/proxy/config/routing.py +13 -4
- coding/proxy/config/schema.py +8 -4
- coding/proxy/config/secrets.py +286 -0
- coding/proxy/config/server.py +8 -3
- coding/proxy/config/service.py +1182 -0
- coding/proxy/config/store.py +384 -0
- coding/proxy/config/ui_registry.py +669 -0
- coding/proxy/routing/executor.py +19 -14
- coding/proxy/routing/quota_guard.py +31 -7
- coding/proxy/server/app.py +27 -6
- coding/proxy/server/config_routes.py +360 -0
- coding/proxy/server/dashboard.py +270 -58
- coding/proxy/server/generations.py +718 -0
- coding/proxy/server/routes.py +21 -15
- coding/proxy/server/security.py +350 -0
- coding/proxy/server/static/config/config.css +181 -0
- coding/proxy/server/static/config/config.js +1267 -0
- coding/proxy/vendors/token_manager.py +2 -1
- {coding_proxy-0.5.2a8.dist-info → coding_proxy-0.6.0.dist-info}/METADATA +15 -8
- {coding_proxy-0.5.2a8.dist-info → coding_proxy-0.6.0.dist-info}/RECORD +36 -21
- {coding_proxy-0.5.2a8.dist-info → coding_proxy-0.6.0.dist-info}/WHEEL +1 -1
- {coding_proxy-0.5.2a8.dist-info → coding_proxy-0.6.0.dist-info}/entry_points.txt +0 -0
- {coding_proxy-0.5.2a8.dist-info → coding_proxy-0.6.0.dist-info}/licenses/LICENSE +0 -0
coding/proxy/auth/runtime.py
CHANGED
|
@@ -33,6 +33,14 @@ class RuntimeReauthCoordinator:
|
|
|
33
33
|
- 重认证期间 TokenManager 持续抛 TokenAcquireError
|
|
34
34
|
- Router 触发 failover → 熔断器 OPEN → 请求路由到下一层级
|
|
35
35
|
- 重认证完成后 TokenManager 获得新凭证 → 熔断器恢复 → 后端可用
|
|
36
|
+
|
|
37
|
+
.. warning::
|
|
38
|
+
``server/generations.py`` 的 generation 交接逻辑直接读写本类私有属性
|
|
39
|
+
(``_providers`` / ``_states`` / ``_locks`` / ``_last_error`` /
|
|
40
|
+
``_last_completed`` / ``_token_updaters`` / ``_token_store``),
|
|
41
|
+
行为由 ``tests/test_generations_app.py`` 锁定。重命名属性、加
|
|
42
|
+
``__slots__`` 或改动数据结构时必须同步 ``_relay_reauth`` /
|
|
43
|
+
``_finish_relay`` / ``_forward_tokens``。
|
|
36
44
|
"""
|
|
37
45
|
|
|
38
46
|
def __init__(
|
coding/proxy/auth/store.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Token 持久化存储 —
|
|
1
|
+
"""Token 持久化存储 — $CODING_PROXY_HOME/tokens.json.
|
|
2
2
|
|
|
3
3
|
``ProviderTokens`` 数据模型已迁移至 :mod:`coding.proxy.model.auth`。
|
|
4
4
|
本文件保留 ``TokenStoreManager`` 持久化管理器,类型通过 re-export 提供。
|
|
@@ -14,19 +14,19 @@ import logging
|
|
|
14
14
|
from pathlib import Path
|
|
15
15
|
from typing import Any
|
|
16
16
|
|
|
17
|
+
from ..config.home import default_token_store_path
|
|
18
|
+
|
|
17
19
|
# noqa: F401
|
|
18
20
|
from ..model.auth import ProviderTokens
|
|
19
21
|
|
|
20
22
|
logger = logging.getLogger(__name__)
|
|
21
23
|
|
|
22
|
-
_DEFAULT_STORE_PATH = Path("~/.coding-proxy/tokens.json")
|
|
23
|
-
|
|
24
24
|
|
|
25
25
|
class TokenStoreManager:
|
|
26
26
|
"""管理所有 Provider 的 Token 持久化."""
|
|
27
27
|
|
|
28
28
|
def __init__(self, store_path: Path | None = None) -> None:
|
|
29
|
-
self._path = (store_path or
|
|
29
|
+
self._path = (store_path or default_token_store_path()).expanduser()
|
|
30
30
|
self._data: dict[str, dict[str, Any]] = {}
|
|
31
31
|
|
|
32
32
|
def load(self) -> None:
|
coding/proxy/cli/__init__.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""CLI 入口 — Typer 命令行工具.
|
|
2
2
|
|
|
3
|
-
Auth 子命令已正交提取至 :mod:`.auth_commands`.
|
|
3
|
+
Auth / Config 子命令已正交提取至 :mod:`.auth_commands` / :mod:`.config_commands`.
|
|
4
4
|
"""
|
|
5
5
|
|
|
6
6
|
from __future__ import annotations
|
|
@@ -17,41 +17,35 @@ if TYPE_CHECKING:
|
|
|
17
17
|
|
|
18
18
|
from rich.console import Console
|
|
19
19
|
|
|
20
|
-
from ..config.loader import load_config
|
|
21
20
|
from ..logging.db import TimePeriod, TokenLogger
|
|
22
21
|
from ..logging.stats import show_usage
|
|
22
|
+
from .auth_commands import _build_token_store, _offline_config
|
|
23
23
|
from .auth_commands import app as auth_app
|
|
24
24
|
from .auth_commands import auto_login_if_needed as _auto_login_if_needed
|
|
25
|
+
from .config_commands import app as config_app
|
|
25
26
|
|
|
26
|
-
app = typer.Typer(
|
|
27
|
+
app = typer.Typer(
|
|
28
|
+
name="coding-proxy",
|
|
29
|
+
help="Claude Code 多供应商智能代理服务",
|
|
30
|
+
pretty_exceptions_show_locals=False,
|
|
31
|
+
)
|
|
27
32
|
console = Console()
|
|
33
|
+
err_console = Console(stderr=True)
|
|
28
34
|
logger = logging.getLogger(__name__)
|
|
29
35
|
|
|
30
|
-
# 注册 Auth 子应用
|
|
36
|
+
# 注册 Auth / Config 子应用
|
|
31
37
|
app.add_typer(auth_app, name="auth")
|
|
38
|
+
app.add_typer(config_app, name="config")
|
|
32
39
|
|
|
33
40
|
# 注册 Session 子应用
|
|
34
|
-
session_app = typer.Typer(
|
|
41
|
+
session_app = typer.Typer(
|
|
42
|
+
name="session",
|
|
43
|
+
help="管理 Session-Vendor 运行时绑定",
|
|
44
|
+
pretty_exceptions_show_locals=False,
|
|
45
|
+
)
|
|
35
46
|
app.add_typer(session_app, name="session")
|
|
36
47
|
|
|
37
48
|
|
|
38
|
-
def _build_token_store(cfg_path: Path | None = None):
|
|
39
|
-
"""按配置解析 Token Store 路径并完成加载."""
|
|
40
|
-
from ..auth.store import TokenStoreManager
|
|
41
|
-
|
|
42
|
-
cfg = load_config(cfg_path)
|
|
43
|
-
store = TokenStoreManager(
|
|
44
|
-
store_path=Path(cfg.auth.token_store_path)
|
|
45
|
-
if cfg.auth.token_store_path
|
|
46
|
-
else None,
|
|
47
|
-
)
|
|
48
|
-
store.load()
|
|
49
|
-
logger.debug(
|
|
50
|
-
"OAuth token store loaded from config path: %s", cfg.auth.token_store_path
|
|
51
|
-
)
|
|
52
|
-
return cfg, store
|
|
53
|
-
|
|
54
|
-
|
|
55
49
|
def _resolve_period(
|
|
56
50
|
*,
|
|
57
51
|
days: int = 7,
|
|
@@ -84,45 +78,155 @@ def start(
|
|
|
84
78
|
port: int | None = typer.Option(None, "--port", "-p", help="监听端口"),
|
|
85
79
|
host: str | None = typer.Option(None, "--host", "-h", help="监听地址"),
|
|
86
80
|
) -> None:
|
|
87
|
-
"""启动代理服务.
|
|
81
|
+
"""启动代理服务.
|
|
82
|
+
|
|
83
|
+
uvicorn 运行 :class:`GenerationManager`:Dashboard 保存配置后进程内热切换,无需重启;
|
|
84
|
+
存储的配置无效时以 degraded 模式启动(仅 Dashboard 与管理 API 可用)。
|
|
85
|
+
"""
|
|
88
86
|
import uvicorn
|
|
89
87
|
|
|
88
|
+
from ..config.importer import (
|
|
89
|
+
ExplicitConfigMissingError,
|
|
90
|
+
LegacyConfigError,
|
|
91
|
+
StaleYamlError,
|
|
92
|
+
boot,
|
|
93
|
+
)
|
|
94
|
+
from ..config.resolver import MODE_LEGACY
|
|
95
|
+
from ..config.secrets import MasterKeyError
|
|
96
|
+
from ..config.store import ConfigStoreError
|
|
90
97
|
from ..server.app import create_app
|
|
98
|
+
from ..server.generations import GenerationManager
|
|
91
99
|
from .banner import print_banner
|
|
92
100
|
|
|
93
101
|
cfg_path = _resolve_config_path(config)
|
|
94
|
-
|
|
102
|
+
try:
|
|
103
|
+
booted = boot(cfg_path)
|
|
104
|
+
except (
|
|
105
|
+
StaleYamlError,
|
|
106
|
+
ExplicitConfigMissingError,
|
|
107
|
+
LegacyConfigError,
|
|
108
|
+
MasterKeyError,
|
|
109
|
+
ConfigStoreError,
|
|
110
|
+
) as exc:
|
|
111
|
+
err_console.print(f"[red]{exc}[/red]")
|
|
112
|
+
raise typer.Exit(2) from None
|
|
113
|
+
resolved = booted.resolved
|
|
114
|
+
for notice in booted.notices:
|
|
115
|
+
err_console.print(f"[yellow]{notice}[/yellow]")
|
|
116
|
+
if resolved.mode == MODE_LEGACY:
|
|
117
|
+
err_console.print("[yellow]配置导入失败,本次以只读方式运行旧 YAML[/yellow]")
|
|
118
|
+
cfg = resolved.config
|
|
119
|
+
if cfg is None:
|
|
120
|
+
for error in resolved.errors:
|
|
121
|
+
loc = ".".join(map(str, error["loc"])) or "<root>"
|
|
122
|
+
err_console.print(f"[red]{loc}: {error['msg']}[/red]")
|
|
123
|
+
err_console.print(
|
|
124
|
+
"[red]存储的配置无效,以 degraded 模式启动(代理接口返回 503);"
|
|
125
|
+
"请在 Dashboard → Config 或用 `coding-proxy config` 修复[/red]"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
from ..logging import build_log_config
|
|
95
129
|
|
|
130
|
+
manager = GenerationManager(boot=booted, build=create_app)
|
|
131
|
+
server_cfg, logging_cfg = manager.server, manager.logging
|
|
96
132
|
if port:
|
|
97
|
-
|
|
133
|
+
server_cfg.port = port
|
|
134
|
+
resolved.sources["server.port"] = "cli"
|
|
98
135
|
if host:
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
# 自动登录检查
|
|
102
|
-
asyncio.run(_auto_login_if_needed(cfg_path))
|
|
136
|
+
server_cfg.host = host
|
|
137
|
+
resolved.sources["server.host"] = "cli"
|
|
103
138
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
139
|
+
# 自动登录检查(配置无效时跳过)
|
|
140
|
+
if cfg is not None:
|
|
141
|
+
asyncio.run(_auto_login_if_needed(cfg_path, cfg=cfg))
|
|
107
142
|
|
|
108
|
-
#
|
|
109
|
-
print_banner(console, host=
|
|
143
|
+
# 打印启动品牌横幅与带 admin token 的 Dashboard 链接(仅控制台,不进日志)
|
|
144
|
+
print_banner(console, host=server_cfg.host, port=server_cfg.port)
|
|
145
|
+
_print_dashboard_url(server_cfg.host, server_cfg.port, server_cfg.allowed_hosts)
|
|
110
146
|
|
|
111
|
-
#
|
|
112
|
-
_file_path: str | None =
|
|
147
|
+
# 解析文件日志路径:未设置时用默认值;显式空串 = 禁用文件日志(透传 build_log_config)
|
|
148
|
+
_file_path: str | None = (
|
|
149
|
+
logging_cfg.file if logging_cfg.file is not None else ".logs/coding-proxy.log"
|
|
150
|
+
)
|
|
113
151
|
uvicorn.run(
|
|
114
|
-
|
|
115
|
-
host=
|
|
116
|
-
port=
|
|
152
|
+
manager,
|
|
153
|
+
host=server_cfg.host,
|
|
154
|
+
port=server_cfg.port,
|
|
117
155
|
log_config=build_log_config(
|
|
118
|
-
level=
|
|
156
|
+
level=logging_cfg.level,
|
|
119
157
|
file_path=_file_path,
|
|
120
|
-
max_bytes=
|
|
121
|
-
backup_count=
|
|
158
|
+
max_bytes=logging_cfg.max_bytes,
|
|
159
|
+
backup_count=logging_cfg.backup_count,
|
|
122
160
|
),
|
|
161
|
+
proxy_headers=False,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _dashboard_host(host: str) -> str:
|
|
166
|
+
"""监听地址 → 浏览器可访问的主机(通配地址改用 loopback,IPv6 加方括号)."""
|
|
167
|
+
if host in ("", "0.0.0.0"):
|
|
168
|
+
return "127.0.0.1"
|
|
169
|
+
if host == "::":
|
|
170
|
+
return "[::1]"
|
|
171
|
+
return f"[{host}]" if ":" in host else host
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _dashboard_host_rejected(shown: str, allowed_hosts: list[str]) -> bool:
|
|
175
|
+
"""打印的主机会被管理面 Host 校验(403)拒绝.
|
|
176
|
+
|
|
177
|
+
IP 字面量即监听地址,中间件按本机地址放行;主机名须在 loopback ∪ allowed_hosts 中。
|
|
178
|
+
"""
|
|
179
|
+
import ipaddress
|
|
180
|
+
|
|
181
|
+
from ..server import security
|
|
182
|
+
|
|
183
|
+
parsed = security.split_host(shown)
|
|
184
|
+
if parsed is None:
|
|
185
|
+
return True
|
|
186
|
+
name = parsed[0]
|
|
187
|
+
try:
|
|
188
|
+
ipaddress.ip_address(name)
|
|
189
|
+
return False
|
|
190
|
+
except ValueError:
|
|
191
|
+
pass
|
|
192
|
+
return name not in security.LOOPBACK_HOSTS | security.normalize_allowed_hosts(
|
|
193
|
+
allowed_hosts
|
|
123
194
|
)
|
|
124
195
|
|
|
125
196
|
|
|
197
|
+
def _print_dashboard_url(
|
|
198
|
+
host: str, port: int, allowed_hosts: list[str] | None = None
|
|
199
|
+
) -> None:
|
|
200
|
+
"""``#admin=`` fragment 不随请求发送,token 不会出现在服务端访问日志."""
|
|
201
|
+
import json
|
|
202
|
+
|
|
203
|
+
from ..config.home import load_or_create_admin_token
|
|
204
|
+
from ..config.store import ConfigStoreError
|
|
205
|
+
|
|
206
|
+
shown = _dashboard_host(host)
|
|
207
|
+
url = f"http://{shown}:{port}/dashboard?tab=config"
|
|
208
|
+
try:
|
|
209
|
+
url += f"#admin={load_or_create_admin_token()}"
|
|
210
|
+
except (OSError, ConfigStoreError) as exc:
|
|
211
|
+
err_console.print(
|
|
212
|
+
f"[yellow]admin token 不可用({type(exc).__name__}),"
|
|
213
|
+
"Config 页需执行 `coding-proxy config token` 后解锁[/yellow]"
|
|
214
|
+
)
|
|
215
|
+
console.print(f"Dashboard: {url}", markup=False, highlight=False, soft_wrap=True)
|
|
216
|
+
allowed = list(allowed_hosts or [])
|
|
217
|
+
if _dashboard_host_rejected(shown, allowed):
|
|
218
|
+
value = json.dumps([*allowed, shown.strip("[]")], ensure_ascii=False)
|
|
219
|
+
err_console.print(
|
|
220
|
+
f"主机 {shown} 不在 server.allowed_hosts 中,Dashboard 与管理 API 会返回 403;"
|
|
221
|
+
f"请执行 coding-proxy config set server.allowed_hosts '{value}' 后重启,"
|
|
222
|
+
f"或经 SSH 隧道访问 http://127.0.0.1:{port}/dashboard",
|
|
223
|
+
style="yellow",
|
|
224
|
+
markup=False,
|
|
225
|
+
highlight=False,
|
|
226
|
+
soft_wrap=True,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
126
230
|
@app.command()
|
|
127
231
|
def status(
|
|
128
232
|
port: int = typer.Option(3392, "--port", "-p", help="代理服务端口"),
|
|
@@ -177,8 +281,8 @@ def usage(
|
|
|
177
281
|
-t 全部历史(按供应商+模型聚合)
|
|
178
282
|
"""
|
|
179
283
|
period, count = _resolve_period(days=days, week=week, month=month, total=total)
|
|
180
|
-
cfg =
|
|
181
|
-
token_logger = TokenLogger(cfg.db_path)
|
|
284
|
+
cfg = _offline_config(decrypt=False)
|
|
285
|
+
token_logger = TokenLogger(Path(db_path).expanduser() if db_path else cfg.db_path)
|
|
182
286
|
# 解析逗号分隔的多 vendor(如 "anthropic,zhipu" → ["anthropic", "zhipu"])
|
|
183
287
|
vendor_filter: str | list[str] | None = None
|
|
184
288
|
if vendor:
|
|
@@ -6,22 +6,57 @@ import asyncio
|
|
|
6
6
|
import inspect
|
|
7
7
|
import logging
|
|
8
8
|
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
9
10
|
|
|
10
11
|
import typer
|
|
11
12
|
from rich.console import Console
|
|
12
13
|
|
|
14
|
+
from ..config.importer import StoredConfigInvalidError, load_offline_config
|
|
13
15
|
from ..config.loader import load_config
|
|
16
|
+
from ..config.secrets import MasterKeyError
|
|
17
|
+
from ..config.store import ConfigStoreError
|
|
14
18
|
|
|
15
|
-
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from ..config.schema import ProxyConfig
|
|
21
|
+
|
|
22
|
+
app = typer.Typer(
|
|
23
|
+
name="auth", help="管理 OAuth 登录凭证", pretty_exceptions_show_locals=False
|
|
24
|
+
)
|
|
16
25
|
console = Console()
|
|
26
|
+
err_console = Console(stderr=True)
|
|
17
27
|
logger = logging.getLogger(__name__)
|
|
18
28
|
|
|
19
29
|
|
|
20
|
-
def
|
|
21
|
-
"""
|
|
30
|
+
def _offline_config(*, decrypt: bool) -> ProxyConfig:
|
|
31
|
+
"""离线读取配置:已迁移读 config.db,否则只读读取旧 YAML 并提示迁移."""
|
|
32
|
+
try:
|
|
33
|
+
cfg, hint = load_offline_config(decrypt=decrypt)
|
|
34
|
+
except (ConfigStoreError, MasterKeyError, StoredConfigInvalidError) as exc:
|
|
35
|
+
err_console.print(f"[red]{exc}[/red]")
|
|
36
|
+
raise typer.Exit(1) from None
|
|
37
|
+
if hint:
|
|
38
|
+
err_console.print(f"[dim]{hint}[/dim]")
|
|
39
|
+
return cfg
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _build_token_store(
|
|
43
|
+
cfg_path: Path | None = None,
|
|
44
|
+
*,
|
|
45
|
+
cfg: ProxyConfig | None = None,
|
|
46
|
+
decrypt: bool = True,
|
|
47
|
+
):
|
|
48
|
+
"""按配置解析 Token Store 路径并完成加载.
|
|
49
|
+
|
|
50
|
+
``cfg`` 优先;其次显式 YAML 路径(legacy 只读);否则读取运行时配置。
|
|
51
|
+
"""
|
|
22
52
|
from ..auth.store import TokenStoreManager
|
|
23
53
|
|
|
24
|
-
cfg
|
|
54
|
+
if cfg is None:
|
|
55
|
+
cfg = (
|
|
56
|
+
load_config(cfg_path)
|
|
57
|
+
if cfg_path is not None
|
|
58
|
+
else _offline_config(decrypt=decrypt)
|
|
59
|
+
)
|
|
25
60
|
store = TokenStoreManager(
|
|
26
61
|
store_path=Path(cfg.auth.token_store_path)
|
|
27
62
|
if cfg.auth.token_store_path
|
|
@@ -96,7 +131,7 @@ async def _run_auth_login(provider: str | None) -> None:
|
|
|
96
131
|
@app.command("status")
|
|
97
132
|
def auth_status() -> None:
|
|
98
133
|
"""查看已登录的 OAuth 凭证状态."""
|
|
99
|
-
_, store = _build_token_store()
|
|
134
|
+
_, store = _build_token_store(decrypt=False)
|
|
100
135
|
|
|
101
136
|
providers = store.list_providers()
|
|
102
137
|
if not providers:
|
|
@@ -140,7 +175,7 @@ def auth_logout(
|
|
|
140
175
|
),
|
|
141
176
|
) -> None:
|
|
142
177
|
"""清除已存储的 OAuth 凭证."""
|
|
143
|
-
_, store = _build_token_store()
|
|
178
|
+
_, store = _build_token_store(decrypt=False)
|
|
144
179
|
|
|
145
180
|
if provider:
|
|
146
181
|
store.remove(provider)
|
|
@@ -152,7 +187,9 @@ def auth_logout(
|
|
|
152
187
|
|
|
153
188
|
|
|
154
189
|
# ── 自动登录辅助 ─────────────────────────────────────────────
|
|
155
|
-
async def auto_login_if_needed(
|
|
190
|
+
async def auto_login_if_needed(
|
|
191
|
+
cfg_path: Path | None = None, *, cfg: ProxyConfig | None = None
|
|
192
|
+
) -> None:
|
|
156
193
|
"""检查各 Provider 是否缺少凭证,自动触发浏览器登录.
|
|
157
194
|
|
|
158
195
|
仅对已启用、且未在 config 中显式提供凭证的 Tier 做检查。
|
|
@@ -163,11 +200,13 @@ async def auto_login_if_needed(cfg_path: Path | None) -> None:
|
|
|
163
200
|
1. needs_login() — 快速本地判断(无凭证或已过期且无 refresh_token)
|
|
164
201
|
2. refresh() — Google access_token 过期且存在 refresh_token 时静默刷新
|
|
165
202
|
3. validate() — 网络验证已有凭证是否仍有效(仅在有凭证且未刷新时触发)
|
|
203
|
+
|
|
204
|
+
仍读取 legacy ``cfg.copilot`` / ``cfg.antigravity``(行为不变)。
|
|
166
205
|
"""
|
|
167
206
|
from ..auth.providers.github import GitHubDeviceFlowProvider
|
|
168
207
|
from ..auth.providers.google import GoogleOAuthProvider
|
|
169
208
|
|
|
170
|
-
cfg, store = _build_token_store(cfg_path)
|
|
209
|
+
cfg, store = _build_token_store(cfg_path, cfg=cfg)
|
|
171
210
|
|
|
172
211
|
async def _resolve_needs_login(provider, tokens) -> bool:
|
|
173
212
|
result = provider.needs_login(tokens)
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""CLI Config 子命令 — config.db 的路径、导入导出、字段与密钥修改.
|
|
2
|
+
|
|
3
|
+
所有输出只含字段路径与脱敏信息;密钥值从不回显。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import typer
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
|
|
16
|
+
from ..config.home import (
|
|
17
|
+
admin_token_path,
|
|
18
|
+
config_db_path,
|
|
19
|
+
load_or_create_admin_token,
|
|
20
|
+
master_key_path,
|
|
21
|
+
proxy_home,
|
|
22
|
+
write_private_atomic,
|
|
23
|
+
)
|
|
24
|
+
from ..config.importer import (
|
|
25
|
+
ImportPlanError,
|
|
26
|
+
LegacyConfigError,
|
|
27
|
+
StoreNotReadyError,
|
|
28
|
+
ensure_store_ready,
|
|
29
|
+
require_migrated_or_empty,
|
|
30
|
+
)
|
|
31
|
+
from ..config.secrets import MasterKeyError
|
|
32
|
+
from ..config.service import (
|
|
33
|
+
ConfigService,
|
|
34
|
+
ConfigStoreMissing,
|
|
35
|
+
ConfigValidationError,
|
|
36
|
+
)
|
|
37
|
+
from ..config.store import ConfigStoreError, RevisionConflict
|
|
38
|
+
|
|
39
|
+
app = typer.Typer(
|
|
40
|
+
name="config",
|
|
41
|
+
help="管理配置存储($CODING_PROXY_HOME/config.db)",
|
|
42
|
+
pretty_exceptions_show_locals=False,
|
|
43
|
+
)
|
|
44
|
+
console = Console()
|
|
45
|
+
err_console = Console(stderr=True)
|
|
46
|
+
|
|
47
|
+
_EXPECTED_ERRORS = (
|
|
48
|
+
ConfigStoreError,
|
|
49
|
+
ConfigValidationError,
|
|
50
|
+
ConfigStoreMissing,
|
|
51
|
+
ImportPlanError,
|
|
52
|
+
LegacyConfigError,
|
|
53
|
+
MasterKeyError,
|
|
54
|
+
RevisionConflict,
|
|
55
|
+
StoreNotReadyError,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _fail(exc: Exception) -> typer.Exit:
|
|
60
|
+
if isinstance(exc, ConfigValidationError):
|
|
61
|
+
for error in exc.errors:
|
|
62
|
+
loc = ".".join(map(str, error["loc"])) or "<root>"
|
|
63
|
+
err_console.print(f"[red]{loc}: {error['msg']}[/red]")
|
|
64
|
+
else:
|
|
65
|
+
err_console.print(f"[red]{exc}[/red]")
|
|
66
|
+
return typer.Exit(1)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _print_pinned(paths: list[str]) -> None:
|
|
70
|
+
for path in paths:
|
|
71
|
+
console.print(
|
|
72
|
+
f"[yellow]密钥 {path} 保持为空(不回落到包内默认环境变量);如需使用,"
|
|
73
|
+
f"请执行 `coding-proxy config set-secret {path} --default-env`[/yellow]"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _parse_value(raw: str) -> Any:
|
|
78
|
+
"""按 JSON 解析;非法 JSON 时按普通字符串处理."""
|
|
79
|
+
try:
|
|
80
|
+
return json.loads(raw)
|
|
81
|
+
except ValueError:
|
|
82
|
+
return raw
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@app.command("path")
|
|
86
|
+
def config_path() -> None:
|
|
87
|
+
"""显示配置相关文件路径."""
|
|
88
|
+
console.print(f"home: {proxy_home()}")
|
|
89
|
+
console.print(f"config.db: {config_db_path()}")
|
|
90
|
+
console.print(f"master.key: {master_key_path()}")
|
|
91
|
+
console.print(f"admin_token: {admin_token_path()}")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@app.command("export")
|
|
95
|
+
def config_export(
|
|
96
|
+
out: Path | None = typer.Option(None, "--out", "-o", help="写入文件(0600)"),
|
|
97
|
+
) -> None:
|
|
98
|
+
"""导出当前有效配置为 YAML(密钥已脱敏)."""
|
|
99
|
+
try:
|
|
100
|
+
require_migrated_or_empty()
|
|
101
|
+
text = ConfigService().export_yaml()
|
|
102
|
+
except _EXPECTED_ERRORS as exc:
|
|
103
|
+
raise _fail(exc) from None
|
|
104
|
+
if out is None:
|
|
105
|
+
sys.stdout.write(text)
|
|
106
|
+
return
|
|
107
|
+
write_private_atomic(out.expanduser(), text.encode("utf-8"))
|
|
108
|
+
console.print(f"[green]已导出到 {out}[/green]")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@app.command("import")
|
|
112
|
+
def config_import(
|
|
113
|
+
file: Path = typer.Argument(..., help="YAML 配置文件"),
|
|
114
|
+
dry_run: bool = typer.Option(False, "--dry-run", help="只校验并显示计划,不写入"),
|
|
115
|
+
) -> None:
|
|
116
|
+
"""从 YAML 导入(整体替换当前覆盖);``<redacted>`` 表示保留本地已存密钥."""
|
|
117
|
+
if not file.is_file():
|
|
118
|
+
err_console.print(f"[red]文件不存在: {file}[/red]")
|
|
119
|
+
raise typer.Exit(1)
|
|
120
|
+
try:
|
|
121
|
+
summary = ConfigService().import_yaml(file, dry_run=dry_run)
|
|
122
|
+
except _EXPECTED_ERRORS as exc:
|
|
123
|
+
raise _fail(exc) from None
|
|
124
|
+
title = "导入计划(dry-run)" if dry_run else "已导入"
|
|
125
|
+
console.print(f"[bold]{title}[/bold]: {summary['source']}")
|
|
126
|
+
console.print(f" 覆盖 sections: {', '.join(summary['sections']) or '(无)'}")
|
|
127
|
+
if summary["removed_sections"]:
|
|
128
|
+
console.print(f" 恢复默认: {', '.join(summary['removed_sections'])}")
|
|
129
|
+
for path, kind in summary["secrets"].items():
|
|
130
|
+
console.print(f" 密钥 {path}: {kind}")
|
|
131
|
+
for warning in summary["warnings"]:
|
|
132
|
+
console.print(f" [yellow]{warning}[/yellow]")
|
|
133
|
+
if summary["changes"]:
|
|
134
|
+
verb = "将改变" if dry_run else "已改变"
|
|
135
|
+
console.print(f" [yellow]相对当前配置{verb}的字段:[/yellow]")
|
|
136
|
+
for path in summary["changes"]:
|
|
137
|
+
console.print(f" {path}")
|
|
138
|
+
elif not summary["diffs"]:
|
|
139
|
+
console.print(" 生效配置与当前一致")
|
|
140
|
+
if summary["diffs"]:
|
|
141
|
+
console.print("[red]与 YAML 语义不一致的字段:[/red]")
|
|
142
|
+
for path in summary["diffs"]:
|
|
143
|
+
console.print(f" [red]{path}[/red]")
|
|
144
|
+
if dry_run:
|
|
145
|
+
raise typer.Exit(1)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@app.command("set")
|
|
149
|
+
def config_set(
|
|
150
|
+
path: str = typer.Argument(..., help="字段路径,如 vendors.zhipu.timeout_ms"),
|
|
151
|
+
value: str = typer.Argument(..., help="JSON 值(非法 JSON 按字符串处理)"),
|
|
152
|
+
) -> None:
|
|
153
|
+
"""修改单个字段(含 bootstrap 字段)."""
|
|
154
|
+
try:
|
|
155
|
+
ensure_store_ready()
|
|
156
|
+
result, bootstrap = ConfigService().set_path(path, _parse_value(value))
|
|
157
|
+
except _EXPECTED_ERRORS as exc:
|
|
158
|
+
raise _fail(exc) from None
|
|
159
|
+
section = path.split(".")[0]
|
|
160
|
+
console.print(
|
|
161
|
+
f"[green]已保存 {path}[/green]({section} revision "
|
|
162
|
+
f"{result.revisions.get(section, 0)})"
|
|
163
|
+
)
|
|
164
|
+
for secret_path in result.cleared_secrets:
|
|
165
|
+
console.print(f"[yellow]目标地址已变更,已清空密钥 {secret_path}[/yellow]")
|
|
166
|
+
_print_pinned(result.pinned_secrets)
|
|
167
|
+
if bootstrap:
|
|
168
|
+
console.print("[yellow]bootstrap 字段需重启生效[/yellow]")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@app.command("reset")
|
|
172
|
+
def config_reset(
|
|
173
|
+
section: str = typer.Argument(..., help="要恢复默认的 section"),
|
|
174
|
+
) -> None:
|
|
175
|
+
"""删除 section 覆盖,恢复包内默认值."""
|
|
176
|
+
try:
|
|
177
|
+
ensure_store_ready()
|
|
178
|
+
result = ConfigService().reset_section(section)
|
|
179
|
+
except _EXPECTED_ERRORS as exc:
|
|
180
|
+
raise _fail(exc) from None
|
|
181
|
+
console.print(f"[green]已恢复默认: {section}[/green]")
|
|
182
|
+
if result.cleared_secrets:
|
|
183
|
+
console.print(
|
|
184
|
+
f"[yellow]目标地址已变更,已清空密钥: {', '.join(result.cleared_secrets)}[/yellow]"
|
|
185
|
+
)
|
|
186
|
+
_print_pinned(result.pinned_secrets)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@app.command("set-secret")
|
|
190
|
+
def config_set_secret(
|
|
191
|
+
path: str = typer.Argument(..., help="密钥路径,如 vendors.zhipu.api_key"),
|
|
192
|
+
env: str | None = typer.Option(None, "--env", help="绑定到环境变量"),
|
|
193
|
+
stdin: bool = typer.Option(False, "--stdin", help="从标准输入读取密钥(加密保存)"),
|
|
194
|
+
clear: bool = typer.Option(False, "--clear", help="清空(显式为空)"),
|
|
195
|
+
default_env: bool = typer.Option(
|
|
196
|
+
False, "--default-env", help="恢复为包内默认的环境变量"
|
|
197
|
+
),
|
|
198
|
+
) -> None:
|
|
199
|
+
"""设置密钥(值从不回显)."""
|
|
200
|
+
chosen = [env is not None, stdin, clear, default_env]
|
|
201
|
+
if sum(chosen) != 1:
|
|
202
|
+
err_console.print(
|
|
203
|
+
"[red]--env / --stdin / --clear / --default-env 必须且只能指定一个[/red]"
|
|
204
|
+
)
|
|
205
|
+
raise typer.Exit(2)
|
|
206
|
+
if env is not None:
|
|
207
|
+
op: dict[str, Any] = {"op": "env", "var": env}
|
|
208
|
+
elif stdin:
|
|
209
|
+
op = {"op": "set", "value": sys.stdin.read().strip()}
|
|
210
|
+
elif clear:
|
|
211
|
+
op = {"op": "clear"}
|
|
212
|
+
else:
|
|
213
|
+
op = {"op": "default_env"}
|
|
214
|
+
try:
|
|
215
|
+
ensure_store_ready()
|
|
216
|
+
ConfigService().set_secret(path, op)
|
|
217
|
+
except _EXPECTED_ERRORS as exc:
|
|
218
|
+
raise _fail(exc) from None
|
|
219
|
+
console.print(f"[green]已更新密钥 {path}({op['op']})[/green]")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@app.command("token")
|
|
223
|
+
def config_token() -> None:
|
|
224
|
+
"""输出 Dashboard 管理 token(不存在时创建)."""
|
|
225
|
+
try:
|
|
226
|
+
token = load_or_create_admin_token()
|
|
227
|
+
except (OSError, ConfigStoreError) as exc:
|
|
228
|
+
raise _fail(exc) from None
|
|
229
|
+
sys.stdout.write(token + "\n")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
__all__ = ["app"]
|
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
from pydantic import BaseModel
|
|
5
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
6
|
+
|
|
7
|
+
from .home import default_token_store_str
|
|
6
8
|
|
|
7
9
|
|
|
8
10
|
class AuthConfig(BaseModel):
|
|
@@ -13,12 +15,14 @@ class AuthConfig(BaseModel):
|
|
|
13
15
|
此配置作为运行时注入值的权威来源(Single Source of Truth)。
|
|
14
16
|
"""
|
|
15
17
|
|
|
18
|
+
model_config = ConfigDict(hide_input_in_errors=True)
|
|
19
|
+
|
|
16
20
|
github_client_id: str = "Iv1.b507a08c87ecfe98"
|
|
17
21
|
google_client_id: str = (
|
|
18
22
|
"1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com"
|
|
19
23
|
)
|
|
20
24
|
google_client_secret: str = "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"
|
|
21
|
-
token_store_path: str =
|
|
25
|
+
token_store_path: str = Field(default_factory=default_token_store_str)
|
|
22
26
|
|
|
23
27
|
|
|
24
28
|
__all__ = ["AuthConfig"]
|