inkstone 0.1.3: image-caps preflight, a zero-prompt browser sign-in, key calls on the session cookie (#832)

inkstone 0.1.3 (#832, yunwang2442-creator):

- Image requests are prechecked before they leave: 8 images, 10MB each, 40MB in all.
  - A request over a cap gets a local 400 shape refusal, so magpie asks the next account and rests none.
  - The plan's invalid_media / media_fetch_failed / unsupported_media_type errors become the same kind of refusal.
- The body rewrite strips the reasoning fields and sets image detail to auto.
- A zero-prompt browser sign-in comes first, and a second browser method reuses a pasted key.
  - Neither browser method is offered when no Chromium-family browser is found (#825).
- The /keys calls ride the session cookie, without the pagination query. Key creation retries the console's -15100 "refresh page and retry".
- The #826 metadata token read is kept, and its test is back.
- The fake browser is built once per user and source hash (#824), and the title wait reads only on Windows.
- maxConcurrency is 4.
- The doubled comment line is dropped from every opencode2.mjs copy, agy-cli's included.

Reviewed at 88e66bde, on mote (macOS, Bun 1.4.2) with a temp HOME:
- full bun test: 6853 pass / 0 fail; both checks exit 0
- bun scripts/check.mjs and bun scripts/check.mjs inkstone: exit 0
- 21 hand breaks: 20 red, 1 not caught (the /keys pagination test calls protocol.listKeys directly; follow-up filed)

Not tried: a real InkStone account or sign-in, Windows and Linux runs.
This commit is contained in:
我是一条没有名字的区
2026-11-07 22:24:56 +08:00
committed by GitHub
parent d34785ae88
commit 087c36123d
51 changed files with 964 additions and 176 deletions
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
+127 -29
View File
@@ -23,6 +23,30 @@
API Key 是可选的:不填,账号仍显示额度,只是不服务模型。填了,同一个账号
既显示额度、又服务对话。
## 登录方式
| 方式 | 做什么 | 产出 |
|---|---|---|
| **浏览器登录(推荐)** | **零提示**:点一下就直接开窗。用**插件自己的专用浏览器 profile** 打开控制台,你在里面登录(密码 / 短信 / 扫码),登录完成后自动创建 `ink-*` API Key。**Windows** 上插件用窗口标题判断登录完成、**自己关窗**;**macOS / Linux** 读不了窗口标题,登录完成后请**自己关掉窗口**,插件接着自动收尾。之后的续期/重登都静默完成 | 额度 + 模型 |
| **浏览器登录 + 复用已有 Key** | 同上,但开窗前会先问一句要不要粘贴现有 Key(留空则新建) | 额度 + 模型 |
| **仅 API Key** | 只粘贴 Key;`GET /v1/models` 探活 | 只有模型 |
| **API Key + 控制台 token** | 粘贴 Key,再粘贴 `uaa-token=…` 那一项(DevTools → Application → Cookies,复制整条 `uaa-token=…` 即可,插件只取值) | 额度 + 模型 |
> 浏览器登录需要本机装有 Microsoft Edge、Google Chrome 或 Chromium(可以用 `MAGPIE_INKSTONE_BROWSER` 指定路径)。Safari 用不了:插件要在单独的浏览器 profile 里登录,Safari 不支持。没有这些浏览器时,选「仅 API Key」,或「API Key + 控制台 token」(token 可以从任何浏览器里复制,包括 Safari)。
>
> 不读、不动你日常浏览器的任何数据:Edge/Chrome 136+ 禁止在默认用户目录上开调试端口,而且把真实 profile 从别的路径打开会清掉端砚登录态。插件的专用 profile 是唯一可行且安全的地方。
账号的 Key 上限是 10 把,所以本插件建的 Key 名字是
`ink-<host>-<account>-<random>`(18 字符),清理只碰这个前缀,**手动建的 Key
永远不动**;默认保留最新两把、并始终保留本次登录创建的那把。
### 登录态复用与续期
`uaa-token` 是网页登录态,不是 OAuth refresh token;平台前端没有 refresh
逻辑。插件默认保留一个**专用浏览器 profile**,快过期时用 headless 打开控制台
页面**静默续期**(SSO 会话还在就会换新 cookie)。关掉 `keep_sign_in` 就改成
一次性 profile:登录完删除,过期后手动重登。
## 模型
插件只使用 **OpenAI Chat Completions**(`https://discovery-api.intern-ai.org.cn/v1`)。
@@ -32,18 +56,61 @@ API Key 是可选的:不填,账号仍显示额度,只是不服务模型。
- `GET /api/tokenplan/v1/public/models`(无需登录):上下文、输入类型、能力、价格。
决策模型 `intern-decision-4b` 只支持 SystemOne,不是聊天接口,不列入。
**不做思考强度档位**:平台明确不支持通过请求参数开启/关闭/调整思考强度。
**不做思考强度档位**:平台明确不支持通过请求参数开启/关闭/调整思考强度
(实测 `reasoning_effort`、`reasoning.effort`、`thinking.type` 都被静默忽略),
插件会把这些字段从请求里剥掉,免得别的入口带来的参数造成干扰。
**免费标记与倍率(magpie 专有展示字段,OpenCode 忽略):**
- `free: true`:接口价(输入与输出)都是 0 的模型——与控制台自己的免费判定
一致。目前是 `Agents-A1 / Atria-Dawn / Sage-A1.5 / intern-s2` 四个。
- `rate`:**推导值**,不是平台的官方倍率(平台没有倍率概念,只有"墨点/百万
token"的绝对价)。归一化口径:**1000 墨点/1M 输入 token = x1**——qwen3.8-27b
x0.8、deepseek-v4.1-flash-1017 x1、minimax-m3 x2.1、kimi-k2.6 x6.5、glm-5.3 x8。
token"的绝对价)。归一化口径:**1000 墨点/1M 输入 token = x1**——qwen3.8-27b x0.8、deepseek-v4.1-flash-1017 x1、minimax-m3 x2.1、kimi-k2.6 x6.5、glm-5.3 x8。
免费模型不设 rate(magpie 的 `rate: 0` 表示"未提供",不是免费)。rate 不参与
计费,平台实际按 token 扣墨点。
## 图片与限制
平台对**单次请求里的图片**有硬性限制(2026-11 实测六个模型一致:免费
`Agents-A1 / intern-s2 / Sage-A1.5` 与付费 `deepseek-v4.1-flash / qwen3.8-27b /
kimi-k2.6` 全部相同):
| 限制 | 数值 |
|---|---|
| 单请求图片张数 | ≤ **8** 张(base64 与 URL 引用都计入) |
| 单张图片体积 | ≤ **10 MB** |
| 单请求图片总体积 | ≤ **40 MB** |
| 支持的格式 | PNG / JPEG / WebP / GIF / BMP(SVG 等被拒) |
体积按**解码后的原图字节**算,不是 base64 字符串长度(base64 有 4/3 膨胀:
11 MB 的 base64 对应约 8.2 MB 原图,是放行的;16 MB 的 base64 对应约 12 MB
原图,会被拒)。
这些限制是**每请求**的、基于请求内容本身的——新会话、重试、换 Key 都绕不开。
图片一旦进了会话历史,之后的每一轮请求都带着它们:超限后这个会话在这个
平台上就持续失败,直到历史里不再引用那么多图片。
### 超限预检
插件在**发请求之前**就检查上面四项:超限的请求**不会发出去**,插件直接
返回一个 magpie 读得懂的「请求形状被拒」错误(400 + `extra inputs are not
permitted: …`)。magpie 对这种错误的处理是**问组里的下一个成员**,而且本家
不休息、不计失败——也就是说,如果你把端砚放进一个多模型的组,图片超限的
请求会自动落到组里别的模型上,任务不中断;端砚单独使用时,你会看到一条
说明清楚原因(几张图、多大、超了哪条)的错误,而不是平台那句读不出来的
原话。拒绝消息是中英双语的:英文主干给 magpie 匹配,中文括号给人看。
### 错误码对照
| 端砚错误 | 含义 | 插件的处理 |
|---|---|---|
| `invalid_media` + "too many images in request" | 超过 8 张 | 预检拦下,不会到达平台;万一到达(如历史边缘竞态),翻译成形状错误 |
| `invalid_media` + "inline image exceeds configured byte limit" | 单张超 10 MB | 同上 |
| `invalid_media` + "cumulative image bytes exceeded …" | 总量超 40 MB | 同上。注意这条平台原话里的 "exceeded" 会让 magpie 误判成「额度用尽」从而休息好账号——插件翻译后的文案避开了这些词 |
| `invalid_media` + "unsupported media type" | 格式不支持(如 SVG) | 预检拦下 |
| `media_fetch_failed` (502) | URL 引用的图片平台拉取失败 | 翻译成形状错误(换一个能拉到的图床,或改用 base64) |
| `quota_exceeded` (429) | 5h/7d 窗口用尽(Anthropic 式响应,看 `Retry-After: 1` 头) | 原样透传,magpie 本来就认 429 |
## 额度卡片
有控制台登录态时,magpie 的账户卡显示:
@@ -56,30 +123,6 @@ API Key 是可选的:不填,账号仍显示额度,只是不服务模型。
按模型的 token 消耗明细不在额度卡上(那是用量页的事),额度卡只管额度。
读不到的字段不会显示成 0:额度读取失败时卡片说明原因,模型调用不受影响。
## 登录方式
| 方式 | 做什么 | 产出 |
|---|---|---|
| **浏览器登录(推荐)** | 用**插件自己的专用浏览器 profile** 开一个窗口,你在里面登录控制台(密码 / 短信 / 扫码)。登录窗口**不带调试端口**(阿里验证码能过)。**Windows** 上插件用窗口标题判断登录完成、**自己关窗**;**macOS / Linux** 读不了窗口标题,登录完成后请**自己关掉窗口**,插件接着自动收尾。之后的续期/重登都静默完成 | 额度 + 模型 |
| **仅 API Key** | 只粘贴 Key;`GET /v1/models` 探活 | 只有模型 |
| **API Key + 控制台 token** | 粘贴 Key,再粘贴 `uaa-token=…` 那一项(DevTools → Application → Cookies,复制整条 `uaa-token=…` 即可,插件只取值) | 额度 + 模型 |
浏览器登录需要本机装有 Microsoft Edge、Google Chrome 或 Chromium(也可以用 `MAGPIE_INKSTONE_BROWSER` 指定路径)。Safari 用不了:插件要在单独的浏览器 profile 里登录,Safari 不支持。没有这些浏览器时,选「仅 API Key」,或「API Key + 控制台 token」(token 可以从任何浏览器里复制,包括 Safari)。
> 不读、不动你日常浏览器的任何数据:Edge/Chrome 136+ 禁止在默认用户目录上开调试端口,而且把真实 profile 从别的路径打开会清掉端砚登录态。插件的专用 profile 是唯一可行且安全的地方。
浏览器登录时可以把**现有 Key** 粘进 “TokenPlan API key”;留空才会
创建新 Key。账号的 Key 上限是 10 把,所以本插件建的 Key 名字是
`ink-<host>-<account>-<random>`(18 字符),清理只碰这个前缀,**手动建的 Key
永远不动**;默认保留最新两把、并始终保留本次登录创建的那把。
### 登录态复用与续期
`uaa-token` 是网页登录态,不是 OAuth refresh token;平台前端没有 refresh
逻辑。插件默认保留一个**专用浏览器 profile**,快过期时用 headless 打开控制台
页面**静默续期**(SSO 会话还在就会换新 cookie)。关掉 `keep_sign_in` 就改成
一次性 profile:登录完删除,过期后手动重登。
## 免费墨点领取(可选)
控制台首页加载时会 `POST /users/free-grant` 领当月免费墨点(幂等,没有按钮)。
@@ -93,7 +136,7 @@ API Key 是可选的:不填,账号仍显示额度,只是不服务模型。
magpie plugin add @magpie-community/opencode-inkstone-auth
```
然后在 magpie 里给 `书生·端砚 ` 登录。
然后在 magpie 里给 `书生·端砚` 登录。
## 存储
@@ -111,7 +154,7 @@ magpie plugin add @magpie-community/opencode-inkstone-auth
## OpenCode 2.x
OpenCode 2.x 没有 `auth.usage` / `auth.refresh` / `auth.checkin`:额度卡片、静默续期和每日签到只在 magpie 里可用;Chat 模型在 2.x 照常可用。
OpenCode 2.x 没有 `auth.usage` / `auth.refresh` / `auth.checkin`:额度卡片、静默续期和每日签到只在 magpie 里可用;Chat 模型在 2.x 照常可用(预检与改写随 loader 的 fetch 一样生效)。
## 旧入口迁移
@@ -128,6 +171,61 @@ bun scripts/check.mjs inkstone
`testdata/public-models.json` 是一次真实的公共模型接口回复(模型 id 未改),
测试用它驱动解析与过滤。所有测试都在本地 fake 上跑,不触网。
`preflight.test.mjs` 里有一份 magpie 宿主 `shapeRefused` 词表的本地拷贝——
改预检文案时它会验证新的措辞仍然命中形状词、不触发排除词。
## License
MIT
## English
Unofficial. One console sign-in gives both the ink credits (balance, 5-hour and
7-day windows, credit packs) and the plan's models over OpenAI Chat Completions.
Four sign-in methods produce the same `intern-inkstone` account: a **zero-prompt
browser sign-in** (one click opens the plugin's own browser profile; the plugin
closes the window itself on Windows, or reads the session after you quit it on
macOS/Linux, then creates an `ink-*` API key), the same browser sign-in with an
optional pasted key to reuse, API key only (models, no credit card), and API key
+ console token (pasted `uaa-token=…`, models and card). The sign-in window
carries no debugging port, so the console's captcha sees an ordinary browser.
Browser-created keys are named `ink-<host>-<account>-<random>` (18 characters).
Pruning (default on) touches only that prefix of this machine's and account's
keys, keeps the newest two and always the key created on this sign-in; manual
keys are never deleted. A dedicated browser profile keeps the console session
for silent renewal (`keep_sign_in`, default on); off, each login's profile is
deleted and an expired token needs a manual sign-in.
The platform caps the pictures of one request: at most **8** (base64 and URL
references both count), **10 MB** per picture and **40 MB** together, measured
in decoded image bytes, not base64 characters (base64 grows by 4/3). The formats
taken are PNG, JPEG, WebP, GIF and BMP. The caps are per request and content
based: once a session's history carries too many pictures, every later turn
fails the same way on this platform.
The plugin checks those caps **before** the request leaves and refuses an over-
the-cap one locally, in the shape magpie reads as "this request's shape is
refused" (400 + "extra inputs are not permitted: …"): magpie asks the group's
next member, and this one rests nobody and counts no failure — in a model group
the task moves on; alone, you get a bilingual message saying which cap the
request passed and by how much. The plan's own image refusals, which magpie
would misread (its "cumulative image bytes exceeded …" hits magpie's quota words
and would rest a healthy account), are translated to the same shape; the plan's
own wording never reaches the response body. Inline images missing a `detail`
get `detail: "auto"`, and the reasoning fields the plan silently ignores are
stripped from the body.
`intern-decision-4b` is a SystemOne decision model, not a chat candidate. The
plan takes no reasoning-effort controls (it silently ignores them), so the
plugin strips those fields. `free` marks the models the console prices at zero;
`rate` is a derived display multiplier against 1000 ink points per 1M input
tokens, not the platform's own (the platform has none).
The daily free ink points (`POST /users/free-grant`) run through magpie's
check-in hook when you turn it on, once a day, idempotent; an account without a
bound phone number reports `ineligible`.
## License
+118 -12
View File
@@ -5,7 +5,7 @@ import "./nonet.mjs"
import { readFileSync } from "node:fs"
import { afterEach, expect, test } from "bun:test"
import { InkStoneAuthPlugin } from "./index.mjs"
import { fakeInkStone, json } from "./fake.mjs"
import { fakeInkStone, json, ok } from "./fake.mjs"
let f
afterEach(() => f?.close())
@@ -110,14 +110,21 @@ test("the loader serves the models with the key at the platform's base URL", asy
expect(loader.baseURL).toBe(f.origin + "/v1")
})
test("the sign-in methods cover browser, API key, and API key + console token", async () => {
test("the sign-in methods cover two browser ways, API key, and API key + console token", async () => {
// a machine with a Chromium browser, whatever the test machine has
const p = await plugin({ browserCandidates: () => ["/opt/chromium/chrome"] })
const labels = p.auth.methods.map((m) => m.label)
// zero-prompt browser sign-in first, the paste-optional one second
expect(labels[0]).toContain("Browser sign-in")
expect(labels[1]).toContain("API key only")
expect(labels[2]).toContain("console token")
// the browser method must not block the host's authorize call: the browser
expect(labels[0]).not.toContain("reuse")
expect(labels[1]).toContain("Browser sign-in")
expect(labels[1]).toContain("reuse")
expect(labels[2]).toContain("API key only")
expect(labels[3]).toContain("console token")
// the zero-prompt method has no prompts at all: the host opens the window
// straight away (sensenova's and cursor's browser sign-in is the same)
expect(p.auth.methods[0].prompts ?? []).toEqual([])
// both browser methods must not block the host's authorize call: the browser
// work runs in its callback (the host's authorize deadline is short)
const browser = p.auth.methods[0]
const result = browser.authorize({})
@@ -131,10 +138,11 @@ test("the sign-in methods cover browser, API key, and API key + console token",
expect(result.instructions).toContain("Sign in there")
expect(result.url).toBe("")
}
// the browser method's key prompt is optional; a non-sk- one is refused
expect(browser.prompts[0].validate("")).toBeUndefined()
expect(browser.prompts[0].validate("sk-abc")).toBeUndefined()
expect(browser.prompts[0].validate("nope")).toContain("sk-")
// the reuse method's key prompt is optional; a non-sk- one is refused
const reuse = p.auth.methods[1]
expect(reuse.prompts[0].validate("")).toBeUndefined()
expect(reuse.prompts[0].validate("sk-abc")).toBeUndefined()
expect(reuse.prompts[0].validate("nope")).toContain("sk-")
})
test("with no Chromium browser the browser sign-in fails at authorize and names the other sign-ins (#825)", async () => {
@@ -152,8 +160,8 @@ test("with no Chromium browser the browser sign-in fails at authorize and names
expect(result.error).toContain('"API key only"')
expect(result.error).toContain('"API key + console token"')
// the names it gives are the other methods' own labels
expect(p.auth.methods[1].label).toStartWith("API key only")
expect(p.auth.methods[2].label).toStartWith("API key + console token")
expect(p.auth.methods[2].label).toStartWith("API key only")
expect(p.auth.methods[3].label).toStartWith("API key + console token")
if (process.platform === "darwin") expect(result.error).toContain("Safari can't be used")
else expect(result.error).not.toContain("Safari")
} finally {
@@ -167,7 +175,7 @@ test("the API-key + console-token method reads the token out of a pasted cookie"
serve()
f.route("GET /api/tokenplan/v1/users/validate", () => json({ code: 0, data: { name: "张三", phone: "12345678901" } }))
const p = await plugin()
const method = p.auth.methods[2]
const method = p.auth.methods[3]
// a full cookie string must be reduced to just the uaa-token value
const okResult = await method.authorize({
apiKey: "sk-test",
@@ -196,6 +204,104 @@ test("the API-key + console-token method reads the token out of a pasted cookie"
}
})
test("the key-management calls ride the session cookie, not the bearer", async () => {
f = fakeInkStone()
const p = await plugin()
const seen = []
const serve = (method, path) =>
f.route(`${method} /api/tokenplan/v1${path}`, (r) => {
seen.push(`${method} ${path}: auth=${r.headers.get("authorization") ? "bearer" : "none"} cookie=${r.headers.get("cookie") ? "yes" : "no"}`)
return json({ code: 0, msg: "success", data: {} })
})
serve("GET", "/keys")
serve("POST", "/keys")
serve("DELETE", "/keys/ak_1")
const { listKeys, createKey, deleteKey } = await import("./lib/protocol.mjs")
const token = "fake-token"
await listKeys(token).catch(() => {})
await createKey(token, "ink-x", "idem-1").catch(() => {})
await deleteKey(token, "ak_1").catch(() => {})
expect(seen.length).toBe(3)
for (const line of seen) {
// the /keys family takes the session cookie; a bearer there is the
// -10002 "not authenticated" the real console answers (verified live,
// 2026-11-07: the sign-in then failed at key creation on the real thing)
expect(line).toContain("cookie=yes")
expect(line).not.toContain("auth=bearer")
}
})
test("the fetch wiring is the request path — each piece breaks it in a way the fake sees", async () => {
// 作者 review:他逐项破坏 chatFetch 的每一节(删 loader fetch、关翻译、关
// rewrite、关软重试、还原分页),97 个测试全绿——纯函数测试抓不住接线。
// 这一条把接线钉住:每一节都经这层 fetch(或 keys 层)被假服务看到。
f = fakeInkStone()
const p = await plugin()
const loader = await p.auth.loader(async () => auth)
const tiny = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
// ① 预检在 fetch 层生效:9 张图到不了平台
let asked = 0
f.route("POST /v1/chat/completions", () => (asked++, json({ ok: true })))
const nine = {
model: "Sage-A1.5",
messages: [{ role: "user", content: [{ type: "text", text: "x" }, ...Array.from({ length: 9 }, () => ({ type: "image_url", image_url: { url: `data:image/png;base64,${tiny}` } }))] }],
}
const r1 = await loader.fetch(`${f.origin}/v1/chat/completions`, { method: "POST", body: JSON.stringify(nine) })
expect(r1.status).toBe(400)
expect((await r1.json()).error.message).toContain("extra inputs are not permitted")
expect(asked).toBe(0)
// ② 翻译在 fetch 层生效:端砚的 invalid_media 400 被换写成宿主认得的形状
f.route("POST /v1/chat/completions", () => json({ code: "invalid_media", message: "unsupported media type" }, 400))
const r2 = await loader.fetch(`${f.origin}/v1/chat/completions`, { method: "POST", body: JSON.stringify({ messages: [{ role: "user", content: "hi" }] }) })
expect(r2.status).toBe(400)
expect((await r2.json()).error.message).toContain("extra inputs are not permitted")
// ③ 改写在 fetch 层生效:reasoning 被剥、detail 被补,上游收到的就是改写后的
let received = null
f.route("POST /v1/chat/completions", (r) => {
asked++
received = r.json
return json({ ok: true })
})
const withReasoning = {
model: "Sage-A1.5",
reasoning: { effort: "high" },
messages: [{ role: "user", content: [{ type: "text", text: "x" }, { type: "image_url", image_url: { url: `data:image/png;base64,${tiny}` } }] }],
}
const r3 = await loader.fetch(`${f.origin}/v1/chat/completions`, { method: "POST", body: JSON.stringify(withReasoning) })
expect(r3.status).toBe(200)
expect("reasoning" in received).toBe(false)
expect(received.messages[0].content[1].image_url.detail).toBe("auto")
// ④ /keys 的 cookie + 无分页 query(真机修复的回归防线——query 加回去会红)
const seen = { query: "", cookie: "" }
f.route("GET /api/tokenplan/v1/keys", (r) => {
seen.query = r.url
seen.cookie = r.headers.get("cookie") ?? ""
return json({ code: 0, data: { total: 0, items: [] } })
})
const { listKeys } = await import("./lib/protocol.mjs")
await listKeys("fake-token")
expect(seen.cookie).toContain("uaa-token=fake-token")
expect(seen.query).not.toContain("page=")
expect(seen.query).not.toContain("page_size=")
// ⑤ 软拒绝重试在 keys 层生效:-15100 后换名字再试
const attempts = []
f.route("POST /api/tokenplan/v1/keys", (r) => {
attempts.push(r.json?.name)
if (attempts.length === 1) return json({ code: -15100, msg: "API Key fetch failed, refresh page and retry" })
return ok({ key: "sk-retried" })
})
const { ensureKey } = await import("./lib/keys.mjs")
const key = await ensureKey("fake-token", "acct", { create: true, log: () => {} })
expect(key).toBe("sk-retried")
expect(attempts.length).toBe(2)
expect(attempts[0]).not.toBe(attempts[1])
})
test("cleanDetail masks real uaa-token, sk-, Bearer and JWT runs", async () => {
const { cleanDetail } = await import("./lib/protocol.mjs")
expect(cleanDetail("failed: uaa-token=secretValue123456")).toBe("failed: ***")
+4
View File
@@ -132,7 +132,11 @@ test('the window title is read on Windows only, even when it already shows the c
expect(reads).toBe(0)
}
// the same title does end it on Windows, so the check above is not empty
// — on the second hit exactly (a build that counts three reads the
// window a third time before it answers, and fails here)
reads = 0
expect(await waitForConsoleWindow(child, { platform: 'win32', titleOf, settleMs: 0, timeoutMs: 2000, pollMs: 20 })).toBe('console')
expect(reads).toBe(2)
} finally {
try { child.kill() } catch {}
}
+59 -14
View File
@@ -4,7 +4,7 @@
// port-file → CDP cookie read → graceful close → key creation path runs here.
import "./nonet.mjs"
import { execSync } from "node:child_process"
import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync } from "node:fs"
import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync, renameSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"
@@ -19,11 +19,46 @@ const savedEnv = {}
let f
beforeAll(() => {
// compile the fake browser once (bun build --compile takes under a second)
fakeDir = mkdtempSync(join(tmpdir(), "inkstone-fake-browser-"))
const out = join(fakeDir, process.platform === "win32" ? "fake-chrome.exe" : "fake-chrome")
// compile the fake browser once (bun build --compile takes under a second).
// The exe goes to a FIXED path keyed by the source's hash, not a fresh
// mkdtemp every run: Windows Defender allows an exe by its path, so a
// randomly named one pops the firewall prompt on every run (and every run
// of every contributor's machine). Same bytes → same path → prompted once.
// Rebuilt only when testdata/fake-browser.mjs changes.
//
// The dir is per-user (`os.userInfo().username`): a fixed name in the
// shared /tmp could be pre-created by another user on a Linux CI runner.
// A half-written build never parks at the final name — the compile goes to
// a temp name that is renamed over, so `existsSync(out)` below is only
// true of a complete exe (the reviewer's point about a crashed compile
// keeping junk forever).
const entry = join(import.meta.dir, "testdata/fake-browser.mjs")
execSync(`${JSON.stringify(process.execPath)} build --compile ${JSON.stringify(entry)} --outfile ${JSON.stringify(out)}`, { stdio: "pipe" })
const { createHash } = require("node:crypto")
const { userInfo } = require("node:os")
let user = ""
try {
user = userInfo().username.replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 16) || "u"
} catch {
user = process.env.USER || process.env.USERNAME || "u"
user = user.replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 16) || "u"
}
const key = createHash("sha256").update(readFileSync(entry)).digest("hex").slice(0, 12)
fakeDir = join(tmpdir(), `inkstone-fake-browser-${user}-${key}`)
mkdirSync(fakeDir, { recursive: true })
const exeName = process.platform === "win32" ? "fake-chrome.exe" : "fake-chrome"
const out = join(fakeDir, exeName)
if (!existsSync(out)) {
// bun build --compile appends its own .exe on Windows, so the temp name
// is computed after the build: look for whatever `*.building*` came out
const tmpOut = join(fakeDir, `${exeName}.building`)
try {
rmSync(tmpOut, { force: true })
} catch {}
rmSync(join(fakeDir, `${exeName}.building.exe`), { force: true })
execSync(`${JSON.stringify(process.execPath)} build --compile ${JSON.stringify(entry)} --outfile ${JSON.stringify(tmpOut)}`, { stdio: "pipe" })
const built = existsSync(tmpOut) ? tmpOut : join(fakeDir, `${exeName}.building.exe`)
renameSync(built, out)
}
fakeExe = out
profile = mkdtempSync(join(tmpdir(), "inkstone-fake-profile-"))
// save what we override: bun test runs every file in one process, so these
@@ -44,12 +79,12 @@ afterAll(() => {
if (value === undefined) delete process.env[key]
else process.env[key] = value
}
// the compiled fake is ~59 MB: never leave it behind (#824)
for (const dir of [profile, fakeDir]) {
try {
if (dir) rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 })
} catch {}
}
try {
rmSync(profile, { recursive: true, force: true })
} catch {}
// the profile is per-run; the compiled fake browser is not (fixed path,
// rebuilt only when its source changes), so removing it here would make
// every run recompile and re-prompt the firewall on Windows
})
afterEach(() => {
@@ -95,9 +130,6 @@ test("the silent renewal reads the session cookie through a real CDP exchange",
expect(await renewSilently({ browserPath: fakeExe })).toBe("fake-uaa-token-for-tests")
}, 30_000)
// #826: an "API key + console token" entry is saved by the host as
// {type: "api", key, metadata: {apiKey, uaaToken}}. A renewed token goes back
// under metadata, and the rest of the entry is written back as it was.
test("a renewed token is written back where the api entry keeps it, under metadata", async () => {
f = fakeInkStone()
f.route("GET /api/tokenplan/v1/credits/balance", () => ok(poolUsageFixture()))
@@ -171,3 +203,16 @@ test("prune_keys off leaves every key alone, whatever the count", async () => {
}
expect(keys.length).toBe(3)
}, 60_000)
test("the reuse method keeps a pasted key instead of creating one", async () => {
f = fakeInkStone()
const keys = serveKeyRoutes()
const p = await pluginWithFakeBrowser()
const reuse = p.auth.methods[1]
expect(reuse.label).toContain("reuse")
const saved = await reuse.authorize({ apiKey: "sk-pasted" }).callback("", {})
expect(saved.type).toBe("success")
expect(saved.apiKey).toBe("sk-pasted")
// the pasted key is kept: nothing was created on the console
expect(keys.length).toBe(0)
}, 60_000)
+156 -69
View File
@@ -29,6 +29,7 @@ import {
import { bootModels, createCatalog, liveRowsOf, publicRowsOf } from "./lib/models.mjs"
import { cardOf } from "./lib/quota.mjs"
import { ensureKey, pruneKeys } from "./lib/keys.mjs"
import { precheckImages, rewriteBody, translateError } from "./lib/preflight.mjs"
import {
readUaaToken,
requireBrowser,
@@ -46,6 +47,71 @@ const DEFAULT_LOGIN_TIMEOUT_MS = 8 * 60_000
const apiBase = () => ENDPOINTS.api
/**
* 模型请求的 fetch 包装:预检(超限本地拒、宿主可切换)→ 改写(补 detail、
* 剥无效参数)→ 真发 → 错误翻译(端砚的图片错误宿主读不对,见 preflight.mjs)。
* 只认 chat/completions 和 models 两个端点;别的原样透传。
*/
function chatFetch(key, log = () => {}) {
const upstream = (...args) => globalThis.fetch(...args)
return async (input, init = {}) => {
const url = typeof input === "string" ? input : input?.url ?? ""
const method = (init.method ?? (typeof input === "object" ? input?.method : undefined) ?? "GET").toUpperCase()
const isChat = url.includes("/chat/completions") && method === "POST"
if (!isChat) return upstream(input, init)
const raw = init.body
let text = ""
if (typeof raw === "string") text = raw
else if (raw instanceof ArrayBuffer) text = new TextDecoder().decode(raw)
else if (ArrayBuffer.isView(raw)) text = new TextDecoder().decode(raw)
else if (typeof input === "object" && typeof input?.text === "function" && init.body === undefined) text = await input.text().catch(() => "")
if (text) {
// ①预检:超限不发请求,直接给宿主认得的"换下家"形状。
let body
try {
body = JSON.parse(text)
} catch {
body = null
}
if (body) {
const refusal = precheckImages(body)
if (refusal) {
return new Response(refusal.body, {
status: refusal.status,
headers: { "content-type": "application/json" },
})
}
}
// ②③改写:补 detail、剥无效参数。
init = { ...init, body: rewriteBody(text) }
}
// 真发。
let res
try {
res = await upstream(input, init)
} catch (e) {
throw e
}
// ④错误翻译:端砚的图片错误码宿主读不对,换成宿主认得的形状。
if (!res.ok && res.status !== 429) {
let said = ""
try {
said = await res.text()
} catch {}
const translated = translateError(res.status, said, log)
if (translated) {
return new Response(translated.body, {
status: translated.status,
headers: { "content-type": "application/json" },
})
}
// 没翻译就还回去:body 只能读一次,用读到的重建。
return new Response(said, { status: res.status, statusText: res.statusText, headers: res.headers })
}
return res
}
}
const optNum = (v, fallback) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Number(v) : fallback)
/** 第一个非空候选(trim 后):`??` 会放过空串,这里不会。 */
@@ -288,6 +354,81 @@ export async function InkStoneAuthPlugin({ client, magpie } = {}, options = {})
return declared
}
/**
* 两个浏览器登录方式共用的 authorize:display 与候选浏览器的预检、
* 开窗指令、回调里的建 Key。差别只在粘贴的 Key(零提示方式为空)。
*/
const browserAuthorize = (pasted) => {
if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
return {
type: "failed",
error:
'The browser sign-in needs a display, and this machine has none. Sign in with "API key only", or with "API key + console token" to also get the ink-credit card.',
}
}
try {
// an empty list fails here, before the host is told a window opened
requireBrowser(browserPath, browserList ? { candidates: browserList } : undefined)
} catch (e) {
return { type: "failed", error: cleanDetail(e?.message ?? e) }
}
// The browser work runs in the callback: the host's authorize call
// has a short deadline, while a sign-in can take minutes.
return {
url: "",
opened: true,
instructions:
process.platform === "win32"
? "A browser window opens on the InkStone console. Sign in there (password, SMS or QR code); the plugin reads the completed sign-in by itself and closes the window. You do not need to close it. After the sign-in the plugin creates an ink-* API key on your account — the plaintext is shown once, and the plugin keeps it for you."
: "A browser window opens on the InkStone console. Sign in there (password, SMS or QR code), then quit that browser yourself — Cmd+Q on macOS (closing its last window is not enough), or close its last window on Linux. The plugin then reads the session from the profile and finishes. After the sign-in the plugin creates an ink-* API key on your account — the plaintext is shown once, and the plugin keeps it for you.",
method: "auto",
async callback(_code, { signal } = {}) {
let token = ""
try {
token = await signInWithBrowser({
browserPath,
keepSignIn: keepSignInOn(),
timeoutMs: loginTimeoutMs,
waitForLogin: typeof waitForLogin === "function" ? waitForLogin : undefined,
signal,
log,
})
} catch (e) {
if (e?.cancelled) return { type: "failed", error: "the sign-in was cancelled" }
return { type: "failed", error: cleanDetail(`InkStone sign-in: ${e?.message ?? e}`) }
}
try {
const user = await usersValidate(token).catch(() => null)
const data = user?.data ?? {}
const username = firstNonEmpty(data.name, data.username, data.nickname, data.phone, data.email)
// 如果账号段读不出,拿 token 的指纹兜底:保证两账号前缀永远不撞。
const accountIdent = username || `anon-${fingerprint(token).slice(0, 8)}`
const apiKey = await ensureKey(token, accountIdent, {
apiKey: pasted,
create: createKeyOn(),
prune: pruneOn(),
log,
})
return {
type: "success",
access: apiKey,
refresh: "",
expires: 0,
apiKey,
uaaToken: token,
accountId: username || `inkstone-${fingerprint(apiKey)}`,
username,
source: "browser",
}
} catch (e) {
return { type: "failed", error: cleanDetail(`InkStone sign-in: ${e?.message ?? e}`) }
}
},
}
}
return {
config: async (cfg) => {
cfg.provider ??= {}
@@ -396,7 +537,19 @@ export async function InkStoneAuthPlugin({ client, magpie } = {}, options = {})
type: "oauth",
label: "Browser sign-in (ink credits + creates an API key)",
/**
* 插件专用 profile 的窗口;插件实时读会话并自己关窗。
* 零提示:点一下直接开窗,登录后自动建 ink-* Key。与 sensenova、
* cursor、cline 的浏览器登录同款——生态惯例是浏览器登录不问问题。
*/
authorize() {
return browserAuthorize("")
},
},
{
type: "oauth",
label: "Browser sign-in + reuse an existing API key",
/**
* 浏览器登录前可粘贴已有 Key(留空则自动新建)。唯一一个先问
* 一句再开窗的浏览器方式;不想被问就用上一个。
*/
prompts: [
{
@@ -412,73 +565,7 @@ export async function InkStoneAuthPlugin({ client, magpie } = {}, options = {})
},
],
authorize(inputs) {
const pasted = normalizeApiKey(inputs?.apiKey)
if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
return {
type: "failed",
error:
'The browser sign-in needs a display, and this machine has none. Sign in with "API key only", or with "API key + console token" to also get the ink-credit card.',
}
}
try {
// an empty list fails here, before the host is told a window opened
requireBrowser(browserPath, browserList ? { candidates: browserList } : undefined)
} catch (e) {
return { type: "failed", error: cleanDetail(e?.message ?? e) }
}
// The browser work runs in the callback: the host's authorize call
// has a short deadline, while a sign-in can take minutes.
return {
url: "",
opened: true,
instructions:
process.platform === "win32"
? "A browser window opens on the InkStone console. Sign in there (password, SMS or QR code); the plugin reads the completed sign-in by itself and closes the window. You do not need to close it. After the sign-in the plugin creates an ink-* API key on your account (leave the prompt empty; paste an existing key or turn off \"Create an API key on browser sign-in\" to skip) — the plaintext is shown once, and the plugin keeps it for you."
: "A browser window opens on the InkStone console. Sign in there (password, SMS or QR code), then quit that browser yourself — Cmd+Q on macOS (closing its last window is not enough), or close its last window on Linux. The plugin then reads the session from the profile and finishes. After the sign-in the plugin creates an ink-* API key on your account (leave the prompt empty; paste an existing key or turn off \"Create an API key on browser sign-in\" to skip) — the plaintext is shown once, and the plugin keeps it for you.",
method: "auto",
async callback(_code, { signal } = {}) {
let token = ""
try {
token = await signInWithBrowser({
browserPath,
keepSignIn: keepSignInOn(),
timeoutMs: loginTimeoutMs,
waitForLogin: typeof waitForLogin === "function" ? waitForLogin : undefined,
signal,
log,
})
} catch (e) {
if (e?.cancelled) return { type: "failed", error: "the sign-in was cancelled" }
return { type: "failed", error: cleanDetail(`InkStone sign-in: ${e?.message ?? e}`) }
}
try {
const user = await usersValidate(token).catch(() => null)
const data = user?.data ?? {}
const username = firstNonEmpty(data.name, data.username, data.nickname, data.phone, data.email)
// 如果账号段读不出,拿 token 的指纹兜底:保证两账号前缀永远不撞。
const accountIdent = username || `anon-${fingerprint(token).slice(0, 8)}`
const apiKey = await ensureKey(token, accountIdent, {
apiKey: pasted,
create: createKeyOn(),
prune: pruneOn(),
log,
})
return {
type: "success",
access: apiKey,
refresh: "",
expires: 0,
apiKey,
uaaToken: token,
accountId: username || `inkstone-${fingerprint(apiKey)}`,
username,
source: "browser",
}
} catch (e) {
return { type: "failed", error: cleanDetail(`InkStone sign-in: ${e?.message ?? e}`) }
}
},
}
return browserAuthorize(normalizeApiKey(inputs?.apiKey))
},
},
{
@@ -577,7 +664,7 @@ export async function InkStoneAuthPlugin({ client, magpie } = {}, options = {})
const auth = await getAuth()
const key = apiKeyOf(auth)
if (!key) return {}
return { baseURL: apiBase(), apiKey: key }
return { baseURL: apiBase(), apiKey: key, fetch: chatFetch(key, log) }
},
/**
+21 -3
View File
@@ -70,7 +70,7 @@ export function keyItems(listReply) {
/** 账号现在有几把 Key(total 缺失时按数组数)。 */
export async function keyCount(token) {
const listed = await listKeys(token, { query: { page: 1, page_size: 50 } })
const listed = await listKeys(token)
const items = keyItems(listed)
const total = Number(listed?.data?.total ?? listed?.data?.total_count ?? 0)
return Math.max(Number.isFinite(total) ? total : 0, items.length)
@@ -86,7 +86,7 @@ export async function keyCount(token) {
export async function pruneKeys(token, username, { freeSlots = 0, keep = 2, protectName = "", log } = {}) {
let deleted = 0
try {
const listed = await listKeys(token, { query: { page: 1, page_size: 50 } })
const listed = await listKeys(token)
const prefix = keyPrefixFor(username)
const ours = keyItems(listed)
.filter((k) => k.name.startsWith(prefix))
@@ -174,6 +174,24 @@ export async function ensureKey(token, username, { apiKey = "", create = true, p
"the console created an API key but did not return it (the plaintext is shown only once). " +
"Create one in the console and paste it instead.",
)
}
// 「API Key fetch failed, refresh page and retry」:登录窗口刚关、
// headless 刚读完 cookie 就建 Key 时的软风控(真机实测,2026-11-07——
// 同一枚 cookie 稍后重试就成功)。稍等重试两次,换名字换幂等键。
else if (/fetch failed, refresh page/i.test(String(e?.message ?? ""))) {
let last = e
for (let attempt = 0; attempt < 2; attempt++) {
await new Promise((r) => setTimeout(r, 2500))
try {
name = keyNameFor(username)
reply = await createKey(token, name, randomUUID())
last = null
break
} catch (e2) {
last = e2
}
}
if (last) throw last
} else throw e
}
const created = String(reply?.data?.key ?? "").trim()
@@ -190,7 +208,7 @@ export async function ensureKey(token, username, { apiKey = "", create = true, p
if (e?.status === 401 || e?.status === 403) {
// 建出来却被拒:删掉这把,别给账号留垃圾。
try {
const listed = await listKeys(token, { query: { page: 1, page_size: 50 } })
const listed = await listKeys(token)
const match = keyItems(listed).find((k) => k.name === name)
if (match) await deleteKey(token, match.id)
} catch {}
+210
View File
@@ -0,0 +1,210 @@
// 请求预检:图片限制(8 张 / 单张 10MB / 总量 40MB / 格式)、detail 补齐、
// 无效参数剥离、端砚错误到宿主分类的翻译。
//
// 限制按**解码后的原图字节**算,不是 base64 字符串(2026-11 实测:8.24MB 原图
// / base64 11MB → 200;12MB 原图 / base64 16MB → 400)。base64 是 4/3 膨胀,
// 所以用 `长度 × 3/4` 反推原图。限制是平台级的:免费三个模型与付费三个模型
// 实测一致,预检不需要按模型区分。
//
// 超限的拒绝在**本地**给出,不发请求。拒绝体照宿主 `shapeRefused` 的词表
// 写(magpie 的 internal/gateway/fallback.go):400 + "extra inputs are
// not permitted: …" 命中 shapeWords 且不触发 quota/credit/unserved/refused
// 任一排除词——宿主会问组里的下家、本家不休息也不计失败。英文主干给宿主
// 匹配,中文括号给人看。中文不能用「额度/用量/套餐/上限/余额」这些字眼——
// 它们正是宿主 quotaWords/creditWords 的排除词,一出现宿主就把这个请求
// 当配额用尽(好账号要白休息 15 分钟)而不是换下家。
// 平台的图片上限(实测于 2026-11,6 个模型一致)。
export const IMAGE_LIMITS = {
count: 8,
perImage: 10 * 1024 * 1024, // 解码后的原图字节
total: 40 * 1024 * 1024,
}
// 平台收的图片格式(image_url 的 data: 前缀或 URL 的扩展名都算)。
const TAKEN_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif", "image/bmp"])
const DATA_URL = /^data:([^;,]+)\s*(;base64)?\s*,/i
/** base64 长度反推的原图字节(4/3 膨胀的逆)。 */
export function decodedBytes(b64) {
const s = String(b64 ?? "")
const pad = s.endsWith("==") ? 2 : s.endsWith("=") ? 1 : 0
return Math.max(0, Math.floor((s.length * 3) / 4) - pad)
}
// URL 引用里已知平台不收的图片扩展名:只拒绝这些,其余一律放行——平台
// 会自己拉取并按字节判断(拉不到是 502 media_fetch_failed,会被翻译成
// 形状错误)。按最后一个点猜格式会误伤 `render.php?id=1`、`abc.download`
// 这类链接(真机审查发现,2026-11-07)。
const UNTAKEN_EXTENSIONS = new Set(["svg", "svgz", "tiff", "tif", "heic", "heif", "avif", "ico"])
/** 一张图片的类型与原图字节:data: URL 解前缀;http(s) URL 只认已知坏扩展。 */
export function imageOf(url) {
const m = DATA_URL.exec(String(url ?? ""))
if (m) {
const rest = String(url).slice(m[0].length)
// data:image/jpg 在野外在见(非正式媒体类型),按 image/jpeg 判
const type = m[1].toLowerCase() === "image/jpg" ? "image/jpeg" : m[1].toLowerCase()
return { type, bytes: m[2] ? decodedBytes(rest) : 0, inline: true }
}
const u = String(url ?? "").split(/[?#]/)[0].toLowerCase()
const ext = /\.([a-z0-9]+)$/.exec(u)?.[1]
// 只认黑名单:命中 → 平台不收的类型;未知扩展(php、download、无扩展)
// → type 置空放行,平台按拉到的字节自己判断
const untaken = ext && UNTAKEN_EXTENSIONS.has(ext) ? `image/${ext === "svgz" ? "svg+xml" : ext}` : ""
return { type: untaken, bytes: 0, inline: false }
}
// 拒绝文案里禁止出现的字眼:它们是宿主 quotaWords/creditWords/unservedWords
// 的匹配词,出现在 message 里宿主就不认这是"换下家"的形状拒绝了。
// ("exceeded"、"limit"、"unsupported"、"invalid" 这些英文词同理——所以
// 英文主干只用 "extra inputs are not permitted" + 数字 + "this plan takes
// at most",逐词验证过不在任何排除表里。)
const UNSAID_ZH = /[额度用量套餐上限余额欠费限流频率频繁速率]/
/**
* 预检一个 chat 请求体:返回拒绝消息(超限时)或 null(放行)。
* 只读不写:改写(detail、参数剥离)在 rewriteBody 里,分开便于测试。
*/
export function precheckImages(body) {
const parts = []
for (const message of Array.isArray(body?.messages) ? body.messages : []) {
if (!Array.isArray(message?.content)) continue
for (const part of message.content) {
if (part?.type === "image_url" && part?.image_url) parts.push(part)
}
}
if (parts.length === 0) return null
if (parts.length > IMAGE_LIMITS.count) {
return refused(`this request carries ${parts.length} images; this plan takes at most ${IMAGE_LIMITS.count} in one request`, `本请求带 ${parts.length} 张图片,单请求最多接受 ${IMAGE_LIMITS.count} 张`)
}
let total = 0
for (let i = 0; i < parts.length; i++) {
const { type, bytes, inline } = imageOf(parts[i].image_url?.url)
if (type && !TAKEN_TYPES.has(type)) {
return refused(`${type} is not a picture this plan takes`, `平台不接受 ${type} 格式的图片`)
}
if (!inline) continue // URL 引用的字节数这里算不到,交给端砚自己拉(拉不到是 502 media_fetch_failed)
total += bytes
if (bytes > IMAGE_LIMITS.perImage) {
return refused(
`one image in this request is ${(bytes / 1048576).toFixed(1)} MB; this plan takes at most ${(IMAGE_LIMITS.perImage / 1048576).toFixed(0)} MB per image`,
`单张图片 ${(bytes / 1048576).toFixed(1)} MB,超过平台单张最多接受的 ${(IMAGE_LIMITS.perImage / 1048576).toFixed(0)} MB`,
)
}
}
if (total > IMAGE_LIMITS.total) {
return refused(
`this request's images are ${(total / 1048576).toFixed(1)} MB together; this plan takes at most ${(IMAGE_LIMITS.total / 1048576).toFixed(0)} MB in one request`,
`图片合计 ${(total / 1048576).toFixed(1)} MB,超过平台单请求最多接受的 ${(IMAGE_LIMITS.total / 1048576).toFixed(0)} MB`,
)
}
return null
}
/** 宿主认得的"请求形状被拒":400 + shapeWords 命中 + 无排除词(见模块头注释)。 */
export function shapeRefusal(detail, detailZh) {
const message = `extra inputs are not permitted: ${detail}(${detailZh})`
if (UNSAID_ZH.test(message)) {
// 中文文案混进了宿主的排除词:宁可自己报错也不发会让 magpie 误判的体。
throw new Error(`preflight refusal wording carries a host exclusion word: ${message}`)
}
return {
status: 400,
body: JSON.stringify({
error: { message, type: "invalid_request_error", code: "invalid_media", param: null },
}),
}
}
function refused(detail, detailZh) {
return shapeRefusal(detail, detailZh)
}
/**
* 改写请求体:①每张内联图补 `detail`(缺了补 auto,用户写了尊重不动——
* 实测非必填,low 省 token 是用户自己的选择)②剥端砚不收的参数。
* 返回新字符串;body 不能解析时原样返回(让端砚自己拒绝)。
*/
const UNSUPPORTED_FIELDS = ["reasoning", "reasoning_effort", "thinking"]
export function rewriteBody(text) {
let body
try {
body = JSON.parse(String(text))
} catch {
return text
}
if (!body || typeof body !== "object" || Array.isArray(body)) return text
let touched = false
for (const field of UNSUPPORTED_FIELDS) {
if (field in body) {
delete body[field]
touched = true
}
}
if (body.output_config && typeof body.output_config === "object" && !Array.isArray(body.output_config) && "effort" in body.output_config) {
delete body.output_config.effort
touched = true
}
for (const message of Array.isArray(body.messages) ? body.messages : []) {
if (!Array.isArray(message?.content)) continue
for (const part of message.content) {
if (part?.type === "image_url" && part?.image_url && typeof part.image_url === "object" && part.image_url.detail === undefined) {
part.image_url.detail = "auto"
touched = true
}
}
}
return touched ? JSON.stringify(body) : text
}
/**
* 端砚的错误 → 宿主分类。宿主从回复本身判断(status + body),所以翻译
* 就是把端砚的话换成宿主词表读得出的话:
* - 端砚的四种 invalid_media / media_fetch_failed:宿主一个都读不对
* ("too many images" 是不可重试的 failOther,"cumulative … exceeded"
* 反而误中 quotaWords 让好账号休息 15 分钟)——统一换成 shape 拒绝体,
* 宿主问下家、本家不休息。
* - 429 quota_exceeded:Anthropic 式无 error.code,靠 Retry-After 区分;
* OpenAI 式带 code。原样透传(宿主本来就认 429)。
*/
const INKSTONE_IMAGE_CODES = new Set(["invalid_media", "media_fetch_failed", "unsupported_media_type"])
export function translateError(status, bodyText, log = () => {}) {
if (status !== 400 && status !== 502) return null
let json
try {
json = JSON.parse(String(bodyText))
} catch {
return null
}
const code = json?.code ?? json?.error?.code
if (typeof code !== "string" || !INKSTONE_IMAGE_CODES.has(code)) return null
// 端砚的原话("cumulative image bytes exceeded …")带宿主排除词 "exceeded"。
// 宿主 wordsOf(body) 对整个响应体做正则——原话进 body 的任何字段(包括
// 不读的 detail)都会让这个 400 被当成配额用尽,好账号白休息 15 分钟。
// 所以原话只进日志,body 里只有换过的、逐词验证过的话。
const said = cleanSaid(json?.error?.message ?? json?.msg ?? json?.message ?? code)
log("warn", `inkstone: the plan refused an image (${code}: ${said}); translated to a shape refusal the host can fail over at`)
const why =
code === "invalid_media" || code === "unsupported_media_type"
? "one of this request's pictures is more than this plan takes"
: "the plan could not fetch a picture this request links to"
return {
status: 400,
body: JSON.stringify({
error: {
message: `extra inputs are not permitted: ${why}(端砚拒绝了这个请求里的图片,已改判为可切换的请求形状错误,组内下家会接手)`,
type: "invalid_request_error",
code: "invalid_media",
param: null,
},
}),
}
}
function cleanSaid(text) {
return String(text ?? "").replace(/[<>]/g, "").slice(0, 120) || "invalid media"
}
+30 -7
View File
@@ -69,6 +69,27 @@ export function consoleHeaders(token, extra = {}) {
}
}
/**
* Key 管理接口(/keys 的 GET/POST/DELETE)只认会话 cookie,不认 Bearer——
* 2026-11-07 真机实测:Bearer 打 /keys 返回 -10002 "request is not
* authenticated",同一枚 token 作 cookie 就 200。额度接口恰好相反(只认
* Bearer,见上)。所以 console* 系列带 auth 选项,keys.mjs 传 "cookie"。
*/
export function cookieHeaders(token, extra = {}) {
return {
accept: "application/json",
"accept-language": "zh-CN",
origin: ENDPOINTS.console,
referer: `${ENDPOINTS.console}/token-plan/home`,
"sec-fetch-site": "same-origin",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
...clientHints(),
cookie: `uaa-token=${token}`,
...extra,
}
}
async function readJson(res, what) {
const text = await res.text().catch(() => "")
let json = null
@@ -98,12 +119,12 @@ async function readJson(res, what) {
return json
}
async function consoleFetch(url, token, init, what, timeoutMs = TIMEOUT_MS) {
async function consoleFetch(url, token, init, what, timeoutMs = TIMEOUT_MS, auth = "bearer") {
let res
try {
res = await fetch(url, {
...init,
headers: consoleHeaders(token, init?.headers),
headers: auth === "cookie" ? cookieHeaders(token, init?.headers) : consoleHeaders(token, init?.headers),
signal: AbortSignal.timeout(timeoutMs),
})
} catch (e) {
@@ -113,13 +134,13 @@ async function consoleFetch(url, token, init, what, timeoutMs = TIMEOUT_MS) {
}
/** GET a console API. `query` is an object of search params. */
export function consoleGet(path, token, { query, timeoutMs } = {}) {
export function consoleGet(path, token, { query, timeoutMs, auth } = {}) {
const q = query ? `?${new URLSearchParams(query)}` : ""
return consoleFetch(`${ENDPOINTS.console}${path}${q}`, token, { method: "GET" }, path, timeoutMs)
return consoleFetch(`${ENDPOINTS.console}${path}${q}`, token, { method: "GET" }, path, timeoutMs, auth)
}
/** POST/PUT/DELETE a console API. */
export function consoleSend(path, token, { method = "POST", body, headers, timeoutMs } = {}) {
export function consoleSend(path, token, { method = "POST", body, headers, timeoutMs, auth } = {}) {
return consoleFetch(
`${ENDPOINTS.console}${path}`,
token,
@@ -130,6 +151,7 @@ export function consoleSend(path, token, { method = "POST", body, headers, timeo
},
path,
timeoutMs,
auth,
)
}
@@ -194,7 +216,7 @@ export const usersValidate = (token, o) => consoleGet(`${CONSOLE_API}/users/vali
export const freeGrant = (token, o) => consoleSend(`${CONSOLE_API}/users/free-grant`, token, { ...o })
export function listKeys(token, o) {
return consoleGet(`${CONSOLE_API}/keys`, token, o)
return consoleGet(`${CONSOLE_API}/keys`, token, { ...o, auth: "cookie" })
}
export function createKey(token, name, idempotencyKey, o) {
@@ -202,11 +224,12 @@ export function createKey(token, name, idempotencyKey, o) {
body: { name },
headers: { "Idempotency-Key": idempotencyKey },
...o,
auth: "cookie",
})
}
export function deleteKey(token, id, o) {
return consoleSend(`${CONSOLE_API}/keys/${encodeURIComponent(id)}`, token, { method: "DELETE", ...o })
return consoleSend(`${CONSOLE_API}/keys/${encodeURIComponent(id)}`, token, { method: "DELETE", ...o, auth: "cookie" })
}
/** A stable short fingerprint for names and cache buckets. */
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
File diff suppressed because one or more lines are too long
+232
View File
@@ -0,0 +1,232 @@
// 预检层的测试:图片限制的边界、改写的正确性、错误翻译,以及最重要的——
// 我们给的拒绝体必须命中 magpie 宿主 shapeRefused 的词表且不触发任何排除词
// (词表从宿主源码 internal/gateway/fallback.go 的正则原样抄下,宿主改词表
// 时这里的测试要跟着对)。
import "./nonet.mjs"
import { describe, expect, test } from "bun:test"
import { IMAGE_LIMITS, decodedBytes, imageOf, precheckImages, rewriteBody, translateError } from "./lib/preflight.mjs"
/* ------------------------------------------------ 宿主词表(fallback.go 原样) */
const R = (s) => new RegExp(s, "i")
const HOST = {
shapeWords: R(
"failed to deserialize|unknown (item |content |input )?(type|variant|field|parameter)|unknown_parameter|unrecognized (request argument|field|parameter)|extra (inputs|fields) are not permitted|additional properties are not allowed|schema exceeds the maximum (nesting )?depth|schema[^\\\"]{0,60}\\bnesting depth\\b|function_declarations\\[\\d+\\]\\.parameters\\b|schema specified other fields alongside any_?of",
),
quotaWords: R(
"quota|insufficient|balance|credit|billing|out of budget|budget (exceeded|exhausted)|exceeded|rate.?limit|usage.?limit|limit.?reached|hit your .*limit|limit.{0,24}resets|too many requests|overloaded|余额|额度|欠费|限流|频率|频繁|速率|套餐|用量|上限",
),
creditWords: R(
"insufficient.?(balance|credit|fund)|balance|credit|billing|payment|arrear|overdue|suspended|余额|欠费|充值|账户.*(不足|停)",
),
unservedWords: R(
"model.{0,80}(not (supported|accessible|available|found|enabled|allowed)|unsupported|does ?n[o']t exist|unknown|invalid)|(no such|unknown|invalid|unsupported) model|model_not_found|has no provider supported|deployment[ _]?not[ _]?found|deployment.{0,60}does ?n[o']t exist|模型.{0,12}(不存在|不支持|无权|未开通)",
),
refusedWords: R("unapproved channel|illegal api invocation"),
}
/** 宿主 shapeRefused 的等价实现:400/422 + 命中形状词 + 无排除词 → 问下家不休息。 */
function hostShapeRefused(status, bodyText) {
return (
(status === 400 || status === 226 || status === 422) &&
HOST.shapeWords.test(bodyText) &&
!HOST.quotaWords.test(bodyText) &&
!HOST.creditWords.test(bodyText) &&
!HOST.unservedWords.test(bodyText) &&
!HOST.refusedWords.test(bodyText)
)
}
/* ------------------------------------------------ 图片模型 */
const tiny = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
const img = (url, detail) => ({ type: "image_url", image_url: detail ? { url, detail } : { url } })
const body = (n, url = `data:image/png;base64,${tiny}`) => ({
model: "Sage-A1.5",
messages: [{ role: "user", content: [{ type: "text", text: "x" }, ...Array.from({ length: n }, () => img(url))] }],
})
describe("decodedBytes", () => {
test("reverses the 4/3 b64 growth (no padding)", () => {
expect(decodedBytes("AAAA")).toBe(3)
expect(decodedBytes("AAAAA")).toBe(3) // 5*3/4=3.75 floor 3, no padding marker
})
test("subtracts the padding", () => {
// tiny 是一个真实 1x1 PNG(70 字节),base64 后 96 字符、双 = 结尾。
expect(decodedBytes(tiny)).toBe(70)
// 多补一个 = 不改变解码语义(仍按 == 读 2 个填充)。
expect(decodedBytes(`${tiny}=`)).toBe(70)
expect(decodedBytes("")).toBe(0)
expect(decodedBytes(undefined)).toBe(0)
// 单 = 结尾的 4n+1 长度(非法长度向下取整到 2 字节)。
const onePad = "AAAA=" // 5 chars, ends with single =
expect(decodedBytes(onePad)).toBe(2)
})
})
describe("imageOf", () => {
test("reads a data: URL's type and size", () => {
const one = imageOf(`data:image/png;base64,${tiny}`)
expect(one.type).toBe("image/png")
expect(one.inline).toBe(true)
expect(one.bytes).toBe(decodedBytes(tiny))
})
test("data:image/jpg is read as image/jpeg (the informal type is in the wild)", () => {
expect(imageOf("data:image/jpg;base64,AAAA").type).toBe("image/jpeg")
})
test("a data: URL without base64 is zero bytes", () => {
expect(imageOf("data:image/svg+xml,<svg/>")).toEqual({ type: "image/svg+xml", bytes: 0, inline: true })
})
test("a URL whose extension is a known-untaken type is refused", () => {
expect(imageOf("https://x.test/p.svg?w=1").type).toBe("image/svg")
expect(imageOf("https://x.test/p.heic").type).toBe("image/heic")
expect(imageOf("https://x.test/p.tif").type).toBe("image/tif")
})
test("a URL with an unknown (or no) extension passes — the plan fetches and judges the bytes itself", () => {
// 每一个都曾被误判为图片类型而拒绝(真机审查,2026-11-07)
for (const url of ["https://x.test/render.php?id=1", "https://x.test/abc.download", "https://x.test/12345.67", "https://x.test/noext", "https://x.test/a.png?w=1"]) {
expect(imageOf(url).type).toBe("")
}
})
})
/* ------------------------------------------------ 边界(8/9 张、10MB、40MB、格式) */
const MB = 1048576
const b64OfRawMB = (mb) => "A".repeat(Math.round((mb * MB * 4) / 3))
describe("precheckImages", () => {
test("eight images pass, nine are refused with the count", () => {
expect(precheckImages(body(8))).toBeNull()
const refusal = precheckImages(body(9))
expect(refusal).not.toBeNull()
expect(refusal.status).toBe(400)
expect(refusal.body).toContain("9 images")
})
test("URL-referenced images count toward the cap too", () => {
expect(precheckImages(body(8, "https://x.test/a.png"))).toBeNull()
expect(precheckImages(body(9, "https://x.test/a.png"))).not.toBeNull()
})
test("a mixed base64 + URL request counts both", () => {
const b = body(4)
b.messages[0].content.push(...Array.from({ length: 4 }, () => img("https://x.test/a.png")))
expect(precheckImages(b)).toBeNull()
b.messages[0].content.push(img("https://x.test/a.png"))
expect(precheckImages(b)).not.toBeNull()
})
test("a 9.9 MB image passes, a 10.1 MB one is refused", () => {
expect(precheckImages(body(1, `data:image/png;base64,${b64OfRawMB(9.9)}`))).toBeNull()
const refusal = precheckImages(body(1, `data:image/png;base64,${b64OfRawMB(10.1)}`))
expect(refusal).not.toBeNull()
expect(refusal.body).toContain("10.1 MB")
})
test("39 MB total passes, 41 MB is refused", () => {
expect(precheckImages(body(4, `data:image/png;base64,${b64OfRawMB(9.5)}`))).toBeNull()
const refusal = precheckImages(body(5, `data:image/png;base64,${b64OfRawMB(9.5)}`))
expect(refusal).not.toBeNull()
expect(refusal.body).toContain("together")
})
test("an SVG (data: or URL) is refused as a format", () => {
expect(precheckImages(body(1, "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'/>"))).not.toBeNull()
expect(precheckImages(body(1, "https://x.test/picture.svg"))).not.toBeNull()
})
test("no images, no content array, a broken body: all pass", () => {
expect(precheckImages({ messages: [{ role: "user", content: "hi" }] })).toBeNull()
expect(precheckImages({})).toBeNull()
expect(precheckImages(null)).toBeNull()
})
})
/* ------------------------------------------------ 拒绝体必须命中宿主词表 */
describe("the refusal hits the host's shapeRefused, never its exclusions", () => {
for (const [name, make] of [
["count", () => precheckImages(body(9))],
["per-image", () => precheckImages(body(1, `data:image/png;base64,${b64OfRawMB(10.1)}`))],
["total", () => precheckImages(body(5, `data:image/png;base64,${b64OfRawMB(9.5)}`))],
["format", () => precheckImages(body(1, "data:image/svg+xml,<svg/>"))],
]) {
test(`${name}: 400 + shapeWords, no quota/credit/unserved/refused word`, () => {
const refusal = make()
expect(refusal.status).toBe(400)
expect(hostShapeRefused(400, refusal.body)).toBe(true)
// 逐词反查:哪一类误中了能直接看到
expect(HOST.quotaWords.test(refusal.body)).toBe(false)
expect(HOST.creditWords.test(refusal.body)).toBe(false)
expect(HOST.unservedWords.test(refusal.body)).toBe(false)
expect(HOST.refusedWords.test(refusal.body)).toBe(false)
// 中英都在:英文给宿主,中文给人
expect(refusal.body).toContain("extra inputs are not permitted")
expect(refusal.body).toMatch(/(.+)/)
})
}
})
/* ------------------------------------------------ 改写 */
describe("rewriteBody", () => {
test("adds detail: auto to every inline image lacking one", () => {
const out = JSON.parse(rewriteBody(JSON.stringify(body(2))))
for (const part of out.messages[0].content) {
if (part.type === "image_url") expect(part.image_url.detail).toBe("auto")
}
})
test("leaves a user's own detail alone", () => {
const b = { messages: [{ role: "user", content: [img(`data:image/png;base64,${tiny}`, "low")] }] }
const out = JSON.parse(rewriteBody(JSON.stringify(b)))
expect(out.messages[0].content[0].image_url.detail).toBe("low")
})
test("strips the fields the plan does not take", () => {
const b = { ...body(0), reasoning: { effort: "high" }, reasoning_effort: "high", thinking: { type: "enabled" }, output_config: { effort: "high" } }
const out = JSON.parse(rewriteBody(JSON.stringify(b)))
expect("reasoning" in out).toBe(false)
expect("reasoning_effort" in out).toBe(false)
expect("thinking" in out).toBe(false)
expect("effort" in out.output_config).toBe(false)
})
test("a body that is not JSON, not an object, or already clean goes back as it came", () => {
expect(rewriteBody("not json")).toBe("not json")
expect(rewriteBody("[1,2]")).toBe("[1,2]")
const clean = JSON.stringify(body(1, `data:image/png;base64,${tiny}`)).replace(/}$/,"") // keep detail-less
const out = rewriteBody(JSON.stringify(body(1)))
expect(() => JSON.parse(out)).not.toThrow()
expect(rewriteBody(JSON.stringify({ messages: [{ role: "user", content: "hi" }] }))).toBe(JSON.stringify({ messages: [{ role: "user", content: "hi" }] }))
})
})
/* ------------------------------------------------ 错误翻译 */
describe("translateError", () => {
test("the four image refusals become shape refusals the host can switch on", () => {
for (const [status, bodyText] of [
[400, JSON.stringify({ code: "invalid_media", message: "too many images in request" })],
[400, JSON.stringify({ code: "invalid_media", message: "inline image exceeds configured byte limit" })],
[400, JSON.stringify({ code: "invalid_media", message: "cumulative image bytes exceeded configured request limit" })],
[400, JSON.stringify({ code: "invalid_media", message: "unsupported media type" })],
[502, JSON.stringify({ code: "media_fetch_failed", message: "could not fetch https://x.test/a.png" })],
]) {
const translated = translateError(status, bodyText)
expect(translated).not.toBeNull()
expect(translated.status).toBe(400)
// 宿主读得对:问下家、本家不休息——而不是 quota 误判("exceeded" 在原话里!)
expect(hostShapeRefused(translated.status, translated.body)).toBe(true)
expect(HOST.quotaWords.test(translated.body)).toBe(false)
}
})
test("a 400 the plan words differently, and non-JSON, pass through untranslated", () => {
expect(translateError(400, JSON.stringify({ code: "invalid_request", message: "bad" }))).toBeNull()
expect(translateError(400, "not json")).toBeNull()
expect(translateError(429, JSON.stringify({ error: { code: "quota_exceeded" } }))).toBeNull()
expect(translateError(500, JSON.stringify({ code: "invalid_media" }))).toBeNull()
})
})
/* ------------------------------------------------ 限额常量与实测对齐 */
describe("IMAGE_LIMITS match what the platform answered", () => {
test("8 images, 10 MB a picture, 40 MB a request", () => {
expect(IMAGE_LIMITS.count).toBe(8)
expect(IMAGE_LIMITS.perImage).toBe(10 * MB)
expect(IMAGE_LIMITS.total).toBe(40 * MB)
})
})
+3
View File
@@ -44,6 +44,9 @@ if (!headless) {
mkdirSync(profilePath, { recursive: true })
const server = Bun.serve({
port: 0,
// 仅本机回环:绑 0.0.0.0(不指定 hostname 的默认)会触发 Windows 防火墙
// 对每次编译出来的新 exe 弹"允许访问",路径随机所以每次都弹
hostname: "127.0.0.1",
fetch(req, server) {
const u = new URL(req.url)
if (u.pathname === "/json/version") return Response.json({ Browser: "FakeChrome/1.0" })
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
-1
View File
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)