factory 0.1.11: magpie renews the sign-in ahead of time through auth.refresh

auth.refresh with refreshLead 3 minutes (in-fetch: 2). It renews under
the lock the request path and mendOrg already share, asks whoami again as
droid does, and gives the tokens and org fields. A renewed map (spent
refresh token → what it gave) lets a request that read the old sign-in
before magpie saved go on with the new one, and keeps rotated tokens when a
save fails. WorkOS refusing the refresh token is signIn "expired" (as the
request path's lapse already was); 429 and 5xx throw and are retried.

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:
yetone
2026-10-03 12:07:22 +08:00
parent c64f555ebd
commit 9b434a5ed3
4 changed files with 209 additions and 9 deletions
+12 -3
View File
@@ -29,9 +29,18 @@ The sign-in is kept wherever the host keeps provider sign-ins:
It holds WorkOS's access and refresh tokens, with the organization,
region and host.
**Refreshing.** The access token is renewed two minutes before it lapses.
WorkOS rotates the refresh token, so the plugin never runs two refreshes
at once.
**Refreshing.**
- magpie renews the access token three minutes before it lapses, through
the plugin's `auth.refresh`, once for the account and before its
requests and usage need it; magpie saves the new tokens. OpenCode
doesn't call that hook: there the token is renewed two minutes before it
lapses, before a request, and the plugin saves it.
- WorkOS rotates the refresh token, so the plugin never runs two refreshes
at once, and never spends one refresh token twice: a request that comes
before magpie has saved a renewal goes on with the new tokens.
- The account counts as signed out only when WorkOS refuses the refresh
token (a 4xx other than 429). Any other failure keeps the sign-in, and
the current token is used while it lasts.
**Refusals.** If Factory refuses the organization a request names, the
plugin asks `whoami` again and resends the request once. If the refusal
+72 -5
View File
@@ -16,6 +16,10 @@ const CLIENT_ID = "client_01HNM792M5G5G1A2THWPXKFMXB"
const VERSION = "0.231.0"
// how long before an access token lapses it is renewed (droid: a minute)
const REFRESH_LEAD = 2 * 60 * 1000
// and how long before, magpie renews it ahead of time (auth.refresh): a
// minute more, so under magpie the check before a request finds it fresh.
// WorkOS's access tokens are short-lived, so not much more
const MAGPIE_LEAD = 3 * 60 * 1000
// how long an account whose whoami failed waits before asking again
const ASK_AGAIN = 10 * 60 * 1000
@@ -757,6 +761,24 @@ export const FactoryAuthPlugin = async ({ client }) => {
lock = run.catch(() => {})
return run
}
// renewed is what each refresh this process ran gave, by the refresh
// token it spent: a sign-in still holding that one (magpie not yet
// saving what auth.refresh gave, or a save that failed) goes on with
// the new tokens rather than spending the old one again
const renewed = new Map()
const took = (spent, c) => {
for (const [k, v] of renewed) if (v.expires > 0 && Date.now() >= v.expires) renewed.delete(k)
renewed.set(spent, { access: c.access, refresh: c.refresh, expires: c.expires, orgId: c.orgId, activeOrganizationId: c.activeOrganizationId, region: c.region, premBaseHost: c.premBaseHost })
}
// latest is c with the newest tokens this process got for it
const latest = (c) => {
for (let i = 0; i < 16 && c.refresh; i++) {
const got = renewed.get(c.refresh)
if (!got || got.access === c.access || (c.expires > 0 && got.expires > 0 && got.expires <= c.expires)) break
c = { ...c, ...got }
}
return c
}
// when each account last asked whoami for its org, so one whoami can't
// answer doesn't ask before every request, nor hold back the others
const asked = new Map()
@@ -819,16 +841,17 @@ export const FactoryAuthPlugin = async ({ client }) => {
// it was, the built-in's clearing of the account's lapse.
const fresh = (renewed) =>
locked(async () => {
const c = await current()
const c = latest(await current())
if (c.key) return keyed(c) // an API key: nothing to renew, and no org with it
if ((c.expires > 0 && Date.now() < c.expires - REFRESH_LEAD) || !c.refresh) return orgOf(c)
const spent = c.refresh
let t
try {
t = await renew(c.refresh, "")
t = await renew(spent, "")
} catch (e) {
// a hiccup while the token still runs: go on with it
if (!refused(e) && c.expires > 0 && Date.now() < c.expires) return orgOf(c)
if (refused(e)) throw Object.assign(new Error(`${c.accountId || "the account"}'s Factory sign-in has expired — sign in again (${e.message})`), { lapsed: true })
if (refused(e)) throw lapsed(c, e)
throw e
}
c.access = t.access_token
@@ -837,6 +860,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
// droid asks whoami again for each new token, keeping the org it names
await reconcile(c)
ask(c)
took(spent, c)
await save(c)
renewed?.()
return c
@@ -852,7 +876,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
locked(async () => {
if (status !== 403) return false
const isOrg = orgRefused(status, text)
const c = await current()
const c = latest(await current())
if (c.key) return false // an API key carries no org droid would send
if (c.activeOrganizationId) {
if (!isOrg) return false // the org was sent: the refusal is about something else
@@ -877,9 +901,10 @@ export const FactoryAuthPlugin = async ({ client }) => {
org = await firstOrg(c)
} catch {}
if (!org) return false
const spent = c.refresh
let t
try {
t = await renew(c.refresh, org)
t = await renew(spent, org)
} catch {
return false
}
@@ -887,6 +912,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
c.expires = expiry(t.access_token)
c.orgId = org
if (t.refresh_token) c.refresh = t.refresh_token
took(spent, c)
await save(c)
renewed?.()
return true
@@ -928,6 +954,18 @@ export const FactoryAuthPlugin = async ({ client }) => {
return { fresh, mendOrg, usage }
}
// lapsed is WorkOS refusing c's refresh token for good: the account
// needs signing in again
const lapsed = (c, e) =>
Object.assign(new Error(`${c.accountId || "the account"}'s Factory sign-in has expired — sign in again (${e.message})`), { lapsed: true, signIn: "expired" })
// renewal is what of c magpie keeps over the stored sign-in
const renewal = (c) => {
const out = { access: c.access, refresh: c.refresh, expires: c.expires }
for (const k of ["orgId", "activeOrganizationId", "region", "premBaseHost"]) if (typeof c[k] === "string") out[k] = c[k]
return out
}
return {
config: async (config) => {
config.provider ??= {}
@@ -951,6 +989,35 @@ export const FactoryAuthPlugin = async ({ client }) => {
// droid's FACTORY_API_KEY: the key is the bearer, never renewed
{ type: "api", label: "Factory API key (fk-…)", placeholder: "fk-…" },
],
// magpie renews the sign-in MAGPIE_LEAD before its end, before its
// requests and usage ask for it, and saves what this gives. Under
// the same lock as the renewal before a request, so the two never
// spend one refresh token; that check stays for OpenCode, which
// doesn't call this
refreshLead: MAGPIE_LEAD,
async refresh(auth) {
if (auth?.type !== "oauth" || !auth.access || !auth.refresh) return undefined
return locked(async () => {
const c = latest({ ...auth })
// renewed here already, the store not yet saying so
if (c.access !== auth.access && c.expires > 0 && Date.now() < c.expires - MAGPIE_LEAD) return renewal(c)
const spent = c.refresh
let t
try {
t = await renew(spent, "")
} catch (e) {
if (refused(e)) throw lapsed(c, e)
throw e
}
c.access = t.access_token
c.expires = expiry(t.access_token)
if (t.refresh_token) c.refresh = t.refresh_token
await reconcile(c)
ask(c)
took(spent, c)
return renewal(c)
})
},
// magpie's own hook: the account's limits
async usage(getAuth) {
return account(getAuth).usage()
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-factory-auth",
"version": "0.1.10",
"version": "0.1.11",
"description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
"type": "module",
"main": "./index.mjs",
+124
View File
@@ -0,0 +1,124 @@
// magpie's auth.refresh: the sign-in renewed ahead of its end, magpie
// saving what the hook gives. WorkOS rotates the refresh token, so the hook
// and the renewal before a request never spend one twice.
import { afterEach, expect, test } from "bun:test"
import { FactoryAuthPlugin } from "./index.mjs"
const real = globalThis.fetch
afterEach(() => (globalThis.fetch = real))
const jwt = (exp) => "h." + Buffer.from(JSON.stringify({ exp: Math.floor(exp / 1000) })).toString("base64url") + ".s"
const later = Date.now() + 3_600_000
const NEW = jwt(later)
const due = () => ({
type: "oauth",
access: "tok-old",
refresh: "r-old",
expires: Date.now() + 60_000,
accountId: "ada",
activeOrganizationId: "fac_A",
region: "",
premBaseHost: "",
})
// fake WorkOS and Factory: authenticate answers with auth (a Response, or
// the new pair), slowly enough for another caller to come meanwhile
function serve(auth = () => new Response(JSON.stringify({ access_token: NEW, refresh_token: "r-new" }))) {
const seen = []
globalThis.fetch = async (url, init) => {
const u = new URL(String(url))
seen.push({ path: u.pathname, body: String(init?.body ?? "") })
if (u.pathname.endsWith("/authenticate")) {
await new Promise((r) => setTimeout(r, 20))
return auth()
}
if (u.pathname.endsWith("/whoami")) return new Response(JSON.stringify({ orgId: "fac_A", region: "" }))
return new Response("{}", { status: 200 })
}
return seen
}
async function plugin(stored) {
let auth = stored
const sets = []
const client = { auth: { set: async ({ body }) => (sets.push(body), (auth = body)) } }
const hooks = await FactoryAuthPlugin({ client })
return { hooks, sets, getAuth: async () => auth, now: () => auth }
}
const renewals = (seen) => seen.filter((s) => s.path.endsWith("/authenticate"))
test("renews a sign-in near its end, giving magpie the new tokens to save", async () => {
const seen = serve()
const { hooks, sets } = await plugin(due())
expect(hooks.auth.refreshLead).toBe(3 * 60 * 1000)
const got = await hooks.auth.refresh(due(), "factory")
expect(got).toMatchObject({ access: NEW, refresh: "r-new", expires: Math.floor(later / 1000) * 1000, activeOrganizationId: "fac_A" })
expect(got.type).toBeUndefined()
expect(sets).toEqual([]) // magpie saves it, not the hook
expect(renewals(seen).length).toBe(1)
expect(renewals(seen)[0].body).toContain("refresh_token=r-old")
})
test("a request's renewal and magpie's share one refresh", async () => {
const seen = serve()
const { hooks, getAuth, now } = await plugin(due())
const l = await hooks.auth.loader(getAuth)
const [res, got] = await Promise.all([
l.fetch("https://api.factory.ai/api/llm/o/v1/responses", { method: "POST", body: "{}" }),
hooks.auth.refresh(due(), "factory"),
])
expect(res.status).toBe(200)
expect(renewals(seen).length).toBe(1)
expect(got).toMatchObject({ access: NEW, refresh: "r-new" })
expect(now().access).toBe(NEW)
})
test("a request after magpie's renewal, not yet saved, doesn't spend the old refresh token", async () => {
const seen = serve()
const { hooks, getAuth } = await plugin(due())
const got = await hooks.auth.refresh(due(), "factory")
expect(got.access).toBe(NEW)
// the store still holds the old pair
const l = await hooks.auth.loader(getAuth)
const res = await l.fetch("https://api.factory.ai/api/llm/o/v1/responses", { method: "POST", body: "{}" })
expect(res.status).toBe(200)
expect(renewals(seen).length).toBe(1)
const sent = seen.find((s) => s.path.endsWith("/responses"))
expect(sent).toBeDefined()
// and asked again with the old sign-in, it gives what it got
expect(await hooks.auth.refresh(due(), "factory")).toMatchObject({ access: NEW, refresh: "r-new" })
expect(renewals(seen).length).toBe(1)
})
test("a refresh token WorkOS refuses is a sign-in expired", async () => {
serve(() => new Response(JSON.stringify({ error: "invalid_grant" }), { status: 400 }))
const { hooks, sets } = await plugin(due())
const e = await hooks.auth.refresh(due(), "factory").catch((e) => e)
expect(e).toBeInstanceOf(Error)
expect(e.signIn).toBe("expired")
expect(e.message).toContain("ada's Factory sign-in has expired")
expect(sets).toEqual([])
})
test("a passing failure throws plainly, for magpie to try again", async () => {
serve(() => new Response("busy", { status: 503 }))
const { hooks } = await plugin(due())
const e = await hooks.auth.refresh(due(), "factory").catch((e) => e)
expect(e).toBeInstanceOf(Error)
expect(e.signIn).toBeUndefined()
// and so does a rate limit
serve(() => new Response(JSON.stringify({ error: "rate_limited" }), { status: 429 }))
const r = await hooks.auth.refresh(due(), "factory").catch((e) => e)
expect(r).toBeInstanceOf(Error)
expect(r.signIn).toBeUndefined()
})
test("nothing to renew: no refresh token, or an API key", async () => {
const seen = serve()
const { hooks } = await plugin(due())
expect(await hooks.auth.refresh({ ...due(), refresh: "" }, "factory")).toBeUndefined()
expect(await hooks.auth.refresh({ type: "api", key: "fk-abcdefghij" }, "factory")).toBeUndefined()
expect(seen).toEqual([])
})