Files
plugins/packages/sensenova/api.test.mjs
T
我是一条没有名字的区 6a0d9e5b7a sensenova 0.2.0: browser sign-in, plan-filtered models and credit-pool isolation (#730)
sensenova 0.2.0 (yunwang2442-creator): a browser sign-in that captures the console's
OAuth redirect in a one-off Chromium and reuses or creates a `magpie-<host>-<account>-*`
Token Plan API key; the password sign-in kept as a headless fallback; models filtered
to the account's plan; the Flash-Lite pool kept apart from the general pool. Credentials
are sealed with DPAPI on Windows and stored as plaintext elsewhere, as 0.1.3 stored them.
When DPAPI fails, the value is stored as plaintext and the reason is logged.

Reviewed at d57f4a8b (every line of the diff vs main, every new or changed test).

Run at d57f4a8b:
- mote (macOS, Bun 1.4.2, sandbox HOME): `bun test packages/sensenova`: 57 pass, 0 fail;
  `bun test` (whole repo): 5863 pass, 0 fail; `bun scripts/check.mjs`: ok.
- xiaomi-gpu (Windows 11, Bun 1.4.2) via win-run: `bun test packages/sensenova`: 57 pass, 0 fail.
  DPAPI is refused on that box, so this run took the real plaintext fallback.
- A 0.1.3-shaped record ({type:oauth, access, refresh, expires, accountId, uid, apiKey},
  all plaintext, no tokenHost) against a local fake with separate password and browser
  token paths: the refresh went to the password token endpoint only; then the loader
  served sk-legacy, usage read the pools and models listed the plan's model.
- Refresh failures: 400 invalid_grant gives dead + signIn expired, so the host stops.
  500, 503 HTML and an unreachable server give dead:false, so the host retries after
  RENEW_RETRY (30s). A dpapi: value that can't be unsealed gives signIn expired.

Broken by hand (each change in its own copy; each one turned the named test red):
- seal throws off Windows: 5 red, the 0.1.3 upgrade test among them
- seal throws when DPAPI refuses on Windows: 2 red
- seal throws when DPAPI can't load: 1 red
- pruning scoped to every magpie- key: "never touches another saved account's key"
- no activeSuffix protection: "the key in use is never pruned"
- the pre-prune at the 20-key limit put back: "a full account ... is a key_limit error"
- reuse from any magpie- key: "reuse picks this account's newest working key"
- refresh never dead: "a refresh token the platform has revoked says the sign-in is gone"
- create_key off when unset (the old optionOn): "create_key defaults on outside magpie"
- dedicated pool's grant left out: "several granted pools add up"

Not covered by a test: sending a 0.1.3 record (no tokenHost) to the browser token
endpoint keeps every test green, because the fake serves both token endpoints at
/oauth2/token. The code sends it to the password endpoint, as the run above shows.
HOST_TAG (os.hostname) has no test; checked by reading.

Not tried: a real sign-in (no SenseNova account here, no credentials entered). The
author reports real browser, password, refresh and 0.1.3-upgrade runs on Windows 10
and WSL2 Ubuntu (Node 24) on the PR.
2026-11-05 02:45:52 +08:00

231 lines
12 KiB
JavaScript

// The API key side: the catalogue it reads, the models magpie lists for the
// account (its own plan's coverage ∩ what the key serves ∩ what answers a chat
// request), the reasoning effort levels each declares, and the chat loader.
// Everything runs against the local fake.
import "./nonet.mjs"
import { afterEach, expect, test } from "bun:test"
import { SenseNovaAuthPlugin, _internal, optionEnabled } from "./index.mjs"
import { fakeSenseNova, json } from "./fake.mjs"
let f
afterEach(() => f?.close())
// the account one sign-in leaves behind: the console JWT for the pools, the
// API key (kept beside it) for the models and chat
const auth = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000, accountId: "yiheng13", apiKey: "sk-test" }
// the catalogue the key is served: two models the plan covers and chat
// answers, one the plan doesn't cover (the vendor 403s it), one that draws
// (a chat endpoint 404s it)
const CATALOGUE = {
data: [
{ id: "glm-5.2", name: "glm-5.2", context_length: 1048576, max_output_length: 131072, input_modalities: ["text"], output_modalities: ["text"], supported_features: ["tools", "json_mode", "reasoning"] },
{ id: "sensenova-6.8-flash-lite", name: "sensenova-6.8-flash-lite", context_length: 262144, max_output_length: 65536, input_modalities: ["text", "image"], output_modalities: ["text"], supported_features: ["tools", "json_mode", "reasoning"] },
{ id: "deepseek-v4.1-flash", name: "deepseek-v4.1-flash", context_length: 1048576, max_output_length: 65536, input_modalities: ["text"], output_modalities: ["text"], supported_features: ["reasoning"] },
{ id: "sensenova-u1.5-lite", name: "sensenova-u1.5-lite", context_length: 262144, max_output_length: 65536, input_modalities: ["text"], output_modalities: ["image"], supported_features: ["tools"] },
],
}
// the plan this account's pools cover
const PLAN = (ids) => ({ plan: { name: "Free Plan" }, pools: [{ name: "通用积分池", pool_type: "default", model_ids: ids }] })
// routes for a listing: the pools the console shows and the catalogue the key
// is served. Both are counted so a test can say what was asked for.
function serve(list = CATALOGUE, planIds = ["glm-5.2", "sensenova-6.8-flash-lite", "sensenova-u1.5-lite"]) {
f.route("GET /models", (r) => {
expect(r.headers.get("authorization")).toBe("Bearer sk-test")
return json(list)
})
f.route("GET /lite/console/v1/tokenplan/pool-usage", (r) => {
expect(r.headers.get("authorization")).toBe("Bearer tok")
return json(PLAN(planIds))
})
}
async function plugin() {
return SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
}
// the host's own default for a lead it isn't told (host.js RENEW_LEAD)
const HOST_DEFAULT_LEAD = 5 * 60 * 1000
test("a cold listing gives the plan's models, not the raw catalogue", async () => {
// no usage() read first: this is a fresh host process, or the first listing
// after a sign-in. What the plan covers is read here, from this account.
f = fakeSenseNova()
serve()
const p = await plugin()
const models = await p.provider.models({ id: "sensenova-token-plan", models: {} }, { auth })
// deepseek-v4.1-flash is in the catalogue but not the plan (403 from the
// vendor); sensenova-u1.5-lite is in the plan but draws (404 at chat)
expect(Object.keys(models).sort()).toEqual(["glm-5.2", "sensenova-6.8-flash-lite"])
})
test("the listing carries each model's limits, input kinds and effort tiers", async () => {
f = fakeSenseNova()
serve()
const p = await plugin()
const models = await p.provider.models({ id: "sensenova-token-plan", models: {} }, { auth })
expect(models["glm-5.2"].limit).toEqual({ context: 1048576, output: 131072 })
// the tiers are the same for every model: the platform publishes no per-model
// list, so nothing narrower than "these are offered" is claimed
expect(Object.keys(models["glm-5.2"].variants)).toEqual(["none", "low", "high"])
expect(Object.keys(models["sensenova-6.8-flash-lite"].variants)).toEqual(["none", "low", "high"])
// what is claimed is checkable from the reply itself: whether it takes images
expect(models["sensenova-6.8-flash-lite"].capabilities.input.image).toBe(true)
expect(models["glm-5.2"].capabilities.input.image).toBe(false)
})
test("a model the catalogue says doesn't reason gets no effort tiers", () => {
// the gate is the catalogue's own supported_features, not a hand-kept table:
// a model that stops reasoning stops offering tiers, with nothing to update
const flat = _internal.modelOf({ id: "x", name: "x", context: 1000, output: 100, reasoning: false })
expect(flat.reasoning).toBe(false)
expect(flat.variants).toBeUndefined()
const deep = _internal.modelOf({ id: "y", name: "y", context: 1000, output: 100, reasoning: true })
expect(Object.keys(deep.variants)).toEqual(["none", "low", "high"])
})
test("two accounts on different plans list different models", async () => {
// nothing about the plan is kept between calls: a module global would let
// the first account's plan filter the second's list
f = fakeSenseNova()
const p = await plugin()
const wide = { ...auth, access: "tok-wide", apiKey: "sk-wide" }
const narrow = { ...auth, access: "tok-narrow", apiKey: "sk-narrow" }
f.route("GET /models", (r) => {
const want = r.headers.get("authorization") === "Bearer sk-wide" ? CATALOGUE : { data: CATALOGUE.data.slice(0, 1) }
return json(want)
})
f.route("GET /lite/console/v1/tokenplan/pool-usage", (r) => {
const ids = r.headers.get("authorization") === "Bearer tok-wide"
? ["glm-5.2", "sensenova-6.8-flash-lite"]
: ["glm-5.2"]
return json(PLAN(ids))
})
const a = await p.provider.models({ id: "sensenova-token-plan", models: {} }, { auth: wide })
const b = await p.provider.models({ id: "sensenova-token-plan", models: {} }, { auth: narrow })
expect(Object.keys(a).sort()).toEqual(["glm-5.2", "sensenova-6.8-flash-lite"])
expect(Object.keys(b)).toEqual(["glm-5.2"])
})
test("a plan read that fails keeps the bootstrap list rather than the catalogue", async () => {
// the vendor refusing the pools says nothing about what the key can call,
// so the raw catalogue (which holds a model that 403s) must not be listed
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json({ error: "no" }, 500))
f.route("GET /models", () => json(CATALOGUE))
const p = await plugin()
const given = { "glm-5.2": {} }
expect(await p.provider.models({ id: "sensenova-token-plan", models: given }, { auth })).toEqual(given)
})
test("a key the platform has refused lists nothing, not the bootstrap set", async () => {
// a refused key calls nothing, whatever the plan covers: falling back to the
// bootstrap list here would advertise five models that every request to them
// would fail on
f = fakeSenseNova()
serve()
f.route("GET /models", () => json({ error: "unauthorized" }, 401))
const p = await plugin()
const given = { "glm-5.2": {} }
expect(await p.provider.models({ id: "sensenova-token-plan", models: given }, { auth })).toEqual({})
})
test("a 200 that carries no pools is a failed read, so the bootstrap list stands", async () => {
// an empty plan and a reply that isn't the console's shape must not be read
// the same way: the first means the account can call nothing, the second
// means we don't know, and only the second falls back
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json({ plan: { name: "Free Plan" } }))
f.route("GET /models", () => json(CATALOGUE))
const p = await plugin()
const given = { "glm-5.2": {} }
expect(await p.provider.models({ id: "sensenova-token-plan", models: given }, { auth })).toEqual(given)
})
test("an account with no API key advertises no models and serves no chat", async () => {
// the five models in the provider's config belong to an account that has a
// key; without one, listing them would offer models whose requests go out
// with no auth at all
f = fakeSenseNova()
const p = await plugin()
const noKey = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000, accountId: "yiheng13" }
expect(await p.provider.models({ id: "sensenova-token-plan", models: { "glm-5.2": {} } }, { auth: noKey })).toEqual({})
expect(await p.auth.loader(async () => noKey)).toEqual({})
})
test("the loader serves the models with the key, at the platform's base URL", async () => {
f = fakeSenseNova()
const p = await plugin()
const loader = await p.auth.loader(async () => auth)
// magpie sends "Authorization: Bearer <apiKey>" for @ai-sdk/openai-compatible
// itself (host.js sdkHeaders), so the loader only says where and with what
expect(loader.apiKey).toBe("sk-test")
expect(loader.baseURL).toBe(f.origin)
expect(loader.fetch).toBeUndefined()
})
test("the renewal lead is where the host reads it", async () => {
// host.js takes the lead from auth (leadOf(a), a = auth), not from the
// hooks object: on the wrong side of auth it is silently the host's default
const p = await plugin()
expect(p.refreshLead).toBeUndefined()
expect(p.auth.refreshLead).toBe(_internal.EARLY_MS)
expect(p.auth.refreshLead).toBeGreaterThan(HOST_DEFAULT_LEAD)
})
test("the sign-in asks for the account, its password and an optional key", async () => {
const p = await plugin()
const m = p.auth.methods[1] // the password method; [0] is the browser one
expect(m.prompts.map((x) => x.key)).toEqual(["username", "password", "apiKey"])
// the key is optional: an empty one passes, a non-sk- one doesn't
expect(m.prompts[2].validate("")).toBeUndefined()
expect(m.prompts[2].validate("sk-abc")).toBeUndefined()
expect(m.prompts[2].validate("nope")).toContain("sk-")
// the sign-in runs in the background: a url would open the console for nothing
expect(m.authorize({ username: "u", password: "p", apiKey: "" }).url).toBe("")
})
test("a plan that names no models lists none, rather than the bootstrap set", async () => {
// an empty plan is an answer, not a failed read: falling back to the
// bootstrap list would offer models the vendor then refuses. The pools must
// be read for this to mean anything — a test that returns {} before reading
// them would pass whatever this branch does.
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json({ plan: { name: "Free Plan" }, pools: [] }))
f.route("GET /models", () => json(CATALOGUE))
const p = await plugin()
const given = { "glm-5.2": {} }
const models = await p.provider.models({ id: "sensenova-token-plan", models: given }, { auth })
expect(models).toEqual({})
// it got as far as the plan, and stopped there: the catalogue was never asked
expect(f.seen.some((r) => r.path.includes("pool-usage"))).toBe(true)
expect(f.seen.some((r) => r.path === "/models")).toBe(false)
})
test("a plan and a catalogue that share no model list none", async () => {
// both reads succeeded and agree there is nothing to offer: that is an
// answer too, and the bootstrap set must not reappear to cover it up
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json(PLAN(["some-model-the-key-isnt-served"])))
f.route("GET /models", () => json(CATALOGUE))
const p = await plugin()
const given = { "glm-5.2": {} }
expect(await p.provider.models({ id: "sensenova-token-plan", models: given }, { auth })).toEqual({})
// both were really consulted this time
expect(f.seen.some((r) => r.path.includes("pool-usage"))).toBe(true)
expect(f.seen.some((r) => r.path === "/models")).toBe(true)
})
test("create_key defaults on outside magpie, where the host has no option", () => {
// OpenCode has no magpie.option: optionOn() used to answer false for an
// unset option, which silently turned key creation off there while the
// comment and the option's default:true said on
expect(optionEnabled(undefined, {}, "create_key", true)).toBe(true)
expect(optionEnabled(undefined, { create_key: false }, "create_key", true)).toBe(false)
expect(optionEnabled({ option: () => false }, { create_key: true }, "create_key", true)).toBe(false)
expect(optionEnabled({ option: () => true }, {}, "create_key", true)).toBe(true)
// pruning stays opt-in in both hosts
expect(optionEnabled(undefined, {}, "prune_old_keys", false)).toBe(false)
})