From b850c9da3d4983059dbb31a8cb479ca9b6b6b8de Mon Sep 17 00:00:00 2001 From: MYCF711 <1451895195@qq.com> Date: Thu, 29 Oct 2026 21:35:28 +0800 Subject: [PATCH] codearts 0.2.5: the card names the account by its phone, not by IAM's URN (#483) The card names a CodeArts account by its masked phone (138****8000), read from IAM once per account (6h cache), while accountId stays the IAM URN, the account's identity. A renewal keeps the phone, reads it once for an account signed in before 0.2.5, never renames a named account, and gives an account stored without an accountId the URN. Reviewed at fa5aaae (round 4). Run on mote (macOS, Node 22, Bun 1.4.2) in a sandbox HOME, at that head: - node --test packages/codearts/index.test.mjs: 125 pass / 0 fail - bun test packages/codearts/index.test.mjs: 125 pass / 0 fail - bun scripts/check.mjs codearts: ok Broken by hand, each red at the test it should hit: - sign-in accountId: identity.id -> identity.name (index.mjs:2746): "a sign-in names the account by its URN while the card shows the phone" red (124/1). - refresh reads no phone (identified = next): "auth.refresh keeps a named account's identity ..." red (124/1). CI (test, on-npm) green at fa5aaae. Version 0.2.4 -> 0.2.5. Not tried: a real Huawei Cloud account. --- packages/codearts/README.md | 18 ++- packages/codearts/index.mjs | 183 +++++++++++++++++++++++++++---- packages/codearts/index.test.mjs | 140 +++++++++++++++++++++++ packages/codearts/package.json | 2 +- 4 files changed, 319 insertions(+), 24 deletions(-) diff --git a/packages/codearts/README.md b/packages/codearts/README.md index f8eec39..2e25ccb 100644 --- a/packages/codearts/README.md +++ b/packages/codearts/README.md @@ -35,9 +35,21 @@ magpie's (or OpenCode's) own account store. `auth.refresh` renews it 30 minutes expires, reusing the same verifier and DPoP key; a stale credential met on a request (`401`, `APIG.0602`) is renewed once and the request sent again. A refresh token is spent once per account, however many loaders ask; a renewal that only fails for now (STS unreachable) -answers `503` and keeps the sign-in, and only one STS turns away for good marks it. The -account id is the signer named in the refresh token, so signing in again replaces the account -instead of adding one. +answers `503` and keeps the sign-in, and only one STS turns away for good marks it. + +**The card's name:** the account is shown by its **phone number** (`138****8000`, masked the way +the other magpie cards mask theirs), read once after signing in from Huawei Cloud IAM — +`GET https://iam.cn-north-4.myhuaweicloud.com/v3.0/OS-USER/users/{principal_id}`, signed with +the same temporary credentials — and kept on the credential as `user_phone`. The refresh token +names the signer only by IAM's own ids (`hw12323`, and the URN +`iam:::user:`), which read as an ID nobody can tell apart from another account's; +the account name is the fallback when the phone can't be read, and the URN never is. + +`accountId` is the account's identity — the URN, as before — and it never changes: magpie +keys the user's own name for the account, its proxy, model picks and a gateway key's list by +it, so a re-sign-in and a renewal give the same value back. The card's name is usage's `user`, +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. ## Models diff --git a/packages/codearts/index.mjs b/packages/codearts/index.mjs index 6fa9f85..e328bae 100644 --- a/packages/codearts/index.mjs +++ b/packages/codearts/index.mjs @@ -67,6 +67,23 @@ const OPENGW_GATEWAY_CONFIG_URL = `${OPENGW_HOST}/api/v1/gateway/config` // 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)) + +// 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/ +// {principal_id}` answers `user.phone`, measured `0086-13800138000`). +// +// Deliberately NOT in SIGNED_HOSTS. magpie forwards requests through this +// plugin's `fetch`, and that set is the fence around the account's temporary +// credentials; adding IAM to it would let an `api` override carry them to +// another service. The plugin's own GET is signed here, by this one function, +// for this one URL — nothing forwarded ever reaches IAM signed. +const IAM_HOST = "https://iam.cn-north-4.myhuaweicloud.com" +const IAM_USER_URL = (userId) => `${IAM_HOST}/v3.0/OS-USER/users/${encodeURIComponent(userId)}` +const IAM_TIMEOUT_MS = 8_000 +// The phone never changes for one IAM user, and the card asks often: one read +// per account is enough, kept in memory for IAM_PHONE_TTL_MS (a failed read +// included, so a card refresh does not ask IAM again every time). +const IAM_PHONE_TTL_MS = 6 * 60 * 60 * 1000 // The daily free token pool a `maas_type: benefit` chat draws on (never the // credit packages), so a free model's spend shows up in the usage panel. const BENEFIT_BALANCE_URL = `${OPENGW_HOST}/api/v1/user/tokens/balance` @@ -482,25 +499,119 @@ function b64Json(s) { } } +/** The signer's claims from the refresh token's `user_profile`, or null. */ +function profileOf(cred) { + const token = typeof cred?.refresh_token === "string" ? cred.refresh_token : "" + const parts = token.split(".") + if (parts.length !== 3) return null + const payload = b64Json(parts[1]) + const raw = payload?.user_profile + return typeof raw === "string" ? (safeJson(raw) ?? b64Json(raw)) : asRecord(raw) +} + /** * Who signed in. STS answers with no user fields, so without this every * sign-in looked like a new account to magpie (one more `codearts#xxxxxx`); * the refresh_token is a JWT whose `user_profile` claim names the signer. * `id` tells accounts apart, `name` is what the usage card shows. + * + * The claim carries no phone number, only IAM's `account_name` (the `hw…` + * string) and `principal_urn` — which is why the card used to show + * `iam:::user:`, an ID nobody can tell apart from another + * account's. `user_phone` (read from IAM after sign-in, see + * `fetchAccountPhone`) stands in front of them when it is there. */ function accountIdentityOf(cred) { const legacy = { id: firstOf(cred?.user_name, cred?.user_id), name: firstOf(cred?.user_name) } - const token = typeof cred?.refresh_token === "string" ? cred.refresh_token : "" - const parts = token.split(".") - if (parts.length !== 3) return legacy - const payload = b64Json(parts[1]) - const raw = payload?.user_profile - const profile = typeof raw === "string" ? (safeJson(raw) ?? b64Json(raw)) : asRecord(raw) - const id = firstOf(profile?.principal_urn, profile?.account_name, profile?.account_id, profile?.user_id, legacy.id) - const name = firstOf(profile?.user_name, profile?.account_name, profile?.domain_name, legacy.name) + const profile = profileOf(cred) + if (!profile) return { ...legacy, name: firstOf(cred?.user_phone, legacy.name) } + const id = firstOf(profile.principal_urn, profile.account_name, profile.account_id, profile.user_id, legacy.id) + const name = firstOf(cred?.user_phone, profile.user_name, profile.account_name, profile.domain_name, legacy.name) return { id, name } } +/** + * A phone number as the cards show it: `0086-13800138000` → `138****8000`. + * The area code Huawei answers with is dropped, and any number too short to + * mask is not a name worth showing (empty, so the caller falls back). + */ +function maskPhone(raw) { + let digits = String(raw ?? "").replace(/\D/g, "") + // Huawei Cloud writes the country code as `0086-…`; a person's own number + // may come as `+86 …`. Either is dropped when an 11-digit number follows. + if (digits.length > 11 && digits.startsWith("0086")) digits = digits.slice(4) + else if (digits.length > 11 && digits.startsWith("86")) digits = digits.slice(2) + // a phone is 11 digits; a shorter run is not a number to mask + if (digits.length < 11) return "" + return `${digits.slice(0, 3)}****${digits.slice(-4)}` +} + +// One phone read per IAM user, re-read after IAM_PHONE_TTL_MS. A failed read +// is cached too (an empty answer): without that, a card refresh asks IAM again +// every time, each able to wait the full timeout. Stale entries are dropped +// past a cap, so the map does not grow for the life of the host. +const IAM_PHONE_CAP = 1024 +const phoneByIamUser = new Map() + +function rememberPhone(iamUserId, phone) { + if (phoneByIamUser.size >= IAM_PHONE_CAP) { + for (const [k, v] of phoneByIamUser) if (Date.now() - v.at >= IAM_PHONE_TTL_MS) phoneByIamUser.delete(k) + if (phoneByIamUser.size >= IAM_PHONE_CAP * 2) phoneByIamUser.clear() + } + phoneByIamUser.set(iamUserId, { at: Date.now(), phone }) +} + +/** + * The account's own phone number, read from Huawei Cloud IAM with the + * credentials the sign-in already holds. Best effort: `""` when the claim has + * no `principal_id`, the call fails, or the answer carries no usable number — + * a display name must never cost anyone a sign-in. + */ +async function fetchAccountPhone(cred, fetcher = globalThis.fetch) { + const iamUserId = firstOf(profileOf(cred)?.principal_id, profileOf(cred)?.user_id) + if (!iamUserId || !cred?.access_key_id || !cred?.security_token) return "" + const hit = phoneByIamUser.get(iamUserId) + if (hit && Date.now() - hit.at < IAM_PHONE_TTL_MS) return hit.phone + try { + const url = IAM_USER_URL(iamUserId) + const signed = await signRequestHuawei( + cred.access_key_id, cred.secret_access_key, cred.security_token, + "GET", url, new Uint8Array(), + ) + const headers = new Headers() + signed.forEach((value, key) => { + if (key !== "host") headers.set(key, value) + }) + const res = await fetcher(url, { + method: "GET", + headers, + redirect: "error", + signal: AbortSignal.timeout(IAM_TIMEOUT_MS), + }) + if (!res.ok) { + rememberPhone(iamUserId, "") + return "" + } + const body = await res.json().catch(() => null) + const phone = maskPhone(body?.user?.phone) + rememberPhone(iamUserId, phone) + return phone + } catch { + rememberPhone(iamUserId, "") + return "" + } +} + +/** `{ user_phone }` when the account has one to show, else `{}` (never throws). */ +async function accountPhoneField(cred, fetcher) { + try { + const phone = await fetchAccountPhone(cred, fetcher) + return phone ? { user_phone: phone } : {} + } catch { + return {} + } +} + /** The credential a sign-in carries; magpie keeps it in the `access` field. */ function credentialOf(auth) { if (!auth || auth.type !== "oauth") return null @@ -2432,13 +2543,28 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { async refresh(auth) { const cred = credentialOf(auth) if (!cred) return undefined - const next = await renewOnce(cred) - const accountId = auth.accountId ? "" : accountIdentityOf(next).id + const renewed = await renewOnce(cred) + // A rotation rebuilds the credential: keep the phone, which only the + // stored one knows (`renewOnce` carries `session_id` itself), and read + // it once for an account signed in before it was being read at all. + const next = { + ...renewed, + ...(cred.user_phone && !renewed.user_phone ? { user_phone: cred.user_phone } : {}), + } + const identified = next.user_phone ? next : { ...next, ...(await accountPhoneField(next, fetcher)) } + const identity = accountIdentityOf(identified) + // accountId is the account's identity in magpie (its user-set name, + // proxy, model picks and a gateway key's list hang off it), so a + // renewal never renames one. An account stored without an accountId at + // all gets the URN, as main does — otherwise signing it in again would + // add a second row. + const accountId = auth.accountId ? "" : identity.id return { - access: JSON.stringify(next), - refresh: next.refresh_token, - expires: expiresFromCredential(next), + access: JSON.stringify(identified), + refresh: identified.refresh_token, + expires: expiresFromCredential(identified), ...(accountId ? { accountId } : {}), + ...(identity.id ? { uid: identity.id } : {}), } }, @@ -2546,7 +2672,11 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { grants: readGrants(ledgerPath, await ledgerKey(cred)), benefitIds: state.benefit ? [...state.benefit] : BENEFIT_MODEL_FALLBACK, }) - const user = accountIdentityOf(cred).name + // 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 + // that read (the next refresh stores it). + const phone = firstOf(cred.user_phone) || (await fetchAccountPhone(cred, fetcher)) + const user = phone || accountIdentityOf(cred).name return user ? { ...usage, user } : usage } catch (e) { return { error: e?.message ?? String(e), windows: [] } @@ -2600,15 +2730,21 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { 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" } - // Who signed in, so signing in again replaces the account - // instead of adding a `codearts#xxxxxx` beside it. - const accountId = accountIdentityOf(cred).id + // 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)) } + const identity = accountIdentityOf(identified) + // `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 { type: "success", - access: outcome.access, + access: JSON.stringify(identified), refresh: cred.refresh_token, expires: outcome.expires, - ...(accountId ? { accountId } : {}), + accountId: identity.id, + ...(identity.id ? { uid: identity.id } : {}), } } catch (e) { return { type: "failed", error: e?.message ?? String(e) } @@ -2636,7 +2772,12 @@ function nearExpiry(cred) { * merged), so the account's other fields — its accountId — go along. */ async function persistCredential(client, account, cred) { - const accountId = firstOf(account?.accountId, accountIdentityOf(cred).id) + const identity = accountIdentityOf(cred) + // `accountId` is the account's identity in magpie, so it stays what main + // stores: the URN, and what the record already had first. The phone is in + // the credential (`user_phone`) and shown by usage's `user`. + const accountId = firstOf(account?.accountId, identity.id) + const uid = firstOf(identity.id, account?.uid) const body = { ...asRecord(account), type: "oauth", @@ -2644,6 +2785,7 @@ async function persistCredential(client, account, cred) { refresh: cred.refresh_token, expires: expiresFromCredential(cred), ...(accountId ? { accountId } : {}), + ...(uid ? { uid } : {}), } try { await client?.auth?.set?.({ path: { id: PROVIDER }, body }) @@ -2664,6 +2806,7 @@ export const _internal = { generatePkcePair, generateDpopKeyPair, keyPairFromStoredJwk, signDpopJws, buildCanonicalRequest, signRequestHuawei, credentialFromTokenResponse, credentialOf, expiresFromCredential, accountIdentityOf, accountSessionIds, + profileOf, maskPhone, fetchAccountPhone, accountPhoneField, IAM_HOST, IAM_USER_URL, requestToken, exchangeAuthorizationCode, exchangeRefreshToken, refreshCredential, isDeadRefreshToken, isPermanentRefreshFailure, nearExpiry, persistCredential, buildOAuthLoginUrl, buildPortalLoginResultUrl, diff --git a/packages/codearts/index.test.mjs b/packages/codearts/index.test.mjs index 8246367..bb79d56 100644 --- a/packages/codearts/index.test.mjs +++ b/packages/codearts/index.test.mjs @@ -259,6 +259,101 @@ test("accountIdentityOf reads the signer from the refresh token's user_profile", assert.deepEqual(x.accountIdentityOf({ refresh_token: "opaque", user_name: "bob" }), { id: "bob", name: "bob" }) }) +// A credential whose refresh token carries the IAM claims a real one does. +function credWithProfile(claims) { + const b64u = (o) => Buffer.from(JSON.stringify(o)).toString("base64url") + return { + access_key_id: "AK", + secret_access_key: "SK", + security_token: "ST", + refresh_token: `h.${b64u({ user_profile: JSON.stringify(claims) })}.s`, + } +} + +test("maskPhone shows a number a person can tell apart, or nothing", () => { + // Huawei Cloud IAM answers `0086-13800138000`; the other magpie cards show + // `138****8000`. + assert.equal(x.maskPhone("0086-13800138000"), "138****8000") + assert.equal(x.maskPhone("+86 138 0013 8000"), "138****8000") + assert.equal(x.maskPhone("13800138000"), "138****8000") + // Too short to be a number: no name, so the caller falls back. + assert.equal(x.maskPhone(""), "") + assert.equal(x.maskPhone("12345"), "") + assert.equal(x.maskPhone(undefined), "") +}) + +test("accountIdentityOf names an account by its phone, never by IAM's ids", () => { + const b64u = (o) => Buffer.from(JSON.stringify(o)).toString("base64url") + const profile = { principal_urn: "iam::d1:user:hw12323", account_name: "hw12323" } + const token = `h.${b64u({ user_profile: JSON.stringify(profile) })}.s` + // The phone read from IAM stands in front of `hw12323` and of the URN. + assert.deepEqual(x.accountIdentityOf({ refresh_token: token, user_phone: "138****8000" }), { + id: "iam::d1:user:hw12323", + name: "138****8000", + }) + // Without one, the account name — while `id` stays the URN magpie keys by. + assert.deepEqual(x.accountIdentityOf({ refresh_token: token }), { id: "iam::d1:user:hw12323", name: "hw12323" }) +}) + +test("fetchAccountPhone reads IAM with the account's own credentials, and only once", async () => { + const seen = [] + const cred = credWithProfile({ principal_id: "uid-1" }) + const fetcher = async (url, init) => { + seen.push([String(url), new Headers(init.headers).get("authorization")]) + return new Response(JSON.stringify({ user: { name: "hw12323", phone: "0086-13800138000" } }), { status: 200 }) + } + assert.equal(await x.fetchAccountPhone(cred, fetcher), "138****8000") + assert.equal(seen.length, 1) + assert.equal(seen[0][0], "https://iam.cn-north-4.myhuaweicloud.com/v3.0/OS-USER/users/uid-1") + assert.ok(String(seen[0][1]).startsWith("SDK-HMAC-SHA256 "), "signed, like every other call of the account") + // The number does not change: the second read is free. + assert.equal(await x.fetchAccountPhone(cred, fetcher), "138****8000") + assert.equal(seen.length, 1) +}) + +test('fetchAccountPhone is best effort — no claim, a refusal, or no number gives ""', async () => { + // No `principal_id` in the token: IAM is never called. + const unreadable = { access_key_id: "AK", secret_access_key: "SK", security_token: "ST", refresh_token: "R" } + assert.equal(await x.fetchAccountPhone(unreadable, async () => { throw new Error("must not be called") }), "") + const cred = credWithProfile({ principal_id: "uid-2" }) + assert.equal(await x.fetchAccountPhone(cred, async () => new Response("{}", { status: 403 })), "") + assert.equal( + await x.fetchAccountPhone(cred, async () => new Response(JSON.stringify({ user: { name: "hw12323" } }), { status: 200 })), + "", + ) +}) + +test("usage names an account by the phone its credential carries", async () => { + const cred = { ...(await makeCred()), user_phone: "138****8000" } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { + fetch: async () => new Response(JSON.stringify({ metrics: [ + { name: "usageTotalPackageCredit", package_credit_amount: 500, package_credit_remain: 500 }, + ] }), { status: 200 }), + ledgerPath: path.join(ledgerDir, "unused.json"), + }) + const usage = await plugin.auth.usage(async () => makeAuth(cred)) + assert.equal(usage.user, "138****8000") + assert.equal(usage.windows.length > 0, true, "the phone must not replace the windows") +}) + +test("a renewal keeps the account's name and its uid, with the phone in the credential", async () => { + const saved = [] + const client = { auth: { set: async ({ body }) => { saved.push(body) } } } + const cred = { + ...(await makeCred()), + user_phone: "138****8000", + refresh_token: credWithProfile({ principal_urn: "iam::d:user:hw123" }).refresh_token, + } + const account = await x.persistCredential(client, { accountId: "iam::d:user:hw123", uid: "iam::d:user:hw123" }, cred) + assert.equal(saved.length, 1) + // accountId is the identity: it must not be renamed (magpie keys the user's + // own settings by it). The phone lives in the credential and is shown by usage. + assert.equal(saved[0].accountId, "iam::d:user:hw123") + assert.equal(saved[0].uid, "iam::d:user:hw123") + assert.equal(JSON.parse(saved[0].access).user_phone, "138****8000") + assert.equal(account.accountId, "iam::d:user:hw123") +}) + test("accountSessionIds is stable per account and differs between accounts", async () => { const a = await x.accountSessionIds({ session_id: "s1", access_key_id: "AK1" }) assert.deepEqual(await x.accountSessionIds({ session_id: "s1", access_key_id: "AK2" }), a) @@ -2364,3 +2459,48 @@ test("a code STS turns down sends the browser to the portal's failure page", asy await assert.rejects(result, /token request failed: 400/) }) }) + +test("auth.refresh keeps a named account's identity and gives an unnamed one the URN (review #483)", async () => { + const urn = "iam::d:user:hw123" + const profiled = credWithProfile({ principal_urn: urn, principal_id: "pid-1" }) + const cred = { ...(await makeCred()), refresh_token: profiled.refresh_token } + const fetcher = async (url) => + String(url).includes("iam.cn-north-4") + ? new Response(JSON.stringify({ user: { phone: "0086-13800138000" } }), { status: 200 }) + : new Response(JSON.stringify({ + credentials: { access_key_id: "AK2", secret_access_key: "SK2", security_token: "ST2", expiration: "2031-01-01T00:00:00Z" }, + refresh_token: profiled.refresh_token, + }), { status: 200 }) + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + + // an account that has an accountId: a renewal does not rename it + const named = await plugin.auth.refresh({ ...makeAuth(cred), accountId: urn }) + assert.equal(named.accountId, undefined) + // the phone is read on the renewal and kept on the credential + assert.equal(JSON.parse(named.access).user_phone, "138****8000") + + // an account without one: the renewal gives it the URN (else a re-sign-in + // would add a second row) + const unnamed = await plugin.auth.refresh(makeAuth(cred)) + assert.match(String(unnamed.accountId ?? ""), /^iam::/) + assert.equal(JSON.parse(unnamed.access).user_phone, "138****8000") +}) + +test("a sign-in names the account by its URN while the card shows the phone (review #483)", async () => { + const b64u = (o) => Buffer.from(JSON.stringify(o)).toString("base64url") + const urn = "iam::d1:user:hw123" + const rt = `h.${b64u({ user_profile: JSON.stringify({ principal_urn: urn, principal_id: "pid-1", account_name: "hw123" }) })}.s` + const fetcher = async (url) => + String(url).includes("iam.cn-north-4") + ? new Response(JSON.stringify({ user: { phone: "0086-13800138000" } }), { status: 200 }) + : new Response(stsBody("AK", rt), { status: 200 }) + const plugin = await CodeArtsAuthPlugin({ client: {} }, { 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 + // accountId is the identity (the URN); the phone is on the credential + assert.equal(out.accountId, urn) + assert.equal(JSON.parse(out.access).user_phone, "138****8000") +}) diff --git a/packages/codearts/package.json b/packages/codearts/package.json index f9d087a..0940bbb 100644 --- a/packages/codearts/package.json +++ b/packages/codearts/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-codearts-auth", - "version": "0.2.4", + "version": "0.2.5", "description": "Huawei Cloud CodeArts (码道) in OpenCode and magpie: its models through Huawei Cloud OAuth sign-in, signed requests, credit usage and the daily check-in (unofficial)", "type": "module", "main": "./index.mjs",