diff --git a/packages/kiro/README.md b/packages/kiro/README.md index 84114ba..c5901e3 100644 --- a/packages/kiro/README.md +++ b/packages/kiro/README.md @@ -46,8 +46,12 @@ Power) and makes its requests, in OpenCode and in magpie. Provider id: kiro-cli refreshes its own token first (`kiro-cli debug refresh-auth-token`). A token the plugin refreshes itself is written back, so kiro-cli and the IDE go on with it. -- **Kiro API key (`ksk_…`)**: sent with `tokentype: API_KEY`. Its profile is - found with `GetProfile`. +- **Kiro API key (`ksk_…`)**: sent with `tokentype: API_KEY`, as kiro-cli + sends it. `GetProfile` is asked in us-east-1, then eu-central-1, for the + region the key's profile is in; a key it finds none for is used in + us-east-1, as kiro-cli uses it. Its models are listed with the control + plane's `ListAvailableModels` and its credits with `GetUsageLimits`, and + no profile is named in its calls, as kiro-cli names none. A browser sign-in is kept where OpenCode keeps sign-ins (`auth.json`; in magpie, `plugin-auth.json`) as an `oauth` entry. The entry holds the diff --git a/packages/kiro/apikey.test.mjs b/packages/kiro/apikey.test.mjs new file mode 100644 index 0000000..4cff558 --- /dev/null +++ b/packages/kiro/apikey.test.mjs @@ -0,0 +1,143 @@ +// A Kiro API key (ksk_…) is used as kiro-cli uses it. Recorded from kiro-cli +// 2.32.0 with KIRO_API_KEY set to a made-up key, in a sandbox HOME, against +// a local recorder (no real key, no real Kiro): +// +// GetProfile POST management/ X-Amz-Target AmazonCodeWhispererService.GetProfile, body {} +// ListAvailableModels POST management/?origin=KIRO_CLI X-Amz-Target KiroControlPlaneBearerService.ListAvailableModels, body {"origin":"KIRO_CLI"} +// GetUsageLimits POST management/?origin=KIRO_CLI X-Amz-Target AmazonCodeWhispererService.GetUsageLimits, body {"origin":"KIRO_CLI"} +// GenerateAssistantResponse no profileArn in the body +// +// each with Content-Type application/x-amz-json-1.0, Authorization Bearer +// and tokentype API_KEY, and no profile named even when GetProfile +// gave one. With every management host refused, kiro-cli asked GetProfile +// in us-east-1, eu-central-1 (then GovCloud and ISO), and went on to list +// models and chat in us-east-1 all the same. +// +// Hollowhere (magpie's Discord, kiro-cli 2.33.1): a key kiro-cli lists +// claude-opus-5.5 with got Auto alone here, and every request failed with +// "Kiro didn't take the API key: 400 Bad Request" — GetProfile's 400. +import { test, expect, afterAll, beforeAll, afterEach } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { realpathSync } from "node:fs" + +let plugin +beforeAll(async () => { + // Bun reads HOME once, at start: run as HOME=$(mktemp -d) bun test + 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 KEY = "ksk_test_not_a_real_key" +const EU = "arn:aws:codewhisperer:eu-central-1:333333333333:profile/EUKEY" +const MODELS = [ + { modelId: "auto", modelName: "Auto", tokenLimits: { maxInputTokens: 1000000, maxOutputTokens: 64000 } }, + { modelId: "claude-opus-5.5", modelName: "Claude Opus 5.5", tokenLimits: { maxInputTokens: 1000000, maxOutputTokens: 128000 } }, +] +const MORE = [{ modelId: "claude-sonnet-5.5", modelName: "Claude Sonnet 5.5", tokenLimits: { maxInputTokens: 1000000, maxOutputTokens: 64000 } }] + +// kiro is Kiro's API as an API key sees it, answering only what kiro-cli +// sends: GetProfile's answer in each region is given (a 400 where none), +// the REST calls a sign-in makes answer 400, and a chat stops at a 500. +function kiro({ profileIn = {} } = {}) { + const seen = { calls: [], chats: [] } + globalThis.fetch = async (input, init = {}) => { + const url = new URL(String(input)) + const h = Object.fromEntries(new Headers(init.headers).entries()) + const region = url.hostname.split(".")[1] + if (h.authorization !== `Bearer ${KEY}` || h.tokentype !== "API_KEY") return new Response("{}", { status: 403 }) + if (url.hostname.startsWith("management.")) { + const target = h["x-amz-target"] ?? "" + seen.calls.push({ region, path: url.pathname, query: url.search, target, body: init.body }) + if (url.pathname !== "/" || h["content-type"] !== "application/x-amz-json-1.0" || init.method !== "POST") + return new Response(JSON.stringify({ message: "profileArn is required for this request." }), { status: 400 }) + const body = JSON.parse(init.body) + if (target === "AmazonCodeWhispererService.GetProfile") { + if (profileIn[region]) return Response.json({ profile: { arn: profileIn[region], profileName: "key" } }) + return new Response(JSON.stringify({ __type: "ValidationException", message: "Invalid request" }), { status: 400 }) + } + if (url.search !== "?origin=KIRO_CLI" || body.origin !== "KIRO_CLI" || "profileArn" in body) + return new Response(JSON.stringify({ message: "Invalid request" }), { status: 400 }) + if (target === "KiroControlPlaneBearerService.ListAvailableModels") { + if (body.nextToken === "p2") return Response.json({ models: MORE }) + return Response.json({ models: MODELS, defaultModel: { modelId: "auto" }, nextToken: "p2" }) + } + if (target === "AmazonCodeWhispererService.GetUsageLimits") + return Response.json({ subscriptionInfo: { subscriptionTitle: "KIRO PRO+" }, + usageBreakdownList: [{ displayNamePlural: "Credits", currentUsageWithPrecision: 10, usageLimitWithPrecision: 2000 }] }) + } + if (url.pathname === "/generateAssistantResponse") { + const b = JSON.parse(init.body) + seen.chats.push({ region, profileArn: b.profileArn, model: b.conversationState.currentMessage.userInputMessage.modelId }) + return new Response(JSON.stringify({ message: "stop here" }), { status: 500 }) + } + throw new Error("unexpected " + url) + } + return seen +} + +const hooks = () => plugin({ client: { auth: { set: async () => {} } } }) +const auth = { type: "api", key: KEY } +const ask = async (h, model) => { + const l = await h.auth.loader(async () => auth) + return l.fetch("https://kiro.invalid/v1/messages", { method: "POST", body: JSON.stringify({ model, messages: [{ role: "user", content: "hi" }] }) }) +} + +test("a key GetProfile finds no profile for lists its models, as kiro-cli lists them", async () => { + const seen = kiro() + const h = await hooks() + const models = await h.provider.models({ models: { auto: {} } }, { auth }) + expect(Object.keys(models)).toEqual(["auto", "claude-opus-5.5", "claude-sonnet-5.5"]) + // GetProfile in both of Kiro's regions, then the list in us-east-1, each page + expect(seen.calls.map((c) => [c.region, c.target])).toEqual([ + ["us-east-1", "AmazonCodeWhispererService.GetProfile"], + ["eu-central-1", "AmazonCodeWhispererService.GetProfile"], + ["us-east-1", "KiroControlPlaneBearerService.ListAvailableModels"], + ["us-east-1", "KiroControlPlaneBearerService.ListAvailableModels"], + ]) + expect(JSON.parse(seen.calls[2].body)).toEqual({ origin: "KIRO_CLI" }) + expect(JSON.parse(seen.calls[3].body)).toEqual({ origin: "KIRO_CLI", nextToken: "p2" }) +}) + +test("a key GetProfile finds no profile for chats in us-east-1, naming no profile", async () => { + const seen = kiro() + const h = await hooks() + const res = await ask(h, "claude-opus-5.5") + await res.text() + expect(seen.chats).toEqual([{ region: "us-east-1", profileArn: undefined, model: "claude-opus-5.5" }]) + // GetProfile isn't asked again on the next request + await (await ask(h, "auto")).text() + expect(seen.calls.filter((c) => c.target.endsWith("GetProfile")).length).toBe(2) +}) + +test("a key whose profile is in eu-central-1 is used there, its calls naming no profile", async () => { + const seen = kiro({ profileIn: { "eu-central-1": EU } }) + const h = await hooks() + const models = await h.provider.models({ models: { auto: {} } }, { auth }) + expect(Object.keys(models)).toContain("claude-opus-5.5") + await (await ask(h, "claude-opus-5.5")).text() + expect(seen.calls.filter((c) => c.target.endsWith("ListAvailableModels")).map((c) => c.region)).toEqual(["eu-central-1", "eu-central-1"]) + expect(seen.chats).toEqual([{ region: "eu-central-1", profileArn: undefined, model: "claude-opus-5.5" }]) +}) + +test("a key's credits are GetUsageLimits as kiro-cli asks it", async () => { + const seen = kiro() + const h = await hooks() + const u = await h.auth.usage(async () => auth) + expect(u.error).toBeUndefined() + expect(u.plan).toBe("Kiro Pro+") + expect(u.windows[0].display).toBe("10 / 2000") + const call = seen.calls.find((c) => c.target === "AmazonCodeWhispererService.GetUsageLimits") + expect(call.query).toBe("?origin=KIRO_CLI") + expect(JSON.parse(call.body)).toEqual({ origin: "KIRO_CLI" }) +}) diff --git a/packages/kiro/index.mjs b/packages/kiro/index.mjs index 58595bd..b94cddb 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -333,25 +333,48 @@ async function managementCall(region, a, method, query, body) { return JSON.parse(text) } -// profileOf finds the profile a sign-in that doesn't name one uses: an API -// key's own, Builder ID's, or the first Kiro lists in either of its regions. -async function profileOf(c) { - if (c.method === "apikey") { - const res = await fetch(management("us-east-1") + "/", { - method: "POST", - headers: { ...authHeaders({ token: c.access, tokenType: "API_KEY" }), "Content-Type": "application/x-amz-json-1.0", - "X-Amz-Target": "AmazonCodeWhispererService.GetProfile" }, - body: "{}", - signal: AbortSignal.timeout(20_000), - }) - if (!res.ok) { - const msg = `Kiro didn't take the API key: ${res.status} ${STATUS_TEXT[res.status] ?? ""}`.trimEnd() - throw res.status === 401 || res.status === 403 ? gone(msg) : new Error(msg) - } - const arn = (await res.json().catch(() => null))?.profile?.arn - if (!arn) throw new Error("Kiro didn't say which profile the API key is for") - return arn +// controlCall is one of Kiro's management operations as kiro-cli sends it +// for an API key: AWS JSON 1.0, the operation named in X-Amz-Target, POSTed +// to the endpoint's root (with ?origin=KIRO_CLI where kiro-cli adds it). +async function controlCall(region, a, target, body, query) { + const res = await fetch(management(region) + "/" + (query ? "?" + new URLSearchParams(query) : ""), { + method: "POST", + headers: { ...authHeaders(a), "Content-Type": "application/x-amz-json-1.0", "X-Amz-Target": target, + "x-amzn-codewhisperer-optout": "false" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(20_000), + }) + const text = await res.text() + if (!res.ok) throw new KiroError(res.status, text) + return JSON.parse(text) +} + +// KEY_REGIONS are where kiro-cli asks GetProfile for an API key's profile, +// in its order (the GovCloud and ISO ones after them aren't Kiro's +// subscriptions). +const KEY_REGIONS = ["us-east-1", "eu-central-1"] + +// keyProfile is an API key's profile, as kiro-cli finds it: GetProfile in +// each region until one answers with a profile. kiro-cli goes on without +// one when every region turns it down (a key from an account with no +// CodeWhisperer profile answers 400), and so does this: "" then, and the +// key's calls are made in us-east-1 without a profile, as kiro-cli makes +// them (Hollowhere, on magpie's Discord: a key kiro-cli 2.33.1 served +// failed every request here with "Kiro didn't take the API key: 400"). +async function keyProfile(c) { + for (const region of KEY_REGIONS) { + try { + const arn = (await controlCall(region, { token: c.access, tokenType: "API_KEY" }, "AmazonCodeWhispererService.GetProfile", {})) + ?.profile?.arn + if (arn) return arn + } catch {} } + return "" +} + +// profileOf finds the profile a sign-in that doesn't name one uses: +// Builder ID's, or the first Kiro lists in either of its regions. +async function profileOf(c) { if (c.builderID) return BUILDER_ID_PROFILE let last for (const region of ["us-east-1", "eu-central-1"]) { @@ -370,6 +393,8 @@ async function profileOf(c) { // usageLimits is Get-Usage-Limits: the plan, the account's email, credits. function usageLimits(a, email) { + // an API key's, as kiro-cli asks for it: no profile, no email asked + if (a.tokenType === "API_KEY") return controlCall(a.region, a, "AmazonCodeWhispererService.GetUsageLimits", { origin: "KIRO_CLI" }, { origin: "KIRO_CLI" }) return managementCall(a.region, a, "Get-Usage-Limits", { origin: "KIRO_CLI", profileArn: a.profile, resourceType: "CREDIT", isEmailRequired: String(email) }) } @@ -497,7 +522,12 @@ function account(client) { saved = true } } - if (!c.profile) { + if (c.method === "apikey") { + if (!c.asked) { + c.profile = await keyProfile(c) + c.asked = true + } + } else if (!c.profile) { c.profile = await profileOf(c) if (!auth?.profileArn && !saved) { await save(auth, c) @@ -510,7 +540,10 @@ function account(client) { await save(auth, c) } held = { id, c } - return { token: c.access, tokenType: tokenType(c), profile: c.profile, region: regionOf(c.profile, c.region) } + // kiro-cli names no profile in an API key's calls, even one GetProfile + // found; the profile only says the key's region + const profile = c.method === "apikey" ? "" : c.profile + return { token: c.access, tokenType: tokenType(c), profile, region: regionOf(c.profile, c.region) } }) // renew is auth.refresh's: a sign-in kept here (not kiro-cli's or the // IDE's, which their owners keep) renewed under the same lock as the @@ -584,9 +617,25 @@ function runtimeModel(m) { // picks a model for each request. const MODELS = [{ id: "auto", name: "Auto" }] +// keyModels is an API key's list, asked as kiro-cli asks it: Kiro's +// control plane's ListAvailableModels, with no profile, each page. +async function keyModels(a) { + const out = { models: [] } + let next + for (let i = 0; i < 20; i++) { + const page = await controlCall(a.region, a, "KiroControlPlaneBearerService.ListAvailableModels", + { origin: "KIRO_CLI", ...(next ? { nextToken: next } : {}) }, { origin: "KIRO_CLI" }) + out.models.push(...(page?.models ?? [])) + out.defaultModel ??= page?.defaultModel + next = page?.nextToken + if (!next) break + } + return out +} + // listModels is List-Available-Models, the default first. async function listModels(a) { - const out = await managementCall(a.region, a, "List-Available-Models", { origin: "KIRO_CLI", profileArn: a.profile }) + const out = a.tokenType === "API_KEY" ? await keyModels(a) : await managementCall(a.region, a, "List-Available-Models", { origin: "KIRO_CLI", profileArn: a.profile }) const list = [] for (const m of out?.models ?? []) { if (!m?.modelId) continue diff --git a/packages/kiro/package.json b/packages/kiro/package.json index 0235dc6..046e41f 100644 --- a/packages/kiro/package.json +++ b/packages/kiro/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kiro-auth", - "version": "0.1.14", + "version": "0.1.15", "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie", "type": "module", "main": "./index.mjs",