sensenova 0.2.0: browser sign-in, plan-filtered models and credit-pool isolation (#730)

sensenova 0.2.0 (yunwang2442-creator): a browser sign-in that captures the console's
OAuth redirect in a one-off Chromium and reuses or creates a `magpie-<host>-<account>-*`
Token Plan API key; the password sign-in kept as a headless fallback; models filtered
to the account's plan; the Flash-Lite pool kept apart from the general pool. Credentials
are sealed with DPAPI on Windows and stored as plaintext elsewhere, as 0.1.3 stored them.
When DPAPI fails, the value is stored as plaintext and the reason is logged.

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

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

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

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

Not tried: a real sign-in (no SenseNova account here, no credentials entered). The
author reports real browser, password, refresh and 0.1.3-upgrade runs on Windows 10
and WSL2 Ubuntu (Node 24) on the PR.
This commit is contained in:
我是一条没有名字的区
2026-11-05 02:45:52 +08:00
committed by GitHub
parent 5112465ca1
commit 6a0d9e5b7a
18 changed files with 3088 additions and 871 deletions
+1 -1
View File
@@ -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` |
+68 -72
View File
@@ -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-<host>-<账号哈希>-…`:**另一台机器的、
或另一个 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-<host>-<account-hash>-…`. 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
+14 -2
View File
@@ -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)
})
+67
View File
@@ -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)
}
})
File diff suppressed because it is too large Load Diff
+82
View File
@@ -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([])
})
+507
View File
@@ -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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
}
function htmlPage(title, body, ok) {
return `<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><title>${escapeHtml(title)}</title>
<style>
:root { color-scheme: dark light; }
body { margin:0; min-height:100vh; display:grid; place-items:center;
font:15px/1.7 system-ui, "Segoe UI", "Microsoft YaHei", sans-serif;
background:#0f1115; color:#e8e8ea; }
main { text-align:center; padding:0 32px; max-width:420px; }
.badge { width:64px; height:64px; margin:0 auto 18px; border-radius:50%;
display:grid; place-items:center; font-size:32px;
background:${ok ? "rgba(52,199,123,.15)" : "rgba(255,92,92,.15)"}; }
h1 { font-size:19px; margin:0 0 8px; font-weight:600; }
p { margin:0; color:#9aa0a6; font-size:13.5px; }
</style></head>
<body><main><div class="badge">${ok ? "✅" : "⚠️"}</div><h1>${escapeHtml(title)}</h1><p>${escapeHtml(body)}</p></main></body></html>`;
}
/** 极简 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<void>}>}
* 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 {
/* 窗口在最后一刻被关掉之类,忽略 */
}
}
+172
View File
@@ -0,0 +1,172 @@
/**
* DPAPI 密封:Windows 用户态加密(CryptProtectData / CryptUnprotectData)。
*
* 落盘形状:plugin-auth.json 里的 refresh_token / access_token / API Key
* 以 "dpapi:<base64>" 存放——密文只有**当前 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 用户(换机器/换用户后需要重新登录)");
}
}
+208
View File
@@ -0,0 +1,208 @@
/**
* Token Plan API keys: naming, reuse, creation and the 20-key guard.
*
* Keys created here are named `magpie-<host>-<account>-<time>-<random>`:
* - the host tag keeps another machine's keys out of this machine's prune;
* - the account tag is a hash, not the account name, so the console's key
* list does not carry the user's identity;
* - the random part comes from crypto, not Math.random.
*/
import { randomBytes } from "node:crypto";
import { hostname } from "node:os";
import {
createApiKey,
createdApiKey,
deleteApiKey,
keyFingerprint,
listApiKeys,
probeApiKey,
} from "./protocol.mjs";
export const KEY_LIMIT = 20;
/** 8 hex chars: enough that two machines do not collide, short enough for a key name. */
export const HOST_TAG = keyFingerprint(hostname() || "host").slice(0, 8);
// 8 hex chars: a 4-char tag collides for two accounts on one host with
// probability 1/65536, and a collision would let them reuse each other's keys.
const accountTag = (username) => keyFingerprint(username || "account").slice(0, 8);
const randomTag = () => randomBytes(2).toString("hex");
const stamp = () => new Date().toISOString().slice(0, 16).replace(/[-:T]/g, "");
/** A key name that carries no account name and no Math.random. */
export function keyNameFor(username) {
return `${keyPrefix(username)}${stamp()}-${randomTag()}`.slice(0, 64);
}
/** The name prefix this account's keys share: host tag plus account tag. */
export function keyPrefix(username) {
return `magpie-${HOST_TAG}-${accountTag(username)}-`;
}
const at = (value) => {
const n = Date.parse(String(value ?? ""));
return Number.isFinite(n) ? n : 0;
};
/** New-key validation: the gateway needs 3–10s before a new key answers. */
export async function probeWithRetry(apiKey, baseURL, log) {
const delays = [0, 1500, 3000, 4500, 6000];
let last = null;
for (let i = 0; i < delays.length; i++) {
if (delays[i]) await new Promise((r) => setTimeout(r, delays[i]));
try {
return await probeApiKey(apiKey, baseURL);
} catch (e) {
last = e;
if (e?.status !== 401 && e?.status !== 403) throw e;
log?.("info", `sensenova: the new key is still taking effect (try ${i + 1}, HTTP ${e.status})`);
}
}
throw last;
}
/** How many keys the account has, counting the array if total_count is absent. */
export async function keyCount(access) {
const listed = await listApiKeys(access, { pageSize: 20 });
const count = (listed?.api_keys ?? []).filter((k) => k && k.id).length;
return Math.max(Number(listed?.total_count ?? listed?.total_size ?? 0) || 0, count);
}
/**
* An existing key this machine can reuse: the newest key of this account
* (`magpie-<host>-<account>-*`) whose plaintext the list returned and which
* the vendor still accepts. Scoped by the account tag so a key that belongs
* to another saved account is never borrowed.
*/
export async function findReusableKey(access, baseURL, { username = "" } = {}) {
let listed;
try {
listed = await listApiKeys(access, { pageSize: 20 });
} catch {
return "";
}
const rows = (listed?.api_keys ?? []).filter((k) => k && k.id && typeof k.api_key === "string" && k.api_key);
const ours = rows
.filter((k) => String(k.displayname ?? "").startsWith(keyPrefix(username)))
.sort((a, b) => at(b.create_time) - at(a.create_time));
for (const k of ours) {
try {
if (await probeApiKey(k.api_key, baseURL)) return k.api_key;
} catch (e) {
if (e?.status !== 401 && e?.status !== 403) return "";
}
}
return "";
}
/** Delete a key this sign-in created when it could not be validated. */
export async function cleanupKey(access, created, keyName, log) {
try {
if (created?.id) {
await deleteApiKey(access, created.id);
return;
}
const listed = await listApiKeys(access, { pageSize: 20 });
const match = (listed?.api_keys ?? []).find((k) => k.displayname === keyName);
if (match?.id) await deleteApiKey(access, match.id);
} catch (e) {
log?.("warn", `sensenova: could not clean up the failed key (${e?.message ?? e})`);
}
}
/**
* Prune this account's old keys only.
*
* The candidate set is `magpie-<host>-<account>-*`: a key another saved
* account on this machine still uses is never in it, whatever prune is asked
* to free.
*
* freeSlots = 0: keep the newest two.
* freeSlots > 0: free that many slots for a new key, oldest first.
* The key in use (by its last 4) and the key just created never go; a key
* whose create_time cannot be parsed is never deleted (its age is unknown).
*/
export async function pruneKeys(access, { username = "", keyName = "", activeSuffix = "", freeSlots = 0, log } = {}) {
let deleted = 0;
try {
const listed = await listApiKeys(access, { pageSize: 20 });
const rows = (listed?.api_keys ?? []).filter((k) => k && k.id);
const prefix = keyPrefix(username);
const ours = rows
.filter((k) => String(k.displayname ?? "").startsWith(prefix))
.sort((a, b) => at(b.create_time) - at(a.create_time));
if (!ours.length) return 0;
const protectedIds = new Set();
if (keyName) {
const fresh = ours.find((k) => k.displayname === keyName);
if (fresh?.id) protectedIds.add(fresh.id);
}
if (activeSuffix) {
for (const k of rows) {
if (String(k.api_key ?? "").endsWith(activeSuffix)) protectedIds.add(k.id);
}
}
const keep = new Set([...ours.slice(0, 2).map((k) => k.id), ...protectedIds]);
const candidates = ours
.filter((k) => !protectedIds.has(k.id) && at(k.create_time) > 0)
.sort((a, b) => at(a.create_time) - at(b.create_time));
for (const k of candidates) {
if (freeSlots > 0 ? deleted >= freeSlots : keep.has(k.id)) continue;
await deleteApiKey(access, k.id)
.then(() => {
deleted += 1;
})
.catch((e) => log?.("warn", `sensenova: pruning a key failed (${e?.message ?? e})`));
}
const skipped = ours.filter((k) => !protectedIds.has(k.id) && at(k.create_time) <= 0);
if (skipped.length) {
log?.("warn", `sensenova: skipped ${skipped.length} key(s) whose create_time cannot be parsed`);
}
} catch (e) {
log?.("warn", `sensenova: key pruning skipped (${e?.message ?? e})`);
}
return deleted;
}
/**
* Reuse a valid key, or create one (with the 20-key guard and optional prune).
* Throws {code:"key_limit"} when the account is full and pruning cannot help.
*/
export async function ensureKey(access, username, { baseURL, prune = false, log } = {}) {
const reused = await findReusableKey(access, baseURL, { username });
if (reused) return reused;
const total = await keyCount(access);
if (total >= KEY_LIMIT) {
const err = new Error(
`this account already has ${total} API keys (the limit is ${KEY_LIMIT}). ` +
`Delete one in the console's API Keys page, then sign in again; ` +
`the plugin never deletes a key before it knows which one is yours.`,
);
err.code = "key_limit";
throw err;
}
const keyName = keyNameFor(username);
const created = await createApiKey(access, keyName);
const apiKey = createdApiKey(created);
if (!apiKey) {
await cleanupKey(access, created, keyName, log);
throw new Error("the console created a key but did not return it; use an API key instead");
}
try {
await probeWithRetry(apiKey, baseURL, log);
} catch (e) {
if (e?.status === 401 || e?.status === 403) {
await cleanupKey(access, created, keyName, log);
throw new Error(`the new API key was refused (HTTP ${e.status}); use an API key instead`);
}
log?.("warn", `sensenova: the new key's check did not finish (${e?.message ?? e})`);
}
if (prune) await pruneKeys(access, { username, keyName, activeSuffix: apiKey.slice(-4), log });
return apiKey;
}
+484
View File
@@ -0,0 +1,484 @@
/**
* 模型目录:Token Plan 的聊天模型清单。
*
* 事实来源分两层:
* 1. 官网文档(platform.sensenova.cn/docs)给出「哪些模型能聊天、输入输出是什么」;
* 2. 活的 `GET /v1/models` 给出当前部署的上下文、输出上限、价格与能力字段。
*
* 两者不一致时,**能力以文档为准、上限以接口为准**。原因很具体:
* - `/v1/models` 对 `deepseek-flash` 只写 text,但官网明确它支持图片和视频(视频仅 Chat);
* - `/v1/models` 对 `kimi-k3` 只写 text,但官网说它有原生视觉能力;
* - `/v1/models` 还会多出 `deepseek-v4.1-flash` 这种实际 403 的杂项。
*
* 所以内置清单不是“兜底占位”,而是目录的骨架;接口只用来覆盖上限/价格/描述。
*/
export const NPM = "@ai-sdk/openai-compatible";
export const DEFAULT_BASE_URL = "https://token.sensenova.cn/v1";
const DEFAULT_CONTEXT = 1_048_576;
const DEFAULT_OUTPUT = 65_536;
/**
* 实测的 `max_tokens` 合法上界(不是营销数字,也不等于模型实际会生成这么长)。
*
* 2026-10-29 用真实账号发 `max_tokens: 400000`,接口返回
* `field MaxTokens invalid, should be in [1, N]`,N 即下表。
* `/v1/models` 的 `max_output_length` 对这两个模型是 65,536,会把 agent
* 能请求的输出人为截短;所以实测值优先于 live,Kimi 因持续 429 未测,保持 live。
*/
export const MEASURED_OUTPUT_LIMITS = {
"deepseek-flash": { value: 393_216, measuredAt: "2026-10-29", evidence: "[1, 393216]" },
"deepseek-v4-flash": { value: 384_000, measuredAt: "2026-10-29", evidence: "[1, 384000]" },
};
/** 官网模型表里能走 Chat Completions 的模型。 */
export const CHAT_MODELS = [
{
id: "sensenova-6.8-flash-lite",
name: "SenseNova 6.8 Flash Lite",
contextLength: 262_144,
maxCompletionTokens: 65_536,
inputModalities: ["text", "image"],
outputModalities: ["text"],
supportsTools: true,
reasoning: true,
efforts: ["none", "low", "medium", "high", "max"],
description:
"SenseNova 6.8 Flash-Lite is a lightweight multimodal agent model designed for real-world workflows, supporting text conversation and image input understanding.",
},
{
id: "deepseek-v4-flash",
name: "DeepSeek V4 Flash",
contextLength: 1_048_576,
maxCompletionTokens: 384_000,
inputModalities: ["text"],
outputModalities: ["text"],
supportsTools: true,
reasoning: true,
efforts: ["none", "low", "high", "max"],
description:
"DeepSeek V4 Flash is a high-performance conversational model by DeepSeek, supporting thinking/non-thinking modes, 1M context window, and tool calling.",
},
{
id: "deepseek-flash",
name: "DeepSeek V4.1 Flash",
contextLength: 1_048_576,
maxCompletionTokens: 393_216,
// 官网:文本、图片、视频;视频仅 Chat Completions。
inputModalities: ["text", "image", "video"],
outputModalities: ["text"],
supportsTools: true,
reasoning: true,
efforts: ["none", "low", "high", "max"],
description:
"DeepSeek V4.1 Flash is a high-performance conversational model by DeepSeek, supporting thinking/non-thinking modes, 1M context window, image/video input (video on Chat), and tool calling.",
},
{
id: "glm-5.2",
name: "GLM-5.2",
contextLength: 1_048_576,
maxCompletionTokens: 131_072,
inputModalities: ["text"],
outputModalities: ["text"],
supportsTools: true,
reasoning: true,
efforts: ["none", "low", "high", "max"],
description:
"GLM-5.2 is the flagship model for the era of long-horizon tasks, with a 1M context window and thinking/non-thinking modes.",
},
{
id: "kimi-k3",
name: "Kimi K3",
contextLength: 1_048_576,
maxCompletionTokens: 65_536,
// 官网:原生视觉能力;/v1/models 只写 text,以文档为准。
inputModalities: ["text", "image"],
outputModalities: ["text"],
supportsTools: true,
reasoning: true,
efforts: ["none", "low", "high", "max"],
description:
"Kimi K3 is a high-performance native multimodal agent model by Kimi, with visual understanding, a 1M context window, and tool calling.",
},
];
/** 图像生成模型:不进入 Chat 目录(magpie 的 chat provider 不服务 /v1/images/*)。 */
export const IMAGE_MODELS = [
{
id: "sensenova-u1.5-lite",
name: "SenseNova U1.5 Lite",
contextLength: 262_144,
maxCompletionTokens: 65_536,
inputModalities: ["text", "image"],
outputModalities: ["image"],
supportsTools: false,
reasoning: false,
efforts: [],
},
{
id: "sensenova-u1.5-fast",
name: "SenseNova U1.5 Fast",
contextLength: 262_144,
maxCompletionTokens: 65_536,
inputModalities: ["text", "image"],
outputModalities: ["image"],
supportsTools: false,
reasoning: false,
efforts: [],
},
];
/** `/v1/models` 里会冒出来、但不属于 Token Plan 的 id。 */
export const STRAY_MODEL_IDS = ["deepseek-v4.1-flash"];
/** 兜底清单(登录前 / 拉取失败时)。也叫“骨架清单”。 */
export const FALLBACK_MODELS = [...CHAT_MODELS, ...IMAGE_MODELS];
const positive = (v) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Number(v) : undefined);
const text = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
const list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : undefined);
const bool = (v) => (typeof v === "boolean" ? v : v === "true" ? true : v === "false" ? false : undefined);
const unique = (xs) => [...new Set(xs)];
const known = (id) => CHAT_MODELS.find((m) => m.id === id);
const imageModel = (id) => IMAGE_MODELS.find((m) => m.id === id);
/** 归一化一条模型记录(兼容 snake_case / camelCase 两种拼写)。 */
export function normalizeModel(raw) {
if (!raw || typeof raw !== "object") return null;
const id = text(raw.id) ?? text(raw.model_id) ?? text(raw.model);
if (!id) return null;
const curated = known(id);
const image = imageModel(id);
const liveInput = list(raw.input_modalities ?? raw.inputModalities);
const liveOutput = list(raw.output_modalities ?? raw.outputModalities);
const features = list(raw.supported_features ?? raw.supportedFeatures) ?? [];
// 能力取“文档 ∪ 接口”:文档补上接口漏掉的图片/视频,接口补上文档没写的新能力。
const inputModalities = unique([...(curated?.inputModalities ?? image?.inputModalities ?? []), ...(liveInput ?? [])]);
const outputModalities = unique([...(curated?.outputModalities ?? image?.outputModalities ?? []), ...(liveOutput ?? [])]);
const supportsTools =
bool(raw.supports_tools) ??
bool(raw.supportsTool) ??
bool(raw.tool_call) ??
(features.includes("tools") ? true : undefined) ??
curated?.supportsTools ??
false;
const reasoning =
bool(raw.reasoning) ??
bool(raw.supports_reasoning) ??
(features.includes("reasoning") ? true : undefined) ??
curated?.reasoning ??
false;
const efforts = reasoning ? (curated?.efforts ?? ["none", "low", "high", "max"]) : [];
const created = positive(raw.created);
// created 是 unix 秒;毫秒级时间戳或超大值会算出离谱年份甚至 Invalid Date,
// 直接 toISOString 会抛 RangeError——夹在 2000–2200 年之间,超界就放弃。
let released = "";
if (created) {
const date = new Date(created * 1000);
const year = date.getUTCFullYear();
if (Number.isFinite(year) && year > 2000 && year < 2200) released = date.toISOString().slice(0, 10);
}
return {
id,
name: curated?.name ?? image?.name ?? text(raw.name) ?? text(raw.model_name) ?? id,
contextLength:
positive(raw.context_length ?? raw.contextLength ?? raw.max_context_tokens) ??
curated?.contextLength ??
DEFAULT_CONTEXT,
maxCompletionTokens:
MEASURED_OUTPUT_LIMITS[id]?.value ??
positive(
raw.max_output_length ??
raw.max_output_tokens ??
raw.maxCompletionTokens ??
raw.max_completion_tokens ??
raw.max_output_tokens,
) ??
curated?.maxCompletionTokens ??
DEFAULT_OUTPUT,
inputModalities: inputModalities.length ? inputModalities : ["text"],
outputModalities: outputModalities.length ? outputModalities : ["text"],
supportsTools,
reasoning,
efforts,
description: text(raw.description) ?? curated?.description ?? "",
released,
};
}
/** 从各式信封里取出模型数组({data:[…]} / {models:[…]} / 裸数组)。
* 单条坏记录只丢自己,不能让整批清单失败(否则活清单静默变兜底)。 */
export function extractModels(payload) {
const rows = Array.isArray(payload)
? payload
: Array.isArray(payload?.data)
? payload.data
: Array.isArray(payload?.models)
? payload.models
: [];
return rows
.map((row) => {
try {
return normalizeModel(row);
} catch {
return null;
}
})
.filter(Boolean);
}
/** 只保留能走 Chat Completions 的模型:有文本输出、不是图像模型、不是杂项 id。 */
export function isChatModel(m) {
if (!m || typeof m !== "object") return false;
if (STRAY_MODEL_IDS.includes(m.id)) return false;
const outputs = m.outputModalities ?? ["text"];
return outputs.includes("text");
}
export function chatModels(models) {
return (models ?? []).filter(isChatModel);
}
/** 图像生成模型:output 含 image;magpie 的 Drawers 会从 provider.models 里挑。 */
export function isImageModel(m) {
if (!m || typeof m !== "object") return false;
const outputs = m.outputModalities ?? [];
return outputs.includes("image") && !outputs.includes("text");
}
/**
* provider.models / config 的目录:聊天 +(宿主支持时)图像,杂项 id 仍过滤。
* OpenCode 的 provider 不列 image-only 模型(上游惯例),magpie 的 Drawers 需要它们。
*/
export function catalogModels(models, { images = true } = {}) {
return (models ?? []).filter(
(m) => !STRAY_MODEL_IDS.includes(m?.id) && (isChatModel(m) || (images && isImageModel(m))),
);
}
/**
* 收窄到控制台计划池覆盖的模型。covered 为空集时返回空数组(计划明确说没有可调用的模型):
*
*/
export function filterByPlan(models, covered) {
const ids = covered instanceof Set ? covered : new Set(Array.isArray(covered) ? covered : []);
// An empty set means the plan names no models: nothing is listed, not everything.
return (models ?? []).filter((m) => ids.has(m?.id));
}
/**
* 拉一次、按账号缓存一段时间的模型目录。
*
* 缓存必须按 API Key 分桶:provider.models 是按账号调用的,A 账号的清单
* 不能给 B 账号用 6 小时;并发请求也不该 join 另一个账号的 in-flight。
* 失败时保留该账号上次成功的清单;空清单做 30 秒负缓存,避免新 Key 生效前风暴。
*/
export function createCatalog({ baseURL = DEFAULT_BASE_URL, timeoutMs = 15_000, refreshMs = 6 * 3600_000, fetchImpl } = {}) {
const root = baseURL.replace(/\/+$/, "");
const doFetch = fetchImpl ?? fetch;
let lastCached = null;
const buckets = new Map();
const bucketFor = (apiKey) => {
let bucket = buckets.get(apiKey);
if (!bucket) {
bucket = { cached: null, fetchedAt: 0, inflight: null, emptyAt: 0 };
buckets.set(apiKey, bucket);
}
return bucket;
};
return {
baseURL: root,
/** 最近一次任意账号成功列表(没有则 null);只用于登录前的 config 播种。 */
peek: () => lastCached,
async raw(apiKey) {
await this.load(apiKey);
const b = bucketFor(apiKey);
return b.raw ?? [];
},
async load(apiKey) {
if (!apiKey) throw new Error("没有 API Key");
const bucket = bucketFor(apiKey);
const now = Date.now();
if (bucket.cached && now - bucket.fetchedAt < refreshMs) return bucket.cached;
if (bucket.inflight) return bucket.inflight;
if (bucket.emptyAt && now - bucket.emptyAt < 30_000) return bucket.cached ?? [];
bucket.inflight = (async () => {
try {
const res = await doFetch(`${root}/models`, {
headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },
signal: AbortSignal.timeout(timeoutMs),
});
if (!res.ok) {
const err = new Error(`GET /models → HTTP ${res.status}`);
err.status = res.status;
throw err;
}
const body = await res.json();
// raw rows keep the catalogue as authority for the listing path;
// normalized rows (curated ∪ live) stay for the bootstrap config.
const rawRows = (Array.isArray(body) ? body : Array.isArray(body?.data) ? body.data : []).filter(Boolean);
const models = extractModels(body);
if (models.length) {
bucket.cached = models;
bucket.raw = rawRows;
bucket.fetchedAt = Date.now();
bucket.emptyAt = 0;
lastCached = models;
} else {
bucket.emptyAt = Date.now();
}
return models.length ? models : (bucket.cached ?? []);
} catch (e) {
// 瞬时失败保留上次成功清单;没有就交给调用方兜底。
if (bucket.cached) return bucket.cached;
throw e;
} finally {
bucket.inflight = null;
}
})();
return bucket.inflight;
},
};
}
/* ------------------------------------------------------- magpie 对象形状 */
const hasNonTextInput = (m) => (m.inputModalities ?? []).some((modality) => modality !== "text");
function modalityFlags(modalities) {
const l = list(modalities) ?? ["text"];
return {
text: l.includes("text"),
image: l.includes("image"),
audio: l.includes("audio"),
video: l.includes("video"),
pdf: l.includes("pdf"),
};
}
/**
* 推理档位:每个 key 是档位,value 是该协议真正要发的参数。
* Chat 用 reasoningEffort;Anthropic 用 thinking/output_config;Responses 只留 none。
*/
function variantsOf(m, protocol = "chat") {
if (m.reasoning !== true) return {};
const efforts = Array.isArray(m.efforts) && m.efforts.length ? m.efforts : ["none", "low", "high"];
const out = {};
for (const level of efforts.filter((x) => ["none", "low", "high"].includes(x))) {
if (protocol === "responses") {
if (level === "none") out[level] = { reasoningEffort: "none" };
continue;
}
if (protocol === "anthropic") {
out[level] =
level === "none"
? { thinking: { type: "disabled" } }
: { thinking: { type: "enabled" }, output_config: { effort: level } };
continue;
}
out[level] = { reasoningEffort: level };
}
return out;
}
/** 按 wire 协议裁掉视频:只有 Chat Completions 支持视频。 */
function inputsFor(m, video) {
const inputs = m.inputModalities ?? ["text"];
return video === false ? inputs.filter((x) => x !== "video") : inputs;
}
/** `config` 里声明一条模型。 */
export function toConfigModel(m, { video = true, protocol = "chat" } = {}) {
const inputs = inputsFor(m, video);
const out = {
name: m.name,
reasoning: m.reasoning === true,
tool_call: m.supportsTools === true,
attachment: hasNonTextInput({ inputModalities: inputs }),
modalities: { input: inputs, output: m.outputModalities },
limit: { context: m.contextLength, output: m.maxCompletionTokens },
};
const variants = variantsOf(m, protocol);
if (Object.keys(variants).length) out.variants = variants;
return out;
}
/** `provider.models` 返回的一条模型。 */
export function toProviderModel(m, providerID, { baseURL = DEFAULT_BASE_URL, npm = NPM, video = true, protocol = "chat" } = {}) {
const inputs = inputsFor(m, video);
return {
id: m.id,
providerID,
name: m.name,
api: { id: m.id, url: baseURL.replace(/\/+$/, ""), npm },
status: "active",
headers: {},
options: {},
cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
limit: { context: m.contextLength, output: m.maxCompletionTokens },
capabilities: {
temperature: true,
reasoning: m.reasoning === true,
attachment: hasNonTextInput({ inputModalities: inputs }),
toolcall: m.supportsTools === true,
input: modalityFlags(inputs),
output: modalityFlags(m.outputModalities),
interleaved: false,
},
release_date: m.released ?? "",
variants: variantsOf(m, protocol),
};
}
/**
* 给“用回了兜底清单”的返回打标记:magpie 据此在界面上说明
* "这是插件自己的缺省清单,不是这家现在给你的清单"。
*/
export function fellBack(map) {
const out = { ...map };
out[Symbol.for("magpie.fellBack")] = true;
return out;
}
/**
* A catalogue row as the provider lists it (the shape api.test.mjs reads).
* The reasoning tiers are the catalogue's own supported_features gate: a model
* that stops reasoning stops offering tiers. The tier set is deliberately the
* common three (none/low/high): the platform publishes no per-model list, and
* a wrong tier is answered loudly with a 400 rather than silently.
*/
export function modelOf(row) {
const r = row ?? {};
const features = Array.isArray(r.supported_features) ? r.supported_features : [];
const reasoning = r.reasoning !== undefined ? r.reasoning === true : features.includes("reasoning");
const image = Array.isArray(r.input_modalities) ? r.input_modalities.includes("image") : false;
const out = {
id: r.id,
name: r.name || r.id,
limit: { context: r.context ?? 0, output: r.output ?? 0 },
reasoning,
tool_call: features.includes("tools"),
modalities: { input: image ? ["text", "image"] : ["text"], output: ["text"] },
capabilities: {
reasoning,
toolcall: true,
attachment: image,
input: { text: true, image },
output: { text: true },
},
...(reasoning ? { variants: { none: { reasoningEffort: "none" }, low: { reasoningEffort: "low" }, high: { reasoningEffort: "high" } } } : {}),
};
return out;
}
+307
View File
@@ -0,0 +1,307 @@
/**
* The console's password sign-in: the OIDC walk the console's own SPA uses,
* with the password sealed into a JWE before it leaves this machine.
*
* This is the method the upstream package shipped. It is kept as the headless
* fallback; the browser method does not send a password anywhere.
*/
import { createPkce } from "./pkce.mjs";
import { CLIENT_ID, ENDPOINTS, REDIRECT_URI, SCOPE, cleanDetail, tokenHeaders } from "./protocol.mjs";
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 ENC_KEY_ID = "public:hydra.openid.id-token";
const b64url = (bytes) => Buffer.from(bytes).toString("base64url");
const hostOf = (url) => {
try {
return new URL(url).hostname.toLowerCase();
} catch {
return "";
}
};
/** The hosts the walk may visit; the endpoint origins are always allowed. */
const PLATFORM_HOSTS = [/(^|\.)sensenova\.cn$/, /(^|\.)sensecore\.cn$/, /(^|\.)sensecoreapi\.cn$/];
function allowedHost(url) {
let u;
try {
u = new URL(url);
} catch {
return false;
}
const sameOrigin = (e) => {
try {
const x = new URL(e);
return x.host === u.host && x.protocol === u.protocol;
} catch {
return false;
}
};
if (Object.values(ENDPOINTS).some(sameOrigin)) return true;
if (u.protocol !== "https:") return false;
return PLATFORM_HOSTS.some((re) => re.test(u.hostname));
}
/**
* A cookie jar that honours Domain, Path and expiry. The console's Hydra
* cookies can be domain-scoped, and a Max-Age=0 must delete one.
*/
function newJar() {
return new Map(); // name -> { value, domain, path, expires }
}
function collectCookies(response, jar, url) {
const host = hostOf(url);
if (!host) return;
const lines = typeof response.headers.getSetCookie === "function" ? response.headers.getSetCookie() : [];
for (const line of lines) {
const parts = String(line).split(";");
const pair = parts[0] ?? "";
const attrs = parts.slice(1);
const eq = pair.indexOf("=");
if (eq <= 0) continue;
const name = pair.slice(0, eq).trim();
const value = pair.slice(eq + 1).trim();
let domain = host;
let path = "/";
let expires = Infinity;
for (const raw of attrs) {
const [k, ...rest] = raw.trim().split("=");
const v = rest.join("=").trim();
const key = k.toLowerCase();
if (key === "domain" && v) domain = v.replace(/^\./, "").toLowerCase();
else if (key === "path" && v) path = v;
else if (key === "max-age" && /^-?\d+$/.test(v)) {
const s = Number(v);
expires = s <= 0 ? 0 : Date.now() + s * 1000;
} else if (key === "expires" && v) {
const t = Date.parse(v);
if (Number.isFinite(t)) expires = t;
}
}
if (expires <= Date.now()) jar.delete(name);
else jar.set(name, { value, domain, path, expires });
}
}
function cookieHeader(jar, url) {
let u;
try {
u = new URL(url);
} catch {
return "";
}
const host = u.hostname.toLowerCase();
const path = u.pathname || "/";
const now = Date.now();
const out = [];
for (const [name, c] of jar) {
if (c.expires <= now) {
jar.delete(name);
continue;
}
const domainOk = host === c.domain || host.endsWith(`.${c.domain}`);
const pathOk = path === c.path || path.startsWith(c.path.endsWith("/") ? c.path : `${c.path}/`);
if (domainOk && pathOk) out.push(`${name}=${c.value}`);
}
return out.join("; ");
}
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) });
}
function resolveUrl(value, base) {
try {
return new URL(value, base).href;
} catch {
return value;
}
}
/** Find the next hop in a client-rendered body, resolving relative URLs. */
function nextFromBody(body, wanted, base) {
if (!body) return "";
const found = [];
for (const m of body.matchAll(/https?:\/\/[^"'\s<>]+[?&][^"'\s<>]*/g)) found.push(m[0]);
const meta = /<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 raw of found) {
const u = resolveUrl(raw, base);
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++) {
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 !== "" ? resolveUrl(next, location) : nextFromBody(await res.text(), wanted, location);
}
if (location && wanted.test(location)) {
if (!allowedHost(location)) throw new Error(`the sign-in walk left the SenseNova hosts for ${location}`);
return location;
}
return "";
}
/** Seal the password into the 5-segment compact JWE the IAM endpoint wants. */
async function sealPassword(password) {
const res = await fetch(ENDPOINTS.jwks, {
headers: { accept: "application/json", "user-agent": UA },
signal: AbortSignal.timeout(TIMEOUT_MS),
});
if (!res.ok) throw new Error(`JWKS endpoint: HTTP ${res.status}`);
const keys = (await res.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(".");
}
/** The walk's pure guards, exposed for the tests through index._internal. */
export const walkInternals = { allowedHost, newJar, cookieHeader, collectCookies, followUntil };
function iamHeaders() {
return {
"content-type": "application/json",
"user-agent": UA,
accept: "application/json",
origin: ENDPOINTS.console,
referer: `${ENDPOINTS.console}/`,
"sec-fetch-site": "same-origin",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
};
}
/**
* Sign in with the console account and password. Returns access/refresh/expires
* plus `tokenHost: "password"`, so refresh() knows which token endpoint answers.
*/
export 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 } = createPkce();
const nonce = b64url(crypto.getRandomValues(new Uint8Array(16)));
const authUrl =
`${ENDPOINTS.console}/oauth2/auth?` +
new URLSearchParams({
client_id: CLIENT_ID,
code_challenge: challenge,
code_challenge_method: "S256",
redirect_uri: REDIRECT_URI,
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 paramOf = (url, name) => {
try {
return new URL(url).searchParams.get(name) ?? "";
} catch {
return "";
}
};
const loginChallenge = paramOf(challengeUrl, "login_challenge");
if (!loginChallenge) throw new Error("could not obtain a login challenge from the authorization endpoint");
const encrypted = await sealPassword(secret);
const iamRes = await fetch(`${ENDPOINTS.iam}/iam/authn/v1/auth/nova/login`, {
method: "POST",
headers: { ...iamHeaders(), cookie: cookieHeader(jar, ENDPOINTS.iam) },
body: JSON.stringify({ username: user, password: encrypted, challenge: loginChallenge, is_encrypt: true }),
redirect: "manual",
signal: AbortSignal.timeout(TIMEOUT_MS),
});
const iamBody = await iamRes.json().catch(() => ({}));
const redirect = iamBody?.redirect ?? "";
if (!iamRes.ok || !redirect) {
const reason = iamBody?.details?.find?.((d) => d?.reason)?.reason ?? iamBody?.message ?? `HTTP ${iamRes.status}`;
throw Object.assign(new Error(`login refused: ${cleanDetail(reason)}`), {
kind: /locked|disabled|tooMany|rateLimit|tooManyRequests/i.test(String(reason)) ? "retryable" : "credential",
});
}
const codeUrl = await followUntil(resolveUrl(redirect, ENDPOINTS.iam), /[?&]code=/, jar);
const code = paramOf(codeUrl, "code");
const state = paramOf(codeUrl, "state");
if (!code) throw new Error("callback ended without an authorization code");
if (state !== nonce) throw new Error("callback state did not match the issued nonce");
const tokenRes = await fetch(ENDPOINTS.token, {
method: "POST",
headers: tokenHeaders(),
body: new URLSearchParams({
grant_type: "authorization_code",
code,
code_verifier: verifier,
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
scope: SCOPE,
}).toString(),
redirect: "manual",
signal: AbortSignal.timeout(TIMEOUT_MS),
});
const body = await tokenRes.json().catch(() => ({}));
if (!tokenRes.ok || !body.access_token) {
throw new Error(
`token exchange failed: ${cleanDetail(body.error_description ?? body.error ?? `HTTP ${tokenRes.status}`)}`,
);
}
return {
access: body.access_token,
refresh: body.refresh_token ?? "",
expires: Date.now() + (Number(body.expires_in) || 10800) * 1000,
tokenHost: "password",
};
}
+23
View File
@@ -0,0 +1,23 @@
/**
* PKCE:一次登录会话的码对与 state。
*
* 标准 PKCE(与平台授权端点的参数一致):
* verifier = base64url(48 随机字节) → 64 字符,在 43–128 限制内
* challenge = base64url(SHA256(verifier))
* state = base64url(16 随机字节) → 22 字符
* Go 用 base64.RawURLEncoding,等价于这里的 "base64url"(无填充、URL 安全表)。
*/
import { createHash, randomBytes } from "node:crypto";
/** base64url 无填充随机串(与 Go 的 base64.RawURLEncoding 一致)。 */
export function randomString(bytes) {
return randomBytes(bytes).toString("base64url");
}
/** 一次登录会话的 PKCE 码对与 state。 */
export function createPkce() {
const verifier = randomString(48);
const challenge = createHash("sha256").update(verifier, "utf8").digest("base64url");
return { verifier, challenge, state: randomString(16) };
}
+343
View File
@@ -0,0 +1,343 @@
/**
* The platform's endpoints, its OAuth flows, and the console's own APIs.
*
* ENDPOINTS is a mutable object on purpose: the tests point it at a local fake
* (the same shape `fake.mjs` uses), so no test can reach the real platform.
* Production code reads the values at call time, never at import time.
*/
import { createHash } from "node:crypto";
export const ENDPOINTS = {
console: "https://platform.sensenova.cn",
// The password sign-in's IAM and token hosts (the console's own OIDC walk).
iam: "https://iam.sensecoreapi.cn",
token: "https://signin.sensecore.cn/oauth2/token",
jwks: "https://signin.sensecore.cn/.well-known/jwks.json",
// The browser sign-in's token host, which is the console origin.
platformToken: "https://platform.sensenova.cn/oauth2/token",
api: "https://token.sensenova.cn/v1",
};
export const CLIENT_ID = "nova";
export const REDIRECT_URI = "https://platform.sensenova.cn";
export const SCOPE = "openid offline offline_access";
export const TOKEN_PLAN_KEY_TYPE = "API_KEY_TYPE_TOKEN_PLAN";
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";
/** The browser sign-in's authorize endpoint (the console's own OAuth). */
export const authorizeUrl = () => `${ENDPOINTS.console}/oauth2/auth`;
/** The browser sign-in's token endpoint. */
export const browserTokenUrl = () => `${ENDPOINTS.console}/oauth2/token`;
/** The password sign-in's token endpoint (IAM's Hydra). */
export const passwordTokenUrl = () => ENDPOINTS.token;
/** The console's credit-pool endpoint. */
export const poolUsageUrl = () => `${ENDPOINTS.console}/lite/console/v1/tokenplan/pool-usage`;
/** The Token Plan API-key endpoint. */
export const apiKeysUrl = () => `${ENDPOINTS.console}/lite/console/v1/metered/api-keys`;
/** The OpenAI-compatible base the API key speaks to. */
export const apiBase = () => ENDPOINTS.api;
/** Protocol errors carry the HTTP status and the vendor's OAuth error code. */
export class ProtocolError extends Error {
constructor(message, { status = 0, code = "" } = {}) {
super(message);
this.name = "ProtocolError";
this.status = status;
this.code = code;
}
get invalidGrant() {
return this.code === "invalid_grant";
}
}
/**
* Vendor text goes into logs and the account card, so it must not carry a
* credential. Only token-shaped runs are masked; the diagnostic words stay.
*/
const SECRETISH =
/(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9._-]{10,}[A-Za-z0-9._-]*|Bearer\s+(?:eyJ[A-Za-z0-9._-]{10,}|sk-[A-Za-z0-9-]{8,})|(?:refresh|access|id)_token["'=:\s]*[A-Za-z0-9._-]{20,}|sk-[A-Za-z0-9-]{20,})/gi;
export function cleanDetail(value) {
return String(value ?? "").replace(SECRETISH, "***");
}
function clientHints() {
return {
"user-agent": UA,
"sec-ch-ua": '"Chromium";v="152", "Not;A=Brand";v="24", "Google Chrome";v="152"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
};
}
/** The token endpoints' browser-shaped headers (the platform's WAF expects them). */
export function tokenHeaders() {
return {
"content-type": "application/x-www-form-urlencoded",
accept: "application/json",
origin: ENDPOINTS.console,
referer: `${ENDPOINTS.console}/`,
"sec-fetch-site": "same-origin",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
...clientHints(),
};
}
/** The console APIs' browser-shaped headers. */
export function consoleHeaders(accessToken) {
return {
authorization: `Bearer ${accessToken}`,
accept: "application/json",
"content-type": "application/json",
origin: ENDPOINTS.console,
referer: `${ENDPOINTS.console}/console/keys`,
"sec-fetch-site": "same-origin",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
...clientHints(),
};
}
/** The credit-pool endpoint's headers. */
export function quotaHeaders(accessToken) {
return {
authorization: `Bearer ${accessToken}`,
accept: "application/json",
referer: `${ENDPOINTS.console}/console`,
"sec-fetch-site": "same-origin",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
...clientHints(),
};
}
/** The browser sign-in URL (PKCE, prompt=login so a stale console session can't answer). */
export function buildAuthorizeUrl({ challenge, state }) {
const q = new URLSearchParams();
q.set("client_id", CLIENT_ID);
q.set("response_type", "code");
q.set("code_challenge", challenge);
q.set("code_challenge_method", "S256");
q.set("redirect_uri", REDIRECT_URI);
q.set("state", state);
q.set("scope", SCOPE);
q.set("prompt", "login");
return `${authorizeUrl()}?${q.toString()}`;
}
export function exchangeForm(code, verifier) {
const form = new URLSearchParams();
form.set("grant_type", "authorization_code");
form.set("client_id", CLIENT_ID);
form.set("code", code);
form.set("redirect_uri", REDIRECT_URI);
form.set("code_verifier", verifier);
return form;
}
export function refreshForm(refreshToken) {
const form = new URLSearchParams();
form.set("grant_type", "refresh_token");
form.set("client_id", CLIENT_ID);
form.set("refresh_token", refreshToken);
return form;
}
async function postToken(url, form, { timeoutMs = 20_000 } = {}) {
let res;
try {
res = await fetch(url, {
method: "POST",
headers: tokenHeaders(),
body: form,
redirect: "manual",
signal: AbortSignal.timeout(timeoutMs),
});
} catch (e) {
throw new ProtocolError(`token endpoint: ${cleanDetail(e?.message ?? e)}`);
}
const text = await res.text().catch(() => "");
let json = null;
try {
json = JSON.parse(text);
} catch {
/* a non-JSON body is handled by its status */
}
if (!res.ok || json?.error) {
const code = typeof json?.error === "string" ? json.error : "";
const detail = cleanDetail(json?.error_description || text.slice(0, 200).trim() || `HTTP ${res.status}`);
throw new ProtocolError(`token endpoint: ${detail}`, { status: res.status, code });
}
if (!json || typeof json !== "object") {
throw new ProtocolError("token endpoint returned non-JSON", { status: res.status });
}
return json;
}
/** Exchange the browser's authorization code with our PKCE verifier. */
export function exchangeCode({ code, verifier, timeoutMs }) {
return postToken(browserTokenUrl(), exchangeForm(code, verifier), { timeoutMs });
}
/** Renew a browser sign-in's token pair (Hydra rotates the refresh token). */
export function refreshTokens(refreshToken, { timeoutMs } = {}) {
return postToken(browserTokenUrl(), refreshForm(refreshToken), { timeoutMs });
}
/** Renew a password sign-in's token pair (IAM's Hydra). */
export function refreshPasswordTokens(refreshToken, { timeoutMs } = {}) {
return postToken(passwordTokenUrl(), refreshForm(refreshToken), { timeoutMs });
}
/** Read the console's credit pools. */
export async function fetchPoolUsage(accessToken, { timeoutMs = 20_000 } = {}) {
let res;
try {
res = await fetch(poolUsageUrl(), {
headers: quotaHeaders(accessToken),
signal: AbortSignal.timeout(timeoutMs),
});
} catch (e) {
throw new ProtocolError(`credit-pool endpoint: ${cleanDetail(e?.message ?? e)}`);
}
if (res.status === 401 || res.status === 403) {
throw new ProtocolError(`credit-pool endpoint refused the session (HTTP ${res.status})`, { status: res.status });
}
if (!res.ok) throw new ProtocolError(`credit-pool endpoint: HTTP ${res.status}`, { status: res.status });
try {
return await res.json();
} catch {
throw new ProtocolError("credit-pool endpoint returned non-JSON", { status: res.status });
}
}
/** Decode a JWT payload; the token came from the vendor, so no signature check. */
export function jwtPayload(token) {
const parts = String(token ?? "").trim().split(".");
if (parts.length !== 3) return null;
try {
return JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
} catch {
return null;
}
}
/** The console account's name and stable uid. */
export function identityFromTokens(tokens) {
const claims = jwtPayload(tokens?.access_token) ?? {};
const id = jwtPayload(tokens?.id_token) ?? {};
const nested = id?.id_token ?? {};
const pick = (...values) => {
for (const value of values) if (typeof value === "string" && value.trim()) return value.trim();
return "";
};
return {
username: pick(
claims?.ext?.username,
claims?.username,
nested?.username,
claims?.preferred_username,
claims?.email,
),
uid: pick(claims?.sub, claims?.user_id, nested?.sub, nested?.user_id),
};
}
/** A stable short fingerprint for names and cache buckets. */
export function keyFingerprint(value) {
return createHash("sha256").update(String(value ?? "")).digest("hex").slice(0, 12);
}
/** Trim a pasted key: spaces, a stray `Bearer `, and wrapping quotes. */
export function normalizeApiKey(value) {
let s = String(value ?? "").trim();
if (/^bearer\s+/i.test(s)) s = s.replace(/^bearer\s+/i, "");
return s.replace(/^["'`]|["'`]$/g, "").trim();
}
/** A best-effort key check: only 401/403 says the key is invalid. */
export async function probeApiKey(apiKey, baseURL = apiBase(), { timeoutMs = 10_000 } = {}) {
const res = await fetch(`${String(baseURL).replace(/\/+$/, "")}/models`, {
headers: { authorization: `Bearer ${apiKey}`, accept: "application/json" },
signal: AbortSignal.timeout(timeoutMs),
});
if (res.status === 401 || res.status === 403) {
throw new ProtocolError(`API key refused (HTTP ${res.status})`, { status: res.status });
}
return res.ok;
}
/* ------------------------------------------------------- console API keys */
async function consoleJson(url, accessToken, init = {}, { timeoutMs = 20_000 } = {}) {
let res;
try {
res = await fetch(url, {
...init,
headers: consoleHeaders(accessToken),
signal: AbortSignal.timeout(timeoutMs),
});
} catch (e) {
throw new ProtocolError(`console request failed: ${cleanDetail(e?.message ?? e)}`);
}
const text = await res.text().catch(() => "");
let json = null;
try {
json = JSON.parse(text);
} catch {
/* status-only response */
}
if (!res.ok) {
const detail = cleanDetail(
json?.message || json?.error_description || json?.error || text.slice(0, 200).trim() || `HTTP ${res.status}`,
);
throw new ProtocolError(`console refused the request (HTTP ${res.status}): ${detail}`, { status: res.status });
}
if (!json || typeof json !== "object") {
throw new ProtocolError("console returned non-JSON", { status: res.status });
}
return json;
}
export function listApiKeys(accessToken, { timeoutMs, pageSize = 1 } = {}) {
const q = new URLSearchParams({ key_type: TOKEN_PLAN_KEY_TYPE, page_size: String(pageSize) });
return consoleJson(`${apiKeysUrl()}?${q.toString()}`, accessToken, { method: "GET" }, { timeoutMs });
}
export function createApiKey(accessToken, displayname, { timeoutMs } = {}) {
return consoleJson(
apiKeysUrl(),
accessToken,
{ method: "POST", body: JSON.stringify({ displayname, key_type: TOKEN_PLAN_KEY_TYPE }) },
{ timeoutMs },
);
}
export async function deleteApiKey(accessToken, id, { timeoutMs = 20_000 } = {}) {
let res;
try {
res = await fetch(`${apiKeysUrl()}/${encodeURIComponent(id)}`, {
method: "DELETE",
headers: consoleHeaders(accessToken),
signal: AbortSignal.timeout(timeoutMs),
});
} catch (e) {
throw new ProtocolError(`delete API key failed: ${cleanDetail(e?.message ?? e)}`);
}
if (res.ok) return true;
if (res.status === 404) return false;
const text = await res.text().catch(() => "");
throw new ProtocolError(
`delete API key failed (HTTP ${res.status}): ${cleanDetail(text.slice(0, 200).trim())}`,
{ status: res.status },
);
}
export function createdApiKey(payload) {
return String(payload?.api_key_plain ?? payload?.api_key ?? "").trim();
}
+172
View File
@@ -0,0 +1,172 @@
/**
* pool-usage → the windows magpie's account card draws.
*
* The console sends every number as a string and reset_at as epoch seconds.
* A window's `used` is the spent share; when the console leaves `used` out,
* limit - remaining is the fallback, and a window with neither is skipped
* rather than shown as 0% (which would read as "nothing spent").
*
* The general pool covers Flash-Lite too, but Flash-Lite is spent from its
* own pool first. The general window therefore carries `notModels` for the
* dedicated pool's ids, so a full general pool does not gate Flash-Lite
* while the dedicated pool still has room.
*
* Grants (grant_balance) are a balance that expires, not a spent window.
* Several granted pools add up; the earliest expiry is the one told.
*/
/** Tolerant number: "600000" / 591300.256 / null; negatives to 0. */
export function flexNum(value) {
const n = typeof value === "number" ? value : Number(String(value ?? "").trim() || 0);
return Number.isFinite(n) && n > 0 ? n : 0;
}
function optionalNum(value) {
if (value === null || value === undefined) return undefined;
const s = String(value).trim();
if (!s) return undefined;
const n = Number(s);
return Number.isFinite(n) ? n : undefined;
}
export function flexInt(value) {
const n = Math.trunc(flexNum(value));
return n > 0 ? n : 0;
}
/** Up to two decimals, no thousands separators (the card adds its own). */
export function compact(n) {
const v = Number(n);
if (!Number.isFinite(v) || v <= 0) return "0";
const s = v.toFixed(2).replace(/\.?0+$/, "");
return s === "" ? "0" : s;
}
const isoOf = (seconds) => (seconds > 0 ? new Date(seconds * 1000).toISOString() : undefined);
function isDedicated(pool) {
const t = String(pool?.pool_type ?? "").toLowerCase();
const name = String(pool?.name ?? "").toLowerCase();
return t === "dedicated" || t === "flash" || name.includes("flash") || name.includes("专属");
}
/** The ids a dedicated pool serves when the console does not list them. */
const FLASH_LITE_IDS = ["sensenova-6.7-flash-lite", "sensenova-6.8-flash-lite"];
function scopeOf(pool, dedicated, dedicatedIds) {
const ids = Array.isArray(pool?.model_ids) ? pool.model_ids.filter((x) => typeof x === "string" && x) : [];
if (dedicated) return ids.length ? { models: ids } : { model: "flash-lite" };
// The general window keeps its own `models` (the GUI groups by them) and
// adds `notModels` for the dedicated ids, so a full general pool does not
// gate Flash-Lite while its own pool still has room.
return { ...(ids.length ? { models: ids } : {}), ...(dedicatedIds.length ? { notModels: [...dedicatedIds] } : {}) };
}
/** Pools from either `{data:{pools}}` or top-level `{pools}`. */
export function poolsOf(raw) {
if (Array.isArray(raw?.data?.pools)) return raw.data.pools;
if (Array.isArray(raw?.pools)) return raw.pools;
return [];
}
export function toUsage(raw, { username = "", planFallback = "Token Plan" } = {}) {
const pools = poolsOf(raw);
if (!Array.isArray(raw?.data?.pools) && !Array.isArray(raw?.pools)) {
// not the console's shape at all: a failed read, not an empty plan
const detail = raw?.error?.message ?? raw?.message ?? raw?.error;
throw new Error(
typeof detail === "string" && detail ? `pool-usage: ${detail}` : "pool-usage returned no credit pools",
);
}
// The GUI draws the first two windows as meters; the default pool goes first.
const ordered = [...pools].sort((a, b) => (isDedicated(a) ? 1 : 0) - (isDedicated(b) ? 1 : 0));
const dedicatedIds = [
...new Set(
ordered
.filter(isDedicated)
.flatMap((p) => {
const ids = Array.isArray(p?.model_ids) ? p.model_ids.filter((x) => typeof x === "string" && x) : [];
return ids.length ? ids : FLASH_LITE_IDS;
}),
),
];
const windows = [];
let grantsTotal = 0;
let expiryAt = 0;
for (const pool of ordered) {
const dedicated = isDedicated(pool);
const scope = scopeOf(pool, dedicated, dedicatedIds);
const label =
typeof pool?.name === "string" && pool.name.trim() ? pool.name.trim() : dedicated ? "Dedicated pool" : "General pool";
for (const [w, tag, span] of [
[pool?.window_5h, "5 hours", 5 * 3600],
[pool?.window_7d, "7 days", 7 * 24 * 3600],
]) {
const limit = flexNum(w?.limit);
if (limit <= 0) continue;
const usedAmount = optionalNum(w?.used);
const remaining = optionalNum(w?.remaining);
const amount =
usedAmount !== undefined
? Math.max(0, usedAmount)
: remaining !== undefined
? Math.max(0, limit - remaining)
: undefined;
if (amount === undefined) continue;
const resetsAt = isoOf(flexInt(w?.reset_at));
const round = (n) => Math.round(n * 100) / 100;
windows.push({
name: `${label} · ${tag}`,
used: (amount / limit) * 100,
...(resetsAt ? { resetsAt } : {}),
display: `${compact(amount)} / ${compact(limit)}`,
amount: round(amount),
limit: round(limit),
unit: "credits",
span,
...scope,
});
}
// Grants are a balance that expires, not a spent window. Several granted
// pools add up (the dedicated pool carries its own grant too, as 0.1.3
// read it); the earliest expiry is the one told.
const grant = flexNum(pool?.grant_balance);
if (grant > 0) {
grantsTotal += grant;
const expiry = flexInt(pool?.nearest_grant_expiry);
if (expiry > 0 && (!expiryAt || expiry < expiryAt)) expiryAt = expiry;
}
}
const plan = raw?.data?.plan?.name ?? raw?.plan?.name;
const planName = typeof plan === "string" && plan.trim() ? plan.trim() : planFallback;
if (!(grantsTotal > 0)) return {
plan: planName,
...(username ? { user: username } : {}),
windows,
};
const count = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });
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 {
plan: planName,
...(username ? { user: username } : {}),
windows,
balance: `${count.format(grantsTotal)} 积分${day ? ` · ${day} 到期` : ""}`,
};
}
/** The pools-array entry point (the card read routes through toUsage). */
export function usageOf(pools) {
return toUsage({ pools });
}
+7 -6
View File
@@ -1,14 +1,17 @@
{
"name": "@magpie-community/opencode-sensenova-auth",
"version": "0.1.3",
"description": "SenseNova (SenseTime 日日新) Token Plan in OpenCode and magpie: one sign-in gives the console account's credit pools, windows and grants, and (with an optional API key) the plan's models for chat",
"version": "0.2.0",
"description": "SenseNova (SenseTime 日日新) Token Plan in OpenCode and magpie: browser or password sign-in for the credit pools, windows and grants, plus the plan's models through a Token Plan API key",
"type": "module",
"main": "./opencode.mjs",
"exports": { ".": "./opencode2.mjs" },
"exports": {
".": "./opencode2.mjs"
},
"files": [
"index.mjs",
"opencode.mjs",
"opencode2.mjs",
"lib/",
"README.md"
],
"keywords": [
@@ -30,8 +33,6 @@
"directory": "packages/sensenova"
},
"magpie": {
"options": {
"signin": false
}
"maxConcurrency": 1
}
}
+72 -14
View File
@@ -5,6 +5,7 @@
import "./nonet.mjs"
import { afterEach, expect, test } from "bun:test"
import { SenseNovaAuthPlugin, _internal } from "./index.mjs"
import { _setCryptoForTests, unseal } from "./lib/dpapi.mjs"
import { fakeSenseNova, json, jwksOf } from "./fake.mjs"
let f
@@ -13,7 +14,7 @@ afterEach(() => f?.close())
// one sign-in, start to finish, against whatever the fake answers
const signIn = async () => {
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
return p.auth.methods[0].authorize({ username: "u", password: "secret", apiKey: "" }).callback()
return p.auth.methods[1].authorize({ username: "u", password: "secret", apiKey: "" }).callback()
}
// the JWKS the fake serves (a real RSA key the seal can encrypt to)
@@ -70,15 +71,15 @@ test("a password is sealed into a JWE and the tokens come back", async () => {
return json({ access_token: "jwt-123", refresh_token: "r-123", expires_in: 10800 })
})
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const m = p.auth.methods[0]
const m = p.auth.methods[1]
const r = m.authorize({ username: "yiheng13", password: "secret", apiKey: "sk-abc" })
const out = await r.callback()
expect(out.type).toBe("success")
expect(out.access).toBe("jwt-123")
expect(out.refresh).toBe("r-123")
expect(await unseal(out.access)).toBe("jwt-123")
expect(await unseal(out.refresh)).toBe("r-123")
expect(out.accountId).toBe("yiheng13")
// the API key rides along on the account
expect(out.apiKey).toBe("sk-abc")
expect(await unseal(out.apiKey)).toBe("sk-abc")
})
test("a password the platform refuses is a failed sign-in, its reason kept", async () => {
@@ -89,7 +90,7 @@ test("a password the platform refuses is a failed sign-in, its reason kept", asy
json({ message: "InvalidArgument", details: [{ "@type": "x", reason: "invalidAccountOrPassword" }] }, 400),
)
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const m = p.auth.methods[0]
const m = p.auth.methods[1]
const r = m.authorize({ username: "yiheng13", password: "wrong", apiKey: "" })
const out = await r.callback()
expect(out.type).toBe("failed")
@@ -106,8 +107,8 @@ test("a refresh token is renewed, and the new one replaces the old", async () =>
})
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const renewed = await p.auth.refresh({ type: "oauth", access: "old", refresh: "old-r", expires: Date.now() + 1000 })
expect(renewed.access).toBe("jwt-2")
expect(renewed.refresh).toBe("new-r")
expect(await unseal(renewed.access)).toBe("jwt-2")
expect(await unseal(renewed.refresh)).toBe("new-r")
})
test("a refresh token the platform has revoked says the sign-in is gone", async () => {
@@ -118,7 +119,7 @@ test("a refresh token the platform has revoked says the sign-in is gone", async
// (host.js: e?.signIn === "expired"); without it the dead token is retried
// every RENEW_RETRY (30 s) and the account never asks to be signed in again
const err = await p
.auth.refresh({ type: "oauth", access: "old", refresh: "dead", expires: Date.now() + 1000 })
.auth.refresh({ type: "oauth", access: "old", refresh: "dead", expires: Date.now() + 1000, tokenHost: "password" })
.then(() => null, (e) => e)
expect(err).toBeInstanceOf(Error)
expect(err.dead).toBe(true)
@@ -137,7 +138,7 @@ test("a refresh that fails for any reason other than a dead token keeps the sign
for (const [status, error] of [[500, "server_error"], [400, "invalid_request"]]) {
f.route("POST " + TOKEN_PATH, () => json({ error }, status))
const err = await p
.auth.refresh({ type: "oauth", access: "old", refresh: "r", expires: Date.now() + 1000 })
.auth.refresh({ type: "oauth", access: "old", refresh: "r", expires: Date.now() + 1000, tokenHost: "password" })
.then(() => null, (e) => e)
expect(err).toBeInstanceOf(Error)
expect(err.dead).toBe(false)
@@ -154,7 +155,7 @@ test("a walk that leaves the SenseNova hosts is refused, not followed", async ()
new Response(null, { status: 302, headers: { location: "https://not-sensenova.example/continue" } }),
)
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const out = await p.auth.methods[0].authorize({ username: "u", password: "p", apiKey: "" }).callback()
const out = await p.auth.methods[1].authorize({ username: "u", password: "p", apiKey: "" }).callback()
expect(out.type).toBe("failed")
expect(out.error).toContain("SenseNova hosts")
})
@@ -171,7 +172,7 @@ test("a page body pointing off-site is not taken as the next hop", async () => {
}),
)
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const out = await p.auth.methods[0].authorize({ username: "u", password: "p", apiKey: "" }).callback()
const out = await p.auth.methods[1].authorize({ username: "u", password: "p", apiKey: "" }).callback()
expect(out.type).toBe("failed")
expect(out.error).toContain("login challenge")
})
@@ -186,7 +187,7 @@ test("a hop carrying what the walk seeks, on another domain, is not the answer",
new Response(null, { status: 302, headers: { location: "https://evil.example/?login_challenge=stolen&state=x" } }),
)
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const out = await p.auth.methods[0].authorize({ username: "u", password: "p", apiKey: "" }).callback()
const out = await p.auth.methods[1].authorize({ username: "u", password: "p", apiKey: "" }).callback()
expect(out.type).toBe("failed")
expect(out.error).toContain("SenseNova hosts")
})
@@ -200,7 +201,7 @@ test("a downgraded http:// hop to a SenseNova domain is refused", async () => {
new Response(null, { status: 302, headers: { location: "http://platform.sensenova.cn/continue" } }),
)
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const out = await p.auth.methods[0].authorize({ username: "u", password: "p", apiKey: "" }).callback()
const out = await p.auth.methods[1].authorize({ username: "u", password: "p", apiKey: "" }).callback()
expect(out.type).toBe("failed")
expect(out.error).toContain("SenseNova hosts")
})
@@ -242,3 +243,60 @@ test("a code exchange answered with a 307 does not replay the code and verifier"
expect((await signIn()).type).toBe("failed")
expect(f.seen.some((r) => r.path === "/elsewhere")).toBe(false)
})
test("an account saved by 0.1.3 (plaintext, no tokenHost) still refreshes and serves its key", async () => {
// 0.1.3 wrote access/refresh/apiKey as plaintext and never wrote a tokenHost.
// The upgrade must read that record as-is: no re-login, no reinstall. A record
// with no tokenHost refreshes at the password endpoint, which is the one
// 0.1.3 itself used.
f = fakeSenseNova()
f.route("POST " + TOKEN_PATH, (r) => {
expect(r.form?.grant_type).toBe("refresh_token")
expect(r.form?.refresh_token).toBe("plain-r")
return json({ access_token: "jwt-new", refresh_token: "plain-r2", expires_in: 10800 })
})
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const legacy = {
type: "oauth",
access: "plain-jwt",
refresh: "plain-r",
expires: Date.now() + 1000,
accountId: "alice",
apiKey: "sk-legacy",
}
const renewed = await p.auth.refresh(legacy)
expect(await unseal(renewed.access)).toBe("jwt-new")
expect(await unseal(renewed.refresh)).toBe("plain-r2")
const loader = await p.auth.loader(async () => legacy)
expect(loader.apiKey).toBe("sk-legacy")
expect(loader.baseURL).toBe(f.origin)
})
test("a Windows session whose DPAPI refuses still refreshes, storing plaintext as 0.1.3 did", async () => {
// CryptProtectData can fail for a roaming profile or a session without the
// user's credentials. Throwing there makes every refresh fail forever with
// no sign-in prompt, so the value falls back to plaintext (0.1.3's storage)
// and the reason is logged.
f = fakeSenseNova()
f.route("POST " + TOKEN_PATH, () => json({ access_token: "jwt-2", refresh_token: "new-r", expires_in: 10800 }))
const logs = []
_setCryptoForTests({
protect() {
throw new Error("Access is denied")
},
unprotect() {
throw new Error("Access is denied")
},
})
try {
const p = await SenseNovaAuthPlugin({
client: { auth: { set: async () => {} }, app: { log: async ({ body }) => logs.push(body) } },
})
const renewed = await p.auth.refresh({ type: "oauth", access: "old", refresh: "old-r", expires: Date.now() + 1000 })
expect(renewed.access).toBe("jwt-2")
expect(renewed.refresh).toBe("new-r")
expect(logs.some((l) => String(l?.message ?? "").includes("DPAPI"))).toBe(true)
} finally {
_setCryptoForTests(null)
}
})
+13 -1
View File
@@ -69,12 +69,24 @@ test("the real catalogue's own fields are what the models declare", async () =>
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const models = await p.provider.models({ id: "sensenova-token-plan", models: {} }, { auth })
const byId = Object.fromEntries(MODELS.data.map((m) => [m.id, m]))
// deepseek output limits are the measured max_tokens bounds, not the
// catalogue's conservative max_output_length (2026-10-29, a real account:
// [1, 393216] / [1, 384000]); the catalogue's own numbers would cut an
// agent's output to a sixth
const MEASURED = { "deepseek-flash": 393216, "deepseek-v4-flash": 384000 };
for (const id of Object.keys(models)) {
expect(models[id].limit).toEqual({ context: byId[id].context_length, output: byId[id].max_output_length })
expect(models[id].limit).toEqual({
context: byId[id].context_length,
output: MEASURED[id] ?? byId[id].max_output_length,
})
const takesImage = byId[id].input_modalities.includes("image")
expect(models[id].capabilities.input.image).toBe(takesImage)
expect(models[id].modalities.input).toEqual(takesImage ? ["text", "image"] : ["text"])
}
// the model that only draws is left out of a chat provider's listing (the
// browser host would list it for magpie's Drawers; this plugin instance has
// no magpie input, so the chat convention holds)
expect(models["sensenova-u1.5-lite"]).toBeUndefined()
})
test("the bootstrap list is a subset of what the plan and catalogue agree on", async () => {
+1 -1
View File
@@ -64,7 +64,7 @@
{ "package": "@magpie-community/opencode-raccoon-auth", "name": "商汤小浣熊", "icon": "sensenova-color", "providers": ["raccoon"], "community": true,
"summary": { "en": "SenseTime Raccoon (xiaohuanxiong.com) models, account credits and daily check-in, with browser sign-in or Raccoon desktop's live sign-in.", "zh": "商汤小浣熊(xiaohuanxiong.com)模型、积分余额与每日签到,支持浏览器登录或直接复用小浣熊桌面端登录态。" } },
{ "package": "@magpie-community/opencode-sensenova-auth", "name": "SenseNova", "icon": "sensenova-color", "providers": ["sensenova-token-plan"], "community": true,
"summary": { "en": "SenseNova (SenseTime 日日新) Token Plan: one console sign-in reads the credit pools, their 5-hour and 7-day windows and the expiring grants, and — with an API key pasted at sign-in — serves the plan's own models for chat.", "zh": "商汤日日新 Token Plan:一次控制台登录即可读取积分池、5 小时 / 7 天窗口与将过期的返赠余额;登录时粘贴 API Key,同一个账号就能直接调用计划内模型对话。" } },
"summary": { "en": "SenseNova (SenseTime 日日新) Token Plan: a browser sign-in (or the console account and password) reads the credit pools, their 5-hour and 7-day windows and the expiring grants, and serves the plan's own models — the browser sign-in reuses or creates a Token Plan API key for you.", "zh": "商汤日日新 Token Plan:浏览器登录(或控制台账号密码)读取积分池、5 小时 / 7 天窗口与将过期的返赠余额,并直接调用计划内模型——浏览器登录会自动复用或创建 Token Plan API Key。" } },
{ "package": "@magpie-community/opencode-autoclaw-auth", "name": "AutoClaw", "providers": ["autoclaw", "autoclaw-cn"], "community": true,
"summary": { "en": "AutoClaw (Zhipu OpenClaw) cloud accounts: oversea web sign-in (Google/z.ai) or CN phone SMS, credit balance and daily check-in.", "zh": "AutoClaw(智谱澳龙/OpenClaw)云端账号:国际版网页登录(Google/z.ai)或国内手机验证码,积分余额与每日签到。" } },
{ "package": "@magpie-community/opencode-codearts-auth", "name": "CodeArts / OfficeAce", "providers": ["codearts", "officeace"], "community": true,