From 6a0d9e5b7a7d97ee2c87afa819296afa34daf501 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=88=91=E6=98=AF=E4=B8=80=E6=9D=A1=E6=B2=A1=E6=9C=89?= =?UTF-8?q?=E5=90=8D=E5=AD=97=E7=9A=84=E5=8C=BA?= Date: Thu, 5 Nov 2026 02:45:52 +0800 Subject: [PATCH] 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---*` 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. --- README.md | 2 +- packages/sensenova/README.md | 140 ++- packages/sensenova/api.test.mjs | 16 +- packages/sensenova/dpapi.test.mjs | 67 ++ packages/sensenova/index.mjs | 1321 +++++++++++--------------- packages/sensenova/keys.test.mjs | 82 ++ packages/sensenova/lib/browser.mjs | 507 ++++++++++ packages/sensenova/lib/dpapi.mjs | 172 ++++ packages/sensenova/lib/keys.mjs | 208 ++++ packages/sensenova/lib/models.mjs | 484 ++++++++++ packages/sensenova/lib/password.mjs | 307 ++++++ packages/sensenova/lib/pkce.mjs | 23 + packages/sensenova/lib/protocol.mjs | 343 +++++++ packages/sensenova/lib/quota.mjs | 172 ++++ packages/sensenova/package.json | 13 +- packages/sensenova/signin.test.mjs | 86 +- packages/sensenova/testdata.test.mjs | 14 +- registry.json | 2 +- 18 files changed, 3088 insertions(+), 871 deletions(-) create mode 100644 packages/sensenova/dpapi.test.mjs create mode 100644 packages/sensenova/keys.test.mjs create mode 100644 packages/sensenova/lib/browser.mjs create mode 100644 packages/sensenova/lib/dpapi.mjs create mode 100644 packages/sensenova/lib/keys.mjs create mode 100644 packages/sensenova/lib/models.mjs create mode 100644 packages/sensenova/lib/password.mjs create mode 100644 packages/sensenova/lib/pkce.mjs create mode 100644 packages/sensenova/lib/protocol.mjs create mode 100644 packages/sensenova/lib/quota.mjs diff --git a/README.md b/README.md index 6dc12d8..767f5b8 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ subscription and makes its requests. The packages work in OpenCode and in | [raccoon](packages/raccoon) | SenseTime Raccoon (商汤小浣熊, xiaohuanxiong.com): account credits and daily check-in, with browser sign-in or Raccoon desktop's sign-in | `raccoon` | | [river](packages/river) | River (river.ai) pay-as-you-go inference, with your API key: per-account models, documented reasoning efforts and live prices | `river` | | [sap-aicore](packages/sap-aicore) | SAP AI Core deployments for account-scoped GPT Responses and Claude Messages models | `sap-aicore` | -| [sensenova](packages/sensenova) | SenseNova (商汤日日新) Token Plan: one console sign-in gives the credit pools, windows and grants, and (with an optional API key) the plan's models for chat | `sensenova-token-plan` | +| [sensenova](packages/sensenova) | SenseNova (商汤日日新) Token Plan: browser or password sign-in gives the credit pools, windows and grants, and the plan's models — the browser sign-in reuses or creates a Token Plan API key for you | `sensenova-token-plan` | | [trae](packages/trae) | Trae CN (trae.cn) and Trae international (trae.ai), free tier included, with Trae's browser sign-in (experimental) | `trae-cn`, `trae-global` | | [workbuddy](packages/workbuddy) | WorkBuddy (China build, CodeBuddy plan) | `workbuddy` | | [workbuddy](packages/workbuddy) | WorkBuddy (international build) | `workbuddy-ai` | diff --git a/packages/sensenova/README.md b/packages/sensenova/README.md index f1a6fb8..47a0aab 100644 --- a/packages/sensenova/README.md +++ b/packages/sensenova/README.md @@ -1,22 +1,33 @@ -# SenseNova (SenseTime 日日新) Token Plan +# SenseNova (商汤日日新) Token Plan SenseNova(商汤日日新)**Token Plan** 的积分额度与模型,接进 OpenCode 和 [magpie](https://usemagpie.ai):一次登录同时拿到**额度**(积分池、5 小时 / 7 天窗口、返赠余额与到期)和**模型**(控制台计划内的模型,OpenAI 兼容推理)。 -## 一次登录,额度与模型都在 +> 非官方插件,风险自负。本包与商汤无隶属或背书关系。它读取控制台未公开的 +> `pool-usage` 接口,浏览器登录会在本机起一个一次性 Chromium,并会在你自己的 +> 账号里创建(开启清理时也会删除)名为 `magpie-*` 的 API Key。平台没有公开 +> 这些接口,随时可能变化或失效。本插件不绕过验证码、限流或任何平台限制。 -控制台账号(`platform.sensenova.cn`,账号密码)登录时,可同时填入一个 -API Key(`sk-…`,可选)。控制台 JWT 读额度,API Key 转发对话——一个账号, -两套凭证,和 workbuddy 式的接入体验一致。 +## 登录 -| 凭证 | 来源 | 给什么 | +三条路,产出的都是同一个 `sensenova-token-plan` 账号。 + +| 方式 | 做什么 | 需要 | |---|---|---| -| **控制台 JWT** | OIDC 授权码流(PKCE + IAM) | **额度**:积分池、5h / 7d 窗口、返赠余额与到期 | -| **API Key**(`sk-…`) | 控制台「API Keys」页 | **模型**:计划内的模型清单,OpenAI 兼容推理 | +| **浏览器登录(会创建 API Key),首选** | 起一个一次性 Chromium 窗口,在窗口里登录控制台(密码、短信码或扫码均可)。插件在 OAuth 回调落地时截住 `code`,随后复用或创建本账号的 Token Plan API Key | 有 Edge 或 Chrome 的桌面环境 | +| **账号密码** | 控制台自己的 OIDC 授权码流,密码在本机封成 JWE 后才离开,明文不上网、不落盘。可同时粘贴一个已有的 API Key | 无(无头可用) | +| **仅 API Key** | 只用粘贴的 key 服务模型;额度不可见 | 一个 API Key | -API Key 是可选的:不填,账号仍显示额度,只是不服务模型。填了,同一个账号 -既显示额度、又服务对话。 +浏览器登录创建的 Key 名为 `magpie--<账号哈希>-…`:**另一台机器的、 +或另一个 SenseNova 账号的 Key 都不会被复用或删除。** 同一个账号保存了两次时, +两条记录共用这组 Key。provider 设置里有两个开关: + +- **Create an API key on browser sign-in**(默认开):浏览器登录后,若本机没有 + 可复用的 Key,就在账号上创建一个。 +- **Prune old magpie API keys**(默认关):只保留**本账号**最新的两个 + `magpie-*` Key,删除更旧的。手动创建的 Key、以及名字属于别的 SenseNova + 账号的 Key 永不删除;创建时间读不出的 Key 也永不删除。 ## 额度 @@ -24,82 +35,67 @@ API Key 是可选的:不填,账号仍显示额度,只是不服务模型。 `window_5h` / `window_7d` 显示成额度窗口,把 `grant_balance` 显示成卡片的 **余额**——数字(magpie 自己的千分位格式)加「积分」,到期时间紧凑地跟在 旁边(`· 11-04 到期`,跨年带年份)。到期是**积分的到期**,不是套餐的,所以 -不放进卡片头部的套餐到期位(`until`)。这一栏按短数字排版,太长的句子会被 -放大到占满整张卡。多个积分池的赠款相加,到期取最早的一个。每个池的窗口标注 -它覆盖的模型(`models` 字段),让 magpie 按模型分组渲染——通用积分池与 -Flash-Lite 积分池各自独立显示,不挤进同一个 tooltip。 +不放进卡片头部的套餐到期位(`until`)。多个积分池的赠款相加,到期取最早的 +一个。 + +窗口的 `used` 是已用份额;控制台没给 `used` 时用 `limit - remaining` 兜底; +两者都没有的窗口跳过,而不是显示成 0%(那会读成「一点没用」)。超支不截断。 + +通用池的窗口带 `notModels`(专属池的模型),Flash-Lite 池的窗口带 `models`: +商汤先从 Flash-Lite 自己的池扣费,所以通用池用满时不应连带卡住仍有余额的 +Flash-Lite。 ## 模型 -API Key 读 `GET /v1/models`(免费、只读、不计费),目录里的 `context_length` -与 `max_output_length` 就是模型声明的窗口与输出上限。请求走 -`https://token.sensenova.cn/v1`(OpenAI 兼容)。 +模型列表是**账号目录 ∩ 计划覆盖**:计划不覆盖的模型(平台会回 403)不会列出。 +DeepSeek 系列的输出上限用实测值(393,216 / 384,000,2026-10-29 在真实账号上 +测到),而不是目录里偏保守的 `max_output_length`。没有 API Key 的账号不列 +模型;被平台拒绝的 key 也不列。会推理的模型给出 `none` / `low` / `high` 三档 +reasoning effort——这是一套**刻意收窄的通用值**,不是「每个模型都核实过支持」: +多给一档会在任务中途冒出 400,少给一档只是少一个选项。 -模型列表按**计划覆盖**过滤:只列出控制台积分池 `model_ids` 内、且可对话 -(非画图)的模型。计划外的模型(如 `deepseek-v4.1-flash`)不列出,避免选到 -后 403。会推理的模型给出三档 reasoning effort(`none` / `low` / `high`), -magpie 出思考强度选择器;「会不会推理」取自目录自己的 `supported_features`。 +## OpenCode 2.x -## 数据来源与可核查性 +2.x 的桥没有 magpie 的 `auth.usage`、`auth.refresh` 和 provider options 的位置: +在 OpenCode 2.x 下没有额度卡片、也不会自动续期(对话仍走 API Key)。密码输入 +在那里显示为普通文本框。 -商汤没有公开列出这些内容的文档页(`platform.sensenova.cn/docs` 由 JS 渲染, -`sensenova.cn/token-plan` 只点名了两个模型)。所以本插件的口径来自**一个免费 -Token Plan 账号的实测**,并且把抓到的字面响应放进了仓库: +## 凭证 -- `testdata/models.json` —— 一次真实 `GET /v1/models` 回复(7 个模型) -- `testdata/pool-usage.json` —— 一次真实 `pool-usage` 回复(两个积分池) +Windows 上用 DPAPI 密封后再保存(`dpapi:…`),只有你自己的 Windows 用户能读。 +Windows 上 DPAPI 不可用时(漫游配置、损坏的 profile、没有用户凭据的会话)回退 +明文并记录原因,账号不会因此刷新失败。其他平台没有 DPAPI,按 0.1.x 的做法存明文 +(magpie 把它放在你自己的数据目录里)。 -两份都只替换了账号自己的 pool id,其余按原样保留(包括额度数字是**字符串** -这件事)。`testdata.test.mjs` 拿这两份的**值**跑解析与过滤——它证明的是解析器 -吃得下这些值;字节来自哪,是对我自己账号抓包的陈述,测试本身无法自证来源。 +## 开发 -一个实测结论值得注意:目录里 7 个模型**全都**标着 `businesses: -["tokenplan","metered"]`,但计划的积分池只覆盖其中 6 个,而第 7 个 -(`deepseek-v4.1-flash`)调用会被平台拒为 403。**目录自己区分不出来**,所以 -必须用该账号的池去过滤——这也是每次列模型都重新读一次池、不缓存全局的原因。 + bun test packages/sensenova + bun scripts/check.mjs sensenova -还有一条边界要说清:测试用的 fake(`fake.mjs`)是按公开的 magpie host 契约和 -抓到的响应形状写的,但它是我的模型,不是商汤的服务本身。真实登录链路在这一头 -仍未跑过,这是本包目前唯一没有实测覆盖的部分。 +`testdata/` 里有一次真实的 `/v1/models` 回复和一次真实的 `pool-usage` 回复 +(只替换了账号自己的 pool id),解析器由平台的原始字节驱动。 -reasoning effort 档位给的是**一套刻意收窄的通用值**(`none` / `low` / `high`), -对所有模型一视同仁。要说清楚的是:这**不是**「已核实这三个档位每个模型都支持」—— -平台没有公开列出档位,某模型真实接受哪些只有从账号内部逐个请求才知道。这里刻意不 -去声称那种查不动的事,是因为猜错的代价不对称:少给一档只是少一个选项,多给一档则会 -在任务中途冒出一个莫名其妙的 400。猜错时平台直接报错,不会静默出错。 +## English -真正可核验的是「这个模型会不会推理」:目录回复里的 `supported_features` 直接写了, -`testdata/models.json` 就是证据。所以唯一的开关取自它,而不是取自一张手写的表。 +Unofficial. Three sign-in methods produce the same `sensenova-token-plan` account: +browser sign-in (one-off Chromium, CDP capture of the OAuth redirect, then reuse or +create a Token Plan API key), the console password walk (headless fallback; the +password is sealed to a JWE before it leaves the machine), and API key only +(models, no credit pools). -## 安装 +Browser-created keys are named `magpie---…`. Another machine's +or another SenseNova account's keys are never reused or pruned; two saved sign-ins of +the same account share the prefix. Two provider options: +create a key on browser sign-in (default on), prune old magpie keys (default off, +keeps this account's newest two). -```sh -magpie plugin add @magpie-community/opencode-sensenova-auth -magpie plugin login sensenova-token-plan -``` - -登录时填控制台账号、密码,以及(可选)API Key。 - -## 登录的实现 - -控制台登录走它自己的 OIDC 授权码流(PKCE + IAM):密码用平台 JWKS 公钥 -封成 JWE(RSA-OAEP + A256GCM),明文不上网、不落盘。控制台 JWT 只有约 -180 分钟,拿到 `refresh_token` 后自动续期(Hydra 会轮换 refresh token, -每次续期后的新值都会被保存),不需要再输密码。API Key 不参与轮换,续期时 -保留在账号上。 - -## provider id - -`sensenova-token-plan`。**不是** `sensenova`:那个 id 留给用户自己的 custom -provider(sk- key,`token.sensenova.cn`),本插件不与之冲突。 - -## 边界 - -- 面板显示的是**商汤控制台自己的口径**,与网页控制台一致。 -- 免费公测的 key 有 TPM/RPM 限额与 5h / 7d 窗口额度,限流时商汤回 429 或 - `token plan entitlement exhausted`。 -- 平台若变更接口或加密参数,插件可能失效。 +The credit-pool windows carry `notModels` for the dedicated pool's models so a full +general pool does not gate Flash-Lite. The model listing is the catalogue +intersected with the plan's coverage. On Windows credentials are DPAPI-sealed; when +DPAPI refuses (roaming profile, damaged profile, a session without the user's +credentials) the value is stored in plaintext with a logged reason, and the other +platforms store plaintext too (the 0.1.x behaviour). ## 许可证 -MIT +MIT \ No newline at end of file diff --git a/packages/sensenova/api.test.mjs b/packages/sensenova/api.test.mjs index 9a98342..3246797 100644 --- a/packages/sensenova/api.test.mjs +++ b/packages/sensenova/api.test.mjs @@ -4,7 +4,7 @@ // Everything runs against the local fake. import "./nonet.mjs" import { afterEach, expect, test } from "bun:test" -import { SenseNovaAuthPlugin, _internal } from "./index.mjs" +import { SenseNovaAuthPlugin, _internal, optionEnabled } from "./index.mjs" import { fakeSenseNova, json } from "./fake.mjs" let f @@ -177,7 +177,7 @@ test("the renewal lead is where the host reads it", async () => { test("the sign-in asks for the account, its password and an optional key", async () => { const p = await plugin() - const m = p.auth.methods[0] + 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() @@ -217,3 +217,15 @@ test("a plan and a catalogue that share no model list none", async () => { 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) +}) \ No newline at end of file diff --git a/packages/sensenova/dpapi.test.mjs b/packages/sensenova/dpapi.test.mjs new file mode 100644 index 0000000..27257e1 --- /dev/null +++ b/packages/sensenova/dpapi.test.mjs @@ -0,0 +1,67 @@ +// The credential seal: DPAPI on Windows, plaintext elsewhere — and a Windows +// session whose DPAPI refuses must still keep the account working (0.1.3 +// stored plaintext, so falling back is the upgrade-safe behaviour). +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { _setCryptoForTests, seal, unseal } from "./lib/dpapi.mjs" + +afterEach(() => _setCryptoForTests(null)) + +test("a Windows session whose DPAPI refuses stores the value as plaintext and says why", async () => { + const platform = Object.getOwnPropertyDescriptor(process, "platform") + Object.defineProperty(process, "platform", { value: "win32", configurable: true }) + _setCryptoForTests({ + protect() { + throw new Error("Access is denied") + }, + unprotect() { + throw new Error("Access is denied") + }, + }) + const logs = [] + try { + const stored = await seal("jwt-1", { log: (level, message) => logs.push([level, message]) }) + // 0.1.3 kept plaintext; a broken profile must not turn every refresh into + // an error the host retries forever + expect(stored).toBe("jwt-1") + expect(await unseal(stored)).toBe("jwt-1") + expect(logs.length).toBe(1) + expect(logs[0][0]).toBe("warn") + expect(logs[0][1]).toContain("DPAPI") + } finally { + if (platform) Object.defineProperty(process, "platform", platform) + } +}) + +test("a working DPAPI still seals, and unseal reads it back", async () => { + _setCryptoForTests({ + protect: (plain) => Buffer.from("sealed:" + plain, "utf8"), + unprotect: (buf) => Buffer.from(String(buf).replace(/^sealed:/, ""), "utf8"), + }) + const stored = await seal("jwt-2") + expect(stored).toStartWith("dpapi:") + expect(await unseal(stored)).toBe("jwt-2") +}) + +test("a plaintext value is returned as-is, so 0.1.3 records keep working", async () => { + expect(await unseal("plain-jwt")).toBe("plain-jwt") + expect(await unseal("")).toBe("") +}) + +test("a Windows session whose DPAPI cannot be loaded stores the value as plaintext and says why", async () => { + const platform = Object.getOwnPropertyDescriptor(process, "platform") + Object.defineProperty(process, "platform", { value: "win32", configurable: true }) + _setCryptoForTests({ loadError: "crypt32.dll failed to load" }) + const logs = [] + try { + const stored = await seal("jwt-3", { log: (level, message) => logs.push([level, message]) }) + // the same 0.1.3-safe outcome as an outright refusal: plaintext + a reason + expect(stored).toBe("jwt-3") + expect(await unseal(stored)).toBe("jwt-3") + expect(logs.length).toBe(1) + expect(logs[0][0]).toBe("warn") + expect(logs[0][1]).toContain("could not be loaded") + } finally { + if (platform) Object.defineProperty(process, "platform", platform) + } +}) \ No newline at end of file diff --git a/packages/sensenova/index.mjs b/packages/sensenova/index.mjs index 4c60fd5..5f0480e 100644 --- a/packages/sensenova/index.mjs +++ b/packages/sensenova/index.mjs @@ -1,811 +1,584 @@ -// OpenCode provider plugin for SenseNova (SenseTime 日日新) Token Plan: -// a SenseNova console account's credit pools, windows and grants, on the -// account's own models. -// -// One sign-in gives both, like workbuddy's: the console account (with its -// password, sealed into a JWE so it never travels in plaintext) holds the -// quota — the pools, their 5-hour and weekly windows, the grants that -// expire — and an API key (sk-…) pasted with it is what the models are -// spoken to with. The console JWT is what reads the pools; the key is what -// serves chat. The two are one account in magpie. -// -// The console JWT lives ~180 minutes, so a refresh token that renews itself -// (Hydra rotates it — every refresh's new refresh token is saved) is the -// whole point of the sign-in. -// -// The provider id is "sensenova-token-plan", NOT "sensenova": that one is -// the user's own custom provider (an sk- key at token.sensenova.cn), and a -// plugin claiming it would take over the models it already serves. +/** + * SenseNova (SenseTime 日日新) Token Plan for OpenCode and magpie. + * + * One account has two credentials: a console OAuth token pair that reads the + * credit pools, and a Token Plan API key that serves the plan's models. + * + * The browser method creates the API key on the account (and may reuse one + * this machine made earlier); the password method keeps the console's own + * OIDC walk as a headless fallback; the API-key method serves models without + * a console sign-in. The provider id is the upstream package's id, so an + * existing account keeps its models and groups. + */ -// ---- the platform's endpoints, as the console's own traffic uses them -// They live in ENDPOINTS so a test can point them at a local fake; the -// plugin itself never changes them. -const ENDPOINTS = { - console: "https://platform.sensenova.cn", - iam: "https://iam.sensecoreapi.cn", - token: "https://signin.sensecore.cn/oauth2/token", - jwks: "https://signin.sensecore.cn/.well-known/jwks.json", - api: "https://token.sensenova.cn/v1", -} +import { browserCandidates, startLoginCapture } from "./lib/browser.mjs"; +import { seal, unseal } from "./lib/dpapi.mjs"; +import { ensureKey } from "./lib/keys.mjs"; +import { createPkce } from "./lib/pkce.mjs"; +import { passwordLogin, walkInternals } from "./lib/password.mjs"; +import { + ENDPOINTS, + buildAuthorizeUrl, + cleanDetail, + exchangeCode, + fetchPoolUsage, + identityFromTokens, + keyFingerprint, + normalizeApiKey, + probeApiKey, + refreshPasswordTokens, + refreshTokens, +} from "./lib/protocol.mjs"; +import { poolsOf, toUsage, usageOf } from "./lib/quota.mjs"; +import { + FALLBACK_MODELS, + MEASURED_OUTPUT_LIMITS, + catalogModels, + chatModels, + createCatalog, + fellBack, + filterByPlan, + modelOf, + toConfigModel, +} from "./lib/models.mjs"; -const CONSOLE = () => ENDPOINTS.console -const IAM_ORIGIN = () => ENDPOINTS.iam -const TOKEN_ENDPOINT = () => ENDPOINTS.token -const JWKS_ENDPOINT = () => ENDPOINTS.jwks -const API_BASE = () => ENDPOINTS.api -const CLIENT_ID = "nova" -const SCOPE = "openid offline offline_access" -const ENC_KEY_ID = "public:hydra.openid.id-token" -const UA = - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36" -const TIMEOUT_MS = 20_000 -const MAX_HOPS = 8 -const EARLY_MS = 10 * 60 * 1000 // renew this close to a token's end (auth.refresh lead) -const poolUsageUrl = () => CONSOLE() + "/lite/console/v1/tokenplan/pool-usage" +const PROVIDER_ID = "sensenova-token-plan"; +const EARLY_MS = 10 * 60 * 1000; +const NPM = "@ai-sdk/openai-compatible"; +const DEFAULT_QUOTA_TTL_MS = 60_000; +const DEFAULT_LOGIN_TIMEOUT_MS = 8 * 60 * 1000; +const FALLBACK_TOKEN_LIFETIME_MS = 3 * 3600 * 1000; -const NPM = "@ai-sdk/openai-compatible" +const PROTOCOLS = { + chat: { npm: NPM, video: true }, + anthropic: { npm: "@ai-sdk/anthropic", video: false }, + responses: { npm: "@ai-sdk/openai", video: false }, +}; -// ---- small helpers +const lifetimeOf = (expiresIn) => + Number.isFinite(Number(expiresIn)) && Number(expiresIn) > 0 + ? Number(expiresIn) * 1000 + : FALLBACK_TOKEN_LIFETIME_MS; -const str = (o, k) => (typeof o?.[k] === "string" && o[k].trim() ? o[k].trim() : undefined) -const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : undefined) -const num = (v) => { - if (typeof v === "number" && Number.isFinite(v)) return v - if (typeof v === "string" && v.trim() && Number.isFinite(Number(v))) return Number(v) - return undefined -} -const b64url = (bytes) => Buffer.from(bytes).toString("base64url") - -// ---- the crypto: JWE password sealing, PKCE, JWT expiry - -// Seal the password into the 5-segment compact JWE the IAM endpoint wants: -// RSA-OAEP (OAEP over SHA-1 — the SHA-256 variants are refused) + A256GCM. -// The protected header's base64url SEGMENT is the AAD (RFC 7516 §5.1), and -// WebCrypto's ciphertext||tag buffer is split into the last two segments. -async function sealPassword(password) { - const jwksRes = await fetch(JWKS_ENDPOINT(), { headers: { accept: "application/json" }, signal: AbortSignal.timeout(TIMEOUT_MS) }) - if (!jwksRes.ok) throw new Error(`JWKS endpoint: HTTP ${jwksRes.status}`) - const keys = (await jwksRes.json())?.keys ?? [] - const key = keys.find((k) => k.kid === ENC_KEY_ID) - if (!key) throw new Error(`JWKS has no key ${ENC_KEY_ID}`) - - const rsaKey = await crypto.subtle.importKey( - "jwk", - { kty: "RSA", n: key.n, e: key.e, alg: "RSA-OAEP", ext: true }, - { name: "RSA-OAEP", hash: "SHA-1" }, - false, - ["encrypt"], - ) - - const contentKey = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt"]) - const rawKey = new Uint8Array(await crypto.subtle.exportKey("raw", contentKey)) - const iv = crypto.getRandomValues(new Uint8Array(12)) - const protectedHeader = b64url(new TextEncoder().encode(JSON.stringify({ alg: "RSA-OAEP", enc: "A256GCM" }))) - const sealed = new Uint8Array( - await crypto.subtle.encrypt( - { name: "AES-GCM", iv, additionalData: new TextEncoder().encode(protectedHeader), tagLength: 128 }, - contentKey, - new TextEncoder().encode(password), - ), - ) - const ciphertext = sealed.subarray(0, sealed.length - 16) - const tag = sealed.subarray(sealed.length - 16) - const encryptedKey = await crypto.subtle.encrypt({ name: "RSA-OAEP" }, rsaKey, rawKey) - return [protectedHeader, b64url(encryptedKey), b64url(iv), b64url(ciphertext), b64url(tag)].join(".") -} - -const pkce = async () => { - const verifier = b64url(crypto.getRandomValues(new Uint8Array(48))) - const challenge = b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)))) - return { verifier, challenge } -} - -// ---- the redirect walk (cookies kept per host; fetch can't do this itself) - -// The domains the walk may visit. It carries Hydra session and CSRF cookies, -// so a hop found in a page body to some other domain must not be taken. The -// hosts the endpoints are set to are allowed too, which is how a test running -// the whole flow against a local fake gets through. -const SENSENOVA_HOSTS = [/(^|\.)sensenova\.cn$/, /(^|\.)sensecore\.cn$/, /(^|\.)sensecoreapi\.cn$/] - -function allowedHost(url) { - let u +/** + * A provider option: the host's value when it has one, else the fallback. + * magpie fills the option's default before the plugin reads it; outside + * magpie (OpenCode) there is no host value, so the fallback decides. + */ +export function optionEnabled(magpie, options, key, fallback = false) { try { - u = new URL(url) + const value = magpie?.option?.(PROVIDER_ID, key); + if (typeof value === "boolean") return value; } catch { - return false + /* older host */ } - // a test points ENDPOINTS at a local fake (http on loopback). The match is - // per origin, protocol included: matching the host alone would let an - // http:// downgrade of a production https endpoint through this line, before - // the check below ever got to see it — and the jar keys off .host too, so - // the session cookie would go with it in the clear - const sameOrigin = (e) => { + return typeof options?.[key] === "boolean" ? options[key] : fallback; +} + +/** The browser method needs a Chromium and, on Linux, a display. */ +function browserAvailable() { + if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return false; + try { + return browserCandidates().length > 0; + } catch { + return false; + } +} + +export async function SenseNovaAuthPlugin({ client, magpie } = {}, options = {}) { + const baseURL = + typeof options.baseURL === "string" && options.baseURL.trim() + ? options.baseURL.trim().replace(/\/+$/, "") + : ENDPOINTS.api; + const browserPath = typeof options.browser === "string" && options.browser.trim() ? options.browser.trim() : undefined; + const quotaTtlMs = + Number.isFinite(Number(options.quotaTtlMs)) && Number(options.quotaTtlMs) > 0 + ? Number(options.quotaTtlMs) + : DEFAULT_QUOTA_TTL_MS; + const loginTimeoutMs = + Number.isFinite(Number(options.loginTimeoutMs)) && Number(options.loginTimeoutMs) > 0 + ? Number(options.loginTimeoutMs) + : DEFAULT_LOGIN_TIMEOUT_MS; + const protocol = Object.hasOwn(PROTOCOLS, options.protocol) ? options.protocol : "chat"; + const wire = { ...PROTOCOLS[protocol], protocol }; + // Image-only models are for magpie's Drawers; OpenCode's provider catalogue + // stays a chat provider (the upstream convention). + const hostIsMagpie = Boolean(magpie); + + const catalog = createCatalog({ baseURL }); + const quotaCache = new Map(); // sealed access -> { at, value } + const planCache = new Map(); // sealed access -> { at, ids } + + const log = (level, message) => { try { - const x = new URL(e) - return x.host === u.host && x.protocol === u.protocol + client?.app?.log?.({ body: { service: PROVIDER_ID, level, message: cleanDetail(message) } }); } catch { - return false + /* logging is best effort */ } - } - if (Object.values(ENDPOINTS).some(sameOrigin)) return true - // the platform itself is https only: an http://sensenova.cn is not the - // platform but a downgrade or a spoof of it - if (u.protocol !== "https:") return false - return SENSENOVA_HOSTS.some((re) => re.test(u.hostname)) -} + }; -// cookies keyed by host: one that set a cookie is the only one it goes back to -function newJar() { - return new Map() -} + const pruneOn = () => optionEnabled(magpie, options, "prune_old_keys", false); + const createKeyOn = () => optionEnabled(magpie, options, "create_key", true); -const hostOf = (url) => { - try { - return new URL(url).host - } catch { - return "" - } -} + const apiKeyOf = async (auth) => { + if (!auth) return ""; + const raw = auth.type === "api" ? (auth.key ?? "") : (auth.apiKey ?? ""); + if (!raw) return ""; + if (String(raw).startsWith("dpapi:")) return unseal(raw); + return normalizeApiKey(raw); + }; -function cookieHeader(jar, url) { - const own = jar.get(hostOf(url)) - return own && own.size ? [...own.entries()].map(([n, v]) => `${n}=${v}`).join("; ") : "" -} + const refreshTokensFor = (auth, refreshToken) => + auth?.tokenHost === "browser" ? refreshTokens(refreshToken) : refreshPasswordTokens(refreshToken); -function collectCookies(response, jar, url) { - const host = hostOf(url) - if (!host) return - const raw = typeof response.headers.getSetCookie === "function" ? response.headers.getSetCookie() : [] - let own = jar.get(host) - if (!own) jar.set(host, (own = new Map())) - for (const line of raw) { - const [pair = ""] = line.split(";") - const i = pair.indexOf("=") - if (i > 0) own.set(pair.slice(0, i).trim(), pair.slice(i + 1).trim()) - } -} - -async function httpGet(url, jar) { - if (!allowedHost(url)) throw new Error(`refusing to visit ${url}: outside the SenseNova hosts`) - const headers = { "user-agent": UA, accept: "*/*" } - const cookie = cookieHeader(jar, url) - if (cookie) headers.cookie = cookie - return fetch(url, { redirect: "manual", headers, signal: AbortSignal.timeout(TIMEOUT_MS) }) -} - -// Some transitions are rendered client-side: scan a 200 body for the next hop. -// Only a hop to an allowed host is taken, so a page that points elsewhere -// can't pull the walk (and the cookies it holds) off-site. -function nextFromBody(body, wanted) { - if (!body) return "" - const found = [] - for (const m of body.matchAll(/https?:\/\/[^"'\s<>]+[?&][^"'\s<>]*/g)) found.push(m[0]) - const meta = /]+http-equiv=["']refresh["'][^>]+url=["']([^"']+)/i.exec(body) - if (meta) found.push(meta[1]) - for (const p of [ - /window\.location\.replace\(["']([^"']+)["']/, - /window\.location\.href\s*=\s*["']([^"']+)["']/, - /location\.href\s*=\s*["']([^"']+)["']/, - ]) { - const f = p.exec(body) - if (f) found.push(f[1]) - } - for (const u of found) if (allowedHost(u) && wanted.test(u)) return u - return "" -} - -async function followUntil(start, wanted, jar) { - let location = start - for (let hop = 0; hop < MAX_HOPS && location; hop++) { - // the host is checked before what the hop carries: a URL holding the very - // parameter we're looking for, on a domain we have no business visiting, is - // not the answer — taking it would walk off-site with the Hydra session - // and CSRF cookies the jar holds - if (!allowedHost(location)) throw new Error(`the sign-in walk left the SenseNova hosts for ${location}`) - if (wanted.test(location)) return location - const res = await httpGet(location, jar) - collectCookies(res, jar, location) - const next = res.headers.get("location") ?? "" - location = next !== "" ? next : nextFromBody(await res.text(), wanted) - } - // the last hop's target is a hop too, so it is checked like any other: a - // walk that used up its budget must not hand back an off-site URL merely - // because it looks like the thing it was looking for - if (location && wanted.test(location)) { - if (!allowedHost(location)) throw new Error(`the sign-in walk left the SenseNova hosts for ${location}`) - return location - } - return "" -} - -const paramOf = (url, name) => { - try { - return new URL(url).searchParams.get(name) ?? "" - } catch { - return "" - } -} - -// ---- the login flow and the refresh - -async function refreshToken(refresh) { - const res = await fetch(TOKEN_ENDPOINT(), { - method: "POST", - headers: { "content-type": "application/x-www-form-urlencoded", "user-agent": UA, accept: "application/json" }, - body: new URLSearchParams({ - grant_type: "refresh_token", - refresh_token: refresh, - client_id: CLIENT_ID, - scope: SCOPE, - }).toString(), - // a 307 or 308 replays this POST, body included, to wherever the reply - // points — a refresh token must never leave with a redirect, so one is an - // error here rather than a step to follow - redirect: "manual", - signal: AbortSignal.timeout(TIMEOUT_MS), - }) - const body = await res.json().catch(() => ({})) - if (!res.ok || !body.access_token) { - // only invalid_grant means the refresh token itself is dead; any other - // 400 says nothing about it and must not purge a healthy pair - const dead = res.status === 400 && body.error === "invalid_grant" - throw Object.assign( - new Error(`refresh rejected (HTTP ${res.status}): ${body.error_description ?? body.error ?? ""}`), - // the host only marks an account signed-out on an error that says so - // (host.js: e?.signIn === "expired"); without it a dead token is - // retried every RENEW_RETRY (30 s) and never shown as needing a sign-in - { dead, ...(dead ? { signIn: "expired" } : {}) }, - ) - } - return { - access: body.access_token, - refresh: body.refresh_token ?? refresh, - expires: Date.now() + (Number(body.expires_in) || 10800) * 1000, - } -} - -async function passwordLogin(username, password) { - const user = String(username ?? "").trim() - const secret = String(password ?? "") - if (!user || !secret.trim()) throw new Error("username and password are required") - - const jar = newJar() - const { verifier, challenge } = await pkce() - const nonce = b64url(crypto.getRandomValues(new Uint8Array(16))) - - // step 1 — start the OIDC walk on the console origin (the CSRF cookie is - // bound to this host; starting anywhere else kills the flow) - const authUrl = - CONSOLE() + - "/oauth2/auth?" + - new URLSearchParams({ - client_id: CLIENT_ID, - code_challenge: challenge, - code_challenge_method: "S256", - redirect_uri: CONSOLE(), - response_type: "code", - scope: SCOPE, - state: nonce, - }).toString() - const first = await httpGet(authUrl, jar) - collectCookies(first, jar, authUrl) - const challengeUrl = await followUntil(first.headers.get("location") ?? authUrl, /[?&]login_challenge=/, jar) - const loginChallenge = paramOf(challengeUrl, "login_challenge") - if (!loginChallenge) throw new Error("could not obtain a login challenge from the authorization endpoint") - - // step 2 — seal the password and sign in at IAM - const encrypted = await sealPassword(secret) - const iamUrl = `${IAM_ORIGIN()}/iam/authn/v1/auth/nova/login` - const iamRes = await fetch(iamUrl, { - method: "POST", - headers: { - "content-type": "application/json", - "user-agent": UA, - accept: "application/json", - origin: CONSOLE(), - referer: CONSOLE() + "/", - cookie: cookieHeader(jar, iamUrl), - }, - body: JSON.stringify({ username: user, password: encrypted, challenge: loginChallenge, is_encrypt: true }), - redirect: "manual", // the sealed password must not be replayed off-origin - signal: AbortSignal.timeout(TIMEOUT_MS), - }) - const iamBody = await iamRes.json().catch(() => ({})) - const redirect = iamBody?.redirect ?? "" - if (!iamRes.ok || !redirect) { - // the real reason lives in details[].reason, not the top-level message - const reason = - iamBody?.details?.find?.((d) => d?.reason)?.reason ?? iamBody?.message ?? `HTTP ${iamRes.status}` - throw Object.assign(new Error(`login refused: ${reason}`), { - // time-based refusals carry a window; credential ones never retry - kind: /locked|disabled|tooMany|rateLimit|tooManyRequests/i.test(String(reason)) ? "retryable" : "credential", - }) - } - - // step 3 — walk the callback for the code (state must round-trip) - const codeUrl = await followUntil(redirect, /[?&]code=/, jar) - const code = paramOf(codeUrl, "code") - if (!code) throw new Error("callback ended without an authorization code") - if (paramOf(codeUrl, "state") !== nonce) throw new Error("callback state did not match the issued nonce") - - // step 4 — exchange code + verifier for the token pair - const tokenRes = await fetch(TOKEN_ENDPOINT(), { - method: "POST", - headers: { "content-type": "application/x-www-form-urlencoded", "user-agent": UA, accept: "application/json" }, - body: new URLSearchParams({ - grant_type: "authorization_code", - code, - code_verifier: verifier, - client_id: CLIENT_ID, - redirect_uri: CONSOLE(), - scope: SCOPE, - }).toString(), - redirect: "manual", // nor the authorization code with its PKCE verifier - signal: AbortSignal.timeout(TIMEOUT_MS), - }) - const tokenBody = await tokenRes.json().catch(() => ({})) - if (!tokenRes.ok || !tokenBody.access_token) - throw new Error(`token exchange failed: ${tokenBody.error_description ?? tokenBody.error ?? `HTTP ${tokenRes.status}`}`) - return { - access: tokenBody.access_token, - refresh: tokenBody.refresh_token ?? "", - expires: Date.now() + (Number(tokenBody.expires_in) || 10800) * 1000, - } -} - -// ---- the model catalogue (an API key's models) - -// The reasoning effort levels this plugin offers. The platform publishes no -// list of them, and what a given model actually answers can only be learned by -// asking from inside an account — so this table claims no knowledge of any -// model's real tiers. The three are a deliberately narrow common set (`none` -// being thinking off), and being wrong here is loud rather than silent: a -// level the vendor doesn't take answers 400 and magpie shows that, where a -// guessed-at tier would only show up as a confusing failure mid-task. What -// *is* checkable is whether a model reasons at all — the catalogue's own -// `supported_features` says so, and testdata/models.json holds a real reply — -// so that is the only gate here. -const EFFORTS = ["none", "low", "high"] - -// the models the plan ships, as magpie's provider starts with: the same ids -// the catalogue serves, with the limits the platform declared when this was -// written and the reasoning levels each takes. The API key's account -// refreshes them with the live catalogue (provider.models below); the -// plan's pools filter that list to what the key can call. -const BOOT_MODELS = { - "glm-5.2": { name: "glm-5.2", context: 1048576, output: 131072 }, - "deepseek-v4-flash": { name: "deepseek-v4-flash", context: 1048576, output: 65536 }, - "deepseek-flash": { name: "deepseek-flash", context: 1048576, output: 65536 }, - "sensenova-6.8-flash-lite": { name: "sensenova-6.8-flash-lite", context: 262144, output: 65536 }, - "kimi-k3": { name: "kimi-k3", context: 1048576, output: 65536 }, -} - -// What the plan covers is read from the account's own pools each time its -// models are listed (provider.models below) and never kept in a module -// global: a global would be shared between accounts (two SenseNova accounts -// on different plans would filter each other's lists) and would be cold in a -// fresh host process, where it would list a model the vendor answers 403 to. - -// The catalogue the platform serves: free, read-only, and it costs no -// inference allowance. Its own fields are the authority on a model's -// context window and output limit. -async function apiModels(key) { - const res = await fetch(API_BASE() + "/models", { - headers: { authorization: "Bearer " + key, accept: "application/json" }, - signal: AbortSignal.timeout(TIMEOUT_MS), - }) - if (res.status === 401 || res.status === 403) - throw Object.assign(new Error(`SenseNova refused the API key (HTTP ${res.status})`), { refused: true }) - if (!res.ok) throw new Error(`model catalogue: HTTP ${res.status}`) - const body = await res.json().catch(() => ({})) - const data = Array.isArray(body?.data) ? body.data : [] - return data.map((m) => ({ - id: str(m, "id") ?? "", - name: str(m, "name") ?? str(m, "id") ?? "", - context: num(m?.context_length) ?? 0, - output: num(m?.max_output_length) ?? 0, - // a model that takes images in, and one that draws them out - image: Array.isArray(m?.input_modalities) && m.input_modalities.includes("image"), - draws: Array.isArray(m?.output_modalities) && m.output_modalities.includes("image"), - reasoning: Array.isArray(m?.supported_features) && m.supported_features.includes("reasoning"), - })).filter((m) => m.id) -} - -// a model as OpenCode's provider lists it: id, name, limits, what it can do -// and the reasoning effort levels it takes. The API it is spoken on comes -// from the provider's own npm and api (the config hook below), so a model -// says nothing about where it goes. -function modelOf(m, provider) { - const image = m.image === true - const efforts = m.reasoning !== false ? EFFORTS : undefined - return { - id: m.id, - name: m.name || m.id, - limit: { context: m.context ?? 0, output: m.output ?? 0 }, - reasoning: m.reasoning !== false, - tool_call: true, - modalities: { input: image ? ["text", "image"] : ["text"], output: ["text"] }, - capabilities: { - reasoning: m.reasoning !== false, - toolcall: true, - attachment: image, - input: { text: true, image }, - output: { text: true }, - }, - // the effort levels this model takes, each a variant: the gateway sends - // one as `reasoning_effort`, `none` is thinking off. A model that takes - // none is the family's, listed at its own name; one that does not has - // no variants. - ...(efforts && efforts.length ? { variants: Object.fromEntries(efforts.map((e) => [e, { reasoningEffort: e }])) } : {}), - } -} - -// ---- the pool usage (the console's data source) - -// pools → the card's windows and balance. The console returns its numbers -// as strings: limit/used/remaining per window, reset_at as epoch seconds. -// -// The GUI draws only an account's first two windows as meters and puts the -// rest in the row's tooltip, so each window says which models its pool covers -// — the host keeps that field (`ids(w?.models)`) and the GUI groups windows by -// it, which gives every pool its own meters instead of one pool's meters with -// the rest hidden. -// -// The grants — a balance that expires, not a window that gets spent — go to -// `balance`, which the GUI draws as its own chip under the windows. That chip -// is styled for a short figure ("¥12.34", "1,234 积分"), so the balance stays -// a short line: the figure in magpie's own countFormat (thousands separators, -// at most two decimals), the console's own word for it (积分, as joycode's -// balance does), and the expiry right beside it — the expiry belongs to the -// credits, not to the plan, so it must not sit in the head's plan-term slot. -// The date is UTC, as the console's epoch seconds read, month and day within -// the current year and with the year once it differs. -// -// Several granted pools add up (a pool's grant is its own; the chip is the -// account's), and the earliest expiry is the one told, that being when the -// first of them is lost. -function usageOf(pools) { - const count = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }) - const round = (n) => Math.round(n * 100) / 100 - const windows = [] - let grants = 0 - let expiryAt = 0 - const ordered = [...(Array.isArray(pools) ? pools : [])].sort( - (a, b) => (a?.pool_type === "default" ? -1 : 1) - (b?.pool_type === "default" ? -1 : 1), - ) - for (const pool of ordered) { - const poolName = str(pool, "name") ?? "pool" - // the models this pool covers: the GUI groups a window by them, so the - // Flash-Lite pool's windows hang under the flash-lite models instead of - // vanishing into the account's first-two-meters row - const models = (Array.isArray(pool?.model_ids) ? pool.model_ids : []).filter((x) => typeof x === "string" && x) - for (const [key, label, span] of [ - ["window_5h", "5 hours", 5 * 3600], - ["window_7d", "7 days", 7 * 86400], - ]) { - const w = obj(pool?.[key]) - if (!w) continue - const limit = num(w.limit) - if (limit === undefined || limit <= 0) continue - const used = num(w.used) ?? 0 - const resetAt = num(w.reset_at) - windows.push({ - name: `${poolName} · ${label}`, - used: Math.max(0, Math.min(100, (100 * used) / limit)), - display: `${round(used)} / ${round(limit)}`, - amount: round(used), - limit: round(limit), - unit: "credits", - span, - ...(models.length ? { models } : {}), - ...(resetAt && resetAt > 0 ? { resetsAt: new Date(resetAt * 1000).toISOString() } : {}), - }) + const save = async (body) => { + if (typeof client?.auth?.set !== "function") return false; + try { + await client.auth.set({ path: { id: PROVIDER_ID }, body }); + return true; + } catch { + return false; } - const grant = num(pool?.grant_balance) - if (grant !== undefined && grant > 0) { - grants += grant - const expiry = num(pool?.nearest_grant_expiry) - if (expiry && expiry > 0 && (!expiryAt || expiry < expiryAt)) expiryAt = expiry + }; + + const bootModels = () => + Object.fromEntries(chatModels(FALLBACK_MODELS).map((m) => [m.id, toConfigModel(m, wire)])); + + const declareModels = () => + Object.fromEntries( + catalogModels(catalog.peek() ?? FALLBACK_MODELS, { images: hostIsMagpie }).map((m) => [ + m.id, + toConfigModel(m, wire), + ]), + ); + + /** The ids the account's plan covers, or null when the read says nothing. */ + const planIds = async (auth) => { + const sealed = auth?.access ?? ""; + if (!sealed) return null; + const cached = planCache.get(sealed); + if (cached && Date.now() - cached.at < quotaTtlMs) return cached.ids; + let access; + try { + access = await unseal(sealed); + } catch { + return null; } - } - if (!(grants > 0)) return { windows } - // the expiry day, UTC as the console's epoch reads: "11-04" this year, - // "2027-03-01" once the year differs - const day = expiryAt > 0 - ? (() => { - const d = new Date(expiryAt * 1000), now = new Date() - const md = `${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")}` - return d.getUTCFullYear() === now.getUTCFullYear() ? md : `${d.getUTCFullYear()}-${md}` - })() - : "" - return { windows, balance: `${count.format(grants)} 积分${day ? " · " + day + " 到期" : ""}` } -} + try { + const raw = await fetchPoolUsage(access); + if (!Array.isArray(raw?.data?.pools) && !Array.isArray(raw?.pools)) { + // not the console's shape: the read failed, the plan says nothing + return null; + } + const ids = new Set( + poolsOf(raw) + .flatMap((p) => (Array.isArray(p?.model_ids) ? p.model_ids : [])) + .filter((x) => typeof x === "string" && x), + ); + planCache.set(sealed, { at: Date.now(), ids }); + if (planCache.size > 8) planCache.clear(); + return ids; + } catch { + return null; + } + }; -async function poolUsage(access) { - if (!access) throw new Error("no console token to read the plan with") - const res = await fetch(poolUsageUrl(), { - headers: { authorization: "Bearer " + access, accept: "application/json", "user-agent": UA }, - signal: AbortSignal.timeout(TIMEOUT_MS), - }) - if (res.status === 401 || res.status === 403) - throw Object.assign(new Error(`console refused the token (HTTP ${res.status})`), { status: res.status }) - if (!res.ok) throw new Error(`pool-usage: HTTP ${res.status}`) - const body = await res.json().catch(() => ({})) - // a 200 that isn't the shape the console sends is a failed read, not an - // empty plan: read the other way it would list no models for an account that - // has a whole plan, and hide that the platform changed under us - if (!body || typeof body !== "object" || !Array.isArray(body.pools)) - throw new Error("pool-usage: the reply carries no pools to read") - const plan = obj(body?.plan) - const pools = body.pools - const ids = pools.flatMap((p) => (Array.isArray(p?.model_ids) ? p.model_ids : [])).filter((x) => typeof x === "string" && x) - return { - plan: str(plan, "name") ?? str(plan, "id") ?? "SenseNova", - // the ids this account's plan covers: provider.models lists against these - models: ids, - ...usageOf(pools), - } -} - -// ---- the plugin - -// The provider id magpie files this plugin's card under. -const PROVIDER_ID = "sensenova-token-plan" - -function makePlugin() { - return async ({ client }) => { - // magpie saves what refresh gives; used by the login method and renewals. - // The API key is kept beside the access/refresh tokens as `apiKey`, the - // way minimax keeps `realUserID` — not its own account, part of this one. - const save = async (a) => { - if (typeof client?.auth?.set !== "function") return false + /** The usage card, with a 401 recovery that only spends a refresh token once. */ + const readUsage = async (getAuth, auth) => { + const sealed = auth?.access ?? ""; + const hit = quotaCache.get(sealed); + if (hit && Date.now() - hit.at < quotaTtlMs) return hit.value; + let access = ""; + try { + access = await unseal(sealed); + } catch (e) { + return { error: cleanDetail(e?.message ?? e), signIn: "expired" }; + } + try { + const value = toUsage(await fetchPoolUsage(access), { username: auth.username || auth.accountId || "" }); + quotaCache.set(sealed, { at: Date.now(), value }); + if (quotaCache.size > 8) quotaCache.clear(); + return value; + } catch (e) { + if (e?.status !== 401) return { error: cleanDetail(e?.message ?? e), signIn: "kept" }; + // A 401 may be a token the host already renewed; look before spending one. + const now = await getAuth(); + if (now?.access && now.access !== auth.access) { + try { + const value = toUsage(await fetchPoolUsage(await unseal(now.access)), { + username: now.username || now.accountId || "", + }); + quotaCache.set(now.access, { at: Date.now(), value }); + return { ...value, signIn: "renewed" }; + } catch (e2) { + return { error: cleanDetail(e2?.message ?? e2), signIn: "kept" }; + } + } + if (!now?.refresh) return { error: "no refresh token; sign in again", signIn: "expired" }; try { - await client.auth.set({ path: { id: PROVIDER_ID }, body: a }) - return true - } catch { - return false + const t = await refreshTokensFor(now, await unseal(now.refresh)); + if (!t?.access_token) throw new Error("refresh returned no access token"); + const next = { + ...now, + access: await seal(t.access_token, { log }), + refresh: await seal(t.refresh_token || (await unseal(now.refresh)), { log }), + expires: Date.now() + lifetimeOf(t.expires_in), + }; + if (!(await save(next))) { + return { error: "renewed, but the new tokens could not be saved; sign in again", signIn: "kept" }; + } + const value = toUsage(await fetchPoolUsage(t.access_token), { + username: next.username || next.accountId || "", + }); + quotaCache.set(next.access, { at: Date.now(), value }); + return { ...value, signIn: "renewed" }; + } catch (e2) { + if (e2?.invalidGrant) return { error: `${cleanDetail(e2?.message ?? e2)}; sign in again`, signIn: "expired" }; + return { error: cleanDetail(e2?.message ?? e2), signIn: "kept" }; } } + }; - // the account's API key, wherever it is stored (the account's `apiKey`) - const apiKeyOf = (auth) => auth?.apiKey + return { + config: async (cfg) => { + cfg.provider ??= {}; + const p = (cfg.provider[PROVIDER_ID] ??= {}); + p.name ??= "SenseNova Token Plan"; + p.npm ??= wire.npm; + p.api ??= baseURL; + p.models = { ...bootModels(), ...(p.models ?? {}) }; + }, - return { - // magpie's provider config: the name, the AI SDK package and the - // endpoint the requests go to, with the models the provider starts - // with (the account's own catalogue replaces them once it answers). - config: async (cfg) => { - cfg.provider ??= {} - // `??=` keeps a provider the user configured in plugins.json - cfg.provider[PROVIDER_ID] ??= { - name: "SenseNova", - npm: NPM, // chat completions - api: API_BASE(), - models: Object.fromEntries( - Object.entries(BOOT_MODELS).map(([id, m]) => [ - id, - modelOf({ id, name: m.name, context: m.context, output: m.output, image: false, draws: false, reasoning: true }, undefined), + provider: { + id: PROVIDER_ID, + + async models(provider, { auth } = {}) { + const declared = + provider?.models && Object.keys(provider.models).length > 0 ? provider.models : declareModels(); + if (!auth) return declared; + + let apiKey = ""; + try { + apiKey = await apiKeyOf(auth); + } catch (e) { + log("warn", `sensenova: ${e?.message ?? e}`); + return fellBack(declared); + } + // Signed in for quota only: this account serves no models. + if (!apiKey) return {}; + + // User-pinned models are honoured as they are: a plan read that fails + // (or a read we cannot trust) must keep them, not replace them. + const coveredOrThrow = async () => { + const covered = await planIds(auth); + if (covered === null) throw Object.assign(new Error("plan read failed"), { planFailed: true }); + return covered; + }; + try { + // The plan is asked before the catalogue: coverage that names no + // models ends here, and /models is never called. + const covered = await coveredOrThrow(); + if (!covered.size) return {}; + // the listing reads the catalogue raw: the live row is the authority + // for what a model takes (curated knowledge stays in the bootstrap + // config, where nothing live has answered yet) + const rawRows = await catalog.raw(apiKey); + const live = catalogModels( + rawRows.map((r) => ({ + id: r.id, + name: r.name, + contextLength: r.context_length, + maxCompletionTokens: r.max_output_length, + inputModalities: r.input_modalities, + outputModalities: r.output_modalities, + reasoning: (r.supported_features ?? []).includes("reasoning"), + supportsTools: (r.supported_features ?? []).includes("tools"), + efforts: [], + })), + { images: hostIsMagpie }, + ); + if (!live.length) return fellBack(declared); + const filtered = filterByPlan(live, covered); + if (!filtered.length) return {}; + return Object.fromEntries( + filtered.map((m) => [ + m.id, + modelOf({ + id: m.id, + name: m.name, + context: m.contextLength, + output: MEASURED_OUTPUT_LIMITS[m.id]?.value ?? m.maxCompletionTokens, + input_modalities: m.inputModalities, + supported_features: m.supportsTools ? ["tools"] : [], + reasoning: m.reasoning, + }), ]), - ), + ); + } catch (e) { + // The user's own pins survive a failed listing untouched. + if (e?.planFailed && provider?.models && Object.keys(provider.models).length) return provider.models; + // A 401/403 says this key is refused: advertising models would be a lie. + if (e?.status === 401 || e?.status === 403) return {}; + log("warn", `sensenova: keeping the declared models (${e?.message ?? e})`); + return fellBack(declared); } }, - // magpie's provider hook: the id and the model list. The models come - // from the API key's catalogue; a model outside the plan's pools, or - // one that draws (a chat endpoint answers 404 to it), stays unlisted. - provider: { - id: PROVIDER_ID, - // The account's models: what its own plan covers, ∩ what its key - // serves, ∩ what a chat endpoint answers (a drawing model 404s there). - // Both reads are this account's and both happen here, so a cold host - // lists the same set a warm one does. Either read failing gives the - // bootstrap list back — every id in which the plan does cover — rather - // than a raw catalogue that would carry deepseek-v4.1-flash, which the - // vendor refuses with 403. - async models(provider, { auth }) { - const key = apiKeyOf(auth) - // no key: this account can call nothing, so it advertises nothing - if (!key) return {} - let plan - try { - plan = await poolUsage(auth?.access) - } catch { - return provider.models - } - // An empty plan, and an empty overlap with the catalogue, are both - // answers: this account has nothing to offer. Only a read that - // failed falls back to the bootstrap list — that list is the one set - // known to sit inside a free plan, so falling back is safe where - // guessing an unfiltered catalogue would not be. - const covered = new Set(plan.models) - if (!covered.size) return {} - let list - try { - list = await apiModels(key) - } catch (e) { - // the key itself refused: it calls nothing, whatever the plan - // covers, so nothing is listed rather than the bootstrap set - if (e?.refused) return {} - return provider.models - } - const models = list.filter((m) => !m.draws && covered.has(m.id)) - if (!models.length) return {} - return Object.fromEntries(models.map((m) => [m.id, modelOf(m, provider)])) + }, + + auth: { + provider: PROVIDER_ID, + refreshLead: EARLY_MS, + maxConcurrency: 1, + + options: [ + { + key: "create_key", + label: "Create an API key on browser sign-in", + description: + "After a browser sign-in, create a Token Plan API key on the account if this machine has none to reuse.", + default: true, }, - }, - auth: { - // which provider this sign-in belongs to: magpie files the card and - // the account under it (host.js reads auth.provider, not the hook's - // own provider field) - provider: PROVIDER_ID, - // the host reads the lead off auth (leadOf(a), with a = auth), not off - // the hooks object: where it sits decides whether magpie renews this - // far ahead of the token's end or at its own default of 5 minutes - refreshLead: EARLY_MS, - // magpie renews ahead of the token's end, once per account - async refresh(auth) { - if (auth?.type !== "oauth" || !auth.access || !auth.refresh) return undefined - // every failure goes back as an error, not as undefined: host.js - // records its RENEW_RETRY cooldown only when auth.refresh throws, so - // returning undefined would have magpie retry the same failing call - // on every hook until the token's own expiry passed. Only a dead - // token carries signIn "expired" and ends the sign-in; a transient - // one leaves it as it was, for the vendor's answer to tell. - return await refreshToken(auth.refresh) + { + key: "prune_old_keys", + label: "Prune old magpie API keys", + description: + "Keep the newest two keys this sign-in's account created and delete older ones. Manual keys and keys named for another SenseNova account are never touched; two saved sign-ins of the same account share the prefix.", + confirm: "Old magpie-* keys of this account will be deleted; manual keys and other accounts' keys are kept.", }, - // the chat loader: an account with an API key serves the models - // (OpenAI-compatible at token.sensenova.cn/v1). magpie sends - // `Authorization: Bearer ` for @ai-sdk/openai-compatible - // itself, so no custom fetch is needed — the key (kept on the - // account as `apiKey`) goes in as the apiKey the loader returns. - async loader(getAuth) { - const auth = await getAuth() - const key = apiKeyOf(auth) - if (!key) return {} - return { baseURL: API_BASE(), apiKey: key } - }, - // the account's credit pools (the console JWT, not the API key). - // Renewal is the host's job: it renews through auth.refresh, this far - // ahead of the token's end, under a cross-process lock. So usage reads - // with the token in hand and touches a refresh token only when the - // console refuses that token with a 401 — and it first looks for a - // renewal someone else already made. That narrows the window rather - // than closing it: a plugin can't take the host's lock, so if the host - // is mid-renewal at this exact moment the two can still spend one - // rotating token twice and the second is refused. The next read recovers. - async usage(getAuth) { - const auth = await getAuth() - if (auth?.type !== "oauth" || !auth.access) return { error: "not signed in" } - const card = (u, signIn) => ({ - plan: u.plan, - ...(u.balance ? { balance: u.balance } : {}), - windows: u.windows, - user: auth.accountId ?? auth.email ?? "sensenova", - signIn, - }) - try { - return card(await poolUsage(auth.access), "kept") - } catch (e) { - if (e?.status !== 401) return { error: e?.message ?? String(e), signIn: "kept" } - } - // refused mid-life: another renewal may have landed while this read - // was in flight, and Hydra spends a refresh token once, so look - // before spending one of our own - const now = await getAuth() - if (now?.access && now.access !== auth.access) { - try { - return card(await poolUsage(now.access), "renewed") - } catch (e) { - return { error: e?.message ?? String(e), signIn: "kept" } + ], + + methods: [ + { + type: "oauth", + label: "Browser sign-in (creates an API key)", + /** + * The plugin opens a one-off Chromium itself, captures the OAuth + * redirect before the console SPA consumes the code, and returns + * opened:true with url:"" so magpie does not open a second page. + */ + async authorize() { + if (!browserAvailable()) { + throw new Error( + "No Chromium browser was found (or no display is available). Use the account password method or an API key instead.", + ); } - } - if (!now?.refresh) return { error: "no refresh token; sign in again", signIn: "expired" } - try { - const t = await refreshToken(now.refresh) - // the API key rides through: the JWT changes, the key doesn't - if (!(await save({ ...now, ...t }))) - // an unsaved pair is no recovery: the next host would spend a - // refresh token that is already spent - return { error: "renewed, but the new tokens could not be saved; sign in again", signIn: "kept" } - return card(await poolUsage(t.access), "renewed") - } catch (e) { - const why = e?.message ?? String(e) - if (e?.dead) return { error: `${why}; sign in again`, signIn: "expired" } - return { error: why, signIn: "kept" } - } - }, - methods: [ - { - // one sign-in: the console account (its password, sealed to a - // JWE) for the quota, and the API key pasted with it for the - // models. The key is optional — without it the card still shows - // the quota, only no models — but with it the account serves - // chat too, the way workbuddy's one account does both. - type: "oauth", - label: "Sign in with SenseNova account", - prompts: [ - { - type: "input", - key: "username", - message: "Your SenseNova console account (platform.sensenova.cn)", - validate: (v) => (String(v ?? "").trim() ? undefined : "account is required"), - }, - { - type: "password", - key: "password", - message: "Your SenseNova console password (sealed to JWE before it leaves this machine)", - validate: (v) => (String(v ?? "").trim() ? undefined : "password is required"), - }, - { - type: "password", - key: "apiKey", - message: "Your SenseNova API key (sk-…, optional, for the models)", - placeholder: "sk-...", - validate: (v) => { - const s = String(v ?? "").trim() - return s === "" || s.startsWith("sk-") ? undefined : "the key starts with sk-" - }, - }, - ], - authorize: (inputs) => { - const username = String(inputs?.username ?? "").trim() - const password = String(inputs?.password ?? "") - const apiKey = String(inputs?.apiKey ?? "").trim() - if (!username || !password) throw new Error("enter your SenseNova account and password") - return { - // no page to open: the sign-in runs in the background from the - // prompts, as loomy and the other prompt sign-ins do it. A url - // here would have magpie open the console for nothing. - url: "", - instructions: "Signs in to the SenseNova console with your account; the password is sealed (JWE) and never stored.", - method: "auto", - async callback() { - try { - const t = await passwordLogin(username, password) - return { - type: "success", - access: t.access, - refresh: t.refresh, - expires: t.expires, - accountId: username, - uid: username, - // the API key rides along on the account: magpie keeps - // every field the result carries - ...(apiKey ? { apiKey } : {}), - } - } catch (e) { - return { type: "failed", error: `SenseNova sign-in: ${e?.message ?? e}` } + const pkce = createPkce(); + const authorizeUrl = buildAuthorizeUrl(pkce); + const session = await startLoginCapture({ + authorizeUrl, + expectedState: pkce.state, + timeoutMs: loginTimeoutMs, + browserPath, + log: (message) => log("info", `sensenova: ${message}`), + }); + return { + url: "", + opened: true, + instructions: + "A one-off browser window is open. Sign in to the SenseNova console there (password, SMS code or QR code); " + + "the plugin captures the redirect and creates an API key named magpie-* on this account (it may reuse or delete older keys it created).", + method: "auto", + async callback() { + try { + const { code } = await session.result; + const tokens = await exchangeCode({ code, verifier: pkce.verifier }); + if (!tokens?.access_token) throw new Error("the token response has no access_token"); + if (!tokens?.refresh_token) throw new Error("the token response has no refresh_token (offline scope missing)"); + const { username, uid } = identityFromTokens(tokens); + // the same id the account is saved under, so two records of + // one account share their key prefix even without a username + const accountId = username || uid || `sensenova-${keyFingerprint(tokens.refresh_token)}`; + let apiKey = ""; + if (createKeyOn()) { + apiKey = await ensureKey(tokens.access_token, accountId, { + baseURL, + prune: pruneOn(), + log, + }); } - }, - } - }, + return { + type: "success", + accountId, + uid, + username, + refresh: await seal(tokens.refresh_token, { log }), + access: await seal(tokens.access_token, { log }), + expires: Date.now() + lifetimeOf(tokens.expires_in), + ...(apiKey ? { apiKey: await seal(apiKey, { log }) } : {}), + tokenHost: "browser", + }; + } catch (e) { + return { type: "failed", error: cleanDetail(e?.message ?? e) }; + } finally { + await session.close(); + } + }, + }; }, - ], + }, + { + type: "oauth", + label: "Account password (headless fallback)", + prompts: [ + { + type: "input", + key: "username", + message: "Your SenseNova console account", + validate: (v) => (String(v ?? "").trim() ? undefined : "account is required"), + }, + { + type: "password", + key: "password", + message: "Your SenseNova console password (sealed to a JWE before it leaves this machine)", + validate: (v) => (String(v ?? "").trim() ? undefined : "password is required"), + }, + { + type: "password", + key: "apiKey", + message: "A Token Plan API key (optional; the browser method creates one for you)", + placeholder: "sk-...", + validate: (v) => { + const s = String(v ?? "").trim(); + return s === "" || s.startsWith("sk-") ? undefined : "the key starts with sk-"; + }, + }, + ], + authorize(inputs) { + const username = String(inputs?.username ?? "").trim(); + const password = String(inputs?.password ?? ""); + if (!username || !password) throw new Error("enter the console account and password"); + const apiKeyInput = normalizeApiKey(inputs?.apiKey); + return { + url: "", + instructions: "Signs in to the SenseNova console; the password is sealed and never stored.", + method: "auto", + async callback() { + try { + const t = await passwordLogin(username, password); + if (apiKeyInput) { + try { + await probeApiKey(apiKeyInput, baseURL); + } catch (e) { + if (e?.status === 401 || e?.status === 403) { + return { type: "failed", error: "the API key was refused; check it and try again" }; + } + } + } + return { + type: "success", + accountId: username, + uid: username, + username, + access: await seal(t.access, { log }), + refresh: await seal(t.refresh, { log }), + expires: t.expires, + ...(apiKeyInput ? { apiKey: await seal(apiKeyInput, { log }) } : {}), + tokenHost: "password", + }; + } catch (e) { + return { type: "failed", error: cleanDetail(e?.message ?? e) }; + } + }, + }; + }, + }, + { + type: "api", + label: "API key only (models, no credit pools)", + keyless: true, + prompts: [ + { + type: "password", + key: "apiKey", + message: "Token Plan API key (console → API Keys)", + placeholder: "sk-...", + validate: (v) => (normalizeApiKey(v) ? undefined : "API key is required"), + }, + ], + async authorize(inputs) { + const apiKey = normalizeApiKey(inputs?.apiKey); + if (!apiKey) return { type: "failed", error: "API key is required" }; + try { + await probeApiKey(apiKey, baseURL); + } catch (e) { + if (e?.status === 401 || e?.status === 403) return { type: "failed", error: cleanDetail(e?.message ?? e) }; + log("warn", `sensenova: API key probe did not finish (${e?.message ?? e})`); + } + return { + type: "success", + key: await seal(apiKey, { log }), + metadata: { apiKey: undefined, email: `key:${keyFingerprint(apiKey)}` }, + }; + }, + }, + ], + + async loader(getAuth) { + const auth = await getAuth(); + const apiKey = await apiKeyOf(auth); + if (!apiKey) return {}; + return { baseURL, apiKey }; }, - } - } + + async usage(getAuth) { + const auth = await getAuth(); + if (!auth) return { error: "not signed in" }; + if (auth.type === "api") { + return { + error: "This account signed in with an API key only: models work, credit pools are not visible.", + signIn: "kept", + }; + } + if (!auth.access) return { error: "not signed in", signIn: "expired" }; + const value = await readUsage(getAuth, auth); + if (value?.error) return value; + return { ...value, user: auth.username || auth.accountId || value.user || "sensenova" }; + }, + + async refresh(auth) { + if (auth?.type !== "oauth" || !auth.access || !auth.refresh) return undefined; + let refreshToken = ""; + try { + refreshToken = await unseal(auth.refresh); + } catch (e) { + throw Object.assign(new Error(cleanDetail(e?.message ?? e)), { signIn: "expired" }); + } + if (!refreshToken) throw Object.assign(new Error("no refresh token; sign in again"), { signIn: "expired" }); + try { + const t = await refreshTokensFor(auth, refreshToken); + if (!t?.access_token) throw new Error("refresh returned no access_token"); + return { + access: await seal(t.access_token, { log }), + refresh: await seal(t.refresh_token || refreshToken, { log }), + expires: Date.now() + lifetimeOf(t.expires_in), + }; + } catch (e) { + const error = new Error(`refresh failed: ${cleanDetail(e?.message ?? e)}`); + error.dead = Boolean(e?.invalidGrant); + if (e?.invalidGrant) error.signIn = "expired"; + throw error; + } + }, + }, + }; } -export const SenseNovaAuthPlugin = makePlugin() -export default SenseNovaAuthPlugin - -// for tests +/** Tests point ENDPOINTS at a local fake and replace the crypto/launcher. */ export const _internal = { - sealPassword, - pkce, - passwordLogin, - refreshToken, - usageOf, - poolUsage, - apiModels, - modelOf, ENDPOINTS, - EFFORTS, - BOOT_MODELS, + startLoginCapture, + passwordLogin, + refreshToken: refreshPasswordTokens, + ensureKey, + browserAvailable, + seal, + unseal, + ...walkInternals, EARLY_MS, - allowedHost, - newJar, - cookieHeader, - collectCookies, - followUntil, -} + modelOf, + usageOf, + toUsage, + poolsOf, +}; + +export default SenseNovaAuthPlugin; diff --git a/packages/sensenova/keys.test.mjs b/packages/sensenova/keys.test.mjs new file mode 100644 index 0000000..5b4702d --- /dev/null +++ b/packages/sensenova/keys.test.mjs @@ -0,0 +1,82 @@ +// The API-key lifecycle: the keys one account can reuse and prune never +// reach another saved account's keys. Everything runs against the local fake. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { ensureKey, findReusableKey, keyPrefix, pruneKeys } from "./lib/keys.mjs" +import { fakeSenseNova, json } from "./fake.mjs" + +let f +afterEach(() => f?.close()) + +const KEYS_PATH = "/lite/console/v1/metered/api-keys" + +// a day apart, so "newest two" is unambiguous +const day = (n) => new Date(Date.UTC(2026, 0, n)).toISOString() + +/** One account's keys, as the console lists them (plaintext api_key included). */ +const keyRow = (name, n) => ({ id: name, displayname: name, api_key: `sk-${name}`, create_time: day(n) }) + +test("pruning one account's old keys never touches another saved account's key", async () => { + f = fakeSenseNova() + const alice = keyPrefix("alice") + const bob = keyPrefix("bob") + expect(alice).not.toStartWith(bob) + + // alice has three keys; bob has one, older than all of alice's + const rows = [ + keyRow(`${alice}20260101`, 1), + keyRow(`${alice}20260102`, 2), + keyRow(`${alice}20260103`, 3), + keyRow(`${bob}20260104`, 4), + ] + f.route("GET " + KEYS_PATH, () => json({ api_keys: rows, total_count: rows.length })) + f.route("DELETE " + KEYS_PATH + "/" + `${bob}20260104`, () => json({})) + for (const r of rows.filter((k) => k.displayname.startsWith(alice))) { + f.route("DELETE " + KEYS_PATH + "/" + r.displayname, () => json({})) + } + + const deleted = await pruneKeys("tok", { username: "alice", log: () => {} }) + expect(deleted).toBe(1) // only alice's oldest; the newest two stay + + const gone = f.seen.filter((r) => r.method === "DELETE").map((r) => r.path.split("/").pop()) + expect(gone).toEqual([`${alice}20260101`]) + expect(gone.some((id) => id.startsWith(bob))).toBe(false) +}) + +test("the key in use is never pruned, even when it is the oldest", async () => { + f = fakeSenseNova() + const alice = keyPrefix("alice") + const rows = [keyRow(`${alice}20260101`, 1), keyRow(`${alice}20260102`, 2), keyRow(`${alice}20260103`, 3)] + f.route("GET " + KEYS_PATH, () => json({ api_keys: rows, total_count: 3 })) + for (const r of rows) f.route("DELETE " + KEYS_PATH + "/" + r.displayname, () => json({})) + + const deleted = await pruneKeys("tok", { username: "alice", activeSuffix: "20260101", log: () => {} }) + expect(deleted).toBe(0) + expect(f.seen.filter((r) => r.method === "DELETE")).toEqual([]) +}) + +test("reuse picks this account's newest working key, never another account's", async () => { + f = fakeSenseNova() + const alice = keyPrefix("alice") + const bob = keyPrefix("bob") + const rows = [keyRow(`${alice}20260101`, 1), keyRow(`${bob}20260102`, 2), keyRow(`${bob}20260103`, 3)] + f.route("GET " + KEYS_PATH, () => json({ api_keys: rows, total_count: 3 })) + // every key the fake is probed with answers fine + f.route("GET /models", () => json({ data: [] })) + + const reused = await findReusableKey("tok", f.origin, { username: "alice" }) + expect(reused).toBe(`sk-${alice}20260101`) + expect(reused).not.toContain(bob) +}) + +test("a full account with no key to reuse is a key_limit error, not a deletion", async () => { + f = fakeSenseNova() + const alice = keyPrefix("alice") + const rows = Array.from({ length: 20 }, (_, i) => keyRow(`${alice}2026${String(i + 1).padStart(4, "0")}`, i + 1)) + f.route("GET " + KEYS_PATH, () => json({ api_keys: rows, total_count: 20 })) + f.route("GET /models", () => json({}, 401)) + + const err = await ensureKey("tok", "alice", { baseURL: f.origin }).then(() => null, (e) => e) + expect(err?.code).toBe("key_limit") + expect(f.seen.filter((r) => r.method === "DELETE")).toEqual([]) +}) \ No newline at end of file diff --git a/packages/sensenova/lib/browser.mjs b/packages/sensenova/lib/browser.mjs new file mode 100644 index 0000000..22996ae --- /dev/null +++ b/packages/sensenova/lib/browser.mjs @@ -0,0 +1,507 @@ +/** + * 受控浏览器登录:用本机 Edge/Chrome 的一个临时实例完成 OAuth 授权码捕获。 + * + * The login capture follows the console's own OIDC walk, stopped at the redirect through CDP: + * the plugin: a temporary Chromium window; CDP stops the redirect where it lands and reads the code + * + * + * 两者都保证: + * - 抓取发生在官方 SPA 消费 code 之前(SPA 从未加载,code 从未到过它的手上); + * - code 用**我们自己生成的 PKCE verifier** 交换(手工 state 不被官方 SPA 承认); + * - 登录全程落在一次性 profile 里,不碰日常浏览器的 cookie 与登录态, + * 关闭时整个 profile 目录删除。 + * + * 回调到达时用一张"登录成功"页面替换掉导航(Fetch.fulfillRequest), + * 而不是放行——这样 SPA 依然不会执行。 + * + * 两处针对 Bun 1.3.1(Windows)原生崩溃的规避,改代码前请先看 detach() 与 + * removeProfile() 的说明:收尾时**不**调用 WebSocket.close(),也**不**用 + * Bun 的 rmSync 递归删目录——两者单独测没事,和"CDP 会话刚结束"叠在一起会 + * 偶发 panic: Segmentation fault,而插件宿主是长驻进程,崩了会连累 magpie。 + */ + +import { spawn, spawnSync } from "node:child_process"; +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +/** 默认只拦官方控制台域名的请求(自测时可用本地域名复现同一流程)。 */ +const DEFAULT_CALLBACK_HOST = "platform.sensenova.cn"; + +/** 浏览器候选(Windows 优先;未来 mac/linux 同规则)。MAGPIE_SENSENOVA_BROWSER 可覆盖。 */ +function candidates() { + const env = process.env.MAGPIE_SENSENOVA_BROWSER; + const out = []; + if (env) out.push(env); + const pf = process.env.ProgramFiles; + const pf86 = process.env["ProgramFiles(x86)"]; + const local = process.env.LOCALAPPDATA; + const home = process.env.HOME; + if (process.platform === "win32") { + if (pf86) out.push(join(pf86, "Microsoft", "Edge", "Application", "msedge.exe")); + if (pf) out.push(join(pf, "Microsoft", "Edge", "Application", "msedge.exe")); + if (pf86) out.push(join(pf86, "Google", "Chrome", "Application", "chrome.exe")); + if (pf) out.push(join(pf, "Google", "Chrome", "Application", "chrome.exe")); + if (local) out.push(join(local, "Google", "Chrome", "Application", "chrome.exe")); + if (local) out.push(join(local, "Microsoft", "Edge", "Application", "msedge.exe")); + } else if (process.platform === "darwin") { + out.push("/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"); + out.push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"); + out.push("/Applications/Chromium.app/Contents/MacOS/Chromium"); + } else { + out.push("/usr/bin/microsoft-edge", "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"); + } + if (home) out.push(join(home, "Applications", "Chromium.app", "Contents", "MacOS", "Chromium")); + return out; +} + +/** 找到所有可用的 Chromium 系浏览器(去重)。 */ +export function browserCandidates(explicit) { + if (explicit && typeof explicit === "string") { + if (existsSync(explicit)) return [explicit]; + throw new Error(`指定的浏览器不存在: ${explicit}`); + } + const seen = new Set(); + const out = []; + for (const p of candidates()) { + if (p && existsSync(p) && !seen.has(p)) { + seen.add(p); + out.push(p); + } + } + if (!out.length) { + throw new Error( + "没有找到 Microsoft Edge 或 Chrome。请安装 Edge,或用环境变量 MAGPIE_SENSENOVA_BROWSER 指定浏览器可执行文件路径。", + ); + } + return out; +} + +/** 找到首选的 Chromium 系浏览器;找不到时给出可操作的报错。 */ +export function findBrowser(explicit) { + return browserCandidates(explicit)[0]; +} + +/** + * 给浏览器一个干净的环境。 + * + * magpie 的 GUI 宿主会带 `__COMPAT_LAYER` 之类的兼容层变量;Edge 继承后 + * 会走 `--edge-skip-compat-layer-relaunch` 重启,重启后的进程不写 + * `DevToolsActivePort`,窗口就停在 about:blank。CLI 启动没有这些变量, + * 所以同一套代码在 CLI 里正常、在 app 里黑屏。 + */ +function browserEnv() { + const env = { ...process.env }; + for (const key of ["__COMPAT_LAYER", "COMPAT_LAYER", "CHROME_HEADLESS", "ELECTRON_RUN_AS_NODE"]) { + delete env[key]; + } + return env; +} + +function escapeHtml(text) { + return String(text ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); +} + +function htmlPage(title, body, ok) { + return ` +${escapeHtml(title)} + +
${ok ? "✅" : "⚠️"}

