diff --git a/README.en.md b/README.en.md index ef4fbfb..80f1cdf 100644 --- a/README.en.md +++ b/README.en.md @@ -265,6 +265,13 @@ and can't be renewed, or with one agy already failed on, agy is not run: the account shows its sign-in has expired until you sign in again. Other failed usage reads wait 10 minutes before the next try, doubling up to 6 hours. +On macOS, a Magpie run as a LaunchDaemon is outside your login session and +can't read your login keychain, and neither can agy there. An account of agy's +own then runs with the copy of its sign-in the Magpie window kept (see above); +one with no copy says why: run Magpie with `magpie daemon install` (a service of +your own) or the Magpie app instead, or sign it in with "Add another Google +account", which keeps its sign-in in a file. + ## Environment variables | Name | Default value | What it does | diff --git a/README.md b/README.md index 8661c8d..a51accd 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,11 @@ your location"),尽管它自己查的额度已经拿到了。这时插件按 登录已过期且无法续期、或 agy 已在这份登录上失败过时,不运行 agy,账号显示登录已过期,直到重新登录。 其他失败的额度查询等 10 分钟再试,每次翻倍,最长 6 小时。 +macOS 上,以 LaunchDaemon 方式运行的 Magpie 不在你的登录会话里,读不到登录钥匙串,agy 在那里也读不到。 +这时 agy 自己的账号用 Magpie 窗口为它复制的那份登录(见上文);没有复制的,账号会说明原因: +改用 `magpie daemon install`(以你自己的服务运行)或 Magpie 应用,或用“添加另一个 Google 账号”登录, +它的登录保存在文件里。 + ## 环境变量 | 变量 | 默认值 | 作用 | diff --git a/index.mjs b/index.mjs index 13ce658..72fc3d2 100644 --- a/index.mjs +++ b/index.mjs @@ -8038,9 +8038,11 @@ async function homeOfAuth(getAuth) { // can't tell, and its kept home (keptFor) while agy holds another. With // none kept, it is agy's own still, and is told agy holds another. // While agy holds it, it is kept again when agy's sign-in has changed. +// Out of this magpie's reach (a LaunchDaemon: signin.mjs), it runs in its +// kept home too, which the magpie that could read it (the window) wrote. function ownHome(email, stored) { if (!email) return null - if (heldByAnother(stored, email)) return keptFor(email) + if (heldByAnother(stored, email) || stored?.state === "unreachable") return keptFor(email) inAccount(null, () => keepOwn(email, stored)).catch(() => {}) return null } @@ -8068,6 +8070,9 @@ function readUsageOf(home, email = "") { if (email) { let stored = null try { stored = await storedSignIn() } catch {} + // out of reach: read with the sign-in kept for it, when there is one + const kept = stored?.state === "unreachable" ? keptFor(email) : null + if (kept) return readUsageOf(kept) if (heldByAnother(stored, email)) { // kept while agy held it: read with its own sign-in const kept = keptFor(email) @@ -8202,8 +8207,9 @@ export const AntigravityBridgePlugin = async () => { const stored = storedSignInNow() const notSignedIn = cannotSignIn(stored) if (notSignedIn) { - return jsonError(401, `${notSignedIn}: sign in again in magpie, or run \`agy\` in a terminal`, undefined, - { headers: { "X-Magpie-Sign-In": "expired" } }) + // out of reach, signing in again here mends nothing + const why = stored?.state === "unreachable" ? notSignedIn : `${notSignedIn}: sign in again in magpie, or run \`agy\` in a terminal` + return jsonError(401, why, undefined, { headers: { "X-Magpie-Sign-In": "expired" } }) } // an account of agy's own that agy no longer holds: its request // would go out as the account agy holds now diff --git a/package.json b/package.json index 6570ea9..cdc8ce0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.115", + "version": "0.1.116", "description": "Magpie/OpenCode model provider that connects your local agy CLI through the Agent Client Protocol (agy acp), so Antigravity subscription models run through the real CLI", "type": "module", "main": "./opencode.mjs", diff --git a/signin.mjs b/signin.mjs index 109057d..2e80991 100644 --- a/signin.mjs +++ b/signin.mjs @@ -1,6 +1,7 @@ import { execFile } from "node:child_process" import { createHash } from "node:crypto" import fs from "node:fs" +import os from "node:os" import path from "node:path" import { currentHome, homeOf, tokenFile } from "./account.mjs" @@ -221,7 +222,8 @@ export function emailOf(raw) { } // readStoredValue reads agy's keyring value on this computer: { raw }, or -// { state } when there is none ("missing") or it can't be read ("unknown"). +// { state } when there is none ("missing"), it can't be read ("unknown"), +// or this process can't reach the keychain it is in ("unreachable"). async function readStoredValue({ platform = process.platform, exec = run, env = process.env, home = currentHome() } = {}) { // an account with a home of its own (account.mjs): agy keeps its // sign-in in a file there, the same JSON @@ -238,10 +240,10 @@ async function readStoredValue({ platform = process.platform, exec = run, env = if (ENV_SIGN_INS.some((name) => env[name])) return { state: "unknown" } if (platform === "darwin") { const r = await exec("/usr/bin/security", ["find-generic-password", "-s", SERVICE, "-a", USER, "-w"]) + if (r.code === 0) return { raw: r.stdout } + if (await loginKeychainOutOfReach({ exec, env })) return { state: "unreachable" } // 44: errSecItemNotFound - if (r.code === 44) return { state: "missing" } - if (r.code !== 0) return { state: "unknown" } - return { raw: r.stdout } + return { state: r.code === 44 ? "missing" : "unknown" } } if (platform === "win32") { const r = await exec("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", WINDOWS_SCRIPT]) @@ -256,6 +258,32 @@ async function readStoredValue({ platform = process.platform, exec = run, env = return { state: "unknown" } } +// loginKeychainOutOfReach says this process runs outside the user's +// login session on macOS: their login keychain, where agy keeps its +// sign-in, is not among the keychains it searches. A LaunchDaemon run as +// the user (mayne_wong on X) searches only System.keychain, so the +// keyring read finds nothing (44) while the window, in the login session, +// finds agy signed in: the gateway answered "agy isn't signed in", and +// signing in again said it was. agy, run there, can't read it either. +// false when it can't tell. +async function loginKeychainOutOfReach({ exec, env }) { + const home = env.HOME || (env === process.env ? os.homedir() : "") + if (!home) return false + const dir = path.join(home, "Library", "Keychains") + if (!fs.existsSync(path.join(dir, "login.keychain-db")) && !fs.existsSync(path.join(dir, "login.keychain"))) return false + const r = await exec("/usr/bin/security", ["list-keychains"]) + if (r.code !== 0) return false + const searched = [...String(r.stdout ?? "").matchAll(/"([^"]+)"/g)].map((m) => m[1]) + return searched.length > 0 && !searched.some((k) => k.startsWith(dir + path.sep)) +} + +// OUT_OF_REACH is what an account of agy's own is told when its sign-in +// is out of reach (loginKeychainOutOfReach), with no copy kept in a file. +export const OUT_OF_REACH = "this magpie runs outside your macOS login session (as a LaunchDaemon), where your " + + "login keychain, which holds agy's sign-in, can't be read. Run magpie as your own service instead " + + "(`magpie daemon install`, or the magpie app), or sign the account in with \"Add another Google account\", " + + "which keeps its sign-in in a file this magpie can read" + // readStoredSignIn reads agy's stored sign-in on this computer. export async function readStoredSignIn({ now = Date.now(), ...opts } = {}) { const v = await readStoredValue(opts) @@ -315,6 +343,7 @@ const USERINFO_URL = "https://www.googleapis.com/oauth2/v2/userinfo" // Google sign-in, or "" when it may. export function cannotSignIn(s) { if (s?.state === "missing") return "agy isn't signed in" + if (s?.state === "unreachable") return OUT_OF_REACH if (s?.state === "present" && !s.canRenew && s.expired) return "agy's sign-in has expired" return "" } diff --git a/test/catalog.mjs b/test/catalog.mjs index 910a8ca..d6d7c07 100644 --- a/test/catalog.mjs +++ b/test/catalog.mjs @@ -263,6 +263,82 @@ test("an account of agy's own that agy held once reads its own usage, and sends } }) +// mayne_wong on X: magpie's gateway run as a LaunchDaemon searches only +// System.keychain, so agy's sign-in in the login keychain reads as none +// there (44) while the window reads it. An account of agy's own the window +// kept runs in its kept home there; one it never kept is told why, not to +// sign in again (which the window answered with "already signed in"). +test("out of the login keychain's reach (a LaunchDaemon), an account of agy's own runs with the sign-in the window kept", async () => { + const signIn = (email) => ({ + token: { access_token: "ya29." + email, refresh_token: "1//" + email, expiry: "0001-01-01T00:00:00Z" }, + auth_method: "consumer", id_token_email: email, + }) + const options = { + platform: "darwin", modelsBehavior: DYNAMIC_OK, + storedSignIn: "go-keyring-base64:" + Buffer.from(JSON.stringify(signIn("a@example.com"))).toString("base64") + "\n", + onSpawn: (_file, args) => args[0] === "--version" ? { code: 0, stdout: "1.5.12\n" } : 1, + } + const asked = [] + const realFetch = globalThis.fetch + globalThis.fetch = async (url, init) => { + asked.push(init.headers.Authorization) + const reply = /loadCodeAssist/.test(url) ? { cloudaicompanionProject: "p" } : { groups: [{ + displayName: "Gemini Models", description: "Models within this group: Gemini 4 Argon", + buckets: [{ bucketId: "w", displayName: "Weekly Limit Remaining", window: "weekly", resetTime: "2026-11-22T00:00:00Z", remainingFraction: 0.9 }], + }] } + return new Response(JSON.stringify(reply), { status: 200 }) + } + try { + await withKit(options, async (kit) => { + const a = { type: "oauth", key: "agy", metadata: { email: "a@example.com" } } + const b = { type: "oauth", key: "agy", metadata: { email: "b@example.com" } } + // the window, in the login session: a is read from the keyring, and kept + const first = await kit.plugin.auth.usage(async () => a, {}) + assert.equal(first.error, undefined, JSON.stringify(first)) + const accounts = path.join(kit.env.XDG_STATE_HOME, "magpie-agy-bridge", "accounts") + const keptHome = path.join(accounts, fs.readdirSync(accounts)[0]) + + // the gateway, as a LaunchDaemon: the login keychain is there, but not searched + fs.mkdirSync(path.join(kit.env.HOME, "Library", "Keychains"), { recursive: true }) + fs.writeFileSync(path.join(kit.env.HOME, "Library", "Keychains", "login.keychain-db"), "") + options.storedSignIn = "missing" + options.keychains = ' "/Library/Keychains/System.keychain"\n' + kit.clock.advance(60_000) + asked.length = 0 + const ua = await kit.plugin.auth.usage(async () => a, {}) + assert.equal(ua.error, undefined, JSON.stringify(ua)) + assert.equal(ua.windows.find(w => !w.model)?.used, 10) + assert.ok(asked.length > 0 && asked.every(h => h === "Bearer ya29.a@example.com"), asked.join()) + const la = await kit.plugin.auth.loader(async () => a) + const served = await la.fetch(MESSAGES_URL, { method: "POST", body: JSON.stringify(baseBody()) }) + assert.notEqual(served.status, 401, await served.clone().text()) + await served.text() + assert.ok(kit.acpSpawns.length > 0) + assert.ok(kit.acpSpawns.every(s => s.env.HOME === keptHome), "a's request ran outside its kept home") + + // b was never kept: told why, not to sign in again + const before = kit.acpSpawns.length + const lb = await kit.plugin.auth.loader(async () => b) + const refused = await lb.fetch(MESSAGES_URL, { method: "POST", body: JSON.stringify(baseBody()) }) + assert.equal(refused.status, 401) + const why = await refused.text() + assert.match(why, /LaunchDaemon/) + assert.match(why, /magpie daemon install/) + assert.doesNotMatch(why, /sign in again in magpie/) + assert.equal(kit.acpSpawns.length, before, "agy was run where it can't read its sign-in") + const ub = await kit.plugin.auth.usage(async () => b, {}) + assert.equal(ub.signIn, "expired") + assert.match(ub.error, /LaunchDaemon/) + assert.doesNotMatch(ub.error, /Sign in again/) + // the keychain was only read + assert.ok(kit.execFiles.every(c => c.file !== "/usr/bin/security" || ["find-generic-password", "list-keychains"].includes(c.args[0]))) + await settle(kit) + }) + } finally { + globalThis.fetch = realFetch + } +}) + // The first request after a start, before anything read agy's keyring, // isn't sent as the account agy holds either. test("an account of agy's own: the first request after a start waits for the keyring read", async () => { diff --git a/test/signin.mjs b/test/signin.mjs index 156e688..d244c4f 100644 --- a/test/signin.mjs +++ b/test/signin.mjs @@ -54,6 +54,35 @@ test("a value of another shape, or an API key, concludes nothing", () => { } }) +test("macOS: a login keychain this process doesn't search (a LaunchDaemon) is out of reach, not a missing sign-in", async () => { + const fs = await import("node:fs") + const os = await import("node:os") + const path = await import("node:path") + const home = fs.mkdtempSync(path.join(os.tmpdir(), "agy-kc-")) + try { + const dir = path.join(home, "Library", "Keychains") + const env = { HOME: home } + const mac = (find, list, listCode = 0) => async (_file, args) => args[0] === "list-keychains" ? { code: listCode, stdout: list } : { code: find, stdout: "" } + const system = ' "/Library/Keychains/System.keychain"\n' + const login = ` "${dir}/login.keychain-db"\n` + system + // no login keychain at all: nothing is out of reach + assert.equal((await readStoredSignIn({ platform: "darwin", exec: mac(44, system), env })).state, "missing") + fs.mkdirSync(dir, { recursive: true }) + fs.writeFileSync(path.join(dir, "login.keychain-db"), "") + assert.equal((await readStoredSignIn({ platform: "darwin", exec: mac(44, login), env })).state, "missing") + for (const code of [44, 36]) { + const s = await readStoredSignIn({ platform: "darwin", exec: mac(code, system), env }) + assert.equal(s.state, "unreachable", String(code)) + assert.match(cannotSignIn(s), /LaunchDaemon[\s\S]*magpie daemon install[\s\S]*Add another Google account/) + } + // a search list it can't read concludes nothing new + assert.equal((await readStoredSignIn({ platform: "darwin", exec: mac(44, "", 1), env })).state, "missing") + assert.equal((await readStoredSignIn({ platform: "darwin", exec: mac(51, ""), env })).state, "unknown") + } finally { + fs.rmSync(home, { recursive: true, force: true }) + } +}) + test("readStoredSignIn asks each system's keyring the way go-keyring stores it", async () => { const value = stored({ access_token: "a", refresh_token: "r", expiry: "2026-11-12T00:00:00Z" }) const calls = [] diff --git a/test/testkit.mjs b/test/testkit.mjs index 74a8edc..27f3620 100644 --- a/test/testkit.mjs +++ b/test/testkit.mjs @@ -597,6 +597,11 @@ export async function createBridgeKit(options = {}) { const execFile = (file, args = [], opts, callback) => { if (typeof opts === "function") callback = opts kit.execFiles.push({ file, args }) + // the keychains `security` searches (options.keychains, its output) + if (args[0] === "list-keychains" && options.keychains !== undefined) { + setImmediate(() => callback(null, options.keychains, "")) + return + } const stored = options.storedSignIn setImmediate(() => stored === "missing" || stored === undefined ? callback(Object.assign(new Error("not found (test)"), { code: 44 }), "", "") diff --git a/usage.mjs b/usage.mjs index dce8259..317b078 100644 --- a/usage.mjs +++ b/usage.mjs @@ -666,6 +666,8 @@ export function createUsageReader(resolveAgy, options = {}) { let stored try { stored = await signIn() } catch { stored = { state: "unknown" } } const why = cannotSignIn(stored) + // out of this process's reach, signing in again here mends nothing + if (why && stored?.state === "unreachable") return { windows: [], error: `${why}.`, signIn: "expired" } if (why) return expired(why) if (isDead(stored)) return expired("agy's sign-in no longer works") const key = stored?.state === "present" ? stored.fp : "unknown"