diff --git a/packages/codearts/README.md b/packages/codearts/README.md index 0b0ff4c..d520ac9 100644 --- a/packages/codearts/README.md +++ b/packages/codearts/README.md @@ -65,6 +65,37 @@ it, so a re-sign-in and a renewal give the same value back. The card's name is u which shows `user_phone` once a sign-in or renewal has read it. IAM is *not* one of the hosts the plugin signs forwarded requests for (`SIGNED_HOSTS`): the one phone read is made by the plugin itself, for that one URL. +**Sign in from the CodeArts Agent on this machine** (since 0.3.10, #998): when the CodeArts Agent +IDE is installed and signed in here, a second method takes its sign-in instead of a browser. +The IDE keeps it in its VS Code-style state database, key `huaweicloud.codearts-snap` +(`userInfoKey.originData`: AK/SK/security token, `domainId`, `expiresAt`, `stationType`): + +| System | File | +|---|---| +| macOS | `~/Library/Application Support/codearts-agent/User/globalStorage/state.vscdb` | +| Windows | `%APPDATA%\codearts-agent\User\globalStorage\state.vscdb` | +| Linux | `$XDG_CONFIG_HOME/codearts-agent/User/globalStorage/state.vscdb` (else `~/.config/…`) | + +`MAGPIE_CODEARTS_IDE_STATE` points it elsewhere. The plugin never opens or writes the IDE's file +with SQLite: it copies it (with its `-wal`/`-journal`) into a temporary folder, reads the copy and +removes it. A missing, unreadable or half-written file, or one without a whole credential, is +"unknown": the method isn't offered, or the sign-in fails saying why (never with a secret). The +credential is checked once (`snap-manager/v1/current/user` on its station) and kept like a +browser sign-in's, but it has no refresh token: it is renewed by reading the IDE's file again +once the IDE has renewed it, never through STS. Until then a renewal only fails for now +(`503`, the sign-in kept); signing in to another account in the IDE doesn't change this one. +The account is the IDE's `domainId`. + +**The international station** (since 0.3.10, #998): a credential from the international +CodeArts (`stationType: "international"`) is sent only to +`snap-access.ap-southeast-1.myhuaweicloud.com`, and a mainland one only to the mainland hosts. +Its token package shows as one window, `usage_token_num` of `package_token_amount` from +`start_date` to `end_date`, and the plan is `package_name_en`. The international station has no +`opengw` endpoints, credit batches or daily check-in, so the plugin asks none of them there +(check-in answers "inactive"). Not tried yet with a real international account: chats go to +`/api/v2/chat/completions` there as on the mainland, and the model list falls back to the +built-in one when the station doesn't answer it. + ## Models The account's live list: CodeArts' builtin models, plus the free models of its daily benefit @@ -79,8 +110,9 @@ rate), shown as `DeepSeek-V4.1-Flash-1017`, not folded into `DeepSeek-V4.1-Flash ## Requests - Every request is signed with Huawei's SDK-HMAC-SHA256 using the temporary credentials, and - only for CodeArts' own two hosts, `snap-access.cn-north-4.myhuaweicloud.com` and - `opengw.developer.huaweicloud.com`: a request anywhere else (an overridden `api`) is refused + only for CodeArts' own hosts, `snap-access.cn-north-4.myhuaweicloud.com` and + `opengw.developer.huaweicloud.com` (and, for an international credential, only + `snap-access.ap-southeast-1.myhuaweicloud.com`): a request anywhere else (an overridden `api`) is refused before the credentials leave, and no signed or token request follows a redirect. - The gateway allows 3 concurrent sessions per account and tells them apart by `x-ot-session-id`; the plugin sends one stable session id per account (and a fresh trace per @@ -251,12 +283,25 @@ measurements and code of [HuHong-Tao](https://github.com/yuweihao17/codearts/pul `access` 字段里,保存在 magpie / OpenCode 自己的账号存储中;过期前 30 分钟自动续期,请求遇到临时凭据 过期时就地续期并重发一次。同一账号的 refresh_token 只用一次;续期只是暂时失败(如 STS 连不上)时返回 `503` 并保留登录,只有被 STS 明确拒绝才标记需要重新登录。账号标识取自 refresh_token,重复登录不会多出账号。 +- **用本机的 CodeArts Agent 登录**(0.3.10 起,#998):本机装了码道 IDE 且已登录时,多一个登录方式,直接用 IDE 的登录, + 不开浏览器。IDE 把它存在自己的 `state.vscdb`(键 `huaweicloud.codearts-snap`)里:macOS 为 + `~/Library/Application Support/codearts-agent/User/globalStorage/state.vscdb`,Windows 为 + `%APPDATA%\codearts-agent\User\globalStorage\state.vscdb`,Linux 为 `$XDG_CONFIG_HOME`(否则 `~/.config`)下的同一路径; + `MAGPIE_CODEARTS_IDE_STATE` 可改。插件只读:先把文件(连同 `-wal`/`-journal`)拷到临时目录再读拷贝,绝不打开或写 IDE 的文件。 + 文件不存在、读不了、写了一半或凭据不全都算「未知」:不提供这个方式,或登录失败并说明原因(不含任何密钥)。 + 这种登录没有 refresh token,续期是等 IDE 自己续期后重新读它的文件,绝不走 STS;IDE 还没续期时续期只是暂时失败(`503`,保留登录)。 + 账号标识是 IDE 的 `domainId`。 +- **国际站**(0.3.10 起,#998):国际站凭据(`stationType: "international"`)只发往 + `snap-access.ap-southeast-1.myhuaweicloud.com`,国内凭据只发往国内主机。token 套餐显示为一个窗口: + `start_date`–`end_date` 内 `package_token_amount` 中已用的 `usage_token_num`,套餐名取 `package_name_en`。 + 国际站没有 `opengw` 接口、积分批次和每日签到,插件在那里一概不请求(签到回答「未开通」)。尚未用真实国际站账号试过: + 对话仍发到 `/api/v2/chat/completions`,模型列表读不到时用内置列表。 - **模型**:账号实时的内置模型列表;领取当日免费权益成功后,再加上免费模型(每个北京自然日领一次,与 客户端一致;当天还没领取时遇到 `benefit not found` 也会先领取再重发)。每个模型的「消耗系数」作为 magpie 的倍率上报,来自账号主智能体(`build`)的模型列表。 0.3.2 起模型名照码道给的显示:带日期的 `deepseek-v4.1-flash-1017` 是另一个模型(错峰倍率不同),显示为 `DeepSeek-V4.1-Flash-1017`,不再和 `DeepSeek-V4.1-Flash` 叫同一个名字(#677)。 -- **请求**:SDK-HMAC-SHA256 签名,只签给码道自己的两个主机(`snap-access.cn-north-4.myhuaweicloud.com`、 - `opengw.developer.huaweicloud.com`),发往其他地址(如改过的 `api`)的请求在凭据发出前就被拒绝,签名请求和令牌请求都不跟随重定向;像客户端一样发送 `x-ot-session-id` 会话头(每账号一个会话),账号内 +- **请求**:SDK-HMAC-SHA256 签名,只签给码道自己的主机(`snap-access.cn-north-4.myhuaweicloud.com`、 + `opengw.developer.huaweicloud.com`;国际站凭据只签 `snap-access.ap-southeast-1.myhuaweicloud.com`),发往其他地址(如改过的 `api`)的请求在凭据发出前就被拒绝,签名请求和令牌请求都不跟随重定向;像客户端一样发送 `x-ot-session-id` 会话头(每账号一个会话),账号内 在途请求不超过 3 个,`TM.00001041` 退避重试,网关排队时按客户端的方式等待(0.2.3 起,magpie 在这个请求之后还有别的账号、供应商或路由组成员时(`x-magpie-fallback: 1`),排队的请求立即退出队列并以 `503` 加队列的 `Retry-After` 回答,magpie 随即改问下一个);总是以流式请求上游(码道 只对流式回答计量积分),调用方要非流式时折叠回 JSON;默认注入 `thinking: { type: "enabled" }`,思考与 正文分开;200 里内嵌的错误换算为 `429` / `400` / `502` 并带厂商原话;码道只接受不超过 64 个字符的工具名, diff --git a/packages/codearts/index.mjs b/packages/codearts/index.mjs index e1147fa..fd9ca05 100644 --- a/packages/codearts/index.mjs +++ b/packages/codearts/index.mjs @@ -63,10 +63,28 @@ const SNAP_STATISTICS_URL = `${SNAP_HOST}/snap-manager/v1/statistics/plugin` // opengw gateway config: the benefit/free-quota model set. const OPENGW_HOST = "https://opengw.developer.huaweicloud.com" const OPENGW_GATEWAY_CONFIG_URL = `${OPENGW_HOST}/api/v1/gateway/config` -// The only hosts the account's credentials are signed for and sent to: the -// two the plugin itself calls, by name. STS takes the refresh token, never a -// signature, and the portal only ever opens in the browser. -const SIGNED_HOSTS = new Set([SNAP_HOST, OPENGW_HOST].map((u) => new URL(u).host)) +// The stations an account lives on, each with the API hosts its credential is +// signed for (#998). The mainland one is where the browser sign-in lands; the +// international one (ap-southeast-1) answers the same snap-access paths but +// has no opengw (its gateway/config, free pool and benefit claim are 404s), so +// nothing of opengw's is asked there. The console of each only ever opens in +// the browser and is never signed for. +const STATIONS = { + mainland: { id: "mainland", snap: SNAP_HOST, opengw: OPENGW_HOST, console: "https://codearts.huaweicloud.com" }, + international: { + id: "international", + snap: "https://snap-access.ap-southeast-1.myhuaweicloud.com", + opengw: "", + console: "https://console-intl.huaweicloud.com", + }, +} +/** The hosts a credential of `station` is signed for: its API hosts, by name. */ +const apiHostsOf = (station) => [station.snap, station.opengw].filter(Boolean).map((u) => new URL(u).host) +// The only hosts any account's credentials are signed for and sent to: the +// stations' API hosts, by name, and each credential only for its own +// station's (`stationOf`). STS takes the refresh token, never a signature, +// and the portals and consoles only ever open in the browser. +const SIGNED_HOSTS = new Set(Object.values(STATIONS).flatMap(apiHostsOf)) // Huawei Cloud IAM: the one place an account's own phone number can be read // with the credentials a sign-in already carries (`GET /v3.0/OS-USER/users/ @@ -587,6 +605,8 @@ function profileOf(cred) { * the name (the `accountId` / `uid` rule in magpie-plugin-scaffold, #27). */ function accountIdentityOf(cred) { + // A sign-in read from the CodeArts Agent is the account its domainId names. + if (cred?.source === IDE_SOURCE) return { id: firstOf(cred.domain_id), name: displayNameOf(cred.user_phone, cred.user_name) } const legacy = { id: firstOf(cred?.user_name, cred?.user_id), name: firstOf(cred?.user_name) } const profile = profileOf(cred) if (!profile) return { ...legacy, name: displayNameOf(cred?.user_phone, legacy.name) } @@ -1620,7 +1640,7 @@ function queueInfoOf(headers) { /** One signed call on a queued trace: GET is where it stands, DELETE takes it out. */ async function traceQueueCall(method, cred, traceId, context, signal) { - const url = TRACE_QUEUE_URL(traceId) + const url = onStation(TRACE_QUEUE_URL(traceId), cred) const headers = await signFor(cred, method, url, new Uint8Array()) headers.set(SESSION_HEADER, context.sessionId) return context.fetcher(url, { method, headers, signal, redirect: "error" }) @@ -1683,18 +1703,48 @@ function hostOf(url) { } } -/** Is this an https URL on one of SIGNED_HOSTS (its default port), the only ones the credentials go to? */ -function isSignedHostUrl(url) { +/** + * The station a credential belongs to: what it was signed in on. Only the + * CodeArts Agent sign-in can carry another than the mainland one (the + * browser sign-in is the mainland portal's), and a credential from before + * stations existed is the mainland's. + */ +function stationOf(cred) { + return STATIONS[cred?.station] ?? STATIONS.mainland +} + +/** + * `url` on the credential's own station: a mainland snap-access URL (the + * plugin's own constants, the config's `api`) goes to the same path on the + * station's snap-access host. Anything else stays as it is, and is signed or + * refused as it is. + */ +function onStation(url, cred) { + const station = stationOf(cred) + const s = String(url) + if (station === STATIONS.mainland) return s + return s === SNAP_HOST || s.startsWith(`${SNAP_HOST}/`) ? station.snap + s.slice(SNAP_HOST.length) : s +} + +/** The chat base (loader `baseURL`) of the credential's station. */ +const chatBaseOf = (cred) => `${stationOf(cred).snap}/api/v2` + +/** + * Is this an https URL (default port) on one of the hosts the credentials go + * to: SIGNED_HOSTS, or with `cred`, its own station's API hosts only? + */ +function isSignedHostUrl(url, cred) { try { const u = new URL(url) - return u.protocol === "https:" && SIGNED_HOSTS.has(u.host) + const hosts = cred ? new Set(apiHostsOf(stationOf(cred))) : SIGNED_HOSTS + return u.protocol === "https:" && hosts.has(u.host) } catch { return false } } -const refusalTo = (url) => - `refusing to sign a request to ${hostOf(url) || "an unknown host"}: only CodeArts' own hosts (${[...SIGNED_HOSTS].join(", ")}) get the account's credentials` +const refusalTo = (url, cred) => + `refusing to sign a request to ${hostOf(url) || "an unknown host"}: only CodeArts' own hosts (${(cred ? apiHostsOf(stationOf(cred)) : [...SIGNED_HOSTS]).join(", ")}) get the account's credentials` /** * The SDK-HMAC-SHA256 headers for one request (all but `host`, which fetch @@ -1704,7 +1754,7 @@ const refusalTo = (url) => * to wherever it points. */ async function signFor(cred, method, url, body, extraSigned) { - if (!isSignedHostUrl(url)) throw new Error(refusalTo(url)) + if (!isSignedHostUrl(url, cred)) throw new Error(refusalTo(url, cred)) const signed = await signRequestHuawei( cred.access_key_id, cred.secret_access_key, cred.security_token, method, url, body, extraSigned, @@ -1745,8 +1795,10 @@ function withSignInMark(res) { */ async function signedFetch(cred, input, init, context) { const req = typeof Request !== "undefined" && input instanceof Request ? input : null - const url = req ? req.url : String(input) - if (!isSignedHostUrl(url)) return errorResponse(400, "", refusalTo(url)) + // A station's account goes to its own station: a mainland snap-access URL + // (the config's `api`) is taken to the same path there. + const url = onStation(req ? req.url : String(input), cred) + if (!isSignedHostUrl(url, cred)) return errorResponse(400, "", refusalTo(url, cred)) const method = String(init?.method ?? req?.method ?? "GET").toUpperCase() const baseHeaders = new Headers(init?.headers ?? req?.headers) // magpie says another account, provider or group member follows this @@ -1921,6 +1973,7 @@ async function signedGet(url, cred, fetcher, extraUnsignedHeaders) { /** A signed GET's answer whatever its status (`{ ok, status, text }`), undefined when the vendor wasn't reached. */ async function signedRead(url, cred, fetcher, extraUnsignedHeaders) { + url = onStation(url, cred) try { const headers = await signFor(cred, "GET", url, new Uint8Array()) for (const [k, v] of Object.entries(extraUnsignedHeaders ?? {})) headers.set(k, v) @@ -1957,6 +2010,7 @@ function describeHttpFailure(status, text) { * Gives `{ ok: true, data }` or `{ ok: false, message }`, never throws. */ async function snapRequest(method, url, cred, fetcher, payload) { + url = onStation(url, cred) const body = payload === undefined ? new Uint8Array() : utf8(JSON.stringify(payload)) let res let text @@ -2388,8 +2442,13 @@ async function fetchRemoteModels(cred, fetcher, state) { const seen = new Set() const benefitIds = [] - const gatewayAnswer = await signedRead(OPENGW_GATEWAY_CONFIG_URL, cred, fetcher) - const gateway = !gatewayAnswer + // A station without opengw (the international one) has no free channel: + // no free models, and nothing of opengw's is asked. + const station = stationOf(cred) + const gatewayAnswer = station.opengw ? await signedRead(OPENGW_GATEWAY_CONFIG_URL, cred, fetcher) : undefined + const gateway = !station.opengw + ? [] + : !gatewayAnswer ? undefined : isNoBenefitChannel(gatewayAnswer.text) ? [] @@ -2461,6 +2520,15 @@ const CREDIT_METRIC_LABELS = { } const TOTAL_CREDIT_METRIC = "usageTotalPackageCredit" +/** Compact token counts the way an international account reads them (5000000 → "5.0M"). */ +function formatCount(n) { + const v = Math.max(0, Number.isFinite(n) ? n : 0) + if (v >= 1e9) return `${(v / 1e9).toFixed(1)}B` + if (v >= 1e6) return `${(v / 1e6).toFixed(1)}M` + if (v >= 1e4) return `${(v / 1e3).toFixed(1)}K` + return String(Math.round(v)) +} + /** Compact credit counts for the display string (12345 → "1.2万"). */ function formatCredit(n) { const v = Math.max(0, Number.isFinite(n) ? n : 0) @@ -2520,6 +2588,41 @@ function benefitWindow(raw, ids = BENEFIT_MODEL_FALLBACK) { } } +/** What a token metric is called on the card. */ +const TOKEN_METRIC_LABELS = { usageTokenChatMessages: "Tokens" } + +/** + * A token plan's windows from `statistics/plugin`'s metrics: one for each + * metric with an allowance (`package_token_amount` > 0), used being + * `usage_token_num`. The period is `start_date`–`end_date`, so the window + * resets (or the plan ends) at `end_date`. `gated`: a credit total already + * gates the account, so these only show. + */ +function tokenWindows(metrics, data, station, gated) { + const end = vendorDate(data.end_date) + const start = vendorDate(data.start_date) + const format = station === STATIONS.mainland ? formatCredit : formatCount + const out = [] + for (const item of metrics) { + const rec = asRecord(item) + const limit = num(rec.package_token_amount) + if (limit <= 0) continue + const used = Math.max(0, num(rec.usage_token_num)) + out.push({ + name: firstOf(TOKEN_METRIC_LABELS[rec.name], "Tokens"), + used: clamp((used / limit) * 100), + display: `${format(used)} / ${format(limit)}`, + amount: used, + limit, + unit: "tokens", + ...(end ? { resetsAt: new Date(end).toISOString() } : {}), + ...(end && start && end > start ? { span: Math.round((end - start) / 1000) } : {}), + ...(gated || out.length > 0 ? { aside: true } : {}), + }) + } + return out +} + /** * Map the account's `statistics/plugin` (+ free pool) answer to magpie's usage * shape. `batches` are its credit batches with their own expiry (see @@ -2530,7 +2633,7 @@ function benefitWindow(raw, ids = BENEFIT_MODEL_FALLBACK) { * `end_date`. A window's `runsOut` is only credit its own remainder holds: * none when that is 0, or when nothing in it lapses (#982). */ -function usageFromStatistics(raw, benefitRaw, { batches, grants, benefitIds, now = Date.now() } = {}) { +function usageFromStatistics(raw, benefitRaw, { batches, grants, benefitIds, now = Date.now(), station = STATIONS.mainland } = {}) { let data = raw if (raw && typeof raw.code === "number") { if (raw.code !== 0) return { error: firstOf(raw.message, raw.msg, `CodeArts code ${raw.code}`), windows: [] } @@ -2538,7 +2641,9 @@ function usageFromStatistics(raw, benefitRaw, { batches, grants, benefitIds, now } if (!data || typeof data !== "object") return { error: "CodeArts could not be parsed", windows: [] } const pkg = asRecord(data.package) - const plan = firstOf(pkg.package_name_cn, pkg.package_name_en, pkg.spec_code) + const plan = station === STATIONS.mainland + ? firstOf(pkg.package_name_cn, pkg.package_name_en, pkg.spec_code) + : firstOf(pkg.package_name_en, pkg.package_name_cn, pkg.spec_code) const metrics = Array.isArray(data.metrics) ? data.metrics : [] const known = batches ?? grantBatches(grants) // The plan's own batch ends when the month's allowance comes back. @@ -2599,11 +2704,249 @@ function usageFromStatistics(raw, benefitRaw, { batches, grants, benefitIds, now const totalLabel = CREDIT_METRIC_LABELS[TOTAL_CREDIT_METRIC] windows.sort((a, b) => (a.name === totalLabel ? -1 : b.name === totalLabel ? 1 : 0)) + // A plan metered in tokens (`is_token_package`, the international + // station's Free plan, #998): each metric's `usage_token_num` of its + // `package_token_amount`, for the period to `end_date`. The first one + // gates the account unless a credit total already does. + const tokens = pkg.is_token_package === true ? tokenWindows(metrics, data, station, windows.some((w) => !w.aside)) : [] + windows.push(...tokens) + const benefit = benefitRaw ? benefitWindow(benefitRaw, benefitIds) : undefined if (benefit) windows.push(benefit) if (windows.length > 0) return { plan: plan || undefined, signIn: "kept", windows } - return { plan: plan || undefined, windows, error: "该账号无积分额度" } + return { plan: plan || undefined, windows, error: pkg.is_token_package === true ? "该账号无 token 额度" : "该账号无积分额度" } +} + +// ---- the CodeArts Agent on this machine (#998) ------------------------------ +// +// The CodeArts Agent IDE keeps its own sign-in in its VS Code-style state +// database: `state.vscdb` (SQLite) in its globalStorage, table `ItemTable`, +// key `huaweicloud.codearts-snap`, whose `userInfoKey.originData` holds the +// STS triple (`accessKey`, `secretKey`, `securityToken`), `domainId`, +// `expiresAt` and `stationType`. The Windows path is the one measured in the +// issue (`%APPDATA%\codearts-agent\…`); the macOS and Linux ones follow where +// Electron keeps an app's user data on those systems. +// +// The file is the IDE's: it is only ever read, by copying it (and its +// journal) into a temporary folder of our own and opening the copy, so the +// IDE's database is never locked, opened or written. A sign-in from it is +// renewed by reading it again (the IDE renews its own, about every two hours); +// nothing is written back. A file that is missing, unreadable, half-written +// or holds no usable sign-in is unknown: nothing is offered from it, and an +// account signed in from it keeps its sign-in until it reads well again. + +const IDE_SOURCE = "codearts-agent-ide" +const IDE_STATE_KEY = "huaweicloud.codearts-snap" +const IDE_APP_DIR = "codearts-agent" +// A state database larger than this is not copied. +const IDE_DB_MAX_BYTES = 256 * 1024 * 1024 +// What the IDE calls its stations; a value not here is a station this plugin +// doesn't know, and nothing is signed in from it. +const IDE_STATIONS = { international: "international", mainland: "mainland", china: "mainland", cn: "mainland", domestic: "mainland" } + +/** Where the CodeArts Agent keeps `state.vscdb` on `platform`; "" when there is no place to look. */ +function ideStatePath(platform = process.platform, env = process.env, home = os.homedir()) { + const tail = [IDE_APP_DIR, "User", "globalStorage", "state.vscdb"] + if (platform === "win32") { + const appData = firstOf(env?.APPDATA) || (firstOf(home) ? path.win32.join(home, "AppData", "Roaming") : "") + return appData ? path.win32.join(appData, ...tail) : "" + } + if (platform === "darwin") return firstOf(home) ? path.posix.join(home, "Library", "Application Support", ...tail) : "" + // XDG: a relative XDG_CONFIG_HOME is ignored + const xdg = firstOf(env?.XDG_CONFIG_HOME) + const config = xdg && path.posix.isAbsolute(xdg) ? xdg : firstOf(home) ? path.posix.join(home, ".config") : "" + return config ? path.posix.join(config, ...tail) : "" +} + +/** Open a SQLite file with Bun's driver, or Node's. */ +async function openSqlite(file) { + try { + const { Database } = await import("bun:sqlite") + return new Database(file) + } catch (e) { + if (typeof Bun !== "undefined") throw e + } + const { DatabaseSync } = await import("node:sqlite") + return new DatabaseSync(file) +} + +/** The station an IDE's `stationType` names; null for one this plugin doesn't know. */ +function ideStationOf(stationType) { + if (stationType === undefined || stationType === null || stationType === "") return STATIONS.mainland + const id = IDE_STATIONS[String(stationType).trim().toLowerCase()] + return id ? STATIONS[id] : null +} + +/** + * The credential in the IDE's `huaweicloud.codearts-snap` value, as + * `{ cred }`, or `{ reason }` when it holds none. A reason never carries any + * of the credential's values. + */ +function ideCredentialFromValue(value) { + const text = typeof value === "string" ? value : value instanceof Uint8Array ? new TextDecoder().decode(value) : "" + if (!text) return { reason: "CodeArts Agent is not signed in on this machine" } + const stored = safeJson(text) + if (!stored) return { reason: "CodeArts Agent's stored sign-in could not be read" } + let user = stored.userInfoKey + if (typeof user === "string") user = safeJson(user) + let origin = asRecord(user).originData + if (typeof origin === "string") origin = safeJson(origin) + origin = asRecord(origin) + const ak = firstOf(origin.accessKey) + const sk = firstOf(origin.secretKey) + const token = firstOf(origin.securityToken) + if (!ak || !sk || !token) return { reason: "CodeArts Agent is not signed in on this machine (its stored sign-in has no credential)" } + const domainId = firstOf(String(origin.domainId ?? "")) + if (!domainId) return { reason: "CodeArts Agent's stored sign-in names no account (domainId)" } + const station = ideStationOf(origin.stationType) + if (!station) { + const said = String(origin.stationType) + return { reason: `CodeArts Agent is signed in on a station this plugin doesn't know (${/^[\w.-]{1,40}$/.test(said) ? said : "unrecognised"})` } + } + const expires = vendorDate(origin.expiresAt) + return { + cred: { + access_key_id: ak, + secret_access_key: sk, + security_token: token, + ...(expires ? { expires_at: new Date(expires).toISOString() } : {}), + domain_id: domainId, + station: station.id, + source: IDE_SOURCE, + }, + } +} + +/** + * Read the IDE's sign-in from `file`: `{ cred }`, or `{ reason, missing? }` + * when there is none to use (`missing`: no file at all). Never throws, never + * writes or opens the IDE's own file. + */ +async function readIdeCredential(file, { tmp = os.tmpdir() } = {}) { + if (!file) return { reason: "there is no place to look for CodeArts Agent on this system", missing: true } + let st + try { + st = fs.statSync(file) + } catch (e) { + return e?.code === "ENOENT" + ? { reason: "CodeArts Agent is not installed or not signed in on this machine", missing: true } + : { reason: "CodeArts Agent's state.vscdb could not be read" } + } + if (!st.isFile() || st.size === 0 || st.size > IDE_DB_MAX_BYTES) return { reason: "CodeArts Agent's state.vscdb could not be read" } + let dir = "" + let db + try { + dir = fs.mkdtempSync(path.join(tmp, "codearts-ide-")) + const copy = path.join(dir, "state.vscdb") + fs.writeFileSync(copy, fs.readFileSync(file), { mode: 0o600 }) + // What the IDE hasn't folded into the file yet: its write-ahead log, or a + // rollback journal a write left behind. The copy applies (or undoes) it. + for (const suffix of ["-wal", "-journal"]) { + let bytes + try { + bytes = fs.readFileSync(file + suffix) + } catch { + continue + } + fs.writeFileSync(copy + suffix, bytes, { mode: 0o600 }) + } + db = await openSqlite(copy) + // Finalized before the close: Bun's close leaves the file open while a + // statement lives, and on Windows an open file can't be removed, which + // would leave this copy of the sign-in behind. + const stmt = db.prepare("SELECT value FROM ItemTable WHERE key = ?") + let row + try { + row = stmt.get(IDE_STATE_KEY) + } finally { + stmt.finalize?.() + } + return ideCredentialFromValue(row?.value) + } catch { + return { reason: "CodeArts Agent's state.vscdb could not be read" } + } finally { + try { + db?.close() + } catch { + /* gone with the folder */ + } + if (dir) { + try { + fs.rmSync(dir, { recursive: true, force: true }) + } catch { + /* best effort */ + } + } + } +} + +/** + * A reader of the IDE's sign-in at `file`, read again only when the file + * changed (by its size, time and inode): a renewal that finds the IDE hasn't + * renewed yet asks again every half minute. + */ +function ideReader(file) { + let last = null + return async () => { + let stamp = "" + try { + const st = fs.statSync(file) + stamp = `${st.size}:${st.mtimeMs}:${st.ino}` + for (const suffix of ["-wal", "-journal"]) { + try { + const j = fs.statSync(file + suffix) + stamp += `|${suffix}:${j.size}:${j.mtimeMs}` + } catch { + /* none */ + } + } + } catch { + stamp = "" + } + if (stamp && last?.stamp === stamp) return last.result + const result = await readIdeCredential(file) + last = stamp ? { stamp, result } : null + return result + } +} + +/** + * Check an IDE credential with the station's `current/user` before signing in + * with it, and read the account's name there. `{ error }` only when CodeArts + * turns the credential away (401/403); a read that fails otherwise signs in + * all the same, without the name. + */ +async function checkIdeCredential(cred, fetcher) { + const answer = await signedRead(`${stationOf(cred).snap}/snap-manager/v1/current/user`, cred, fetcher, SNAP_EXTRA_HEADERS) + if (answer && (answer.status === 401 || answer.status === 403)) { + return { error: `CodeArts turned the CodeArts Agent's sign-in away (HTTP ${answer.status}): open CodeArts Agent so it signs in again, then try again` } + } + if (!answer?.ok) return { fields: {} } + const raw = asRecord(safeJson(answer.text)) + const user = asRecord("data" in raw ? raw.data : raw) + const name = firstOf(user.user_name, user.userName) + const id = firstOf(String(user.user_id ?? user.userId ?? "")) + return { fields: { ...(name ? { user_name: name } : {}), ...(id ? { user_id: id } : {}) } } +} + +/** + * The IDE's sign-in read again, in place of a renewal: the account's own, + * renewed by the IDE. Throws (for now, never for good) when the file can't be + * read, holds another account or station, or the IDE hasn't renewed it yet. + */ +async function renewFromIde(cred, read) { + const got = await read() + if (!got.cred) throw new Error(`CodeArts: ${got.reason}; open CodeArts Agent and sign in there`) + const next = got.cred + if (next.domain_id !== cred.domain_id) throw new Error("CodeArts: CodeArts Agent on this machine is signed in to another account now") + if (next.station !== stationOf(cred).id) throw new Error("CodeArts: CodeArts Agent on this machine is signed in on another station now") + if (next.access_key_id === cred.access_key_id && next.security_token === cred.security_token) { + throw new Error("CodeArts: CodeArts Agent hasn't renewed its sign-in yet; open CodeArts Agent on this machine") + } + // The account's own fields outlive the credential: its session and name. + const kept = Object.fromEntries(["session_id", "user_name", "user_id", "user_phone"].filter((k) => cred[k]).map((k) => [k, cred[k]])) + return { ...next, ...kept } } // ---- the plugin ------------------------------------------------------------- @@ -2648,7 +2991,16 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { // loaders, magpie's auth.refresh): STS spends a refresh token once, so a // second use of it would turn the account away. Whoever comes later with // the same token gets what that renewal gave. + // The CodeArts Agent on this machine (its state.vscdb), read again only + // when it changed. + // (`ideStateFile`, or MAGPIE_CODEARTS_IDE_STATE: another file, for tests) + const ideFile = typeof options?.ideStateFile === "string" + ? options.ideStateFile + : firstOf(process.env.MAGPIE_CODEARTS_IDE_STATE) || ideStatePath() + const readIde = ideReader(ideFile) const renewOnce = async (cred) => { + // A sign-in from the IDE is renewed by the IDE: read it again, never STS. + if (cred.source === IDE_SOURCE) return renewFromIde(cred, readIde) const token = firstOf(cred.refresh_token) if (!token) return refreshCredential(cred, fetcher) const state = await stateOf(cred) @@ -2732,6 +3084,95 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { } } + const browserMethod = { + type: "oauth", + label: "Sign in with Huawei Cloud", + async authorize() { + const flow = await startOAuthFlow(fetcher) + return { + url: flow.loginUrl, + 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 { + const outcome = await flow.result + const cred = safeJson(outcome.access) + if (!cred?.access_key_id) return { type: "failed", error: "CodeArts did not return a credential" } + // The card's name is the phone (one read away, best effort: + // 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)) } + // 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. + const record = { + type: "success", + 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 { + await flow.close() + } + }, + } + }, + } + + // Sign in from the CodeArts Agent on this machine: its own stored sign-in, + // read (never written), checked once with the station, and renewed by + // reading it again. No browser, no refresh token, and nothing of it reaches + // the OfficeAce card: that one signs in on its own. + const ideMethod = { + type: "oauth", + label: "Use the CodeArts Agent on this machine", + async authorize() { + return { + url: "", + instructions: "Reads the sign-in of the CodeArts Agent on this computer. Keep CodeArts Agent signed in: its sign-in lasts about two hours, and the renewed one is read from there.", + method: "auto", + async callback() { + try { + const read = await readIde() + if (!read.cred) return { type: "failed", error: read.reason } + if (Date.parse(read.cred.expires_at ?? "") <= now()) { + return { type: "failed", error: "CodeArts Agent's sign-in has expired: open CodeArts Agent so it renews it, then try again" } + } + const checked = await checkIdeCredential(read.cred, fetcher) + if (checked.error) return { type: "failed", error: checked.error } + const cred = { ...read.cred, ...checked.fields, session_id: randomHex(16) } + const identity = accountIdentityOf(cred) + return { + type: "success", + access: JSON.stringify(cred), + expires: expiresFromCredential(cred), + accountId: identity.id, + uid: identity.id, + } + } catch (e) { + return { type: "failed", error: e?.message ?? String(e) } + } + }, + } + }, + } + return { // The provider and the models it has before anyone is signed in. config: async (config) => { @@ -2858,6 +3299,8 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { // One account = one upstream session and one in-flight budget. const ids = await accountSessionIds(cred) const state = accountState(ids.sessionId) + // A station without opengw has no free models: none is sent as one. + if (!stationOf(cred).opengw && state.benefit === null) state.benefit = new Set() const context = { ...ids, gate: state.gate, @@ -2875,7 +3318,7 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { signInDead: () => signInDead, } return { - baseURL: CHAT_API_BASE, + baseURL: chatBaseOf(cred), async fetch(input, init = {}) { const c = await current() return signedFetch(c, input, init, context) @@ -2891,16 +3334,19 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { const identity = accountIdentityOf(cred).id if (identity) noteProviderAccount(PROVIDER, identity) try { + const station = stationOf(cred) const text = await signedGet(SNAP_STATISTICS_URL, cred, fetcher, SNAP_EXTRA_HEADERS) if (text === undefined) return { error: "CodeArts answered an error", windows: [] } const state = await stateOf(cred) // The free pool only once today's benefit is the account's; best - // effort either way: a credit account without one is normal. - const free = state.benefit === null || state.benefit.size > 0 + // effort either way: a credit account without one is normal. A + // station without opengw has none. + const free = !!station.opengw && (state.benefit === null || state.benefit.size > 0) const benefitText = free ? await signedGet(BENEFIT_BALANCE_URL, cred, fetcher) : undefined // Each batch's own expiry, read again every ten minutes (and after a // check-in); a failed read keeps the last one, else the ledger stands in. - if (!state.batchesAt || Date.now() - state.batchesAt > CREDIT_BATCHES_TTL_MS) { + // The international station's plans are metered in tokens: no batches. + if (station === STATIONS.mainland && (!state.batchesAt || Date.now() - state.batchesAt > CREDIT_BATCHES_TTL_MS)) { const read = await fetchCreditBatches(cred, fetcher).catch(() => undefined) if (read) state.batches = read state.batchesAt = Date.now() @@ -2909,6 +3355,7 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { batches: state.batches, grants: readGrants(ledgerPath, await ledgerKey(cred)), benefitIds: state.benefit ? [...state.benefit] : BENEFIT_MODEL_FALLBACK, + station, }) // The card names the account by its phone, not by IAM's `hw…` id or // its URN — read once here for an account whose credential predates @@ -2926,6 +3373,9 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { async checkin(getAuth) { const cred = credentialOf(await getAuth()) if (!cred?.access_key_id) return { outcome: "failed", message: "not signed in" } + // The international station has no 「每日领取」 (its ops/delivery + // answers 400 HDN.1000). + if (stationOf(cred) !== STATIONS.mainland) return { outcome: "inactive", message: "no daily check-in on this station" } const key = await ledgerKey(cred) const state = await stateOf(cred) const today = beijingDay() @@ -2953,58 +3403,12 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { return r }, - methods: [ - { - type: "oauth", - label: "Sign in with Huawei Cloud", - async authorize() { - const flow = await startOAuthFlow(fetcher) - return { - url: flow.loginUrl, - 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 { - const outcome = await flow.result - const cred = safeJson(outcome.access) - if (!cred?.access_key_id) return { type: "failed", error: "CodeArts did not return a credential" } - // The card's name is the phone (one read away, best effort: - // 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)) } - // 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. - const record = { - type: "success", - 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 { - await flow.close() - } - }, - } - }, - }, - ], + // The browser sign-in first, always; the CodeArts Agent's second, only + // while the IDE's state file is there (the host picks a method by its + // place, so the browser one keeps its). + get methods() { + return ideFile && fs.existsSync(ideFile) ? [browserMethod, ideMethod] : [browserMethod] + }, }, } } @@ -3072,6 +3476,9 @@ export const _internal = { isRegularModel, queueInfoOf, waitInQueue, TRACE_QUEUE_URL, SESSION_HEADER, snapRequest, dailyCheckin, parseModelInfo, extractArray, fetchRemoteModels, creditWindow, benefitWindow, usageFromStatistics, + STATIONS, stationOf, onStation, chatBaseOf, apiHostsOf, tokenWindows, formatCount, + IDE_SOURCE, IDE_STATE_KEY, ideStatePath, ideStationOf, ideCredentialFromValue, readIdeCredential, ideReader, + checkIdeCredential, renewFromIde, openSqlite, } // ═══════════════════════════════════════════════════════════════════════════ diff --git a/packages/codearts/index.test.mjs b/packages/codearts/index.test.mjs index 2ee8b22..2e3033a 100644 --- a/packages/codearts/index.test.mjs +++ b/packages/codearts/index.test.mjs @@ -24,6 +24,10 @@ const ledgerDir = fs.mkdtempSync(path.join(os.tmpdir(), "codearts-ledger-")) process.env.MAGPIE_CODEARTS_LEDGER = path.join(ledgerDir, "default.json") test.after(() => fs.rmSync(ledgerDir, { recursive: true, force: true })) +// Never the real CodeArts Agent's state.vscdb: a plugin made here without an +// `ideStateFile` of its own looks at a file that isn't there. +process.env.MAGPIE_CODEARTS_IDE_STATE = path.join(ledgerDir, "no-ide", "state.vscdb") + const buf = (s) => new TextEncoder().encode(s) // ---- crypto primitives ----------------------------------------------------- @@ -1684,7 +1688,11 @@ test("a 403 is a sign-in the account no longer has, on chats and other requests }) test("isSignedHostUrl takes only https URLs on the two hosts the plugin calls, by name", () => { - assert.deepEqual([...x.SIGNED_HOSTS].sort(), ["opengw.developer.huaweicloud.com", "snap-access.cn-north-4.myhuaweicloud.com"]) + assert.deepEqual([...x.SIGNED_HOSTS].sort(), [ + "opengw.developer.huaweicloud.com", + "snap-access.ap-southeast-1.myhuaweicloud.com", + "snap-access.cn-north-4.myhuaweicloud.com", + ]) assert.equal(x.isSignedHostUrl(CHAT_URL), true) assert.equal(x.isSignedHostUrl(x.BENEFIT_CLAIM_URL), true) assert.equal(x.isSignedHostUrl("https://SNAP-ACCESS.cn-north-4.myhuaweicloud.com/api/v2/chat/completions"), true, "a hostname has no case") @@ -3972,3 +3980,436 @@ test("folding a stream keeps two ids at one index as two calls", () => { { index: 0, id: "call_fixture_A", function: { arguments: '"A"}' } }, ]), [["call_fixture_A", "fixture_alpha", '{"key":"A"}']]) }) + +// ---- the international station and the CodeArts Agent sign-in (#998) ------- + +const INTL = "https://snap-access.ap-southeast-1.myhuaweicloud.com" +const intlCred = { access_key_id: "IAK", secret_access_key: "ISK", security_token: "IST", domain_id: "dom1", station: "international", source: x.IDE_SOURCE, session_id: "s1" } + +test("the international snap-access host is signed; lookalikes and other regions are not", () => { + assert.equal(x.isSignedHostUrl(`${INTL}/snap-manager/v1/statistics/plugin`), true) + assert.equal(x.isSignedHostUrl(`${INTL}/snap-manager/v1/statistics/plugin`, intlCred), true) + for (const other of [ + "https://snap-access.ap-southeast-1.myhuaweicloud.com.evil.com/api", + "https://evil-snap-access.ap-southeast-1.myhuaweicloud.com/api", + "https://snap-access.ap-southeast-2.myhuaweicloud.com/api", + "https://snap-access.ap-southeast-3.myhuaweicloud.com/api", + "https://snap-access.af-south-1.myhuaweicloud.com/api", + "https://console-intl.huaweicloud.com/devcloud/", + "http://snap-access.ap-southeast-1.myhuaweicloud.com/api", + "https://snap-access.ap-southeast-1.myhuaweicloud.com:8443/api", + ]) { + assert.equal(x.isSignedHostUrl(other), false, other) + assert.equal(x.isSignedHostUrl(other, intlCred), false, other) + } +}) + +test("a credential is signed only for its own station's hosts", async () => { + // international: not the mainland's snap-access, nor opengw + for (const url of [CHAT_URL, x.BENEFIT_CLAIM_URL, x.OPENGW_GATEWAY_CONFIG_URL]) { + assert.equal(x.isSignedHostUrl(url, intlCred), false, url) + await assert.rejects(x.signFor(intlCred, "GET", url, new Uint8Array()), /refusing to sign/) + } + // mainland (no station said): not the international host + assert.equal(x.isSignedHostUrl(`${INTL}/api/v2/chat/completions`, signedCred), false) + await assert.rejects(x.signFor(signedCred, "GET", `${INTL}/x`, new Uint8Array()), /refusing to sign a request to snap-access\.ap-southeast-1/) + const ok = await x.signFor(intlCred, "GET", `${INTL}/x`, new Uint8Array()) + assert.match(ok.get("authorization"), /^SDK-HMAC-SHA256 Access=IAK,/) +}) + +test("onStation takes the plugin's mainland snap URLs to the credential's station, and nothing else", () => { + assert.equal(x.onStation(x.SNAP_STATISTICS_URL, intlCred), `${INTL}/snap-manager/v1/statistics/plugin`) + assert.equal(x.onStation(CHAT_URL, intlCred), `${INTL}/api/v2/chat/completions`) + assert.equal(x.onStation(CHAT_URL, signedCred), CHAT_URL) + // a lookalike stays itself (and is then refused) + const look = "https://snap-access.cn-north-4.myhuaweicloud.com.evil.com/api" + assert.equal(x.onStation(look, intlCred), look) + assert.equal(x.onStation(x.BENEFIT_CLAIM_URL, intlCred), x.BENEFIT_CLAIM_URL) + assert.equal(x.chatBaseOf(intlCred), `${INTL}/api/v2`) + assert.equal(x.chatBaseOf(signedCred), x.CHAT_API_BASE) + assert.equal(x.stationOf({ station: "elsewhere" }), x.STATIONS.mainland) +}) + +// The issue's own statistics/plugin answer, as the international host gave it. +const intlStatistics = { + metrics: [ + { name: "usageDataChatMessages", value: -1, usage_token_num: 0, package_token_amount: 0, show: false }, + { name: "usageTokenChatMessages", value: 0, usage_token_num: 131, package_token_amount: 5000000, show: true }, + ], + start_date: "2026-11-11", + end_date: "2026-12-12", + package: { + spec_code: "codearts.agent.trial", + status: "normal", + package_name_en: "Free", + package_name_cn: "体验版", + package_url: "https://console-intl.huaweicloud.com/devcloud/?region=ap-southeast-1&locale=zh-cn#/change-new/apply?", + is_token_package: true, + is_credit_package: false, + }, + is_teadmin: true, + is_white_list: false, +} + +test("usageFromStatistics: a token package is a token window, used of package_token_amount, to end_date", () => { + const u = x.usageFromStatistics(intlStatistics, undefined, { station: x.STATIONS.international, batches: [] }) + assert.equal(u.plan, "Free") + assert.equal(u.signIn, "kept") + assert.equal(u.error, undefined) + assert.equal(u.windows.length, 1) + const [w] = u.windows + assert.equal(w.name, "Tokens") + assert.equal(w.amount, 131) + assert.equal(w.limit, 5000000) + assert.equal(w.unit, "tokens") + assert.equal(w.display, "131 / 5.0M") + assert.ok(Math.abs(w.used - 0.00262) < 1e-9) + assert.equal(w.resetsAt, "2026-12-11T16:00:00.000Z") + assert.equal(w.span, 31 * 86400) + assert.equal(w.aside, undefined, "the token allowance gates the account") + // the mainland names the same plan in Chinese + assert.equal(x.usageFromStatistics(intlStatistics, undefined, { batches: [] }).plan, "体验版") + // not a token package: no token window + const credit = { ...intlStatistics, package: { ...intlStatistics.package, is_token_package: false } } + assert.equal(x.usageFromStatistics(credit, undefined, { batches: [] }).windows.length, 0) + // a spent allowance is 100% + const spent = { ...intlStatistics, metrics: [{ name: "usageTokenChatMessages", usage_token_num: 6e6, package_token_amount: 5e6 }] } + assert.equal(x.usageFromStatistics(spent, undefined, { station: x.STATIONS.international, batches: [] }).windows[0].used, 100) +}) + +// One statement, finalized: Bun keeps a file open while a statement lives. +function sqlRun(db, sql, ...params) { + const stmt = db.prepare(sql) + try { + stmt.run(...params) + } finally { + stmt.finalize?.() + } +} + +// A state.vscdb as the CodeArts Agent writes it, in a folder of the test's own. +async function ideFixture({ value, wal = false, raw } = {}) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "codearts-ide-test-")) + test.after(() => fs.rmSync(dir, { recursive: true, force: true })) + const file = path.join(dir, "state.vscdb") + if (raw !== undefined) { + fs.writeFileSync(file, raw) + return { file, dir } + } + const db = await x.openSqlite(file) + if (wal) db.exec("PRAGMA journal_mode=WAL") + db.exec("CREATE TABLE IF NOT EXISTS ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)") + sqlRun(db, "INSERT INTO ItemTable (key, value) VALUES (?, ?)", "workbench.other", "{}") + if (value !== undefined) sqlRun(db, "INSERT INTO ItemTable (key, value) VALUES (?, ?)", x.IDE_STATE_KEY, value) + // with WAL the connection stays open, so the row is still only in the -wal + if (!wal) db.close() + return { file, dir, db } +} + +const ideValue = (origin, { asString = false } = {}) => JSON.stringify({ userInfoKey: { originData: asString ? JSON.stringify(origin) : origin, other: 1 } }) +const ideOrigin = (over = {}) => ({ + accessKey: "IDEAK1", secretKey: "IDESECRET1", securityToken: "IDETOKEN1", domainId: "dom1", + expiresAt: Date.parse("2030-01-01T00:00:00Z"), loginType: "codearts", stationType: "international", ...over, +}) +const SECRETS = /IDEAK|IDESECRET|IDETOKEN/ + +test("ideStatePath: each system's own place for the CodeArts Agent's state.vscdb", () => { + assert.equal( + x.ideStatePath("win32", { APPDATA: "C:\\Users\\a\\AppData\\Roaming" }, "C:\\Users\\a"), + "C:\\Users\\a\\AppData\\Roaming\\codearts-agent\\User\\globalStorage\\state.vscdb", + ) + assert.equal(x.ideStatePath("win32", {}, "C:\\Users\\a"), "C:\\Users\\a\\AppData\\Roaming\\codearts-agent\\User\\globalStorage\\state.vscdb") + assert.equal(x.ideStatePath("darwin", { XDG_CONFIG_HOME: "/x" }, "/Users/a"), "/Users/a/Library/Application Support/codearts-agent/User/globalStorage/state.vscdb") + assert.equal(x.ideStatePath("linux", {}, "/home/a"), "/home/a/.config/codearts-agent/User/globalStorage/state.vscdb") + assert.equal(x.ideStatePath("linux", { XDG_CONFIG_HOME: "/xdg" }, "/home/a"), "/xdg/codearts-agent/User/globalStorage/state.vscdb") + assert.equal(x.ideStatePath("linux", { XDG_CONFIG_HOME: "rel" }, "/home/a"), "/home/a/.config/codearts-agent/User/globalStorage/state.vscdb") + assert.equal(x.ideStatePath("linux", {}, ""), "") + assert.equal(x.ideStatePath("win32", {}, ""), "") +}) + +test("ideStatePath on this system is where this system keeps it", () => { + const got = x.ideStatePath() + if (process.platform === "win32") { + assert.equal(got, path.join(process.env.APPDATA, "codearts-agent", "User", "globalStorage", "state.vscdb")) + } else if (process.platform === "darwin") { + assert.equal(got, path.join(os.homedir(), "Library", "Application Support", "codearts-agent", "User", "globalStorage", "state.vscdb")) + } else { + const xdg = process.env.XDG_CONFIG_HOME + const base = xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), ".config") + assert.equal(got, path.join(base, "codearts-agent", "User", "globalStorage", "state.vscdb")) + } +}) + +test("readIdeCredential reads the IDE's sign-in from a copy, never touching its file", async () => { + for (const asString of [false, true]) { + const { file, dir } = await ideFixture({ value: ideValue(ideOrigin(), { asString }) }) + const before = fs.readFileSync(file) + const mtime = fs.statSync(file).mtimeMs + const r = await x.readIdeCredential(file) + assert.deepEqual(r.cred, { + access_key_id: "IDEAK1", secret_access_key: "IDESECRET1", security_token: "IDETOKEN1", + expires_at: "2030-01-01T00:00:00.000Z", domain_id: "dom1", station: "international", source: x.IDE_SOURCE, + }) + assert.deepEqual(fs.readFileSync(file), before, "the IDE's file is unchanged") + assert.equal(fs.statSync(file).mtimeMs, mtime) + assert.deepEqual(fs.readdirSync(dir), ["state.vscdb"], "no journal, -wal or -shm made beside it") + } + // a value stored as bytes, and a mainland one (no stationType) + const { file } = await ideFixture({ value: Buffer.from(ideValue(ideOrigin({ stationType: undefined, expiresAt: "2030-01-01T00:00:00Z" }))) }) + const r = await x.readIdeCredential(file) + assert.equal(r.cred.station, "mainland") + assert.equal(r.cred.expires_at, "2030-01-01T00:00:00.000Z") +}) + +test("readIdeCredential leaves no copy of the sign-in behind, read or not", async () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "codearts-ide-tmp-")) + test.after(() => fs.rmSync(tmp, { recursive: true, force: true })) + const good = await x.readIdeCredential((await ideFixture({ value: ideValue(ideOrigin()) })).file, { tmp }) + assert.equal(good.cred?.access_key_id, "IDEAK1", good.reason) + await x.readIdeCredential((await ideFixture({ raw: "not a database" })).file, { tmp }) + await x.readIdeCredential((await ideFixture({})).file, { tmp }) + assert.deepEqual(fs.readdirSync(tmp), []) +}) + +test("readIdeCredential reads a row still in the IDE's write-ahead log", async () => { + const { file, db } = await ideFixture({ value: ideValue(ideOrigin()), wal: true }) + try { + assert.ok(fs.existsSync(`${file}-wal`)) + const r = await x.readIdeCredential(file) + assert.equal(r.cred?.access_key_id, "IDEAK1") + } finally { + db.close() + } +}) + +test("readIdeCredential reads while the IDE holds its database locked: it reads a copy, never the IDE's file", async () => { + const { file } = await ideFixture({ value: ideValue(ideOrigin()) }) + const ide = await x.openSqlite(file) + try { + ide.exec("BEGIN EXCLUSIVE") + const r = await x.readIdeCredential(file) + assert.equal(r.cred?.access_key_id, "IDEAK1", r.reason) + } finally { + ide.exec("ROLLBACK") + ide.close() + } +}) + +test("readIdeCredential: missing, unreadable, half-written or empty is unknown, and says no secret", async () => { + const cases = [] + cases.push(["missing", await x.readIdeCredential(path.join(os.tmpdir(), `no-such-${process.pid}`, "state.vscdb"))]) + cases.push(["no path", await x.readIdeCredential("")]) + cases.push(["not sqlite", await x.readIdeCredential((await ideFixture({ raw: "IDEAK1 IDESECRET1 garbage" })).file)]) + cases.push(["empty file", await x.readIdeCredential((await ideFixture({ raw: "" })).file)]) + const whole = fs.readFileSync((await ideFixture({ value: ideValue(ideOrigin()) })).file) + cases.push(["half-written", await x.readIdeCredential((await ideFixture({ raw: whole.subarray(0, Math.floor(whole.length / 2)) })).file)]) + cases.push(["a folder", await x.readIdeCredential((await ideFixture({ value: ideValue(ideOrigin()) })).dir)]) + cases.push(["no row", await x.readIdeCredential((await ideFixture({})).file)]) + cases.push(["not json", await x.readIdeCredential((await ideFixture({ value: '{"userInfoKey": IDEAK1' })).file)]) + cases.push(["no token", await x.readIdeCredential((await ideFixture({ value: ideValue(ideOrigin({ securityToken: "" })) })).file)]) + cases.push(["no secret", await x.readIdeCredential((await ideFixture({ value: ideValue(ideOrigin({ secretKey: undefined })) })).file)]) + cases.push(["no domain", await x.readIdeCredential((await ideFixture({ value: ideValue(ideOrigin({ domainId: "" })) })).file)]) + cases.push(["signed out", await x.readIdeCredential((await ideFixture({ value: JSON.stringify({ userInfoKey: {} }) })).file)]) + cases.push(["unknown station", await x.readIdeCredential((await ideFixture({ value: ideValue(ideOrigin({ stationType: "mars" })) })).file)]) + for (const [name, r] of cases) { + assert.equal(r.cred, undefined, name) + assert.equal(typeof r.reason, "string", name) + assert.ok(r.reason.length > 0, name) + assert.doesNotMatch(r.reason, SECRETS, name) + } + assert.equal(cases[0][1].missing, true) + assert.match(cases.at(-1)[1].reason, /mars/) + if (process.platform !== "win32" && process.getuid?.() !== 0) { + const { file } = await ideFixture({ value: ideValue(ideOrigin()) }) + fs.chmodSync(file, 0o000) + try { + const r = await x.readIdeCredential(file) + assert.equal(r.cred, undefined) + assert.match(r.reason, /could not be read/) + } finally { + fs.chmodSync(file, 0o600) + } + } +}) + +test("the CodeArts Agent sign-in is offered only while its state file is there", async () => { + const none = await CodeArtsAuthPlugin({ client: {} }, { ideStateFile: path.join(os.tmpdir(), `no-ide-${process.pid}`, "state.vscdb") }) + assert.equal(none.auth.methods.length, 1) + const { file } = await ideFixture({ value: ideValue(ideOrigin()) }) + const plugin = await CodeArtsAuthPlugin({ client: {} }, { ideStateFile: file }) + assert.equal(plugin.auth.methods.length, 2) + assert.equal(plugin.auth.methods[0].label, "Sign in with Huawei Cloud", "the browser one keeps its place") + assert.equal(plugin.auth.methods[1].type, "oauth") + assert.match(plugin.auth.methods[1].label, /CodeArts Agent/) + fs.rmSync(file) + assert.equal(plugin.auth.methods.length, 1, "read again each time") +}) + +async function ideSignIn(plugin) { + const flow = await plugin.auth.methods[1].authorize() + assert.equal(flow.url, "") + assert.equal(flow.method, "auto") + return flow.callback() +} + +test("signing in from the CodeArts Agent: checked with its station, the account its domainId", async () => { + const { file } = await ideFixture({ value: ideValue(ideOrigin()) }) + const calls = [] + const fetcher = async (url, init) => { + calls.push({ url: String(url), auth: new Headers(init?.headers).get("authorization") }) + return new Response(JSON.stringify({ domain_id: "dom1", user_id: "u1", user_name: "alice" }), { status: 200 }) + } + const plugin = await CodeArtsAuthPlugin({ client: { auth: { set: async () => assert.fail("nothing is written") } } }, { fetch: fetcher, ideStateFile: file }) + const r = await ideSignIn(plugin) + assert.equal(r.type, "success", r.error) + assert.equal(r.accountId, "dom1") + assert.equal(r.uid, "dom1") + assert.equal(r.refresh, undefined) + assert.equal(r.expires, Date.parse("2030-01-01T00:00:00Z")) + const cred = JSON.parse(r.access) + assert.equal(cred.station, "international") + assert.equal(cred.source, x.IDE_SOURCE) + assert.equal(cred.user_name, "alice") + assert.match(cred.session_id, /^[0-9a-f]{32}$/) + assert.deepEqual(calls.map((c) => c.url), [`${INTL}/snap-manager/v1/current/user`]) + assert.match(calls[0].auth, /^SDK-HMAC-SHA256 Access=IDEAK1,/) +}) + +test("signing in from the CodeArts Agent fails, without a secret, when there is nothing good to sign in with", async () => { + // turned away by the station + { + const { file } = await ideFixture({ value: ideValue(ideOrigin()) }) + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => new Response('{"error_code":"APIG.0301"}', { status: 401 }), ideStateFile: file }) + const r = await ideSignIn(plugin) + assert.equal(r.type, "failed") + assert.match(r.error, /401/) + assert.doesNotMatch(r.error, SECRETS) + } + // expired: not even asked + { + const { file } = await ideFixture({ value: ideValue(ideOrigin({ expiresAt: Date.parse("2020-01-01T00:00:00Z") })) }) + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => assert.fail("no request"), ideStateFile: file }) + const r = await ideSignIn(plugin) + assert.equal(r.type, "failed") + assert.match(r.error, /expired/) + } + // gone between the listing and the sign-in + { + const { file } = await ideFixture({ value: ideValue(ideOrigin()) }) + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => assert.fail("no request"), ideStateFile: file }) + const flow = await plugin.auth.methods[1].authorize() + fs.rmSync(file) + const r = await flow.callback() + assert.equal(r.type, "failed") + assert.doesNotMatch(r.error, SECRETS) + } + // a vendor that can't be reached still signs in (the check is for a refusal) + { + const { file } = await ideFixture({ value: ideValue(ideOrigin()) }) + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => { throw new Error("offline") }, ideStateFile: file }) + assert.equal((await ideSignIn(plugin)).type, "success") + } +}) + +test("an IDE sign-in is renewed by reading the IDE's file again, never by STS", async () => { + const fx = await ideFixture({ value: ideValue(ideOrigin()) }) + const fetcher = async (url) => { + assert.notEqual(String(url), x.STS_TOKEN_ENDPOINT, "no STS for an IDE sign-in") + return new Response("{}", { status: 200 }) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher, ideStateFile: fx.file }) + const signed = await ideSignIn(plugin) + const cred = JSON.parse(signed.access) + const auth = { type: "oauth", access: signed.access, expires: signed.expires, accountId: signed.accountId } + // the IDE hasn't renewed yet: for now, not for good + const unchanged = await plugin.auth.refresh(auth).then(() => null, (e) => e) + assert.ok(unchanged, "an unchanged file is no renewal") + assert.notEqual(unchanged.signIn, "expired") + assert.equal(x.isPermanentRefreshFailure(unchanged), false) + assert.doesNotMatch(unchanged.message, SECRETS) + // the IDE renewed: the new triple, the same account and session + await rewriteIde(fx.file, ideValue(ideOrigin({ accessKey: "IDEAK2", securityToken: "IDETOKEN2", expiresAt: Date.parse("2031-01-01T00:00:00Z") }))) + const r = await plugin.auth.refresh(auth) + const next = JSON.parse(r.access) + assert.equal(next.access_key_id, "IDEAK2") + assert.equal(next.security_token, "IDETOKEN2") + assert.equal(next.session_id, cred.session_id) + assert.equal(next.source, x.IDE_SOURCE) + assert.equal(r.expires, Date.parse("2031-01-01T00:00:00Z")) + assert.equal(r.uid, "dom1") + assert.equal(r.refresh, undefined) + // another account in the IDE now, or the file gone: for now, never for good + await rewriteIde(fx.file, ideValue(ideOrigin({ accessKey: "IDEAK3", domainId: "dom2" }))) + const other = await plugin.auth.refresh({ ...auth, access: r.access }).then(() => null, (e) => e) + assert.match(other?.message ?? "", /another account/) + assert.notEqual(other.signIn, "expired") + fs.rmSync(fx.file) + const gone = await plugin.auth.refresh({ ...auth, access: r.access }).then(() => null, (e) => e) + assert.ok(gone) + assert.notEqual(gone.signIn, "expired") + assert.doesNotMatch(gone.message, SECRETS) +}) + +// The IDE writes its file again: a new state.vscdb in the same place. +async function rewriteIde(file, value) { + const db = await x.openSqlite(file) + sqlRun(db, "INSERT INTO ItemTable (key, value) VALUES (?, ?)", x.IDE_STATE_KEY, value) + db.close() + // a clock coarse enough to give the same mtime still sees the size or inode move + const t = new Date(Date.now() + 5000) + fs.utimesSync(file, t, t) +} + +test("an international account chats, reads and renews on its own station only", async () => { + const fx = await ideFixture({ value: ideValue(ideOrigin()) }) + const urls = [] + let chats = 0 + const fetcher = async (url, init) => { + const u = String(url) + urls.push(u) + assert.ok(u.startsWith(`${INTL}/`), `only the international host: ${u}`) + if (u.endsWith("/current/user")) return new Response("{}", { status: 200 }) + if (u.endsWith("/chat/completions")) { + chats++ + const auth = new Headers(init.headers).get("authorization") + // the first goes with a credential the vendor calls expired + if (chats === 1) return new Response(JSON.stringify({ error_code: "APIG.0602", error_msg: "the security token has expired" }), { status: 400 }) + assert.match(auth, /Access=IDEAK2,/) + return sseResponse(okStream) + } + if (u.includes("/statistics/plugin")) return new Response(JSON.stringify(intlStatistics), { status: 200 }) + return new Response('{"error_code":"APIG.0101"}', { status: 404 }) + } + const sets = [] + const plugin = await CodeArtsAuthPlugin({ client: { auth: { set: async (o) => sets.push(o) } } }, { fetch: fetcher, ideStateFile: fx.file }) + const signed = await ideSignIn(plugin) + const auth = { type: "oauth", access: signed.access, expires: signed.expires, accountId: signed.accountId } + const loaded = await plugin.auth.loader(async () => auth) + assert.equal(loaded.baseURL, `${INTL}/api/v2`) + await rewriteIde(fx.file, ideValue(ideOrigin({ accessKey: "IDEAK2", securityToken: "IDETOKEN2" }))) + // the config's mainland `api` is taken to the account's station + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [], stream: true })) + assert.equal(res.status, 200) + assert.equal(chats, 2) + assert.equal(JSON.parse(sets.at(-1).body.access).access_key_id, "IDEAK2") + // opengw is no host of this account + const refused = await loaded.fetch(x.OPENGW_GATEWAY_CONFIG_URL, { method: "GET" }) + assert.equal(refused.status, 400) + + const usage = await plugin.auth.usage(async () => auth) + assert.equal(usage.plan, "Free") + assert.equal(usage.windows.length, 1) + assert.equal(usage.windows[0].limit, 5000000) + assert.equal(usage.user, undefined, "a hw/id name is no name") + // its models: whatever the station answers, nothing asked of opengw + await plugin.provider.models({ models: {} }, { auth }) + const checkin = await plugin.auth.checkin(async () => auth) + assert.equal(checkin.outcome, "inactive") + assert.ok(!urls.some((u) => u.includes("opengw") || u.includes("cn-north-4"))) +}) + +test("a mainland account's loader keeps the mainland chat base", async () => { + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => sseResponse(okStream) }) + const loaded = await plugin.auth.loader(async () => makeAuth(await makeCred())) + assert.equal(loaded.baseURL, x.CHAT_API_BASE) +}) diff --git a/packages/codearts/package.json b/packages/codearts/package.json index a563f64..e160fb6 100644 --- a/packages/codearts/package.json +++ b/packages/codearts/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-codearts-auth", - "version": "0.3.8", + "version": "0.3.10", "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": "./opencode.mjs",