diff --git a/packages/codearts/README.md b/packages/codearts/README.md index b4977dd..65fc676 100644 --- a/packages/codearts/README.md +++ b/packages/codearts/README.md @@ -25,26 +25,35 @@ or install it from magpie's Plugins tab and sign in there. **Sign in with Huawei Cloud** opens Huawei Cloud's consent page. The plugin listens on a loopback port (`127.0.0.1`, ≥ 10000) for the redirect and exchanges the code at Huawei Cloud STS — a PKCE flow whose token requests carry an ES256 DPoP proof, as the CodeArts client does. -STS answers with temporary AK/SK/security-token credentials and a refresh token. +STS answers with temporary AK/SK/security-token credentials and a refresh token. The callback +server takes one GET to `/oauth/callback`, exactly; one that comes back without a code (the +portal's error) fails the sign-in at once. **Where it is kept:** the whole credential (AK/SK/security token, expiry, refresh token, the PKCE verifier and the DPoP private key) is a JSON string in the account's `access` field, in magpie's (or OpenCode's) own account store. `auth.refresh` renews it 30 minutes before it expires, reusing the same verifier and DPoP key; a stale credential met on a request -(`401`, `APIG.0602`) is renewed once and the request sent again. The account id is the signer -named in the refresh token, so signing in again replaces the account instead of adding one. +(`401`, `APIG.0602`) is renewed once and the request sent again. A refresh token is spent once +per account, however many loaders ask; a renewal that only fails for now (STS unreachable) +answers `503` and keeps the sign-in, and only one STS turns away for good marks it. The +account id is the signer named in the refresh token, so signing in again replaces the account +instead of adding one. ## Models The account's live list: CodeArts' builtin models, plus the free models of its daily benefit once today's benefit has been claimed (`POST /api/v1/benefit/claim`, once a Beijing day, as the -client does). Each model's credit rate (the client's 「消耗系数」) is reported as magpie's `rate`, +client does; a `benefit not found` on a day not yet claimed claims it too). Each model's credit +rate (the client's 「消耗系数」) is reported as magpie's `rate`, with its reasoning flag and limits, from the account's main agent (`build`) model list. Before signing in, a short built-in catalog stands in. ## Requests -- Every request is signed with Huawei's SDK-HMAC-SHA256 using the temporary credentials. +- Every request is signed with Huawei's SDK-HMAC-SHA256 using the temporary credentials, and + only for CodeArts' own two hosts, `snap-access.cn-north-4.myhuaweicloud.com` and + `opengw.developer.huaweicloud.com`: a request anywhere else (an overridden `api`) is refused + before the credentials leave, and no signed or token request follows a redirect. - The gateway allows 3 concurrent sessions per account and tells them apart by `x-ot-session-id`; the plugin sends one stable session id per account (and a fresh trace per request) like the client, keeps at most 3 chats in flight per account, retries @@ -69,7 +78,9 @@ signing in, a short built-in catalog stands in. `~/.config/magpie/codearts-checkins.json` (or `MAGPIE_CODEARTS_LEDGER`). This part is still being checked against more accounts — trust the CodeArts console where they differ. - `auth.checkin`: the client's 「限时福利 → 每日领取」 — `GET /v1/ops/delivery?channel=IDE`, - `POST /v1/ops/claim`, then `POST /v1/ops/confirm` when the claim answers an id. Turn on + `POST /v1/ops/claim`, then `POST /v1/ops/confirm` when the claim answers an id. A claim whose + confirm failed is kept in that ledger for the day and confirmed at the next check-in; one the + client leaves unconfirmed (`id: null`) never is. Turn on *Auto check-in* for CodeArts under **Settings → Usage → Plugins**. ## Options @@ -100,18 +111,21 @@ magpie 里使用其 GLM、DeepSeek、openPangu 等模型。provider id:`codear > 这可能不符合华为云的服务条款,接口也可能随时变更。使用风险(包括账号受限)由使用者自行承担。 - **登录**:华为云 OAuth(PKCE + DPoP),本机 `127.0.0.1`(端口 ≥ 10000)接收回调,向 STS 换取临时 - AK/SK/security-token。完整凭据(含 refresh_token、PKCE verifier、DPoP 私钥)以 JSON 存在账号的 + AK/SK/security-token;回调只接受精确的 `/oauth/callback` GET,回调不带 code(portal 报错)时立即判定登录失败。完整凭据(含 refresh_token、PKCE verifier、DPoP 私钥)以 JSON 存在账号的 `access` 字段里,保存在 magpie / OpenCode 自己的账号存储中;过期前 30 分钟自动续期,请求遇到临时凭据 - 过期时就地续期并重发一次;账号标识取自 refresh_token,重复登录不会多出账号。 + 过期时就地续期并重发一次。同一账号的 refresh_token 只用一次;续期只是暂时失败(如 STS 连不上)时返回 + `503` 并保留登录,只有被 STS 明确拒绝才标记需要重新登录。账号标识取自 refresh_token,重复登录不会多出账号。 - **模型**:账号实时的内置模型列表;领取当日免费权益成功后,再加上免费模型(每个北京自然日领一次,与 - 客户端一致)。每个模型的「消耗系数」作为 magpie 的倍率上报,来自账号主智能体(`build`)的模型列表。 -- **请求**:SDK-HMAC-SHA256 签名;像客户端一样发送 `x-ot-session-id` 会话头(每账号一个会话),账号内 + 客户端一致;当天还没领取时遇到 `benefit not found` 也会先领取再重发)。每个模型的「消耗系数」作为 magpie 的倍率上报,来自账号主智能体(`build`)的模型列表。 +- **请求**:SDK-HMAC-SHA256 签名,只签给码道自己的两个主机(`snap-access.cn-north-4.myhuaweicloud.com`、 + `opengw.developer.huaweicloud.com`),发往其他地址(如改过的 `api`)的请求在凭据发出前就被拒绝,签名请求和令牌请求都不跟随重定向;像客户端一样发送 `x-ot-session-id` 会话头(每账号一个会话),账号内 在途请求不超过 3 个,`TM.00001041` 退避重试,网关排队时按客户端的方式等待;总是以流式请求上游(码道 只对流式回答计量积分),调用方要非流式时折叠回 JSON;默认注入 `thinking: { type: "enabled" }`,思考与 正文分开;200 里内嵌的错误换算为 `429` / `400` / `502` 并带厂商原话。 - **用量与签到**:总积分决定账号是否可用,其余积分桶只做明细;另有每日免费额度窗口。各批积分的到期 时间读自码道控制台同一批接口,读不到时退回插件的签到账本 `~/.config/magpie/codearts-checkins.json` - (这部分仍在用更多账号验证,请以控制台为准)。`auth.checkin` 与客户端「限时福利 → 每日领取」一致, + (这部分仍在用更多账号验证,请以控制台为准)。`auth.checkin` 与客户端「限时福利 → 每日领取」一致 + (插件领取后确认失败的,当天记在签到账本里,下次签到时补确认;客户端本就不确认的 `id: null` 领取不会被确认), 在 **设置 → 用量 → Plugins** 打开「每日自动签到」即可。 - **致谢**:原作者 [yuweihao17](https://github.com/yuweihao17/codearts);HuHong-Tao、ReachForStar 的 实测与实现;[Ebony-Vinyl/dsh-our-free-model](https://github.com/Ebony-Vinyl/dsh-our-free-model)。 diff --git a/packages/codearts/index.mjs b/packages/codearts/index.mjs index 6a753ee..92e7fff 100644 --- a/packages/codearts/index.mjs +++ b/packages/codearts/index.mjs @@ -59,17 +59,20 @@ const CHAT_API_BASE = "https://snap-access.cn-north-4.myhuaweicloud.com/api/v2" const SNAP_HOST = "https://snap-access.cn-north-4.myhuaweicloud.com" const SNAP_MODEL_BUILTIN_URL = `${SNAP_HOST}/v1/model/builtin` const SNAP_STATISTICS_URL = `${SNAP_HOST}/snap-manager/v1/statistics/plugin` -// The only hosts the account's credentials are signed for and sent to. -const HUAWEI_HOST = /(^|\.)(myhuaweicloud\.com|myhuaweicloud\.cn|huaweicloud\.com)$/i // opengw gateway config: the benefit/free-quota model set. -const OPENGW_GATEWAY_CONFIG_URL = "https://opengw.developer.huaweicloud.com/api/v1/gateway/config" +const OPENGW_HOST = "https://opengw.developer.huaweicloud.com" +const OPENGW_GATEWAY_CONFIG_URL = `${OPENGW_HOST}/api/v1/gateway/config` +// The only hosts the account's credentials are signed for and sent to: the +// two the plugin itself calls, by name. STS takes the refresh token, never a +// signature, and the portal only ever opens in the browser. +const SIGNED_HOSTS = new Set([SNAP_HOST, OPENGW_HOST].map((u) => new URL(u).host)) // The daily free token pool a `maas_type: benefit` chat draws on (never the // credit packages), so a free model's spend shows up in the usage panel. -const BENEFIT_BALANCE_URL = "https://opengw.developer.huaweicloud.com/api/v1/user/tokens/balance" +const BENEFIT_BALANCE_URL = `${OPENGW_HOST}/api/v1/user/tokens/balance` // The free models are the account's only once today's benefit is claimed: the // CodeArts agent POSTs this before it lists them (`claimBenefit`), and leaves // them out when it fails (4004 no benefit / expired, 4006 today's places gone). -const BENEFIT_CLAIM_URL = "https://opengw.developer.huaweicloud.com/api/v1/benefit/claim" +const BENEFIT_CLAIM_URL = `${OPENGW_HOST}/api/v1/benefit/claim` const BENEFIT_OK = "0000" // The agent's own model list, with each model's credit rate (`credit[]. // ratio_display`, shown as "1.50x") and its parameters: the CodeAgent's detail. @@ -513,6 +516,8 @@ async function requestToken(body, keyPair, fetcher) { method: "POST", headers: { DPoP: dpop, "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body).toString(), + // A 307/308 would send the refresh token and verifier on with the body. + redirect: "error", signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS), }) } catch (e) { @@ -616,23 +621,26 @@ const buildPortalLoginResultUrl = (ok) => /** * Start the loopback callback server, listening on 127.0.0.1:port>=10000. It - * takes one thing: a GET to the callback path with the authorization code, - * which it exchanges at STS (PKCE + DPoP), then sends the browser on to the - * portal's own result page. The redirect target is always that page, never a - * parameter of the request. + * takes one thing: a GET to the callback path, exactly as sent, with the + * authorization code, which it exchanges at STS (PKCE + DPoP), then sends the + * browser on to the portal's own result page. A callback without a code ends + * the sign-in at once, with the portal's own words when it gave any. The + * redirect target is always that page, never a parameter of the request. */ -function startOAuthCallbackServer(ticketId, pkce, keyPair, fetcher) { +function startOAuthCallbackServer(pkce, keyPair, fetcher) { let resolveResult let rejectResult const result = new Promise((resolve, reject) => { resolveResult = resolve rejectResult = reject }) - let exchanging = false + let answered = false const server = createServer((request, response) => { - const url = new URL(request.url ?? "/", `http://127.0.0.1:${request.socket.localPort}`) - if (url.pathname !== REDIRECT_PATH) { + // The path as sent, not as a URL would normalise it (`/oauth/./callback`). + const raw = request.url ?? "/" + const query = raw.indexOf("?") + if ((query < 0 ? raw : raw.slice(0, query)) !== REDIRECT_PATH) { response.writeHead(404).end("Not found") return } @@ -640,17 +648,20 @@ function startOAuthCallbackServer(ticketId, pkce, keyPair, fetcher) { response.writeHead(405, { Allow: "GET" }).end("Method not allowed") return } - const code = url.searchParams.get("code") - if (!code) { - response.writeHead(400).end("Missing authorization code") - return - } - // One sign-in, one code: a second callback for the same flow is refused. - if (exchanging) { + // One sign-in, one callback: another one for the same flow is refused. + if (answered) { response.writeHead(409).end("This sign-in is already being completed") return } - exchanging = true + answered = true + const url = new URL(raw, `http://127.0.0.1:${request.socket.localPort}`) + const code = url.searchParams.get("code") + if (!code) { + response.writeHead(307, { Location: buildPortalLoginResultUrl(false) }).end() + const said = firstOf(url.searchParams.get("error_description"), url.searchParams.get("error")) + rejectResult(new Error(`CodeArts sign-in failed: ${said || "the callback came back without an authorization code"}`)) + return + } const port = request.socket.localPort ?? 0 void exchangeAuthorizationCode(code, pkce.codeVerifier, port, keyPair, fetcher).then( (token) => { @@ -668,19 +679,31 @@ function startOAuthCallbackServer(ticketId, pkce, keyPair, fetcher) { return listenOnCallbackPort(server).then((port) => ({ port, server, result })) } -/** Listen on 127.0.0.1, retrying with a random port >= 10000 if needed. */ +const CALLBACK_PORT_TRIES = 20 +const randomCallbackPort = () => Math.floor(Math.random() * (65_536 - MIN_CALLBACK_PORT)) + MIN_CALLBACK_PORT + +/** + * Listen on 127.0.0.1: the port the system gives, or, when that is below + * 10000, a random one >= 10000, another while the one picked is taken. + */ function listenOnCallbackPort(server) { return new Promise((resolve, reject) => { + let tries = 0 const tryListen = (port) => { - server.once("error", reject) + const failed = (e) => { + if (port !== 0 && e?.code === "EADDRINUSE" && ++tries < CALLBACK_PORT_TRIES) tryListen(randomCallbackPort()) + else reject(e) + } + server.once("error", failed) server.listen(port, "127.0.0.1", () => { + server.off("error", failed) const address = server.address() const assigned = typeof address === "object" && address ? address.port : 0 if (assigned >= MIN_CALLBACK_PORT) { resolve(assigned) return } - server.close(() => tryListen(Math.floor(Math.random() * (65_536 - MIN_CALLBACK_PORT)) + MIN_CALLBACK_PORT)) + server.close(() => tryListen(randomCallbackPort())) }) } tryListen(0) @@ -693,11 +716,12 @@ function listenOnCallbackPort(server) { * the callback server is closed as soon as the result settles. */ async function startOAuthFlow(fetcher) { - const ticketId = randomHex(32) const pkce = await generatePkcePair() const keyPair = await generateDpopKeyPair() - const { port, server, result } = await startOAuthCallbackServer(ticketId, pkce, keyPair, fetcher) - const loginUrl = buildOAuthLoginUrl(port, pkce, ticketId) + const { port, server, result } = await startOAuthCallbackServer(pkce, keyPair, fetcher) + // The authorize URL carries a ticket_id as the IDE's does; the code flow + // itself never reads it back. + const loginUrl = buildOAuthLoginUrl(port, pkce, randomHex(32)) let closed = false const close = async () => { @@ -811,7 +835,8 @@ function parseSseEvents(text) { /** The error code an answer carries (`TM.00001041`, `InferHub.4291.200`, …), or "". */ function errorCodeOf(text) { - const m = /"(?:error_code|code)"\s*:\s*"([A-Za-z]*\.?[0-9][0-9A-Za-z.]*)"/.exec(String(text ?? "")) + // Any number of named parts before the digits: `InferHub.ModelArts.81111.429`. + const m = /"(?:error_code|code)"\s*:\s*"((?:[A-Za-z]+\.)*[A-Za-z]*[0-9][0-9A-Za-z.]*)"/.exec(String(text ?? "")) return m ? m[1] : "" } @@ -870,7 +895,9 @@ function classifyHead(text, done) { const code = errorCodeOf(text) // Wait for the error event's end, so its message is whole. if (code) return done || /\n/.test(text.slice(text.indexOf(code))) ? code : undefined - if (done || text.includes("[DONE]")) return "answer" + // The stream's own end, never a "[DONE]" inside an event: the gateway's + // rate-limit error carries `"text":"[DONE]"`. + if (done || /^data:\s*\[DONE\]\s*$/m.test(text)) return "answer" return undefined } @@ -1013,6 +1040,16 @@ function signInExpiredResponse(text) { return new Response(body, { status: 401, headers: { "content-type": "application/json", "X-Magpie-Sign-In": "expired" } }) } +/** + * A stale credential that couldn't be renewed: turned away for good, a 401 + * that marks the sign-in; or only for now (STS unreachable, a DPoP proof + * refused), a 503 that keeps it, for magpie to try again or fail over. + */ +function unrenewedResponse(context, text) { + if (context.signInDead?.()) return signInExpiredResponse(text) + return errorResponse(503, errorCodeOf(text), "临时凭据已过期,续期暂时失败,请稍后再试", { "X-Magpie-Sign-In": "kept" }) +} + /** Rebuild a response whose body was read, keeping the vendor's answer. */ function rebuildResponse(res, text, extraHeaders = {}) { const headers = streamHeaders(res.headers) @@ -1110,16 +1147,15 @@ function queueInfoOf(headers) { /** One signed call on a queued trace: GET is where it stands, DELETE takes it out. */ async function traceQueueCall(method, cred, traceId, context, signal) { const url = TRACE_QUEUE_URL(traceId) - const signed = await signRequestHuawei( - cred.access_key_id, cred.secret_access_key, cred.security_token, - method, url, new Uint8Array(), - ) - const headers = new Headers() - signed.forEach((value, key) => { - if (key !== "host") headers.set(key, value) - }) + const headers = await signFor(cred, method, url, new Uint8Array()) headers.set(SESSION_HEADER, context.sessionId) - return context.fetcher(url, { method, headers, ...(signal ? { signal } : {}) }) + return context.fetcher(url, { method, headers, signal, redirect: "error" }) +} + +/** The caller's signal, bounded to `ms` from now: a call that hangs can't outlast the wait it is part of. */ +function withinMs(signal, ms) { + const timeout = AbortSignal.timeout(Math.max(0, Math.min(ms, REQUEST_TIMEOUT_MS))) + return signal ? AbortSignal.any([signal, timeout]) : timeout } /** @@ -1129,7 +1165,7 @@ async function traceQueueCall(method, cred, traceId, context, signal) { * Gives "promoted" or "gone"; throws the abort. */ async function waitInQueue(cred, queued, context, signal, deadline) { - const leave = () => void traceQueueCall("DELETE", cred, queued.traceId, context).catch(() => {}) + const leave = () => void traceQueueCall("DELETE", cred, queued.traceId, context, AbortSignal.timeout(REQUEST_TIMEOUT_MS)).catch(() => {}) let retryAfter = queued.retryAfter let failures = 0 try { @@ -1141,12 +1177,16 @@ async function waitInQueue(cred, queued, context, signal, deadline) { await delay(retryAfter * 1000, signal) let body = null try { - const res = await traceQueueCall("GET", cred, queued.traceId, context, signal) + // The poll and its answer are bounded by what is left of the wait. + const res = await traceQueueCall("GET", cred, queued.traceId, context, withinMs(signal, deadline - Date.now())) body = safeJson(await res.text()) if (!res.ok && !body?.status) throw new Error(`HTTP ${res.status}`) } catch (e) { if (signal?.aborted) throw e - if (++failures >= 3) return "gone" + if (++failures >= 3) { + leave() + return "gone" + } continue } const status = String(body?.status ?? "queued") @@ -1169,16 +1209,39 @@ function hostOf(url) { } } -/** Is this an https URL on one of Huawei Cloud's hosts, the only ones the credentials go to? */ -function isHuaweiUrl(url) { +/** Is this an https URL on one of SIGNED_HOSTS (its default port), the only ones the credentials go to? */ +function isSignedHostUrl(url) { try { const u = new URL(url) - return u.protocol === "https:" && HUAWEI_HOST.test(u.hostname) + return u.protocol === "https:" && SIGNED_HOSTS.has(u.host) } catch { return false } } +const refusalTo = (url) => + `refusing to sign a request to ${hostOf(url) || "an unknown host"}: only CodeArts' own hosts (${[...SIGNED_HOSTS].join(", ")}) get the account's credentials` + +/** + * The SDK-HMAC-SHA256 headers for one request (all but `host`, which fetch + * sets), signed only for SIGNED_HOSTS: whichever route asks, now or added + * later, the account's credentials sign nothing else. Every signed call also + * goes with `redirect: "error"`: a redirect would forward the security token + * to wherever it points. + */ +async function signFor(cred, method, url, body, extraSigned) { + if (!isSignedHostUrl(url)) throw new Error(refusalTo(url)) + const signed = await signRequestHuawei( + cred.access_key_id, cred.secret_access_key, cred.security_token, + method, url, body, extraSigned, + ) + const headers = new Headers() + signed.forEach((value, key) => { + if (key !== "host") headers.set(key, value) + }) + return headers +} + /** Mark a 401/403 the way magpie reads a sign-in that is gone. */ function withSignInMark(res) { if (res.status !== 401 && res.status !== 403) return res @@ -1195,20 +1258,21 @@ function withSignInMark(res) { * a session frees or the budget runs out — then a 429, which magpie fails * over on; * - a stale credential (401, `APIG.0602`) is renewed once and the request sent - * again; when that can't be done, a 401 marks the sign-in; + * again; when STS turns the renewal away for good, a 401 marks the sign-in, + * and when it only fails for now, a 503 keeps it; + * - `benefit not found` on a day not yet claimed claims it and sends again; + * otherwise the model goes as the account's builtin one, if it has it; * - a 200 carrying only an error (a spent quota, an unknown model) becomes a * 429/502 with the vendor's words instead of an empty reply. * The permit is held until the answer's body ends: the gateway counts the - * session while it streams. Only Huawei Cloud hosts are signed for: a request + * session while it streams. Only SIGNED_HOSTS are signed for: a request * anywhere else (an overridden `api`, say) is refused before the access key or * security token leave. */ async function signedFetch(cred, input, init, context) { const req = typeof Request !== "undefined" && input instanceof Request ? input : null const url = req ? req.url : String(input) - if (!isHuaweiUrl(url)) { - return errorResponse(400, "", `refusing to sign a request to ${hostOf(url) || "an unknown host"}: only Huawei Cloud hosts get the account's credentials`) - } + if (!isSignedHostUrl(url)) return errorResponse(400, "", refusalTo(url)) const method = String(init?.method ?? req?.method ?? "GET").toUpperCase() const baseHeaders = new Headers(init?.headers ?? req?.headers) let body @@ -1225,14 +1289,11 @@ async function signedFetch(cred, input, init, context) { let active = cred const send = async () => { - const signed = await signRequestHuawei( - active.access_key_id, active.secret_access_key, active.security_token, - method, url, body, extra, - ) + const signed = await signFor(active, method, url, body, extra) const headers = new Headers(baseHeaders) - signed.forEach((value, key) => { - if (key !== "host") headers.set(key, value) - }) + // The body may have been reshaped: the transport counts it again. + headers.delete("content-length") + signed.forEach((value, key) => headers.set(key, value)) headers.set("Chat-Id", context.chatId) headers.set("Session-Id", context.sessionId) // The session headers the CodeArts agent sends: one session per account, @@ -1250,12 +1311,22 @@ async function signedFetch(cred, input, init, context) { headers, ...(body.length > 0 ? { body } : {}), ...(signal ? { signal } : {}), + // After the caller's init, so no caller turns it back on. + redirect: "error", }) } // A sign-in known to be beyond renewal never reaches the network again. if (context.signInDead?.()) return signInExpiredResponse() - if (!chat) return withSignInMark(await send()) + if (!chat) { + const res = await send() + if (res.status !== 401 || !context.renewCredential) return withSignInMark(res) + const text = await res.text().catch(() => "") + const next = await context.renewCredential(active) + if (!next) return unrenewedResponse(context, text) + active = next + return withSignInMark(await send()) + } const release = await context.gate.acquire(signal) let handedOver = false @@ -1263,6 +1334,7 @@ async function signedFetch(cred, input, init, context) { const clock = context.now ?? Date.now const started = clock() let renewed = false + let claimTried = false let queueDeadline = 0 for (let attempt = 0; ; attempt += 1) { const res = await send() @@ -1299,6 +1371,7 @@ async function signedFetch(cred, input, init, context) { active = next continue } + return unrenewedResponse(context, text) } return signInExpiredResponse(text) } @@ -1311,12 +1384,21 @@ async function signedFetch(cred, input, init, context) { body = utf8(JSON.stringify(chat.body)) continue } - // No free benefit for this model on this account (`4004`), or the header - // isn't taken for it (`4005`): it is the account's plain builtin model. - if (extra && /InferHub\.400[45]\.200|benefit not found/i.test(code || text) && isRegularModel(model, context.state)) { - context.state?.noBenefit.add(model) - extra = undefined - continue + if (extra && /InferHub\.400[45]\.200|benefit not found/i.test(code || text)) { + // A new Beijing day whose benefit isn't claimed yet: claim it, as the + // agent does each day, and send it again as the free model. + if (!claimTried && context.state && context.state.claim?.day !== beijingDay()) { + claimTried = true + if (await ensureBenefitClaimed(active, context.fetcher, context.state)) continue + } + // No free benefit for this model on this account (`4004`), or the + // header isn't taken for it (`4005`): it is the account's plain + // builtin model, till the next day's claim. + if (isRegularModel(model, context.state)) { + context.state?.noBenefit.add(model) + extra = undefined + continue + } } if (code === SESSION_LIMIT_ERROR || text.includes(SESSION_LIMIT_ERROR)) { const wait = retryDelayMs(attempt, context.retryDelays) @@ -1336,19 +1418,10 @@ async function signedFetch(cred, input, init, context) { /** A signed GET returning the response text, or undefined on any failure. */ async function signedGet(url, cred, fetcher, extraUnsignedHeaders) { - const signed = await signRequestHuawei( - cred.access_key_id, cred.secret_access_key, cred.security_token, - "GET", url, new Uint8Array(), - ) - const headers = new Headers() - signed.forEach((value, key) => { - if (key !== "host") headers.set(key, value) - }) - if (extraUnsignedHeaders !== undefined) { - for (const [k, v] of Object.entries(extraUnsignedHeaders)) headers.set(k, v) - } try { - const res = await fetcher(url, { method: "GET", headers, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }) + const headers = await signFor(cred, "GET", url, new Uint8Array()) + for (const [k, v] of Object.entries(extraUnsignedHeaders ?? {})) headers.set(k, v) + const res = await fetcher(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }) if (!res.ok) return undefined return await res.text() } catch { @@ -1375,19 +1448,13 @@ async function snapRequest(method, url, cred, fetcher, payload) { let res let text try { - const signed = await signRequestHuawei( - cred.access_key_id, cred.secret_access_key, cred.security_token, - method, url, body, - ) - const headers = new Headers() - signed.forEach((value, key) => { - if (key !== "host") headers.set(key, value) - }) + const headers = await signFor(cred, method, url, body) for (const [k, v] of Object.entries(SNAP_EXTRA_HEADERS)) headers.set(k, v) res = await fetcher(url, { method, headers, ...(payload === undefined ? {} : { body }), + redirect: "error", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), }) text = await res.text() @@ -1512,6 +1579,13 @@ function readGrants(file, account) { return Array.isArray(list) ? list : [] } +function writeLedger(file, all) { + fs.mkdirSync(path.dirname(file), { recursive: true }) + const tmp = `${file}.${process.pid}.tmp` + fs.writeFileSync(tmp, JSON.stringify(all, null, 2)) + fs.renameSync(tmp, file) +} + /** Keep one claim (one a Beijing day), dropping what lapsed long ago. */ function recordGrant(file, account, grant) { try { @@ -1521,10 +1595,35 @@ function recordGrant(file, account, grant) { const list = (Array.isArray(all[account]) ? all[account] : []) .filter((g) => (vendorDate(g.expiresAt) ?? 0) > keep && beijingDay(vendorDate(g.at) ?? 0) !== day) all[account] = [...list, grant] - fs.mkdirSync(path.dirname(file), { recursive: true }) - const tmp = `${file}.${process.pid}.tmp` - fs.writeFileSync(tmp, JSON.stringify(all, null, 2)) - fs.renameSync(tmp, file) + writeLedger(file, all) + } catch { + /* best effort */ + } +} + +// The claim this plugin made today whose confirm failed, per account: the +// next check-in confirms it, whichever magpie (or OpenCode) on this machine +// runs it. A claim the IDE leaves unconfirmed (`id: null`) is never kept +// here, so it is never confirmed. Kept for its Beijing day only. +const UNCONFIRMED = "_unconfirmed" + +/** Today's claim this plugin left unconfirmed for `account`, if any. */ +function readUnconfirmed(file, account) { + const left = asRecord(asRecord(readLedger(file)[UNCONFIRMED])[account]) + return left.day === beijingDay() ? left : undefined +} + +/** Keep the claim left unconfirmed for `account`, or with null drop it; other days' go. */ +function recordUnconfirmed(file, account, left) { + try { + const all = readLedger(file) + const today = beijingDay() + const kept = Object.fromEntries( + Object.entries(asRecord(all[UNCONFIRMED])).filter(([k, v]) => k !== account && asRecord(v).day === today), + ) + if (left) kept[account] = { ...left, day: today } + all[UNCONFIRMED] = kept + writeLedger(file, all) } catch { /* best effort */ } @@ -1544,18 +1643,32 @@ function grantExpiry(benefit, at) { * list the activities, claim the `USER_LOGIN` one with `{campaignId, channel}`, * and confirm it when the claim answers an id (`benefit.id !== null`), or the * credits stay pending. Answers magpie's check-in outcome; never throws. + * `unconfirmed` is today's claim this plugin left unconfirmed (the ledger's); + * an answer's own `unconfirmed` is one to keep there. */ -async function dailyCheckin(cred, fetcher) { +async function dailyCheckin(cred, fetcher, { unconfirmed } = {}) { const first = await dailyCampaign(cred, fetcher) if (first.error) return { outcome: "failed", message: first.error } const item = first.item if (!item) return { outcome: "inactive", message: "当前没有每日领取活动" } const credit = num(item.benefitAmount) + // Claimed here, but the confirm failed: confirm it now, or the credits stay + // pending. Only that claim: one the IDE leaves unconfirmed is `CLAIMED` as + // well, and the IDE never confirms it. When the confirm fails, only the + // activity tells whether it was confirmed after all; still claimed, it is a + // failure magpie tries again later that day. + const campaign = item.campaignId !== undefined && item.campaignId !== null && item.campaignId !== "" + const leftHere = unconfirmed && String(unconfirmed.campaignId) === String(item.campaignId) + if (!item.claimable && item.status === "CLAIMED" && campaign && leftHere) { + const confirmed = await snapRequest("POST", OPS_CONFIRM_URL, cred, fetcher, { campaignId: item.campaignId }) + if (confirmed.ok) return claimedOutcome(asRecord(unconfirmed.benefit), credit) + const again = await dailyCampaign(cred, fetcher) + if (isClaimedToday(again.item) && again.item.status !== "CLAIMED") return { outcome: "done", message: "今天已领取" } + return { outcome: "failed", message: `领取确认失败:${confirmed.message}` } + } if (isClaimedToday(item)) return { outcome: "done", message: "今天已领取" } if (!item.claimable) return { outcome: "ineligible", message: `当前不可领取(status=${item.status ?? "null"})` } - if (item.campaignId === undefined || item.campaignId === null || item.campaignId === "") { - return { outcome: "failed", message: "活动缺少 campaignId" } - } + if (!campaign) return { outcome: "failed", message: "活动缺少 campaignId" } const claimed = await snapRequest("POST", OPS_CLAIM_URL, cred, fetcher, { campaignId: item.campaignId, channel: OPS_CHANNEL }) if (!claimed.ok) { @@ -1567,8 +1680,15 @@ async function dailyCheckin(cred, fetcher) { const benefit = asRecord(claimed.data) if (claimed.data && benefit.id !== null) { const confirmed = await snapRequest("POST", OPS_CONFIRM_URL, cred, fetcher, { campaignId: item.campaignId }) - if (!confirmed.ok) return { outcome: "failed", message: `领取确认失败:${confirmed.message}` } + if (!confirmed.ok) { + return { outcome: "failed", message: `领取确认失败:${confirmed.message}`, unconfirmed: { campaignId: item.campaignId, benefit } } + } } + return claimedOutcome(benefit, credit) +} + +/** The outcome of a check-in that went through, with the grant the ledger keeps. */ +function claimedOutcome(benefit, credit) { const got = num(benefit.benefitAmount) || credit const at = Date.now() const grant = { at: new Date(at).toISOString(), credit: got, expiresAt: new Date(grantExpiry(benefit, at)).toISOString() } @@ -1618,16 +1738,9 @@ function extractArray(text, path) { async function claimBenefit(cred, fetcher) { const body = utf8("{}") try { - const signed = await signRequestHuawei( - cred.access_key_id, cred.secret_access_key, cred.security_token, - "POST", BENEFIT_CLAIM_URL, body, - ) - const headers = new Headers() - signed.forEach((value, key) => { - if (key !== "host") headers.set(key, value) - }) + const headers = await signFor(cred, "POST", BENEFIT_CLAIM_URL, body) headers.set("x-snap-traceid", randomHex(16)) - const res = await fetcher(BENEFIT_CLAIM_URL, { method: "POST", headers, body, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }) + const res = await fetcher(BENEFIT_CLAIM_URL, { method: "POST", headers, body, redirect: "error", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }) const data = safeJson(await res.text()) const code = firstOf(String(data?.error_code ?? "")) || `HTTP ${res.status}` return { ok: code === BENEFIT_OK, code, message: firstOf(data?.error_msg, data?.message) } @@ -1642,7 +1755,8 @@ const CLAIM_RETRY_MS = 60 * 60 * 1000 /** * Is today's free benefit the account's? Claimed once a Beijing day (one claim * at a time); a refusal is asked again an hour later, and a vendor that can't - * be reached leaves the last answer standing. + * be reached leaves the last answer standing. A claim that goes through starts + * the day afresh: the models the last one had no benefit for are asked again. */ function ensureBenefitClaimed(cred, fetcher, state) { const day = beijingDay() @@ -1652,6 +1766,7 @@ function ensureBenefitClaimed(cred, fetcher, state) { .then((r) => { if (r.network) return was?.ok ?? false state.claim = { day, ok: r.ok, at: Date.now(), code: r.code, message: r.message } + if (r.ok) state.noBenefit?.clear() return r.ok }) .finally(() => { state.claiming = null }) @@ -1956,18 +2071,44 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { // nothing else: the gate; its free models today (null until its // gateway/config was read; the fallback stands until then), its builtin // ones, and the ones the gateway said it has no benefit for; today's - // benefit claim; its main agent's id; its credit batches. + // benefit claim; its main agent's id; its credit batches; the renewal of its + // credential under way, and the last one made; today's check-in claim whose + // confirm failed. const accounts = new Map() const accountState = (key) => { if (!accounts.has(key)) { accounts.set(key, { gate: createConcurrencyGate(maxInflight), benefit: null, regular: null, noBenefit: new Set(), claim: null, claiming: null, agentId: "", batches: undefined, batchesAt: 0, + renewing: null, renewed: null, unconfirmed: null, }) } return accounts.get(key) } const stateOf = async (cred) => accountState((await accountSessionIds(cred)).sessionId) + + // One renewal per refresh token, whoever asks for it (each of the account's + // loaders, magpie's auth.refresh): STS spends a refresh token once, so a + // second use of it would turn the account away. Whoever comes later with + // the same token gets what that renewal gave. + const renewOnce = async (cred) => { + const token = firstOf(cred.refresh_token) + if (!token) return refreshCredential(cred, fetcher) + const state = await stateOf(cred) + if (state.renewed?.from === token) return state.renewed.next + if (state.renewing?.from !== token) { + const promise = refreshCredential(cred, fetcher) + .then((next) => { + state.renewed = { from: token, next } + return next + }) + .finally(() => { + if (state.renewing?.promise === promise) state.renewing = null + }) + state.renewing = { from: token, promise } + } + return state.renewing.promise + } // The ledger's key: the signer, which outlives a sign-in; else the session. const ledgerKey = async (cred) => accountIdentityOf(cred).id || (await accountSessionIds(cred)).sessionId @@ -2040,7 +2181,7 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { async refresh(auth) { const cred = credentialOf(auth) if (!cred) return undefined - const next = await refreshCredential(cred, fetcher) + const next = await renewOnce(cred) const accountId = auth.accountId ? "" : accountIdentityOf(next).id return { access: JSON.stringify(next), @@ -2058,32 +2199,41 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { // magpie renews ahead of expiry by itself; this covers hosts that // ignore `auth.refresh` (OpenCode) and a credential that went stale - // anyway (a 401 / APIG.0602). One renewal at a time; null when it fails. + // anyway (a 401 / APIG.0602). One renewal at a time, shared with the + // account's other loaders and auth.refresh; null when it fails. let refreshing = null let signInDead = false + // Another renewal may have landed already (magpie's own, or another + // process's): the stored one, when it is newer than `than`. + const takeStored = async (than) => { + const latest = await getAuth().catch(() => null) + const stored = credentialOf(latest) + if (!stored || !than(stored)) return { latest, stored: null } + cred = stored + account = latest + return { latest, stored } + } const renewCredential = (stale) => { if (signInDead) return Promise.resolve(null) refreshing ??= (async () => { - // Another renewal may have landed already (magpie's own, or another - // process): take that over rather than spend the refresh token twice. - const latest = await getAuth().catch(() => null) - const stored = credentialOf(latest) - if (stored && stored.access_key_id !== stale.access_key_id && !nearExpiry(stored)) { - cred = stored - account = latest - return stored - } - const base = stored ?? cred - if (!base.refresh_token) return null - const next = await refreshCredential(base, fetcher) - cred = next - account = await persistCredential(client, latest ?? account, next) - return next - })() - .catch((e) => { - if (isPermanentRefreshFailure(e)) signInDead = true + const first = await takeStored((s) => s.access_key_id !== stale.access_key_id && !nearExpiry(s)) + if (first.stored) return first.stored + const base = credentialOf(first.latest) ?? cred + try { + const next = await renewOnce(base) + cred = next + account = await persistCredential(client, first.latest ?? account, next) + return next + } catch (e) { + if (!isPermanentRefreshFailure(e)) return null + // The token was spent a moment ago by someone else: theirs stands. + const after = await takeStored((s) => !!s.refresh_token && s.refresh_token !== base.refresh_token) + if (after.stored) return after.stored + signInDead = true return null - }) + } + })() + .catch(() => null) .finally(() => { refreshing = null }) return refreshing } @@ -2157,12 +2307,29 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { async checkin(getAuth) { const cred = credentialOf(await getAuth()) if (!cred?.access_key_id) return { outcome: "failed", message: "not signed in" } - const { grant, ...r } = await dailyCheckin(cred, fetcher) + const key = await ledgerKey(cred) + const state = await stateOf(cred) + const today = beijingDay() + // The account's own memory first: the ledger is written best effort, + // and a write that failed mustn't lose the claim; the ledger carries it + // to another process, or past a restart. + const held = state.unconfirmed?.day === today ? state.unconfirmed : undefined + const left = held ?? readUnconfirmed(ledgerPath, key) + const { grant, unconfirmed, ...r } = await dailyCheckin(cred, fetcher, { unconfirmed: left }) + // A claim whose confirm failed is kept for the next check-in; one + // confirmed now, or found done, is dropped. + if (unconfirmed) { + state.unconfirmed = { ...unconfirmed, day: today } + recordUnconfirmed(ledgerPath, key, unconfirmed) + } else if (left && r.outcome !== "failed") { + state.unconfirmed = null + recordUnconfirmed(ledgerPath, key, null) + } if (r.outcome === "claimed") { // The new batch shows at the next usage read; the ledger keeps it in // case the vendor's batch list can't be read. - ;(await stateOf(cred)).batchesAt = 0 - if (grant) recordGrant(ledgerPath, await ledgerKey(cred), grant) + state.batchesAt = 0 + if (grant) recordGrant(ledgerPath, key, grant) } return r }, @@ -2249,11 +2416,11 @@ export const _internal = { requestToken, exchangeAuthorizationCode, exchangeRefreshToken, refreshCredential, isDeadRefreshToken, isPermanentRefreshFailure, nearExpiry, persistCredential, buildOAuthLoginUrl, buildPortalLoginResultUrl, - startOAuthCallbackServer, listenOnCallbackPort, startOAuthFlow, isHuaweiUrl, hostOf, + startOAuthCallbackServer, listenOnCallbackPort, startOAuthFlow, isSignedHostUrl, hostOf, SIGNED_HOSTS, signFor, traceQueueCall, BENEFIT_CLAIM_URL, AGENT_LIST_URL, AGENT_DETAIL_URL, CODE_AGENT_ID, canonicalQuery, beijingDay, nextBeijingMidnight, vendorDate, creditRateOf, claimBenefit, ensureBenefitClaimed, parseAgentModel, fetchAgentModels, - readGrants, recordGrant, grantExpiry, grantBatches, soonestLapse, fetchCreditBatches, + readGrants, recordGrant, readUnconfirmed, recordUnconfirmed, grantExpiry, grantBatches, soonestLapse, fetchCreditBatches, PACKAGE_CREDIT_PAGE_URL, OPS_CREDIT_OVERVIEW_URL, OPS_CREDIT_CAMPAIGN_URL, toBytes, isBenefitModel, prepareChatBody, signedFetch, signedGet, parseSseEvents, errorCodeOf, errorMessageOf, isStaleCredential, isRateLimitCode, embeddedErrorStatus, classifyHead, diff --git a/packages/codearts/index.test.mjs b/packages/codearts/index.test.mjs index 3ed924e..4ed6c72 100644 --- a/packages/codearts/index.test.mjs +++ b/packages/codearts/index.test.mjs @@ -7,6 +7,8 @@ import test from "node:test" import assert from "node:assert/strict" import fs from "node:fs" +import http from "node:http" +import net from "node:net" import os from "node:os" import path from "node:path" @@ -211,6 +213,9 @@ test("prepareChatBody reshapes a chat into what the gateway accepts and meters", assert.equal(x.prepareChatBody(null), null) }) +// The free model's TPM limit, word for word as the gateway sent it in a 200. +const tpmEvent = 'data:{"text":"[DONE]","error_code":"InferHub.ModelArts.81111.429","error_msg":"The model TPM limit has been significantly exceeded. Please reduce the request rate and retry later."}' + test("classifyHead tells an answer from an embedded error", () => { const role = `data: ${JSON.stringify({ choices: [{ delta: { role: "assistant" } }] })}\n\n` const content = `data: ${JSON.stringify({ choices: [{ delta: { content: "hi" } }] })}\n\n` @@ -221,12 +226,22 @@ test("classifyHead tells an answer from an embedded error", () => { assert.equal(x.classifyHead(`data: {"error_code":"TM.00001041"`, false), undefined) // not whole yet assert.equal(x.classifyHead("", true), "answer") assert.equal(x.classifyHead(JSON.stringify({ choices: [{ message: { content: "x" } }] }), true), "answer") + // The free model's TPM limit, as the gateway sends it: no space after + // `data:`, a code of several parts, and a "[DONE]" that is no end. + assert.equal(x.classifyHead(`${tpmEvent}\n\n`, false), "InferHub.ModelArts.81111.429") + assert.equal(x.classifyHead(`data: ${JSON.stringify({ text: "[DONE]" })}\n\n`, false), undefined) + assert.equal(x.classifyHead(role + "data: [DONE]\n\n", false), "answer") }) test("errorCodeOf / errorMessageOf / isRateLimitCode read the gateway's errors", () => { const text = '{"error_code":"InferHub.4291.200","error_msg":"insufficient \\"quota\\""}' assert.equal(x.errorCodeOf(text), "InferHub.4291.200") assert.equal(x.errorMessageOf(text), 'insufficient "quota"') + for (const code of ["InferHub.ModelArts.81111.429", "TM.00001041", "APIG.0602", "81114.429", "STS5.1806"]) { + assert.equal(x.errorCodeOf(`{"error_code":"${code}"}`), code) + } + assert.equal(x.errorCodeOf('{"code":"build"}'), "", "a word is no code") + assert.equal(x.isRateLimitCode("InferHub.ModelArts.81111.429"), true) assert.equal(x.isRateLimitCode("InferHub.4291.200"), true) assert.equal(x.isRateLimitCode("81111.429"), true) assert.equal(x.isRateLimitCode("InferHub.002002009.404"), false) @@ -555,7 +570,7 @@ test("fetchRemoteModels merges both endpoints, filters VL, and keeps the publish test("signedGet returns undefined on a non-2xx response", async () => { const fetcher = async () => new Response("nope", { status: 401 }) - const text = await x.signedGet("https://example.com/x", { access_key_id: "AK", secret_access_key: "SK", security_token: "ST" }, fetcher) + const text = await x.signedGet(x.SNAP_MODEL_BUILTIN_URL, { access_key_id: "AK", secret_access_key: "SK", security_token: "ST" }, fetcher) assert.equal(text, undefined) }) @@ -776,6 +791,19 @@ test("an error inside a 200 becomes a status magpie acts on, with the vendor's w assert.equal(body.error.message.startsWith("CodeArts"), false, "magpie adds the provider name itself") }) +test("the free model's TPM limit inside a 200 is a 429 magpie fails over on, not an empty reply", async () => { + const cred = await makeCred() + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => sseResponse(`${tpmEvent}\n\n`) }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + for (const stream of [true, false]) { + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "deepseek-v4.1-flash", messages: [{ role: "user", content: "你好" }], stream })) + assert.equal(res.status, 429) + const body = await res.json() + assert.equal(body.error.code, "InferHub.ModelArts.81111.429") + assert.match(body.error.message, /TPM limit/) + } +}) + test("embeddedErrorStatus sorts the gateway's codes into what magpie acts on", () => { assert.equal(x.embeddedErrorStatus("InferHub.4291.200"), 429) assert.equal(x.embeddedErrorStatus("81114.429"), 429) @@ -950,6 +978,68 @@ test("giving up in the queue takes the request out of it", async () => { assert.deepEqual(calls.map((c) => c[0]), ["POST", "DELETE"]) }) +test("a queue poll that hangs can't outlast the wait: the request leaves the queue, a 429", async () => { + const cred = await makeCred() + const calls = [] + let deleted + const sawDelete = new Promise((r) => { deleted = r }) + const fetcher = async (url, init) => { + calls.push(init.method) + if (init.method === "DELETE") { + deleted() + return new Response("{}", { status: 200 }) + } + if (String(url) === x.TRACE_QUEUE_URL("T3")) { + // The poll never answers: only its signal ends it (without one, never), + // at once when it ended while the request was signed, as fetch does. + // Its open socket is what keeps a real process alive meanwhile: an + // AbortSignal.timeout alone doesn't, in node or bun. + return new Promise((_, reject) => { + if (init.signal?.aborted) return reject(init.signal.reason) + const socket = setInterval(() => {}, 1_000) + init.signal?.addEventListener("abort", () => { + clearInterval(socket) + reject(init.signal.reason) + }) + }) + } + return new Response("{}", { status: 429, headers: { "queue-status": "queued", "trace-id": "T3", "retry-after": "0" } }) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher, queueBudgetMs: 200 }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] })) + assert.equal(res.status, 429) + await sawDelete + assert.equal(calls[0], "POST") + assert.equal(calls.at(-1), "DELETE") + assert.ok(calls.slice(1, -1).length >= 1 && calls.slice(1, -1).every((m) => m === "GET")) +}) + +test("three failed polls take the request out of the queue before the 429", async () => { + const cred = await makeCred() + const calls = [] + let deleted + const sawDelete = new Promise((r) => { deleted = r }) + const fetcher = async (url, init) => { + calls.push(init.method) + if (init.method === "DELETE") { + deleted() + return new Response("{}", { status: 200 }) + } + if (String(url) === x.TRACE_QUEUE_URL("T4")) return new Response("busy", { status: 503 }) + return new Response("{}", { status: 429, headers: { "queue-status": "queued", "trace-id": "T4", "retry-after": "0" } }) + } + // A budget the polls can't run out: it is the failures that end the wait. + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher, queueBudgetMs: 60_000 }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] })) + assert.equal(res.status, 429) + // The DELETE is sent in the background, after it signs: wait for it, with a + // bound so a missing one fails here rather than at the runner's timeout. + await Promise.race([sawDelete, new Promise((r) => setTimeout(r, 2_000))]) + assert.deepEqual(calls, ["POST", "GET", "GET", "GET", "DELETE"]) +}) + test("a 429 that is no queue passes through for magpie to fail over", async () => { const cred = await makeCred() const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => new Response('{"error_code":"81111.429"}', { status: 429 }) }) @@ -1086,15 +1176,81 @@ test("a 403 is a sign-in the account no longer has, on chats and other requests assert.equal(calls, 2, "a 403 is not retried") }) -test("isHuaweiUrl takes only https URLs on Huawei Cloud's own hosts", () => { - assert.equal(x.isHuaweiUrl(CHAT_URL), true) - assert.equal(x.isHuaweiUrl("https://codearts.huaweicloud.com/x"), true) - assert.equal(x.isHuaweiUrl("https://iam.myhuaweicloud.cn/v3"), true) - assert.equal(x.isHuaweiUrl("http://snap-access.cn-north-4.myhuaweicloud.com/api"), false, "not over plain http") - assert.equal(x.isHuaweiUrl("https://myhuaweicloud.com.example.com/"), false) - assert.equal(x.isHuaweiUrl("https://evilmyhuaweicloud.com/"), false) - assert.equal(x.isHuaweiUrl("https://example.com/?u=myhuaweicloud.com"), false) - assert.equal(x.isHuaweiUrl("not a url"), false) +test("isSignedHostUrl takes only https URLs on the two hosts the plugin calls, by name", () => { + assert.deepEqual([...x.SIGNED_HOSTS].sort(), ["opengw.developer.huaweicloud.com", "snap-access.cn-north-4.myhuaweicloud.com"]) + assert.equal(x.isSignedHostUrl(CHAT_URL), true) + assert.equal(x.isSignedHostUrl(x.BENEFIT_CLAIM_URL), true) + assert.equal(x.isSignedHostUrl("https://SNAP-ACCESS.cn-north-4.myhuaweicloud.com/api/v2/chat/completions"), true, "a hostname has no case") + // Other Huawei Cloud hosts don't get the account's signature either. + for (const other of ["https://codearts.huaweicloud.com/x", "https://iam.myhuaweicloud.cn/v3", "https://sts.cn-north-4.myhuaweicloud.com/v1/oauth2/tokens", "https://snap-access.cn-south-1.myhuaweicloud.com/api"]) { + assert.equal(x.isSignedHostUrl(other), false, other) + } + assert.equal(x.isSignedHostUrl("http://snap-access.cn-north-4.myhuaweicloud.com/api"), false, "not over plain http") + assert.equal(x.isSignedHostUrl("https://snap-access.cn-north-4.myhuaweicloud.com:8443/api"), false, "not on another port") + assert.equal(x.isSignedHostUrl("https://snap-access.cn-north-4.myhuaweicloud.com.example.com/"), false) + assert.equal(x.isSignedHostUrl("https://example.com/?u=snap-access.cn-north-4.myhuaweicloud.com"), false) + assert.equal(x.isSignedHostUrl("not a url"), false) +}) + +test("signFor signs only for the two hosts, whichever route asks", async () => { + const signed = await x.signFor(signedCred, "GET", x.SNAP_MODEL_BUILTIN_URL, new Uint8Array()) + assert.match(signed.get("authorization"), /^SDK-HMAC-SHA256 Access=AK,/) + assert.equal(signed.get("host"), null, "fetch sets the host") + await assert.rejects(x.signFor(signedCred, "GET", "https://example.com/x", new Uint8Array()), /refusing to sign a request to example\.com/) + // A route that signs for another host gets nothing out, and never calls. + let called = false + const never = async () => { called = true; return new Response("{}") } + assert.equal(await x.signedGet("https://example.com/x", signedCred, never), undefined) + assert.equal((await x.snapRequest("POST", "https://example.com/x", signedCred, never, {})).ok, false) + assert.equal(called, false) +}) + +test("a 3xx is never followed: whatever the route, the credentials stay on the two hosts", async () => { + // Where a redirect would send them, and a stand-in for CodeArts that sends + // every request there. + const reached = [] + const elsewhere = http.createServer((req, res) => { + reached.push(req.headers) + res.end("{}") + }) + await new Promise((r) => elsewhere.listen(0, "127.0.0.1", r)) + const gateway = http.createServer((req, res) => { + res.writeHead(307, { Location: `http://127.0.0.1:${elsewhere.address().port}/stolen` }).end() + }) + await new Promise((r) => gateway.listen(0, "127.0.0.1", r)) + // The plugin's calls go to the stand-in through the real fetch, with the + // init the plugin gave them. + const calls = [] + const fetcher = (url, init) => { + calls.push([String(url), init?.redirect]) + const u = new URL(url) + return fetch(`http://127.0.0.1:${gateway.address().port}${u.pathname}${u.search}`, init) + } + try { + const cred = await makeCred() + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher, ledgerPath: path.join(ledgerDir, "redirect.json") }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + // A chat, even one whose caller asks to follow, and a request that isn't one. + await assert.rejects(loaded.fetch(CHAT_URL, { ...chatInit({ model: "GLM-5.2", messages: [] }), redirect: "follow" })) + await assert.rejects(loaded.fetch(x.SNAP_MODEL_BUILTIN_URL, { method: "GET" })) + // The model list, usage, the check-in, the benefit claim, a queue poll, a token request. + await plugin.provider.models({ models: {} }, { auth: makeAuth(cred) }) + await plugin.auth.usage(async () => makeAuth(cred)) + await plugin.auth.checkin(async () => makeAuth(cred)) + assert.equal((await x.claimBenefit(cred, fetcher)).ok, false) + await assert.rejects(x.traceQueueCall("GET", cred, "T", { sessionId: "s", fetcher })) + await assert.rejects(x.refreshCredential(cred, fetcher)) + assert.equal(reached.length, 0, "nothing reached the host a redirect pointed at") + for (const url of [CHAT_URL, x.SNAP_MODEL_BUILTIN_URL, x.OPENGW_GATEWAY_CONFIG_URL, x.SNAP_STATISTICS_URL, x.OPS_DELIVERY_URL, x.BENEFIT_CLAIM_URL, x.TRACE_QUEUE_URL("T"), x.STS_TOKEN_ENDPOINT]) { + assert.ok(calls.some(([u]) => u === url), `${url} was called`) + } + assert.deepEqual(calls.filter(([, redirect]) => redirect !== "error"), [], "every call goes with redirect: error") + } finally { + for (const s of [gateway, elsewhere]) { + s.closeAllConnections?.() + await new Promise((r) => s.close(r)) + } + } }) test("a request to any other host is refused before the credentials leave", async () => { @@ -1110,6 +1266,109 @@ test("a request to any other host is refused before the credentials leave", asyn assert.equal(calls, 0) }) +const staleBody = '{"error_code":"APIG.0602","error_msg":"the security token has expired"}' +const spentBody = JSON.stringify({ error_code: "STS5.1806", error_msg: "refresh token has been used" }) + +test("a renewal that fails only for now keeps the sign-in, and the next request renews again", async () => { + const cred = await makeCred() + let sts = 0 + const fetcher = async (url, init) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) { + sts += 1 + return sts === 1 ? new Response("upstream unavailable", { status: 503 }) : new Response(stsBody("AK2", "R2"), { status: 200 }) + } + return /Access=AK,/.test(new Headers(init.headers).get("authorization")) ? new Response(staleBody, { status: 401 }) : sseResponse(okStream) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const a = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] })) + assert.equal(a.status, 503) + assert.equal(a.headers.get("x-magpie-sign-in"), "kept") + const b = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [], stream: true })) + assert.equal(b.status, 200) + await b.text() + assert.equal(sts, 2) + + // A request that isn't a chat: the same. + const other = await CodeArtsAuthPlugin({ client: {} }, { + fetch: async (url) => (String(url) === x.STS_TOKEN_ENDPOINT ? new Response("", { status: 503 }) : new Response(staleBody, { status: 401 })), + }) + const res = await (await other.auth.loader(async () => makeAuth(cred))).fetch("https://snap-access.cn-north-4.myhuaweicloud.com/v1/model/builtin", { method: "GET" }) + assert.equal(res.status, 503) + assert.equal(res.headers.get("x-magpie-sign-in"), "kept") +}) + +test("two loaders of one account and magpie's own renewal spend its refresh token once", async () => { + const cred = await makeCred() + let sts = 0 + let release + const held = new Promise((r) => { release = r }) + const fetcher = async (url, init) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) { + sts += 1 + await held + // STS takes a refresh token once. + return sts === 1 ? new Response(stsBody("AK2", "R2"), { status: 200 }) : new Response(spentBody, { status: 400 }) + } + return /Access=AK,/.test(new Headers(init.headers).get("authorization")) ? new Response(staleBody, { status: 401 }) : sseResponse(okStream) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + // Nothing is stored meanwhile: every read gives the old record. + const getAuth = async () => makeAuth(cred) + const loaders = await Promise.all([plugin.auth.loader(getAuth), plugin.auth.loader(getAuth)]) + const answers = Promise.all(loaders.map((l) => l.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] })))) + const refreshed = plugin.auth.refresh(makeAuth(cred)) + while (sts < 1) await new Promise((r) => setTimeout(r, 5)) + await new Promise((r) => setTimeout(r, 20)) + release() + for (const res of await answers) { + assert.equal(res.status, 200) + assert.equal(res.headers.get("x-magpie-sign-in"), null) + } + assert.equal(JSON.parse((await refreshed).access).access_key_id, "AK2") + // One that comes later with the spent token gets what the renewal gave. + assert.equal(JSON.parse((await plugin.auth.refresh(makeAuth(cred))).access).access_key_id, "AK2") + assert.equal(sts, 1) +}) + +test("a refresh token spent a moment ago by someone else: their renewal is taken, the sign-in kept", async () => { + const cred = await makeCred() + const theirs = { ...cred, access_key_id: "AK3", secret_access_key: "SK3", security_token: "ST3", refresh_token: "R3" } + let stored = cred + const fetcher = async (url, init) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) { + stored = theirs // another process won the race and saved its renewal + return new Response(spentBody, { status: 400 }) + } + return /Access=AK,/.test(new Headers(init.headers).get("authorization")) ? new Response(staleBody, { status: 401 }) : sseResponse(okStream) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const loaded = await plugin.auth.loader(async () => makeAuth(stored)) + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [], stream: true })) + assert.equal(res.status, 200) + assert.equal(await res.text(), okStream) + const next = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [], stream: true })) + assert.equal(next.status, 200, "the account isn't marked") + await next.text() +}) + +test("a reshaped body goes without the caller's Content-Length", async () => { + const cred = await makeCred() + const seen = [] + const plugin = await CodeArtsAuthPlugin({ client: {} }, { + fetch: async (url, init) => { + seen.push({ length: new Headers(init.headers).get("content-length"), bytes: init.body.length }) + return sseResponse(okStream) + }, + }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const body = JSON.stringify({ model: "codearts/GLM-5.2", messages: [] }) + const headers = { "content-type": "application/json", "content-length": String(body.length) } + await (await loaded.fetch(CHAT_URL, { method: "POST", headers, body })).text() + assert.equal(seen[0].length, null) + assert.notEqual(seen[0].bytes, body.length, "the body was reshaped") +}) + test("requestToken reads a spent refresh token as a sign-in gone for good", async () => { const keyPair = await x.generateDpopKeyPair() const fetcher = async () => new Response(JSON.stringify({ error_code: "STS5.1806", error_msg: "refresh token has been used" }), { status: 400 }) @@ -1381,6 +1640,44 @@ test("a benefit the account can't claim: no free models, and no benefit header", assert.deepEqual(sent, [null]) }) +test("benefit not found on a day not yet claimed claims it, and sends the free model again", async () => { + const state = { + benefit: new Set(["deepseek-v4.1-flash"]), regular: new Set(["deepseek-v4.1-flash"]), noBenefit: new Set(), + claim: { day: "2000-01-01", ok: true, at: 0 }, claiming: null, + } + const sent = [] + let claims = 0 + const fetcher = async (url, init) => { + if (String(url) === x.BENEFIT_CLAIM_URL) { + claims += 1 + return new Response('{"error_code":"0000"}', { status: 200 }) + } + const benefit = new Headers(init.headers).get("maas_type") + sent.push(benefit) + // Yesterday's benefit is spent: only today's claim brings it back. + return benefit && !claims ? sseResponse(sse({ error_code: "InferHub.4004.200", error_msg: "benefit not found" })) : sseResponse(okStream) + } + const context = { ...(await x.accountSessionIds(signedCred)), gate: x.createConcurrencyGate(3), state, fetcher } + const res = await x.signedFetch(signedCred, CHAT_URL, chatInit({ model: "deepseek-v4.1-flash", messages: [] }), context) + assert.equal(res.status, 200) + assert.equal((await res.json()).choices[0].message.content, "你好") + assert.deepEqual(sent, ["benefit", "benefit"]) + assert.equal(claims, 1) + assert.equal(state.claim.day, x.beijingDay()) + assert.equal(state.noBenefit.size, 0) +}) + +test("a day's claim asks again about the models the last day had no benefit for", async () => { + const state = { noBenefit: new Set(["deepseek-v4.1-flash"]), claim: { day: "2000-01-01", ok: true, at: 0 } } + const claimed = async () => new Response('{"error_code":"0000"}', { status: 200 }) + assert.equal(await x.ensureBenefitClaimed(signedCred, claimed, state), true) + assert.equal(state.noBenefit.size, 0) + // A refused claim leaves them as they were. + const refused = { noBenefit: new Set(["deepseek-v4.1-flash"]), claim: null } + assert.equal(await x.ensureBenefitClaimed(signedCred, async () => new Response('{"error_code":"4004"}', { status: 200 }), refused), false) + assert.equal(refused.noBenefit.size, 1) +}) + test("ensureBenefitClaimed claims once a day and asks again only an hour after a refusal", async () => { const cred = await makeCred() let claims = 0 @@ -1541,9 +1838,123 @@ test("checkin skips the confirm when the claim answers no id", async () => { assert.equal(calls.some((c) => c.url === x.OPS_CONFIRM_URL), false) }) +test("checkin confirms the claim it left unconfirmed, and tries again later when the confirm fails", async () => { + const cred = await makeCred() + // The first try: the claim goes through, the confirm doesn't; the answer + // says what to keep for the next check-in. + const s = { item: daily() } + const { unconfirmed, ...first } = await x.dailyCheckin(cred, opsFetcher(s, { confirm: () => new Response("", { status: 502 }) }).fetcher) + assert.deepEqual(first, { outcome: "failed", message: "领取确认失败:HTTP 502" }) + assert.deepEqual(unconfirmed, { campaignId: 1, benefit: { id: 42, benefitAmount: 1000 } }) + assert.equal(s.item.status, "CLAIMED") + // Later that day, told what it left: it is confirmed now, not taken as done. + const { fetcher, calls } = opsFetcher(s) + const { grant, ...again } = await x.dailyCheckin(cred, fetcher, { unconfirmed }) + assert.deepEqual(again, { outcome: "claimed", credit: 1000, message: "+1000 积分" }) + assert.equal(grant.credit, 1000) + assert.deepEqual(calls.map((c) => [c.method, c.url]), [["GET", x.OPS_DELIVERY_URL], ["POST", x.OPS_CONFIRM_URL]]) + assert.deepEqual(calls[1].body, { campaignId: 1 }) + assert.equal((await x.dailyCheckin(cred, fetcher, { unconfirmed })).outcome, "done") + // A claimed activity it didn't leave unconfirmed, or another campaign's, is + // done, and nothing is confirmed: the IDE leaves `id: null` claims so. + for (const left of [undefined, { campaignId: 9 }]) { + const notOurs = opsFetcher({ item: daily({ claimable: false, status: "CLAIMED" }) }) + assert.equal((await x.dailyCheckin(cred, notOurs.fetcher, { unconfirmed: left })).outcome, "done") + assert.deepEqual(notOurs.calls.map((c) => c.url), [x.OPS_DELIVERY_URL]) + } + // A confirm the vendor turns down while the activity is still only claimed + // (活动太火爆, a code in a 200, as much as a 503): a failure, tried again later. + const busy = () => new Response(JSON.stringify({ code: 500, message: "活动太火爆" }), { status: 200 }) + for (const confirm of [busy, () => new Response("", { status: 503 })]) { + const still = opsFetcher({ item: daily({ claimable: false, status: "CLAIMED" }) }, { confirm }) + const r = await x.dailyCheckin(cred, still.fetcher, { unconfirmed }) + assert.equal(r.outcome, "failed") + assert.match(r.message, /^领取确认失败:/) + assert.deepEqual(still.calls.map((c) => c.method), ["GET", "POST", "GET"], "the activity is looked at again") + } + // Turned down because it was confirmed meanwhile (the IDE): done. + const elsewhere = (st) => { + st.item = { ...st.item, status: "CONFIRMED" } + return new Response(JSON.stringify({ code: 1002, message: "already confirmed" }), { status: 200 }) + } + const meanwhile = opsFetcher({ item: daily({ claimable: false, status: "CLAIMED" }) }, { confirm: elsewhere }) + assert.equal((await x.dailyCheckin(cred, meanwhile.fetcher, { unconfirmed })).outcome, "done") +}) + +test("a failed confirm is still made by the next check-in when the ledger can't be written", async () => { + const cred = await makeCred() + // A ledger under a file, not a folder: every write to it fails. + const blocker = path.join(ledgerDir, "not-a-folder") + fs.writeFileSync(blocker, "") + const ledgerPath = path.join(blocker, "ledger.json") + let confirms = 0 + const ops = opsFetcher({ item: daily() }, { + confirm: (st) => { + confirms += 1 + if (confirms === 1) return new Response("", { status: 502 }) + st.item = { ...st.item, status: "CONFIRMED" } + return new Response(JSON.stringify({ code: 0, data: null }), { status: 200 }) + }, + }) + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: ops.fetcher, ledgerPath }) + assert.equal((await plugin.auth.checkin(async () => makeAuth(cred))).outcome, "failed") + assert.equal(fs.existsSync(ledgerPath), false) + assert.equal((await plugin.auth.checkin(async () => makeAuth(cred))).outcome, "claimed") + assert.equal(confirms, 2) + assert.equal((await plugin.auth.checkin(async () => makeAuth(cred))).outcome, "done") + assert.equal(confirms, 2) +}) + +test("a claim answering no id is never confirmed, however many check-ins follow it", async () => { + const cred = await makeCred() + const ledgerPath = path.join(ledgerDir, "no-id.json") + const ops = opsFetcher({ item: daily() }, { + claim: (st) => { + st.item = { ...st.item, claimable: false, status: "CLAIMED" } // as the IDE's id-less claim leaves it + return new Response(JSON.stringify({ code: 0, data: { id: null, benefitAmount: 1000 } }), { status: 200 }) + }, + }) + const outcomes = [] + // A second magpie, a restart, OpenCode: each a plugin of its own. + for (let i = 0; i < 3; i++) { + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: ops.fetcher, ledgerPath }) + outcomes.push((await plugin.auth.checkin(async () => makeAuth(cred))).outcome) + } + assert.deepEqual(outcomes, ["claimed", "done", "done"]) + assert.equal(ops.calls.filter((c) => c.url === x.OPS_CONFIRM_URL).length, 0, "no confirm the IDE wouldn't send") + const [grants] = Object.entries(JSON.parse(fs.readFileSync(ledgerPath, "utf8"))).filter(([k]) => !k.startsWith("_")).map(([, v]) => v) + assert.equal(grants.length, 1, "one grant, not one per check-in") +}) + +test("a confirm that failed is made by the next check-in, in another magpie too, and then forgotten", async () => { + const cred = await makeCred() + const ledgerPath = path.join(ledgerDir, "unconfirmed.json") + let confirms = 0 + const ops = opsFetcher({ item: daily() }, { + confirm: (st) => { + confirms += 1 + if (confirms === 1) return new Response("", { status: 502 }) + st.item = { ...st.item, status: "CONFIRMED" } + return new Response(JSON.stringify({ code: 0, data: null }), { status: 200 }) + }, + }) + const checkin = async () => { + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: ops.fetcher, ledgerPath }) + return plugin.auth.checkin(async () => makeAuth(cred)) + } + assert.equal((await checkin()).outcome, "failed") + const kept = JSON.parse(fs.readFileSync(ledgerPath, "utf8"))._unconfirmed + assert.deepEqual(Object.values(kept).map((v) => [v.campaignId, v.day]), [[1, x.beijingDay()]]) + assert.deepEqual(await checkin(), { outcome: "claimed", credit: 1000, message: "+1000 积分" }) + assert.equal(confirms, 2) + assert.deepEqual(JSON.parse(fs.readFileSync(ledgerPath, "utf8"))._unconfirmed, {}, "confirmed, so forgotten") + assert.equal((await checkin()).outcome, "done") + assert.equal(confirms, 2) +}) + test("checkin tells done, inactive and ineligible apart", async () => { const cred = await makeCred() - for (const status of ["CLAIMED", "CONFIRMED", "CONSUMED"]) { + for (const status of ["CONFIRMED", "CONSUMED"]) { const { fetcher, calls } = opsFetcher({ item: daily({ claimable: false, status }) }) assert.equal((await x.dailyCheckin(cred, fetcher)).outcome, "done") assert.equal(calls.length, 1) @@ -1584,13 +1995,48 @@ test("startOAuthFlow serves a callback server and a valid login URL", async () = const port = Number(url.searchParams.get("port")) assert.ok(port >= 10000, "callback port must be >= 10000") - // A callback without a code is rejected. - const res = await fetch(`http://127.0.0.1:${port}/oauth/callback`) - assert.equal(res.status, 400) + // A callback without a code fails the flow at once (the browser is sent to + // the portal's failure page, not followed there). + const res = await fetch(`http://127.0.0.1:${port}/oauth/callback`, { redirect: "manual" }) + assert.equal(res.status, 307) + await assert.rejects(flow.result, /without an authorization code/) await flow.close() }) +test("the callback port is one >= 10000, another while the one picked is taken", async () => { + const { EventEmitter } = await import("node:events") + // A stand-in server: the system gives a port below 10000, and the first + // random picks are someone else's. + const fakeServer = (taken, code = "EADDRINUSE") => { + const tried = [] + const server = Object.assign(new EventEmitter(), { + listen(port, host, cb) { + tried.push(port) + this.port = port === 0 ? 8080 : port + if (port !== 0 && tried.length - 1 <= taken) { + queueMicrotask(() => this.emit("error", Object.assign(new Error("listen failed"), { code }))) + return + } + queueMicrotask(cb) + }, + address() { return { port: this.port } }, + close(cb) { queueMicrotask(cb) }, + }) + return { server, tried } + } + const busy = fakeServer(3) + const port = await x.listenOnCallbackPort(busy.server) + assert.equal(busy.tried[0], 0) + assert.equal(busy.tried.length, 5) + assert.ok(port >= 10000) + assert.equal(port, busy.tried.at(-1)) + // Anything but a taken port is no reason to try another. + const denied = fakeServer(1, "EACCES") + await assert.rejects(x.listenOnCallbackPort(denied.server), { code: "EACCES" }) + assert.equal(denied.tried.length, 2) +}) + /** Run a callback server for one test, its STS answered by `sts`. */ async function withCallbackServer(sts, run) { const pkce = await x.generatePkcePair() @@ -1600,7 +2046,7 @@ async function withCallbackServer(sts, run) { exchanges.push(new URLSearchParams(init.body)) return sts() } - const { port, server, result } = await x.startOAuthCallbackServer("ticket", pkce, keyPair, fetcher) + const { port, server, result } = await x.startOAuthCallbackServer(pkce, keyPair, fetcher) result.catch(() => {}) const call = (query = "", init = {}) => fetch(`http://127.0.0.1:${port}${x.REDIRECT_PATH}${query}`, { redirect: "manual", ...init }) @@ -1612,18 +2058,58 @@ async function withCallbackServer(sts, run) { } } -test("the callback server takes only a GET with a code, and never a redirect it is handed", async () => { - await withCallbackServer(() => new Response(stsBody("AK", "R"), { status: 200 }), async ({ port, call, exchanges }) => { +/** + * A GET with its path sent as written, over a bare socket: fetch, and bun's + * http.request, normalise `/oauth/./callback` before it leaves. Gives the + * status and the Location. + */ +const rawGet = (port, rawPath) => new Promise((resolve, reject) => { + const socket = net.connect(port, "127.0.0.1", () => { + socket.write(`GET ${rawPath} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\n\r\n`) + }) + let answer = "" + socket.on("data", (d) => { answer += d }) + socket.on("end", () => resolve({ + status: Number(/^HTTP\/1\.1 (\d{3})/.exec(answer)?.[1]), + location: /^location: *(.*?)\r?$/im.exec(answer.split("\r\n\r\n")[0])?.[1] ?? null, + })) + socket.on("error", reject) +}) + +test("the callback server takes only a GET to the exact path with a code, and never a redirect it is handed", async () => { + await withCallbackServer(() => new Response(stsBody("AK", "R"), { status: 200 }), async ({ port, call, result, exchanges }) => { const post = await call("?code=C", { method: "POST" }) assert.equal(post.status, 405) assert.equal(post.headers.get("allow"), "GET") - // The old login's parameters are no way in: no code, no exchange, no redirect. - const legacy = await call(`?secret=${encodeURIComponent('{"access":"AK"}')}&redirect=${encodeURIComponent("https://evil.example/")}`) - assert.equal(legacy.status, 400) - assert.equal(legacy.headers.get("location"), null) - const elsewhere = await fetch(`http://127.0.0.1:${port}/other?code=C`, { redirect: "manual" }) - assert.equal(elsewhere.status, 404) + // Only the path exactly as sent: none of these is it. + const near = ["/other", "/oauth/./callback", "/oauth/%2e/callback", "/oauth/callback/", "/OAUTH/callback", "//oauth/callback"] + for (const path of near.map((p) => `${p}?code=C`)) { + assert.equal((await rawGet(port, path)).status, 404, path) + } assert.equal(exchanges.length, 0) + // The old login's parameters are no way in: no code is a sign-in that + // failed, at once, and the browser goes to the portal's page, not theirs. + // (Sent the raw way too, so the 404s above aren't the socket's doing.) + const legacyRaw = await rawGet(port, `${x.REDIRECT_PATH}?secret=S&redirect=https%3A%2F%2Fevil.example%2F`) + assert.deepEqual(legacyRaw, { status: 307, location: x.buildPortalLoginResultUrl(false) }) + await assert.rejects(result, /without an authorization code/) + // Nothing after that is taken, nor exchanged. + const legacy = await call(`?secret=${encodeURIComponent('{"access":"AK"}')}&redirect=${encodeURIComponent("https://evil.example/")}`) + assert.equal(legacy.status, 409) + assert.equal(legacy.headers.get("location"), null) + assert.equal((await call("?code=C")).status, 409) + assert.equal(exchanges.length, 0) + }) +}) + +test("a callback the portal sends back with an error ends the sign-in at once, in its words", async () => { + await withCallbackServer(() => new Response(stsBody("AK", "R"), { status: 200 }), async ({ call, result }) => { + const started = Date.now() + const res = await call("?error=access_denied&error_description=user%20cancelled%20the%20sign-in") + assert.equal(res.status, 307) + assert.equal(res.headers.get("location"), x.buildPortalLoginResultUrl(false)) + await assert.rejects(result, /CodeArts sign-in failed: user cancelled the sign-in/) + assert.ok(Date.now() - started < 5_000, "not left to the 180 s timeout") }) }) diff --git a/packages/codearts/package.json b/packages/codearts/package.json index 8f7b41c..9b87e8c 100644 --- a/packages/codearts/package.json +++ b/packages/codearts/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-codearts-auth", - "version": "0.2.0", + "version": "0.2.1", "description": "Huawei Cloud CodeArts (码道) in OpenCode and magpie: its models through Huawei Cloud OAuth sign-in, signed requests, credit usage and the daily check-in (unofficial)", "type": "module", "main": "./index.mjs",