fix: revoke stale OAuth on re-auth and reject tokens missing force-ssl scope

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-22 01:17:23 -05:00
parent 6851984983
commit 0309bbe0f6
3 changed files with 92 additions and 5 deletions

View File

@ -571,6 +571,7 @@ async def shorts_live_analytics(
@app.get("/api/shorts/oauth/start")
async def shorts_oauth_start(channel_pk: str, request: Request) -> RedirectResponse:
try:
await shorts_oauth.prepare_reauthorize(channel_pk)
url = shorts_oauth.build_authorize_url(
channel_pk=channel_pk,
request_base=_request_public_base(request),

View File

@ -250,6 +250,68 @@ def requested_scopes() -> list[str]:
return [s for s in YOUTUBE_SCOPES.split() if s]
FORCE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
async def token_scopes(access_token: str) -> set[str]:
"""Granted scopes on an access token (tokeninfo)."""
if not access_token:
return set()
try:
async with httpx.AsyncClient(timeout=20.0, trust_env=False) as client:
resp = await client.get(
"https://oauth2.googleapis.com/tokeninfo",
params={"access_token": access_token},
)
data = resp.json() if resp.content else {}
raw = str(data.get("scope") or "")
return {s for s in raw.split() if s.strip()}
except Exception:
return set()
def missing_required_scopes(granted: set[str]) -> list[str]:
need = set(requested_scopes())
return sorted(s for s in need if s not in granted)
async def revoke_refresh_token(*, refresh_token: str, client_id: str = "", client_secret: str = "") -> bool:
"""Revoke old refresh token so re-auth must issue a new one with full scopes."""
rt = str(refresh_token or "").strip()
if not rt:
return False
try:
async with httpx.AsyncClient(timeout=20.0, trust_env=False) as client:
resp = await client.post(
"https://oauth2.googleapis.com/revoke",
data={"token": rt},
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
return resp.status_code in (200, 400)
except Exception:
return False
async def prepare_reauthorize(channel_pk: str) -> None:
"""Drop stale refresh_token before OAuth — fixes silent scope downgrade on re-auth."""
ch = db.get_shorts_channel(channel_pk) or {}
creds = channel_oauth_creds(ch)
rt = str(creds.get("refresh_token") or "").strip()
if rt:
await revoke_refresh_token(
refresh_token=rt,
client_id=str(creds.get("client_id") or ""),
client_secret=str(creds.get("client_secret") or ""),
)
db.update_shorts_channel(
channel_pk,
refresh_token="",
oauth_ok=0,
oauth_checked_at=time.time(),
oauth_error="重授权中:已撤销旧 token,完成 Google 授权后将写入新权限",
)
async def exchange_code(*, code: str, state: str, request_base: str = "") -> dict[str, Any]:
packed = _oauth_states.pop(state, None)
if not packed:
@ -287,9 +349,21 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
raise ValueError(f"换取 token 失败: {token.get('error_description') or token or token_resp.text}")
access = str(token["access_token"])
refresh = str(token.get("refresh_token") or "").strip()
had_old = bool(str(channel.get("refresh_token") or "").strip())
granted = await token_scopes(access)
missing = missing_required_scopes(granted)
if missing:
scope_hint = "、".join(s.rsplit("/", 1)[-1] for s in missing)
raise ValueError(
f"授权权限不完整(缺 {scope_hint})。"
f"请再点「重授权」;若仍失败,到 Google 账号 → 第三方应用访问权限,移除本应用后再授权。"
)
if not refresh:
refresh = str(channel.get("refresh_token") or "").strip()
if not refresh:
if had_old:
raise ValueError(
"Google 未下发新 refresh_token,旧 token 无法升级 YPP 所需权限。"
"请再点一次「重授权」(系统已自动撤销旧 token)。"
)
raise ValueError("未拿到 refresh_token,请在 Google 账号权限里撤销本应用后重试")
ch_resp = await client.get(
@ -340,6 +414,12 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
if yt_title and (not name or name.startswith("Shorts") or name == "未命名频道"):
patch["name"] = yt_title
updated = db.update_shorts_channel(channel_pk, **patch)
try:
from . import yt_long_db
yt_long_db.sync_channels_from_shorts()
except Exception:
pass
try:
from . import youtube_manage as ytm
from .yt_long_monetize import refresh_ypp_for_shorts_channel
@ -354,6 +434,7 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
"youtube_channel_id": yt_id,
"youtube_title": yt_title,
"youtube_handle": yt_handle,
"oauth_scopes_ok": True,
"oauth_client_source": source,
"oauth_profile_id": source_meta.get("profile_id") or "",
}
@ -387,11 +468,16 @@ async def probe_channel_oauth(channel: dict[str, Any], cfg: dict[str, Any] | Non
)
return {"ok": False, "error": "未授权或缺少 OAuth 凭证", "channel_id": cid}
try:
await refresh_access_token(
access = await refresh_access_token(
client_id=creds["client_id"],
client_secret=creds["client_secret"],
refresh_token=creds["refresh_token"],
)
missing = missing_required_scopes(await token_scopes(str(access)))
if missing:
err = "OAuth 权限不足(缺 force-ssl),请点「重授权」升级 YPP 获利权限"
db.update_shorts_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err)
return {"ok": False, "error": err, "channel_id": cid, "missing_scopes": missing}
db.update_shorts_channel(cid, oauth_ok=1, oauth_checked_at=now, oauth_error="")
return {"ok": True, "channel_id": cid}
except Exception as exc:

View File

@ -459,8 +459,8 @@ export default function ShortsPage() {
if (hasBound && needTitle) {
const ok = window.confirm(
`本卡需要的 YouTube 频道:\n${needTitle}${needHandle ? ` ${needHandle}` : ""}\n\n` +
`Google 列表里的「品牌账号名」经常和上面不一样。\n` +
`点错了没关系:不会写入授权,页面会告诉你实际选中了谁,再换下一个试。\n\n继续打开 Google?`
`系统将自动撤销旧 OAuth token,再打开 Google 重新授权(含 YPP 获利所需 force-ssl 权限)。\n` +
`Google 品牌账号名可能和上面不一样;点错了页面会提示,不会写入。\n\n继续?`
);
if (!ok) return;
}