Files
yetone 38594b5aee gemini-web 0.1.0: the Gemini web app, one streamed call to its own endpoint per request
@jtbbtnt54249 on X (11-18) asked for a Gemini web plugin: the community
@dorokuma/magpie-gemini-web is "太慢了根本用不了". The MCP in their
screenshot is a Gemini web "custom app" remote connector: Google's servers
call a public MCP URL, so it can't serve a local agent and is not a route.

Why the existing one is slow: it goes through a separate local Go backend
that fetches the XSRF token before every request, uploads prompts over
128KB as a file, sleeps 2s between retries, and holds replies behind a
tool-fence gate and a slot limiter.

This package calls gemini.google.com the way the app's page does:
- the page's tokens (SNlM0e, cfb2h, FdrFJe) are read from /app once and
  kept 15 minutes;
- each request is one POST to StreamGenerate, the whole request inline in
  a temporary chat (slot 45, nothing kept in history), read as it
  streams and given back as SSE or a whole completion;
- tools are asked for as <tool_call> text (prompt.mjs and openai.mjs from
  doubao-work) and given back as tool_calls;
- signed in: a Chrome profile of the plugin's own opens at Google's
  sign-in, the user signs in themselves, the google.com cookies are read
  with Storage.getCookies on the browser target (nothing attached to the
  page) and the window closes. Set-Cookie renewals are saved back with
  client.auth.set; RotateCookies every ten minutes; signed out, rotate,
  then reopen the profile headless, then ask for a sign-in;
- a visitor (no account) gets Google's visitor model;
- models from the account's own picker (otAQ7b), fallback marked;
- prompts over 600K characters get 413 before they are sent (measured:
  315K fine, 900K ignored the request, 1.8M refused with error 3); error 3
  is named as a refusal with its likely causes.

Run:
- HOME=$(mktemp -d) bun test packages/gemini-web on mote: 28 pass. The
  fixtures are real StreamGenerate replies (a signed-in "pong" served as
  4 Hydrogen, a visitor's rivers text with its real chunks) and a real
  otAQ7b list, with the location Google guessed scrubbed.
- Broken by hand: not sending `at` turns two tests red.
- Full suite on mote, HOME=$(mktemp -d) bun test at ea805ecc plus this change (before the root README line): 9091 pass, 20 skip, 0 fail.
- bun scripts/check.mjs: registry.json and gemini-web ok.
- Real, through the plugin's fetch from Bun on mote, as a visitor: three
  "pong" requests, first text at 14.0s (reads the page), 7.9s, 6.9s; a
  tool request came back as Echo {"text":"391"} with finish tool_calls.
  Signed in, in the app's own page: first text about 3.5s.

Not tried: a real Google sign-in through the plugin's window (Google may
refuse a browser with a DevTools port open), whether DBSC stops
RotateCookies, thinking output, paid models (4 Carbon, 4 Neon). Said in
the README.

First publish of a new package: publish.yml can't publish it (no trusted
publisher yet), so magpie installs it from the dist branch until the
owner publishes it once and adds the trust.
2026-11-19 14:14:50 +08:00

207 lines
7.9 KiB
JavaScript

