From d767d1c8e6e95f278ee72fcec245b56665783584 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 22 Oct 2026 14:03:15 +0800 Subject: [PATCH] kiro 0.1.13: a Google and a GitHub sign-in of one email are two accounts, not one replacing the other (#309) molvqingtai: Kiro keeps a GitHub and a Google sign-in that share an email as two accounts, but only one could be added; the second replaced the first. The plugin named each sign-in by its email alone, and magpie's host.js settle (internal/plugin/host.js:1022) replaces an account whose accountId is the new sign-in's, unless both carry a uid and the two differ (the rule WorkBuddy's uid uses, #413). Each browser sign-in now carries uid = its way in, lowercased (google, github, builderid, enterprise, internal). accountId stays the email, so: - Google and GitHub (or Builder ID) of one email are kept side by side; magpie labels the two rows apart by their slot. - A sign-in again the same way still replaces its own account. - An account saved before 0.1.13 (bare email, loginProvider kept, as the built-in's mover also saved it) still matches a sign-in again, so no duplicate appears. It is given its uid from loginProvider on its first request, model listing or usage read (one save per token), and on magpie's renewal (auth.refresh returns uid with the token). Until then, a sign-in the other way of the same email would still replace it, as before; magpie lists each account's models when its host starts, so that window is the time to the first listing. Not changed: kiro-cli's and the IDE's sign-in (a pointer to whatever they are signed in to; kiro-cli's social token doesn't say Google or GitHub) keeps no uid and matches by email as before. Two Identity Center orgs with one email are still one (both "enterprise"). Kiro's userInfo gives no per-account id this plugin reads; none was assumed. Run at this tree (origin/main 6219a71), sandbox HOME: - bun test packages/kiro: 49 pass, 0 fail. - bun test (whole repo): 2102 pass, 0 fail. - bun scripts/check.mjs: ok. - accounts.test.mjs on origin/main's index.mjs: 2 of 3 red (Google and GitHub sign-ins carry no uid, so magpie's rule keeps one; an old account is never given its uid). The third (no save for an account that has its uid or no known way) passes on both, as it should. Not tried: a real Google and GitHub Kiro sign-in of one email (no such accounts here); the reporter is asked to confirm on #309. --- packages/kiro/README.md | 6 ++ packages/kiro/accounts.test.mjs | 142 ++++++++++++++++++++++++++++++++ packages/kiro/index.mjs | 27 +++++- packages/kiro/package.json | 2 +- 4 files changed, 173 insertions(+), 4 deletions(-) create mode 100644 packages/kiro/accounts.test.mjs diff --git a/packages/kiro/README.md b/packages/kiro/README.md index 7ad79ce..91c5a71 100644 --- a/packages/kiro/README.md +++ b/packages/kiro/README.md @@ -19,6 +19,12 @@ Power) and makes its requests, in OpenCode and in magpie. Provider id: the browser to AWS, and trades the code AWS returns. - The account is named by the email Kiro has for it (`Get-Usage-Limits`), and its plan is read from the same call. + - Kiro keeps a Google, a GitHub, a Builder ID and an Identity Center + sign-in of one email as different accounts. The sign-in carries a `uid` + (`google`, `github`, `builderid`, `enterprise`), so magpie keeps each one + beside the others, and a sign-in again the same way replaces only its + own account. An account signed in before 0.1.13 is given its `uid` on + its first request, model listing, usage read or renewal. - A company's own identity provider (`external_idp`) is not supported here. Sign in with `kiro-cli login` and use the next method instead. - **Kiro CLI's or Kiro IDE's sign-in**: uses the account kiro-cli is signed diff --git a/packages/kiro/accounts.test.mjs b/packages/kiro/accounts.test.mjs new file mode 100644 index 0000000..a88d6a4 --- /dev/null +++ b/packages/kiro/accounts.test.mjs @@ -0,0 +1,142 @@ +// Two Kiro accounts of one email, signed in with Google and with GitHub, +// are two accounts to Kiro, and magpie keeps both (#309): a sign-in is +// given a uid, the way it was signed in to, and magpie replaces an account +// of the same email only when the two uids agree or either has none +// (magpie's host.js settle). A sign-in again the same way still replaces +// its account; one kept before the uid was is given it, so a sign-in the +// other way no longer replaces it. +import { test, expect, afterAll, beforeAll, afterEach } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { realpathSync } from "node:fs" +import { get } from "node:http" + +let plugin +beforeAll(async () => { + // Bun reads HOME once, at start: run as HOME=$(mktemp -d) bun test, so + // no real sign-in is ever read or written + if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") + ;({ KiroAuthPlugin: plugin } = await import("./index.mjs")) +}) +const offline = async () => { throw new Error("no network in tests") } +const real = globalThis.fetch +globalThis.fetch = offline +afterAll(() => (globalThis.fetch = real)) +afterEach(() => (globalThis.fetch = offline)) + +const EMAIL = "same@example.com" +const PROFILE = "arn:aws:codewhisperer:us-east-1:111111111111:profile/TEST" + +// Kiro's auth service gives a token for each code, and its management API +// names every account EMAIL +function kiro() { + let n = 0 + globalThis.fetch = async (url) => { + if (String(url).startsWith("https://prod.us-east-1.auth.desktop.kiro.dev/oauth/token")) + return Response.json({ accessToken: "a" + ++n, refreshToken: "r" + n, expiresIn: 3600, profileArn: PROFILE }) + if (String(url).startsWith("https://management.")) + return Response.json({ subscriptionInfo: { subscriptionTitle: "KIRO FREE" }, userInfo: { email: EMAIL } }) + throw new Error("unexpected request to " + url) + } +} + +// signIn runs the browser sign-in as Kiro's page ends it: back to the +// plugin's port with the code and the way it was signed in to +async function signIn(hooks, option) { + const m = hooks.auth.methods[0] + const a = await m.authorize() + const q = new URL(a.url).searchParams + const back = new URL(q.get("redirect_uri")) + back.pathname = "/oauth/callback" + back.search = new URLSearchParams({ state: q.get("state"), code: "code-" + option, login_option: option }).toString() + await new Promise((ok, fail) => get(back, (res) => (res.resume(), res.on("end", ok))).on("error", fail)) + return a.callback() +} + +// settle is magpie's (internal/plugin/host.js settle): a sign-in saved at +// key replaces an account of the same accountId, unless both have a uid +// and the two differ +function settle(all, key) { + const now = all[key] + for (const k of Object.keys(all)) { + if (k === key) continue + const was = all[k] + const other = now.uid && was.uid && now.uid !== was.uid + if (now.accountId && was.accountId === now.accountId && !other) { + all[k] = now + delete all[key] + return k + } + } + return key +} +let next = 0 +const keep = (all, r) => { + const { type: _t, provider: _p, ...rest } = r + const key = "kiro#" + next++ + all[key] = { type: "oauth", ...rest } + return settle(all, key) +} + +test("a Google and a GitHub sign-in of one email are two accounts; the same way again replaces its own", async () => { + kiro() + const hooks = await plugin({ client: { auth: { set: async () => {} } } }) + const google = await signIn(hooks, "google") + const github = await signIn(hooks, "github") + expect(google).toMatchObject({ type: "success", accountId: EMAIL, loginProvider: "Google", uid: "google" }) + expect(github).toMatchObject({ type: "success", accountId: EMAIL, loginProvider: "Github", uid: "github" }) + + const all = {} + const g = keep(all, google) + const h = keep(all, github) + expect(Object.keys(all)).toHaveLength(2) + expect(g).not.toBe(h) + + const again = await signIn(hooks, "google") + expect(keep(all, again)).toBe(g) + expect(Object.keys(all)).toHaveLength(2) + expect(all[g].access).toBe(again.access) + expect(all[h].access).toBe(github.access) +}, 20_000) + +test("an account kept before the uid was is given it, by a renewal and by a request", async () => { + const old = { type: "oauth", access: "old", refresh: "r0", expires: Date.now() + 60_000, method: "social", loginProvider: "Google", + region: "us-east-1", profileArn: PROFILE, accountId: EMAIL } + + // magpie's renewal keeps the fields it gives over the old + globalThis.fetch = async (url) => { + if (String(url).endsWith("/refreshToken")) return Response.json({ accessToken: "new", refreshToken: "r1", expiresIn: 3600 }) + throw new Error("unexpected request to " + url) + } + let hooks = await plugin({ client: { auth: { set: async () => {} } } }) + expect(await hooks.auth.refresh(old)).toMatchObject({ access: "new", uid: "google" }) + expect(await hooks.auth.refresh({ ...old, uid: "google" })).not.toHaveProperty("uid") + + // a request, the models or the usage save it, once + globalThis.fetch = async () => Response.json({ subscriptionInfo: { subscriptionTitle: "KIRO FREE" }, userInfo: { email: EMAIL } }) + const saves = [] + hooks = await plugin({ client: { auth: { set: async (r) => void saves.push(r.body) } } }) + const stored = { ...old, expires: Date.now() + 3600_000 } + await hooks.auth.usage(async () => stored) + await hooks.auth.usage(async () => stored) + expect(saves).toHaveLength(1) + expect(saves[0]).toMatchObject({ accountId: EMAIL, loginProvider: "Google", uid: "google", access: "old" }) + + // given it, a GitHub sign-in of the same email goes beside it + const all = { kiro: { ...saves[0] } } + expect(keep(all, { type: "success", accountId: EMAIL, uid: "github", access: "gh" })).not.toBe("kiro") + expect(Object.keys(all)).toHaveLength(2) + // and a Google one replaces it + expect(keep(all, { type: "success", accountId: EMAIL, uid: "google", access: "g2" })).toBe("kiro") + expect(Object.keys(all)).toHaveLength(2) +}) + +test("an account with its uid, or with no way known, isn't saved for one", async () => { + globalThis.fetch = async () => Response.json({ subscriptionInfo: { subscriptionTitle: "KIRO FREE" }, userInfo: { email: EMAIL } }) + const saves = [] + const hooks = await plugin({ client: { auth: { set: async (r) => void saves.push(r.body) } } }) + const base = { type: "oauth", access: "t", refresh: "r", expires: Date.now() + 3600_000, method: "social", region: "us-east-1", + profileArn: PROFILE, accountId: EMAIL } + await hooks.auth.usage(async () => ({ ...base, loginProvider: "Github", uid: "github" })) + await hooks.auth.usage(async () => ({ ...base, access: "t2" })) // no way known: nothing to give it + expect(saves).toHaveLength(0) +}) diff --git a/packages/kiro/index.mjs b/packages/kiro/index.mjs index 9279728..c6058ad 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -50,6 +50,12 @@ const SIGN_IN_TIMEOUT = 10 * 60 * 1000 const BUILDER_ID_START = "https://view.awsapps.com/start" const BUILDER_ID_PROFILE = "arn:aws:codewhisperer:us-east-1:638616132270:profile/AAAACCCCXXXX" const isBuilderID = (provider) => String(provider ?? "").toLowerCase() === "builderid" +// uidOf is what tells two Kiro accounts of one email apart: the way it was +// signed in to. Kiro keeps a Google and a GitHub sign-in of one email (or +// Builder ID's, or Identity Center's) as different accounts, and magpie +// keeps a sign-in of an email already signed in as that account unless +// both have a uid and the two differ (#309). "" when it isn't known. +const uidOf = (loginProvider) => String(loginProvider ?? "").trim().toLowerCase() const env = (k) => process.env[k] ?? "" const home = () => env("HOME") || homedir() @@ -438,11 +444,15 @@ function account(client) { lock = run.catch(() => {}) return run } + // an account signed in here before its uid was kept is given it, so a + // sign-in with another way to the same email no longer replaces it + const uidSaved = new Set() + const uidField = (auth) => (!auth?.uid && uidOf(auth?.loginProvider) ? { uid: uidOf(auth.loginProvider) } : {}) const save = async (auth, c) => { if (!c.own || !client?.auth?.set) return const { type: _t, ...rest } = auth await client.auth.set({ path: { id: ID }, body: { ...rest, type: "oauth", access: c.access, refresh: c.refresh, expires: c.expires, - profileArn: c.profile, region: c.region } }).catch(() => {}) + profileArn: c.profile, region: c.region, ...uidField(auth) } }).catch(() => {}) } const creds = (auth, stale = false) => locked(async () => { @@ -460,6 +470,7 @@ function account(client) { } read = newest(read) let c = held?.id === id ? held.c : null + let saved = false if (!c || read.access !== c.access || !fresh(c) || stale) { if (!read.profile && c && read.access === c.access) read.profile = c.profile if (stale && c && read.access !== c.access && fresh(read)) stale = false // the owner refreshed it already @@ -468,11 +479,20 @@ function account(client) { if (c.method === "apikey") throw gone("Kiro turned down the API key saved on the provider") c = renewed(c, await refresh(c)) await save(auth, c) + saved = true } } if (!c.profile) { c.profile = await profileOf(c) - if (!auth?.profileArn) await save(auth, c) + if (!auth?.profileArn && !saved) { + await save(auth, c) + saved = true + } + } + // once per token: a save that didn't take isn't tried on every request + if (!saved && c.own && uidField(auth).uid && !uidSaved.has(c.access)) { + uidSaved.add(c.access) + await save(auth, c) } held = { id, c } return { token: c.access, tokenType: tokenType(c), profile: c.profile, region: regionOf(c.profile, c.region) } @@ -493,7 +513,7 @@ function account(client) { const out = { access: c.access, expires: c.expires } if (c.refresh !== auth.refresh) out.refresh = c.refresh if (c.profile && c.profile !== auth.profileArn) out.profileArn = c.profile - return out + return { ...out, ...uidField(auth) } }) return creds } @@ -1405,6 +1425,7 @@ async function browserSignIn() { const who = await whoIs(c) const user = who.email || "Kiro account" finish({ type: "success", provider: ID, refresh: c.refresh, access: c.access, expires: c.expires, accountId: user, + ...(uidOf(c.loginProvider) ? { uid: uidOf(c.loginProvider) } : {}), method: c.method, loginProvider: c.loginProvider, region: c.region, profileArn: who.profile, ...(c.clientId ? { clientId: c.clientId, clientSecret: c.clientSecret } : {}), ...(who.plan ? { plan: who.plan } : {}) }) html(200, page(true, "You're signed in", `${user} is signed in. You can close this tab.`)) diff --git a/packages/kiro/package.json b/packages/kiro/package.json index fa3478f..2567877 100644 --- a/packages/kiro/package.json +++ b/packages/kiro/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kiro-auth", - "version": "0.1.12", + "version": "0.1.13", "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie", "type": "module", "main": "./index.mjs",