kiro 0.1.40: Kiro sign-ins made elsewhere are imported from a JSON file or paste by their refresh token (#1132)
Accounts signed in to Kiro elsewhere (Kiro Account Manager lists and exports, kiro2api, the Kiro IDE's kiro-auth-token.json with its <clientIdHash>.json client, kiro-cli's tokens) are imported in magpie's "Import accounts from a file…" by their refresh token. Each is renewed where its kind is renewed (Google/GitHub at prod.us-east-1.auth.desktop.kiro.dev, Builder ID / Identity Center at oidc.<region>.amazonaws.com with its client) and named by the email Kiro has for it. Other providers' entries in a sign-in store are skipped, duplicates are renewed once, at most 100 a time. A region or profile ARN read from a file can't pick a host any more, on every route (import, the IDE's file, kiro-cli's DB, a saved sign-in): regionOf takes only Kiro's API regions (us-east-1, eu-central-1) from a profile, arnOf keeps only arn:aws:codewhisperer:<region>:<12 digits>:profile/<id> (else Kiro is asked for it), and oidc/runtime/management/refreshURL refuse a region that isn't an AWS region's shape. Version 0.1.40: #1156 published 0.1.39 first, so main was merged into the branch and the version raised (f8af341f). With arnOf, #1156's test fixture ARN (account "1") was dropped and its reasoning-replay test went red on the merge; every test fixture ARN now has a 12-digit account (0b899428). What was run, on mote with HOME=$(mktemp -d) as CI: - PR head 41938ff0, packages/kiro: bun test, 202 pass, 0 fail. - The earlier review's repro (imported Google sign-in, fresh access token, profileArn arn:aws:codewhisperer:attacker.example/#:1:profile/X): at 41938ff0 every request goes to *.kiro.dev, nothing saved with the crafted ARN. With 5dd9e682's index.mjs put back it and all five profile-host.test.mjs tests are red (hosts [management.attacker.example]). - Merged head f8af341f (main atbaeb95a4): root bun test, 8771 pass, 1 fail (reasoning-replay's fixture, above). - Reviewed head 0b899428: root bun test, 8772 pass, 0 fail, 613 files. Main since gained only2523b43a(packages/agy-cli/test/smoke.mjs). Read for credential safety: no logging; errors carry no token; refresh tokens and client secrets go only to Kiro's auth service and AWS OIDC; an imported sign-in has no dbKey/idePath, so renewing it writes back to no kiro-cli or IDE file. No .github, dependency or new host. Not tried: a real Kiro account imported from a real export.
This commit is contained in:
@@ -75,6 +75,55 @@ them, are under "Other ways to sign 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.
|
||||
- **Import accounts from a file** (magpie only, `auth.import`): a JSON file,
|
||||
or JSON pasted in, of sign-ins made elsewhere, one account or a list:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "email": "user@gmail.com", "refreshToken": "…", "provider": "Google" },
|
||||
{ "refreshToken": "…", "provider": "Github" },
|
||||
{ "refreshToken": "…", "clientId": "…", "clientSecret": "…", "provider": "BuilderId" },
|
||||
{ "refreshToken": "…", "clientId": "…", "clientSecret": "…", "provider": "Enterprise", "region": "eu-central-1" }
|
||||
]
|
||||
```
|
||||
|
||||
- `provider` is the way it was signed in to: `Google` and `Github` are
|
||||
renewed through Kiro's auth service in us-east-1; `BuilderId` and
|
||||
`Enterprise` (IAM Identity Center) through AWS's OIDC in `region`
|
||||
(blank: us-east-1), with the `clientId` and `clientSecret` registered
|
||||
for it. With no `provider`, `authMethod` (`social`, `IdC`) or `auth`
|
||||
(`Social`, `IdC`) says it, and else a sign-in with a client is AWS's.
|
||||
- Also read: Kiro Account Manager's export (`{ accounts: [{ email,
|
||||
provider, credentials: { refreshToken, … } }] }`), kiro2api's
|
||||
`KIRO_AUTH_TOKEN` list, the Kiro IDE's `kiro-auth-token.json` (choose its
|
||||
`<clientIdHash>.json` with it for a Builder ID or Identity Center
|
||||
sign-in), kiro-cli's tokens (`access_token`, `refresh_token`, …; one with
|
||||
a `start_url` or `scopes` is AWS's, renewed with the
|
||||
`kirocli:odic:device-registration` client chosen with it) and this
|
||||
plugin's own entries in `plugin-auth.json` or OpenCode's `auth.json`.
|
||||
Other providers' entries there (keys not `kiro` or `kiro#…`) are passed
|
||||
over, so none of their tokens is sent to Kiro.
|
||||
- Each sign-in is renewed first unless its access token has more than 2
|
||||
minutes left (`accessToken` with `expiresAt`), as the Kiro IDE renews
|
||||
it. Kiro may give a new refresh token and stop taking the old one, so
|
||||
the tool the file came from may have to sign in again.
|
||||
- It is named by the email Kiro has for it (the file's `email` when Kiro
|
||||
names none) and kept exactly as a browser sign-in of that way: `email
|
||||
(Google)`, with its `uid`, region, profile ARN and plan. One with no
|
||||
email either is `Kiro account <8 hex>`, from its file's token, so two
|
||||
such stay two accounts. Importing an account signed in already replaces
|
||||
it.
|
||||
- A file's `profileArn` is kept only in the shape Kiro gives one
|
||||
(`arn:aws:codewhisperer:<region>:<12 digits>:profile/<id>`); any other
|
||||
is dropped and Kiro is asked for the profile. As for every sign-in
|
||||
(the IDE's file, kiro-cli's, a saved one), the API's region is taken
|
||||
from the profile only when it is one of Kiro's (us-east-1,
|
||||
eu-central-1), and a region that isn't an AWS region's shape is refused
|
||||
before anything is sent, so no file decides where a token goes.
|
||||
- A sign-in Kiro refuses, one of an unknown `provider`, an AWS one without
|
||||
its client, and a company's own identity provider (`ExternalIdp`) are
|
||||
listed as not imported, with why; the others are imported. One sign-in
|
||||
twice is renewed once. At most 100 are taken at a time.
|
||||
|
||||
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
|
||||
|
||||
@@ -3,7 +3,7 @@ import { test, expect } from "bun:test"
|
||||
const model = "glm-5"
|
||||
const request = { model, output_config: { effort: "high" }, messages: [{ role: "user", content: "hi" }] }
|
||||
const account = { accountId: "account-a", uid: "enterprise" }
|
||||
const credentials = { token: "t", tokenType: "SSO_OIDC", idc: true, profile: "arn:aws:codewhisperer:us-east-1:1:profile/P", region: "us-east-1" }
|
||||
const credentials = { token: "t", tokenType: "SSO_OIDC", idc: true, profile: "arn:aws:codewhisperer:us-east-1:123456789012:profile/P", region: "us-east-1" }
|
||||
|
||||
function answer() {
|
||||
const header = Buffer.concat(Object.entries({ ":message-type": "event", ":event-type": "assistantResponseEvent" }).map(([key, value]) =>
|
||||
@@ -103,7 +103,7 @@ test("failed catalog lookups expire and are separate for each account and region
|
||||
await call(account, { ...credentials, token: "refreshed" })
|
||||
expect(s.reads).toHaveLength(1)
|
||||
await call({ ...account, accountId: "account-b" }, credentials)
|
||||
await call(account, { ...credentials, region: "eu-central-1", profile: "arn:aws:codewhisperer:eu-central-1:1:profile/P" })
|
||||
await call(account, { ...credentials, region: "eu-central-1", profile: "arn:aws:codewhisperer:eu-central-1:123456789012:profile/P" })
|
||||
expect(s.reads).toHaveLength(3)
|
||||
now += 10 * 60 * 1000 + 1
|
||||
await call(account, credentials)
|
||||
@@ -128,7 +128,7 @@ test("native fields use the selected account's regional catalog", async () => {
|
||||
try {
|
||||
await call(account, credentials)
|
||||
await call({ ...account, accountId: "account-b" }, { ...credentials, token: "other" })
|
||||
await call(account, { ...credentials, region: "eu-central-1", profile: "arn:aws:codewhisperer:eu-central-1:1:profile/P" })
|
||||
await call(account, { ...credentials, region: "eu-central-1", profile: "arn:aws:codewhisperer:eu-central-1:123456789012:profile/P" })
|
||||
await call(account, credentials)
|
||||
expect(s.reads).toHaveLength(3)
|
||||
expect(s.calls.map(body => body.additionalModelRequestFields)).toEqual([
|
||||
|
||||
@@ -33,7 +33,7 @@ const listed = (models) => {
|
||||
if (new URL(String(input)).pathname !== "/List-Available-Models") throw new Error("no network in tests")
|
||||
return Response.json({ defaultModel: { modelId: "auto" }, models })
|
||||
}
|
||||
return _internal.listModels({ region: "us-east-1", token: "t", tokenType: "", profile: "arn:aws:codewhisperer:us-east-1:1:profile/P" })
|
||||
return _internal.listModels({ region: "us-east-1", token: "t", tokenType: "", profile: "arn:aws:codewhisperer:us-east-1:123456789012:profile/P" })
|
||||
.finally(() => (globalThis.fetch = was))
|
||||
}
|
||||
const model = (modelId, schema) => ({ modelId, modelName: modelId, tokenLimits: { maxInputTokens: 1000000, maxOutputTokens: 128000 },
|
||||
|
||||
@@ -172,7 +172,7 @@ const creds = (fail) => {
|
||||
let n = 0
|
||||
return async () => {
|
||||
if (n++ && fail) throw fail
|
||||
return { token: "t", tokenType: "", profile: "arn:aws:codewhisperer:us-east-1:1:profile/x", region: "us-east-1" }
|
||||
return { token: "t", tokenType: "", profile: "arn:aws:codewhisperer:us-east-1:123456789012:profile/x", region: "us-east-1" }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
// magpie's "Import accounts from a file…" (auth.import) takes Kiro sign-ins
|
||||
// made elsewhere, by their refresh token: Kiro Account Manager's list
|
||||
// ([{ email, refreshToken, provider }]) and export, kiro2api's, the Kiro
|
||||
// IDE's kiro-auth-token.json with its client, kiro-cli's tokens. Each is
|
||||
// renewed the way its kind is (Kiro's auth service for Google and GitHub,
|
||||
// AWS's OIDC for Builder ID and Identity Center) and kept as the browser
|
||||
// sign-in keeps it.
|
||||
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, 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 PROFILE = "arn:aws:codewhisperer:us-east-1:111111111111:profile/TEST"
|
||||
const BUILDER_ID_PROFILE = "arn:aws:codewhisperer:us-east-1:638616132270:profile/AAAACCCCXXXX"
|
||||
const SOCIAL = "https://prod.us-east-1.auth.desktop.kiro.dev/refreshToken"
|
||||
const OIDC = (region) => `https://oidc.${region}.amazonaws.com/token`
|
||||
|
||||
// kiro renews every refresh token but the refused ones, and names each
|
||||
// account by the email given for its token in emails (none: Kiro's usage
|
||||
// read fails, as whoIs then names nothing)
|
||||
function kiro({ emails = {}, refused = [] } = {}) {
|
||||
const seen = { social: [], oidc: [], usage: [] }
|
||||
let n = 0
|
||||
globalThis.fetch = async (url, init = {}) => {
|
||||
const u = String(url)
|
||||
if (u === SOCIAL || u.startsWith("https://oidc.")) {
|
||||
const body = JSON.parse(init.body)
|
||||
;(u === SOCIAL ? seen.social : seen.oidc).push({ url: u, body, ua: new Headers(init.headers).get("User-Agent") })
|
||||
if (refused.includes(body.refreshToken)) return new Response(JSON.stringify({ error: "invalid_grant" }), { status: 400 })
|
||||
const access = "a" + ++n + ":" + body.refreshToken
|
||||
return Response.json({ accessToken: access, refreshToken: "next-" + body.refreshToken, expiresIn: 3600, ...(u === SOCIAL ? { profileArn: PROFILE } : {}) })
|
||||
}
|
||||
if (u.startsWith("https://management.")) {
|
||||
const token = new Headers(init.headers).get("Authorization").replace("Bearer ", "")
|
||||
seen.usage.push({ url: u, token })
|
||||
const email = emails[token.split(":").slice(1).join(":")] ?? emails[token]
|
||||
if (u.includes("/List-Available-Profiles")) return Response.json({ profiles: [{ arn: PROFILE }] })
|
||||
if (!email) return new Response(JSON.stringify({ message: "boom" }), { status: 500 })
|
||||
return Response.json({ subscriptionInfo: { subscriptionTitle: "KIRO PRO" }, userInfo: { email } })
|
||||
}
|
||||
throw new Error("unexpected request to " + u)
|
||||
}
|
||||
return seen
|
||||
}
|
||||
const hooks = () => plugin({ client: { auth: { set: async () => {} } } })
|
||||
const importing = async (...texts) => (await hooks()).auth.import(texts.map((t) => (typeof t === "string" ? t : JSON.stringify(t))))
|
||||
|
||||
test("magpie offers the import, saying what it takes in each language", async () => {
|
||||
const h = await hooks()
|
||||
expect(typeof h.auth.import).toBe("function")
|
||||
expect(h.auth.importFrom).toContain("refreshToken")
|
||||
for (const lang of ["zh", "zh-TW", "ja", "de"]) expect(h.auth.importFroms[lang]).toContain("refreshToken")
|
||||
})
|
||||
|
||||
test("Kiro Account Manager's list of Google sign-ins: renewed in us-east-1 and kept as the browser sign-in keeps them", async () => {
|
||||
const seen = kiro({ emails: { r1: "billrodrigo0@gmail.com", r2: "other@gmail.com" } })
|
||||
const got = await importing([
|
||||
{ email: "billrodrigo0@gmail.com", refreshToken: "r1", provider: "Google" },
|
||||
{ email: "other@gmail.com", refreshToken: "r2", provider: "Google" },
|
||||
])
|
||||
expect(seen.social.map((s) => s.body)).toEqual([{ refreshToken: "r1" }, { refreshToken: "r2" }])
|
||||
expect(seen.social[0].ua).toBe("Kiro-Desktop/0.2.13 (darwin; arm64)")
|
||||
expect(got).toEqual([
|
||||
{ type: "success", provider: "kiro", refresh: "next-r1", access: expect.stringContaining(":r1"), expires: expect.any(Number),
|
||||
accountId: "billrodrigo0@gmail.com (Google)", uid: "google", method: "social", loginProvider: "Google", region: "us-east-1",
|
||||
profileArn: PROFILE, plan: "Kiro Pro" },
|
||||
expect.objectContaining({ type: "success", accountId: "other@gmail.com (Google)", refresh: "next-r2" }),
|
||||
])
|
||||
expect(got[0].expires).toBeGreaterThan(Date.now() + 50 * 60_000)
|
||||
})
|
||||
|
||||
test("the email Kiro has for the sign-in names it, the file's only when Kiro names none", async () => {
|
||||
kiro({ emails: { r1: "real@example.com" } })
|
||||
const [a, b] = await importing([
|
||||
{ email: "typo@example.com", refreshToken: "r1", provider: "Google" },
|
||||
{ email: "kept@example.com", refreshToken: "r2", provider: "Github" },
|
||||
])
|
||||
expect(a.accountId).toBe("real@example.com (Google)")
|
||||
expect(b).toMatchObject({ type: "success", accountId: "kept@example.com (GitHub)", uid: "github", loginProvider: "Github", method: "social" })
|
||||
})
|
||||
|
||||
test("Builder ID and Identity Center are renewed with their client at AWS, in their region", async () => {
|
||||
const seen = kiro({ emails: { r1: "b@example.com", r2: "e@example.com" } })
|
||||
const [b, e] = await importing([
|
||||
{ refreshToken: "r1", clientId: "c1", clientSecret: "s1", provider: "BuilderId" },
|
||||
{ refreshToken: "r2", clientId: "c2", clientSecret: "s2", provider: "Enterprise", region: "eu-central-1" },
|
||||
])
|
||||
expect(seen.social).toEqual([])
|
||||
expect(seen.oidc.map((s) => [s.url, s.body])).toEqual([
|
||||
[OIDC("us-east-1"), { clientId: "c1", clientSecret: "s1", refreshToken: "r1", grantType: "refresh_token" }],
|
||||
[OIDC("eu-central-1"), { clientId: "c2", clientSecret: "s2", refreshToken: "r2", grantType: "refresh_token" }],
|
||||
])
|
||||
expect(b).toMatchObject({ type: "success", accountId: "b@example.com (Builder ID)", uid: "builderid", method: "idc", loginProvider: "BuilderId",
|
||||
region: "us-east-1", profileArn: BUILDER_ID_PROFILE, clientId: "c1", clientSecret: "s1", refresh: "next-r1" })
|
||||
expect(e).toMatchObject({ type: "success", accountId: "e@example.com (IAM Identity Center)", uid: "enterprise", method: "idc",
|
||||
loginProvider: "Enterprise", region: "eu-central-1", profileArn: PROFILE, clientId: "c2", clientSecret: "s2" })
|
||||
})
|
||||
|
||||
test("the Kiro IDE's kiro-auth-token.json goes with its client's file", async () => {
|
||||
const seen = kiro({ emails: { r1: "ide@example.com" } })
|
||||
const token = { accessToken: "old", refreshToken: "r1", expiresAt: "2020-01-01T00:00:00.000Z", authMethod: "IdC", provider: "BuilderId", clientIdHash: "abc", region: "us-east-1" }
|
||||
const [got] = await importing(token, { clientId: "c1", clientSecret: "s1", expiresAt: "2099-01-01T00:00:00.000Z" })
|
||||
expect(seen.oidc[0].body).toMatchObject({ clientId: "c1", clientSecret: "s1", refreshToken: "r1" })
|
||||
expect(got).toMatchObject({ type: "success", accountId: "ide@example.com (Builder ID)", clientId: "c1" })
|
||||
// without it, it can't be renewed, and says what is missing
|
||||
const [alone] = await importing(token)
|
||||
expect(alone.type).toBe("failed")
|
||||
expect(alone.error).toContain("clientId and clientSecret")
|
||||
})
|
||||
|
||||
test("Kiro Account Manager's export keeps the tokens under credentials, the email beside them", async () => {
|
||||
kiro({ emails: { r1: "kam@example.com" } })
|
||||
const [got] = await importing({ version: "1.8", accounts: [{ email: "kam@example.com", provider: "Google", credentials: { refreshToken: "r1", authMethod: "social", region: "us-east-1" } }] })
|
||||
expect(got).toMatchObject({ type: "success", accountId: "kam@example.com (Google)", method: "social" })
|
||||
})
|
||||
|
||||
test("kiro2api's Social and IdC, and kiro-cli's tokens, are read too", async () => {
|
||||
const seen = kiro({ emails: { r1: "s@example.com", r2: "i@example.com", r3: "cli@example.com" } })
|
||||
const got = await importing(
|
||||
[{ auth: "Social", refreshToken: "r1" }, { auth: "IdC", refreshToken: "r2", clientId: "c2", clientSecret: "s2" }],
|
||||
{ access_token: "old", refresh_token: "r3", expires_at: "2020-01-01T00:00:00.000000Z", provider: "google", profile_arn: PROFILE },
|
||||
)
|
||||
expect(seen.social.map((s) => s.body.refreshToken)).toEqual(["r1", "r3"])
|
||||
expect(seen.oidc.map((s) => s.body.refreshToken)).toEqual(["r2"])
|
||||
expect(got.map((r) => r.accountId)).toEqual(["s@example.com", "i@example.com", "cli@example.com (Google)"])
|
||||
expect(got.every((r) => r.type === "success")).toBe(true)
|
||||
})
|
||||
|
||||
test("kiro-cli's AWS sign-in, with its start URL and its client apart, is renewed at AWS", async () => {
|
||||
const seen = kiro({ emails: { r1: "cli@example.com" } })
|
||||
const [got] = await importing(
|
||||
{ access_token: "old", refresh_token: "r1", expires_at: "2020-01-01T00:00:00Z", region: "us-east-1", start_url: "https://view.awsapps.com/start", scopes: ["codewhisperer:completions"] },
|
||||
{ client_id: "c1", client_secret: "s1", region: "us-east-1" },
|
||||
)
|
||||
expect(seen.social).toEqual([])
|
||||
expect(seen.oidc[0].body).toMatchObject({ clientId: "c1", clientSecret: "s1", refreshToken: "r1" })
|
||||
expect(got).toMatchObject({ type: "success", method: "idc", loginProvider: "BuilderId", accountId: "cli@example.com (Builder ID)" })
|
||||
})
|
||||
|
||||
test("from a sign-in store, only Kiro's entries are taken: no other provider's token is sent to Kiro", async () => {
|
||||
const seen = kiro({ emails: { r1: "k@example.com" } })
|
||||
const store = {
|
||||
kiro: { type: "oauth", access: "old", refresh: "r1", expires: 1, method: "social", loginProvider: "Google", accountId: "k@example.com (Google)" },
|
||||
openai: { type: "oauth", access: "OPENAI_ACCESS", refresh: "OPENAI_REFRESH", expires: Date.now() + 3600_000, accountId: "o@example.com" },
|
||||
"grok#ab12cd": { type: "oauth", access: "x", refresh: "GROK_REFRESH", expires: 1 },
|
||||
}
|
||||
const got = await importing(store)
|
||||
expect(got.map((r) => r.accountId)).toEqual(["k@example.com (Google)"])
|
||||
expect(seen.social.map((s) => s.body.refreshToken)).toEqual(["r1"])
|
||||
expect(seen.usage.every((u) => !u.token.includes("OPENAI"))).toBe(true)
|
||||
})
|
||||
|
||||
test("accounts Kiro names no one for stay apart, each called by its own token", async () => {
|
||||
kiro()
|
||||
const [a, b] = await importing([{ auth: "Social", refreshToken: "t1" }, { auth: "Social", refreshToken: "t2" }])
|
||||
expect(a.type).toBe("success")
|
||||
expect(a.accountId).toMatch(/^Kiro account [0-9a-f]{8}$/)
|
||||
expect(b.accountId).toMatch(/^Kiro account [0-9a-f]{8}$/)
|
||||
expect(a.accountId).not.toBe(b.accountId)
|
||||
})
|
||||
|
||||
test("an access token with time left is kept, not renewed, as the Kiro IDE keeps it", async () => {
|
||||
const seen = kiro({ emails: { live: "live@example.com" } })
|
||||
const expiresAt = new Date(Date.now() + 30 * 60_000).toISOString()
|
||||
const [got] = await importing({ accessToken: "live", refreshToken: "r1", expiresAt, provider: "Google", profileArn: PROFILE })
|
||||
expect(seen.social).toEqual([])
|
||||
expect(got).toMatchObject({ type: "success", access: "live", refresh: "r1", accountId: "live@example.com (Google)" })
|
||||
})
|
||||
|
||||
test("a refresh token Kiro refuses is a failure naming the account, the others still imported", async () => {
|
||||
kiro({ emails: { r2: "ok@example.com" }, refused: ["r1"] })
|
||||
const [bad, good] = await importing([
|
||||
{ email: "gone@example.com", refreshToken: "r1", provider: "Google" },
|
||||
{ email: "ok@example.com", refreshToken: "r2", provider: "Google" },
|
||||
])
|
||||
expect(bad).toEqual({ type: "failed", accountId: "gone@example.com (Google)", error: expect.stringContaining("Kiro refused its refresh token") })
|
||||
expect(good).toMatchObject({ type: "success", accountId: "ok@example.com (Google)" })
|
||||
})
|
||||
|
||||
test("one sign-in twice is renewed once", async () => {
|
||||
const seen = kiro({ emails: { r1: "a@example.com" } })
|
||||
const got = await importing([{ refreshToken: "r1", provider: "Google" }], [{ refreshToken: "r1", provider: "Google" }])
|
||||
expect(seen.social.length).toBe(1)
|
||||
expect(got.length).toBe(1)
|
||||
})
|
||||
|
||||
test("what isn't a sign-in Kiro has is said, asking Kiro nothing", async () => {
|
||||
const seen = kiro()
|
||||
const got = await importing("not json", { hello: "world" }, [{ refreshToken: "r1", provider: "Facebook" }],
|
||||
[{ refreshToken: "r2", provider: "Enterprise" }], [{ refreshToken: "r3", provider: "ExternalIdp" }], [{ refreshToken: "r4", clientId: "c", clientSecret: "s", provider: "Enterprise", region: "moon" }])
|
||||
expect(got.map((r) => r.type)).toEqual(["failed", "failed", "failed", "failed", "failed", "failed"])
|
||||
expect(got[0].error).toBe("not JSON")
|
||||
expect(got[1].error).toContain("no Kiro sign-in")
|
||||
expect(got[2].error).toContain("Facebook")
|
||||
expect(got[3].error).toContain("clientId and clientSecret")
|
||||
expect(got[4].error).toContain("kiro-cli login")
|
||||
expect(got[5].error).toContain("isn't an AWS region")
|
||||
expect(seen.social.length + seen.oidc.length + seen.usage.length).toBe(0)
|
||||
})
|
||||
+183
-16
@@ -9,7 +9,8 @@
|
||||
// kiro-cli's or the IDE's own sign-in can be used instead: it is read where
|
||||
// they keep it each time, refreshed by kiro-cli first, and a token
|
||||
// refreshed here is written back, so they go on with it. A Kiro API key
|
||||
// (ksk_…) signs in too.
|
||||
// (ksk_…) signs in too, and in magpie sign-ins made elsewhere are imported
|
||||
// from a file by their refresh token (auth.import).
|
||||
//
|
||||
// Kiro has no API OpenCode speaks: the models are declared on Anthropic's
|
||||
// Messages, and the fetch here sends each request whole to Kiro's own API
|
||||
@@ -44,15 +45,30 @@ const WORDS = {
|
||||
own: { zh: "Kiro CLI 或 Kiro IDE 已登录的账号", "zh-TW": "Kiro CLI 或 Kiro IDE 已登入的帳號", ja: "Kiro CLI または Kiro IDE のサインイン", de: "Anmeldung von Kiro CLI oder Kiro IDE" },
|
||||
key: { zh: "Kiro API Key(ksk_…)", "zh-TW": "Kiro API Key(ksk_…)", ja: "Kiro API キー(ksk_…)", de: "Kiro-API-Schlüssel (ksk_…)" },
|
||||
}
|
||||
// IMPORT_FROM says what magpie's "Import accounts from a file…" takes
|
||||
const IMPORT_FROM = {
|
||||
en: "Choose a JSON file of Kiro sign-ins, or paste it: one account or a list, each with its refreshToken and the way it signed in (provider: Google, Github, BuilderId or Enterprise; Builder ID and Identity Center also need clientId, clientSecret and region), such as the Kiro IDE's kiro-auth-token.json. Each is renewed with Kiro before it is added, so the tool it came from may have to sign in again.",
|
||||
froms: {
|
||||
zh: "选择 Kiro 登录凭证的 JSON 文件,或直接粘贴:一个账号或一组账号,每个含 refreshToken 和登录方式(provider:Google、Github、BuilderId 或 Enterprise;Builder ID 和 IAM Identity Center 还需要 clientId、clientSecret 和 region),例如 Kiro IDE 的 kiro-auth-token.json。每个账号先向 Kiro 续期再添加,来源工具可能需要重新登录。",
|
||||
"zh-TW": "選擇 Kiro 登入憑證的 JSON 檔,或直接貼上:一個帳號或一組帳號,每個含 refreshToken 和登入方式(provider:Google、Github、BuilderId 或 Enterprise;Builder ID 和 IAM Identity Center 還需要 clientId、clientSecret 和 region),例如 Kiro IDE 的 kiro-auth-token.json。每個帳號先向 Kiro 續期再加入,來源工具可能需要重新登入。",
|
||||
ja: "Kiro のサインイン情報の JSON ファイルを選ぶか貼り付けてください。1 アカウントまたはリストで、各アカウントに refreshToken とサインイン方法(provider:Google、Github、BuilderId、Enterprise。Builder ID と IAM Identity Center は clientId、clientSecret、region も必要)を含めます。Kiro IDE の kiro-auth-token.json もそのまま使えます。各アカウントは追加前に Kiro で更新されるため、元のツールは再サインインが必要になることがあります。",
|
||||
de: "Wähle eine JSON-Datei mit Kiro-Anmeldungen oder füge sie ein: ein Konto oder eine Liste, jedes mit refreshToken und Anmeldeart (provider: Google, Github, BuilderId oder Enterprise; Builder ID und IAM Identity Center brauchen außerdem clientId, clientSecret und region), etwa die kiro-auth-token.json der Kiro IDE. Jedes Konto wird vor dem Hinzufügen bei Kiro erneuert, daher muss sich das Tool, aus dem es stammt, eventuell neu anmelden.",
|
||||
},
|
||||
}
|
||||
const MESSAGES = "@ai-sdk/anthropic"
|
||||
const BASE = "https://runtime.us-east-1.kiro.dev" // what OpenCode is given; the fetch sends each request to the account's region
|
||||
|
||||
const PORTAL = "https://app.kiro.dev"
|
||||
const AUTH_SERVICE = "https://prod.us-east-1.auth.desktop.kiro.dev"
|
||||
const oidc = (region) => `https://oidc.${region}.amazonaws.com`
|
||||
const runtime = (region) => `https://runtime.${region}.kiro.dev`
|
||||
const management = (region) => `https://management.${region}.kiro.dev`
|
||||
const refreshURL = (region) => `https://prod.${region}.auth.desktop.kiro.dev/refreshToken`
|
||||
// a region read from a file goes into these host names: one that isn't a region's shape is refused
|
||||
const inHost = (region) => {
|
||||
if (!AWS_REGION.test(String(region))) throw new Error(`${JSON.stringify(region)} isn't an AWS region`)
|
||||
return region
|
||||
}
|
||||
const oidc = (region) => `https://oidc.${inHost(region)}.amazonaws.com`
|
||||
const runtime = (region) => `https://runtime.${inHost(region)}.kiro.dev`
|
||||
const management = (region) => `https://management.${inHost(region)}.kiro.dev`
|
||||
const refreshURL = (region) => `https://prod.${inHost(region)}.auth.desktop.kiro.dev/refreshToken`
|
||||
// the ports Kiro's sign-in page sends the browser back to, the IDE's
|
||||
const CALLBACK_PORTS = [3128, 4649, 6588, 8008, 9091, 49153, 50153, 51153, 52153, 53153]
|
||||
// what the IDE asks AWS for
|
||||
@@ -165,7 +181,7 @@ async function readCLI() {
|
||||
const m = get(key)
|
||||
if (!m?.access_token) continue
|
||||
const c = { access: m.access_token, refresh: m.refresh_token ?? "", expires: time(m.expires_at), region: m.region || "us-east-1",
|
||||
profile: m.profile_arn ?? "", dbKey: key }
|
||||
profile: arnOf(m.profile_arn), dbKey: key }
|
||||
if (kind === "social") c.method = "social"
|
||||
else if (kind === "odic") {
|
||||
c.method = "idc"
|
||||
@@ -198,7 +214,7 @@ async function readIDE() {
|
||||
}
|
||||
if (!t?.accessToken) return null
|
||||
const c = { access: t.accessToken, refresh: t.refreshToken ?? "", expires: time(t.expiresAt), region: t.region || "us-east-1",
|
||||
profile: t.profileArn ?? "", method: "idc", idePath: path, builderID: isBuilderID(t.provider) }
|
||||
profile: arnOf(t.profileArn), method: "idc", idePath: path, builderID: isBuilderID(t.provider) }
|
||||
if (t.clientIdHash) {
|
||||
try {
|
||||
const reg = JSON.parse(await readFile(join(ideDir(), t.clientIdHash + ".json"), "utf8"))
|
||||
@@ -334,12 +350,17 @@ function authHeaders(a) {
|
||||
const tokenType = (c) => (c.method === "apikey" ? "API_KEY" : c.method === "external-idp" ? "EXTERNAL_IDP" : "")
|
||||
|
||||
// region is where the account's API is: the region its profile is in, else
|
||||
// the nearer of Kiro's two to where it signed in.
|
||||
// the nearer of Kiro's two to where it signed in. It goes into the API's host
|
||||
// name, so only Kiro's own regions are taken from a profile.
|
||||
function regionOf(profile, signedIn) {
|
||||
const parts = String(profile ?? "").split(":")
|
||||
if (parts.length > 4 && parts[3]) return parts[3]
|
||||
if (parts.length > 4 && CREDIT_REGIONS.includes(parts[3])) return parts[3]
|
||||
return String(signedIn ?? "").startsWith("eu-") ? "eu-central-1" : "us-east-1"
|
||||
}
|
||||
// arnOf is a profile ARN as Kiro gives one, else "": one read from a file
|
||||
// that isn't is left for profileOf to ask Kiro for
|
||||
const PROFILE_ARN = /^arn:aws:codewhisperer:[a-z]{2}(?:-[a-z]+)+-\d{1,2}:\d{12}:profile\/[A-Za-z0-9_-]+$/
|
||||
const arnOf = (s) => (PROFILE_ARN.test(String(s ?? "").trim()) ? String(s).trim() : "")
|
||||
|
||||
// STATUS_TEXT is Go's http.StatusText for the answers Kiro gives.
|
||||
const STATUS_TEXT = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 408: "Request Timeout",
|
||||
@@ -688,7 +709,7 @@ async function credOf(auth) {
|
||||
if (auth.source === "kiro") return (await readCLI()) ?? (await readIDE())
|
||||
if (!auth.access) return null
|
||||
return { access: auth.access, refresh: auth.refresh ?? "", expires: auth.expires ?? 0, method: auth.method || "social",
|
||||
region: auth.region || "us-east-1", profile: auth.profileArn ?? "", clientId: auth.clientId ?? "", clientSecret: auth.clientSecret ?? "",
|
||||
region: auth.region || "us-east-1", profile: arnOf(auth.profileArn), clientId: auth.clientId ?? "", clientSecret: auth.clientSecret ?? "",
|
||||
builderID: isBuilderID(auth.loginProvider), own: true,
|
||||
...(auth.profiles && typeof auth.profiles === "object" && !Array.isArray(auth.profiles) ? { profiles: { ...auth.profiles } } : {}) }
|
||||
}
|
||||
@@ -2978,6 +2999,17 @@ function httpsURL(s) {
|
||||
}
|
||||
}
|
||||
|
||||
// signedIn is the account a sign-in keeps, whether made in the browser or
|
||||
// brought in from a file: named by the email Kiro has for it (else the one
|
||||
// given), with the way it was signed in to.
|
||||
function signedIn(c, who, email = who.email, nameless = "Kiro account") {
|
||||
return { type: "success", provider: ID, refresh: c.refresh, access: c.access, expires: c.expires,
|
||||
accountId: email ? nameOf(email, c.loginProvider) : nameless,
|
||||
...(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 } : {}) }
|
||||
}
|
||||
|
||||
// whoIs names a new sign-in with the email Kiro has for it, and its plan.
|
||||
async function whoIs(c) {
|
||||
try {
|
||||
@@ -3152,13 +3184,10 @@ async function browserSignIn(inputs = {}) {
|
||||
// still busy while it is named: a second paste is told it is finishing
|
||||
const who = await whoIs(c)
|
||||
if (stage === "over") return over()
|
||||
const user = who.email ? nameOf(who.email, c.loginProvider) : "Kiro account"
|
||||
const done = signedIn(c, who)
|
||||
stage = "over"
|
||||
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.`))
|
||||
finish(done)
|
||||
html(200, page(true, "You're signed in", `${done.accountId} is signed in. You can close this tab.`))
|
||||
})
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
@@ -3226,6 +3255,140 @@ async function ownSignIn() {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- accounts from a file (magpie's auth.import) ------------------------------------
|
||||
//
|
||||
// A file of sign-ins made elsewhere: Kiro Account Manager's ([{ email,
|
||||
// refreshToken, provider }], or its export with the tokens under
|
||||
// credentials), kiro2api's ({ auth: "Social" | "IdC", refreshToken }), the
|
||||
// Kiro IDE's kiro-auth-token.json (with its <clientIdHash>.json client),
|
||||
// kiro-cli's tokens, or this plugin's own entry. Each is kept as the browser
|
||||
// sign-in keeps it (signedIn), renewed first the way its kind is renewed.
|
||||
|
||||
const IMPORT_MOST = 100 // what magpie keeps of one import
|
||||
const IMPORT_AT_ONCE = 6
|
||||
// the ways a sign-in is named in those files, as loginProvider says them
|
||||
const IMPORT_WAYS = { google: "Google", github: "Github", builderid: "BuilderId", awsbuilderid: "BuilderId", enterprise: "Enterprise",
|
||||
idc: "Enterprise", awsidc: "Enterprise", identitycenter: "Enterprise", iamidentitycenter: "Enterprise", internal: "Internal" }
|
||||
const squash = (s) => s.toLowerCase().replace(/[^a-z]/g, "")
|
||||
const word = (v) => (typeof v === "string" ? v.trim() : "")
|
||||
const pick = (o, ...keys) => keys.map((k) => word(o[k])).find(Boolean) ?? ""
|
||||
// an expiry as ISO time, local "YYYY/MM/DD HH:MM:SS", Unix seconds or ms
|
||||
const whenOf = (v) => (typeof v === "number" ? (v <= 0 ? 0 : v < 1e11 ? v * 1000 : v) : time(v))
|
||||
const emailIn = (s) => /^([^\s()]+@[^\s()]+)(?: \([^()]*\))?$/.exec(s)?.[1] ?? ""
|
||||
const EXTERNAL_IDP = "A company's own identity provider can't be signed in to here yet; sign in with `kiro-cli login`, and use Kiro CLI's sign-in"
|
||||
const NO_CLIENT = "an AWS Builder ID or IAM Identity Center sign-in is renewed with the client it was registered with: add its clientId and clientSecret, or choose the Kiro IDE's registration file (~/.aws/sso/cache/<clientIdHash>.json) with it"
|
||||
const REFUSED = "Kiro refused its refresh token: it has expired, been revoked, or been replaced by a newer one where it came from; sign in there again and export it once more"
|
||||
const REFUSED_IDC = "AWS refused its refresh token or its client: one has expired or been revoked; sign in again where it came from and export it once more"
|
||||
|
||||
// entryOf reads one sign-in of a file: { c, email } as refresh() takes it,
|
||||
// or { error, email }.
|
||||
function entryOf(o) {
|
||||
const said = pick(o, "provider", "loginProvider", "idp", "loginMethod", "login_option")
|
||||
const how = squash(pick(o, "authMethod", "auth_method", "auth", "method"))
|
||||
const email = emailIn(pick(o, "email", "accountId"))
|
||||
if (squash(said) === "externalidp" || how === "externalidp") return { error: EXTERNAL_IDP, email }
|
||||
let loginProvider = IMPORT_WAYS[squash(said)] ?? ""
|
||||
if (said && !loginProvider) return { error: `Kiro has no sign-in with ${JSON.stringify(said)}; provider is Google, Github, BuilderId or Enterprise`, email }
|
||||
const clientId = pick(o, "clientId", "client_id")
|
||||
const clientSecret = pick(o, "clientSecret", "client_secret")
|
||||
const start = pick(o, "startUrl", "start_url", "issuerUrl", "issuer_url")
|
||||
// kiro-cli's AWS sign-in names no provider and keeps its client apart, but has a start URL or scopes
|
||||
const aws = how === "idc" || how === "builderid" || !!clientId || !!start || Array.isArray(o.scopes)
|
||||
const social = loginProvider ? loginProvider === "Google" || loginProvider === "Github" : how === "social" || !aws
|
||||
if (!social && !loginProvider) {
|
||||
loginProvider = how === "builderid" || start === BUILDER_ID_START ? "BuilderId" : start ? "Enterprise" : ""
|
||||
}
|
||||
// Kiro's auth service renews every Google and GitHub sign-in in us-east-1
|
||||
const region = social ? "us-east-1" : pick(o, "idcRegion", "idc_region", "authRegion", "region") || "us-east-1"
|
||||
if (!AWS_REGION.test(region)) return { error: `${JSON.stringify(region)} isn't an AWS region`, email }
|
||||
return { email, c: { access: pick(o, "accessToken", "access_token", "access"), refresh: pick(o, "refreshToken", "refresh_token", "refresh"),
|
||||
expires: whenOf(o.expiresAt ?? o.expires_at ?? o.expires), method: social ? "social" : "idc", loginProvider, region,
|
||||
profile: arnOf(pick(o, "profileArn", "profile_arn")), clientId, clientSecret, builderID: isBuilderID(loginProvider) } }
|
||||
}
|
||||
|
||||
// signInsIn are the sign-ins a file's text holds; the clients registered
|
||||
// with AWS it holds (the Kiro IDE's <clientIdHash>.json) go into regs.
|
||||
function signInsIn(text, regs) {
|
||||
let v
|
||||
try {
|
||||
v = JSON.parse(text)
|
||||
} catch {
|
||||
return [{ error: "not JSON" }]
|
||||
}
|
||||
const out = []
|
||||
const seen = new Set()
|
||||
const walk = (o, depth) => {
|
||||
if (!o || typeof o !== "object" || depth > 4 || seen.has(o)) return
|
||||
seen.add(o)
|
||||
if (Array.isArray(o)) return o.forEach((x) => walk(x, depth + 1))
|
||||
const t = o.credentials && typeof o.credentials === "object" && !Array.isArray(o.credentials) ? { ...o, ...o.credentials } : o
|
||||
if (pick(t, "refreshToken", "refresh_token", "refresh", "accessToken", "access_token", "access")) return out.push(entryOf(t))
|
||||
const clientId = pick(t, "clientId", "client_id")
|
||||
const clientSecret = pick(t, "clientSecret", "client_secret")
|
||||
if (clientId && clientSecret) return regs.push({ clientId, clientSecret })
|
||||
// a sign-in store (magpie's plugin-auth.json, OpenCode's auth.json) keeps other providers' too: only Kiro's are taken
|
||||
for (const [k, x] of Object.entries(o)) if (!(x && (x.type === "oauth" || x.type === "api") && !/^kiro(#|$)/i.test(k))) walk(x, depth + 1)
|
||||
}
|
||||
walk(v, 0)
|
||||
return out.length || regs.length ? out : [{ error: "no Kiro sign-in in it (no refreshToken)" }]
|
||||
}
|
||||
|
||||
// importOne checks a sign-in with Kiro as signing in does: renewed unless
|
||||
// its access token still has time (as the Kiro IDE renews it), then named
|
||||
// by the email Kiro has for it.
|
||||
async function importOne(e) {
|
||||
const failed = (error) => ({ type: "failed", error, ...(e.email ? { accountId: nameOf(e.email, e.c?.loginProvider) } : {}) })
|
||||
if (e.error) return failed(e.error)
|
||||
let c = e.c
|
||||
if (c.method === "idc" && !(c.clientId && c.clientSecret)) return failed(NO_CLIENT)
|
||||
try {
|
||||
let renewed = false
|
||||
if (!c.access || !(c.expires - Date.now() > EARLY_MS)) {
|
||||
if (!c.refresh) return failed("its access token has ended, and it has no refreshToken to renew it with")
|
||||
c = await refresh(c)
|
||||
renewed = true
|
||||
}
|
||||
let who = await whoIs(c)
|
||||
// an access token Kiro didn't answer to: renewed, and asked again
|
||||
if (!who.email && !renewed && c.refresh) {
|
||||
c = await refresh(c)
|
||||
who = await whoIs(c)
|
||||
}
|
||||
// one Kiro names no one is still its own account: called by its file's token, so two such aren't kept as one
|
||||
const tag = createHash("sha256").update(e.c.refresh || e.c.access).digest("hex").slice(0, 8)
|
||||
return signedIn(c, who, who.email || e.email, `Kiro account ${tag}`)
|
||||
} catch (err) {
|
||||
return failed(err?.gone ? (c.method === "idc" ? REFUSED_IDC : REFUSED) : err?.message ?? String(err))
|
||||
}
|
||||
}
|
||||
|
||||
async function importSignIns(texts, signal) {
|
||||
const regs = []
|
||||
const found = texts.flatMap((t) => signInsIn(t, regs))
|
||||
if (regs.length === 1) for (const e of found) if (e.c?.method === "idc" && !e.c.clientId) Object.assign(e.c, regs[0])
|
||||
// one sign-in twice: renewing it twice would spend its refresh token
|
||||
const tokens = new Set()
|
||||
const list = found.filter((e) => {
|
||||
const k = e.c?.refresh || e.c?.access
|
||||
if (!k) return true
|
||||
if (tokens.has(k)) return false
|
||||
tokens.add(k)
|
||||
return true
|
||||
})
|
||||
const left = list.length > IMPORT_MOST ? list.splice(IMPORT_MOST - 1).length : 0
|
||||
const results = []
|
||||
let next = 0
|
||||
const work = async () => {
|
||||
while (next < list.length && !signal?.aborted) {
|
||||
const i = next++
|
||||
results[i] = await importOne(list[i])
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(IMPORT_AT_ONCE, list.length) }, work))
|
||||
if (left) results.push({ type: "failed", error: `${left} more sign-ins weren't imported: at most ${IMPORT_MOST} are taken at a time; import the rest on their own` })
|
||||
return results.filter(Boolean)
|
||||
}
|
||||
|
||||
// ---- the plugin ------------------------------------------------------------------------
|
||||
|
||||
async function bodyOf(input, init) {
|
||||
@@ -3306,6 +3469,10 @@ export async function KiroAuthPlugin({ client, magpie } = {}) {
|
||||
return { error: e.message, signIn: e.gone ? "expired" : "kept" }
|
||||
}
|
||||
},
|
||||
// magpie's "Import accounts from a file…" (OpenCode ignores it)
|
||||
importFrom: IMPORT_FROM.en,
|
||||
importFroms: IMPORT_FROM.froms,
|
||||
import: (texts, { signal } = {}) => importSignIns(Array.isArray(texts) ? texts : [texts], signal),
|
||||
// labels, messages and hints are magpie's own fields: the same words
|
||||
// by the window's language (OpenCode shows the English)
|
||||
// magpie's switches for the provider (#2038): shown in its editor, read
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-kiro-auth",
|
||||
"version": "0.1.39",
|
||||
"version": "0.1.40",
|
||||
"description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
// A profile ARN's region and a sign-in's region go into the host every
|
||||
// token and request is sent to. One read from a file (an imported list,
|
||||
// the Kiro IDE's kiro-auth-token.json, kiro-cli's database, a saved
|
||||
// sign-in) is taken only in the shape Kiro gives it: an ARN that isn't one
|
||||
// is dropped and Kiro is asked for the profile, a profile's region outside
|
||||
// Kiro's own falls back, and a region that isn't one is refused before any
|
||||
// request (plugins#1132 review).
|
||||
import { test, expect, afterAll, beforeAll, afterEach } from "bun:test"
|
||||
import { homedir, tmpdir } from "node:os"
|
||||
import { mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
|
||||
let plugin, internal
|
||||
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, _internal: internal } = await import("./index.mjs"))
|
||||
})
|
||||
const offline = async () => { throw new Error("no network in tests") }
|
||||
const real = globalThis.fetch
|
||||
globalThis.fetch = offline
|
||||
const ideDir = () => join(homedir(), ".aws", "sso", "cache")
|
||||
afterAll(() => {
|
||||
globalThis.fetch = real
|
||||
rmSync(ideDir(), { recursive: true, force: true })
|
||||
})
|
||||
afterEach(() => {
|
||||
globalThis.fetch = offline
|
||||
rmSync(ideDir(), { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const CRAFTED = "arn:aws:codewhisperer:attacker.example/#:1:profile/X"
|
||||
const PROFILE = "arn:aws:codewhisperer:us-east-1:111111111111:profile/TEST"
|
||||
const later = () => new Date(Date.now() + 3600e3).toISOString()
|
||||
const kiroHost = (h) => h.endsWith(".kiro.dev") || h.endsWith(".amazonaws.com")
|
||||
|
||||
// every request's host noted; Kiro answers each as if it were the one asked
|
||||
function kiro() {
|
||||
const hosts = []
|
||||
globalThis.fetch = async (url) => {
|
||||
hosts.push(new URL(String(url)).host)
|
||||
return Response.json({ profiles: [{ arn: PROFILE }], userInfo: { email: "x@y.z" }, subscriptionInfo: { subscriptionTitle: "KIRO FREE" }, models: [] })
|
||||
}
|
||||
return hosts
|
||||
}
|
||||
const hooks = () => plugin({ client: { auth: { set: async () => {} } } })
|
||||
|
||||
test("an imported profileArn doesn't pick the host: it is dropped and Kiro asked for the profile", async () => {
|
||||
const hosts = kiro()
|
||||
const h = await hooks()
|
||||
const [got] = await h.auth.import([JSON.stringify([{ email: "u@gmail.com", provider: "Google", refreshToken: "r", accessToken: "a",
|
||||
expiresAt: later(), profileArn: CRAFTED }])])
|
||||
expect(hosts.length).toBeGreaterThan(0)
|
||||
expect(hosts.every(kiroHost)).toBe(true)
|
||||
expect(got).toMatchObject({ type: "success", profileArn: PROFILE })
|
||||
})
|
||||
|
||||
test("the Kiro IDE's file with a malformed profileArn sends nothing outside Kiro", async () => {
|
||||
mkdirSync(ideDir(), { recursive: true })
|
||||
writeFileSync(join(ideDir(), "kiro-auth-token.json"), JSON.stringify({ accessToken: "t", refreshToken: "r", expiresAt: later(),
|
||||
authMethod: "social", provider: "Google", profileArn: CRAFTED }))
|
||||
expect((await internal.readIDE()).profile).toBe("")
|
||||
const hosts = kiro()
|
||||
const h = await hooks()
|
||||
await h.provider.models({ models: { auto: {} } }, { auth: { type: "oauth", source: "kiro-ide", access: "", refresh: "", expires: 0 } })
|
||||
expect(hosts.length).toBeGreaterThan(0)
|
||||
expect(hosts.every(kiroHost)).toBe(true)
|
||||
})
|
||||
|
||||
test("a saved sign-in's malformed profileArn sends a request nowhere outside Kiro", async () => {
|
||||
const hosts = kiro()
|
||||
const h = await hooks()
|
||||
const stored = { type: "oauth", access: "a", refresh: "r", expires: Date.now() + 3600e3, method: "social", region: "us-east-1", profileArn: CRAFTED, accountId: "u@gmail.com (Google)" }
|
||||
const l = await h.auth.loader(async () => stored)
|
||||
await l.fetch("https://kiro.invalid/v1/messages", { method: "POST", body: JSON.stringify({ model: "auto", messages: [{ role: "user", content: "hi" }] }) })
|
||||
expect(hosts.length).toBeGreaterThan(0)
|
||||
expect(hosts.every(kiroHost)).toBe(true)
|
||||
})
|
||||
|
||||
test("a region that isn't one is refused before the refresh is sent", async () => {
|
||||
mkdirSync(ideDir(), { recursive: true })
|
||||
writeFileSync(join(ideDir(), "kiro-auth-token.json"), JSON.stringify({ accessToken: "t", refreshToken: "r", expiresAt: "2020-01-01T00:00:00Z",
|
||||
authMethod: "social", provider: "Google", region: "attacker.example/#" }))
|
||||
const hosts = kiro()
|
||||
const e = await internal.refresh(await internal.readIDE()).catch((e) => e)
|
||||
expect(e.message).toContain("isn't an AWS region")
|
||||
expect(hosts).toEqual([])
|
||||
})
|
||||
|
||||
test("only Kiro's own regions are taken from a profile", () => {
|
||||
expect(internal.regionOf(CRAFTED, "us-east-1")).toBe("us-east-1")
|
||||
expect(internal.regionOf("arn:aws:codewhisperer:us-west-2:111111111111:profile/X", "eu-west-1")).toBe("eu-central-1")
|
||||
expect(internal.regionOf("arn:aws:codewhisperer:eu-central-1:111111111111:profile/X", "us-east-1")).toBe("eu-central-1")
|
||||
expect(internal.regionOf(PROFILE, "eu-central-1")).toBe("us-east-1")
|
||||
})
|
||||
@@ -20,7 +20,7 @@ const listed = async (models) => {
|
||||
return Response.json({ defaultModel: DEFAULT, models, nextToken: null })
|
||||
}
|
||||
try {
|
||||
return await _internal.listModels({ region: "us-east-1", token: "t", tokenType: "", profile: "arn:aws:codewhisperer:us-east-1:1:profile/P" })
|
||||
return await _internal.listModels({ region: "us-east-1", token: "t", tokenType: "", profile: "arn:aws:codewhisperer:us-east-1:123456789012:profile/P" })
|
||||
} finally {
|
||||
globalThis.fetch = was
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { _internal } from "./index.mjs"
|
||||
const { buildKiro, events, reply, generate, features, sealReasoning, unsealReasoning } = _internal
|
||||
const scope = "account-region-model"
|
||||
const native = { reasoningText: { text: "The path costs 35.", signature: "CAQSbmF0aXZlLXNpZ25hdHVyZQ==" } }
|
||||
const creds = async () => ({ token: "t", tokenType: "SSO_OIDC", idc: true, profile: "arn:aws:codewhisperer:us-east-1:1:profile/P", region: "us-east-1" })
|
||||
const creds = async () => ({ token: "t", tokenType: "SSO_OIDC", idc: true, profile: "arn:aws:codewhisperer:us-east-1:123456789012:profile/P", region: "us-east-1" })
|
||||
const auth = { accountId: "account", uid: "enterprise" }
|
||||
const model = "claude-opus-5.5"
|
||||
const req = { model, messages: [{ role: "user", content: "Compute the path, then ask for confirmation." }] }
|
||||
@@ -164,7 +164,7 @@ test("the first native-model request loads its schema and applies magpie's effor
|
||||
}
|
||||
try {
|
||||
const plugin = await KiroAuthPlugin()
|
||||
const loader = await plugin.auth.loader(async () => ({ type: "oauth", access: "t", expires: Date.now() + 3600000, accountId: "account", uid: "google", loginProvider: "Google", profileArn: "arn:aws:codewhisperer:us-east-1:1:profile/P", region: "us-east-1" }))
|
||||
const loader = await plugin.auth.loader(async () => ({ type: "oauth", access: "t", expires: Date.now() + 3600000, accountId: "account", uid: "google", loginProvider: "Google", profileArn: "arn:aws:codewhisperer:us-east-1:123456789012:profile/P", region: "us-east-1" }))
|
||||
const res = await loader.fetch("https://kiro.test/v1/messages", { method: "POST", headers: { "x-magpie-effort": "low" }, body: JSON.stringify({ model: "gpt-5.6-luna", output_config: { effort: "max" }, messages: req.messages }) })
|
||||
await res.text()
|
||||
expect(paths).toContain("/List-Available-Models")
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@
|
||||
{ "package": "@magpie-community/opencode-cursor-auth", "name": "Cursor", "icon": "cursor", "providers": ["cursor"], "community": true, "replaces": "cursor",
|
||||
"summary": { "en": "Cursor Pro, Pro+, Ultra and Teams — every model your plan has, with tool calls.", "zh": "Cursor Pro、Pro+、Ultra 与 Teams:套餐里的所有模型,支持工具调用。" } },
|
||||
{ "package": "@magpie-community/opencode-kiro-auth", "name": "Kiro", "icon": "kiro-color", "providers": ["kiro"], "community": true, "replaces": "kiro",
|
||||
"summary": { "en": "Kiro Free, Pro, Pro+ and Power — Kiro's sign-in, kiro-cli's, or an API key.", "zh": "Kiro Free、Pro、Pro+ 与 Power:Kiro 登录、沿用 kiro-cli 的登录,或 API key。" } },
|
||||
"summary": { "en": "Kiro Free, Pro, Pro+ and Power — Kiro's sign-in, kiro-cli's, an API key, or accounts imported by refresh token.", "zh": "Kiro Free、Pro、Pro+ 与 Power:Kiro 登录、沿用 kiro-cli 的登录、API key,或按 refresh token 导入账号。" } },
|
||||
{ "package": "@magpie-community/opencode-minimax-auth", "name": "MiniMax Code", "icon": "minimax-color", "providers": ["minimax-code", "minimax-code-global"], "community": true,
|
||||
"summary": { "en": "MiniMax Code credits and M Plan with device sign-in, native web search, image/video generation and media tools through Magpie MCP.", "zh": "MiniMax Code 积分与 M Plan、设备登录,提供原生网络搜索、生图、生视频及多模态 MCP 工具。" } },
|
||||
{ "package": "@magpie-community/opencode-warp-auth", "name": "Warp", "icon": "warp", "providers": ["warp"], "community": true,
|
||||
|
||||
Reference in New Issue
Block a user