From db307844e73f026355c6742614ea21cc1dd6d08b Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 4 Nov 2026 12:37:29 +0800 Subject: [PATCH] orcaterm 0.1.6: keep the WeChat sign-in's refresh token and renew from it (#675) orinsid's desktop-client logs (#675, 11-04) show OrcaTerm 1.6.8 renewing from a long-lived oauth_refresh_token_v2 on a 110-minute schedule, while the plugin dropped the exchange's refresh token (`refresh: r.accessToken`) and renewed from the two-hour access token, which OrcaTerm answers SESSION_EXPIRED for 30 minutes into an idle sign-in. OrcaTerm's own bundle (orcaterm.cloud.tencent.com/terminal, orcaterm_components/orcaterm_app, fetched 11-04) settles the protocol: - the WeChat exchange sends {code, state, client: "desktop"} from the desktop client, and reads data.refreshToken from the reply; - the client keeps a refresh token only when it matches /^\.\d{1,6}\.[A-Za-z0-9_-]{43}$/ and its uuid is the access token's jti (persistLoginRefreshToken); - OAuthRefreshToken sends {refreshToken} when it has one, else {accessToken}. The plugin now does the same: the exchange sends client "desktop", a matching refresh token is the sign-in's `refresh`, renewal sends it (an access token past its expiry no longer stops a renewal that has one), and a reply's RefreshToken replaces it, else it is kept. A sign-in from before 0.1.6 has the access token in `refresh` and renews as before until the next scan. Run (mote): packages/orcaterm `bun test`, 121 pass / 0 fail, including the new refresh-token.test.mjs (6 tests). Broken by hand: dropped client "desktop", sent {accessToken} always and saved `refresh: r.accessToken` again: 4 of the 6 new tests went red (the two that stay green check a mismatched token isn't kept and the pre-0.1.6 path). Not tried: a real WeChat sign-in. No OrcaTerm account here, so whether the reply to client "desktop" carries refreshToken for this flow, and whether renewal rotates it, is from the vendor's bundle, not a capture. If the reply has none, the sign-in falls back to the 0.1.5 behaviour. --- packages/orcaterm/index.mjs | 22 +++-- packages/orcaterm/package.json | 2 +- packages/orcaterm/refresh-token.test.mjs | 109 +++++++++++++++++++++++ packages/orcaterm/wechat.mjs | 55 ++++++++++-- 4 files changed, 172 insertions(+), 16 deletions(-) create mode 100644 packages/orcaterm/refresh-token.test.mjs diff --git a/packages/orcaterm/index.mjs b/packages/orcaterm/index.mjs index 285a591..30ad62c 100644 --- a/packages/orcaterm/index.mjs +++ b/packages/orcaterm/index.mjs @@ -25,6 +25,7 @@ import { createLocalCapture, exchangeCode, looksLikeAccessToken, + looksLikeRefreshToken, readTokenClaims, refreshAccessToken, startWechatLogin, @@ -1991,11 +1992,13 @@ export const OrcaTermAuthPlugin = async ({ client } = {}) => { const r = await exchangeCode({ code, state }) // magpie writes the credential only when a `refresh` is present // (host `save()`); with just a `key` it is stored as type "api" - // and never renewed. + // and never renewed. The refresh token is what renews it + // past the access token's two hours (#675); a reply without + // one falls back to renewing from the access token. return { type: "success", access: r.accessToken, - refresh: r.accessToken, + refresh: r.refreshToken || r.accessToken, expires: r.expiresAt ?? Date.now() + 7200 * 1000, // magpie deduplicates re-sign-ins by accountId, not userId. accountId: r.userId, @@ -2030,22 +2033,27 @@ export const OrcaTermAuthPlugin = async ({ client } = {}) => { /** * Renewal. A WeChat access token lives two hours; `OAuthRefreshToken` trades - * it for a fresh one of the same length, so a normal session never sees an - * expiry. + * the refresh token kept at sign-in (or, for a sign-in from before 0.1.6, + * the access token itself) for a fresh one of the same length. * * A console cookie has nothing to renew — it lasts until the user signs out * of the console. */ async refresh(auth) { const bearer = bearerOf(auth) - if (!bearer) return null + // #675: a sign-in from 0.1.6 on keeps OrcaTerm's refresh token in + // `refresh`, which renews after the access token's session is gone, + // as the desktop client does. One from before holds the access + // token there and renews from it until the next scan. + const refreshToken = looksLikeRefreshToken(auth?.refresh) ? String(auth.refresh).trim() : "" + if (!bearer && !refreshToken) return null try { - const r = await refreshAccessToken(bearer) + const r = await refreshAccessToken(bearer, { refreshToken }) const userId = readTokenClaims(bearer).userId || auth?.userId || auth?.metadata?.userId return { key: r.accessToken, access: r.accessToken, - refresh: r.accessToken, + refresh: r.refreshToken || r.accessToken, expires: r.expiresAt ?? undefined, ...(userId ? { accountId: auth?.accountId || String(userId), uid: auth?.uid || String(userId), userId: String(userId) } : {}), metadata: { ...(auth?.metadata ?? {}), via: "wechat-qr", expires: r.expiresAt ?? undefined }, diff --git a/packages/orcaterm/package.json b/packages/orcaterm/package.json index 369c29c..a0cacca 100644 --- a/packages/orcaterm/package.json +++ b/packages/orcaterm/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-orcaterm-auth", - "version": "0.1.5", + "version": "0.1.6", "description": "OrcaTerm (Tencent Cloud 遨驰终端) AI quota as an OpenAI-compatible provider for magpie and OpenCode", "type": "module", "main": "./opencode.mjs", diff --git a/packages/orcaterm/refresh-token.test.mjs b/packages/orcaterm/refresh-token.test.mjs new file mode 100644 index 0000000..f8ba872 --- /dev/null +++ b/packages/orcaterm/refresh-token.test.mjs @@ -0,0 +1,109 @@ +// #675 (orinsid, 2026-11-04): OrcaTerm's desktop client keeps a long-lived +// refresh token (oauth_refresh_token_v2) and renews from it, while the +// plugin threw the exchange's refresh token away and renewed from the +// two-hour access token, which OrcaTerm stops renewing once its web session +// is gone. The client's own bundle sends client "desktop" to +// /oauth/wechat/exchange, keeps data.refreshToken when its jti prefix is the +// access token's jti, and calls OAuthRefreshToken with {refreshToken} when it +// has one, {accessToken} otherwise. +import { test, afterEach } from "bun:test" +import assert from "node:assert/strict" +import { OrcaTermAuthPlugin } from "./index.mjs" + +const realFetch = globalThis.fetch +afterEach(() => { globalThis.fetch = realFetch }) +const json = data => Response.json({ code: 0, data }) +const JTI = "0d4c2f7e-9b1a-4c3d-8e5f-6a7b8c9d0e1f" +const tail = "A".repeat(43) +const access = (jti, exp = Math.floor(Date.now() / 1000) + 7200) => + `eyJhbGciOiJub25lIn0.${Buffer.from(JSON.stringify({ userId: "u1", jti, exp })).toString("base64url")}.test` +const refreshOf = (jti, n = 1) => `${jti}.${n}.${tail}` + +async function scan(data, seen) { + globalThis.fetch = async (url, init) => { + if (String(url).endsWith("/oauth/wechat/config")) return json({ + appid: "rt-test", redirect_uri: "https://orcaterm.com/oauth/wechat/bridge", + state: "rt-state", scope: "snsapi_login", + }) + assert.ok(String(url).endsWith("/oauth/wechat/exchange")) + seen.push(JSON.parse(init.body)) + return json(data) + } + const plugin = await OrcaTermAuthPlugin() + const flow = await plugin.auth.methods[0].authorize() + try { + const res = await realFetch(new URL("/cb", flow.url), { + method: "POST", headers: { "content-type": "application/json", origin: new URL(flow.url).origin, connection: "close" }, + body: JSON.stringify({ code: "c", state: "rt-state", error: null }), + }) + assert.equal(res.status, 200) + return await flow.callback() + } finally { flow.__cap.close() } +} + +test("QR sign-in asks for the desktop client's refresh token and keeps it as the sign-in's refresh", async () => { + const seen = [] + const r = await scan({ userId: "u1", providerUsername: "A", accessToken: access(JTI), refreshToken: refreshOf(JTI), expiresIn: 7200 }, seen) + assert.equal(r.type, "success") + assert.equal(seen[0].client, "desktop") + assert.equal(r.refresh, refreshOf(JTI)) + assert.equal(r.access, access(JTI)) +}) + +test("a refresh token issued with another access token, or none, isn't kept", async () => { + for (const refreshToken of [refreshOf("11111111-2222-3333-4444-555555555555"), "not-a-token", undefined]) { + const r = await scan({ userId: "u1", providerUsername: "A", accessToken: access(JTI), refreshToken, expiresIn: 7200 }, []) + assert.equal(r.type, "success") + assert.equal(r.refresh, r.access) + } +}) + +async function renew(stored, reply) { + const sent = [] + globalThis.fetch = async (url, init) => { + assert.equal(String(url), "https://orcaterm.com/cgi/api?action=OAuthRefreshToken") + sent.push(JSON.parse(init.body).data) + return json(reply) + } + const plugin = await OrcaTermAuthPlugin() + return { next: await plugin.auth.refresh(stored), sent } +} + +test("renewal sends the refresh token, not the access token, and keeps the one the reply rotates to", async () => { + const next2 = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" + const { next, sent } = await renew( + { type: "oauth", access: access(JTI), refresh: refreshOf(JTI), expires: Date.now() + 60e3 }, + { AccessToken: access(next2), RefreshToken: refreshOf(next2, 2), ExpiresIn: 7200 }, + ) + assert.deepEqual(sent, [{ refreshToken: refreshOf(JTI) }]) + assert.equal(next.access, access(next2)) + assert.equal(next.refresh, refreshOf(next2, 2)) +}) + +test("a reply with no refresh token keeps the one the sign-in has", async () => { + const { next } = await renew( + { type: "oauth", access: access(JTI), refresh: refreshOf(JTI), expires: Date.now() + 60e3 }, + { accessToken: access("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"), expiresIn: 7200 }, + ) + assert.equal(next.refresh, refreshOf(JTI)) +}) + +test("an access token past its expiry still renews from the refresh token", async () => { + const old = access(JTI, Math.floor(Date.now() / 1000) - 3600) + const { next, sent } = await renew( + { type: "oauth", access: old, refresh: refreshOf(JTI), expires: Date.now() - 3600e3 }, + { accessToken: access("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"), expiresIn: 7200 }, + ) + assert.deepEqual(sent, [{ refreshToken: refreshOf(JTI) }]) + assert.ok(next?.access) +}) + +test("a sign-in from before 0.1.6 renews from its access token as it did", async () => { + const before = access(JTI) + const { next, sent } = await renew( + { type: "oauth", access: before, refresh: before, expires: Date.now() + 60e3 }, + { accessToken: access("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"), expiresIn: 7200 }, + ) + assert.deepEqual(sent, [{ accessToken: before }]) + assert.equal(next.refresh, next.access) +}) diff --git a/packages/orcaterm/wechat.mjs b/packages/orcaterm/wechat.mjs index 1c229a6..af655b3 100644 --- a/packages/orcaterm/wechat.mjs +++ b/packages/orcaterm/wechat.mjs @@ -7,8 +7,8 @@ * → the local page below embeds WeChat's qrconnect widget * the scan returns to {redirect_uri} (/oauth/wechat/bridge?code&state), and that * page postMessages the result to its parent — which is our page - * POST {OAUTH}/oauth/wechat/exchange → {userId, accessToken, expiresIn, …} - * POST {CAPI}?action=OAuthRefreshToken → renews it + * POST {OAUTH}/oauth/wechat/exchange → {userId, accessToken, refreshToken, expiresIn, …} + * POST {CAPI}?action=OAuthRefreshToken → renews it from the refresh token * * Why `self_redirect: true` matters: after a scan, qrconnect navigates the *top* * window by default, which replaces the host page and loses the postMessage. @@ -97,7 +97,12 @@ export async function exchangeCode({ code, state, base = OAUTH_BASE }) { const { res, body, text } = await jsonFetch(`${base}/oauth/wechat/exchange`, { method: "POST", headers: { accept: "application/json", "content-type": "application/json" }, - body: JSON.stringify({ code, state }), + // OrcaTerm's desktop client sends client "desktop" (#675), and only then + // does the reply carry a refreshToken: a long-lived credential that + // OAuthRefreshToken renews from after the two-hour access token and its + // web session are gone. The web console sends no client and gets a + // session cookie instead, which magpie has no use for. + body: JSON.stringify({ code, state, client: "desktop" }), }) const known = ["STATE_EXPIRED", "STATE_MISMATCH", "INVALID_REQUEST", "PROVIDER_DISABLED"] const c = String(body?.code ?? "") @@ -118,19 +123,44 @@ export async function exchangeCode({ code, state, base = OAUTH_BASE }) { nickname: d.providerUsername ?? "", avatar: d.avatar ?? "", accessToken: d.accessToken, + refreshToken: refreshTokenFor(d.refreshToken, d.accessToken), expiresIn, expiresAt: expiresIn ? Date.now() + expiresIn * 1000 : null, } } -/** Renew: trade the current token for a fresh one (same two-hour life). */ -export async function refreshAccessToken(token, { base = OAUTH_BASE } = {}) { +// The desktop client's shape of a refresh token: "..<43 chars>", its +// jti that of the access token issued with it. The client keeps one only +// when both hold (persistLoginRefreshToken), and so does this. +const REFRESH_TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.\d{1,6}\.[A-Za-z0-9_-]{43}$/ + +/** True for something shaped like OrcaTerm's refresh token. */ +export function looksLikeRefreshToken(s) { + return REFRESH_TOKEN.test(String(s ?? "").trim()) +} + +/** The refresh token when it belongs to accessToken, else "". */ +export function refreshTokenFor(refreshToken, accessToken) { + const r = String(refreshToken ?? "").trim() + if (!looksLikeRefreshToken(r)) return "" + return readTokenClaims(accessToken).jti === r.split(".")[0] ? r : "" +} + +/** + * Renew: trade the refresh token, or without one the current access token, + * for a fresh access token (same two-hour life). OrcaTerm's own client sends + * one or the other, the refresh token when it has it (OAuthRefreshToken in + * its bundle). A reply may carry the next refresh token; without one the + * same one stays. + */ +export async function refreshAccessToken(token, { base = OAUTH_BASE, refreshToken = "" } = {}) { + const data = refreshToken ? { refreshToken } : { accessToken: token } const { body, text } = await jsonFetch( `${base}/cgi/api?action=OAuthRefreshToken`, { method: "POST", headers: { accept: "application/json", "content-type": "application/json" }, - body: JSON.stringify({ action: "OAuthRefreshToken", data: { accessToken: token } }), + body: JSON.stringify({ action: "OAuthRefreshToken", data }), }, 15000, ) @@ -140,7 +170,15 @@ export async function refreshAccessToken(token, { base = OAUTH_BASE } = {}) { throw new WechatLoginError("INTERNAL_ERROR", `renewal failed: ${(r?.Error?.Message || text).slice(0, 120)}`) } const expiresIn = Number(r?.expiresIn ?? r?.ExpiresIn) || 0 - return { accessToken: next, expiresIn, expiresAt: expiresIn ? Date.now() + expiresIn * 1000 : null } + const nextRefresh = looksLikeRefreshToken(r?.refreshToken ?? r?.RefreshToken) + ? String(r?.refreshToken ?? r?.RefreshToken).trim() + : refreshToken + return { + accessToken: next, + refreshToken: nextRefresh, + expiresIn, + expiresAt: expiresIn ? Date.now() + expiresIn * 1000 : null, + } } /** Read userId/nickname/expiry out of the JWT (no signature check). */ @@ -151,9 +189,10 @@ export function readTokenClaims(token) { userId: p?.userId != null ? String(p.userId) : "", nickname: p?.providerUsername ?? "", exp: Number(p?.exp) || 0, + jti: p?.jti != null ? String(p.jti) : "", } } catch { - return { userId: "", nickname: "", exp: 0 } + return { userId: "", nickname: "", exp: 0, jti: "" } } }