kiro 0.1.6: magpie renews the sign-in ahead of time through auth.refresh
auth.refresh with refreshLead 10 minutes (in-fetch: 2) for sign-ins kept in magpie; kiro-cli's and the IDE's (expires 0) are renewed as before. It runs under the request path's per-account lock, and an after map lets a request holding the old token use the new one. Every failure, a refusal included, throws plainly: the built-in never marked a Kiro account lapsed. The check before each request stays for OpenCode, which doesn't call the hook (magpie 0.1.684+ does). refresh.test.mjs fails without the change; HOME=$(mktemp -d) bun test passes (396 across the repo).
This commit is contained in:
+17
-2
@@ -39,8 +39,23 @@ Power) and makes its requests, in OpenCode and in magpie. Provider id:
|
||||
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
|
||||
tokens, the profile ARN, the region and, for AWS, the registered client.
|
||||
Tokens are refreshed 2 minutes before they expire, and also when Kiro
|
||||
turns one down (a 403, after which the request is tried once more):
|
||||
Refreshing such a sign-in:
|
||||
|
||||
- magpie renews the token 10 minutes before it expires, through the
|
||||
plugin's `auth.refresh`, once for the account and before its requests,
|
||||
models and usage need it. magpie saves the new token. A failed renewal,
|
||||
even one Kiro refused, doesn't mark the account: it is tried again.
|
||||
- OpenCode doesn't call that hook: there the token is refreshed 2 minutes
|
||||
before it expires, before a request, and saved.
|
||||
- Either way, a token Kiro turns down (a 403) is refreshed and the request
|
||||
tried once more.
|
||||
- Only one refresh runs at a time, magpie's renewal included, and a token
|
||||
refreshed but not yet saved is used rather than spending the old refresh
|
||||
token again.
|
||||
- kiro-cli's and the IDE's sign-ins aren't renewed by magpie: they are
|
||||
refreshed before a request, as above, and written back.
|
||||
|
||||
Tokens are refreshed through:
|
||||
|
||||
- Google/GitHub: through `prod.<region>.auth.desktop.kiro.dev/refreshToken`.
|
||||
- Builder ID/Identity Center: through AWS's `oidc.<region>.amazonaws.com/token`.
|
||||
|
||||
+53
-4
@@ -197,7 +197,9 @@ const EXPIRED_CLI = EXPIRED + " with `kiro-cli login` or the Kiro IDE"
|
||||
// there. The built-in marked no Kiro account lapsed, not even then, nor
|
||||
// cleared one: every answer and usage read says the account is kept.
|
||||
const gone = (msg) => Object.assign(new Error(msg), { gone: true })
|
||||
const fresh = (c) => c.method === "apikey" || !c.expires || c.expires - Date.now() > 2 * 60 * 1000
|
||||
const EARLY_MS = 2 * 60 * 1000 // a token this close to its end is refreshed before a request
|
||||
const LEAD_MS = 10 * 60 * 1000 // and this close, magpie renews it ahead of time (auth.refresh)
|
||||
const fresh = (c, early = EARLY_MS) => c.method === "apikey" || !c.expires || c.expires - Date.now() > early
|
||||
|
||||
async function post(url, contentType, body, headers = {}) {
|
||||
let res
|
||||
@@ -400,8 +402,23 @@ async function credOf(auth) {
|
||||
// Account holds the credentials in use, refreshing them when near their
|
||||
// end or when Kiro turned one down; one refresh at a time, as a refresh
|
||||
// may replace the refresh token.
|
||||
//
|
||||
// after is what each refresh gave, by the access token it replaced: a
|
||||
// sign-in read with that token (its save failed, or magpie hasn't yet
|
||||
// saved what auth.refresh gave) goes on with the newer one rather than
|
||||
// spending the replaced refresh token again.
|
||||
function account(client) {
|
||||
let held = null // { id, c }
|
||||
const after = new Map()
|
||||
const newest = (c) => {
|
||||
for (let i = 0; i < 16 && after.has(c.access); i++) c = { ...after.get(c.access) }
|
||||
return c
|
||||
}
|
||||
const renewed = (c, n) => {
|
||||
after.set(c.access, n)
|
||||
if (after.size > 16) after.delete(after.keys().next().value)
|
||||
return n
|
||||
}
|
||||
let lock = Promise.resolve()
|
||||
const locked = (fn) => {
|
||||
const run = lock.then(fn, fn)
|
||||
@@ -414,12 +431,12 @@ function account(client) {
|
||||
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(() => {})
|
||||
}
|
||||
return (auth, stale = false) =>
|
||||
const creds = (auth, stale = false) =>
|
||||
locked(async () => {
|
||||
const id = auth?.type === "api" ? "key:" + auth.key : "oauth:" + (auth?.source ?? "own")
|
||||
// what its owner holds now: it may have refreshed it, signed out, or
|
||||
// signed in to another account since
|
||||
const read = await credOf(auth)
|
||||
let read = await credOf(auth)
|
||||
if (!read) {
|
||||
held = null
|
||||
throw gone(
|
||||
@@ -428,6 +445,7 @@ function account(client) {
|
||||
: "this Kiro account's sign-in is gone; add it again in magpie",
|
||||
)
|
||||
}
|
||||
read = newest(read)
|
||||
let c = held?.id === id ? held.c : null
|
||||
if (!c || read.access !== c.access || !fresh(c) || stale) {
|
||||
if (!read.profile && c && read.access === c.access) read.profile = c.profile
|
||||
@@ -435,7 +453,7 @@ function account(client) {
|
||||
c = read
|
||||
if (!fresh(c) || stale) {
|
||||
if (c.method === "apikey") throw gone("Kiro turned down the API key saved on the provider")
|
||||
c = await refresh(c)
|
||||
c = renewed(c, await refresh(c))
|
||||
await save(auth, c)
|
||||
}
|
||||
}
|
||||
@@ -446,6 +464,25 @@ function account(client) {
|
||||
held = { id, c }
|
||||
return { token: c.access, tokenType: tokenType(c), profile: 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
|
||||
// requests' refresh, so the two never spend one refresh token. It saves
|
||||
// nothing — magpie saves what it gives — and gives only what changed.
|
||||
creds.renew = (auth) =>
|
||||
locked(async () => {
|
||||
const read = await credOf(auth)
|
||||
if (!read?.own || !read.refresh) return undefined
|
||||
let c = newest(read)
|
||||
// renewed here already (a request's refresh, or this hook's whose
|
||||
// result magpie hasn't saved yet), the store not yet saying so
|
||||
if (c.access === read.access || !fresh(c, LEAD_MS)) c = renewed(c, await refresh(c))
|
||||
held = { id: "oauth:own", c }
|
||||
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 creds
|
||||
}
|
||||
|
||||
// ---- models ----------------------------------------------------------------------
|
||||
@@ -1325,6 +1362,18 @@ export async function KiroAuthPlugin({ client } = {}) {
|
||||
return {
|
||||
auth: {
|
||||
provider: ID,
|
||||
// magpie renews a sign-in kept here LEAD_MS before its end, once for
|
||||
// the account, before its requests, models and usage ask for it; the
|
||||
// check before each request stays for OpenCode, which doesn't call
|
||||
// this. kiro-cli's and the IDE's sign-ins have no end magpie knows
|
||||
// (expires 0) and are never asked for.
|
||||
refreshLead: LEAD_MS,
|
||||
// A failure is thrown as it is, a refusal too: the built-in marked
|
||||
// no Kiro account lapsed (see gone).
|
||||
async refresh(auth) {
|
||||
if (auth?.type !== "oauth" || auth.source || !auth.access || !auth.refresh) return undefined
|
||||
return creds.renew(auth)
|
||||
},
|
||||
async loader(getAuth) {
|
||||
const auth = await getAuth()
|
||||
if (!(auth?.type === "api" && auth.key) && auth?.type !== "oauth") return {}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-kiro-auth",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
// magpie renews a sign-in kept here ahead of its end through auth.refresh,
|
||||
// under the same lock as a request's own refresh, so one refresh token is
|
||||
// never spent twice; OpenCode, which doesn't call it, still refreshes
|
||||
// before a request.
|
||||
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 (~/.kiro, ~/.aws, kiro-cli's) 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 REFRESH = "https://prod.us-east-1.auth.desktop.kiro.dev/refreshToken"
|
||||
const signIn = (over = {}) => ({ type: "oauth", access: "old", refresh: "r1", expires: Date.now() + 5 * 60_000, method: "social",
|
||||
region: "us-east-1", profileArn: PROFILE, accountId: "me@example.com", ...over })
|
||||
|
||||
// kiro answers the refresh with the given status (and a new token when
|
||||
// 200), and every request to Kiro's API with a 500; it notes both.
|
||||
function kiro(status = 200, wait = 0) {
|
||||
const seen = { refreshes: [], sent: [] }
|
||||
globalThis.fetch = async (url, init) => {
|
||||
if (String(url) === REFRESH) {
|
||||
seen.refreshes.push(JSON.parse(init.body))
|
||||
if (wait) await new Promise((r) => setTimeout(r, wait))
|
||||
if (status !== 200) return new Response("{}", { status })
|
||||
return Response.json({ accessToken: "new", refreshToken: "r2", expiresIn: 3600 })
|
||||
}
|
||||
seen.sent.push(new Headers(init.headers).get("Authorization"))
|
||||
return new Response(JSON.stringify({ message: "boom" }), { status: 500 })
|
||||
}
|
||||
return seen
|
||||
}
|
||||
const hooksWith = async () => {
|
||||
const saves = []
|
||||
const hooks = await plugin({ client: { auth: { set: async (r) => void saves.push(r) } } })
|
||||
return { hooks, saves }
|
||||
}
|
||||
|
||||
test("magpie renews a sign-in ahead of its end; magpie saves what it gives", async () => {
|
||||
const seen = kiro()
|
||||
const { hooks, saves } = await hooksWith()
|
||||
expect(hooks.auth.refreshLead).toBeGreaterThanOrEqual(2 * 60_000)
|
||||
const got = await hooks.auth.refresh(signIn())
|
||||
expect(got).toEqual({ access: "new", refresh: "r2", expires: expect.any(Number) })
|
||||
expect(got.expires).toBeGreaterThan(Date.now() + 50 * 60_000)
|
||||
expect(seen.refreshes).toEqual([{ refreshToken: "r1" }])
|
||||
expect(saves).toEqual([])
|
||||
})
|
||||
|
||||
test("a request's refresh and magpie's renewal spend the refresh token once", async () => {
|
||||
const seen = kiro(200, 50)
|
||||
const { hooks } = await hooksWith()
|
||||
const stored = signIn({ expires: Date.now() - 1000 }) // the store keeps the old one throughout
|
||||
const l = await hooks.auth.loader(async () => stored)
|
||||
const ask = () => l.fetch("https://kiro.invalid/v1/messages", { method: "POST", body: JSON.stringify({ model: "auto", messages: [{ role: "user", content: "hi" }] }) })
|
||||
const [res, got] = await Promise.all([ask(), hooks.auth.refresh(stored)])
|
||||
expect(res.status).toBe(500)
|
||||
expect(got).toMatchObject({ access: "new", refresh: "r2" })
|
||||
expect(seen.refreshes.length).toBe(1)
|
||||
// the renewal not yet saved, a request goes on with its token
|
||||
await ask()
|
||||
expect(seen.refreshes.length).toBe(1)
|
||||
expect(seen.sent).toEqual(["Bearer new", "Bearer new"])
|
||||
// and asked again before magpie saved it, the same is given
|
||||
expect(await hooks.auth.refresh(stored)).toMatchObject({ access: "new", refresh: "r2" })
|
||||
expect(seen.refreshes.length).toBe(1)
|
||||
})
|
||||
|
||||
// as the built-in, a refusal doesn't mark the account lapsed either
|
||||
test("a refresh token Kiro refused is thrown plainly, the account not marked", async () => {
|
||||
for (const status of [400, 401, 403]) {
|
||||
kiro(status)
|
||||
const { hooks } = await hooksWith()
|
||||
const e = await hooks.auth.refresh(signIn()).catch((e) => e)
|
||||
expect(e.message).toBe("Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE")
|
||||
expect(e.signIn).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
test("any other failure is thrown plainly, to be tried again", async () => {
|
||||
kiro(503)
|
||||
let { hooks } = await hooksWith()
|
||||
let e = await hooks.auth.refresh(signIn()).catch((e) => e)
|
||||
expect(e.message).toBe("refreshing Kiro's sign-in: 503 Service Unavailable")
|
||||
expect(e.signIn).toBeUndefined()
|
||||
;({ hooks } = await hooksWith())
|
||||
globalThis.fetch = offline
|
||||
e = await hooks.auth.refresh(signIn()).catch((e) => e)
|
||||
expect(e.message).toBe("refreshing Kiro's sign-in: no network in tests")
|
||||
expect(e.signIn).toBeUndefined()
|
||||
})
|
||||
|
||||
test("nothing to renew with is nothing renewed", async () => {
|
||||
const seen = kiro()
|
||||
const { hooks } = await hooksWith()
|
||||
expect(await hooks.auth.refresh(signIn({ refresh: "" }))).toBeUndefined()
|
||||
expect(await hooks.auth.refresh({ type: "api", key: "ksk_x" })).toBeUndefined()
|
||||
// kiro-cli's and the IDE's sign-ins are their owners' to refresh
|
||||
expect(await hooks.auth.refresh({ type: "oauth", access: "", refresh: "", expires: 0, source: "kiro-cli" })).toBeUndefined()
|
||||
expect(await hooks.auth.refresh({ type: "oauth", access: "a", refresh: "r", expires: 1, source: "kiro-ide" })).toBeUndefined()
|
||||
expect(seen.refreshes).toEqual([])
|
||||
})
|
||||
Reference in New Issue
Block a user