Skip to content

Commit 41dab6d

Browse files
committed
fix(copilot): 换票 403 时回退 GitHub token,设备码重复点击复用
GitHub 对部分账号在 copilot_internal/v2/token 上回 403(防爬提示), 原实现未捕获,poll 冒泡 500,前端永远停在「登录中」。实测 api.githubcopilot.com 仍接受 GitHub OAuth token,故 403 时回退成 「GitHub token 直接当 Bearer」+ 30 分钟有效期,预刷新按常规节奏再试换票。 同时修设备码轨道两处会让界面永久转圈的问题: - start 每次换新 device_code,用户按旧码授权后服务端轮询新码; 现复用同一用户未过期的 pending(auth_state.find_for)。 - 申请设备码 / 轮询遇直连 ReadTimeout 直接失败;现链路错误重试, 轮询连续 3 次失败才报错。 Qwen Code 同轨一并复用 pending。
1 parent fd4f3f9 commit 41dab6d

8 files changed

Lines changed: 298 additions & 27 deletions

File tree

‎src/provider/auth_state.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,24 @@ def reservation(self, auth_state: str, username: str,
8585
return None
8686
return self._entries[auth_state]
8787

88+
def find_for(self, username: str,
89+
now: int | None = None) -> tuple[str, Reservation[T]] | None:
90+
"""按归属人找一条仍有效的 pending(设备码登录的「重复点击复用」)。
91+
92+
设备码流程里,用户重新点一次登录若拿到**新的** device_code,之前显示
93+
给用户的码就作废了:用户照着旧码在 GitHub 上授权,服务端却在轮询新
94+
code,界面会永远停在「登录中」。故 `start` 先复用同一用户的未过期
95+
会话,保证界面上摆着的码就是被轮询的那个。
96+
"""
97+
current = int(now if now is not None else time.time())
98+
for state, entry in self._entries.items():
99+
if entry.username != username:
100+
continue
101+
if current - entry.created_at >= self._ttl:
102+
continue
103+
return state, entry
104+
return None
105+
88106
def consume(self, auth_state: str, username: str, now: int | None = None) -> bool:
89107
"""消费:成功后该 state 不可再次轮询或重放。"""
90108
if not self.owner(auth_state, username, now):

‎src/provider/copilot/client.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
from ..http_json import json_or_raise
3131
from ..lazy_clients import LazyClients
3232
from . import events as copilot_events
33-
from .credential import CopilotCredential
33+
from .credential import FALLBACK_TOKEN_TTL_SECONDS, CopilotCredential
3434

3535
#: 聊天端点(公开事实,非用户可配置输入)
3636
COPILOT_HOST = "https://api.githubcopilot.com"
@@ -40,6 +40,8 @@
4040
EP_MODELS = "/models"
4141
EP_TOKEN = "/copilot_internal/v2/token"
4242
EP_USER = "/copilot_internal/user"
43+
#: 换票端点拒绝、但聊天端点仍认 GitHub token 的状态码(403 = GitHub 防爬策略)
44+
GITHUB_TOKEN_FALLBACK_STATUSES = frozenset({403})
4345

4446
#: 伪装成官方 VS Code 插件(上游按这两个头放行)
4547
INTEGRATION_ID = "vscode-chat"
@@ -109,9 +111,21 @@ def __init__(
109111

110112
async def exchange(self, github_token: str, *,
111113
username: str = "") -> CopilotCredential:
112-
"""GitHub token → 短期 Copilot token(每次现换,不猜 TTL)。"""
114+
"""GitHub token → 短期 Copilot token(每次现换,不猜 TTL)。
115+
116+
GitHub 对部分账号在换票端点上回 403(防爬提示),而聊天端点仍接受
117+
GitHub token 本身。此时退回「用 GitHub token 当 Bearer」并给一个
118+
有限有效期:登录 / 聊天不再直接失败,预刷新之后会再试换票。
119+
"""
113120
response = await self._short.get(f"{self.github_host}{EP_TOKEN}",
114121
headers=github_headers(github_token))
122+
if response.status_code in GITHUB_TOKEN_FALLBACK_STATUSES:
123+
return CopilotCredential(
124+
github_token=github_token,
125+
copilot_token=github_token,
126+
expires_at=int(time.time()) + FALLBACK_TOKEN_TTL_SECONDS,
127+
username=username,
128+
)
115129
data = await json_or_raise(
116130
response, UpstreamHTTPError, EP_TOKEN,
117131
message="non-JSON copilot token response")

‎src/provider/copilot/credential.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,15 @@
3131
#: 预刷新提前量:token 寿命约 30 分钟,提前 5 分钟换,避免请求临界失败
3232
REFRESH_SKEW_SECONDS = 300
3333

34+
#: 短期 token 换不出来时退回「直接用 GitHub token」的有效期。
35+
#:
36+
#: GitHub 已对部分账号/客户端在 `copilot_internal/v2/token` 上回 403
37+
#: (文案是防爬提示),但 `api.githubcopilot.com` 的 `/models` 与
38+
#: `/chat/completions` 仍接受同一张 GitHub OAuth token 作 Bearer。此时没有
39+
#: 30 分钟的短期票,GitHub token 本身也不会这么快失效,故给一个偏长的
40+
#: 有效窗口,让预刷新按常规节奏重试换票(换成功了就自动切回短期票)。
41+
FALLBACK_TOKEN_TTL_SECONDS = 1800
42+
3443

3544
@dataclass(slots=True)
3645
class CopilotCredential:

‎src/provider/copilot/oauth.py‎

Lines changed: 80 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
from ..base import AuthFlow, AuthResult, AuthSession, UpstreamProtocolViolation
2828
from ..credential_fields import text_field
2929
from ..proxy import build_client
30-
from .client import CopilotClient
30+
from .client import CopilotClient, UpstreamHTTPError
3131

3232
GITHUB_LOGIN = "https://github.com"
3333
EP_DEVICE_CODE = "/login/device/code"
@@ -42,6 +42,11 @@
4242
MAX_INTERVAL = 30
4343
#: 「还在等用户授权」的错误码(RFC 8628):不是失败,继续轮询
4444
PENDING_ERRORS = ("authorization_pending", "slow_down")
45+
#: 申请设备码的尝试次数:GitHub 对直连时常「连上了但首包不来」(ReadTimeout),
46+
#: 一次失败就把 500 甩给界面,用户只会看到「无法启动登录流程」。
47+
DEVICE_CODE_ATTEMPTS = 3
48+
#: 轮询时连续链路失败的上限:直连 GitHub 偶发读超时算「在等」,连续失败才报错
49+
MAX_CONSECUTIVE_FAILURES = 3
4550

4651

4752
@dataclass(slots=True)
@@ -50,6 +55,20 @@ class _Pending:
5055

5156
device_code: str
5257
interval: int
58+
#: 展示给用户的设备码与授权页(复用时据此重建同一张授权链接)
59+
user_code: str = ""
60+
verification_uri: str = GITHUB_LOGIN + EP_DEVICE_CODE
61+
#: 连续链路失败次数(读超时 / 连接被断):连续到上限就报错,不让界面无限转圈
62+
failures: int = 0
63+
64+
65+
def _session(state: str, pending: _Pending) -> AuthSession:
66+
"""pending 载荷 → 对外的 AuthSession(新申请与复用共用同一份拼装)。"""
67+
# 带上 user_code 的完整授权页:用户点开就能直接输码,不必自己抄
68+
auth_url = f"{pending.verification_uri}?{urlencode({'user_code': pending.user_code})}"
69+
return AuthSession(flow=AuthFlow.POLL, state=state, auth_url=auth_url,
70+
interval=pending.interval, callback_url=None,
71+
user_code=pending.user_code)
5372

5473

5574
class CopilotOAuth:
@@ -80,11 +99,20 @@ async def aclose(self) -> None:
8099
await self._tokens.aclose()
81100

82101
async def start(self, username: str) -> AuthSession:
83-
"""申请设备码并登记 pending;校验通过前不让前端导航。"""
84-
response = await self._http.post(
85-
f"{GITHUB_LOGIN}{EP_DEVICE_CODE}",
86-
data={"client_id": self.client_id, "scope": SCOPE},
87-
headers={"Accept": "application/json"})
102+
"""申请设备码并登记 pending;校验通过前不让前端导航。
103+
104+
GitHub 对直连经常「TCP 通了但首包不回」(`ReadTimeout`),一次失败就
105+
把 500 甩给界面会让用户以为功能坏了;这里对**链路错误**重试几次,
106+
业务错误(非 200 / 响应残缺)仍立即失败。
107+
108+
同一用户已有未过期的 pending 时**复用它**:重新申请会换一个新
109+
device_code,用户按界面上旧码在 GitHub 授权就永远不会被轮询到。
110+
"""
111+
existing = self.store.find_for(username)
112+
if existing is not None:
113+
state, reservation = existing
114+
return _session(state, reservation.payload)
115+
response = await self._request_device_code()
88116
if response.status_code != 200:
89117
raise UpstreamProtocolViolation("GitHub device code request rejected")
90118
body = _json_body(response)
@@ -98,23 +126,45 @@ async def start(self, username: str) -> AuthSession:
98126
raw_interval = body.get("interval")
99127
interval = (raw_interval if isinstance(raw_interval, int)
100128
and not isinstance(raw_interval, bool) and raw_interval > 0 else 5)
101-
reservation = self.store.begin(
102-
username, _Pending(device_code=device_code, interval=interval))
103-
# 带上 user_code 的完整授权页:用户点开就能直接输码,不必自己抄
104-
auth_url = f"{verification_uri}?{urlencode({'user_code': user_code})}"
105-
return AuthSession(flow=AuthFlow.POLL, state=reservation, auth_url=auth_url,
106-
interval=interval, callback_url=None, user_code=user_code)
129+
payload = _Pending(device_code=device_code, interval=interval,
130+
user_code=user_code, verification_uri=verification_uri)
131+
state = self.store.begin(username, payload)
132+
return _session(state, payload)
133+
134+
async def _request_device_code(self) -> httpx.Response:
135+
"""申请设备码,链路错误重试(最后一轮的异常照常抛给调用方)。"""
136+
for attempt in range(DEVICE_CODE_ATTEMPTS): # pragma: no branch
137+
try:
138+
return await self._http.post(
139+
f"{GITHUB_LOGIN}{EP_DEVICE_CODE}",
140+
data={"client_id": self.client_id, "scope": SCOPE},
141+
headers={"Accept": "application/json"})
142+
except httpx.TransportError:
143+
if attempt + 1 >= DEVICE_CODE_ATTEMPTS:
144+
raise
145+
raise AssertionError("unreachable") # pragma: no cover - 循环必返回或抛出
107146

108147
async def poll(self, auth_state: str, username: str) -> AuthResult | None:
109148
"""返回 None 表示仍在等授权;成功后 state 被消费。"""
110149
payload = self.store.payload(auth_state, username)
111150
if payload is None:
112151
raise UpstreamProtocolViolation("unknown or consumed auth state")
113-
response = await self._http.post(
114-
f"{GITHUB_LOGIN}{EP_ACCESS_TOKEN}",
115-
data={"client_id": self.client_id, "device_code": payload.device_code,
116-
"grant_type": "urn:ietf:params:oauth:grant-type:device_code"},
117-
headers={"Accept": "application/json"})
152+
try:
153+
response = await self._http.post(
154+
f"{GITHUB_LOGIN}{EP_ACCESS_TOKEN}",
155+
data={"client_id": self.client_id, "device_code": payload.device_code,
156+
"grant_type": "urn:ietf:params:oauth:grant-type:device_code"},
157+
headers={"Accept": "application/json"})
158+
except httpx.TransportError as error:
159+
# 直连 GitHub 常出现「连上了但首包不回」。单次读超时不是登录失败,
160+
# 但连续失败说明链路真断了:到上限才报错,别让界面无限转圈。
161+
payload.failures += 1
162+
if payload.failures < MAX_CONSECUTIVE_FAILURES:
163+
return None
164+
raise UpstreamProtocolViolation(
165+
f"GitHub device login unreachable after {payload.failures} attempts: "
166+
f"{type(error).__name__}") from error
167+
payload.failures = 0
118168
# 上游默认回表单编码;只有显式要 JSON 且解析出非对象才算协议损坏。
119169
# 表单编码 / 空 body = 用户还没授权,按「在等」处理(不能让前端看到
120170
# 一条「响应格式异常」,那会把「点一下授权」误报成故障)。
@@ -134,7 +184,18 @@ async def poll(self, auth_state: str, username: str) -> AuthResult | None:
134184
github_token = text_field(body, "access_token")
135185
if not github_token:
136186
return None # 用户还没完成授权
137-
credential = await self._tokens.exchange(github_token)
187+
try:
188+
credential = await self._tokens.exchange(github_token)
189+
except UpstreamHTTPError as error:
190+
# GitHub 授权成功 ≠ Copilot 可用:免费档 / 未开通 Copilot 的账号
191+
# 换短期 token 会被 403 拒(文案是 GitHub 的「scraping」提示)。
192+
# 必须消费掉会话并给出可行动的原因,否则前端只能看到 500。
193+
self.store.cancel(auth_state, username)
194+
raise UpstreamProtocolViolation(
195+
"GitHub 授权成功,但换取 Copilot token 被拒"
196+
f"(HTTP {error.status}):该账号可能未开通 GitHub Copilot。",
197+
public="GitHub 授权成功,但该账号无法换取 Copilot token"
198+
"(可能未开通 GitHub Copilot)。") from error
138199
credential.username = await self._fetch_login(github_token) or ""
139200
if not self.store.consume(auth_state, username):
140201
raise UpstreamProtocolViolation("auth state was consumed concurrently")
@@ -179,4 +240,4 @@ def _is_json(response: httpx.Response) -> bool:
179240
return "json" in response.headers.get("content-type", "").lower()
180241

181242

182-
__all__ = ["AUTH_STATE_TTL_SECONDS", "CopilotOAuth", "DEFAULT_CLIENT_ID"]
243+
__all__ = ["AUTH_STATE_TTL_SECONDS", "CopilotOAuth", "DEFAULT_CLIENT_ID"]

‎src/provider/qwen_code/oauth.py‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,17 @@ class _Pending:
4545

4646
device_code: str
4747
interval: int
48+
#: 展示给用户的设备码与授权页(复用时据此重建同一张授权链接)
49+
user_code: str = ""
50+
verification_uri: str = ""
51+
52+
53+
def _session(state: str, pending: _Pending) -> AuthSession:
54+
"""pending 载荷 → 对外的 AuthSession(新申请与复用共用同一份拼装)。"""
55+
auth_url = f"{pending.verification_uri}?{urlencode({'user_code': pending.user_code})}"
56+
return AuthSession(flow=AuthFlow.POLL, state=state, auth_url=auth_url,
57+
interval=pending.interval, callback_url=None,
58+
user_code=pending.user_code)
4859

4960

5061
class QwenCodeOAuth:
@@ -71,7 +82,15 @@ async def aclose(self) -> None:
7182
await self._client.aclose()
7283

7384
async def start(self, username: str) -> AuthSession:
74-
"""申请设备码并登记 pending;校验通过前不让前端导航。"""
85+
"""申请设备码并登记 pending;校验通过前不让前端导航。
86+
87+
同一用户已有未过期的 pending 时复用它:重新申请会换新 device_code,
88+
用户按界面上旧码授权就永远不会被轮询到。
89+
"""
90+
existing = self.store.find_for(username)
91+
if existing is not None:
92+
state, reservation = existing
93+
return _session(state, reservation.payload)
7594
response = await self._http.post(
7695
f"{self.host}{EP_DEVICE_CODE}",
7796
json={"client_id": "qwen-code", "scope": "openid profile"},
@@ -89,11 +108,10 @@ async def start(self, username: str) -> AuthSession:
89108
raw_interval = body.get("interval")
90109
interval = (raw_interval if isinstance(raw_interval, int)
91110
and not isinstance(raw_interval, bool) and raw_interval > 0 else 5)
92-
reservation = self.store.begin(
93-
username, _Pending(device_code=device_code, interval=interval))
94-
auth_url = f"{verification_uri}?{urlencode({'user_code': user_code})}"
95-
return AuthSession(flow=AuthFlow.POLL, state=reservation, auth_url=auth_url,
96-
interval=interval, callback_url=None, user_code=user_code)
111+
payload = _Pending(device_code=device_code, interval=interval,
112+
user_code=user_code, verification_uri=verification_uri)
113+
state = self.store.begin(username, payload)
114+
return _session(state, payload)
97115

98116
async def poll(self, auth_state: str, username: str) -> AuthResult | None:
99117
"""返回 None 表示仍在等授权;成功后 state 被消费。"""

0 commit comments

Comments
 (0)