${escapeHtml(title)}

${escapeHtml(body)}

`; +} + +/** 极简 CDP 客户端:send(method, params) + on(event)。 */ +class Cdp { + constructor(ws) { + this.ws = ws; + this.seq = 0; + this.pending = new Map(); + this.handlers = new Set(); + this.closers = new Set(); + ws.onmessage = (e) => this.dispatch(e); + ws.onclose = () => { + for (const fn of this.closers) { + try { + fn(); + } catch {} + } + }; + } + + static async connect(port, { timeoutMs = 20_000 } = {}) { + const deadline = Date.now() + timeoutMs; + let page = null; + while (Date.now() < deadline && !page) { + try { + const res = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(3000) }); + const list = await res.json(); + page = list.find((t) => t.type === "page" && t.webSocketDebuggerUrl); + } catch { + /* 端口刚起来时可能还没有页面目标 */ + } + if (!page) await sleep(100); + } + if (!page) throw new Error("浏览器的调试端口没有可用的页面目标"); + + const ws = new WebSocket(page.webSocketDebuggerUrl); + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("连接浏览器调试 WebSocket 超时")), 10_000); + ws.onopen = () => { + clearTimeout(timer); + resolve(); + }; + ws.onerror = () => { + clearTimeout(timer); + reject(new Error("浏览器调试 WebSocket 连接失败")); + }; + }); + return new Cdp(ws); + } + + dispatch(e) { + let msg = null; + try { + msg = JSON.parse(typeof e.data === "string" ? e.data : ""); + } catch { + return; + } + if (msg?.id && this.pending.has(msg.id)) { + const { resolve, reject } = this.pending.get(msg.id); + this.pending.delete(msg.id); + if (msg.error) reject(new Error(msg.error.message ?? JSON.stringify(msg.error))); + else resolve(msg.result); + return; + } + if (msg?.method) { + for (const fn of this.handlers) { + try { + fn(msg); + } catch {} + } + } + } + + send(method, params = {}) { + return new Promise((resolve, reject) => { + const id = ++this.seq; + this.pending.set(id, { resolve, reject }); + try { + this.ws.send(JSON.stringify({ id, method, params })); + } catch (e) { + this.pending.delete(id); + reject(e); + } + }); + } + + on(fn) { + this.handlers.add(fn); + } + + onClose(fn) { + this.closers.add(fn); + } + + /** + * 丢掉引用但不调用 ws.close()。 + * + * Bun 1.3.1 在 Windows 上"关掉 CDP WebSocket + 立刻杀进程/删目录"会偶发 + * 原生段错误(panic: Segmentation fault)。插件宿主是长驻进程,崩了会连累 + * 整个 magpie,所以这里只解除回调引用:浏览器进程被杀之后这条连接自然断开, + * 迟到的 onclose 也不会再触发任何东西。 + */ + detach() { + this.handlers.clear(); + this.closers.clear(); + this.pending.clear(); + this.ws = null; + } +} + +/** 结束整个浏览器进程树(Windows 上 child.kill 不够干净)。 */ +function killTree(child) { + if (!child || child.exitCode !== null || child.killed) return; + try { + if (process.platform === "win32") { + spawnSync("taskkill", ["/pid", String(child.pid), "/t", "/f"], { stdio: "ignore", windowsHide: true }); + } else { + child.kill("SIGKILL"); + } + } catch { + /* 进程可能已经退出 */ + } +} + +/** + * 删除一次性 profile 目录。 + * + * Windows 上刻意不用 Bun 的 rmSync:Bun 1.3.1 在"CDP 连接刚关闭 + 递归删除 + * Edge profile"这个组合下会偶发原生崩溃(panic: Segmentation fault), + * 而插件宿主是长驻进程,崩了会连累整个 magpie。交给系统 rmdir 做, + * 失败也只是留下一个临时目录,不影响登录结果。 + */ +async function removeProfile(dir) { + for (let i = 0; i < 12; i++) { + if (process.platform === "win32") { + // cmd 会把 & ^ | < > 等元字符拆开(实测 `C:\a&b` 会被当成两条命令, + // 目标目录删不掉还会执行额外片段)。路径含元字符时改走 rmSync: + // 这条分支只发生在 CDP 从未建立的启动失败场景,无 Bun 崩溃风险。 + if (/[&^|<>"]/.test(dir)) { + try { + rmSync(dir, { recursive: true, force: true, maxRetries: 12, retryDelay: 500 }); + return true; + } catch { + /* 文件锁:稍后重试 */ + } + } else { + // spawnSync 会把带空格的参数正确传给 cmd;不要自己拼一整条命令串, + // 那会在 cmd 里产生嵌套引号错误(实测 status 123)。 + const r = spawnSync("cmd", ["/c", "rmdir", "/s", "/q", dir], { stdio: "ignore", windowsHide: true }); + if (r.status === 0) return true; + } + } else { + try { + rmSync(dir, { recursive: true, force: true }); + return true; + } catch { + /* 文件锁:稍后重试 */ + } + } + await sleep(500); // Edge 释放 profile 文件锁需要一点时间 + } + return !existsSync(dir); +} + +async function waitForDebugPort(portFile, child, timeoutMs = 25_000) { + const deadline = Date.now() + timeoutMs; + let exited = false; + child.once("exit", () => { + exited = true; + }); + while (Date.now() < deadline) { + try { + const port = Number(readFileSync(portFile, "utf8").split("\n")[0]); + if (Number.isInteger(port) && port > 0) return port; + } catch { + /* 文件还没写出来 */ + } + if (exited) throw new Error("浏览器启动后立刻退出了(被策略拦截?)"); + await sleep(120); + } + throw new Error( + "浏览器没有写出调试端口,启动失败。若 magpie 以管理员或兼容模式运行,请用普通权限重启后再试;也可以改用“仅 API Key”登录。", + ); +} + +/** + * 打开受控浏览器并等待授权回跳,捕获 code。 + * + * @param {object} o + * @param {string} o.authorizeUrl 要导航到的授权地址 + * @param {string} [o.expectedState] 必须匹配的 state(防串会话) + * @param {number} [o.timeoutMs] 用户完成登录的总预算 + * @param {boolean} [o.headless] 无头(自测用;真实登录必须有头,用户要能看见并操作) + * @param {string} [o.browserPath] 指定浏览器可执行文件 + * @param {(msg: string) => void} [o.log] 诊断日志 + * @returns {Promise<{result: Promise<{code: string, state: string, redirectUrl: string}>, close: () => Promise}>} + * result 在抓到 code 时兑现;窗口被关 / 用户拒绝 / 超时会拒绝。 + * close() 关浏览器 + 删临时 profile(幂等;失败路径也会自动收尾)。 + */ +export async function startLoginCapture({ + authorizeUrl, + expectedState = "", + callbackHost = DEFAULT_CALLBACK_HOST, + timeoutMs = 8 * 60 * 1000, + headless = false, + browserPath, + log = () => {}, +}) { + const exes = browserCandidates(browserPath); + // 环境变量指定的浏览器不存在时 candidates() 会静默跳过——至少说一声。 + const envBrowser = process.env.MAGPIE_SENSENOVA_BROWSER; + if (envBrowser && !existsSync(envBrowser)) { + log(`MAGPIE_SENSENOVA_BROWSER 指定的浏览器不存在,已忽略: ${envBrowser}`); + } + if (process.env.__COMPAT_LAYER || process.env.COMPAT_LAYER) { + log("检测到兼容层变量,浏览器启动时会移除,避免 Edge 重启后丢失调试端口"); + } + + let child = null; + let profileDir = ""; + let portFile = ""; + let cdp = null; + + for (let idx = 0; idx < exes.length; idx++) { + const exe = exes[idx]; + profileDir = mkdtempSync(join(tmpdir(), "magpie-sensenova-login-")); + portFile = join(profileDir, "DevToolsActivePort"); + const args = [ + `--user-data-dir=${profileDir}`, + "--remote-debugging-port=0", + "--no-first-run", + "--no-default-browser-check", + // 隐私:把浏览器自己的后台联网关掉。登录窗口只该跟商汤通信——这几项关掉的是 + // 组件更新、实验变体、账号同步、崩溃上报、域名可靠性探测等浏览器自身的请求; + // 页面发起的请求(登录页、跳转)不受影响。收尾时整个 profile 目录删除。 + "--disable-background-networking", + "--disable-component-update", + "--disable-sync", + "--disable-default-apps", + "--no-service-autorun", + "--disable-breakpad", + "--no-pings", + "--window-size=480,800", + "about:blank", + ]; + if (headless) args.unshift("--headless=new"); + + log(headless ? `启动无头登录浏览器: ${exe}` : `打开登录窗口(${exe})`); + child = spawn(exe, args, { stdio: "ignore", env: browserEnv() }); + + try { + const port = await waitForDebugPort(portFile, child, 25_000); + log(`调试端口 ${port}`); + cdp = await Cdp.connect(port); + break; + } catch (e) { + killTree(child); + await sleep(300); + await removeProfile(profileDir); // 启动失败的清理必须等它做完,别留下含登录态的目录 + if (idx < exes.length - 1) { + log(`浏览器 ${exe} 启动失败(${e?.message ?? e}),尝试备选: ${exes[idx + 1]}`); + continue; + } + throw e; + } + } + + let settled = false; + let cleaned = false; + let timer = null; + let readyResolve = null; + const ready = new Promise((resolve) => { + readyResolve = resolve; + }); + + const cleanup = async () => { + if (cleaned) return; + cleaned = true; + if (timer) clearTimeout(timer); + cdp?.detach(); // 不关 ws:见 detach() 的说明 + killTree(child); + await sleep(600); // 让进程真的死透,再动 profile 目录 + if (!(await removeProfile(profileDir))) { + log(`临时 profile 没能删掉(不影响登录):${profileDir}`); + } + }; + + const result = new Promise((resolve, reject) => { + const ok = (value) => { + if (settled) return; + settled = true; + if (timer) clearTimeout(timer); + resolve(value); + }; + const fail = (error) => { + if (settled) return; + settled = true; + void cleanup().finally(() => reject(error instanceof Error ? error : new Error(String(error)))); + }; + + (async () => { + try { + await cdp.send("Page.enable"); + await cdp.send("Fetch.enable", { + patterns: [{ urlPattern: `*${callbackHost}*`, requestStage: "Request" }], + }); + + cdp.on((evt) => { + if (evt.method !== "Fetch.requestPaused") return; + void onPaused(evt.params, { cdp, expectedState, callbackHost, ok, fail, log }); + }); + cdp.onClose(() => fail(new Error("登录窗口被关闭了"))); + child.once("exit", () => fail(new Error("登录窗口被关闭了"))); + + timer = setTimeout(() => fail(new Error("登录超时:没有在浏览器里完成登录")), timeoutMs); + cdp.send("Page.navigate", { url: authorizeUrl }).catch((e) => log(`导航命令返回: ${e?.message ?? e}`)); + } catch (e) { + fail(e); + } finally { + readyResolve(cdp); + } + })(); + }); + result.catch(() => {}); // 用户取消时可能没人 await,这里兜住未处理拒绝 + + const navigate = async (url) => { + const client = await ready; + if (!client) throw new Error("浏览器没起来,无法导航"); + return client.send("Page.navigate", { url }); + }; + + return { result, close: cleanup, navigate, profileDir }; +} + +async function onPaused(params, ctx) { + const { cdp, expectedState, callbackHost, ok, fail, log } = ctx; + const { requestId, request } = params; + const url = request?.url ?? ""; + + let parsed = null; + try { + parsed = new URL(url); + } catch {} + + const code = parsed?.searchParams.get("code") ?? ""; + const error = parsed?.searchParams.get("error") ?? ""; + const state = parsed?.searchParams.get("state") ?? ""; + + // 不是回调:放行(授权请求本身、页面其它请求都会走到这里) + if (!parsed || parsed.hostname !== callbackHost || (!code && !error)) { + void cdp.send("Fetch.continueRequest", { requestId }).catch(() => {}); + return; + } + + if (expectedState && state !== expectedState) { + log("回调 state 与本会话不匹配,放行并继续等待"); + void cdp.send("Fetch.continueRequest", { requestId }).catch(() => {}); + return; + } + + if (error) { + const detail = parsed.searchParams.get("error_description") || error; + await fulfillPage(cdp, requestId, htmlPage("登录没有完成", detail, false)); + fail(new Error(`平台拒绝了这次登录:${detail}`)); + return; + } + + // 先替换页面(SPA 不执行),再交付 code——fulfill 失败不影响 code 有效性 + await fulfillPage(cdp, requestId, htmlPage("登录成功", "此窗口可以关闭,凭据正在交给 magpie。", true)); + log("已捕获授权码"); + ok({ code, state, redirectUrl: parsed.toString() }); +} + +async function fulfillPage(cdp, requestId, html) { + try { + await cdp.send("Fetch.fulfillRequest", { + requestId, + responseCode: 200, + responseHeaders: [{ name: "content-type", value: "text/html; charset=utf-8" }], + body: Buffer.from(html, "utf8").toString("base64"), + }); + } catch { + /* 窗口在最后一刻被关掉之类,忽略 */ + } +} diff --git a/packages/sensenova/lib/dpapi.mjs b/packages/sensenova/lib/dpapi.mjs new file mode 100644 index 0000000..392e76e --- /dev/null +++ b/packages/sensenova/lib/dpapi.mjs @@ -0,0 +1,172 @@ +/** + * DPAPI 密封:Windows 用户态加密(CryptProtectData / CryptUnprotectData)。 + * + * 落盘形状:plugin-auth.json 里的 refresh_token / access_token / API Key + * 以 "dpapi:" 存放——密文只有**当前 Windows 用户**能解开。 + * 别的用户、别的机器、拷走的文件都解不开;插件也不存账号密码。 + * + * 平台策略: + * - Windows:密封失败就报错(宁可不登录,不静默降级明文)。 + * - 非 Windows:回退明文并保持原样可读(README 有说明;目标平台是 Windows)。 + * - 不带 "dpapi:" 前缀的值一律按明文处理,方便手改/迁移。 + * + * 用 bun:ffi 调 crypt32.dll——magpie 的插件宿主就是 Bun,所以插件里可用; + * 动态 import 让本模块在 Node 下也能加载(只是密封会报错)。 + */ + +const PREFIX = "dpapi:"; + +/** + * FFI 用的常驻缓冲区。 + * + * 关键:Bun 的 ptr() 只给地址、不阻止 GC。任何"短命临时对象"(输入数据本体、 + * DATA_BLOB 结构体、输出结构体)都可能在系统调用期间被回收,让 DPAPI 读到 + * 已释放的内存——实测在内存压力下会返回失败或解出 4 字节乱码。这里把三个 + * 缓冲区全部放在模块级(生命周期与进程一致),held.data 在每次调用前指向输入。 + * 两个函数各自同步完成 FFI,不会交错,所以一组缓冲区就够。 + */ +const held = { + data: null, + inBlob: new Uint8Array(16), + outBlob: new Uint8Array(16), +}; + +/** 填 DATA_BLOB { DWORD cbData; BYTE *pbData; }(x64 下含 4 字节对齐填充)。 */ +function fillBlob(target, buf, ptr) { + const dv = new DataView(target.buffer); + dv.setUint32(0, buf.length, true); + dv.setBigUint64(8, BigInt(ptr(buf)), true); + return target; +} + +/** + * 读 DATA_BLOB 的输出,并交还系统分配的内存。 + * + * 关键:`toArrayBuffer()` 返回的是**视图**,不是拷贝——LocalFree 之后那块内存 + * 就可能被堆复用/覆盖(实测大尺寸密文的头部会被堆元数据改写,看起来像"魔数 + * 位移 8 字节")。所以必须先把字节拷出来,再 LocalFree。 + */ +function readBlob(target, toArrayBuffer, localFree) { + const dv = new DataView(target.buffer); + const size = dv.getUint32(0, true); + const p = dv.getBigUint64(8, true); + if (!p || !size) return null; + const out = Buffer.from(new Uint8Array(toArrayBuffer(Number(p), 0, size))); // new Uint8Array(arrayBuffer) 是拷贝 + localFree(Number(p)); + return out; +} + +let apiPromise = null; +let testApi; + +/** Tests force a working or a failing DPAPI; call with null to restore. */ +export function _setCryptoForTests(api) { + testApi = api; + apiPromise = null; +} + +/** 惰性初始化 crypt32/kernel32;非 Windows 返回 null。 */ +function crypt32() { + if (testApi !== undefined) { + if (testApi?.loadError) throw new Error(testApi.loadError); + return Promise.resolve(testApi); + } + if (!apiPromise) { + apiPromise = (async () => { + if (process.platform !== "win32") return null; + const { dlopen, FFIType, ptr, toArrayBuffer } = await import("bun:ffi"); + const { symbols } = dlopen("crypt32.dll", { + CryptProtectData: { + args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.u32, FFIType.ptr], + returns: FFIType.bool, + }, + CryptUnprotectData: { + args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.u32, FFIType.ptr], + returns: FFIType.bool, + }, + }); + const { symbols: k32 } = dlopen("kernel32.dll", { + LocalFree: { args: [FFIType.ptr], returns: FFIType.ptr }, + }); + + return { + protect(plain) { + held.data = Buffer.from(plain, "utf8"); + fillBlob(held.inBlob, held.data, ptr); + const ok = symbols.CryptProtectData(ptr(held.inBlob), null, null, null, null, 0, ptr(held.outBlob)); + const out = ok ? readBlob(held.outBlob, toArrayBuffer, k32.LocalFree) : null; + held.data = null; + if (!ok) throw new Error("CryptProtectData 调用失败"); + if (!out) throw new Error("CryptProtectData 没有返回密文"); + return out; + }, + unprotect(sealed) { + held.data = Buffer.from(sealed); + fillBlob(held.inBlob, held.data, ptr); + const ok = symbols.CryptUnprotectData(ptr(held.inBlob), null, null, null, null, 0, ptr(held.outBlob)); + const out = ok ? readBlob(held.outBlob, toArrayBuffer, k32.LocalFree) : null; + held.data = null; + if (!ok) throw new Error("CryptUnprotectData 调用失败"); + if (!out) throw new Error("CryptUnprotectData 没有返回明文"); + return out; + }, + }; + })().catch((e) => { + throw new Error(`Windows DPAPI 初始化失败: ${e?.message ?? e}`); + }); + } + return apiPromise; +} + +/** 是否为 DPAPI 密封值。 */ +export function isSealed(value) { + return typeof value === "string" && value.startsWith(PREFIX); +} + +/** + * 密封一个字符串。空值原样返回(空串没有密封的意义)。 + * + * Windows 上 DPAPI 不可用时回退明文并记录原因:0.1.3 的用户 profile 里本来 + * 就是明文,硬抛错会让他们的每次刷新都失败、而且被永久重试。非 Windows 同样 + * 回退明文(与 0.1.3 行为一致)。 + */ +export async function seal(value, { log } = {}) { + const text = typeof value === "string" ? value : value == null ? "" : String(value); + if (!text) return ""; + let api = null; + try { + api = await crypt32(); + } catch (e) { + log?.( + "warn", + `sensenova: DPAPI could not be loaded (${e?.message ?? e}); storing the credential in plaintext, as 0.1.x did`, + ); + return text; + } + if (!api) return text; // non-Windows: plaintext, same as 0.1.3 + try { + return PREFIX + api.protect(text).toString("base64"); + } catch (e) { + log?.( + "warn", + `sensenova: DPAPI cannot seal in this Windows session (${e?.message ?? e}); ` + + `storing the credential in plaintext, as 0.1.x did`, + ); + return text; + } +} + +/** + * 解开一个密封值。明文(无前缀)原样返回,方便手改过的 auth 文件继续可用。 + */ +export async function unseal(value) { + const text = typeof value === "string" ? value : value == null ? "" : String(value); + if (!text || !text.startsWith(PREFIX)) return text; + const api = await crypt32(); + if (!api) throw new Error("这是 Windows DPAPI 密封的凭据,但当前环境没有 DPAPI,无法解开"); + try { + return api.unprotect(Buffer.from(text.slice(PREFIX.length), "base64")).toString("utf8"); + } catch { + throw new Error("凭据解密失败:DPAPI 密文不属于当前 Windows 用户(换机器/换用户后需要重新登录)"); + } +} diff --git a/packages/sensenova/lib/keys.mjs b/packages/sensenova/lib/keys.mjs new file mode 100644 index 0000000..aa4c034 --- /dev/null +++ b/packages/sensenova/lib/keys.mjs @@ -0,0 +1,208 @@ +/** + * Token Plan API keys: naming, reuse, creation and the 20-key guard. + * + * Keys created here are named `magpie---