Files
plugins/packages/agy-cli/login.mjs
T
yetone ecab839688 agy-cli 0.1.1: sign in to Google from magpie, through agy's own agy acp --login
treeman_26897 (Discord #feedback, 11-08): Sign in on agy-cli opened no
browser, and asked for a field to paste the callback into.

Cause: the plugin had no sign-in of its own. Its one method only checked
whether `agy models` worked, and if not it said to run `agy` in a
terminal. magpie still showed "Finish signing in ... in your browser",
but nothing ever opened a page.

Now the method is oauth:
- Already signed in to agy (`agy models` lists models): done at once. No
  page opens and no agy login starts.
- Otherwise the plugin starts `agy acp --login` (agy 1.5 and later). That
  prints Google's link and reads the code from stdin. magpie opens the
  link on the user's machine and shows its code field (method "code").
  - The field takes the code antigravity.google/oauth-callback shows, or
    that page's whole address.
  - No loopback is involved, so it works with Remote magpie and in Docker.
- agy trades the code and keeps the token in its keyring. The plugin never
  sees the token.
- The account is saved only once `agy models` lists models afterwards. A
  wrong, empty or expired code fails, and nothing is saved. Google's
  invalid_grant is worded as "turned the code away".
- The link waits 15 minutes, then agy is stopped. A new sign-in stops the
  previous agy.
- agy 1.4.x has no --login. It gets "update with `agy update`, or run
  `agy` in a terminal".
- The login runs with auto-update off, like the plugin's other agy
  processes.

Import from a file is not added. agy keeps its credentials in the system
keyring, not in a file under ~/.gemini/antigravity-cli.

The empty account the report also describes was not reproduced on
current magpie. A failed sign-in saved nothing, in the GUI and the CLI.
This version also needs models listed before it saves anything.

Run:
- On mote (macOS, Bun 1.4.2) at this tree, `bun test` in packages/agy-cli:
  7 pass / 0 fail.
- `bun scripts/check.mjs` and `bun scripts/check.mjs agy-cli`: exit 0.
- New smoke checks, with the old index.mjs put back: red, at "signed in
  to agy already, the sign-in saves agy" (the old method has no callback).
- Real agy 1.5.3 on mote, sandbox HOME, current magpie `web`, through
  Playwright:
  - Providers > agy-cli opened Google's sign-in page, and the code field
    showed.
  - A bogus code gave "Sign-in didn't finish: Google turned the code
    away...". /api/providers had no agy row.
- `magpie plugin login agy-cli`:
  - With a bogus code, the same error.
  - With real agy 1.4.12, the update message.
- Real agy 1.5.3 on Windows 11 (win-run) and on Linux (WSL2 Ubuntu 24.04,
  wsl-run): authorize gave Google's link in about 2s, and a bogus code
  failed with the invalid_grant wording. No agy was left running.

Not tried:
- A real Google sign-in through to models. Only bogus codes were used, and
  no real account was touched.
- magpie inside a Docker container.

Reported-by: treeman_26897
2026-11-08 11:48:40 +08:00

130 lines
5.1 KiB
JavaScript

import os from "node:os"
import { spawnAgy } from "./platform.mjs"
// The Google sign-in, run by agy itself: `agy acp --login` (agy 1.5 and
// later, "ACP terminal auth") prints Google's sign-in link, then reads the
// code the page it lands on shows, or that page's whole address, from
// stdin. agy trades the code and keeps the token where it always does (the
// system keyring); the plugin never sees it. Nothing opens a browser here:
// magpie opens the link, on the machine the user is at, and takes the code
// in its own field, so this works with magpie on a server or in Docker too.
// How long the link waits for its code before agy is stopped. A sign-in
// magpie gives up on reaches no plugin hook, so this is what ends it.
export const LOGIN_WAIT_MS = 15 * 60 * 1000
// How long agy has to print the link, and to trade the code.
export const LOGIN_START_MS = 30_000
export const LOGIN_FINISH_MS = 60_000
const SIGN_IN_LINK = /https:\/\/accounts\.google\.com\/[^\s"'<>]+/
let pending = null
// lastLine is the last thing agy said, for an error.
function lastLine(text) {
const lines = String(text).split(/\r?\n/).map(line => line.trim()).filter(Boolean)
return lines.at(-1) ?? ""
}
function stop(child) {
try { child.stdin?.end() } catch {}
try { child.kill() } catch {}
}
// startLogin starts agy's sign-in and resolves with its link, or with why
// it couldn't start. A second sign-in ends the first's agy.
export function startLogin(agy, { waitMs = LOGIN_WAIT_MS, startMs = LOGIN_START_MS } = {}) {
if (pending) {
stop(pending)
pending = null
}
return new Promise((resolve) => {
let child
try {
child = spawnAgy(agy, ["acp", "--login"], { cwd: os.tmpdir(), stdio: ["pipe", "pipe", "pipe"] })
} catch (err) {
resolve({ error: `couldn't run agy: ${err.message}` })
return
}
pending = child
let out = ""
let settled = false
let exited = null
const waiters = []
const settle = (value) => {
if (settled) return
settled = true
clearTimeout(startTimer)
resolve(value)
}
const startTimer = setTimeout(() => {
stop(child)
settle({ error: `agy didn't print a sign-in link within ${Math.round(startMs / 1000)}s${lastLine(out) ? ` (${lastLine(out)})` : ""}` })
}, startMs)
const waitTimer = setTimeout(() => stop(child), waitMs)
waitTimer.unref?.()
const read = (data) => {
out += data
const link = SIGN_IN_LINK.exec(out)?.[0]
if (link) settle({ url: link, finish })
}
child.stdout?.setEncoding("utf8")
child.stderr?.setEncoding("utf8")
child.stdout?.on("data", read)
child.stderr?.on("data", read)
child.stdin?.on("error", () => {})
child.on("error", (err) => {
exited = { code: null, err }
for (const w of waiters.splice(0)) w()
settle({ error: `couldn't run agy: ${err.message}` })
})
child.on("close", (code) => {
clearTimeout(waitTimer)
if (pending === child) pending = null
exited = exited ?? { code }
for (const w of waiters.splice(0)) w()
// agy before 1.5 has no --login: it prints acp's usage and exits
if (/Usage:/.test(out) && !SIGN_IN_LINK.test(out)) {
settle({ error: "this agy can't sign in from magpie (it has no `agy acp --login`). Update it with `agy update`, or run `agy` in a terminal once to sign in, then try again." })
}
settle({ error: `agy exited before printing a sign-in link${lastLine(out) ? `: ${lastLine(out)}` : ""}` })
})
// finish hands agy the code (or the page's address) and waits for it
// to trade it. It says why when the sign-in didn't take.
async function finish(code, { signal, finishMs = LOGIN_FINISH_MS } = {}) {
const value = String(code ?? "").trim()
if (!value || /[\r\n]/.test(value)) {
stop(child)
return { error: "paste the code the sign-in page shows" }
}
if (exited) {
return { error: "this sign-in is over (its link waits 15 minutes); start it again" }
}
const before = out.length
const done = new Promise((resolve) => waiters.push(resolve))
let timer
const late = new Promise((resolve) => { timer = setTimeout(() => resolve("late"), finishMs) })
const onAbort = () => stop(child)
signal?.addEventListener?.("abort", onAbort, { once: true })
try {
child.stdin.write(value + "\n")
const how = await Promise.race([done, late])
if (how === "late") {
stop(child)
return { error: `agy didn't finish the sign-in within ${Math.round(finishMs / 1000)}s` }
}
} finally {
clearTimeout(timer)
signal?.removeEventListener?.("abort", onAbort)
}
if (exited.code === 0) return { ok: true, said: lastLine(out.slice(before)) }
const said = lastLine(out.slice(before)) || lastLine(out)
if (/invalid_grant/.test(said)) {
return { error: `Google turned the code away: it was mistyped, used already, or from another sign-in page. Start the sign-in again. (${said})` }
}
return { error: said || `agy exited with code ${exited.code}` }
}
})
}