// Sign-in through a browser window of the plugin's own: Chrome (or Edge,
// Chromium, Brave) with a private profile, opened at Google's sign-in page.
// The user signs in there themselves; the plugin never sees a password.
// It reads the profile's google.com cookies through the browser's own
// DevTools endpoint (Storage.getCookies on the browser target: nothing is
// attached to the page the user types into) and closes the window. The
// profile is kept: when the cookies stop working, the same profile is
// opened again without a window and the browser renews them itself.
import { spawn } from "node:child_process"
import { chmodSync, existsSync, mkdirSync } from "node:fs"
import { createServer } from "node:net"
import { tmpdir } from "node:os"
import { join } from "node:path"
export const SIGN_IN = "https://accounts.google.com/ServiceLogin?continue=" + encodeURIComponent("https://gemini.google.com/app")
const GEMINI = "https://gemini.google.com/app"
const NEED = ["__Secure-1PSID", "__Secure-1PSIDTS"]
export function profileRoot(env = process.env, platform = process.platform) {
if (env.GEMINI_WEB_PROFILE) return env.GEMINI_WEB_PROFILE
if (platform === "win32") return join(env.LOCALAPPDATA || env.APPDATA || tmpdir(), "magpie", "gemini-web-browser")
return join(env.XDG_CONFIG_HOME || join(env.HOME || tmpdir(), ".config"), "magpie", "gemini-web-browser")
}
export function findBrowser(platform = process.platform, env = process.env) {
if (env.GEMINI_WEB_BROWSER && existsSync(env.GEMINI_WEB_BROWSER)) return env.GEMINI_WEB_BROWSER
const home = env.HOME || ""
const candidates =
platform === "darwin"
? [
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
"/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
]
: platform === "win32"
? [
join(env.PROGRAMFILES || "", "Google/Chrome/Application/chrome.exe"),
join(env["PROGRAMFILES(X86)"] || "", "Google/Chrome/Application/chrome.exe"),
join(env.LOCALAPPDATA || "", "Google/Chrome/Application/chrome.exe"),
join(env.PROGRAMFILES || "", "Microsoft/Edge/Application/msedge.exe"),
join(env["PROGRAMFILES(X86)"] || "", "Microsoft/Edge/Application/msedge.exe"),
]
: ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium", "/usr/bin/chromium-browser", "/snap/bin/chromium", "/usr/bin/microsoft-edge"]
return candidates.find((p) => p && existsSync(p)) ?? ""
}
export function browserArgs(profile, port, url, { headless = false } = {}) {
return [
`--user-data-dir=${profile}`,
`--remote-debugging-port=${port}`,
"--remote-debugging-address=127.0.0.1",
"--no-first-run",
"--no-default-browser-check",
"--disable-sync",
"--disable-default-apps",
"--disable-background-mode",
...(headless ? ["--headless=new"] : ["--new-window"]),
url,
]
}
function freePort() {
return new Promise((resolve, reject) => {
const s = createServer()
s.on("error", reject)
s.listen(0, "127.0.0.1", () => {
const { port } = s.address()
s.close(() => resolve(port))
})
})
}
// cdp sends one command to the browser target and answers its result
async function cdp(port, method, params = {}, timeout = 3000) {
const v = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1500) }).then((r) => r.json())
const url = v?.webSocketDebuggerUrl
if (!url) throw new Error("no DevTools endpoint")
return await new Promise((resolve, reject) => {
const ws = new WebSocket(url)
const timer = setTimeout(() => {
try { ws.close() } catch {}
reject(new Error("DevTools timed out"))
}, timeout)
ws.onopen = () => ws.send(JSON.stringify({ id: 1, method, params }))
ws.onerror = () => {
clearTimeout(timer)
reject(new Error("DevTools connection failed"))
}
ws.onmessage = (ev) => {
let m
try { m = JSON.parse(String(ev.data)) } catch { return }
if (m.id !== 1) return
clearTimeout(timer)
try { ws.close() } catch {}
if (m.error) reject(new Error(m.error.message || method + " failed"))
else resolve(m.result)
}
})
}
// googleCookies keeps the cookies a request to gemini.google.com carries
export function googleCookies(list) {
const out = {}
for (const c of list ?? []) {
const d = String(c?.domain ?? "").replace(/^\./, "")
if (d !== "google.com" && d !== "gemini.google.com") continue
if ((c.path ?? "/") !== "/") continue
if (typeof c.name === "string" && typeof c.value === "string") out[c.name] = c.value
}
return out
}
const hasSession = (cookies) => NEED.every((n) => cookies[n])
function waitExit(child, ms) {
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve()
return new Promise((r) => {
const t = setTimeout(r, ms)
child.once("exit", () => {
clearTimeout(t)
r()
})
})
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
// open starts the browser on profile and answers a handle that reads its
// cookies and closes it
export async function open(profile, url, { headless = false, browser = findBrowser() } = {}) {
if (!browser) throw Object.assign(new Error("没有找到 Chrome、Edge、Chromium 或 Brave。请先安装 Chrome,或用 GEMINI_WEB_BROWSER 指定浏览器。"), { code: "browser_missing" })
mkdirSync(profile, { recursive: true, mode: 0o700 })
try { chmodSync(profile, 0o700) } catch {}
const port = await freePort()
const child = spawn(browser, browserArgs(profile, port, url, { headless }), { stdio: "ignore", detached: false })
let exited = false
child.once("error", () => (exited = true))
child.once("exit", () => (exited = true))
return {
get exited() {
return exited
},
async cookies() {
const r = await cdp(port, "Storage.getCookies")
return googleCookies(r?.cookies)
},
async close() {
if (!exited) {
try { child.kill("SIGTERM") } catch {}
await waitExit(child, 2000)
}
if (!exited) {
try { child.kill("SIGKILL") } catch {}
await waitExit(child, 1000)
}
},
}
}
// signIn opens the window and waits (up to timeout) for the user to sign
// in, then answers the cookies. It answers null when the window was
// closed or the time ran out.
export async function signIn(profile, { timeout = 5 * 60_000, poll = 1000, settle = 2500, opener = open } = {}) {
const b = await opener(profile, SIGN_IN)
try {
const end = Date.now() + timeout
while (Date.now() < end && !b.exited) {
const c = await b.cookies().catch(() => null)
if (c && hasSession(c)) {
// let the redirect to gemini.google.com finish, so the cookies it
// sets are in the jar too
await sleep(settle)
return (await b.cookies().catch(() => null)) ?? c
}
await sleep(poll)
}
return null
} finally {
await b.close()
}
}
// renew opens the profile without a window at gemini.google.com, where
// the page's own scripts renew __Secure-1PSIDTS, and answers the cookies
// once it has changed (or what the profile holds after the wait).
export async function renew(profile, { before = {}, timeout = 20_000, poll = 700, opener = open } = {}) {
if (!profile || !existsSync(profile)) return null
const b = await opener(profile, GEMINI, { headless: true })
try {
const end = Date.now() + timeout
let last = null
while (Date.now() < end && !b.exited) {
const c = await b.cookies().catch(() => null)
if (c && hasSession(c)) {
last = c
if (c["__Secure-1PSIDTS"] !== before["__Secure-1PSIDTS"]) return c
}
await sleep(poll)
}
return last
} finally {
await b.close()
}
}