diff --git a/packages/codearts/README.md b/packages/codearts/README.md index d1f2024..9fcc716 100644 --- a/packages/codearts/README.md +++ b/packages/codearts/README.md @@ -96,6 +96,14 @@ Its token package shows as one window, `usage_token_num` of `package_token_amoun `/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. +**International browser sign-in** (since 0.3.17, #1090): "Sign in with Huawei Cloud +(International)" opens Huawei Cloud's international login (`auth.huaweicloud.com`, +`site=intl`), which goes on to the international portal's authorize page +(`codearts.ap-southeast-1.huaweicloud.com/portal/authorize`). The code is exchanged at the same +STS endpoint, and the credential is kept as an international one, through every renewal. It +skips the mainland-only phone and OfficeAce reads. Not tried yet with a real international +account. + ## Models The account's live list: CodeArts' builtin models, plus the free models of its daily benefit @@ -300,6 +308,9 @@ measurements and code of [HuHong-Tao](https://github.com/yuweihao17/codearts/pul `start_date`–`end_date` 内 `package_token_amount` 中已用的 `usage_token_num`,套餐名取 `package_name_en`。 国际站没有 `opengw` 接口、积分批次和每日签到,插件在那里一概不请求(签到回答「未开通」)。尚未用真实国际站账号试过: 对话仍发到 `/api/v2/chat/completions`,模型列表读不到时用内置列表。 +- **国际站浏览器登录**(0.3.17 起,#1090):「Sign in with Huawei Cloud (International)」先打开华为云国际站登录页 + (`auth.huaweicloud.com`,`site=intl`),再到国际站门户的授权页(`codearts.ap-southeast-1.huaweicloud.com/portal/authorize`)。 + 授权码仍在同一个 STS 端点换取,凭据记为国际站凭据,续期后不变;不读国内站才有的手机号和 OfficeAce 信息。尚未用真实国际站账号试过。 - **模型**:账号实时的内置模型列表;领取当日免费权益成功后,再加上免费模型(每个北京自然日领一次,与 客户端一致;当天还没领取时遇到 `benefit not found` 也会先领取再重发)。每个模型的「消耗系数」作为 magpie 的倍率上报,来自账号主智能体(`build`)的模型列表。 0.3.2 起模型名照码道给的显示:带日期的 `deepseek-v4.1-flash-1017` 是另一个模型(错峰倍率不同),显示为 diff --git a/packages/codearts/index.mjs b/packages/codearts/index.mjs index 4e45cfe..88dfcc8 100644 --- a/packages/codearts/index.mjs +++ b/packages/codearts/index.mjs @@ -70,12 +70,25 @@ const OPENGW_GATEWAY_CONFIG_URL = `${OPENGW_HOST}/api/v1/gateway/config` // 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" }, + mainland: { + id: "mainland", + snap: SNAP_HOST, + opengw: OPENGW_HOST, + console: "https://codearts.huaweicloud.com", + portal: "https://codearts.huaweicloud.com/portal", + locale: "zh-cn", + }, + // The international portal is the IDE's `intlPortalHost` (#1090). Its + // authorize page sends a signed-out browser to the mainland login unless + // the login page is asked for `site=intl`, so the browser starts there. international: { id: "international", snap: "https://snap-access.ap-southeast-1.myhuaweicloud.com", opengw: "", console: "https://console-intl.huaweicloud.com", + portal: "https://codearts.ap-southeast-1.huaweicloud.com/portal", + locale: "en-us", + login: "https://auth.huaweicloud.com/authui/login?site=intl", }, } /** The hosts a credential of `station` is signed for: its API hosts, by name. */ @@ -148,9 +161,8 @@ const DAILY_CHECKIN_TYPE = "USER_LOGIN" const CLAIMED_STATUSES = ["CLAIMED", "CONFIRMED", "CONSUMED"] // Unsigned headers snap-access routes on (signing them breaks the signature). const SNAP_EXTRA_HEADERS = { "Agent-Type": "PromptCenter", "X-Language": "zh-cn" } -// OAuth portal (new IAM flow) and the STS token endpoint. -const PORTAL_AUTHORIZE_BASE = "https://codearts.huaweicloud.com/portal/authorize" -const PORTAL_LOGIN_BASE = "https://codearts.huaweicloud.com/portal/login" +// OAuth portal (new IAM flow, each station's `portal`) and the STS token +// endpoint, which answers both stations' codes and refresh tokens (#1090). const STS_TOKEN_ENDPOINT = "https://sts.cn-north-4.myhuaweicloud.com/v1/oauth2/tokens" // OAuth client id (equals the plugin's URI scheme) and local callback path. @@ -161,7 +173,6 @@ const REDIRECT_PATH = "/oauth/callback" const LOGIN_PLUGIN_NAME = "snap_AIIDE" const LOGIN_PLUGIN_VERSION = "5.2.0" const OAUTH_THEME = "2" // activeColorTheme.kind: 2 = Dark -const OAUTH_LOCALE = "zh-cn" const GRANT_AUTHORIZATION_CODE = "authorization_code" const GRANT_REFRESH_TOKEN = "refresh_token" @@ -824,7 +835,7 @@ async function refreshCredential(cred, fetcher) { if (!next.refresh_token) next.refresh_token = refreshToken // Preserve non-rotating identity fields a legacy login may have carried, and // the session id: it belongs to the account, not to the token. - for (const k of ["domain_id", "user_id", "user_name", "session_id"]) { + for (const k of ["domain_id", "user_id", "user_name", "session_id", "station"]) { if (cred[k]) next[k] = cred[k] } return next @@ -844,16 +855,22 @@ async function accountSessionIds(cred) { // ---- OAuth login: URL + loopback callback ---------------------------------- -/** Build the Huawei Cloud portal authorize URL (params mirror the real IDE). */ -function buildOAuthLoginUrl(port, pkce, ticketId) { - return `${PORTAL_AUTHORIZE_BASE}?theme=${OAUTH_THEME}&locale=${OAUTH_LOCALE}` +/** + * The URL the browser opens to sign in on `station` (params mirror the real + * IDE): the station's portal authorize page, or, for a station with its own + * login page, that page with the authorize URL as where it goes next. + */ +function buildOAuthLoginUrl(port, pkce, ticketId, station = STATIONS.mainland) { + const authorize = `${station.portal}/authorize?theme=${OAUTH_THEME}&locale=${station.locale}` + `&uri_scheme=${CLIENT_ID}&client_id=${CLIENT_ID}&port=${port}` + `&code_challenge=${pkce.codeChallenge}&code_challenge_method=SHA-256` + `&ticket_id=${ticketId}&plugin-name=${LOGIN_PLUGIN_NAME}&plugin-version=${LOGIN_PLUGIN_VERSION}` + if (!station.login) return authorize + return `${station.login}&locale=${station.locale}&service=${encodeURIComponent(authorize)}` } -const buildPortalLoginResultUrl = (ok) => - `${PORTAL_LOGIN_BASE}?login_succeed=${ok}&uri_scheme=${CLIENT_ID}&locale=${OAUTH_LOCALE}` +const buildPortalLoginResultUrl = (ok, station = STATIONS.mainland) => + `${station.portal}/login?login_succeed=${ok}&uri_scheme=${CLIENT_ID}&locale=${station.locale}` /** * Start the loopback callback server, listening on 127.0.0.1:port>=10000. It @@ -863,7 +880,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, label = "CodeArts") { +function startOAuthCallbackServer(pkce, keyPair, fetcher, label = "CodeArts", station = STATIONS.mainland) { let resolveResult let rejectResult const result = new Promise((resolve, reject) => { @@ -893,7 +910,7 @@ function startOAuthCallbackServer(pkce, keyPair, fetcher, label = "CodeArts") { const url = new URL(raw, `http://127.0.0.1:${request.socket.localPort}`) const code = url.searchParams.get("code") if (!code) { - response.writeHead(307, { Location: buildPortalLoginResultUrl(false) }).end() + response.writeHead(307, { Location: buildPortalLoginResultUrl(false, station) }).end() const said = firstOf(url.searchParams.get("error_description"), url.searchParams.get("error")) rejectResult(new Error(`CodeArts sign-in failed: ${said || "the callback came back without an authorization code"}`)) return @@ -901,12 +918,14 @@ function startOAuthCallbackServer(pkce, keyPair, fetcher, label = "CodeArts") { const port = request.socket.localPort ?? 0 void exchangeAuthorizationCode(code, pkce.codeVerifier, port, keyPair, fetcher, label).then( (token) => { - response.writeHead(307, { Location: buildPortalLoginResultUrl(true) }).end() + response.writeHead(307, { Location: buildPortalLoginResultUrl(true, station) }).end() const cred = credentialFromTokenResponse(token, pkce.codeVerifier, keyPair) + // A mainland credential carries no station, as before stations existed. + if (station !== STATIONS.mainland) cred.station = station.id resolveResult({ access: JSON.stringify(cred), expires: expiresFromCredential(cred) }) }, (error) => { - response.writeHead(307, { Location: buildPortalLoginResultUrl(false) }).end() + response.writeHead(307, { Location: buildPortalLoginResultUrl(false, station) }).end() rejectResult(error) }, ) @@ -951,13 +970,13 @@ 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, label = "CodeArts") { +async function startOAuthFlow(fetcher, label = "CodeArts", station = STATIONS.mainland) { const pkce = await generatePkcePair() const keyPair = await generateDpopKeyPair() - const { port, server, result } = await startOAuthCallbackServer(pkce, keyPair, fetcher, label) + const { port, server, result } = await startOAuthCallbackServer(pkce, keyPair, fetcher, label, station) // 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)) + const loginUrl = buildOAuthLoginUrl(port, pkce, randomHex(32), station) let closed = false const close = async () => { @@ -3139,14 +3158,20 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { } } - const browserMethod = { + // The browser sign-in on one station. The international one (#1090) opens + // Huawei Cloud's international login first, and its account skips the two + // mainland-only reads below (IAM's phone, OfficeAce's MaaS pair). + const browserMethodOn = (station) => ({ type: "oauth", - label: "Sign in with Huawei Cloud", + label: station === STATIONS.mainland ? "Sign in with Huawei Cloud" : "Sign in with Huawei Cloud (International)", async authorize() { - const flow = await startOAuthFlow(fetcher) + const flow = await startOAuthFlow(fetcher, "CodeArts", station) + const mainland = station === STATIONS.mainland 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.", + instructions: mainland + ? "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." + : "Sign in to Huawei Cloud International in the browser. This signs in CodeArts only. This window closes itself when done.", method: "auto", async callback() { try { @@ -3156,12 +3181,12 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { // 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 identified = mainland ? { ...cred, ...(await accountPhoneField(cred, fetcher)) } : cred // 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 withMaas = mainland ? await withOfficeAceMaas(identified, fetcher) : identified 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 @@ -3188,7 +3213,9 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { }, } }, - } + }) + const browserMethod = browserMethodOn(STATIONS.mainland) + const intlBrowserMethod = browserMethodOn(STATIONS.international) // 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 @@ -3467,10 +3494,13 @@ export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { }, // 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). + // while the IDE's state file is there; the international browser + // sign-in last (the host picks a method by its place, so the older + // ones keep theirs). get methods() { - return ideFile && fs.existsSync(ideFile) ? [browserMethod, ideMethod] : [browserMethod] + return ideFile && fs.existsSync(ideFile) + ? [browserMethod, ideMethod, intlBrowserMethod] + : [browserMethod, intlBrowserMethod] }, }, } @@ -3516,7 +3546,7 @@ export const _internal = { PROVIDER, NPM, CATALOG, CONTEXT_WINDOWS, BENEFIT_MODEL_FALLBACK, MAX_OUTPUT_TOKENS, CHAT_API_BASE, SNAP_MODEL_BUILTIN_URL, SNAP_STATISTICS_URL, OPENGW_GATEWAY_CONFIG_URL, BENEFIT_BALANCE_URL, OPS_DELIVERY_URL, OPS_CLAIM_URL, OPS_CONFIRM_URL, SESSION_LIMIT_ERROR, ACCOUNT_MAX_INFLIGHT, - PORTAL_AUTHORIZE_BASE, STS_TOKEN_ENDPOINT, CLIENT_ID, REDIRECT_PATH, + STS_TOKEN_ENDPOINT, CLIENT_ID, REDIRECT_PATH, firstOf, asRecord, safeJson, num, clamp, prettify, normalizeModelId, upstreamModelId, formatCredit, b64url, utf8, sha256Hex, hmacSha256Hex, generatePkcePair, generateDpopKeyPair, keyPairFromStoredJwk, signDpopJws, diff --git a/packages/codearts/index.test.mjs b/packages/codearts/index.test.mjs index 6c6d3df..5a73017 100644 --- a/packages/codearts/index.test.mjs +++ b/packages/codearts/index.test.mjs @@ -547,6 +547,29 @@ test("buildOAuthLoginUrl matches the real IDE parameters", () => { assert.equal(q.get("plugin-name"), "snap_AIIDE") // The real plugin never sends auth_callback_url (portal derives it from port). assert.equal(q.has("auth_callback_url"), false) + assert.equal(q.get("locale"), "zh-cn") +}) + +test("the international sign-in opens Huawei Cloud's international login, then its portal (#1090)", () => { + const login = new URL(x.buildOAuthLoginUrl(12345, { codeChallenge: "CH" }, "TICKET", x.STATIONS.international)) + assert.equal(login.origin + login.pathname, "https://auth.huaweicloud.com/authui/login") + assert.equal(login.searchParams.get("site"), "intl") + assert.equal(login.searchParams.get("locale"), "en-us") + const service = new URL(login.searchParams.get("service")) + assert.equal(service.origin + service.pathname, "https://codearts.ap-southeast-1.huaweicloud.com/portal/authorize") + assert.equal(service.searchParams.get("locale"), "en-us") + assert.equal(service.searchParams.get("port"), "12345") + assert.equal(service.searchParams.get("code_challenge"), "CH") + assert.equal(service.searchParams.get("ticket_id"), "TICKET") + assert.equal(service.searchParams.get("client_id"), "codearts-agent") + assert.equal( + x.buildPortalLoginResultUrl(true, x.STATIONS.international), + "https://codearts.ap-southeast-1.huaweicloud.com/portal/login?login_succeed=true&uri_scheme=codearts-agent&locale=en-us", + ) + assert.equal( + x.buildPortalLoginResultUrl(true), + "https://codearts.huaweicloud.com/portal/login?login_succeed=true&uri_scheme=codearts-agent&locale=zh-cn", + ) }) test("usageFromStatistics maps credit metrics to windows with real numbers", () => { @@ -907,8 +930,9 @@ test("plugin exposes config, provider.models, and an oauth auth method", async ( assert.equal(typeof plugin.config, "function") assert.equal(plugin.provider.id, "codearts") assert.equal(plugin.auth.provider, "codearts") - assert.equal(plugin.auth.methods.length, 1) + assert.ok(plugin.auth.methods.length >= 2) assert.equal(plugin.auth.methods[0].type, "oauth") + assert.equal(plugin.auth.methods.at(-1).type, "oauth") assert.equal(typeof plugin.auth.checkin, "function") assert.equal(plugin.auth.maxConcurrency, x.ACCOUNT_MAX_INFLIGHT) @@ -2017,6 +2041,19 @@ test("auth.refresh exchanges the refresh token for fresh credentials", async () assert.equal(next.expires, Date.parse("2031-01-01T00:00:00Z")) }) +test("a refresh keeps an international credential on its station (#1090)", async () => { + const cred = { ...(await makeCred()), station: "international" } + const fetcher = async () => new Response(JSON.stringify({ + credentials: { access_key_id: "AK2", secret_access_key: "SK2", security_token: "ST2", expiration: "2031-01-01T00:00:00Z" }, + refresh_token: "R2", + }), { status: 200 }) + const next = await x.refreshCredential(cred, fetcher) + assert.equal(next.access_key_id, "AK2") + assert.equal(next.station, "international") + const mainland = await x.refreshCredential(await makeCred(), fetcher) + assert.equal("station" in mainland, false) +}) + /** Check a token request's DPoP proof: it verifies against the stored key, for POST to the STS endpoint. */ async function assertDpopFor(proof, publicKeyJwk) { const [h, p, s] = proof.split(".") @@ -3477,6 +3514,47 @@ test("a CodeArts sign-in writes only its own record", async () => { assert.equal(calls.some((c) => c.path?.id?.startsWith("officeace")), false, "no record for the other card") }) +test("the international browser sign-in gives an international credential, with no mainland reads (#1090)", async () => { + oa.seenProviderAccounts.clear() + oa.renewalGates.clear() + const calls = [] + const asked = [] + const fetcher = async (url) => { + asked.push(String(url)) + if (String(url) === x.STS_TOKEN_ENDPOINT) return new Response(stsBody("AK-INTL", oaRefreshToken()), { status: 200 }) + return new Response("{}", { status: 200 }) + } + const plugin = await CodeArtsAuthPlugin({ client: oaClient(calls) }, { fetch: fetcher }) + const method = plugin.auth.methods.at(-1) + assert.equal(method.label, "Sign in with Huawei Cloud (International)") + assert.equal(plugin.auth.methods[0].label, "Sign in with Huawei Cloud", "the mainland one keeps its place") + const a = await method.authorize() + const service = new URL(new URL(a.url).searchParams.get("service")) + const port = service.searchParams.get("port") + const done = a.callback() + const res = await fetch(`http://127.0.0.1:${port}${x.REDIRECT_PATH}?code=C1`, { redirect: "manual" }) + assert.match(res.headers.get("location"), /^https:\/\/codearts\.ap-southeast-1\.huaweicloud\.com\/portal\/login\?login_succeed=true/) + const out = await done + assert.equal(out.type, "success") + const cred = JSON.parse(out.access) + assert.equal(cred.access_key_id, "AK-INTL") + assert.equal(cred.station, "international") + assert.equal(x.stationOf(cred).id, "international") + assert.equal(asked.some((u) => u.includes("iam.cn-north-4")), false, "no mainland IAM read") + assert.equal(asked.some((u) => u.includes("client-permission-validate")), false, "no OfficeAce MaaS read") +}) + +test("a mainland browser sign-in's credential carries no station, as before (#1090)", async () => { + const flow = await x.startOAuthFlow(async (url) => String(url) === x.STS_TOKEN_ENDPOINT + ? new Response(stsBody("AK-CN", oaRefreshToken()), { status: 200 }) + : new Response("{}", { status: 200 })) + const port = new URL(flow.loginUrl).searchParams.get("port") + await fetch(`http://127.0.0.1:${port}${x.REDIRECT_PATH}?code=C1`, { redirect: "manual" }) + const out = await flow.result + assert.equal("station" in JSON.parse(out.access), false) + await flow.close() +}) + test("the OfficeAce sign-in writes only its own record", async () => { oa.seenProviderAccounts.clear() oa.renewalGates.clear() @@ -4433,15 +4511,17 @@ test("readIdeCredential: missing, unreadable, half-written or empty is unknown, 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) + assert.equal(none.auth.methods.length, 2) + assert.match(none.auth.methods[1].label, /International/) 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.length, 3) assert.equal(plugin.auth.methods[0].label, "Sign in with Huawei Cloud", "the browser one keeps its place") + assert.match(plugin.auth.methods[2].label, /International/) 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") + assert.equal(plugin.auth.methods.length, 2, "read again each time") }) async function ideSignIn(plugin) { diff --git a/packages/codearts/package.json b/packages/codearts/package.json index 22b4ba5..5f5fd7f 100644 --- a/packages/codearts/package.json +++ b/packages/codearts/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-codearts-auth", - "version": "0.3.16", + "version": "0.3.17", "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",