2727from ..base import AuthFlow , AuthResult , AuthSession , UpstreamProtocolViolation
2828from ..credential_fields import text_field
2929from ..proxy import build_client
30- from .client import CopilotClient
30+ from .client import CopilotClient , UpstreamHTTPError
3131
3232GITHUB_LOGIN = "https://github.com"
3333EP_DEVICE_CODE = "/login/device/code"
4242MAX_INTERVAL = 30
4343#: 「还在等用户授权」的错误码(RFC 8628):不是失败,继续轮询
4444PENDING_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
5574class 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" ]
0 commit comments