diff --git a/packages/kiro/README.md b/packages/kiro/README.md index 91c5a71..84114ba 100644 --- a/packages/kiro/README.md +++ b/packages/kiro/README.md @@ -17,14 +17,21 @@ Power) and makes its requests, in OpenCode and in magpie. Provider id: - Builder ID and Identity Center come back with an AWS sign-in URL and region. The plugin registers a client with AWS's OIDC service, sends 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. + - The account is named by the email Kiro has for it (`Get-Usage-Limits`) + and the way it was signed in to: `email (Google)`, `email (GitHub)`, + `email (Builder ID)`, `email (IAM Identity Center)`, `email + (Internal)`. Its plan is read from the same call, and its usage names + it the same way. - 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. + own account. An account signed in before 0.1.13 is given its `uid`, + and one named by its bare email before 0.1.14 its name, on its first + request, model listing, usage read or renewal. Until then, a sign-in + again the same way goes beside it rather than replacing it: magpie + matches a sign-in by its name, and the plugin can't see the other + accounts to match it by `uid`. - 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 index a88d6a4..c80f038 100644 --- a/packages/kiro/accounts.test.mjs +++ b/packages/kiro/accounts.test.mjs @@ -5,10 +5,17 @@ // (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. +// +// magpie names a plugin's account by its accountId, and two of one email +// read "email (slot)"; the accountId is the email and the way it was +// signed in to, "email (Google)", "email (GitHub)" (#309), and an account +// kept by its bare email is given that name when next used. import { test, expect, afterAll, beforeAll, afterEach } from "bun:test" import { homedir, tmpdir } from "node:os" -import { realpathSync } from "node:fs" +import { mkdirSync, realpathSync, rmSync } from "node:fs" +import { join } from "node:path" import { get } from "node:http" +import { Database } from "bun:sqlite" let plugin beforeAll(async () => { @@ -21,9 +28,16 @@ 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 cliDir = () => + process.platform === "darwin" ? join(homedir(), "Library", "Application Support", "kiro-cli") : join(homedir(), ".local", "share", "kiro-cli") +afterEach(() => { + globalThis.fetch = offline + rmSync(cliDir(), { recursive: true, force: true }) +}) const EMAIL = "same@example.com" +const GOOGLE = EMAIL + " (Google)" +const GITHUB = EMAIL + " (GitHub)" 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 @@ -82,8 +96,8 @@ test("a Google and a GitHub sign-in of one email are two accounts; the same way 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" }) + expect(google).toMatchObject({ type: "success", accountId: GOOGLE, loginProvider: "Google", uid: "google" }) + expect(github).toMatchObject({ type: "success", accountId: GITHUB, loginProvider: "Github", uid: "github" }) const all = {} const g = keep(all, google) @@ -108,8 +122,10 @@ test("an account kept before the uid was is given it, by a renewal and by a requ 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") + expect(await hooks.auth.refresh(old)).toMatchObject({ access: "new", uid: "google", accountId: GOOGLE }) + const kept = await hooks.auth.refresh({ ...old, uid: "google", accountId: GOOGLE }) + expect(kept).not.toHaveProperty("uid") + expect(kept).not.toHaveProperty("accountId") // a request, the models or the usage save it, once globalThis.fetch = async () => Response.json({ subscriptionInfo: { subscriptionTitle: "KIRO FREE" }, userInfo: { email: EMAIL } }) @@ -119,24 +135,70 @@ test("an account kept before the uid was is given it, by a renewal and by a requ 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" }) + expect(saves[0]).toMatchObject({ accountId: GOOGLE, 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(keep(all, { type: "success", accountId: GITHUB, 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(keep(all, { type: "success", accountId: GOOGLE, uid: "google", access: "g2" })).toBe("kiro") expect(Object.keys(all)).toHaveLength(2) }) +test("an account kept by its bare email is given its name on first use, and a sign-in the same way then replaces it", 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) } } }) + // kept by 0.1.13: its uid, and the bare email + const old = { type: "oauth", access: "old", refresh: "r0", expires: Date.now() + 3600_000, method: "social", loginProvider: "Github", + uid: "github", region: "us-east-1", profileArn: PROFILE, accountId: EMAIL } + const u = await hooks.auth.usage(async () => old) + expect(u.user).toBe(GITHUB) + expect(saves).toHaveLength(1) + expect(saves[0]).toMatchObject({ accountId: GITHUB, uid: "github", access: "old" }) + + // the way it was signed in to, each named as Kiro's sign-in page names it + for (const [way, name] of [["BuilderId", "Builder ID"], ["Enterprise", "IAM Identity Center"], ["Internal", "Internal"]]) { + saves.length = 0 + await hooks.auth.usage(async () => ({ ...old, access: "t-" + way, method: "idc", loginProvider: way, uid: undefined })) + expect(saves[0]).toMatchObject({ accountId: `${EMAIL} (${name})`, uid: way.toLowerCase() }) + } + + // named, a GitHub sign-in again replaces it, and a Google one goes beside it + const all = { kiro: { ...saves[0], ...{ accountId: GITHUB, uid: "github" } } } + kiro() + const again = await signIn(hooks, "github") + expect(keep(all, again)).toBe("kiro") + expect(Object.keys(all)).toHaveLength(1) + expect(keep(all, await signIn(hooks, "google"))).not.toBe("kiro") + expect(Object.keys(all)).toHaveLength(2) +}, 20_000) + +test("kiro-cli's sign-in, with no way known, keeps the bare email", async () => { + mkdirSync(cliDir(), { recursive: true }) + const db = new Database(join(cliDir(), "data.sqlite3"), { create: true }) + db.exec("CREATE TABLE auth_kv (key TEXT PRIMARY KEY, value TEXT)") + db.prepare("INSERT INTO auth_kv VALUES (?, ?)").run("kirocli:social:token", JSON.stringify({ access_token: "t", refresh_token: "r", + expires_at: new Date(Date.now() + 3600_000).toISOString(), region: "us-east-1", profile_arn: PROFILE })) + db.close() + 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 r = await (await hooks.auth.methods[1].authorize()).callback() + expect(r).toMatchObject({ type: "success", source: "kiro-cli", accountId: EMAIL }) + const u = await hooks.auth.usage(async () => ({ type: "oauth", source: "kiro-cli", access: "", refresh: "", expires: 0, accountId: EMAIL })) + expect(u.user).toBe(EMAIL) + expect(saves).toHaveLength(0) +}) + 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, loginProvider: "Github", uid: "github", accountId: 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 c6058ad..58595bd 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -56,6 +56,15 @@ const isBuilderID = (provider) => String(provider ?? "").toLowerCase() === "buil // 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() +// nameOf is what an account is called: its email and the way it was signed +// in to, as Kiro's sign-in page names it, so two accounts of one email read +// apart (#309; magpie names a plugin's account by its accountId). A way not +// known, kiro-cli's or the Kiro IDE's sign-in among them, leaves the email +// as it is, and magpie tells two such apart by their slot. +const WAYS = { google: "Google", github: "GitHub", builderid: "Builder ID", enterprise: "IAM Identity Center", internal: "Internal" } +const nameOf = (email, loginProvider) => (WAYS[uidOf(loginProvider)] ? `${email} (${WAYS[uidOf(loginProvider)]})` : email) +// a bare email: what an account was called before nameOf +const bareEmail = (id) => typeof id === "string" && /^[^\s()]+@[^\s()]+$/.test(id) const env = (k) => process.env[k] ?? "" const home = () => env("HOME") || homedir() @@ -448,11 +457,17 @@ function account(client) { // 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) } : {}) + // and one called by its bare email is given its name, the way it was + // signed in to with it + const nameField = (auth) => + bareEmail(auth?.accountId) && nameOf(auth.accountId, auth.loginProvider) !== auth.accountId + ? { accountId: nameOf(auth.accountId, auth.loginProvider) } : {} + const idFields = (auth) => ({ ...uidField(auth), ...nameField(auth) }) 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, ...uidField(auth) } }).catch(() => {}) + profileArn: c.profile, region: c.region, ...idFields(auth) } }).catch(() => {}) } const creds = (auth, stale = false) => locked(async () => { @@ -490,7 +505,7 @@ function account(client) { } } // 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)) { + if (!saved && c.own && Object.keys(idFields(auth)).length && !uidSaved.has(c.access)) { uidSaved.add(c.access) await save(auth, c) } @@ -513,7 +528,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, ...uidField(auth) } + return { ...out, ...idFields(auth) } }) return creds } @@ -1423,7 +1438,7 @@ async function browserSignIn() { return fail(e.message) } const who = await whoIs(c) - const user = who.email || "Kiro account" + const user = who.email ? nameOf(who.email, c.loginProvider) : "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, @@ -1515,7 +1530,10 @@ export async function KiroAuthPlugin({ client } = {}) { const auth = await getAuth() if (!(auth?.type === "api" && auth.key) && auth?.type !== "oauth") return { error: "not signed in", signIn: "kept" } try { - return { ...usageOf(await usageLimits(await creds(auth), true)), signIn: "kept" } + const u = usageOf(await usageLimits(await creds(auth), true)) + // named as the account is + if (u.user && auth.type === "oauth" && !auth.source) u.user = nameOf(u.user, auth.loginProvider) + return { ...u, signIn: "kept" } } catch (e) { return { error: e.message, signIn: "kept" } } diff --git a/packages/kiro/package.json b/packages/kiro/package.json index 2567877..0235dc6 100644 --- a/packages/kiro/package.json +++ b/packages/kiro/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kiro-auth", - "version": "0.1.13", + "version": "0.1.14", "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie", "type": "module", "main": "./index.mjs",