diff --git a/packages/zed/index.mjs b/packages/zed/index.mjs index 36c7978..3d70201 100644 --- a/packages/zed/index.mjs +++ b/packages/zed/index.mjs @@ -146,14 +146,14 @@ const stale = (status, headers) => status === 401 || !!headers.get("x-zed-expire // ---- the account -------------------------------------------------------------- // cloud sends one /client/* request with the account's pair. -async function cloud(method, path, s, body) { +async function cloud(method, path, s, body, timeout = 20_000) { const headers = { Authorization: `${s.userId} ${s.access}`, "Content-Type": "application/json", "User-Agent": userAgent() } if (s.systemId) headers["x-zed-system-id"] = s.systemId const res = await fetch(CLOUD + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), - signal: AbortSignal.timeout(20_000), + signal: AbortSignal.timeout(timeout), }) const text = await res.text() if (!res.ok) throw new ZedStatus(res.status, text, res.headers) @@ -755,9 +755,41 @@ async function complete(s, url, init) { return stream ? streamed(w.wire, res) : whole(w.wire, res) } +// ---- usage ---------------------------------------------------------------------------- + +// usage is what the account says of its plan, as magpie's built-in Zed +// account shows it (zed_usage.go): Zed tells its editor the plan and its +// billing period, not how much of the allowance is spent, so there are no +// windows — the plan's name, when the period ends, and a plan Zed won't +// serve (overdue invoices) as the error it is. +const RFC3339 = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|[+-]\d\d:\d\d)$/i + +async function usage(auth, save) { + const s = stateOf(auth) + if (!s) return { error: "no such Zed account" } + let me + try { + me = parse(await cloud("GET", "/client/users/me", s, undefined, 15_000)) ?? {} + } catch (e) { + if (e?.status === 401) return { error: `${s.who}: the Zed sign-in has expired — sign in again` } + return { error: e?.message ?? String(e) } + } + const plan = planOf(me, s.org || orgOf(me)) + const out = { plan: planName(plan) } + if (plan !== s.plan && save) { + const r = parse(auth.refresh ?? "") ?? {} + await save({ ...auth, refresh: JSON.stringify({ ...r, plan, planName: out.plan }) }).catch(() => {}) + } + const end = me.plan?.subscription_period?.ended_at + if (typeof end === "string" && RFC3339.test(end) && !isNaN(Date.parse(end))) out.until = end + if (me.plan?.has_overdue_invoices) out.error = "Zed: this account has an overdue invoice, so its models are paused (see zed.dev/account)" + else if (plan === "zed_free" || plan === "") out.plan = "No plan" + return out +} + // ---- the plugin --------------------------------------------------------------------- -export async function ZedAuthPlugin() { +export async function ZedAuthPlugin({ client } = {}) { return { config: async (cfg) => { cfg.provider ??= {} @@ -805,9 +837,14 @@ export async function ZedAuthPlugin() { }, } }, + // magpie's own hook: the account's plan and its period + async usage(getAuth) { + const save = client?.auth?.set ? (body) => client.auth.set({ path: { id: PROVIDER }, body }) : null + return usage(await getAuth(), save) + }, }, } } // for tests -export const _internal = { stateOf, parseModels, providerRequest, wireOf, refusal, failedStatus, decrypt, padded, signedInWith, complete, vendors, tokens, lists, orgOf, who, planName } +export const _internal = { stateOf, parseModels, providerRequest, wireOf, refusal, failedStatus, decrypt, padded, signedInWith, complete, vendors, tokens, lists, orgOf, who, planName, usage } diff --git a/packages/zed/package.json b/packages/zed/package.json index bce6e0b..fecc9f7 100644 --- a/packages/zed/package.json +++ b/packages/zed/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zed-auth", - "version": "0.1.0", + "version": "0.1.1", "description": "Sign in to a Zed subscription (Zed Pro, trial, student, business) from OpenCode or magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/zed/usage.test.mjs b/packages/zed/usage.test.mjs new file mode 100644 index 0000000..327a470 --- /dev/null +++ b/packages/zed/usage.test.mjs @@ -0,0 +1,73 @@ +// auth.usage tells what magpie's built-in Zed account shows +// (internal/provider/zed_usage.go), against Zed's replies as its tests +// give them (zed_test.go). +import { afterEach, expect, test } from "bun:test" +import { ZedAuthPlugin } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const me = (plan, overdue = false) => + JSON.stringify({ + user: { legacy_user_id: 4242, github_login: "octo", name: "Octo Cat" }, + organizations: [{ id: "org-team", name: "Team" }, { id: "org-me", name: "Me", is_personal: true }], + default_organization_id: "org-me", + plans_by_organization: { "org-me": plan }, + plan: { plan_v3: plan, subscription_period: { started_at: "2026-09-01T00:00:00Z", ended_at: "2026-10-01T00:00:00Z" }, has_overdue_invoices: overdue }, + }) + +const auth = (plan = "zed_pro") => ({ + type: "oauth", + access: "plain-access", + refresh: JSON.stringify({ userId: "4242", systemId: "", org: "org-me", plan, planName: "Pro" }), + expires: 0, + accountId: "octo", +}) + +async function run(a, reply) { + const seen = [] + const saved = [] + globalThis.fetch = async (url, init) => { + seen.push({ url: String(url), auth: init.headers.Authorization }) + return reply() + } + const client = { auth: { set: async (x) => saved.push(x) } } + const hooks = await ZedAuthPlugin({ client }) + return { u: await hooks.auth.usage(async () => a), seen, saved } +} + +test("a Pro account: its plan and its period's end, no windows", async () => { + const { u, seen, saved } = await run(auth(), () => new Response(me("zed_pro"))) + expect(u).toEqual({ plan: "Pro", until: "2026-10-01T00:00:00Z" }) + expect(seen).toEqual([{ url: "https://cloud.zed.dev/client/users/me", auth: "4242 plain-access" }]) + expect(saved).toEqual([]) +}) + +test("a free account reads No plan, and the plan it moved to is kept", async () => { + const { u, saved } = await run(auth(), () => new Response(me("zed_free"))) + expect(u).toEqual({ plan: "No plan", until: "2026-10-01T00:00:00Z" }) + expect(saved.length).toBe(1) + expect(JSON.parse(saved[0].body.refresh)).toMatchObject({ plan: "zed_free", planName: "Free" }) +}) + +test("an overdue invoice is the error it is", async () => { + const { u } = await run(auth(), () => new Response(me("zed_pro", true))) + expect(u).toEqual({ plan: "Pro", until: "2026-10-01T00:00:00Z", error: "Zed: this account has an overdue invoice, so its models are paused (see zed.dev/account)" }) +}) + +test("a refused pair says the sign-in expired", async () => { + const { u } = await run(auth(), () => new Response("", { status: 401 })) + expect(u).toEqual({ error: "octo: the Zed sign-in has expired — sign in again" }) +}) + +test("another failure says Zed's message", async () => { + const { u } = await run(auth(), () => new Response(JSON.stringify({ code: "x", message: "down for a bit" }), { status: 503 })) + expect(u).toEqual({ error: "Zed: down for a bit (503)" }) +}) + +test("a business plan picked by organization", async () => { + const body = JSON.parse(me("zed_free")) + body.plans_by_organization["org-me"] = "zed_business" + const { u } = await run(auth("zed_business"), () => new Response(JSON.stringify(body))) + expect(u.plan).toBe("Business") +})