From f42a59adf575322f15e203a6a4a17b5292f09478 Mon Sep 17 00:00:00 2001 From: MYCF711 <1451895195@qq.com> Date: Sat, 31 Oct 2026 02:29:36 +0800 Subject: [PATCH] codearts: an OfficeAce card for the same Huawei Cloud account (#522) codearts: an OfficeAce card for the same Huawei Cloud account (#522, MYCF711) Adds the OfficeAce (AgentArts) provider to the codearts package, replacing officeace-auth; accounts signed in there keep working. Each card signs in on its own and holds its own record and refresh token, because a Huawei Cloud STS refresh token is spent once. A renewal writes only the record being renewed, so a removed account never comes back. Reviewed over eight rounds; reviewed head f7c2526. r8 is words only plus the writeSharedRecord -> writeProviderRecord rename (every caller and the test updated). Run at f7c2526 on mote: node --test packages/codearts/index.test.mjs 164/164 pass; bun scripts/check.mjs exit 0, codearts ok. Not tried: a real Huawei Cloud sign-in on either card. --- packages/codearts/README.md | 142 +++- packages/codearts/index.mjs | 1320 +++++++++++++++++++++++++++++- packages/codearts/index.test.mjs | 1169 +++++++++++++++++++++++++- packages/codearts/package.json | 7 +- registry.json | 6 +- 5 files changed, 2611 insertions(+), 33 deletions(-) diff --git a/packages/codearts/README.md b/packages/codearts/README.md index 2e25ccb..01b6d27 100644 --- a/packages/codearts/README.md +++ b/packages/codearts/README.md @@ -1,8 +1,19 @@ # @magpie-community/opencode-codearts-auth -Signs in to **Huawei Cloud CodeArts** (华为云码道, the CodeArts Agent coding plans: Trial, -personal and enterprise credit plans) and serves its models — GLM, DeepSeek, openPangu and -more — in OpenCode and magpie. Provider id: `codearts`. +Signs in to **Huawei Cloud** and serves two providers in OpenCode and magpie: + +- **CodeArts** (华为云码道, the CodeArts Agent coding plans: Trial, personal and enterprise + credit plans) — provider id `codearts`: GLM, DeepSeek, openPangu and more. +- **OfficeAce** (华为云 AgentArts / MaaS) — provider id `officeace`: GLM, DeepSeek, Qwen, Kimi + and 盘古 models, its credit buckets and its daily check-in. + +Each card signs in on its own: the two providers hold separate records with separate Huawei Cloud +refresh tokens, because an STS refresh token is spent once — two records sharing one would sign +each other out. The same Huawei Cloud IAM account works for both, and a credential issued for one +endpoint also signs the other vendor's API (measured, see below), so signing in twice costs two +clicks and nothing else. OfficeAce was its own package (`officeace-auth`) until 0.3.0; accounts +signed in there are read from where magpie already keeps them and keep working — no second +sign-in for those. > **Unofficial.** This package is not affiliated with, authorized or endorsed by Huawei, > Huawei Cloud or CodeArts; their names and marks belong to their owners. It talks to the @@ -15,10 +26,13 @@ more — in OpenCode and magpie. Provider id: `codearts`. ```sh magpie plugin add @magpie-community/opencode-codearts-auth -magpie plugin login codearts +magpie plugin login codearts # CodeArts; the OfficeAce card signs in separately ``` -or install it from magpie's Plugins tab and sign in there. +or install it from magpie's Plugins tab and sign in there. **Coming from `officeace-auth`?** +Nothing to do: the account is stored under the same provider id (`officeace`) and in the same +credential shape, so it is read as it is. Remove the old package first (both cannot serve one +provider id: magpie asks which one if they are both installed). ## Sign-in @@ -106,6 +120,78 @@ signing in, a short built-in catalog stands in. client leaves unconfirmed (`id: null`) never is. Turn on *Auto check-in* for CodeArts under **Settings → Usage → Plugins**. +## OfficeAce (the second provider) + +**Signing in.** The officeace card offers the same 「Sign in with Huawei Cloud」 as the CodeArts +card, and it is the same account system: a CodeArts STS triple signs OfficeAce's subscription API +(V11-HMAC) and passes its CLAW permission check, and an OfficeAce triple signs CodeArts' +`snap-access` calls. But the two cards keep **separate records with separate refresh tokens** — +a sign-in writes only the card it was made on. A Huawei Cloud refresh token is spent once, so two +records holding one token would each sign the other out at its next renewal; one record per +sign-in is what keeps a CodeArts-only user from being asked to sign in again because of the +OfficeAce card. Sign in on the OfficeAce card to get an OfficeAce account. +A sign-in is the only thing that creates an OfficeAce account: a listing never adopts one from +another provider's record, so an account the user signed out of cannot come back by itself. + +**From `officeace-auth`.** That package's records are read unchanged: the account is under the +same provider id and its `access` field holds the same JSON (`modelAppKey`, `securityToken`, +`dpopPrivateJwk`, `refreshToken` …). Its refresh token is still spent at the OAuth client it was +issued to (`pdp5_for_agentarts`), so those accounts keep renewing too. + +**What a record is named, and what a renewal may touch.** `accountId` is the vendor's own stable +id — the IAM domain id, as the record `officeace-auth` wrote carried — and never the masked +phone: magpie hangs a user's own name for the account, its proxy and a gateway key off +`accountId`, so the phone belongs only in `usage().user` (#483, magpie#4416). A renewal never +renames an account: the stored `accountId` and `uid` stand exactly as written — the domain id, or +the phone `officeace-auth` 0.1.14 and later stored — and a value computed from the credential is +only filled in when the record has none. A new sign-in names its account by the domain id. + +**A record is renewed only with its own refresh token.** The unit of coordination is the refresh +chain: the OAuth client a token was issued to plus the token's lineage (a rotation keeps its +parent's, so a record still holding the spent token is known to be on the same chain). Each card's +record holds its own refresh token, from its own sign-in, so it is a chain of its own and spends +its own token however many hooks ask. +An `officeace-auth` record beside a CodeArts record holds a token from another issuer +(`pdp5_for_agentarts` against `codearts-agent`), so it is another chain: it spends its own token, +keeps its own MaaS pair, and a renewal that fails fails — it is never handed another record's +credential. No record's renewal writes another one: a renewal writes only the record it was asked +to renew. That is deliberate — writing the new credential into the other record is exactly what +used to bring a removed account back. + +**Models.** OfficeAce's catalog (`GET {maas}/v2/models`) is a registry, not a promise: 26 entries, +most of which answer `404 ModelArts.81009 Invalid model` at chat. The plugin cuts it down to the +billable list (`GET {subscription}/v1/model-token-rates`, 9 entries) and never lists three ids +measured to always 404. A rates read that fails keeps the last good table — an empty one would +put the un-callable ids back in front of the user. Before a sign-in a built-in table of 10 stands +in. Names carry the account's multiplier (`GLM-5.3 · x0.18`), and the vendor's trailing newline in +`model_name` is trimmed. + +**Requests.** MaaS wants `Authorization: Basic base64(appKey:appSecret)`; the plugin rewrites the +SDK's Bearer header, strips the `officeace/` model prefix, and sends the request to the MaaS base +the account's own credential names (official direct when it names none). A `401` (or a `4xx` +naming the Basic pair) renews the credential once and sends it again — but only when the renewal +changed the pair; the same pair would get the same refusal. An account that signed in without +opening MaaS gets a `400` saying so, not an empty Basic header sent upstream. + +**Usage and check-in.** `GET {subscription}/v1/subscription`: plan buckets (`skus[].quotas`) and +activity bonuses (`bonus_skus`) become magpie windows; a `.trial` bucket carries no expiry and +gets none invented; an expired bucket is folded away (`aside`) and takes no part in routing. The +check-in is `POST {subscription}/v1/subscription/bonus/claim` once a Beijing day: a 2xx with no +`bonus_skus` is 「今日已无新增可领」 (`done`), not a failure. Turn on *Auto check-in* for OfficeAce +under **Settings → Usage → Plugins**. + +**Known limits.** + +- STS spends a refresh token once. Each card of this package signs in on its own and holds its own + record and its own refresh token, so the two cards never affect each other. **A renewal writes + only the record being renewed**, which is also why a record the user removed can never come + back: no other record is written, whether it was listed, used, or not seen at all, and across a + restart too. An old `officeace-auth` record likewise renews only along its own chain. Two + separate magpie processes renewing the same account at the same moment still race; the loser + asks again and is signed out only if the token stays spent. +- `officeace-auth` and this package cannot both serve the `officeace` provider id. Magpie asks + which plugin serves it; remove the old one. + ## Options | Option | Default | What it does | @@ -126,8 +212,17 @@ measurements and code of [HuHong-Tao](https://github.com/yuweihao17/codearts/pul ## 中文 -接入**华为云码道(CodeArts Agent)**的编码套餐(体验版、个人与企业积分套餐),在 OpenCode 和 -magpie 里使用其 GLM、DeepSeek、openPangu 等模型。provider id:`codearts`。 +用**华为云 OAuth 登录**,在 OpenCode 和 magpie 里提供两个供应商: + +- **华为云码道(CodeArts Agent)**的编码套餐(体验版、个人与企业积分套餐),模型为 GLM、DeepSeek、 + openPangu 等。provider id:`codearts`。 +- **OfficeAce(华为云 AgentArts / MaaS)**:GLM、DeepSeek、Qwen、Kimi、盘古等模型,分桶积分与每日签到。 + provider id:`officeace`。 + +两张卡各自登录:两个 provider 各持一条记录、各有一个华为云 refresh token —— STS 的 refresh token 只能用一次, +两条记录共用一个 token 会互相把对方注销。同一个华为云 IAM 账号对两家都有效,且一次登录换到的凭据对两家的接口都能用 +(已实测,见下),所以「登两次」只是多点一次,不会有别的不便。OfficeAce 在 0.3.0 之前是独立的 `officeace-auth` 包: +那些账号按 magpie 原有的位置与形状读取,**不用重新登录**。 > **非官方插件**:与华为、华为云及 CodeArts(码道)没有任何关联,也未获其授权或认可。插件调用的是 > 码道客户端使用的非公开接口,并以与官方客户端相同的方式标识自己(含自动领取每日免费权益与签到), @@ -153,6 +248,39 @@ magpie 里使用其 GLM、DeepSeek、openPangu 等模型。provider id:`codear (这部分仍在用更多账号验证,请以控制台为准)。`auth.checkin` 与客户端「限时福利 → 每日领取」一致 (插件领取后确认失败的,当天记在签到账本里,下次签到时补确认;客户端本就不确认的 `id: null` 领取不会被确认), 在 **设置 → 用量 → Plugins** 打开「每日自动签到」即可。 +- **OfficeAce(第二个供应商)**:officeace 卡片提供与 CodeArts 卡片相同的「华为云登录」,账号体系是同一套: + 码道的 STS 三元组能签 OfficeAce 的订阅接口(V11-HMAC)并通过它的 CLAW 权限校验,反之 OfficeAce 的三元组也能签 + 码道的 `snap-access` 接口。但**两张卡各写各的记录、各持自己的 refresh token**——一次登录只写当前这张卡的记录。 + 华为云的 refresh token 只能用一次,两条记录共用一个 token 会让 CodeArts 用户因为 OfficeAce 那条记录续期而被要求 + 重新登录;一条记录一次登录才是对的。要用 OfficeAce 就在 OfficeAce 卡片上登录。记录放在 + `#<账号身份哈希>` 上,之后再登同一账号会合并,不会多出一行。**只有登录会创建 OfficeAce 账号**: + 列模型时不会从另一家的记录「带入」一个账号,用户登出的账号不会自己回来。老 `officeace-auth` 的记录原样读取:provider id 相同、`access` 里的 JSON 形状相同, + 续期仍走它签发时的 OAuth 客户端(`pdp5_for_agentarts`)。 +- **账号名与续期边界**:`accountId` 用厂商自己的稳定 id(IAM 域名 id,与老 `officeace-auth` 记录里的一致), + **绝不是打码手机号**(#483、magpie#4416;magpie 把用户给账号起的名字、代理、网关 key 都挂在 `accountId` 上, + 手机号只出现在 `usage().user`)。续期不会重命名账号:记录里已有的 `accountId`/`uid` 原样保留(域名 id,或 + `officeace-auth` 0.1.14 存下的手机号),只在该值为空时才补一个。新登录写的 `accountId` 是域名 id。 + 续期只花**这条记录自己的 refresh token**:协调单位是「refresh chain = 签发它的 OAuth 客户端 + token 的血缘」 + (轮换后的新 token 记在父 token 同一血缘上,仍算同一条链)。 + 每条记录都有自己的 token:码道记录由 `codearts-agent` 签发,OfficeAce 记录由 `pdp5_for_agentarts` 签发,各花各的, + 各自保留自己的 MaaS 凭据;**续期只写被续的那条记录,绝不写另一条**(`auth.set` 会把不存在的账号创建出来), + 续期失败就是失败,绝不借用另一条链的凭据。 +- **OfficeAce 的模型**:目录 `/v2/models` 是注册表(26 条,多数对话时回 `404 ModelArts.81009 Invalid model`), + 插件只保留计费清单(`/v1/model-token-rates`,9 条)里的,并永不列出三个实测必 404 的 id;倍率表读取失败时保留上 + 一份好表(空表会让不可调的 id 全部回到用户面前);未登录时用 10 个内置模型兜底。模型名带上倍率(`GLM-5.3 · x0.18`), + 上游 `model_name` 的尾部换行会去掉。 +- **OfficeAce 的请求**:MaaS 要 `Authorization: Basic base64(appKey:appSecret)`,插件把 SDK 的 Bearer 改写掉, + 去掉 `officeace/` 前缀,发到凭据里自带的 MaaS 地址(为空时用官方直连)。`401`(或 4xx 但报文点名这对 Basic 凭据) + 会先续期一次再重发,**但只有续期真的换了这对凭据时才重发**。已登录但没开通 MaaS 的账号会得到一条说清原因的 `400`, + 不会把空的 Basic 头发给上游。 +- **OfficeAce 的用量与签到**:`/v1/subscription` 的套餐桶(`skus[].quotas`)与活动桶(`bonus_skus`)转成 magpie 的窗口; + `.trial` 桶没有到期时间就不显示;已过期的桶收进折叠区(`aside`)且不参与路由。签到是每个北京自然日一次 + `POST /v1/subscription/bonus/claim`:2xx 但 `bonus_skus` 为空是「今日已无新增可领」(`done`),不是失败。 +- **已知限制**:STS 的 refresh_token 只能用一次。本包的每张卡各自登录、各自持有一条记录与一个 token,所以两张卡 + 互不影响;**续期只写被续的那条记录**,因此用户删掉的账号永远不会被写回来(无论它此前有没有被列出/使用过、 + 有没有重启)。老 `officeace-auth` 记录同样只按自己的链续期。两个 magpie 进程同时续期同一个账号仍可能撞车, + 输的一方重试,只有 token 一直是被消费状态才标记需重新登录。 + 另外,`officeace-auth` 与本包不能同时服务 `officeace` 这个 provider id,magpie 会让你选一个,装之前先卸掉旧的。 - **致谢**:原作者 [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 bf5367b..1cb488b 100644 --- a/packages/codearts/index.mjs +++ b/packages/codearts/index.mjs @@ -42,7 +42,7 @@ // replaces its browser sign-in + bearer-token requests with CodeArts' OAuth + // signed-request flow. See README.md. -import { createHash } from "node:crypto" +import { createHash, createHmac } from "node:crypto" import { createServer } from "node:http" import fs from "node:fs" import os from "node:os" @@ -649,7 +649,10 @@ function credentialOf(auth) { const raw = typeof auth.access === "string" ? auth.access : "" if (!raw) return null const cred = safeJson(raw) - return cred && typeof cred.access_key_id === "string" && cred.access_key_id ? cred : null + if (!cred || typeof cred.access_key_id !== "string" || !cred.access_key_id) return null + // Which OAuth client a refresh token may be spent at. A record read here is + // one this package's CodeArts sign-in wrote, whatever an older one lacks. + return { ...cred, oauth_client: firstOf(cred.oauth_client, "codearts-agent") } } function expiresFromCredential(cred) { @@ -660,8 +663,8 @@ function expiresFromCredential(cred) { return Date.now() + 86_400_000 } -/** POST the STS token endpoint with a DPoP proof. */ -async function requestToken(body, keyPair, fetcher) { +/** POST the STS token endpoint with a DPoP proof; `label` is the card that asked. */ +async function requestToken(body, keyPair, fetcher, label = "CodeArts") { const dpop = await signDpopJws(keyPair, "POST", STS_TOKEN_ENDPOINT) let response try { @@ -674,7 +677,7 @@ async function requestToken(body, keyPair, fetcher) { signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS), }) } catch (e) { - throw new Error(`CodeArts token request network error: ${String(e)}`) + throw new Error(`${label} token request network error: ${String(e)}`) } let data = null try { @@ -683,7 +686,7 @@ async function requestToken(body, keyPair, fetcher) { data = null } if (!response.ok || !data?.credentials) { - const message = `CodeArts token request failed: ${response.status}${data ? ` ${JSON.stringify(data)}` : ""}` + const message = `${label} token request failed: ${response.status}${data ? ` ${JSON.stringify(data)}` : ""}` // Only refresh_token invalidation is terminal; a transient DPoP rejection // must not permanently mark the account. if (data?.error === "invalid_grant" || isDeadRefreshToken(message)) { @@ -705,14 +708,14 @@ function isDeadRefreshToken(text) { const isPermanentRefreshFailure = (e) => e?.signIn === "expired" || isDeadRefreshToken(e?.message ?? e) -function exchangeAuthorizationCode(code, codeVerifier, port, keyPair, fetcher) { +function exchangeAuthorizationCode(code, codeVerifier, port, keyPair, fetcher, label = "CodeArts") { return requestToken({ client_id: CLIENT_ID, code, code_verifier: codeVerifier, grant_type: GRANT_AUTHORIZATION_CODE, redirect_uri: `http://127.0.0.1:${port}${REDIRECT_PATH}`, - }, keyPair, fetcher) + }, keyPair, fetcher, label) } function exchangeRefreshToken(refreshToken, codeVerifier, keyPair, fetcher) { @@ -780,7 +783,7 @@ const buildPortalLoginResultUrl = (ok) => * 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(pkce, keyPair, fetcher) { +function startOAuthCallbackServer(pkce, keyPair, fetcher, label = "CodeArts") { let resolveResult let rejectResult const result = new Promise((resolve, reject) => { @@ -816,7 +819,7 @@ function startOAuthCallbackServer(pkce, keyPair, fetcher) { return } const port = request.socket.localPort ?? 0 - void exchangeAuthorizationCode(code, pkce.codeVerifier, port, keyPair, fetcher).then( + void exchangeAuthorizationCode(code, pkce.codeVerifier, port, keyPair, fetcher, label).then( (token) => { response.writeHead(307, { Location: buildPortalLoginResultUrl(true) }).end() const cred = credentialFromTokenResponse(token, pkce.codeVerifier, keyPair) @@ -868,10 +871,10 @@ function listenOnCallbackPort(server) { * The result resolves once the browser is redirected back and STS answers; * the callback server is closed as soon as the result settles. */ -async function startOAuthFlow(fetcher) { +async function startOAuthFlow(fetcher, label = "CodeArts") { const pkce = await generatePkcePair() const keyPair = await generateDpopKeyPair() - const { port, server, result } = await startOAuthCallbackServer(pkce, keyPair, fetcher) + const { port, server, result } = await startOAuthCallbackServer(pkce, keyPair, fetcher, label) // 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)) @@ -2485,8 +2488,8 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { 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) => { + const promise = renewSharedCredential(cred, () => refreshCredential(cred, fetcher)) + .then(async (next) => { state.renewed = { from: token, next } return next }) @@ -2552,7 +2555,13 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { id: PROVIDER, async models(provider, { auth } = {}) { const cred = credentialOf(auth) - if (!cred?.access_key_id) return provider.models + if (!cred?.access_key_id) { + // A models hook that runs with no auth is a provider with no accounts. + noteProviderEmpty(PROVIDER) + return provider.models + } + const identity = accountIdentityOf(cred).id + if (identity) noteProviderAccount(PROVIDER, identity) try { const state = await stateOf(cred) const list = await fetchRemoteModels(cred, fetcher, state) @@ -2604,6 +2613,8 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { let account = await getAuth() let cred = credentialOf(account) if (!cred?.access_key_id || !cred?.secret_access_key) return {} + const identity = accountIdentityOf(cred).id + if (identity) noteProviderAccount(PROVIDER, identity) // magpie renews ahead of expiry by itself; this covers hosts that // ignore `auth.refresh` (OpenCode) and a credential that went stale @@ -2683,6 +2694,8 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { const auth = await getAuth() const cred = credentialOf(auth) if (!cred?.access_key_id) return { error: "not signed in", windows: [] } + const identity = accountIdentityOf(cred).id + if (identity) noteProviderAccount(PROVIDER, identity) try { const text = await signedGet(SNAP_STATISTICS_URL, cred, fetcher, SNAP_EXTRA_HEADERS) if (text === undefined) return { error: "CodeArts answered an error", windows: [] } @@ -2754,7 +2767,7 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { const flow = await startOAuthFlow(fetcher) return { url: flow.loginUrl, - instructions: "Sign in to Huawei Cloud in the browser; this window closes itself when done.", + instructions: "Sign in to Huawei Cloud in the browser. This signs in CodeArts only — the OfficeAce card has its own sign-in. This window closes itself when done.", method: "auto", async callback() { try { @@ -2765,18 +2778,29 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { // a failed read still signs in), shown through usage's // `user`; the credential carries it as `user_phone`. const identified = { ...cred, ...(await accountPhoneField(cred, fetcher)) } - const identity = accountIdentityOf(identified) + // The MaaS pair OfficeAce needs is read once here (best effort: + // an account that never opened MaaS signs in all the same), and + // kept on this credential too, so a later rotation of this + // record hands the other one a credential that still has it. + const withMaas = await withOfficeAceMaas(identified, fetcher) + const identity = accountIdentityOf(withMaas) // `accountId` is the account's identity — the URN, as main // gives it — so a re-sign-in replaces the account instead of // adding a `codearts#xxxxxx`; `uid` is that same URN. - return { + const record = { type: "success", - access: JSON.stringify(identified), + access: JSON.stringify(withMaas), refresh: cred.refresh_token, expires: outcome.expires, accountId: identity.id, ...(identity.id ? { uid: identity.id } : {}), } + // This sign-in writes this card's record only. A Huawei Cloud + // refresh token is spent once, so two records holding one + // token would sign each other out; the other card has its own + // sign-in and its own token. + await writeProviderRecord(client, PROVIDER, withMaas, fetcher) + return record } catch (e) { return { type: "failed", error: e?.message ?? String(e) } } finally { @@ -2855,3 +2879,1261 @@ export const _internal = { snapRequest, dailyCheckin, parseModelInfo, extractArray, fetchRemoteModels, creditWindow, benefitWindow, usageFromStatistics, } + +// ═══════════════════════════════════════════════════════════════════════════ +// OfficeAce — a second provider from the same Huawei Cloud sign-in +// ═══════════════════════════════════════════════════════════════════════════ +// +// OfficeAce (华为云 AgentArts / MaaS) runs on the same Huawei Cloud IAM account +// as CodeArts. Measured with a real account on 2026-10-30, read-only: +// +// * a CodeArts STS triple signs OfficeAce's subscription read +// (V11-HMAC `GET …/v1/subscription`, HTTP 200, same `domain_id`) and passes +// its CLAW permission check (`…/v1/claw/client-permission-validate`); +// * an OfficeAce STS triple signs CodeArts' `snap-access` reads byte for byte +// the same way the CodeArts triple does. +// +// So one credential signs both providers' APIs, but each card signs in on its +// own and keeps its own record: a Huawei Cloud refresh token is spent once, so +// one token written into two records would sign one of them out at the other's +// renewal (`STS5.1806`). The second provider keeps its record in the shape +// `officeace-auth` (the package this one absorbs) has always written — `access` +// is a JSON string carrying `modelAppKey` / `securityToken` / `dpopPrivateJwk` +// … — so the accounts signed in through that package keep working without +// signing in again. The account is stored under the same provider id it always +// had (`officeace`), so its records are exactly where magpie already keeps them. +// +// A renewal writes only the record being renewed. Nothing is ever written into +// another record, which is what kept resurrecting an account the user had +// removed, and a failed renewal never borrows a credential from another chain. + +/** The OfficeAce provider id — the one the `officeace-auth` package used. */ +const OFFICEACE_PROVIDER = "officeace" +const OFFICEACE_NPM = "@ai-sdk/openai-compatible" + +// The three domains, never mixed (each measured; see the OfficeAce internals): +// CLAW sign-in permission check (the MaaS appKey lives behind it) +// STS token exchange — the same endpoint CodeArts uses +// MaaS model catalog and chat +// subscription usage, credit rates and the daily check-in +const OA_CLAW_BASE = "https://agentarts.cn-southwest-2.myhuaweicloud.com" +const OA_PERMISSION_PATH = "/v1/claw/client-permission-validate" +const OA_SUBSCRIPTION_BASE = "https://officeace.cn-southwest-2.huaweicloud-agentarts.com" +const OA_SUBSCRIPTION_PATH = "/v1/subscription" +const OA_TOKEN_RATES_PATH = "/v1/model-token-rates" +const OA_BONUS_CLAIM_PATH = "/v1/subscription/bonus/claim" +const OA_MAAS_MARKET_BASE = "https://api.modelarts-maas.com" +const OA_MODELS_PATH = "/v2/models" +const OA_CHAT_PATH = "/v2/chat/completions" +const OA_REGION = "cn-southwest-2" +const OA_SERVICE = "apic" +/** The OAuth client OfficeAce's own sign-in uses (its old package's refreshes). */ +const OA_AGENTARTS_CLIENT_ID = "pdp5_for_agentarts" +const OA_RATES_TTL_MS = 20 * 60 * 1000 +const OA_REFRESH_LEAD_MS = 10 * 60 * 1000 +const OA_TOKEN_TIMEOUT_MS = 30_000 + +/** The models OfficeAce shows before anyone is signed in (its own desktop list). */ +const OA_FALLBACK_MODELS = { + "glm-5.3": { name: "GLM-5.3", context: 1_000_000, output: 128_000 }, + "glm-5.2": { name: "GLM-5.2", context: 1_000_000, output: 128_000 }, + "glm-5.1": { name: "GLM-5.1", context: 1_000_000, output: 128_000 }, + "deepseek-v4": { name: "DeepSeek-V4", context: 1_000_000, output: 128_000 }, + "deepseek-v4.1": { name: "DeepSeek-V4.1", context: 1_000_000, output: 128_000 }, + "qwen3-30b": { name: "Qwen3 30B", context: 1_000_000, output: 128_000 }, + "qwen3-32b": { name: "Qwen3 32B", context: 1_000_000, output: 128_000 }, + "kimi-k2.6": { name: "Kimi-K2.6", context: 1_000_000, output: 128_000 }, + "pangu-2.0-pro": { name: "盘古 2.0 Pro", context: 1_000_000, output: 128_000 }, + "pangu-2.0-flash": { name: "盘古 2.0 Flash", context: 1_000_000, output: 128_000 }, +} + +/** + * Registry ids that answer `404 ModelArts.81009 Invalid model` on chat whatever + * the headers (measured; `deepseek-v4.1-flash-1017` stays 404 even with + * `maas_type: benefit`). Never listed, whatever the catalog says. + */ +const OA_UNAVAILABLE_IDS = new Set([ + "deepseek-v4.1-flash-1017", + "deepseek-v4.1-flash-bnt", + "deepseek-v4-pro", +]) + +/** OfficeAce's own icon (its `.ico` as a 128×128 PNG). */ +const OFFICEACE_ICON = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAnk0lEQVR42u19ebgcVbXvb+1d1eMZMicSCYEEAkGSYBglTMokg1cJAUUvXBBQUGRSEBEhDteRp4AXfL53laeC90tkiBc/RJkCl0EgDAqJMoUhATKQ5Iw9VO293h9791zVXd3n9DknSH/fgZM+1dW191p7jb+1FmGIL14CiWXQRODie1/Yd6Iv+hcJxoEaGE+M2cyYBuJJYJokAKEZABjFT9n/M3PFv8FcduPSe2X/K/1SuF3VvbnZ76q4jh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kJNnGbfy4kuL7iXteu62aRmimCKeZSb929iZfBYgLPzT5EwScrxiLuh0h85qRM5zAZMLJolCgSnUQJu/p+7I9JoPOJAYTQTMgHQLFhRk+kfW0FoQHAf7f/37fumVLAX0VIK62c1XQwlTDpl/VnLbloMnzlcJJgnAMwLvHhOhIEuCx+VFUMYroPcLXQe0IAhwQHGE+62uGp7kfjDWK+M9xiNti97++KowWI8IA5UGj8i/nJZCbXp+0i5Q4FEx7MmM2CZrF4KkESgOIv5v8+zaI/BwzBoh4A0AvM/glaDwvgQcSU9atrd7roOBOM6//D3yh7zupDILjAAAAAElFTkSuQmCC" + +// ---- one credential, two shapes ------------------------------------------- + +/** + * A Huawei Cloud STS credential in this package's internal shape — the shape + * CodeArts has always stored (`access_key_id`, `secret_access_key`, + * `security_token`, `refresh_token`, `dpop_private_key_jwk` …) plus the MaaS + * fields OfficeAce needs (`model_app_key`, `model_app_secret`, `maas_base_url`). + * + * OfficeAce's own package stored the same credential under different names + * (`access`, `secret`, `securityToken`, `modelAppKey`, `dpopPrivateJwk` …). + * `officeAceCredentialOf` reads either and gives this one; `officeAceRecordOf` + * writes it back in OfficeAce's shape, so a record is readable by both. + */ +function officeAceCredentialOf(auth) { + if (!auth) return null + const raw = typeof auth.access === "string" ? safeJson(auth.access) : asRecord(auth.access) + const flat = raw && typeof raw === "object" ? raw : asRecord(auth) + const pick = (...vs) => firstOf(...vs) + + const access = pick(flat.access_key_id, flat.access) + const secret = pick(flat.secret_access_key, flat.secret) + const securityToken = pick(flat.security_token, flat.securityToken) + // A record with only the STS triple is a sign-in too: usage and the check-in + // are signed with it alone (the MaaS appKey only guards catalog and chat). + if (!access || !secret || !securityToken) return null + + // Which OAuth client issued the refresh token. The CodeArts field names are + // this package's own flow; OfficeAce's (`access` / `securityToken`) are the + // old package's, whose refreshes were asked for as `pdp5_for_agentarts`. + // `oauth_client` is written down when a record says it, so a derived record + // is renewed the way it was made. + const codeArtsShape = !!flat.access_key_id && !!flat.secret_access_key + const profile = profileOf({ refresh_token: pick(flat.refresh_token, auth.refresh) }) || {} + const domain = pick(flat.domain_id, flat.accountId, profile.account_id, profile.domain_id) + return { + access_key_id: access, + secret_access_key: secret, + security_token: securityToken, + expires_at: pick(flat.expires_at, flat.expiresAt, typeof auth.expires === "number" ? new Date(auth.expires).toISOString() : ""), + refresh_token: pick(auth.refresh, flat.refresh_token, flat.refreshToken), + code_verifier: pick(flat.code_verifier, flat.codeVerifier), + dpop_private_key_jwk: flat.dpop_private_key_jwk ?? flat.dpopPrivateJwk ?? null, + session_id: pick(flat.session_id), + user_phone: pick(flat.user_phone, auth.user_phone), + domain_id: domain, + model_app_key: pick(flat.model_app_key, flat.modelAppKey), + model_app_secret: pick(flat.model_app_secret, flat.modelAppSecret), + maas_base_url: pick(flat.maas_base_url, flat.maasBaseUrl), + oauth_client: pick(flat.oauth_client, flat.oauthClient, codeArtsShape ? "codearts-agent" : OA_AGENTARTS_CLIENT_ID), + } +} + +/** Is this credential one this package's own CodeArts sign-in issued? */ +const isCodeArtsClient = (cred) => cred?.oauth_client === "codearts-agent" + +/** The credential as `officeace-auth` stores it (its historical shape). */ +function officeAceCredentialRecord(cred) { + const identity = accountIdentityOf(cred) + const profile = profileOf(cred) || {} + return { + modelAppKey: firstOf(cred.model_app_key), + modelAppSecret: firstOf(cred.model_app_secret), + maasBaseUrl: firstOf(cred.maas_base_url), + access: firstOf(cred.access_key_id), + secret: firstOf(cred.secret_access_key), + securityToken: firstOf(cred.security_token), + projectId: "", + expiresAt: firstOf(cred.expires_at), + refreshToken: firstOf(cred.refresh_token), + codeVerifier: firstOf(cred.code_verifier), + dpopPrivateJwk: cred.dpop_private_key_jwk ?? null, + session_id: firstOf(cred.session_id), + accountId: firstOf(profile.account_id, profile.domain_id, cred.domain_id), + user_phone: firstOf(cred.user_phone), + // A record written from a credential with no marker of its own is one this + // package's CodeArts sign-in (or a rotation of it) issued. + oauth_client: firstOf(cred.oauth_client, "codearts-agent"), + ...(identity.id ? { uid: identity.id } : {}), + } +} + +/** + * What magpie shows for an OfficeAce account. + * + * `accountId` is the vendor's own stable id — the IAM domain id, as the record + * `officeace-auth` wrote carried — and never the masked phone: the name, + * proxy and gateway key a user gives an account hang off `accountId`, so a + * phone there is both a display leak and a re-keying of that account (#483, + * magpie#4416). The phone is only ever `usage().user`. `uid` is the same id. + */ +function officeAceIdentityOf(cred) { + const profile = profileOf(cred) || {} + const domain = firstOf(profile.account_id, profile.domain_id, cred?.domain_id) + return { accountId: domain, uid: domain } +} + +/** The `{type, refresh, access, expires, accountId, uid}` magpie keeps for OfficeAce. */ +function officeAceRecordBody(cred) { + const identity = officeAceIdentityOf(cred) + return { + type: "oauth", + refresh: firstOf(cred.refresh_token), + access: JSON.stringify(officeAceCredentialRecord(cred)), + expires: expiresFromCredential(cred), + ...(identity.accountId ? { accountId: identity.accountId } : {}), + ...(identity.uid ? { uid: identity.uid } : {}), + } +} + +/** The same record in CodeArts' shape (for the sibling write). */ +function codeArtsRecordBody(cred) { + const identity = accountIdentityOf(cred) + return { + type: "oauth", + refresh: firstOf(cred.refresh_token), + access: JSON.stringify(cred), + expires: expiresFromCredential(cred), + ...(identity.id ? { accountId: identity.id, uid: identity.id } : {}), + } +} + +/** The MaaS base URL a credential names, or the official one (空串/裸域名 both handled). */ +function officeAceMaasBase(cred) { + const raw = cred?.maas_base_url + if (typeof raw !== "string" || raw.length === 0) return OA_MAAS_MARKET_BASE + const trimmed = raw.replace(/\/+$/, "") + return /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}` +} + +// ---- V11-HMAC-SHA256: what the subscription API checks -------------------- + +/** `20261030T081500Z` — the X-Sdk-Date form both Huawei signers use. */ +function oaSdkDate(now = new Date()) { + return now.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z") +} + +/** + * Sign one OfficeAce subscription request (V11-HMAC-SHA256). + * + * The differences from the SDK-HMAC signer above are all load-bearing (each + * was measured against the live gateway): + * * the key is derived: HMAC(HMAC(access, secret), scope + 0x01), first 32 + * bytes hex, and that hex string is the signing key; + * * `X-Security-Token` and `x-subscription-type: v2` are mandatory; + * * the canonical URI is decoded and re-encoded segment by segment. + */ +function signOfficeAceV11(urlStr, cred, method = "GET", body, dateOverride) { + const url = new URL(urlStr) + const xdate = dateOverride ?? oaSdkDate() + const path = url.pathname.split("/").map((s) => rfc3986(decodeURIComponent(s))).join("/") + const canonicalUri = path.endsWith("/") ? path : `${path}/` + + const original = { + "x-subscription-type": "v2", + "X-Sdk-Date": xdate, + "X-Security-Token": String(cred.security_token ?? "").trim(), + Host: url.host, + } + if (method === "POST") original["Content-Type"] = "application/json;charset=utf8" + if (cred.project_id) original["X-Project-ID"] = cred.project_id + + const lower = {} + for (const [k, v] of Object.entries(original)) lower[k.toLowerCase()] = String(v).trim().replace(/\s+/g, " ") + const signedHeaders = Object.keys(lower).sort() + const canonicalHeaders = signedHeaders.map((h) => `${h}:${lower[h]}\n`).join("") + + const payloadHash = createHash("sha256").update(body ?? "", "utf8").digest("hex") + const canonicalRequest = [ + method, canonicalUri, canonicalQuery(url), canonicalHeaders, signedHeaders.join(";"), payloadHash, + ].join("\n") + + const scope = `${xdate.slice(0, 8)}/${OA_REGION}/${OA_SERVICE}` + const stringToSign = [ + "V11-HMAC-SHA256", xdate, scope, createHash("sha256").update(canonicalRequest).digest("hex"), + ].join("\n") + + const u1 = createHmac("sha256", cred.access_key_id).update(cred.secret_access_key).digest() + const derivedKey = createHmac("sha256", u1) + .update(Buffer.concat([Buffer.from(scope, "utf8"), Buffer.from([1])])) + .digest() + .subarray(0, 32) + .toString("hex") + const signature = createHmac("sha256", Buffer.from(derivedKey, "utf8")).update(stringToSign).digest("hex") + + return { + ...original, + Authorization: `V11-HMAC-SHA256 Credential=${cred.access_key_id}/${scope}, SignedHeaders=${signedHeaders.join(";")}, Signature=${signature}`, + } +} + +/** One signed OfficeAce request; a network error is `status: 0` with its reason. */ +async function officeAceSigned(cred, urlStr, method = "GET", body, fetcher = fetch) { + const headers = signOfficeAceV11(urlStr, cred, method, body) + try { + const res = await fetcher(urlStr, { + method, + headers, + ...(body === undefined ? {} : { body }), + signal: AbortSignal.timeout(OA_TOKEN_TIMEOUT_MS), + }) + const text = await res.text().catch(() => "") + return { ok: res.ok, status: res.status, text } + } catch (e) { + return { ok: false, status: 0, text: e instanceof Error ? e.message : String(e) } + } +} + +// ---- the MaaS appKey: the CLAW permission check -------------------------- + +/** + * Read the account's MaaS Basic credentials and base URL from the CLAW + * permission check — the same call OfficeAce's own sign-in ends with, signed + * with the STS triple every Huawei Cloud sign-in yields. An account that has + * not opened MaaS answers without `model_auth_info`: that is not a failure, + * it only means catalog/chat have nothing to use yet. + */ +async function fetchOfficeAceMaasInfo(cred, fetcher = fetch) { + const url = `${OA_CLAW_BASE}${OA_PERMISSION_PATH}` + const extra = { "content-type": "application/json" } + const signed = await signRequestHuawei( + cred.access_key_id, cred.secret_access_key, cred.security_token, "GET", url, new Uint8Array(), extra, + ) + const headers = new Headers() + signed.forEach((value, key) => { + if (key !== "host") headers.set(key, value) + }) + const res = await fetcher(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(OA_TOKEN_TIMEOUT_MS) }) + if (!res.ok) throw new Error(`OfficeAce permission check failed: HTTP ${res.status}`) + const body = await res.json().catch(() => null) + const info = body?.subscription?.model_info + const auth = info?.model_auth_info + return { + model_app_key: typeof auth?.model_app_key === "string" ? auth.model_app_key : "", + model_app_secret: typeof auth?.model_app_secret === "string" ? auth.model_app_secret : "", + maas_base_url: typeof info?.model_api_url_base === "string" ? info.model_api_url_base : "", + } +} + +/** The MaaS fields of one account, read at most once per process (best effort). */ +const oaMaasCache = new Map() // identity → { at, info } + +async function officeAceMaasInfo(cred, fetcher = fetch) { + const identity = accountIdentityOf(cred).id || cred.session_id || cred.access_key_id + const hit = oaMaasCache.get(identity) + if (hit && Date.now() - hit.at < 6 * 60 * 60 * 1000) return hit.info + const info = await fetchOfficeAceMaasInfo(cred, fetcher).catch(() => null) + if (info) oaMaasCache.set(identity, { at: Date.now(), info }) + return info +} + +// ---- the OfficeAce API --------------------------------------------------- + +/** Credit multipliers per account; a failed read keeps the last good table. */ +const oaRatesCache = new Map() // identity → { at, map } + +/** + * `GET {SUB}/v1/model-token-rates` — the billable list. It is the whitelist the + * catalog is cut down to: the catalog lists 26 registry entries, 19 of which + * cannot be called; the rates list is what the OfficeAce desktop shows. + * + * A failure returns the last good table rather than an empty one: an empty + * table would disable the whitelist downstream and put the uncallable ids back + * in front of the user (measured defect, 2026-10-26). + */ +async function fetchOfficeAceTokenRates(cred, fetcher = fetch) { + const identity = accountIdentityOf(cred).id || cred.session_id || cred.access_key_id + const hit = oaRatesCache.get(identity) + if (hit && hit.map.size > 0 && Date.now() - hit.at < OA_RATES_TTL_MS) return hit.map + const keepStale = () => { + if (hit) oaRatesCache.set(identity, { at: Date.now(), map: hit.map }) + return hit?.map ?? new Map() + } + + const r = await officeAceSigned(cred, `${OA_SUBSCRIPTION_BASE}${OA_TOKEN_RATES_PATH}`, "GET", undefined, fetcher) + if (!r.ok) return keepStale() + let j + try { + j = JSON.parse(r.text) + } catch { + return keepStale() + } + const rows = Array.isArray(j) ? j : Array.isArray(j?.models) ? j.models : Array.isArray(j?.data) ? j.data : Array.isArray(j?.rates) ? j.rates : [] + const map = new Map() + for (const row of rows) { + const raw = row?.model_name ?? row?.modelName ?? row?.model ?? row?.name + // the vendor's `model_name` carries a trailing newline ("kimi-k3\n") + const name = typeof raw === "string" ? raw.trim() : "" + const rate = Number(row?.cost_coefficient ?? row?.costCoefficient ?? row?.rate) + if (name && Number.isFinite(rate)) map.set(name, rate) + } + if (map.size === 0) return keepStale() + oaRatesCache.set(identity, { at: Date.now(), map }) + return map +} + +/** `GET {maas}/v2/models`, names carrying the account's multiplier (`· x1.5`). */ +async function fetchOfficeAceCatalog(cred, fetcher = fetch) { + const r = await fetcher(`${officeAceMaasBase(cred)}${OA_MODELS_PATH}`, { + headers: { Accept: "application/json", Authorization: basicAuthorization(cred) }, + signal: AbortSignal.timeout(OA_TOKEN_TIMEOUT_MS), + }) + if (!r.ok) throw new Error(`OfficeAce catalog read failed: HTTP ${r.status}`) + const body = await r.json().catch(() => null) + const rows = Array.isArray(body) ? body : Array.isArray(body?.data) ? body.data : [] + const rates = await fetchOfficeAceTokenRates(cred, fetcher).catch(() => new Map()) + const out = [] + for (const row of rows) { + const id = (typeof row === "string" ? row : typeof row?.id === "string" ? row.id : "").trim() + if (!id) continue + const base = typeof row?.name === "string" && row.name.trim() ? row.name.trim() : id + const rate = rates.get(id) + out.push({ id, name: rate !== undefined && rate !== 1 ? `${base} · x${rate}` : base }) + } + return out +} + +/** One OfficeAce model entry, as magpie wants it. */ +function officeAceModelEntry({ id, name, baseUrl = OA_MAAS_MARKET_BASE, context = 1_000_000, output = 128_000 }) { + return { + id, + name, + api: { id, url: `${baseUrl}/v2`, npm: OFFICEACE_NPM }, + status: "active", + headers: {}, + options: {}, + cost: { input: 0, output: 0, cache: { read: 0, write: 0 } }, + limit: { context, output }, + capabilities: { + temperature: true, + reasoning: true, + attachment: false, + toolcall: true, + input: { text: true, image: false, audio: false, video: false, pdf: false }, + output: { text: true, image: false, audio: false, video: false, pdf: false }, + interleaved: false, + }, + release_date: "", + variants: {}, + } +} + +/** The static table `config` hands magpie before a sign-in (never "0 models"). */ +function officeAceStaticModels() { + const out = {} + for (const [id, def] of Object.entries(OA_FALLBACK_MODELS)) { + out[id] = officeAceModelEntry({ id, name: def.name, context: def.context, output: def.output }) + } + return out +} + +/** The account's own catalog: catalog ∩ rates, minus the ids that always 404. */ +function officeAceLiveModels(rows, baseUrl, rates) { + const out = {} + for (const row of rows) { + const id = typeof row === "string" ? row : row?.id + if (typeof id !== "string" || id.length === 0) continue + if (OA_UNAVAILABLE_IDS.has(id)) continue + if (rates && rates.size > 0 && !rates.has(id)) continue + const known = OA_FALLBACK_MODELS[id] + out[id] = officeAceModelEntry({ + id, + name: typeof row?.name === "string" && row.name.length > 0 ? row.name : id, + baseUrl, + context: known?.context ?? 1_000_000, + output: known?.output ?? 128_000, + }) + } + return out +} + +/** + * One usage window. + * + * An expired bucket is folded away (`aside`) and carries no amount/limit: its + * own total would become the denominator and read as "100% left". It takes no + * part in routing either, so the fold is all it needs to say. + */ +function officeAceWindow({ name, used, display, unit, resetsAt = "", expired = false, amount = 0, limit = 0 }) { + return { + name, + used, + display, + unit, + ...(resetsAt ? { resetsAt } : {}), + ...(expired ? { aside: true } : { amount, limit, span: 0 }), + } +} + +/** + * `GET {SUB}/v1/subscription` → magpie windows. + * + * Two kinds of bucket: `skus[].quotas[]` (`sku_attr_code === 'officeace_points'`) + * and `bonus_skus[]`. A `.trial` sku carries no expiry (the trial never + * expires — show it as it is, never guess a date); an expired bucket is marked + * `aside` so the card folds it away instead of letting it hold the top slot. + */ +async function fetchOfficeAceUsage(cred, fetcher = fetch) { + const r = await officeAceSigned(cred, `${OA_SUBSCRIPTION_BASE}${OA_SUBSCRIPTION_PATH}`, "GET", undefined, fetcher) + if (!r.ok) { + const detail = r.text.trim().slice(0, 200) + throw new Error(`订阅查询失败:HTTP ${r.status}${detail === "" ? "" : `:${detail}`}`) + } + let j + try { + j = JSON.parse(r.text) + } catch { + throw new Error("订阅查询失败:响应不是 JSON") + } + + const round = (n) => Math.round(n * 100) / 100 + const windows = [] + const nowMs = Date.now() + let plan = "" + + for (const sku of Array.isArray(j?.skus) ? j.skus : []) { + for (const q of Array.isArray(sku?.quotas) ? sku.quotas : []) { + if (q?.sku_attr_code !== "officeace_points") continue + const total = Number(q.sku_value) + const used = Number(q.current_value) + if (!Number.isFinite(total) || total <= 0) continue + const isTrial = String(sku.sku_code ?? "").endsWith(".trial") + const expiresAt = typeof q.expired_time === "string" && q.expired_time.length > 0 ? q.expired_time : null + const remaining = Math.max(0, total - used) + const expired = expiresAt !== null && !isTrial && new Date(expiresAt).getTime() <= nowMs + if (!plan && typeof sku.sku_name === "string") plan = sku.sku_name + windows.push(officeAceWindow({ + name: `${sku.sku_name ?? "套餐"} · 剩 ${round(remaining)}`, + used: Math.min(100, Math.max(0, Math.round((used / total) * 100))), + // a `.trial` sku carries no expiry: nothing to invent + resetsAt: isTrial || expiresAt === null ? "" : new Date(expiresAt).toISOString(), + display: `${round(remaining)} / ${round(total)}`, + unit: "积分", + expired, + amount: used, + limit: total, + })) + } + } + + for (const bonus of Array.isArray(j?.bonus_skus) ? j.bonus_skus : []) { + const points = Number(bonus?.points) + if (!Number.isFinite(points) || points <= 0) continue + const used = Number(bonus.current_value) + const remaining = Math.max(0, points - (Number.isFinite(used) ? used : 0)) + const expiresAt = typeof bonus.expired_time === "string" ? bonus.expired_time : null + const expired = expiresAt !== null && new Date(expiresAt).getTime() <= nowMs + windows.push(officeAceWindow({ + name: `${bonus.activity_name ?? "活动奖励"} · 剩 ${round(remaining)}`, + used: Math.min(100, Math.round(((points - remaining) / points) * 100)), + resetsAt: expiresAt === null ? "" : new Date(expiresAt).toISOString(), + display: `${round(remaining)} / ${round(points)}`, + unit: "积分", + expired, + amount: points - remaining, + limit: points, + })) + } + + return { plan, windows } +} + +/** + * `POST {SUB}/v1/subscription/bonus/claim` — the daily check-in. + * + * Claiming twice is idempotent: a 2xx with no `bonus_skus` is `done` (today's + * already taken), not a failure. A 2xx that does not parse is `done` too (the + * claim itself may have gone through). + */ +async function officeAceCheckin(cred, fetcher = fetch) { + if (!cred?.access_key_id || !cred?.security_token) { + return { outcome: "failed", message: "凭据缺失(access 或 securityToken),未发起签到" } + } + const r = await officeAceSigned(cred, `${OA_SUBSCRIPTION_BASE}${OA_BONUS_CLAIM_PATH}`, "POST", undefined, fetcher) + if (!r.ok || r.status < 200 || r.status >= 300) { + const detail = r.text.trim().slice(0, 200) + return { + outcome: "failed", + message: `HTTP ${r.status === 0 ? "(未发出/无响应)" : r.status}${detail === "" ? "" : `:${detail}`}`, + } + } + if (r.text.length === 0) return { outcome: "claimed", message: "已领取(响应为空)" } + let j + try { + j = JSON.parse(r.text) + } catch { + return { outcome: "done", message: "已领取(响应无法解析)" } + } + const skus = (Array.isArray(j?.bonus_skus) ? j.bonus_skus : []).map((s) => ({ + name: typeof s?.activity_name === "string" ? s.activity_name : "活动奖励", + points: Number(s?.points) || 0, + })) + const credit = skus.reduce((sum, s) => sum + s.points, 0) + if (skus.length === 0) return { outcome: "done", message: "今日已无新增可领" } + return { + outcome: "claimed", + ...(credit > 0 ? { credit } : {}), + message: skus.map((s) => `${s.name} +${s.points}`).join(";"), + } +} + +/** `officeace/` → ``: magpie names the model with the provider prefix. */ +function officeAceStripPrefix(body) { + if (typeof body !== "string" || body.length === 0) return body + try { + const parsed = JSON.parse(body) + if (typeof parsed?.model === "string" && parsed.model.startsWith("officeace/")) { + parsed.model = parsed.model.slice("officeace/".length) + return JSON.stringify(parsed) + } + } catch { + // not JSON: pass it through + } + return body +} + +/** `base64(appKey:appSecret)` — MaaS takes Basic, the AI SDK only sends Bearer. */ +function basicAuthorization(cred) { + return "Basic " + Buffer.from(`${cred.model_app_key}:${cred.model_app_secret}`).toString("base64") +} + +const oaBasicFingerprint = (cred) => `${cred?.model_app_key ?? ""}:${cred?.model_app_secret ?? ""}:${cred?.maas_base_url ?? ""}` + +/** Is this 4xx the gateway refusing the Basic pair itself? */ +function isOfficeAceBasicRejection(status, text) { + if (status === 401 || status === 403) return true + if (status < 400 || status >= 500) return false + return /APIG\.1009|invalid.*(app|key|secret)|appkey|app_key/i.test(text ?? "") +} + +/** + * One chat request to OfficeAce's MaaS: Bearer is rewritten to Basic, the + * provider prefix stripped. A 401 (or the gateway naming the Basic pair) + * renews the credential once and sends the request again — but only when the + * renewal actually changed the pair; retrying the same pair would just be the + * same refusal with more latency. + */ +async function officeAceChatFetch({ input, init, credential, renew, fetcher = fetch }) { + const req = input instanceof Request ? input : null + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : (req?.url ?? "") + let body = init?.body + if (body === undefined && req) body = await req.text() + body = officeAceStripPrefix(body) + const target = `${officeAceMaasBase(credential)}${OA_CHAT_PATH}` + const signal = init?.signal ?? req?.signal ?? AbortSignal.timeout(OA_TOKEN_TIMEOUT_MS) + + const call = (cred) => + fetcher(target, { + method: "POST", + headers: { "content-type": "application/json", authorization: basicAuthorization(cred) }, + body, + signal, + }) + + const response = await call(credential) + if (response.ok) return response + + const text = await response.text().catch(() => "") + let status = response.status + let said = text + let renewal = "not-attempted" + if (renew && (status === 401 || isOfficeAceBasicRejection(status, said))) { + const before = oaBasicFingerprint(credential) + let renewed + try { + renewed = await renew() + } catch { + renewed = undefined + } + if (!renewed) renewal = "unreadable" + else if (oaBasicFingerprint(renewed) !== before) { + renewal = "changed" + const retry = await call(renewed) + if (retry.ok) return retry + status = retry.status + said = await retry.text().catch(() => "") + } else { + renewal = "unchanged" + } + } + + return Response.json( + { + error: { + type: "provider_error", + message: + `OfficeAce(华为 MaaS)返回 HTTP ${status}:${said.slice(0, 200)}(${officeAceDiagnose(status, renewal)})`, + provider_status: status, + credential_rejected: isOfficeAceBasicRejection(status, said), + renewal_outcome: renewal, + }, + }, + { status: status >= 400 ? status : 502 }, + ) +} + +/** One sentence a person can act on. */ +function officeAceDiagnose(status, renewal) { + if (status === 401 || status === 403) { + if (renewal === "changed") return "续期后仍然是 401,请重新登录" + if (renewal === "unchanged") return "凭据没变,重试无意义,请重新登录" + if (renewal === "unreadable") return "续期失败,请重新登录" + return "凭据被拒,请重新登录" + } + if (status === 404) return "模型名不对,或该模型不在这个账号的套餐里" + if (status === 429) return "被限流,稍后重试或换账号" + if (status >= 500) return "上游服务错误" + return "请求被拒" +} + +// ---- the two records of one account -------------------------------------- +// +// magpie keeps accounts per provider id, and a provider's hooks only ever see +// that provider's own account — there is no call to read another provider's +// record. So the two records of one Huawei Cloud account are written the one +// way the host offers: `client.auth.set` from inside a sign-in or a renewal. +// +// What is remembered here is in this module, shared by the package's two +// plugins (one process, one module): which accounts each provider has, which +// key this package wrote, and the renewal in flight for each refresh chain. A +// record is never written to a key another account may sit at, and a record +// that already holds the account is never written again. +// +// Each record holds its own refresh token: a sign-in writes this card's record +// only, so the two cards of one account are two chains — an `officeace-auth` +// record was issued to `pdp5_for_agentarts`, a CodeArts record to +// `codearts-agent`. Each is only ever renewed with its own token, a renewal +// writes no other record (the host's `auth.set` creates a record that is not +// there), and a failed renewal fails instead of borrowing another chain's. + +/** provider id → the identities its accounts were seen as. */ +const seenProviderAccounts = new Map() +/** refresh chain → { from, promise }: the renewal in flight. */ +const renewalGates = new Map() +/** refresh token → the lineage it belongs to (a rotation keeps its parent's). */ +const refreshLineages = new Map() +/** How long a spent token's renewal stands in for it. */ +const CHAIN_LIVE_MS = 10 * 60 * 1000 +/** How many token lineages are remembered: one per rotation, oldest dropped. */ +const LINEAGE_CAP = 1024 + +/** A stable 8-hex suffix of the account's identity — a key no other account gets. */ +function accountKeySuffix(identity) { + return createHash("sha256").update(String(identity)).digest("hex").slice(0, 8) +} + +/** The OAuth client a credential's refresh token was issued to. */ +function refreshClientOf(cred) { + // A canonical credential with no marker of its own is this package's own shape + // (the CodeArts reader stamps it); only the old OfficeAce chain says pdp5. + return firstOf(cred?.oauth_client) === OA_AGENTARTS_CLIENT_ID ? OA_AGENTARTS_CLIENT_ID : "codearts-agent" +} + +/** + * The lineage a refresh token belongs to. A token never seen is its own + * lineage; a rotation answers a new token for the same chain, and + * `linkRotation` writes that down — so a record still holding the spent token + * is known to belong to the chain that replaced it. + */ +function lineageOf(token) { + const held = refreshLineages.get(token) + if (held) return held + const fresh = createHash("sha256").update(`refresh-chain\n${token}`).digest("hex").slice(0, 16) + rememberLineage(token, fresh) + return fresh +} + +function rememberLineage(token, lineage) { + if (!token || !lineage) return + if (!refreshLineages.has(token) && refreshLineages.size >= LINEAGE_CAP) { + // Oldest first. Forgetting a lineage only means a chain is not recognised — + // that record then spends its own token and fails; two chains never merge. + const oldest = refreshLineages.keys().next().value + if (oldest !== undefined) refreshLineages.delete(oldest) + } + refreshLineages.set(token, lineage) +} + +/** + * The refresh chain a credential's token belongs to: the OAuth client it was + * issued to, plus the token's lineage. STS spends a refresh token once, so the + * chain is the unit of coordination — and a token issued to one client must + * never be sent to the other, which is why the client is in the key too. + * + * The token, not the account: two records of one Huawei Cloud account can sit + * on two chains, and one must never be renewed with the other's credential. + */ +function refreshChainOf(cred, client = refreshClientOf(cred)) { + const token = firstOf(cred?.refresh_token) + if (!token) return { key: "", client, token, lineage: "" } + const lineage = lineageOf(token) + return { key: `${client}\n${lineage}`, client, token, lineage } +} + +/** A rotation answers a new refresh token for the same chain: remember the parent. */ +function linkRotation(cred, next) { + const from = firstOf(cred?.refresh_token) + const to = firstOf(next?.refresh_token) + if (!from || !to || from === to) return + rememberLineage(to, lineageOf(from)) +} + +function noteProviderAccount(provider, identity) { + if (!provider || !identity) return + const set = seenProviderAccounts.get(provider) ?? new Set() + set.add(identity) + seenProviderAccounts.set(provider, set) +} + +/** The provider was listed with no account at all: it has none, as far as this process knows. */ +function noteProviderEmpty(provider) { + // No accounts: any identity this process saw before is gone from the provider + // now, so the set is emptied (a stale identity is not an account). + seenProviderAccounts.set(provider, new Set()) +} + +/** + * Where a record for `identity` may be written under `provider`: the provider's + * own key while it has no account at all, otherwise a key of its identity's + * own that no account can be sitting at. `null` when that provider already has + * this account (writing again would add a second record of one account). + */ +function recordKeyFor(provider, identity) { + const known = seenProviderAccounts.get(provider) + if (known?.has(identity)) return null + if (known && known.size === 0) return provider + return `${provider}#${accountKeySuffix(identity)}` +} + +/** Give the credential the MaaS fields OfficeAce needs (one read per account). */ +async function withOfficeAceMaas(cred, fetcher = fetch) { + if (cred.model_app_key) return cred + const info = await officeAceMaasInfo(cred, fetcher).catch(() => null) + // An answer without a pair means "MaaS is not opened for this account": it is + // not a reason to take a pair the credential already has away. + if (!info?.model_app_key) return cred + return { ...cred, ...info } +} + +/** + * Write one account's record under `target`, in that provider's own shape. + * Used at a sign-in, so the card that signed in keeps its record where a later + * renewal can find it again. Only ever called for the card's own provider: + * writing one sign-in into two records is what `STS5.1806` was about. + */ +async function writeProviderRecord(client, target, cred, fetcher = fetch) { + const identity = accountIdentityOf(cred).id + if (!identity || !client?.auth?.set) return null + const key = recordKeyFor(target, identity) + if (!key) return null + const body = target === OFFICEACE_PROVIDER + ? officeAceRecordBody(await withOfficeAceMaas(cred, fetcher)) + : codeArtsRecordBody(cred) + try { + await client.auth.set({ path: { id: key }, body }) + } catch { + return null + } + return { key, body } +} + +/** + * Renew one Huawei Cloud credential, once per refresh chain. + * + * One credential, renewed once: callers holding the same record (same chain, same + * token) share a single in-flight renewal, so STS is asked once and everyone gets + * that answer. Records on different chains (an `officeace-auth` record beside a + * CodeArts one) never meet in here at all — each spends its own token, and a + * renewal that fails is a failure, never another chain's credential. + */ +function renewSharedCredential(cred, run, client = refreshClientOf(cred)) { + const token = firstOf(cred?.refresh_token) + const chain = refreshChainOf(cred, client) + if (!chain.key) return Promise.resolve().then(run) + const held = renewalGates.get(chain.key) + if (held && held.from === token) return held.promise + const promise = Promise.resolve() + .then(run) + .then((next) => { + // A rotation rebuilds only the STS half of a credential: what the account + // carries besides it (its MaaS pair, its phone, its session) stays. + for (const k of ["model_app_key", "model_app_secret", "maas_base_url", "user_phone", "domain_id", "oauth_client"]) { + if (cred[k] && !next[k]) next[k] = cred[k] + } + // The new token belongs to the same chain: a record still holding the + // spent one is known to be on it (the gate above). Nothing else is + // remembered, so a credential a hook merely saw can never stand in for a + // newer one. + linkRotation(cred, next) + return next + }) + .finally(() => { + if (renewalGates.get(chain.key)?.promise === promise) renewalGates.delete(chain.key) + }) + renewalGates.set(chain.key, { from: token, promise }) + return promise +} + +/** + * Renew a credential through the OAuth client that issued its refresh token: + * this package's CodeArts flow (verifier + DPoP key, no client change), or the + * old OfficeAce flow (`pdp5_for_agentarts`, DPoP key only). + */ +async function renewOfficeAceCredential(cred, fetcher = fetch) { + if (!cred.refresh_token) { + throw Object.assign(new Error("OfficeAce 凭据无法续期(没有 refresh token),请重新登录"), { signIn: "expired" }) + } + if (!cred.dpop_private_key_jwk) { + throw Object.assign(new Error("OfficeAce 凭据无法续期(DPoP 私钥缺失),请重新登录"), { signIn: "expired" }) + } + const keyPair = keyPairFromStoredJwk(cred.dpop_private_key_jwk) + const client = refreshClientOf(cred) + const token = client === "codearts-agent" + ? await requestToken({ + client_id: CLIENT_ID, + code_verifier: firstOf(cred.code_verifier), + grant_type: GRANT_REFRESH_TOKEN, + refresh_token: firstOf(cred.refresh_token), + }, keyPair, fetcher, "OfficeAce") + : await requestToken({ + client_id: OA_AGENTARTS_CLIENT_ID, + grant_type: GRANT_REFRESH_TOKEN, + refresh_token: firstOf(cred.refresh_token), + }, keyPair, fetcher, "OfficeAce") + const next = credentialFromTokenResponse(token, firstOf(cred.code_verifier), keyPair) + // What a rotation does not rebuild: the account's one upstream session, its + // identity, its phone and the MaaS credentials behind the preserved appKey. + for (const k of ["session_id", "domain_id", "user_phone", "model_app_key", "model_app_secret", "maas_base_url", "oauth_client"]) { + if (cred[k]) next[k] = cred[k] + } + if (!next.refresh_token) next.refresh_token = cred.refresh_token + if (!next.oauth_client) next.oauth_client = client + // The MaaS Basic pair is minted per permission check and can rotate with the + // session: read it again when this account has one. Best effort — the stored + // pair stands when the CLAW call is down. + if (cred.model_app_key) { + const info = await fetchOfficeAceMaasInfo(next, fetcher).catch(() => null) + if (info?.model_app_key) { + Object.assign(next, info) + oaMaasCache.set(accountIdentityOf(next).id || next.access_key_id, { at: Date.now(), info }) + } + } + return next +} + +/** + * Is this credential close enough to its expiry to renew first? + */ +function nearOfficeAceExpiry(cred) { + const at = Date.parse(firstOf(cred?.expires_at)) + return Number.isFinite(at) && at - Date.now() <= OA_REFRESH_LEAD_MS +} + +/** + * Store an OfficeAce record for the account this hook runs for (its own + * scope's key), keeping the account's stored `accountId` / `uid`. + * + * magpie hangs a user's own name, proxy and gateway key for an account off + * `accountId`; rewriting it (a phone, or a domain id over the phone an older + * `officeace-auth` stored) would re-key the account. So a stored value stands, + * and one computed from the credential is only filled in when there is none — + * as CodeArts' own `persistCredential` does. + */ +async function persistOfficeAceRecord(client, cred, prev) { + const body = officeAceRecordBody(cred) + const accountId = firstOf(prev?.accountId, body.accountId) + const uid = firstOf(prev?.uid, body.uid) + const record = { + ...body, + ...(accountId ? { accountId } : {}), + ...(uid ? { uid } : {}), + } + try { + await client?.auth?.set?.({ path: { id: OFFICEACE_PROVIDER }, body: record }) + } catch { + /* best effort: the next renewal writes it again */ + } + return record +} + +/** + * OfficeAce — the second provider of this package, signed in on its own card + * through Huawei Cloud OAuth like `codearts`, with a record and a refresh token + * of its own. + * + * Provider id `officeace`: the id `officeace-auth` used, so the accounts signed + * in through that package are read from where magpie already keeps them + * (`officeace`, `officeace#xxxxxx`) and nobody signs in again. + */ +export const OfficeAceAuthPlugin = async ({ client } = {}, options = {}) => { + const fetcher = typeof options?.fetch === "function" ? options.fetch : fetch + const log = (message, level = "info") => { + try { + client?.app?.log?.({ service: "officeace", level, message }) + } catch { + /* no log channel */ + } + } + /** This account's credential, as either shape declares it. */ + const credential = (auth) => officeAceCredentialOf(auth) + const renewNow = (cred) => renewSharedCredential(cred, () => renewOfficeAceCredential(cred, fetcher)) + + return { + // The provider and the models it shows before anyone is signed in. + config: async (config) => { + config.provider ??= {} + config.provider[OFFICEACE_PROVIDER] ??= {} + const p = config.provider[OFFICEACE_PROVIDER] + p.name ??= "OfficeAce" + p.npm ??= OFFICEACE_NPM + p.api ??= `${OA_MAAS_MARKET_BASE}/v2` + p.models = { ...officeAceStaticModels(), ...(p.models ?? {}) } + }, + + // The account's own catalog: the billable list, minus the ids that always 404. + provider: { + id: OFFICEACE_PROVIDER, + async models(provider, { auth } = {}) { + let cred = credential(auth) + if (!cred) { + // No account of its own: nothing is adopted here. An OfficeAce record + // is only ever written by this card's own sign-in — an account the + // user signed out of must not come back on the next listing. + noteProviderEmpty(OFFICEACE_PROVIDER) + return provider.models + } + const identity = accountIdentityOf(cred).id + if (identity) noteProviderAccount(OFFICEACE_PROVIDER, identity) + + if (!cred.model_app_key) { + const healed = await withOfficeAceMaas(cred, fetcher) + if (healed.model_app_key) cred = healed + } + // The catalog and chat are behind the MaaS appKey; without it the + // static table is all there is (and it is honest: nobody knows yet). + if (!cred.model_app_key) return provider.models + + const base = officeAceMaasBase(cred) + try { + const rows = await fetchOfficeAceCatalog(cred, fetcher) + if (!rows.length) return provider.models + let rates = null + try { + rates = await fetchOfficeAceTokenRates(cred, fetcher) + } catch { + rates = null + } + // An empty rates table means "never read", not "no model is billable": + // fall back to the static table rather than the registry's 26 ids, 19 + // of which the user can select and then only fail at chat. + if (!rates || rates.size === 0) { + log("倍率表不可用(空表)—— 目录降级为静态表,不列出注册表占位 id", "warn") + return provider.models + } + const live = officeAceLiveModels(rows, base, rates) + if (Object.keys(live).length === 0) { + log("倍率表与模型目录零交集 —— 退回静态表", "warn") + return provider.models + } + return live + } catch (e) { + log(`目录拉取失败,回退静态表:${e?.message ?? e}`, "warn") + if (/401|403|unauthorized|被拒/i.test(String(e?.message))) { + throw Object.assign(new Error("OfficeAce 登录已失效,请重新登录"), { signIn: "expired" }) + } + return provider.models + } + }, + }, + + auth: { + provider: OFFICEACE_PROVIDER, + icon: OFFICEACE_ICON, + maxConcurrency: 3, + refreshLead: OA_REFRESH_LEAD_MS, + + methods: [ + { + type: "oauth", + label: "Sign in with Huawei Cloud", + /** + * A sign-in of this card's own, not the CodeArts card's: the STS + * triple it yields signs both vendors' APIs (measured), but a Huawei + * Cloud refresh token is spent once, so a second record holding this + * one would sign this card out at its renewal (`STS5.1806`). + * + * `authorize()` returns at once; the waiting happens in `callback()`. + */ + async authorize() { + const flow = await startOAuthFlow(fetcher, "OfficeAce") + return { + url: flow.loginUrl, + instructions: + "Sign in to Huawei Cloud in the browser. This signs in OfficeAce only — the CodeArts card has its own sign-in. This window closes itself when done.", + method: "auto", + async callback() { + try { + const outcome = await flow.result + const cred = safeJson(outcome.access) + if (!cred?.access_key_id) { + return { type: "failed", error: "Huawei Cloud did not return a credential" } + } + // The card's name (its phone), and OfficeAce's MaaS credentials. + const identified = { ...cred, ...(await accountPhoneField(cred, fetcher)) } + const withMaas = await withOfficeAceMaas(identified, fetcher) + // This sign-in writes this card's record only — the two cards + // never share a refresh token, which is spent once. + await writeProviderRecord(client, OFFICEACE_PROVIDER, withMaas, fetcher) + return { ...officeAceRecordBody(withMaas), type: "success" } + } catch (e) { + return { type: "failed", error: e?.message ?? String(e) } + } finally { + await flow.close() + } + }, + } + }, + }, + ], + + /** Renew this account's credential — this card's record only. */ + async refresh(auth) { + const cred = credential(auth) + if (!cred) return undefined + const next = await renewNow(cred) + if (!next) return undefined + const body = officeAceRecordBody(next) + // magpie merges this into the stored record. `accountId` is what the + // user's own name, proxy and gateway key for the account hang off, so a + // renewal never renames one: a stored value stands (phone or domain id, + // as `officeace-auth` wrote it), and one is only filled in when missing. + return { + access: body.access, + refresh: body.refresh, + expires: body.expires, + ...(auth.accountId || !body.accountId ? {} : { accountId: body.accountId }), + ...(auth.uid || !body.uid ? {} : { uid: body.uid }), + } + }, + + /** Rewrite Bearer to Basic, strip the provider prefix, renew once on a 401. */ + async loader(getAuth) { + const stored = await getAuth() + let cred = credential(stored) + if (!cred) return {} + const identity = accountIdentityOf(cred).id + if (identity) noteProviderAccount(OFFICEACE_PROVIDER, identity) + + if (!cred.model_app_key) { + const healed = await withOfficeAceMaas(cred, fetcher) + if (healed.model_app_key) { + cred = healed + await persistOfficeAceRecord(client, cred, stored) + } + } + // Signed in, but MaaS was never opened for this account: say so instead + // of sending an empty Basic header upstream (a 400 that reads like a + // broken model). Usage and the check-in work off the STS triple alone. + if (!cred.model_app_key) { + return { + async fetch() { + return Response.json( + { + error: { + message: + "OfficeAce 账号已登录,但还没有接入华为云 MaaS(凭据里没有 modelAppKey)。" + + "请在 OfficeAce 客户端完成「接入华为云 MaaS 模型」后重试;额度与签到不受影响,已经可以正常使用。", + type: "officeace_maas_not_linked", + code: "MaaSNotLinked", + }, + }, + { status: 400, headers: { "content-type": "application/json" } }, + ) + }, + } + } + + return { + // Empty: the URL is built from the credential's own MaaS base. + baseURL: "", + apiKey: "", + async fetch(input, init) { + const freshRecord = await getAuth().catch(() => null) + const fresh = credential(freshRecord) ?? cred + return officeAceChatFetch({ + input, + init, + credential: fresh, + fetcher, + renew: async () => { + try { + const next = await renewNow(fresh) + if (next) { + await persistOfficeAceRecord(client, next, freshRecord ?? stored) + } + return next + } catch (e) { + log(`续期失败:${e?.message ?? e}`, "warn") + return undefined + } + }, + }) + }, + } + }, + + /** The subscription's buckets: plan quotas and activity bonuses. */ + async usage(getAuth) { + const cred = credential(await getAuth()) + if (!cred) return { error: "未登录", windows: [] } + try { + const u = await fetchOfficeAceUsage(cred, fetcher) + // The phone is a display name, so it goes here only — never into the + // record's `accountId` (see officeAceIdentityOf). + const user = firstOf(cred.user_phone, officeAceIdentityOf(cred).accountId) + return { + plan: u.plan || "OfficeAce", + ...(user ? { user } : {}), + windows: u.windows, + } + } catch (e) { + return { error: String(e?.message ?? e).slice(0, 300), windows: [] } + } + }, + + /** The daily claim; claiming twice is idempotent (a 2xx with no skus is `done`). */ + async checkin(getAuth) { + const stored = await getAuth() + const cred = credential(stored) + if (!cred) return { outcome: "failed", message: "未登录" } + try { + let use = cred + if (nearOfficeAceExpiry(cred) && cred.refresh_token) { + try { + use = (await renewNow(cred)) ?? cred + if (use !== cred) await persistOfficeAceRecord(client, use, stored) + } catch { + /* try with what is stored */ + } + } + const result = await officeAceCheckin(use, fetcher) + if (result.outcome === "claimed") log(`签到:${result.message ?? "已领取"}`) + return result + } catch (e) { + return { outcome: "failed", message: String(e?.message ?? e).slice(0, 300) } + } + }, + }, + + /** Per-request header: the same conversation keeps one upstream session. */ + "chat.headers": async (input, output) => { + const id = input?.model?.providerID ?? input?.provider?.info?.id + if (id !== OFFICEACE_PROVIDER || !input?.sessionID) return + output.headers["x-officeace-session"] = String(input.sessionID).slice(0, 128) + }, + } +} + +// for tests (never a plugin: magpie only calls exported functions) +export const _officeace = { + OFFICEACE_PROVIDER, OA_FALLBACK_MODELS, OA_UNAVAILABLE_IDS, OA_MAAS_MARKET_BASE, + OA_SUBSCRIPTION_BASE, OA_CLAW_BASE, OA_PERMISSION_PATH, OA_TOKEN_RATES_PATH, + officeAceCredentialOf, officeAceCredentialRecord, officeAceRecordBody, codeArtsRecordBody, + officeAceIdentityOf, officeAceMaasBase, officeAceModelEntry, officeAceStaticModels, + officeAceLiveModels, fetchOfficeAceUsage, officeAceCheckin, officeAceStripPrefix, + officeAceChatFetch, officeAceDiagnose, isOfficeAceBasicRejection, oaBasicFingerprint, + fetchOfficeAceTokenRates, fetchOfficeAceCatalog, fetchOfficeAceMaasInfo, officeAceMaasInfo, + signOfficeAceV11, oaSdkDate, officeAceSigned, basicAuthorization, isCodeArtsClient, + renewOfficeAceCredential, renewSharedCredential, nearOfficeAceExpiry, + accountKeySuffix, recordKeyFor, writeProviderRecord, + refreshClientOf, refreshChainOf, refreshLineages, lineageOf, linkRotation, rememberLineage, + noteProviderAccount, noteProviderEmpty, seenProviderAccounts, + renewalGates, withOfficeAceMaas, persistOfficeAceRecord, + OFFICEACE_ICON, +} + + diff --git a/packages/codearts/index.test.mjs b/packages/codearts/index.test.mjs index 1e162af..9848950 100644 --- a/packages/codearts/index.test.mjs +++ b/packages/codearts/index.test.mjs @@ -12,7 +12,11 @@ import net from "node:net" import os from "node:os" import path from "node:path" -import { CodeArtsAuthPlugin, _internal as x } from "./index.mjs" +import { CodeArtsAuthPlugin, OfficeAceAuthPlugin, _internal as x, _officeace as oa } from "./index.mjs" + +// The record-key file lives beside the check-in ledger; a test must never write +// the real ~/.config (a fresh CI home hides this, a developer's does not). +process.env.MAGPIE_CODEARTS_RECORDS = path.join(os.tmpdir(), `codearts-records-test-${process.pid}.json`) // Never the real ledger in ~/.config/magpie: every plugin made here keeps its // check-ins in a scratch file of its own. @@ -2537,3 +2541,1166 @@ test("a sign-in names the account by its URN while the card shows the phone (rev assert.equal(out.accountId, urn) assert.equal(JSON.parse(out.access).user_phone, "138****8000") }) + +// ═══════════════════════════════════════════════════════════════════════════ +// OfficeAce — the package's second provider, signed in on its own card. These +// tests are about the two records one account can have: the one `officeace-auth` +// already wrote, the one this package's own sign-in writes, and the renewal +// that must not spend a refresh token twice. +// ═══════════════════════════════════════════════════════════════════════════ + +const oaB64u = (o) => Buffer.from(JSON.stringify(o)).toString("base64url") + +/** The refresh token of one Huawei Cloud account: a JWT whose `user_profile` names it. */ +const oaRefreshToken = (claims = {}) => + `h.${oaB64u({ user_profile: JSON.stringify({ principal_urn: "iam::d1:user:hw1", principal_id: "pid-oa", account_id: "01a1642ad2ae7f93bf6387ad2fc5f09e", ...claims }) })}.s` + +/** + * A record exactly as the `officeace-auth` package stored it — the shape magpie + * keeps in `plugin-auth.json` under key `officeace`. Values are fake; the field + * names are the ones that package wrote. + */ +async function officeAceAuthRecord(overrides = {}, identity = "iam::d1:user:hw1") { + const keyPair = await x.generateDpopKeyPair() + // The identity is the one the refresh token's claim names: one per test, so a + // rates or MaaS read one test made is never taken for another's. + const refresh = oaRefreshToken({ principal_urn: identity }) + const credential = { + modelAppKey: "app-key", + modelAppSecret: "app-secret", + maasBaseUrl: "", + access: "HSTAOZ3JN3WWYF3L", + secret: "9hefA4eK2KTT", + securityToken: "ST-LEGACY", + projectId: "", + expiresAt: "2031-01-01T00:00:00Z", + refreshToken: refresh, + codeVerifier: "verifier", + dpopPrivateJwk: keyPair.privateKeyJwk, + accountId: "01a1642ad2ae7f93bf6387ad2fc5f09e", + user_phone: "189****8051", + ...overrides, + } + return { + credential, + record: { + type: "oauth", + access: JSON.stringify(credential), + refresh, + expires: Date.parse("2031-01-01T00:00:00Z"), + accountId: "189****8051", + uid: identity, + }, + } +} + +/** What the subscription endpoint answers: a plan, a trial, an expired plan, a bonus. */ +const officeAceSubscriptionBody = () => ({ + domain_id: "01a1642ad2ae7f93bf6387ad2fc5f09e", + subscribe_status: "SUBSCRIBED", + skus: [ + { + sku_code: "officeace_personal_trial.trial", + sku_name: "个人体验版", + quotas: [{ sku_attr_code: "officeace_points", sku_value: 500, current_value: 0, expired_time: "" }], + }, + { + sku_code: "officeace_personal_monthly", + sku_name: "个人版", + quotas: [{ sku_attr_code: "officeace_points", sku_value: 4000, current_value: 1780, expired_time: "2031-01-01T00:00:00Z" }], + }, + { + sku_code: "officeace_personal_old", + sku_name: "旧套餐", + quotas: [{ sku_attr_code: "officeace_points", sku_value: 100, current_value: 100, expired_time: "2020-01-01T00:00:00Z" }], + }, + ], + bonus_skus: [{ activity_name: "新用户专属福利", points: 4000, current_value: 1780, expired_time: "2031-01-01T00:00:00Z" }], +}) + +/** A fetcher that records every call and lets the test answer any URL. */ +function oaFetcher(answer) { + const seen = [] + const fetcher = async (url, init = {}) => { + seen.push({ url: String(url), headers: new Headers(init.headers ?? {}), body: init.body }) + const made = answer ? answer(String(url), init) : undefined + return made ?? new Response("{}", { status: 200 }) + } + return { fetcher, seen } +} + +const oaClient = (calls = []) => ({ + app: { log: async () => {} }, + auth: { + set: async (opts) => { + calls.push(opts) + return { data: true } + }, + }, +}) + +/** The catalog the registry answers: 26 entries, most of them un-callable. */ +const oaCatalogBody = () => ({ + data: [ + { id: "glm-5.3", name: "GLM-5.3" }, + { id: "kimi-k3", name: "Kimi-K3" }, + { id: "deepseek-v4.1-flash-0930", name: "DeepSeek-V4.1-Flash" }, + { id: "deepseek-v4.1-flash-1017", name: "DeepSeek-V4.1-Flash-1017" }, + { id: "deepseek-v4.1-flash-bnt", name: "DeepSeek-V4.1-Flash-BNT" }, + { id: "deepseek-v4-pro", name: "DeepSeek-V4-Pro" }, + ], +}) + +/** The billable list: names with the trailing newline the vendor writes. */ +const oaRatesBody = () => ({ + models: [ + { model_name: "glm-5.3\n", cost_coefficient: 0.18 }, + { model_name: "kimi-k3", cost_coefficient: 1 }, + { model_name: "deepseek-v4.1-flash-0930", cost_coefficient: 1.5 }, + { model_name: "deepseek-v4.1-flash-1017", cost_coefficient: 0.1 }, + { model_name: "glm-5", cost_coefficient: 0.5 }, + ], +}) + +/** The account's MaaS credentials, as the CLAW permission check answers them. */ +const oaMaasAnswer = (key = "app-key", secret = "app-secret") => + new Response( + JSON.stringify({ + subscription: { + model_info: { model_auth_info: { model_app_key: key, model_app_secret: secret }, model_api_url_base: "" }, + }, + }), + { status: 200 }, + ) + +// ---- the migration path: an officeace-auth record keeps working ------------ + +test("an account signed in through officeace-auth is read as it is, no second sign-in", async () => { + const { record } = await officeAceAuthRecord() + // The record is read back as a credential this card can use. + const cred = oa.officeAceCredentialOf(record) + assert.equal(cred.access_key_id, "HSTAOZ3JN3WWYF3L") + assert.equal(cred.secret_access_key, "9hefA4eK2KTT") + assert.equal(cred.security_token, "ST-LEGACY") + assert.equal(cred.model_app_key, "app-key") + assert.equal(cred.model_app_secret, "app-secret") + assert.equal(cred.user_phone, "189****8051") + // ... and it is the old OfficeAce flow's refresh token, renewed that way. + assert.equal(cred.oauth_client, "pdp5_for_agentarts") + assert.equal(oa.isCodeArtsClient(cred), false) + + // Every hook works off it. The subscription read is V11-signed with it. + const { fetcher, seen } = oaFetcher((url) => + url.includes("/v1/subscription") ? new Response(JSON.stringify(officeAceSubscriptionBody()), { status: 200 }) : undefined, + ) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const usage = await plugin.auth.usage(async () => record) + assert.equal(usage.plan, "个人体验版") + assert.equal(usage.user, "189****8051") + assert.equal(usage.windows.length, 4) + assert.match( + seen[0].headers.get("authorization"), + /^V11-HMAC-SHA256 Credential=HSTAOZ3JN3WWYF3L\/\d{8}\/cn-southwest-2\/apic, SignedHeaders=/, + ) +}) + +test("the record officeace-auth wrote is named by the vendor's stable id, never by the phone", async () => { + const { credential, record } = await officeAceAuthRecord() + const identity = oa.officeAceIdentityOf(oa.officeAceCredentialOf(record)) + // accountId is what a user's own name, proxy and gateway key hang off (#483, + // magpie#4416): the vendor's domain id, never the masked phone. The phone is + // a display name and shows up only in usage().user. + assert.deepEqual(identity, { accountId: "01a1642ad2ae7f93bf6387ad2fc5f09e", uid: "01a1642ad2ae7f93bf6387ad2fc5f09e" }) + // Writing it back gives the same shape, so the two packages can share a record. + const again = oa.officeAceCredentialOf({ access: JSON.stringify(oa.officeAceCredentialRecord(oa.officeAceCredentialOf(record))) }) + assert.equal(again.access_key_id, credential.access) + assert.equal(again.model_app_key, credential.modelAppKey) + assert.equal(again.security_token, credential.securityToken) + assert.equal(oa.isCodeArtsClient(again), false) +}) + +// ---- the signer that was measured against the live gateway ---------------- + +test("the subscription signer is the V11 signature measured against the live gateway", () => { + const cred = { access_key_id: "HSTAOZ3JN3WWYF3L", secret_access_key: "9hefA4eK2KTT", security_token: "hQpjbi1ub3J0aC00AQAA" } + const url = "https://officeace.cn-southwest-2.huaweicloud-agentarts.com/v1/subscription" + // The vector was produced by the signer OfficeAce's own package uses, with the + // clock frozen; that signature answered HTTP 200 on 2026-10-30. + const headers = oa.signOfficeAceV11(url, cred, "GET", undefined, "20261030T081500Z") + assert.equal( + headers.Authorization, + "V11-HMAC-SHA256 Credential=HSTAOZ3JN3WWYF3L/20261030/cn-southwest-2/apic, " + + "SignedHeaders=host;x-sdk-date;x-security-token;x-subscription-type, " + + "Signature=b57c95252df55e636edc8c31841b5f8dd064d66d40280ed19ffa4eecccb9adaf", + ) + assert.equal(headers["X-Sdk-Date"], "20261030T081500Z") + assert.equal(headers["X-Security-Token"], "hQpjbi1ub3J0aC00AQAA") + assert.equal(headers["x-subscription-type"], "v2") + // A claim carries a body: content-type takes part in the signature. + const post = oa.signOfficeAceV11(`${url}/bonus/claim`, cred, "POST", undefined, "20261030T081500Z") + assert.match(post.Authorization, /SignedHeaders=content-type;host;x-sdk-date;x-security-token;x-subscription-type,/) +}) + +// ---- usage: the three kinds of bucket, each with its own semantics -------- + +test("usage reads plan, trial and bonus buckets apart, and folds an expired one away", async () => { + const { record } = await officeAceAuthRecord() + const { fetcher } = oaFetcher((url) => + url.includes("/v1/subscription") ? new Response(JSON.stringify(officeAceSubscriptionBody()), { status: 200 }) : undefined, + ) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const { windows } = await plugin.auth.usage(async () => record) + + const trial = windows.find((w) => w.name.startsWith("个人体验版")) + assert.equal(trial.display, "500 / 500") + assert.equal(trial.amount, 0) + assert.equal(trial.limit, 500) + // a `.trial` sku carries no expiry: the window must not invent one + assert.equal("resetsAt" in trial, false) + + const plan = windows.find((w) => w.name.startsWith("个人版")) + assert.equal(plan.display, "2220 / 4000") + assert.equal(plan.amount, 1780) + assert.equal(plan.limit, 4000) + assert.equal(plan.used, 45) + assert.equal(plan.resetsAt, "2031-01-01T00:00:00.000Z") + + const old = windows.find((w) => w.name.startsWith("旧套餐")) + assert.equal(old.aside, true) + // an aside window takes no part in routing: amount/limit would read as 100% left + assert.equal(old.amount, undefined) + assert.equal(old.limit, undefined) + assert.equal(old.display, "0 / 100") + + const bonus = windows.find((w) => w.name.startsWith("新用户专属福利")) + assert.equal(bonus.display, "2220 / 4000") + assert.equal(bonus.used, 45) +}) + +test("a failed usage read is said, never shown as an empty account", async () => { + const { record } = await officeAceAuthRecord() + const { fetcher } = oaFetcher((url) => + url.includes("/v1/subscription") ? new Response("APIGW.0101 API not found", { status: 404 }) : undefined, + ) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const usage = await plugin.auth.usage(async () => record) + assert.deepEqual(usage.windows, []) + assert.match(usage.error, /订阅查询失败:HTTP 404/) +}) + +// ---- the daily check-in: a repeat claim is `done`, not a failure ---------- + +test("checkin tells a claim, a repeat and a real failure apart", async () => { + const { record } = await officeAceAuthRecord() + const answers = [ + new Response(JSON.stringify({ bonus_skus: [{ activity_name: "每日签到有礼", points: 100 }] }), { status: 200 }), + new Response(JSON.stringify({ bonus_skus: [] }), { status: 200 }), + new Response("boom", { status: 500 }), + ] + let i = 0 + const { fetcher } = oaFetcher(() => answers[i++]) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + + const claimed = await plugin.auth.checkin(async () => record) + assert.equal(claimed.outcome, "claimed") + assert.equal(claimed.credit, 100) + assert.match(claimed.message, /每日签到有礼 \+100/) + + const again = await plugin.auth.checkin(async () => record) + assert.equal(again.outcome, "done") + + const failed = await plugin.auth.checkin(async () => record) + assert.equal(failed.outcome, "failed") + assert.match(failed.message, /HTTP 500:boom/) +}) + +test("checkin without a sign-in never calls the vendor", async () => { + const { fetcher, seen } = oaFetcher() + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const out = await plugin.auth.checkin(async () => undefined) + assert.equal(out.outcome, "failed") + assert.equal(seen.length, 0) +}) + +// ---- models: the billable list, trimmed, without ids that always 404 ------ + +test("models are the billable list: the multiplier is trimmed, and an id that always 404s is never listed", async () => { + const { record } = await officeAceAuthRecord({}, "iam::d1:user:hw0199") + const { fetcher, seen } = oaFetcher((url) => { + if (url.endsWith("/v2/models")) return new Response(JSON.stringify(oaCatalogBody()), { status: 200 }) + if (url.includes("/v1/model-token-rates")) return new Response(JSON.stringify(oaRatesBody()), { status: 200 }) + return undefined + }) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const cfg = { provider: {} } + await plugin.config(cfg) + const models = await plugin.provider.models(cfg.provider.officeace, { auth: record }) + + assert.deepEqual(Object.keys(models).sort(), ["deepseek-v4.1-flash-0930", "glm-5.3", "kimi-k3"]) + // the name the vendor sent carries a trailing newline; the rate is trimmed too + assert.equal(models["kimi-k3"].name, "Kimi-K3") + assert.equal(models["glm-5.3"].name, "GLM-5.3 · x0.18") + assert.equal(models["deepseek-v4.1-flash-0930"].name, "DeepSeek-V4.1-Flash · x1.5") + assert.equal(models["glm-5.3"].api.url, "https://api.modelarts-maas.com/v2") + assert.equal(models["glm-5.3"].limit.context, 1_000_000) + // the registry's un-callable placeholders are gone even though the rates list has one + for (const id of oa.OA_UNAVAILABLE_IDS) assert.equal(models[id], undefined) + // the catalog was read with the account's own Basic pair + const catalogCall = seen.find((c) => c.url.endsWith("/v2/models")) + assert.equal( + catalogCall.headers.get("authorization"), + "Basic " + Buffer.from("app-key:app-secret").toString("base64"), + ) +}) + +test("a failed rates read keeps the last good table; one that never read it falls back to the static list", async () => { + const first = await officeAceAuthRecord({}, "iam::d1:user:hw0200") + let ratesDown = false + const { fetcher } = oaFetcher((url) => { + if (url.endsWith("/v2/models")) return new Response(JSON.stringify(oaCatalogBody()), { status: 200 }) + if (url.includes("/v1/model-token-rates")) { + return ratesDown ? new Response("nope", { status: 500 }) : new Response(JSON.stringify(oaRatesBody()), { status: 200 }) + } + return undefined + }) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const cfg = { provider: {} } + await plugin.config(cfg) + + const before = await plugin.provider.models(cfg.provider.officeace, { auth: first.record }) + assert.deepEqual(Object.keys(before).sort(), ["deepseek-v4.1-flash-0930", "glm-5.3", "kimi-k3"]) + // the rates endpoint goes down: the last table stands. An empty one would put + // the registry's un-callable ids back in front of the user. + ratesDown = true + const after = await plugin.provider.models(cfg.provider.officeace, { auth: first.record }) + assert.deepEqual(Object.keys(after).sort(), Object.keys(before).sort()) + + // an account that never read a rates table gets the static list, never the registry + const fresh = await officeAceAuthRecord({}, "iam::d1:user:hw0201") + const { fetcher: downFetcher } = oaFetcher((url) => + url.endsWith("/v2/models") ? new Response(JSON.stringify(oaCatalogBody()), { status: 200 }) : undefined, + ) + const other = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: downFetcher }) + const cfg2 = { provider: {} } + await other.config(cfg2) + const fallback = await other.provider.models(cfg2.provider.officeace, { auth: fresh.record }) + assert.deepEqual(Object.keys(fallback).sort(), Object.keys(oa.OA_FALLBACK_MODELS).sort()) +}) + +test("before a sign-in the OfficeAce provider still lists its models", async () => { + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, {}) + const cfg = { provider: {} } + await plugin.config(cfg) + assert.equal(cfg.provider.officeace.name, "OfficeAce") + assert.equal(cfg.provider.officeace.npm, "@ai-sdk/openai-compatible") + assert.equal(Object.keys(cfg.provider.officeace.models).length, Object.keys(oa.OA_FALLBACK_MODELS).length) + assert.equal(plugin.auth.provider, "officeace") + assert.equal(plugin.provider.id, "officeace") + // the two providers of the package keep their own icons + assert.ok(plugin.auth.icon.startsWith("data:image/png;base64,")) +}) + +// ---- chat: Bearer becomes Basic, one renewal is spent once ---------------- + +test("chat rewrites Bearer to Basic and strips the provider prefix", async () => { + const { record } = await officeAceAuthRecord({}, "iam::d1:user:hw0300") + const { fetcher, seen } = oaFetcher((url) => + url.includes("/v2/chat/completions") ? new Response(JSON.stringify({ ok: true }), { status: 200 }) : undefined, + ) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const loader = await plugin.auth.loader(async () => record) + const response = await loader.fetch("https://api.modelarts-maas.com/v2/chat/completions", { + method: "POST", + headers: { authorization: "Bearer sk-whatever" }, + body: JSON.stringify({ model: "officeace/glm-5.3", messages: [] }), + }) + assert.equal(response.status, 200) + const call = seen.find((c) => c.url.includes("/v2/chat/completions")) + assert.equal( + call.headers.get("authorization"), + "Basic " + Buffer.from("app-key:app-secret").toString("base64"), + ) + assert.equal(JSON.parse(call.body).model, "glm-5.3") +}) + +test("a 401 renews once, and only a renewal that changed the Basic pair is sent again", async () => { + const { record } = await officeAceAuthRecord({}, "iam::d1:user:hw0310") + let chats = 0 + let maasReads = 0 + const { fetcher } = oaFetcher((url) => { + if (url.includes("/v2/chat/completions")) { + chats++ + return chats === 1 + ? new Response(JSON.stringify({ error: "APIG.1009 invalid app key" }), { status: 401 }) + : new Response(JSON.stringify({ ok: true }), { status: 200 }) + } + if (url.includes("/v1/claw/client-permission-validate")) { + maasReads++ + return oaMaasAnswer(`app-key-${maasReads}`, `app-secret-${maasReads}`) + } + if (url === x.STS_TOKEN_ENDPOINT) { + return new Response(stsBody("AK2", oaRefreshToken({ principal_urn: "iam::d1:user:hw0310" })), { status: 200 }) + } + return undefined + }) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const loader = await plugin.auth.loader(async () => record) + const response = await loader.fetch("https://api.modelarts-maas.com/v2/chat/completions", { + method: "POST", + body: JSON.stringify({ model: "glm-5.3", messages: [] }), + }) + assert.equal(response.status, 200) + assert.equal(chats, 2) + // the renewal re-read the MaaS pair, which changed: the retry was worth it + assert.equal(maasReads, 1) +}) + +test("signed in without MaaS, chat says which step is missing instead of sending an empty Basic header", async () => { + const { record } = await officeAceAuthRecord({ modelAppKey: "", modelAppSecret: "" }, "iam::d1:user:hw0320") + const { fetcher, seen } = oaFetcher((url) => + url.includes("/v1/claw/client-permission-validate") + ? new Response(JSON.stringify({ subscription: { model_info: {} } }), { status: 200 }) + : undefined, + ) + const plugin = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const loader = await plugin.auth.loader(async () => record) + const response = await loader.fetch("https://api.modelarts-maas.com/v2/chat/completions", { + method: "POST", + body: JSON.stringify({ model: "glm-5.3", messages: [] }), + }) + assert.equal(response.status, 400) + const body = await response.json() + assert.equal(body.error.code, "MaaSNotLinked") + assert.match(body.error.message, /modelAppKey/) + // nothing was sent to the vendor's chat endpoint + assert.equal(seen.some((c) => c.url.includes("/v2/chat/completions")), false) +}) + +// ---- a sign-in writes only its own card's record --------------------------- + +/** The credential a CodeArts sign-in yields (as magpie stores it). */ +async function codeArtsSignInCredential(overrides = {}) { + const keyPair = await x.generateDpopKeyPair() + return { + access_key_id: "AK-CODEARTS", + secret_access_key: "SK-CODEARTS", + security_token: "ST-CODEARTS", + expires_at: "2031-01-01T00:00:00Z", + refresh_token: oaRefreshToken(), + code_verifier: "verifier", + dpop_private_key_jwk: keyPair.privateKeyJwk, + session_id: "0123456789abcdef0123456789abcdef", + ...overrides, + } +} + +test("a CodeArts sign-in writes only its own record", async () => { + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + const calls = [] + const fetcher = async (url) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) return new Response(stsBody("AK-CODEARTS", oaRefreshToken()), { status: 200 }) + if (String(url).includes("iam.cn-north-4")) { + return new Response(JSON.stringify({ user: { phone: "0086-18970098051" } }), { status: 200 }) + } + if (String(url).includes("/v1/claw/client-permission-validate")) return oaMaasAnswer() + return new Response("{}", { status: 200 }) + } + const plugin = await CodeArtsAuthPlugin({ client: oaClient(calls) }, { fetch: fetcher }) + const a = await plugin.auth.methods[0].authorize() + const done = a.callback() + const port = new URL(a.url).searchParams.get("port") + await fetch(`http://127.0.0.1:${port}${x.REDIRECT_PATH}?code=C1`, { redirect: "manual" }) + const out = await done + assert.equal(out.type, "success") + + // This card's own record, at a key a renewal can find again. + const own = calls.find((c) => c.path?.id?.startsWith("codearts")) + assert.ok(own, "this card's record is written") + assert.match(own.path.id, /^codearts#[0-9a-f]{8}$/) + assert.equal(JSON.parse(own.body.access).access_key_id, "AK-CODEARTS") + // No OfficeAce record: a Huawei Cloud refresh token is spent once, so a + // second record holding it would sign this card out at its next renewal. + assert.equal(calls.some((c) => c.path?.id?.startsWith("officeace")), false, "no record for the other card") +}) + +test("the OfficeAce sign-in writes only its own record", async () => { + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + const calls = [] + const fetcher = async (url) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) return new Response(stsBody("AK-OFFICEACE", oaRefreshToken()), { status: 200 }) + if (String(url).includes("iam.cn-north-4")) { + return new Response(JSON.stringify({ user: { phone: "0086-18970098051" } }), { status: 200 }) + } + if (String(url).includes("/v1/claw/client-permission-validate")) return oaMaasAnswer() + return new Response("{}", { status: 200 }) + } + const plugin = await OfficeAceAuthPlugin({ client: oaClient(calls) }, { fetch: fetcher }) + const a = await plugin.auth.methods[0].authorize() + const done = a.callback() + const port = new URL(a.url).searchParams.get("port") + await fetch(`http://127.0.0.1:${port}${x.REDIRECT_PATH}?code=C1`, { redirect: "manual" }) + const out = await done + assert.equal(out.type, "success") + // its own record is officeace's shape + const own = JSON.parse(out.access) + assert.equal(own.securityToken, "ST-AK-OFFICEACE") + assert.equal(own.modelAppKey, "app-key") + // the vendor's stable id, not the phone the card shows as usage().user + assert.equal(out.accountId, "01a1642ad2ae7f93bf6387ad2fc5f09e") + + const written = calls.find((c) => c.path?.id?.startsWith("officeace")) + assert.ok(written, "this card's record is written") + assert.equal(calls.some((c) => c.path?.id?.startsWith("codearts")), false, "no record for the other card") +}) + +test("recordKeyFor never picks a key another account already sits at", async () => { + oa.seenProviderAccounts.clear() + const { credential } = await officeAceAuthRecord({}, "iam::d1:user:hw-dedupe") + const cred = oa.officeAceCredentialOf({ access: JSON.stringify(credential) }) + const identity = x.accountIdentityOf(cred).id + oa.noteProviderAccount("officeace", identity) + + assert.equal(oa.recordKeyFor("officeace", identity), null) + // a provider with no account at all takes its first one at its own key + oa.noteProviderEmpty("codearts") + assert.equal(oa.recordKeyFor("codearts", identity), "codearts") + // any other account gets a key of its own, never one another account sits at + assert.match(oa.recordKeyFor("officeace", "iam::d1:user:someone-else"), /^officeace#[0-9a-f]{8}$/) + + const calls = [] + const written = await oa.writeProviderRecord(oaClient(calls), "officeace", cred) + assert.equal(written, null) + assert.equal(calls.length, 0) +}) + +test("two renewals of one record at once spend its token once", async () => { + oa.renewalGates.clear() + const { credential } = await officeAceAuthRecord({}, "iam::d1:user:hw0400") + const cred = oa.officeAceCredentialOf({ access: JSON.stringify(credential) }) + let stsCalls = 0 + const fetcher = async (url) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) { + stsCalls++ + await new Promise((resolve) => setTimeout(resolve, 5)) + return new Response(stsBody("AK3", oaRefreshToken({ principal_urn: "iam::d1:user:hw0400", jti: "rotated" })), { status: 200 }) + } + return new Response("{}", { status: 200 }) + } + const run = (c) => oa.renewSharedCredential(c, () => oa.renewOfficeAceCredential(c, fetcher)) + const [a, b] = await Promise.all([run(cred), run({ ...cred })]) + assert.equal(stsCalls, 1, "one record, one token: it is spent once") + assert.equal(a.access_key_id, "AK3") + assert.equal(b.access_key_id, "AK3") +}) + +test("a spent token is not renewed again, and is never refilled from another chain", async () => { + oa.renewalGates.clear() + const { credential } = await officeAceAuthRecord({}, "iam::d1:user:hw0410") + const cred = oa.officeAceCredentialOf({ access: JSON.stringify(credential) }) + let stsCalls = 0 + const fetcher = async (url) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) { + stsCalls++ + // the token was spent elsewhere: STS turns it away for good + return new Response(JSON.stringify({ error_code: "STS5.1806", error_msg: "refresh token has been used" }), { status: 400 }) + } + return new Response("{}", { status: 200 }) + } + await assert.rejects(() => oa.renewSharedCredential(cred, () => oa.renewOfficeAceCredential(cred, fetcher))) + assert.equal(stsCalls, 1) + // the failure stays a failure: no second attempt, no borrowed credential + await assert.rejects(() => oa.renewSharedCredential(cred, () => oa.renewOfficeAceCredential(cred, fetcher))) + assert.equal(stsCalls, 2, "each attempt spends what the record holds — nothing else") +}) + +test("the refresh chain is the OAuth client plus the token's lineage, never the account", () => { + const token = "h.x.y" + const pdp = oa.refreshChainOf({ refresh_token: token, oauth_client: "pdp5_for_agentarts" }) + const ca = oa.refreshChainOf({ refresh_token: token, oauth_client: "codearts-agent" }) + assert.notEqual(pdp.key, ca.key, "one token at two clients is two chains") + assert.equal(pdp.key, oa.refreshChainOf({ refresh_token: token, oauth_client: "pdp5_for_agentarts" }).key) + assert.equal(oa.refreshChainOf({}).key, "") + // a rotation answers a new token for the same chain: the lineage — and so the + // gate key — is the parent's, not a fresh one (review of #522 asked for this + // by name: "the OAuth client plus the token lineage"). + oa.refreshLineages.clear() + const parent = oa.refreshChainOf({ refresh_token: "T1", oauth_client: "codearts-agent" }) + oa.linkRotation({ refresh_token: "T1" }, { refresh_token: "T2" }) + const child = oa.refreshChainOf({ refresh_token: "T2", oauth_client: "codearts-agent" }) + assert.equal(child.lineage, parent.lineage) + assert.equal(child.key, parent.key) + assert.notEqual(oa.refreshChainOf({ refresh_token: "T3", oauth_client: "codearts-agent" }).key, parent.key) +}) + +test("two records on different chains renew independently, each with its own client", async () => { + oa.renewalGates.clear() + const { credential } = await officeAceAuthRecord({}, "iam::d1:user:hw5030") + const pdpCred = oa.officeAceCredentialOf({ access: JSON.stringify(credential) }) + const caCred = await codeArtsSignInCredential({ refresh_token: oaRefreshToken({ principal_urn: "iam::d1:user:hw5030", jti: "Y" }) }) + const clients = [] + const fetcher = async (url, init) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) { + clients.push(new URLSearchParams(String(init.body)).get("client_id")) + return new Response(stsBody(clients.length === 1 ? "AK-PDP" : "AK-CA", oaRefreshToken({ principal_urn: "iam::d1:user:hw5030", jti: `R${clients.length}` })), { status: 200 }) + } + return new Response("{}", { status: 200 }) + } + const officeAceNext = await oa.renewSharedCredential(pdpCred, () => oa.renewOfficeAceCredential(pdpCred, fetcher)) + const codeArtsNext = await oa.renewSharedCredential(caCred, () => x.refreshCredential(caCred, fetcher)) + assert.deepEqual(clients, ["pdp5_for_agentarts", "codearts-agent"]) + assert.equal(officeAceNext.access_key_id, "AK-PDP") + assert.equal(codeArtsNext.access_key_id, "AK-CA") +}) + +test("an officeace-auth record is renewed with its own token, after the CodeArts record of the account was polled", async () => { + oa.renewalGates.clear() + oa.seenProviderAccounts.clear() + // The record officeace-auth wrote: its own chain, issued to pdp5_for_agentarts. + const { record: oldRecord } = await officeAceAuthRecord({}, "iam::d1:user:hw5000") + // The CodeArts record beside it, of the same Huawei Cloud account, on its own chain. + const caCred = await codeArtsSignInCredential({ refresh_token: oaRefreshToken({ principal_urn: "iam::d1:user:hw5000", jti: "Y1" }) }) + const codeartsRecord = { + type: "oauth", + access: JSON.stringify(caCred), + refresh: caCred.refresh_token, + expires: Date.parse("2031-01-01T00:00:00Z"), + accountId: "iam::d1:user:hw5000", + uid: "iam::d1:user:hw5000", + } + const bodies = [] + const fetcher = async (url, init) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) { + bodies.push(String(init.body)) + return new Response(stsBody("AK-X2", oaRefreshToken({ principal_urn: "iam::d1:user:hw5000", jti: "X2" })), { status: 200 }) + } + return new Response("{}", { status: 200 }) + } + // magpie polls usage() of every account, which is what used to leave the + // CodeArts credential in a process-wide ledger the OfficeAce record then took. + const ca = await CodeArtsAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + await ca.auth.usage(async () => codeartsRecord) + + const of = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const out = await of.auth.refresh(oldRecord) + const written = JSON.parse(out.access) + + assert.equal(bodies.length, 1, "the old record spends its own refresh token") + assert.match(bodies[0], /client_id=pdp5_for_agentarts/) + assert.equal(written.access, "AK-X2") + assert.equal(written.oauth_client, "pdp5_for_agentarts") + // the MaaS pair the old record carried survives the rotation (chat needs it) + assert.equal(written.modelAppKey, "app-key") + assert.equal(written.modelAppSecret, "app-secret") + // and the account is not renamed: it already has an accountId + assert.equal(out.accountId, undefined) +}) + +test("a CodeArts renewal that fails at STS fails, and is never handed the OfficeAce record's credential", async () => { + oa.renewalGates.clear() + const { record: oldRecord } = await officeAceAuthRecord({}, "iam::d1:user:hw5010") + const caCred = await codeArtsSignInCredential({ refresh_token: oaRefreshToken({ principal_urn: "iam::d1:user:hw5010", jti: "Y1" }) }) + const codeartsRecord = { + type: "oauth", + access: JSON.stringify(caCred), + refresh: caCred.refresh_token, + expires: Date.parse("2031-01-01T00:00:00Z"), + accountId: "iam::d1:user:hw5010", + uid: "iam::d1:user:hw5010", + } + const fetcher = async (url) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) return new Response("upstream down", { status: 503 }) + return new Response("{}", { status: 200 }) + } + const of = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + await of.auth.usage(async () => oldRecord) // the other record is in this process too + const ca = await CodeArtsAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + await assert.rejects(() => ca.auth.refresh(codeartsRecord), /503/) +}) + +test("a renewal keeps the stored accountId and uid, so a user's name and keys stay with the account", async () => { + oa.renewalGates.clear() + const { record } = await officeAceAuthRecord({}, "iam::d1:user:hw5020") + const stored = { ...record, accountId: "189****8051", uid: "01a1642ad2ae7f93bf6387ad2fc5f09e" } + const fetcher = async (url) => + String(url) === x.STS_TOKEN_ENDPOINT + ? new Response(stsBody("AK-X3", oaRefreshToken({ principal_urn: "iam::d1:user:hw5020", jti: "X3" })), { status: 200 }) + : new Response("{}", { status: 200 }) + const of = await OfficeAceAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + const out = await of.auth.refresh(stored) + // magpie merges the answer into the record: nothing here renames the account + assert.equal(out.accountId, undefined) + assert.equal(out.uid, undefined) + + // and a persist (a renewal met in a request) writes the stored ones back + const calls = [] + await oa.persistOfficeAceRecord(oaClient(calls), oa.officeAceCredentialOf(stored), stored) + assert.equal(calls[0].body.accountId, "189****8051") + assert.equal(calls[0].body.uid, "01a1642ad2ae7f93bf6387ad2fc5f09e") +}) + +test("an OfficeAce account is only ever created by a sign-in: a listing writes no record", async () => { + oa.seenProviderAccounts.clear() + const calls = [] + const fetcher = async () => new Response("{}", { status: 200 }) + // A CodeArts account of the same Huawei Cloud account is signed in and polled + // (what magpie does for every account), and the OfficeAce card has none: the + // listing must not create one for it. An account the user signed out of must + // not come back on the next listing. + const caCred = await codeArtsSignInCredential({ refresh_token: oaRefreshToken({ principal_urn: "iam::d1:user:hw5040", jti: "Y1" }) }) + const codeartsRecord = { + type: "oauth", + access: JSON.stringify(caCred), + refresh: caCred.refresh_token, + expires: Date.parse("2031-01-01T00:00:00Z"), + accountId: "iam::d1:user:hw5040", + uid: "iam::d1:user:hw5040", + } + const ca = await CodeArtsAuthPlugin({ client: oaClient() }, { fetch: fetcher }) + await ca.auth.usage(async () => codeartsRecord) + + const plugin = await OfficeAceAuthPlugin({ client: oaClient(calls) }, { fetch: fetcher }) + const cfg = { provider: {} } + await plugin.config(cfg) + const models = await plugin.provider.models(cfg.provider.officeace, {}) + assert.deepEqual(Object.keys(models).sort(), Object.keys(oa.OA_FALLBACK_MODELS).sort()) + assert.equal(calls.length, 0, "no record is written by a listing") +}) + +test("a renewal never writes the other record of the account", async () => { + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + const canonical = await codeArtsSignInCredential({ model_app_key: "app-key", model_app_secret: "app-secret" }) + const identity = x.accountIdentityOf(canonical).id + const record = { + type: "oauth", + access: JSON.stringify(canonical), + refresh: canonical.refresh_token, + expires: Date.parse("2031-01-01T00:00:00Z"), + accountId: identity, + uid: identity, + } + // The OfficeAce record of this account exists and has been listed — even + // then a renewal must not write it: the two records only share a sign-in, + // never a credential. + oa.noteProviderAccount("officeace", identity) + + const calls = [] + const fetcher = async (url) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) return new Response(stsBody("AK5", oaRefreshToken()), { status: 200 }) + return new Response("{}", { status: 200 }) + } + const plugin = await CodeArtsAuthPlugin({ client: oaClient(calls) }, { fetch: fetcher }) + const renewed = await plugin.auth.refresh(record) + assert.equal(JSON.parse(renewed.access).access_key_id, "AK5") + assert.equal(calls.some((c) => c.path?.id?.startsWith("officeace")), false, "a renewal must not write the other record") +}) + +// ---- two cards, two records, one process restart --------------------------- +// +// Each card signs in on its own and holds its own refresh token, so the two +// records are separate chains. After a magpie restart — when every in-memory map +// is empty and the key this package wrote for a record is only in the small +// records file — renewing one record must leave the other card's record alone. + +/** A magpie-like client that keeps the records it is handed, by key. */ +function storeClient() { + const store = new Map() + return { + store, + client: { + app: { log: async () => {} }, + auth: { + set: async ({ path: p, body }) => { + store.set(p.id, body) + return { data: true } + }, + remove: async ({ path: p }) => { + store.delete(p.id) + }, + }, + }, + } +} + +/** Fake STS: the authorization code yields S1, and every refresh token is spendable once. */ +function oneShotSts(urn = "iam::d1:user:hwRestart", tag = "") { + const spent = new Set() + const calls = [] + let n = 0 + const fetcher = async (url, init = {}) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) { + const form = new URLSearchParams(String(init.body ?? "")) + if (form.get("grant_type") !== "refresh_token") { + return new Response(stsBody("AK-SIGNIN", oaRefreshToken({ principal_urn: urn, jti: `S1${tag}` })), { status: 200 }) + } + const token = form.get("refresh_token") + calls.push(token) + if (spent.has(token)) { + return new Response(JSON.stringify({ error_code: "STS5.1806", error_msg: "refresh token has been used" }), { status: 400 }) + } + spent.add(token) + n += 1 + return new Response(stsBody(`AK-${n}${tag}`, oaRefreshToken({ principal_urn: urn, jti: `S${n + 1}${tag}` })), { status: 200 }) + } + if (String(url).includes("iam.cn-north-4")) { + return new Response(JSON.stringify({ user: { phone: "0086-18970098051" } }), { status: 200 }) + } + if (String(url).includes("/v1/claw/client-permission-validate")) return oaMaasAnswer() + return new Response("{}", { status: 200 }) + } + return { fetcher, calls } +} + +test("a renewal never invalidates the other card's record", async () => { + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + oa.refreshLineages.clear() + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "codearts-two-cards-")) + const ledgerPath = path.join(dir, "checkins.json") + const { client, store } = storeClient() + const urn = "iam::d1:user:hwTwoCards" + // Each card has its own sign-in, so each record has its own refresh token. + const ca = oneShotSts(urn, "CA") + const oaSts = oneShotSts(urn, "OA") + await signInCodeArts(client, { fetch: ca.fetcher, ledgerPath }) + await signInOfficeAce(client, { fetch: oaSts.fetcher, ledgerPath }) + const codeartsKey = `codearts#${oa.accountKeySuffix(urn)}` + const officeaceKey = `officeace#${oa.accountKeySuffix(urn)}` + const accessOf = (body) => { + const a = JSON.parse(body.access) + return a.access_key_id ?? a.access + } + assert.ok(store.has(codeartsKey) && store.has(officeaceKey)) + const tokenOf = (body) => { + const a = JSON.parse(body.access) + return a.refresh_token ?? a.refreshToken + } + assert.notEqual(tokenOf(store.get(codeartsKey)), tokenOf(store.get(officeaceKey)), "two sign-ins, two refresh tokens") + + // magpie restarts; both records stay on their own chain + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + oa.refreshLineages.clear() + + const ca2 = await CodeArtsAuthPlugin({ client }, { fetch: ca.fetcher, ledgerPath }) + const renewed = await ca2.auth.refresh(store.get(codeartsKey)) + assert.equal(accessOf(renewed), "AK-1CA") + + // ... and the other card's record still renews with its own token + const of = await OfficeAceAuthPlugin({ client }, { fetch: oaSts.fetcher, ledgerPath }) + const again = await of.auth.refresh(store.get(officeaceKey)) + assert.equal(accessOf(again), "AK-1OA") +}) + +// ---- the four probes of the #522 review, as regressions --------------------- +// +// Each one names the behaviour it guards; they are the reviewer's probes kept +// as tests (the console lines say what the record did on each run). + +async function probeRecords() { + const kp = await x.generateDpopKeyPair() + // the officeace-auth record: its own chain X, issued to pdp5_for_agentarts + const oaCred = { modelAppKey: "app-key", modelAppSecret: "app-secret", maasBaseUrl: "", access: "AK-X", secret: "SK-X", + securityToken: "ST-X", projectId: "", expiresAt: "2031-01-01T00:00:00Z", refreshToken: oaRefreshToken({ principal_urn: "iam::d1:user:hwprobe", jti: "X1" }), codeVerifier: "", + dpopPrivateJwk: kp.privateKeyJwk, accountId: "01a1642ad2ae7f93bf6387ad2fc5f09e" } + const officeace = { type: "oauth", access: JSON.stringify(oaCred), refresh: oaRefreshToken({ principal_urn: "iam::d1:user:hwprobe", jti: "X1" }), expires: Date.parse("2031-01-01T00:00:00Z"), + accountId: "01a1642ad2ae7f93bf6387ad2fc5f09e", uid: "01a1642ad2ae7f93bf6387ad2fc5f09e" } + // the codearts record of the same account: its own chain Y (signed in before 0.3.0) + const caCred = { access_key_id: "AK-Y", secret_access_key: "SK-Y", security_token: "ST-Y", expires_at: "2031-01-01T00:00:00Z", + refresh_token: oaRefreshToken({ principal_urn: "iam::d1:user:hwprobe", jti: "Y1" }), code_verifier: "v", dpop_private_key_jwk: kp.privateKeyJwk, session_id: "0123456789abcdef0123456789abcdef", + user_phone: "189****8051" } + const codearts = { type: "oauth", access: JSON.stringify(caCred), refresh: oaRefreshToken({ principal_urn: "iam::d1:user:hwprobe", jti: "Y1" }), expires: Date.parse("2031-01-01T00:00:00Z"), accountId: "iam::d1:user:hwprobe", uid: "iam::d1:user:hwprobe" } + return { officeace, codearts } +} + +test("an officeace-auth record's renewal stays on its own chain after a CodeArts usage read", async () => { + oa.renewalGates.clear() + const { officeace, codearts } = await probeRecords() + const sts = [] + const fetcher = async (url, init) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) { + sts.push(String(init?.body)) + return new Response(JSON.stringify({ credentials: { access_key_id: "AK-X2", secret_access_key: "s", security_token: "t", expiration: "2031-01-02T00:00:00Z" }, refresh_token: oaRefreshToken({ principal_urn: "iam::d1:user:hwprobe", jti: "X2" }) }), { status: 200 }) + } + return new Response("{}", { status: 200 }) + } + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "probe-rec-")) + const opts = { fetch: fetcher, ledgerPath: path.join(dir, "l.json") } + const ca = await CodeArtsAuthPlugin({ client: { auth: { set: async () => {} } } }, opts) + const of = await OfficeAceAuthPlugin({ client: { auth: { set: async () => {} } } }, opts) + await ca.auth.usage(async () => codearts) // magpie polls usage of every account + const out = await of.auth.refresh(officeace) + const got = JSON.parse(out.access) + assert.equal(sts.length, 1, "the old record's own refresh token should be spent at STS") + assert.equal(got.access, "AK-X2") +}) + +test("a CodeArts renewal that fails at STS fails instead of taking the OfficeAce chain", async () => { + oa.renewalGates.clear() + const { officeace, codearts } = await probeRecords() + const fetcher = async (url) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) return new Response("upstream down", { status: 503 }) + return new Response("{}", { status: 200 }) + } + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "probe-rec-")) + const opts = { fetch: fetcher, ledgerPath: path.join(dir, "l.json") } + const ca = await CodeArtsAuthPlugin({ client: { auth: { set: async () => {} } } }, opts) + const of = await OfficeAceAuthPlugin({ client: { auth: { set: async () => {} } } }, opts) + await of.auth.usage(async () => officeace) + let out, err + try { out = await ca.auth.refresh(codearts) } catch (e) { err = e } + const got = out && JSON.parse(out.access) + assert.ok(err || got.access_key_id !== "AK-X", "a failed renewal must not borrow the other chain's credential") +}) + +test("a new OfficeAce sign-in names the account by the vendor id, not the masked phone", async () => { + oa.seenProviderAccounts.clear() + const fetcher = async (url) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) return new Response(JSON.stringify({ credentials: { access_key_id: "AK-N", secret_access_key: "s", security_token: "t", expiration: "2031-01-02T00:00:00Z" }, refresh_token: oaRefreshToken({ principal_urn: "iam::d1:user:hwprobe" }) }), { status: 200 }) + if (String(url).includes("iam.cn-north-4")) return new Response(JSON.stringify({ user: { phone: "0086-18970098051" } }), { status: 200 }) + return new Response("{}", { status: 200 }) + } + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "probe-rec-")) + const of = await OfficeAceAuthPlugin({ client: { auth: { set: async () => {} } } }, { fetch: fetcher, ledgerPath: path.join(dir, "l.json") }) + const a = await of.auth.methods[0].authorize() + const done = a.callback() + const port = new URL(a.url).searchParams.get("port") + await fetch(`http://127.0.0.1:${port}${x.REDIRECT_PATH}?code=C1`, { redirect: "manual" }) + const out = await done + assert.equal(out.type, "success") + assert.notEqual(out.accountId, "189****8051", "accountId must be the vendor's stable id, not the masked phone") + assert.ok(String(out.accountId).length > 10, "accountId must be the vendor's stable id") +}) + +test("an officeace record renewal keeps a stored phone accountId", async () => { + oa.renewalGates.clear() + const { officeace } = await probeRecords() + const stored = { ...officeace, accountId: "189****8051" } // what officeace-auth 0.1.14 stored + const cred = JSON.parse(stored.access) + delete cred.user_phone + stored.access = JSON.stringify(cred) + const fetcher = async (url) => String(url) === x.STS_TOKEN_ENDPOINT + ? new Response(JSON.stringify({ credentials: { access_key_id: "AK-X2", secret_access_key: "s", security_token: "t", expiration: "2031-01-02T00:00:00Z" }, refresh_token: oaRefreshToken({ principal_urn: "iam::d1:user:hwprobe", jti: "X2" }) }), { status: 200 }) + : new Response("{}", { status: 200 }) + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "probe-rec-")) + const of = await OfficeAceAuthPlugin({ client: { auth: { set: async () => {} } } }, { fetch: fetcher, ledgerPath: path.join(dir, "l.json") }) + const out = await of.auth.refresh(stored) + assert.ok(out.accountId === undefined || out.accountId === "189****8051", "a renewal must keep the stored accountId as it was") +}) + +// ---- a removed account stays removed --------------------------------------- + +test("a removed OfficeAce record is not written back after a restart", async () => { + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + oa.refreshLineages.clear() + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "codearts-removed-")) + const ledgerPath = path.join(dir, "checkins.json") + const { client, store } = storeClient() + const urn = "iam::d1:user:hwRemoved" + const caSts = oneShotSts(urn, "CA") + const oaSts = oneShotSts(urn, "OA") + // each card has its own sign-in: its own record, its own token + await signInCodeArts(client, { fetch: caSts.fetcher, ledgerPath }) + await signInOfficeAce(client, { fetch: oaSts.fetcher, ledgerPath }) + const codeartsKey = [...store.keys()].find((k) => k.startsWith("codearts")) + const officeaceKey = [...store.keys()].find((k) => k.startsWith("officeace")) + assert.ok(codeartsKey && officeaceKey) + + // the user removes the OfficeAce account; magpie keeps the CodeArts one + store.delete(officeaceKey) + + // magpie restarts, then lists the officeace provider: no accounts at all + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + oa.refreshLineages.clear() + const of = await OfficeAceAuthPlugin({ client }, { fetch: oaSts.fetcher, ledgerPath }) + await of.provider.models({ models: {} }) + + // the CodeArts record still renews — and must not write the removed one back + const ca2 = await CodeArtsAuthPlugin({ client }, { fetch: caSts.fetcher, ledgerPath }) + await ca2.auth.refresh(store.get(codeartsKey)) + assert.equal([...store.keys()].some((k) => k.startsWith("officeace")), false, "a removed account must stay removed") +}) + +test("the OfficeAce card's renewal error says OfficeAce, not CodeArts", async () => { + const { officeace } = await probeRecords() + const fetcher = async (url) => String(url) === x.STS_TOKEN_ENDPOINT + ? new Response(JSON.stringify({ error_code: "STS5.1806", error_msg: "refresh token has been used" }), { status: 400 }) + : new Response("{}", { status: 200 }) + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "probe-rec-")) + const of = await OfficeAceAuthPlugin({ client: { auth: { set: async () => {} } } }, { fetch: fetcher, ledgerPath: path.join(dir, "l.json") }) + let err + try { await of.auth.refresh(officeace) } catch (e) { err = e } + assert.ok(err, "a spent token must fail the renewal") + assert.match(err.message, /^OfficeAce token request failed: 400/) + assert.doesNotMatch(err.message, /CodeArts token request failed/) +}) + +/** Sign in once through the OfficeAce card with its own fake STS. */ +async function signInOfficeAce(client, opts) { + const of = await OfficeAceAuthPlugin({ client }, opts) + const a = await of.auth.methods[0].authorize() + const done = a.callback() + const port = new URL(a.url).searchParams.get("port") + await fetch(`http://127.0.0.1:${port}${x.REDIRECT_PATH}?code=C1`, { redirect: "manual" }) + assert.equal((await done).type, "success") +} + +/** Sign in once through the CodeArts card with its own fake STS. */ +async function signInCodeArts(client, opts) { + const ca = await CodeArtsAuthPlugin({ client }, opts) + const a = await ca.auth.methods[0].authorize() + const done = a.callback() + const port = new URL(a.url).searchParams.get("port") + await fetch(`http://127.0.0.1:${port}${x.REDIRECT_PATH}?code=C1`, { redirect: "manual" }) + assert.equal((await done).type, "success") +} + +test("two accounts: removing one OfficeAce record does not bring it back when the other is listed", async () => { + for (const restart of [false, true]) { + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + oa.refreshLineages.clear() + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "codearts-two-")) + const ledgerPath = path.join(dir, "checkins.json") + const { client, store } = storeClient() + const urnA = "iam::d1:user:hwA" + const urnB = "iam::d1:user:hwB" + const a = oneShotSts(urnA, "A") + const b = oneShotSts(urnB, "B") + const oaA = oneShotSts(urnA, "OA") + const oaB = oneShotSts(urnB, "OB") + await signInCodeArts(client, { fetch: a.fetcher, ledgerPath }) + await signInCodeArts(client, { fetch: b.fetcher, ledgerPath }) + await signInOfficeAce(client, { fetch: oaA.fetcher, ledgerPath }) + await signInOfficeAce(client, { fetch: oaB.fetcher, ledgerPath }) + const keyOf = (provider, urn) => `${provider}#${oa.accountKeySuffix(urn)}` + assert.ok(store.has(keyOf("officeace", urnA)) && store.has(keyOf("codearts", urnA))) + assert.ok(store.has(keyOf("officeace", urnB)) && store.has(keyOf("codearts", urnB))) + + // the user removes A's OfficeAce record; B stays + store.delete(keyOf("officeace", urnA)) + if (restart) { + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + oa.refreshLineages.clear() + } + + // the officeace provider is listed with B's account: A is not in it + const of = await OfficeAceAuthPlugin({ client }, { fetch: oaB.fetcher, ledgerPath }) + await of.provider.models({ models: {} }, { auth: store.get(keyOf("officeace", urnB)) }) + + // A's CodeArts record renews — the removed OfficeAce record must stay gone + const ca2 = await CodeArtsAuthPlugin({ client }, { fetch: a.fetcher, ledgerPath }) + await ca2.auth.refresh(store.get(keyOf("codearts", urnA))) + assert.equal(store.has(keyOf("officeace", urnA)), false, `officeace A must stay removed (restart=${restart})`) + } +}) + +test("a removed OfficeAce record is not written back when the first renewal comes before any listing", async () => { + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + oa.refreshLineages.clear() + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "codearts-nolist-")) + const ledgerPath = path.join(dir, "checkins.json") + const { client, store } = storeClient() + const urn = "iam::d1:user:hwNoList" + const caSts = oneShotSts(urn, "CA") + const oaSts = oneShotSts(urn, "OA") + await signInCodeArts(client, { fetch: caSts.fetcher, ledgerPath }) + await signInOfficeAce(client, { fetch: oaSts.fetcher, ledgerPath }) + const codeartsKey = `codearts#${oa.accountKeySuffix(urn)}` + const officeaceKey = `officeace#${oa.accountKeySuffix(urn)}` + assert.ok(store.has(codeartsKey) && store.has(officeaceKey)) + store.delete(officeaceKey) + + // magpie restarts; a usage refresh and then a renewal come before any catalog listing + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + oa.refreshLineages.clear() + const ca2 = await CodeArtsAuthPlugin({ client }, { fetch: caSts.fetcher, ledgerPath }) + await ca2.auth.usage(async () => store.get(codeartsKey), {}) + await ca2.auth.refresh(store.get(codeartsKey)) + assert.equal(store.has(officeaceKey), false, "no listing yet: nothing may be written back") +}) + +// ---- a record that was listed or used still must not come back ------------- +// +// The usual removal: the provider listed or used the account in this process, +// then the user removes it — no restart. The push must never write it back. + +async function twoAccountsSignedIn(tag) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), `codearts-${tag}-`)) + const ledgerPath = path.join(dir, "checkins.json") + const { client, store } = storeClient() + const urnA = "iam::d1:user:hwA" + const urnB = "iam::d1:user:hwB" + const a = oneShotSts(urnA, "A") + const b = oneShotSts(urnB, "B") + const oaA = oneShotSts(urnA, "OA") + const oaB = oneShotSts(urnB, "OB") + await signInCodeArts(client, { fetch: a.fetcher, ledgerPath }) + await signInCodeArts(client, { fetch: b.fetcher, ledgerPath }) + await signInOfficeAce(client, { fetch: oaA.fetcher, ledgerPath }) + await signInOfficeAce(client, { fetch: oaB.fetcher, ledgerPath }) + const keyOf = (provider, urn) => `${provider}#${oa.accountKeySuffix(urn)}` + return { client, store, ledgerPath, a, b, oaA, oaB, keyOf, urnA, urnB } +} + +test("a removed OfficeAce record is not written back after its models hook listed it", async () => { + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + oa.refreshLineages.clear() + const { client, store, ledgerPath, a, b, keyOf, urnA, urnB } = await twoAccountsSignedIn("models") + const of = await OfficeAceAuthPlugin({ client }, { fetch: b.fetcher, ledgerPath }) + // both accounts were listed in this process + await of.provider.models({ models: {} }, { auth: store.get(keyOf("officeace", urnA)) }) + await of.provider.models({ models: {} }, { auth: store.get(keyOf("officeace", urnB)) }) + // the user removes A; the provider is listed again with B only + store.delete(keyOf("officeace", urnA)) + await of.provider.models({ models: {} }, { auth: store.get(keyOf("officeace", urnB)) }) + // A's CodeArts record renews, no restart in between + const ca2 = await CodeArtsAuthPlugin({ client }, { fetch: a.fetcher, ledgerPath }) + await ca2.auth.refresh(store.get(keyOf("codearts", urnA))) + assert.equal(store.has(keyOf("officeace", urnA)), false, "a listed-but-removed record must stay removed") +}) + +test("a removed OfficeAce record is not written back after its loader used it", async () => { + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + oa.refreshLineages.clear() + const { client, store, ledgerPath, a, b, keyOf, urnA, urnB } = await twoAccountsSignedIn("loader") + const of = await OfficeAceAuthPlugin({ client }, { fetch: b.fetcher, ledgerPath }) + // both accounts went through the loader (a request) + await of.auth.loader(async () => store.get(keyOf("officeace", urnA))) + await of.auth.loader(async () => store.get(keyOf("officeace", urnB))) + store.delete(keyOf("officeace", urnA)) + const ca2 = await CodeArtsAuthPlugin({ client }, { fetch: a.fetcher, ledgerPath }) + await ca2.auth.refresh(store.get(keyOf("codearts", urnA))) + assert.equal(store.has(keyOf("officeace", urnA)), false, "a used-but-removed record must stay removed") +}) + +test("a removed OfficeAce record is not written back when no restart separates the removal from the renewal", async () => { + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + oa.refreshLineages.clear() + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "codearts-oneremove-")) + const ledgerPath = path.join(dir, "checkins.json") + const { client, store } = storeClient() + const urn = "iam::d1:user:hwOne" + const caSts = oneShotSts(urn, "CA") + const oaSts = oneShotSts(urn, "OA") + await signInCodeArts(client, { fetch: caSts.fetcher, ledgerPath }) + await signInOfficeAce(client, { fetch: oaSts.fetcher, ledgerPath }) + const keyOf = (provider) => `${provider}#${oa.accountKeySuffix(urn)}` + const of = await OfficeAceAuthPlugin({ client }, { fetch: oaSts.fetcher, ledgerPath }) + await of.provider.models({ models: {} }, { auth: store.get(keyOf("officeace")) }) + store.delete(keyOf("officeace")) + // no restart, and no listing between the removal and the renewal + const ca2 = await CodeArtsAuthPlugin({ client }, { fetch: caSts.fetcher, ledgerPath }) + await ca2.auth.refresh(store.get(keyOf("codearts"))) + assert.equal(store.has(keyOf("officeace")), false, "a single removed record must stay removed without a restart") +}) diff --git a/packages/codearts/package.json b/packages/codearts/package.json index 80aae6c..0d8ad86 100644 --- a/packages/codearts/package.json +++ b/packages/codearts/package.json @@ -1,7 +1,7 @@ { "name": "@magpie-community/opencode-codearts-auth", - "version": "0.2.6", - "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)", + "version": "0.3.0", + "description": "Huawei Cloud in OpenCode and magpie: CodeArts (码道) and OfficeAce (AgentArts), each from its own Huawei Cloud OAuth sign-in — models, credit rates, credit usage and the daily check-in (unofficial)", "type": "module", "main": "./index.mjs", "exports": "./index.mjs", @@ -17,7 +17,10 @@ "opencode", "opencode-plugin", "magpie", + "auth", + "provider", "codearts", + "officeace", "huaweicloud", "oauth" ], diff --git a/registry.json b/registry.json index a4c99b8..67c2cd2 100644 --- a/registry.json +++ b/registry.json @@ -55,8 +55,8 @@ "summary": { "en": "SenseTime Raccoon (xiaohuanxiong.com) models, account credits and daily check-in, with browser sign-in or Raccoon desktop's live sign-in.", "zh": "商汤小浣熊(xiaohuanxiong.com)模型、积分余额与每日签到,支持浏览器登录或直接复用小浣熊桌面端登录态。" } }, { "package": "@magpie-community/opencode-autoclaw-auth", "name": "AutoClaw", "providers": ["autoclaw", "autoclaw-cn"], "community": true, "summary": { "en": "AutoClaw (Zhipu OpenClaw) cloud accounts: oversea web sign-in (Google/z.ai) or CN phone SMS, credit balance and daily check-in.", "zh": "AutoClaw(智谱澳龙/OpenClaw)云端账号:国际版网页登录(Google/z.ai)或国内手机验证码,积分余额与每日签到。" } }, - { "package": "@magpie-community/opencode-codearts-auth", "name": "CodeArts", "providers": ["codearts"], "community": true, - "summary": { "en": "Unofficial: Huawei Cloud CodeArts (码道) coding plans with Huawei Cloud OAuth sign-in — GLM, DeepSeek, openPangu, live models and credit rates, credit usage and daily check-in.", "zh": "非官方:华为云码道(CodeArts)编码套餐,华为云 OAuth 登录;GLM、DeepSeek、openPangu 等模型,实时模型与积分倍率、积分用量和每日签到。" } }, + { "package": "@magpie-community/opencode-codearts-auth", "name": "CodeArts / OfficeAce", "providers": ["codearts", "officeace"], "community": true, + "summary": { "en": "Unofficial: Huawei Cloud CodeArts (码道) coding plans and OfficeAce (AgentArts), each signed in with Huawei Cloud OAuth on its own card — GLM, DeepSeek, openPangu and OfficeAce's MaaS models, live models and credit rates, credit usage by bucket and the daily check-in. Replaces officeace-auth; accounts signed in there keep working.", "zh": "非官方:华为云码道(CodeArts)编码套餐与 OfficeAce(AgentArts),两张卡各自用华为云 OAuth 登录;GLM、DeepSeek、openPangu 与 OfficeAce 的 MaaS 模型,实时模型与积分倍率、分桶积分用量和每日签到。取代 officeace-auth,原已登录的账号继续可用。" } }, { "package": "@magpie-community/opencode-gcp-ai-auth", "name": "GCP AI", "providers": ["gcp-ai"], "community": true, "summary": { "en": "Vertex AI models and Google Cloud promotional credits, signed with your own gcloud or ADC login. Lists only the models your project can call.", "zh": "用本机 gcloud / ADC 登录使用 Vertex AI 模型,并读取 Google Cloud 促销赠金;只列出项目实际能调用的模型。" } }, { "package": "@magpie-community/middleware-param-override", "name": "Param Override", "kind": "middleware", "community": true, @@ -111,8 +111,6 @@ "summary": { "en": "Email alerts when a provider call fails or a quota window runs out: your own SMTP account, your own words in the mail, and your own list of what to watch, with cooldowns and an hourly cap so a bad hour stays bounded — plus an optional periodic usage digest.", "zh": "供应商调用失败或额度窗口用尽时发邮件提醒:用你自己的 SMTP 账号、自己的邮件文案、自己勾选的监控事项;同类事件冷却合并,另有每小时上限,糟糕的一小时不会失控;另可开启定期用量摘要。" } }, { "package": "@magpie-community/opencode-cloudflare-workers-ai-auth", "name": "Cloudflare Workers AI", "providers": ["cloudflare-workers-ai"], "community": true, "summary": { "en": "Cloudflare Workers AI with your API token (Workers AI:Edit): 28+ models discovered live from models.dev, the 8 paid-only models flagged, and a Neurons/day allowance row in magpie quota.", "zh": "用你的 Cloudflare API Token(Workers AI:Edit 权限)登录 Workers AI:28+ 模型经 models.dev 实时发现,付费专属模型自动标注,magpie quota 显示每日 Neurons 免费额度。" } }, - { "package": "officeace-auth", "name": "OfficeAce", "providers": ["officeace"], "community": true, - "summary": { "en": "Unofficial OfficeAce (Huawei Cloud AgentArts): browser sign-in to a Huawei Cloud account, live models with their credit multipliers, credit usage by bucket, and the daily check-in.", "zh": "非官方 OfficeAce(华为云 AgentArts):浏览器登录华为云账号,实时模型及其积分倍率、分桶积分用量,以及每日签到。" } }, { "package": "@magpie-community/opencode-river-auth", "name": "River", "providers": ["river"], "community": true, "summary": { "en": "River (river.ai) pay-as-you-go inference with your API key: per-account models from /v1/models, documented reasoning efforts and live prices from River's public pricing endpoint.", "zh": "用你的 API key 接入 River (river.ai) 按量计费推理:按账号从 /v1/models 列出模型,带官方推理档位与实时价格。" } }, { "package": "magpie-plugin-pink", "name": "PinK", "kind": "agent",