From bf0a37f6ea358c4dd3aff5183d3ccecf357c649d Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 7 Nov 2026 16:23:37 +0800 Subject: [PATCH] inkstone 0.1.2: read the console token magpie saves under metadata The "API key + console token" method is an api method. magpie's host save() (internal/plugin/host.js, yetone/magpie 191f3c0af) stores such an answer as {type: "api", key, metadata: {...inputs, ...result.metadata}} and drops top-level extras, so the token sat at metadata.uaaToken. The plugin only read auth.uaaToken / uaa_token / consoleToken, and the card said to sign in again. - uaaTokenOf reads the three names at the top level, then under metadata. usernameOf reads metadata's username/accountId/email too. - A renewed token is written back where the entry kept it (putToken): an api entry keeps it under metadata, an oauth entry at the top level, and nothing else in the entry changes. The host's client.auth.set stores the body as given, with no shape it needs, so there is no reason to lift the token out of metadata. The 401 retry uses the same writer on a copy. - The manual method's success result now carries metadata with the parsed token. result.metadata overrides inputs in save(), so the pasted cookie string (with its other session cookies) is no longer what gets stored under metadata.uaaToken. Tests use the exact object save() writes: the card reads for each of the three names under metadata (usage.test.mjs), a renewal through the fake browser writes back exactly {type:"api", key, metadata:{apiKey, uaaToken:}} (fake-browser.test.mjs), and the manual result's metadata.uaaToken is the parsed token (api.test.mjs). Run on mote, HOME=$(mktemp -d): - 0.1.1 index.mjs with the new tests: all 3 new tests red. - packages/inkstone bun test: 73 pass, 0 fail. - bun scripts/check.mjs inkstone: registry.json and inkstone ok. - root bun test: 6757 pass, 20 skip, 0 fail. Broken by hand, each red: putToken always writing the top level (the renewal test's write-back has a top-level uaaToken); metadata read for uaaToken only (the uaa_token/consoleToken cases fail). Not tried: a real InkStone account signed in with the manual method through magpie; the 401-retry path with a metadata entry has no test of its own. Fixes #826 Reported-by: HuHong-Tao --- packages/inkstone/api.test.mjs | 5 ++++ packages/inkstone/fake-browser.test.mjs | 24 +++++++++++++++- packages/inkstone/index.mjs | 37 +++++++++++++++++++++---- packages/inkstone/package.json | 2 +- packages/inkstone/usage.test.mjs | 15 ++++++++++ 5 files changed, 75 insertions(+), 8 deletions(-) diff --git a/packages/inkstone/api.test.mjs b/packages/inkstone/api.test.mjs index d21fd9c..9de8c01 100644 --- a/packages/inkstone/api.test.mjs +++ b/packages/inkstone/api.test.mjs @@ -176,6 +176,11 @@ test("the API-key + console-token method reads the token out of a pasted cookie" expect(okResult.type).toBe("success") expect(okResult.uaaToken).toBe("abc.def.ghi") expect(JSON.stringify(okResult)).not.toContain("SESSIONSECRET") + // host save() stores {...inputs, ...result.metadata} under metadata (#826): + // the result's metadata carries the parsed token, so the pasted cookie + // string, with its other session cookies, is not what gets saved + expect(okResult.metadata.uaaToken).toBe("abc.def.ghi") + expect(okResult.metadata.apiKey).toBe("sk-test") // a bare token value is accepted as-is const bare = await method.authorize({ apiKey: "sk-test", uaaToken: "abc.def.ghi" }) expect(bare.type).toBe("success") diff --git a/packages/inkstone/fake-browser.test.mjs b/packages/inkstone/fake-browser.test.mjs index f0bc01e..f2f1f3c 100644 --- a/packages/inkstone/fake-browser.test.mjs +++ b/packages/inkstone/fake-browser.test.mjs @@ -10,7 +10,7 @@ import { join } from "node:path" import { afterAll, afterEach, beforeAll, expect, test } from "bun:test" import { InkStoneAuthPlugin } from "./index.mjs" import { renewSilently } from "./lib/browser.mjs" -import { fakeInkStone, json, ok, fail } from "./fake.mjs" +import { fakeInkStone, json, ok, fail, jwtOf, poolUsageFixture, packagesFixture } from "./fake.mjs" let fakeExe = "" let fakeDir = "" @@ -95,6 +95,28 @@ test("the silent renewal reads the session cookie through a real CDP exchange", expect(await renewSilently({ browserPath: fakeExe })).toBe("fake-uaa-token-for-tests") }, 30_000) +// #826: an "API key + console token" entry is saved by the host as +// {type: "api", key, metadata: {apiKey, uaaToken}}. A renewed token goes back +// under metadata, and the rest of the entry is written back as it was. +test("a renewed token is written back where the api entry keeps it, under metadata", async () => { + f = fakeInkStone() + f.route("GET /api/tokenplan/v1/credits/balance", () => ok(poolUsageFixture())) + f.route("GET /api/tokenplan/v1/credits/packages", () => ok(packagesFixture())) + f.route("GET /api/tokenplan/v1/users/validate", () => ok({ name: "张三", phone: "12345678901" })) + const writes = [] + const p = await InkStoneAuthPlugin( + { client: { auth: { set: async (req) => writes.push(structuredClone(req.body)) } } }, + { browser: fakeExe }, + ) + const expired = jwtOf({ exp: Math.floor(Date.now() / 1000) - 60 }) + const saved = { type: "api", key: "sk-test", metadata: { apiKey: "sk-test", uaaToken: expired } } + const u = await p.auth.usage(async () => saved) + expect(u.error).toBeUndefined() + expect(writes).toEqual([ + { type: "api", key: "sk-test", metadata: { apiKey: "sk-test", uaaToken: "fake-uaa-token-for-tests" } }, + ]) +}, 30_000) + test("a full browser sign-in opens the login window, reads the session, and creates the key", async () => { f = fakeInkStone() const keys = serveKeyRoutes() diff --git a/packages/inkstone/index.mjs b/packages/inkstone/index.mjs index 167b571..7cb64ea 100644 --- a/packages/inkstone/index.mjs +++ b/packages/inkstone/index.mjs @@ -137,8 +137,27 @@ export async function InkStoneAuthPlugin({ client, magpie } = {}, options = {}) const raw = auth.type === "api" ? (auth.key ?? "") : (auth.apiKey ?? auth.access ?? "") return normalizeApiKey(raw) } - const uaaTokenOf = (auth) => String(auth?.uaaToken ?? auth?.uaa_token ?? auth?.consoleToken ?? "").trim() - const usernameOf = (auth) => String(auth?.username ?? auth?.accountId ?? auth?.email ?? "").trim() + // The browser sign-in is saved as an oauth entry with the token at the top + // level. magpie saves an "api" method's answers under metadata instead: + // {type: "api", key, metadata: {apiKey, uaaToken}} (host.js save(), #826). + const TOKEN_FIELDS = ["uaaToken", "uaa_token", "consoleToken"] + const tokenField = (o) => TOKEN_FIELDS.find((k) => typeof o?.[k] === "string" && o[k].trim()) + const uaaTokenOf = (auth) => { + const top = tokenField(auth) + if (top) return auth[top].trim() + const md = tokenField(auth?.metadata) + return md ? auth.metadata[md].trim() : "" + } + /** A renewed token goes where the entry kept its token, so the entry keeps its shape. */ + const putToken = (auth, token) => { + if (!tokenField(auth) && tokenField(auth?.metadata)) auth.metadata[tokenField(auth.metadata)] = token + else auth[tokenField(auth) ?? "uaaToken"] = token + return auth + } + const usernameOf = (auth) => + String( + firstNonEmpty(auth?.username, auth?.accountId, auth?.email, auth?.metadata?.username, auth?.metadata?.accountId, auth?.metadata?.email) ?? "", + ).trim() const save = async (auth) => { if (typeof client?.auth?.set !== "function") return false @@ -174,7 +193,7 @@ export async function InkStoneAuthPlugin({ client, magpie } = {}, options = {}) return "" } } - auth.uaaToken = token + putToken(auth, token) await save(auth) return token } finally { @@ -230,7 +249,7 @@ export async function InkStoneAuthPlugin({ client, magpie } = {}, options = {}) const next = uaaTokenOf(fresh) if (next && next !== token) return await readQuota(getAuth, fresh, depth + 1) const renewed = await renew(auth) - if (renewed && renewed !== token) return await readQuota(getAuth, { ...auth, uaaToken: renewed }, depth + 1) + if (renewed && renewed !== token) return await readQuota(getAuth, putToken(structuredClone(auth), renewed), depth + 1) } return { plan: "墨点计划 (Token Plan)", @@ -533,13 +552,19 @@ export async function InkStoneAuthPlugin({ client, magpie } = {}, options = {}) try { const user = await usersValidate(token) const data = user?.data ?? {} + const accountId = firstNonEmpty(data.name, data.username, data.nickname, data.phone, data.email, `inkstone-${fingerprint(key)}`) + const username = firstNonEmpty(data.name, data.username) return { type: "success", key, uaaToken: token, - accountId: firstNonEmpty(data.name, data.username, data.nickname, data.phone, data.email, `inkstone-${fingerprint(key)}`), - username: firstNonEmpty(data.name, data.username), + accountId, + username, source: "manual", + // magpie keeps an api method's answers as metadata, and this + // metadata over them: the token read out of the paste, never + // the whole pasted cookie string (#826) + metadata: { apiKey: key, uaaToken: token, accountId, username, source: "manual" }, } } catch (e) { return { type: "failed", error: cleanDetail(`console token: ${e?.message ?? e}`) } diff --git a/packages/inkstone/package.json b/packages/inkstone/package.json index dbed0d6..5d147e4 100644 --- a/packages/inkstone/package.json +++ b/packages/inkstone/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-inkstone-auth", - "version": "0.1.1", + "version": "0.1.2", "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", diff --git a/packages/inkstone/usage.test.mjs b/packages/inkstone/usage.test.mjs index 9566519..9353133 100644 --- a/packages/inkstone/usage.test.mjs +++ b/packages/inkstone/usage.test.mjs @@ -212,3 +212,18 @@ test("a phone number missing before free credits is reported by auth.checkin", a message: "Bind a phone number in the InkStone console to claim free credits.", }) }) + +// #826: the "API key + console token" method is an api method, and magpie's +// host save() keeps its answers under metadata, not at the top level: +// {type: "api", key, metadata: {...inputs, ...result.metadata}}. +test("an api entry with the token under metadata (as host save() writes it) reads the card", async () => { + f = fakeInkStone() + serve() + const p = await plugin() + for (const field of ["uaaToken", "uaa_token", "consoleToken"]) { + const saved = { type: "api", key: "sk-test", metadata: { apiKey: "sk-test", [field]: "uaa-token" } } + const u = await p.auth.usage(async () => saved) + expect(u.error).toBeUndefined() + expect(u.balance).toBe("10 墨点 · 2 个可用包") + } +})