inkstone 0.1.1: with no Chromium browser the browser sign-in fails at authorize and names the other sign-ins

On a machine with no Edge, Chrome or Chromium (a Mac with Safari only),
the browser sign-in's authorize() returned opened: true and "A browser
window opens…", and the failure showed only later, in the callback:
browserCandidates() returns [] without throwing, and only a bad explicit
path threw.

requireBrowser() in lib/browser.mjs is now the one check, used by
authorize(), openSession() and signInWithBrowser(). An empty list fails
at authorize, before anything says a window opened. The message names
the other two methods, "API key only" and "API key + console token" (the
console token can be copied from any browser, so the ink-credit card is
still reachable), and MAGPIE_INKSTONE_BROWSER. On macOS it also says
Safari can't be used, since the sign-in runs in its own browser profile.
signInWithBrowser checks the browser before it makes a one-off profile,
so a missing browser leaves no folder behind. The Linux no-display
refusal names the same two methods. The README says which browsers the
browser sign-in needs.

The plugin takes a browserCandidates option, a test hook in place of
the real lookup; the existing sign-in-methods test now uses it too, so
it no longer depends on whether the test machine has Chrome.

Tests: api.test.mjs "with no Chromium browser the browser sign-in fails
at authorize and names the other sign-ins (#825)" and browser.test.mjs
"requireBrowser gives the first browser, and with none says what to use
instead (#825)".

Run on mote (macOS) through mote-run, HOME=$(mktemp -d), at this tree:
- packages/inkstone: bun test: 70 pass, 0 fail.
- bun scripts/check.mjs inkstone: ✓ registry.json, ✓ inkstone.
- repo root bun test: 6754 pass, 20 skip, 0 fail across 489 files.

Broken by hand, each on mote:
- authorize back to the old no-throw lookup: the authorize test is red
  (Expected "failed", Received undefined).
- the fallback names taken out of the message: both new tests red
  (Expected to contain "\"API key only\"").
- the macOS Safari line taken out: both new tests red (Expected to
  contain "Safari can't be used").

Not tried: a real sign-in on a Safari-only Mac or on Windows/Linux
without a browser; the empty-list path is reached through the test hook.

Fixes #825
Reported-by: HuHong-Tao
This commit is contained in:
yetone
2026-11-07 15:56:13 +08:00
parent 4200fed099
commit 3ae528f031
6 changed files with 81 additions and 12 deletions
+2
View File
@@ -64,6 +64,8 @@ API Key 是可选的:不填,账号仍显示额度,只是不服务模型。
| **仅 API Key** | 只粘贴 Key;`GET /v1/models` 探活 | 只有模型 |
| **API Key + 控制台 token** | 粘贴 Key,再粘贴 `uaa-token=…` 那一项(DevTools → Application → Cookies,复制整条 `uaa-token=…` 即可,插件只取值) | 额度 + 模型 |
浏览器登录需要本机装有 Microsoft Edge、Google Chrome 或 Chromium(也可以用 `MAGPIE_INKSTONE_BROWSER` 指定路径)。Safari 用不了:插件要在单独的浏览器 profile 里登录,Safari 不支持。没有这些浏览器时,选「仅 API Key」,或「API Key + 控制台 token」(token 可以从任何浏览器里复制,包括 Safari)。
> 不读、不动你日常浏览器的任何数据:Edge/Chrome 136+ 禁止在默认用户目录上开调试端口,而且把真实 profile 从别的路径打开会清掉端砚登录态。插件的专用 profile 是唯一可行且安全的地方。
浏览器登录时可以把**现有 Key** 粘进 “TokenPlan API key”;留空才会
+30 -4
View File
@@ -13,8 +13,8 @@ afterEach(() => f?.close())
const META = JSON.parse(readFileSync(new URL("./testdata/public-models.json", import.meta.url), "utf8"))
const auth = { type: "oauth", access: "sk-test", apiKey: "sk-test", uaaToken: "uaa-token" }
async function plugin() {
return InkStoneAuthPlugin({ client: { auth: { set: async () => {} } } })
async function plugin(options) {
return InkStoneAuthPlugin({ client: { auth: { set: async () => {} } } }, options)
}
function serve(live = [{ id: "glm-5.3" }, { id: "Agents-A1" }, { id: "intern-decision-4b" }]) {
@@ -111,7 +111,8 @@ test("the loader serves the models with the key at the platform's base URL", asy
})
test("the sign-in methods cover browser, API key, and API key + console token", async () => {
const p = await plugin()
// a machine with a Chromium browser, whatever the test machine has
const p = await plugin({ browserCandidates: () => ["/opt/chromium/chrome"] })
const labels = p.auth.methods.map((m) => m.label)
expect(labels[0]).toContain("Browser sign-in")
expect(labels[1]).toContain("API key only")
@@ -123,7 +124,7 @@ test("the sign-in methods cover browser, API key, and API key + console token",
if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
// a displayless CI runner is refused up front, not left with a window it cannot open
expect(result.type).toBe("failed")
expect(result.error).toContain("no display")
expect(result.error).toContain("needs a display")
} else {
expect(result.method).toBe("auto")
expect(typeof result.callback).toBe("function")
@@ -136,6 +137,31 @@ test("the sign-in methods cover browser, API key, and API key + console token",
expect(browser.prompts[0].validate("nope")).toContain("sk-")
})
test("with no Chromium browser the browser sign-in fails at authorize and names the other sign-ins (#825)", async () => {
// a display is claimed so a displayless runner reaches the browser check
const display = process.env.DISPLAY
process.env.DISPLAY = display || ":99"
try {
const p = await plugin({ browserCandidates: () => [] })
const result = p.auth.methods[0].authorize({})
// never "opened" with instructions that say a window opens
expect(result.type).toBe("failed")
expect(result.opened).toBeUndefined()
expect(result.callback).toBeUndefined()
expect(result.error).toContain("Microsoft Edge, Google Chrome or Chromium")
expect(result.error).toContain('"API key only"')
expect(result.error).toContain('"API key + console token"')
// the names it gives are the other methods' own labels
expect(p.auth.methods[1].label).toStartWith("API key only")
expect(p.auth.methods[2].label).toStartWith("API key + console token")
if (process.platform === "darwin") expect(result.error).toContain("Safari can't be used")
else expect(result.error).not.toContain("Safari")
} finally {
if (display === undefined) delete process.env.DISPLAY
else process.env.DISPLAY = display
}
})
test("the API-key + console-token method reads the token out of a pasted cookie", async () => {
f = fakeInkStone()
serve()
+22
View File
@@ -9,6 +9,7 @@ import {
jwtExp,
profileDir,
readUaaToken,
requireBrowser,
tokenFresh,
waitForConsoleWindow,
waitForToken,
@@ -39,6 +40,27 @@ test("browser candidates reject a path that is not there", () => {
expect(browserCandidates(process.execPath)).toEqual([process.execPath])
})
test("requireBrowser gives the first browser, and with none says what to use instead (#825)", () => {
expect(requireBrowser(undefined, { candidates: () => ["/a/chrome", "/b/edge"] })).toBe("/a/chrome")
const none = { candidates: () => [] }
for (const platform of ["darwin", "linux", "win32"]) {
let msg = ""
try {
requireBrowser(undefined, { ...none, platform })
} catch (e) {
msg = e.message
}
expect(msg).toContain('"API key only"')
expect(msg).toContain('"API key + console token"')
expect(msg).toContain("MAGPIE_INKSTONE_BROWSER")
// Safari is named on macOS only, where it is the browser the user has
if (platform === "darwin") expect(msg).toContain("Safari can't be used")
else expect(msg).not.toContain("Safari")
}
// a missing explicit path still says which path
expect(() => requireBrowser("/definitely/not/here")).toThrow("/definitely/not/here")
})
test("waitForToken's single read has its own timeout, the account never waits 8 minutes", async () => {
let calls = 0
const session = {
+7 -3
View File
@@ -30,8 +30,8 @@ import { bootModels, createCatalog, liveRowsOf, publicRowsOf } from "./lib/model
import { cardOf } from "./lib/quota.mjs"
import { ensureKey, pruneKeys } from "./lib/keys.mjs"
import {
browserCandidates,
readUaaToken,
requireBrowser,
renewSilently,
signInWithBrowser,
tokenFresh,
@@ -108,6 +108,8 @@ export async function InkStoneAuthPlugin({ client, magpie } = {}, options = {})
const waitForLogin = typeof options.waitForLogin === "function" ? options.waitForLogin : undefined
const quotaTtlMs = optNum(options.quotaTtlMs, QUOTA_TTL_MS)
const browserPath = typeof options.browser === "string" && options.browser.trim() ? options.browser.trim() : undefined
// test hook: the browsers this machine has, in place of the real lookup
const browserList = typeof options.browserCandidates === "function" ? options.browserCandidates : undefined
const log = (level, message) => {
try {
@@ -395,11 +397,13 @@ export async function InkStoneAuthPlugin({ client, magpie } = {}, options = {})
if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
return {
type: "failed",
error: "no display for the browser sign-in; use the API key sign-in on this machine",
error:
'The browser sign-in needs a display, and this machine has none. Sign in with "API key only", or with "API key + console token" to also get the ink-credit card.',
}
}
try {
browserCandidates(browserPath)
// an empty list fails here, before the host is told a window opened
requireBrowser(browserPath, browserList ? { candidates: browserList } : undefined)
} catch (e) {
return { type: "failed", error: cleanDetail(e?.message ?? e) }
}
+19 -4
View File
@@ -82,6 +82,22 @@ export function browserCandidates(explicit) {
return out
}
/**
* 浏览器登录要用的那个浏览器;本机一个 Chromium 系浏览器都没有就抛错。
* authorize() 和真正启动浏览器的地方都走这里,提示语只有一份。
* `candidates` 只给测试用。
*/
export function requireBrowser(explicit, { candidates = browserCandidates, platform = process.platform } = {}) {
const list = candidates(explicit)
if (list.length) return list[0]
let msg =
"The browser sign-in needs Microsoft Edge, Google Chrome or Chromium, and none is installed. " +
'Sign in with "API key only", or with "API key + console token" to also get the ink-credit card. ' +
"Or install one of those browsers, or set MAGPIE_INKSTONE_BROWSER to its path."
if (platform === "darwin") msg += " Safari can't be used: the sign-in runs in its own browser profile, which Safari doesn't support."
throw new Error(msg)
}
/** 插件专用(可续期)profile 的目录;不同平台放各自的应用数据目录。 */
export function profileDir(env = process.env, platform = process.platform) {
if (env.MAGPIE_INKSTONE_PROFILE) return env.MAGPIE_INKSTONE_PROFILE
@@ -365,8 +381,7 @@ async function waitForDebugPort(portFile, child, timeoutMs = 25_000) {
* Edge 的同步确认页还是别的,都能读到 `uaa-token`。
*/
export async function openSession({ browserPath, profile, headless = false, plainBrowser = false, url = LOGIN_URL, log = () => {} } = {}) {
const exe = browserCandidates(browserPath)[0]
if (!exe) throw new Error("No Chromium browser was found (Edge or Chrome); use the API key sign-in instead.")
const exe = requireBrowser(browserPath)
if (!existsSync(profile)) mkdirSync(profile, { recursive: true, mode: 0o700 })
const portFile = join(profile, "DevToolsActivePort")
// 上一轮被强制关闭时可能留下端口/单例锁文件;没有浏览器运行时清掉是安全的。
@@ -554,9 +569,9 @@ export async function waitForConsoleWindow(child, { timeoutMs = 8 * 60_000, poll
* 登录态留在专用 profile 里(keepSignIn),续期和下次登录都直接用它。
*/
export async function signInWithBrowser({ browserPath, keepSignIn = true, timeoutMs = 8 * 60_000, waitForLogin, signal, log = () => {} } = {}) {
// before the one-off profile is made, so a missing browser leaves no folder
const exe = requireBrowser(browserPath)
const dir = keepSignIn ? profileDir() : oneOffProfileDir()
const exe = browserCandidates(browserPath)[0]
if (!exe) throw new Error("No Chromium browser was found (Edge or Chrome); use the API key sign-in instead.")
const cancelled = () => Boolean(signal?.aborted)
return await exclusive(async () => {
log("opening the sign-in window")
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-inkstone-auth",
"version": "0.1.0",
"version": "0.1.1",
"description": "Intern InkStone (书生·端砚) TokenPlan in OpenCode and magpie: one console sign-in gives the ink-credit balance, the 5-hour and 7-day windows and the credit packs, and (with an API key) the plan's models for chat",
"type": "module",
"main": "./opencode.mjs",