diff --git a/README.md b/README.md index 4b614f8..9ce6119 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ subscription and makes its requests. The packages work in OpenCode and in | [devin](packages/devin) | Devin subscription (the devin CLI's account) | `devin` | | [factory](packages/factory) | Factory (Droid) subscription | `factory` | | [grok](packages/grok) | Grok (SuperGrok / X Premium+), through the Grok Build CLI's sign-in | `grok` | +| [joycode](packages/joycode) | JoyCode IDE credits with JD account browser sign-in, live models and credit multipliers (unofficial) | `joycode` | | [kimi-work](packages/kimi-work) | Ordinary Kimi desktop Work subscription, through the desktop app's local sign-in; separate from Kimi Code | `kimi-work` | | [kiro](packages/kiro) | Kiro (Free, Pro, Pro+, Power), with Kiro's sign-in, kiro-cli's or the IDE's, or an API key | `kiro` | | [minimax](packages/minimax) | MiniMax Code (China): account credits and M Plan, with MiniMax Code's device sign-in | `minimax-code` | diff --git a/packages/joycode/CHANGELOG.md b/packages/joycode/CHANGELOG.md new file mode 100644 index 0000000..bbb9bc0 --- /dev/null +++ b/packages/joycode/CHANGELOG.md @@ -0,0 +1,16 @@ +# 更新记录 + +## 0.1.1 + +- 支持浏览器登录京东账号,自动接收并验证 JoyCode 票据,保存租户和登录类型。 +- 接入 IDE 同款额度接口,展示套餐、已用/剩余积分及有效期文字。 +- 按账号动态同步模型列表和积分消耗倍率,正确识别 0× 免费模型。 +- 补齐聊天请求所需的真实账号元数据,修复已登录却无法回复的问题。 +- 将 HTTP 200 流式响应中的裸 JSON 错误转换为明确错误,避免客户端空白等待;权限错误不再误判为登录过期。 +- 保留多轮消息与工具调用,加入 JoyCode 图标并缩短本地插件目录名。 + +验证:25 项回归测试通过;JoyAI-Code-1.6 的真实流式回复、工具调用往返和 magpie provider test 通过;用户确认 Claude 桌面端可使用。 + +## 0.1.0 + +- 本地供应商插件原型:手动 ptKey 登录、静态模型列表、签名网关转发及可选纯文本压平模式。 diff --git a/packages/joycode/LICENSE b/packages/joycode/LICENSE new file mode 100644 index 0000000..59a6d9c --- /dev/null +++ b/packages/joycode/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 kasisama + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/joycode/README.md b/packages/joycode/README.md new file mode 100644 index 0000000..9a07378 --- /dev/null +++ b/packages/joycode/README.md @@ -0,0 +1,73 @@ +# JoyCode + +把京东云 **JoyCode**(JoyCoder IDE 自带的模型额度)作为一个 OpenAI 兼容供应商接进 [magpie](https://usemagpie.ai)。装好后,所有 agent(Claude Code、Codex 等)都能通过 magpie 用 `joycode/` 访问 JoyCode 的模型,并享受 magpie 的多账号号池、故障切换和用量统计。 + +逆向了 JoyCode IDE 的「彩网关」协议(`https://api-ai.jd.com/api`,HMAC-SHA256 签名 query + `ptKey` 账号票据头)。请求与 IDE 本身走同一账号、同一额度。 + +## 安装 + +```bash +magpie plugin add @magpie-community/opencode-joycode-auth +``` + +```bash +magpie plugin login joycode +``` + +两种登录方式(任选): + +1. **浏览器登录(京东账号)**(推荐)— magpie 打开 JoyCode 官方登录页,用京东账号/扫码登录,完成后自动拿到凭证。和 JoyCode IDE 自己的登录走的是同一套流程。 +2. **手动粘贴 ptKey** — 从已登录的 JoyCode IDE 登录态里提取(`%APPDATA%\JoyCode\User\globalStorage\state.vscdb` 的 `JoyCoder.IDE` → `joyCoderUser.ptKey`)。这是**账号票据**,等同密码,勿外传。这种方式还会追问可选的 tenant(企业租户名,个人账号留空)。 + +凭证由 magpie 存在自己的 `plugin-auth.json`(权限 600),本插件目录里不落任何凭证。 + +多账号 = 多次登录:`magpie plugin login joycode` 再跑一遍(或在应用里再点一次),每个账号是一个号池座位,magpie 会自动轮换。 + +## 模型 + +| 模型 ID(magpie 里用 `joycode/…`) | 上下文 | 输出 | 推理 | 视觉 | +|---|---|---|---|---| +| `joycode/JoyAI-Code-1.6` | 200k | 64k | — | — | +| `joycode/GLM-5.3-agent` | 200k | 64k | ✓ | — | +| `joycode/Kimi-K2.6-agent` | 200k | 64k | ✓ | 实验 | +| `joycode/MiniMax-M3-agent` | 200k | 64k | ✓ | 实验 | +| `joycode/Doubao-Seed-2.0-pro-agent` | 200k | 64k | ✓ | 实验 | + +登录后通过 `joycode_modelList` 同步账号可用模型,并通过 `plugin_config` 的 `billingRate` 场景同步积分消耗倍率。点击「重新获取模型」可更新模型和倍率;按 `chatApiModel` 匹配,不会把仅出现在计费表中的模型加入列表。模型自身的倍率优先;公共倍率配置遵守 `excludeTenants`,无租户或被排除的租户不套用公共倍率。明确的 0× 会标记免费;查不到的倍率不当作 0×,也不虚构优惠前倍率。 + +当前实测:JoyAI-Code-1.6 0×、GLM-5.3 0.6×、Kimi-K2.6 0.5×、MiniMax-M3 0.4×、Doubao-Seed-2.0-pro 0.4×。这些是查询结果,代码没有写死价格。它们是积分倍率,不是美元/token 价格。 + +**视觉(image_url)为实验性**:按接口 `features` 声明能力,实际图片请求尚未验收。 + +## 消息转发策略 + +默认保留完整多轮对话及工具调用:magpie 转换为 OpenAI chat completions 后,插件从当前账号的 `joycode_userInfo` 获取真实 `userId`、`tenant`、`orgFullName`,按 IDE 请求格式补入正文,并设置 `language: UNKNOWN`。身份信息按账号 loader 隔离缓存,不接受客户端指定的用户身份。缺少这些元数据时,已观察到网关返回 `AI_GRAY_ACCESS_DENIED`。 + +网关可能以 HTTP 200 和 SSE 响应头返回裸 JSON 错误;插件会把这种错误转换为明确的失败响应,避免客户端一直等待。普通 403 权限错误不会再被误标为登录失效。 + +已实测 JoyAI-Code-1.6 完整流式文字回复、工具调用及工具结果往返,并通过 magpie `provider test`。用户已确认 Claude 桌面端正常使用。 + +如果实测 JoyCode 后端拒绝多轮/工具调用格式的消息,可以开启回退模式: + +```bash +magpie plugin options joycode '{"flatten": true}' +``` + +flatten 模式会把消息压平成 `system + 单条 user prompt`(工具调用和工具结果会被丢弃)。**开了 flatten 就别用 joycode 的模型跑需要工具的 agent 会话**,只适合纯对话。默认关闭。 + +## 已知限制 + +- **额度展示**:通过 IDE 同款 `get_newpoint_ide` 接口读取套餐、已用/总积分、剩余积分和有效期文字,可在账号及用量页面刷新。有效期文字不等同于额度重置时间,因此不推算重置倒计时。多个积分池分别显示,不相加;额度窗口仅作展示,由上游判定具体模型能否继续使用。 +- **ptKey 失效**:表现为账号被标记「需要重新登录」,重新 `magpie plugin login joycode` 即可。 +- **签名 key 轮换**:签名 key 是内嵌在每份 JoyCode IDE 里的公开协议常量,不是密钥。若 JoyCode 轮换它,从新版 `extension.js` 重新提取后,可通过环境变量 `JOYCODE_SIGN_KEY` 覆盖,无需改代码。 +- 登录方式默认 `loginType: PIN_JD_CLOUD`;如果你的账号是京东云企业域登录且请求被拒,改 `index.mjs` 顶部的 `LOGIN_TYPE` 常量。 + +## 开发 + +```bash +bun test # 浏览器登录、额度映射、模型倍率回归测试 +``` + +相关文档:[magpie 插件开发](https://usemagpie.ai/docs/zh/plugins)。版本变更见 [CHANGELOG.md](CHANGELOG.md)。 + +这是非官方适配插件,与京东或 magpie 官方无隶属关系。JoyCode 图标及商标归其权利人所有;代码的 MIT 许可不授予这些品牌资产的权利。 diff --git a/packages/joycode/chat.test.mjs b/packages/joycode/chat.test.mjs new file mode 100644 index 0000000..0cbed34 --- /dev/null +++ b/packages/joycode/chat.test.mjs @@ -0,0 +1,99 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import plugin from './index.mjs' + +async function request(t, response) { + t.mock.method(globalThis, 'fetch', async url => new URL(url).searchParams.get('functionId') === 'joycode_userInfo' + ? Response.json({ code: 0, data: { userId: 'test-user', tenant: 'test-tenant', orgFullName: 'test-org' } }) + : response) + const hooks = await plugin.server({}) + const loader = await hooks.auth.loader(async () => ({ type: 'api', key: 'fake-key' })) + return loader.fetch('https://api-ai.jd.com/v1/chat/completions', { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model: 'JoyAI-Code-1.6', messages: [{ role: 'user', content: 'OK' }], stream: true }), + }) +} +function chunks(parts) { + return new ReadableStream({ start(c) { for (const p of parts) c.enqueue(new TextEncoder().encode(p)); c.close() } }) +} +test('HTTP 200 raw gateway denial becomes actionable error, not empty SSE', async t => { + const r = await request(t, new Response(chunks([' {"error":', '{"code":"AI_GRAY_ACCESS_DENIED","message":"访问受限,请联系管理员开通"}}']), { headers: { 'content-type': 'text/event-stream' } })) + assert.equal(r.status, 403) + assert.equal(r.headers.get('x-magpie-sign-in'), 'kept') + assert.equal((await r.json()).error.code, 'AI_GRAY_ACCESS_DENIED') +}) +test('HTTP 200 SSE with JD msg preserves the business error reason', async t => { + const r = await request(t, new Response(JSON.stringify({ code: 9, msg: '积分已用完', data: { private: 'private-marker' } }), { headers: { 'content-type': 'text/event-stream' } })) + assert.equal(r.status, 502) + assert.equal(r.headers.get('x-magpie-sign-in'), 'kept') + assert.deepEqual((await r.json()).error, { type: 'upstream_error', code: 9, message: '积分已用完' }) +}) + +test('HTTP 200 SSE code 401 expires a ticket after identity has been cached', async t => { + let infoCalls = 0, chats = 0 + t.mock.method(globalThis, 'fetch', async url => { + if (new URL(url).searchParams.get('functionId') === 'joycode_userInfo') { + infoCalls++ + return Response.json({ code: 0, data: { userId: 'test-user' } }) + } + chats++ + return new Response(chats === 1 ? 'data: [DONE]\n\n' : JSON.stringify({ code: 401, data: null, msg: '登录票据已失效' }), { headers: { 'content-type': 'text/event-stream' } }) + }) + const hooks = await plugin.server({}) + const loader = await hooks.auth.loader(async () => ({ type: 'api', key: 'fake-key' })) + const send = () => loader.fetch('https://api-ai.jd.com/v1/chat/completions', { + method: 'POST', body: JSON.stringify({ model: 'JoyAI-Code-1.6', messages: [{ role: 'user', content: 'OK' }], stream: true }), + }) + const first = await send() + assert.equal(first.status, 200) + await first.text() + const expired = await send() + assert.equal(infoCalls, 1) + assert.equal(chats, 2) + assert.equal(expired.status, 401) + assert.equal(expired.headers.get('x-magpie-sign-in'), 'expired') + assert.deepEqual((await expired.json()).error, { type: 'upstream_error', code: 401, message: '登录票据已失效' }) +}) + +test('valid SSE including tool deltas is preserved byte for byte', async t => { + const text = ': heartbeat\n\ndata: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{}"}}]}}]}\n\ndata: [DONE]\n\n' + const r = await request(t, new Response(chunks([text.slice(0,4), text.slice(4)]), { headers: { 'content-type': 'text/event-stream' } })) + assert.equal(r.status, 200) + assert.equal(await r.text(), text) +}) +test('empty upstream success becomes gateway error', async t => { + const r = await request(t, new Response('', { headers: { 'content-type': 'text/event-stream' } })) + assert.equal(r.status, 502) +}) +test('chat adds authenticated account metadata while preserving tools and messages', async t => { + let infoCalls = 0 + const payload = { model: 'JoyAI-Code-1.6', messages: [{ role: 'user', content: 'OK' }], tools: [{ type: 'function', function: { name: 'ping', parameters: { type: 'object' } } }], stream: true, userId: 'untrusted-user' } + t.mock.method(globalThis, 'fetch', async (url, init) => { + if (new URL(url).searchParams.get('functionId') === 'joycode_userInfo') { + infoCalls++ + return Response.json({ code: 0, data: { userId: 'test-user', tenant: 'test-tenant', orgFullName: 'test-org' } }) + } + const sent = JSON.parse(init.body) + assert.equal(sent.userId, 'test-user') + assert.equal(sent.tenant, 'test-tenant') + assert.equal(sent.orgFullName, 'test-org') + assert.equal(sent.language, 'UNKNOWN') + assert.deepEqual(sent.messages, payload.messages) + assert.deepEqual(sent.tools, payload.tools) + assert.equal(init.headers.get('tenant'), 'test-tenant') + return new Response('data: [DONE]\n\n', { headers: { 'content-type': 'text/event-stream' } }) + }) + const hooks = await plugin.server({}) + const loader = await hooks.auth.loader(async () => ({ type: 'api', key: 'fake-key' })) + for (let i = 0; i < 2; i++) { + const r = await loader.fetch('https://api-ai.jd.com/v1/chat/completions', { method: 'POST', body: JSON.stringify(payload) }) + await r.text() + } + assert.equal(infoCalls, 1) +}) + +test('HTTP 403 permission denial is not marked as expired credentials', async t => { + const r = await request(t, Response.json({ error: { code: 'AI_GRAY_ACCESS_DENIED', message: 'denied' } }, { status: 403 })) + assert.equal(r.status, 403) + assert.equal(r.headers.get('x-magpie-sign-in'), 'kept') +}) diff --git a/packages/joycode/icon.png b/packages/joycode/icon.png new file mode 100644 index 0000000..e2e089d Binary files /dev/null and b/packages/joycode/icon.png differ diff --git a/packages/joycode/index.mjs b/packages/joycode/index.mjs new file mode 100644 index 0000000..0005470 --- /dev/null +++ b/packages/joycode/index.mjs @@ -0,0 +1,610 @@ +#!/usr/bin/env bun +/** + * opencode-joycode-auth — JoyCode (JD Cloud JoyCoder IDE credits) as a + * magpie / OpenCode provider. + * + * Protocol derived from the JoyCode IDE's bundled extension.js: + * POST https://api-ai.jd.com/api?appid=joycode_ide&functionId=chat_completions&t=&sign= + * headers: ptKey (account ticket), loginType, optional tenant + * body: OpenAI chat completions JSON + * + * magpie's gateway already converts any agent API into OpenAI chat + * completions format before calling our fetch. We sign each request, inject + * credential headers, and add authenticated account identity to the body. + * We inspect response prefixes for bare JSON gateway errors; valid SSE bytes + * are replayed unchanged, including tool-call deltas. + * + * Options (magpie plugin options joycode '{"…"}'): + * { "flatten": true } — flatten multi-turn messages into a single prompt + * before sending (fallback if JoyCode rejects multi-turn / tool-call + * payloads). Drops tools; useful for plain chat only. + */ +import { createHmac, randomBytes } from 'node:crypto' +import { createServer } from 'node:http' + +const PROVIDER = 'joycode' +const BASE = 'https://api-ai.jd.com' +const GATEWAY_PATH = '/api' +const APPID = 'joycode_ide' +const FUNCTION_ID = 'chat_completions' +const LOGIN_TYPE = 'PIN_JD_CLOUD' + +// HMAC signing key, extracted from the JoyCode IDE's bundled extension.js. +// +// This is a PUBLIC PROTOCOL CONSTANT, not a secret: it is baked into every +// copy of the IDE and identifies the client, nothing more. It cannot +// authorize a request on its own — the account credential is the `ptKey` +// header, which magpie stores in its plugin-auth.json (mode 600), never in +// this folder. +// +// If JoyCode ever rotates the key, re-extract it from extension.js and update +// this constant (or override at runtime via JOYCODE_SIGN_KEY). +const SIGN_KEY = process.env.JOYCODE_SIGN_KEY || '0691a3f0b37b4a85aeb63ad0fc7db3ed' + +/** Models the JoyCode backend offers (from /joycode_modelList). */ +const MODELS = { + 'JoyAI-Code-1.6': { + name: 'JoyAI Code 1.6', + limit: { context: 200000, output: 64000 }, + tool_call: true, + }, + 'GLM-5.3-agent': { + name: 'GLM 5.3', + limit: { context: 200000, output: 64000 }, + reasoning: true, + tool_call: true, + modalities: { input: ['text'] }, + }, + 'Kimi-K2.6-agent': { + name: 'Kimi K2.6', + limit: { context: 200000, output: 64000 }, + reasoning: true, + tool_call: true, + modalities: { input: ['text', 'image'] }, + }, + 'MiniMax-M3-agent': { + name: 'MiniMax M3', + limit: { context: 200000, output: 64000 }, + reasoning: true, + tool_call: true, + modalities: { input: ['text', 'image'] }, + }, + 'Doubao-Seed-2.0-pro-agent': { + name: 'Doubao Seed 2.0 Pro', + limit: { context: 200000, output: 64000 }, + reasoning: true, + tool_call: true, + modalities: { input: ['text', 'image'] }, + }, +} + +// ---------------------------------------------------------------- helpers +// (not exported as module functions: the plugin host treats every exported +// function as a plugin and calls it — v1 default {id, server} below keeps +// them out of that. The test surface is `_internal`.) + +/** + * JoyCode gateway signature (mirrors extension.js module 68327): + * merged = { ...extra, appid, functionId, t: Date.now() } + * h = sortedKeys.map(k => merged[k]).filter(non-empty).join('&') + * sign = hex( HMAC-SHA256(h, secret) ) + * + * The timestamp `t` is part of the signed material, so this MUST be called + * per request — never cache the result. + */ +function signQuery(functionId, extra = {}) { + const merged = { ...extra, appid: APPID, functionId, t: Date.now() } + const h = Object.keys(merged) + .sort() + .map((k) => merged[k]) + .filter((v) => v !== '' && v !== undefined && v !== null) + .join('&') + const sig = createHmac('sha256', SIGN_KEY).update(h).digest('hex') + return { ...merged, sign: sig } +} + +/** Build the signed gateway URL for one request. */ +function buildGatewayUrl(functionId) { + const u = new URL(GATEWAY_PATH, BASE) + for (const [k, v] of Object.entries(signQuery(functionId))) u.searchParams.set(k, String(v)) + return u.toString() +} + +/** Credential headers the gateway expects (ptKey is the account auth). */ +function buildGatewayHeaders(ptKey, tenant, loginType = LOGIN_TYPE) { + return { + ptkey: ptKey, + logintype: loginType, + ...(tenant ? { tenant: encodeURIComponent(tenant) } : {}), + } +} + +/** + * OpenAI `messages` -> { prompt, system } — fallback for accounts/backends + * that reject multi-turn or tool-call payloads. + */ +function flattenMessages(messages) { + const systemParts = [] + const turns = [] + + for (const m of messages ?? []) { + const role = m.role + const content = typeof m.content === 'string' + ? m.content + : Array.isArray(m.content) + ? m.content + .map((c) => { + if (typeof c === 'string') return c + if (c?.type === 'text') return c.text ?? '' + if (c?.type === 'image_url') return '[image omitted]' + return '' + }) + .join('') + : '' + + if (role === 'system' || role === 'developer') { + if (content.trim()) systemParts.push(content.trim()) + continue + } + if (!content.trim()) continue + + if (role === 'user') turns.push(`User: ${content}`) + else if (role === 'assistant') turns.push(`Assistant: ${content}`) + else if (role === 'tool') turns.push(`Tool result: ${content}`) + } + + let prompt + if (turns.length === 1 && turns[0].startsWith('User: ')) { + prompt = turns[0].slice('User: '.length) + } else if (turns.length === 0) { + prompt = systemParts.join('\n\n') || '' + } else { + prompt = `${turns.join('\n\n')}\n\nAssistant:` + } + + return { prompt, system: systemParts.join('\n\n') } +} + +/** Flatten a chat completions body into the minimal shape JoyCode accepts. */ +function flattenBody(payload) { + const { prompt, system } = flattenMessages(payload.messages) + return { + model: payload.model, + messages: [ + ...(system ? [{ role: 'system', content: system }] : []), + { role: 'user', content: prompt }, + ], + stream: payload.stream === true, + ...(payload.stream ? {} : { max_tokens: 64000 }), + } +} + +// ---------------------------------------------------------------- browser login + +/** + * Loopback OAuth, mirroring JoyCode IDE's own login flow (reversed from + * extension.js): + * + * 1. We start a localhost server on a random port and hand magpie the URL + * https://joycode.jd.com/login/?ideAppName=…&fromIde=ide&redirect=0 + * &authPort=&authKey= (magpie opens it in the browser) + * 2. After the user signs in with their JD account, joycode.jd.com calls + * back http://localhost:/…?authPort&authKey&pt_key&loginType&callbackUrl + * 3. We verify authKey matches (CSRF), call joycode_userInfo with the + * pt_key to confirm it works and to learn the account name, then hand + * magpie the completed login. + */ +const LOGIN_URL = 'https://joycode.jd.com/login/' + +function callUserInfo(ptKey, loginType, tenant) { + return fetch(buildGatewayUrl('joycode_userInfo'), { + method: 'POST', + headers: { + 'content-type': 'application/json', + ...buildGatewayHeaders(ptKey, tenant, loginType || LOGIN_TYPE), + }, + body: '{}', + signal: AbortSignal.timeout(30_000), + }).then(async (r) => { + const json = await r.json().catch(() => null) + const user = json?.data + return { + ok: r.ok && json?.code === 0 && typeof user?.userId === 'string' && user.userId.length > 0, + status: r.status, + user, + } + }) +} + +/** + * magpie oauth method contract: + * authorize() returns { url, method: "auto", callback } + * magpie opens `url`; callback() resolves when our loopback server gets + * the redirect. + */ +async function browserLogin() { + const authKey = randomBytes(16).toString('hex') + + // Start the loopback server first so the port in the URL is live. + let resolveLogin + const promise = new Promise((resolve) => { resolveLogin = resolve }) + + const server = createServer((req, res) => { + const u = new URL(req.url ?? '/', 'http://localhost') + const q = u.searchParams + const finish = (ok, message, extra = {}) => { + res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }) + res.end(`${ + ok + ? '

JoyCode 登录成功 ✓

可以回到 magpie 了,此页面会自动关闭。

' + : `

JoyCode 登录失败

${message}

请回到 magpie 重新开始登录。

` + }`) + clearTimeout(expiry) + server.close() + resolveLogin(ok ? { ok: true, ...extra } : { ok: false, error: message }) + } + if (q.get('authKey') !== authKey || Number(q.get('authPort')) !== server.address()?.port) { + res.writeHead(404) + return res.end() + } + const ptKey = q.get('pt_key') + const loginType = q.get('loginType') || LOGIN_TYPE + const tenant = q.get('tenant') || '' + if (!ptKey) return finish(false, '登录页没有返回 pt_key') + // The gateway wraps user information in { code: 0, data: { userId, ... } }. + // Never display its raw response: it contains private account fields. + callUserInfo(ptKey, loginType, tenant) + .then(({ ok, status, user }) => { + if (ok) { + finish(true, '', { ptKey, loginType, tenant, userName: user.userName || user.userId }) + } else { + finish(false, `JoyCode 账号信息校验未通过(HTTP ${status}),请重新登录`) + } + }) + .catch(() => finish(false, '验证票据时网络请求失败或超时,请重试')) + }) + + await new Promise((resolve, reject) => { + server.on('error', reject) + server.listen(0, '127.0.0.1', resolve) + }) + // Auto-expire after 10 minutes (JoyCode IDE uses the same timeout). + const expiry = setTimeout(() => { + try { server.close() } catch {} + resolveLogin({ ok: false, error: '登录超时(10 分钟未完成)' }) + }, 600_000) + expiry.unref?.() + + const port = server.address().port + const url = `${LOGIN_URL}?ideAppName=JoyCode&fromIde=ide&redirect=0&authPort=${port}&authKey=${authKey}` + return { + url, + instructions: '在打开的浏览器里登录你的京东账号(可扫码)。完成后此窗口会自动继续。', + method: 'auto', + async callback() { + const result = await promise + if (!result.ok) return { type: 'failed', error: result.error } + return { + type: 'success', + key: result.ptKey, // saved as { type: "api", key } + accountId: result.userName || undefined, + metadata: { loginType: result.loginType, tenant: result.tenant }, + } + }, + } +} + +// ---------------------------------------------------------------- chat responses + +function chatError(status, code, message) { + return Response.json({ error: { type: 'upstream_error', code, message } }, { + status, + headers: { 'x-magpie-sign-in': status === 401 ? 'expired' : 'kept' }, + }) +} + +async function normalizeChatResponse(response) { + if (!response.ok) { + const headers = new Headers(response.headers) + headers.set('x-magpie-sign-in', response.status === 401 ? 'expired' : 'kept') + return new Response(response.body, { status: response.status, headers }) + } + if (!response.body) return chatError(502, 'empty_response', 'JoyCode 返回空响应') + const reader = response.body.getReader() + const buffered = [] + const decoder = new TextDecoder() + let prefix = '' + let bytes = 0 + // The gateway can label a plain JSON error as HTTP 200 text/event-stream. + // Inspect the prefix before exposing success headers to magpie. + while (!prefix.trim() && bytes <= 65536) { + const next = await reader.read() + if (next.done) break + buffered.push(next.value) + bytes += next.value.byteLength + prefix += decoder.decode(next.value, { stream: true }) + } + if (!prefix.trim()) { + await reader.cancel() + return chatError(502, 'empty_response', 'JoyCode 返回空响应') + } + if (prefix.trimStart().startsWith('{')) { + while (bytes <= 1024 * 1024) { + const next = await reader.read() + if (next.done) break + bytes += next.value.byteLength + prefix += decoder.decode(next.value, { stream: true }) + } + await reader.cancel() + prefix += decoder.decode() + let json + try { json = JSON.parse(prefix) } catch {} + if (json?.error || (json?.code !== undefined && Number(json.code) !== 0)) { + const code = json.error?.code ?? json.code + const status = code === 'AI_GRAY_ACCESS_DENIED' ? 403 : Number(code) === 401 ? 401 : 502 + const message = json.error?.message ?? json.message ?? json.msg + return chatError(status, code, typeof message === 'string' ? message.slice(0, 500) : 'JoyCode 请求被拒绝') + } + if (json?.choices) return Response.json(json) + return chatError(502, 'invalid_response', 'JoyCode 未返回有效的对话响应') + } + // Replay the inspected bytes and then stream normally, preserving tool deltas. + const headers = new Headers(response.headers) + headers.delete('content-length') + headers.delete('content-encoding') + return new Response(new ReadableStream({ + async pull(controller) { + if (buffered.length) { controller.enqueue(buffered.shift()); return } + try { + const next = await reader.read() + if (next.done) controller.close() + else controller.enqueue(next.value) + } catch (error) { controller.error(error) } + }, + cancel(reason) { return reader.cancel(reason) }, + }), { status: response.status, headers }) +} + +// ---------------------------------------------------------------- account data + +async function fetchAccountData(auth, functionId, body = {}) { + if (auth?.type !== 'api' || !auth.key) { + throw Object.assign(new Error('请先登录 JoyCode'), { signIn: 'expired' }) + } + let response + try { + response = await fetch(buildGatewayUrl(functionId), { + method: 'POST', + headers: { + 'content-type': 'application/json; charset=UTF-8', + ...buildGatewayHeaders(auth.key, auth.metadata?.tenant, auth.metadata?.loginType || LOGIN_TYPE), + }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(15_000), + }) + } catch { + throw new Error('JoyCode 数据查询网络失败或超时') + } + const json = await response.json().catch(() => null) + if (response.status === 401 || Number(json?.code) === 401) { + throw Object.assign(new Error('JoyCode 登录已失效,请重新登录'), { signIn: 'expired' }) + } + if (!response.ok || !json || (json.code !== undefined && Number(json.code) !== 0)) { + const message = json?.error?.message ?? json?.message ?? json?.msg + throw new Error(`JoyCode 数据查询失败(HTTP ${response.status})${typeof message === 'string' ? `:${message.slice(0, 500)}` : ''}`) + } + return json.data ?? json +} + +function quotaFromData(data) { + const items = data?.usageItems + if (!Array.isArray(items) || !items.length) throw new Error('JoyCode 暂未返回额度数据') + if (items.some(item => !item || typeof item.title !== 'string' || + !['used', 'total', 'remain', 'usedPercent'].every(key => Number.isFinite(item[key])))) { + throw new Error('JoyCode 额度数据格式不完整') + } + const format = value => new Intl.NumberFormat('en-US', { maximumFractionDigits: 6 }).format(value) + const plans = [...new Set(items.map(item => item.badge).filter(value => typeof value === 'string' && value))] + return { + ...(plans.length ? { plan: plans.join(' / ') } : {}), + // Different buckets may overlap; do not manufacture a summed balance. + ...(items.length === 1 ? { balance: `${format(items[0].remain)} ${items[0].unit || '积分'}` } : {}), + windows: items.map(item => ({ + name: item.title, + used: item.usedPercent, + amount: item.used, + limit: item.total, + unit: item.unit || '积分', + display: `${format(item.used)} / ${format(item.total)} · 剩余 ${format(item.remain)}${item.expireText ? ` · ${item.expireText}` : ''}`, + // Bucket applicability is unspecified, and free models can remain usable. + // Show the balance without blocking the entire account at 100%. + aside: true, + })), + } +} + +function multiplier(value) { + if (typeof value === 'number') return Number.isFinite(value) && value >= 0 ? value : undefined + if (typeof value !== 'string' || !/^\d+(?:\.\d+)?\s*[x×]?$/i.test(value.trim())) return undefined + return multiplier(Number(value.trim().replace(/[x×]$/i, '').trim())) +} + +function billingScene(value, depth = 0) { + if (!value || typeof value !== 'object' || depth > 5) return undefined + if (value.billingRate && typeof value.billingRate === 'object') return value.billingRate + if (Array.isArray(value.billingRates)) return value + for (const key of ['data', 'result', 'config', 'content', 'value']) { + const found = billingScene(value[key], depth + 1) + if (found) return found + } +} + +async function accountModels(provider, { auth } = {}) { + if (auth?.type !== 'api' || !auth.key) return provider.models + const [catalogue, pricing] = await Promise.allSettled([ + fetchAccountData(auth, 'joycode_modelList'), + fetchAccountData(auth, 'plugin_config', { sceneType: 'billingRate' }), + ]) + for (const result of [catalogue, pricing]) { + if (result.status === 'rejected' && result.reason?.signIn === 'expired') throw result.reason + } + if (catalogue.status !== 'fulfilled' || !Array.isArray(catalogue.value)) return provider.models + const scene = pricing.status === 'fulfilled' ? billingScene(pricing.value) : undefined + const tenant = auth.metadata?.tenant?.trim() + const excluded = (scene?.excludeTenants ?? []).some(value => typeof value === 'string' && value.trim() === tenant) + const rates = new Map(tenant && !excluded && Array.isArray(scene?.billingRates) + ? scene.billingRates.map(row => [row.chatApiModel, multiplier(row.billingRate)]) : []) + const models = {} + for (const model of catalogue.value) { + const id = model?.chatApiModel + if (typeof id !== 'string' || !id || model.hidden || model.isHidden || + (model.modelFunctionType && !['ALL', 'chat', 'agent'].includes(model.modelFunctionType))) continue + const base = provider.models?.[id] ?? {} + const features = Array.isArray(model.features) ? model.features : [] + const image = features.includes('vision') + const rate = multiplier(model.billingRate) ?? rates.get(id) + // Remove old rate fields so unavailable pricing never becomes fake free usage. + const { rate: oldRate, rateWas, free, ...rest } = base + models[id] = { + ...rest, + id, + name: model.label || id, + api: { id, url: `${BASE}/v1`, npm: '@ai-sdk/openai-compatible' }, + limit: { + ...base.limit, + context: Number.isFinite(model.maxTotalTokens) ? model.maxTotalTokens : base.limit?.context ?? 200000, + output: Number.isFinite(model.respMaxTokens) ? model.respMaxTokens : base.limit?.output ?? 64000, + }, + capabilities: { + ...base.capabilities, + toolcall: features.includes('function_call'), + input: { ...base.capabilities?.input, text: true, image }, + }, + modalities: { input: image ? ['text', 'image'] : ['text'] }, + ...(rate !== undefined ? { rate, free: rate === 0 } : {}), + } + } + return models +} + +// ---------------------------------------------------------------- plugin + +export const JoyCodeAuthPlugin = async (_input, options) => { + const flatten = options?.flatten === true + + return { + // Provider + models available before anyone signs in. + config: async (cfg) => { + cfg.provider ??= {} + cfg.provider[PROVIDER] ??= { + name: 'JoyCode', + npm: '@ai-sdk/openai-compatible', // chat completions + api: BASE, + models: MODELS, + } + }, + + provider: { id: PROVIDER, models: accountModels }, + + auth: { + provider: PROVIDER, + methods: [ + { + type: 'oauth', + label: '浏览器登录(京东账号)', + authorize: browserLogin, + }, + { + type: 'api', + label: 'JoyCode ptKey', + placeholder: 'pt_key…(JoyCode IDE 登录态里的 ptKey)', + prompts: [ + { + type: 'text', + key: 'tenant', + message: 'Tenant(企业租户名,个人账号留空)', + placeholder: '留空 = 个人账号', + }, + ], + }, + ], + + // What every request for this account carries. + loader: async (getAuth) => { + const auth = await getAuth() + if (auth?.type !== 'api') return {} + const ptKey = auth.key + const tenant = (auth.metadata?.tenant ?? '').trim() + const loginType = auth.metadata?.loginType || LOGIN_TYPE + if (!ptKey) return {} + // Resolve native chat identity once per account loader, never globally. + let identityPromise + const identity = () => { + identityPromise ??= fetchAccountData(auth, 'joycode_userInfo').then(user => { + if (typeof user?.userId !== 'string' || !user.userId) throw new Error('JoyCode 未返回账号身份') + return { userId: user.userId, tenant: user.tenant || tenant, orgFullName: user.orgFullName || '' } + }).catch(error => { identityPromise = undefined; throw error }) + return identityPromise + } + + return { + // Placeholder only — our fetch rewrites the full URL each request, + // because the signature embeds a fresh timestamp. + baseURL: `${BASE}/v1`, + + async fetch(_input, init) { + // Preserve chat structure; the IDE also adds authenticated metadata. + const account = await identity() + const source = typeof init?.body === 'string' ? init.body : new TextDecoder().decode(init?.body) + const payload = JSON.parse(source) + const body = JSON.stringify({ + ...(flatten ? flattenBody(payload) : payload), + ...account, + language: 'UNKNOWN', + }) + + // 2) URL: fresh signature per request. + const url = buildGatewayUrl(FUNCTION_ID) + + // 3) Headers: keep what magpie synthesized (content-type, …), + // add the gateway credentials, drop the OpenAI-style bearer + // JoyCode does not understand. + const headers = new Headers(init?.headers) + for (const [k, v] of Object.entries(buildGatewayHeaders(ptKey, account.tenant, loginType))) { + headers.set(k, v) + } + headers.delete('authorization') + + // 4) Forward (...init carries the abort signal). + const resp = await fetch(url, { ...init, headers, body }) + + return normalizeChatResponse(resp) + }, + } + }, + + async usage(getAuth) { + try { + return quotaFromData(await fetchAccountData(await getAuth(), 'get_newpoint_ide')) + } catch (error) { + return { + error: error.message, + windows: [], + signIn: error.signIn === 'expired' ? 'expired' : 'kept', + } + } + }, + + // No refresh protocol has been verified; rejected tickets require sign-in. + }, + } +} + +// Test surface (bun test). Everything testable lives on this object so the +// entry module exports no bare functions besides the plugin — see the note +// on the helpers above. +export const _internal = { signQuery, buildGatewayUrl, buildGatewayHeaders, flattenMessages, MODELS } + +// OpenCode v1 form: with default { id, server } the host takes only +// `server` as the plugin and never iterates the module's other exports. +export default { id: PROVIDER, server: JoyCodeAuthPlugin } diff --git a/packages/joycode/login.test.mjs b/packages/joycode/login.test.mjs new file mode 100644 index 0000000..e446bf1 --- /dev/null +++ b/packages/joycode/login.test.mjs @@ -0,0 +1,114 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import plugin from './index.mjs' + +const realFetch = globalThis.fetch + +async function simulateLogin(t, upstream) { + t.mock.method(globalThis, 'fetch', async (url, init) => { + assert.equal(new URL(url).searchParams.get('functionId'), 'joycode_userInfo') + assert.equal(init.headers.ptkey, 'test-ticket') + assert.equal(init.headers.tenant, 'tenant_test') + return upstream() + }) + const hooks = await plugin.server({}) + const flow = await hooks.auth.methods[0].authorize() + const loginUrl = new URL(flow.url) + const callbackUrl = new URL(`http://127.0.0.1:${loginUrl.searchParams.get('authPort')}/`) + for (const name of ['authPort', 'authKey']) { + callbackUrl.searchParams.set(name, loginUrl.searchParams.get(name)) + } + callbackUrl.searchParams.set('pt_key', 'test-ticket') + callbackUrl.searchParams.set('loginType', 'PIN_JD_CLOUD') + callbackUrl.searchParams.set('tenant', 'tenant_test') + const response = await realFetch(callbackUrl, { signal: AbortSignal.timeout(2000) }) + const html = await response.text() + return { + html, + async result() { + let timer + try { + return await Promise.race([ + flow.callback(), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('login callback did not settle')), 500) + }), + ]) + } finally { clearTimeout(timer) } + }, + } +} + +test('gateway code 0 and data.userId complete browser login and provide loader credentials', async (t) => { + const login = await simulateLogin(t, () => Response.json({ + code: 0, data: { userId: 'test-account', userName: 'Test Account', pk: 'private-marker' }, + })) + assert.match(login.html, /登录成功/) + assert.doesNotMatch(login.html, /private-marker|test-ticket/) + const result = await login.result() + assert.equal(result.type, 'success') + assert.equal(result.key, 'test-ticket') + assert.equal(result.accountId, 'Test Account') + assert.equal(result.metadata.loginType, 'PIN_JD_CLOUD') + assert.equal(result.metadata.tenant, 'tenant_test') + const hooks = await plugin.server({}) + const loader = await hooks.auth.loader(async () => ({ ...result, type: 'api' })) + assert.equal(typeof loader.fetch, 'function') +}) + +test('wrong authKey returns 404 without settling an in-flight valid sign-in', async (t) => { + let release, started + const gate = new Promise(resolve => { release = resolve }) + const checking = new Promise(resolve => { started = resolve }) + let calls = 0 + t.mock.method(globalThis, 'fetch', async () => { + calls++ + started() + await gate + return Response.json({ code: 0, data: { userId: 'test-account' } }) + }) + const hooks = await plugin.server({}) + const flow = await hooks.auth.methods[0].authorize() + const params = new URL(flow.url).searchParams + const valid = new URL(`http://127.0.0.1:${params.get('authPort')}/`) + valid.search = params.toString() + valid.searchParams.set('pt_key', 'test-ticket') + let settled = false + const result = flow.callback().then(value => { settled = true; return value }) + const pending = realFetch(valid, { signal: AbortSignal.timeout(2000) }) + try { + await checking + for (const key of ['wrong-key', null]) { + const invalid = new URL(valid) + invalid.searchParams.delete('pt_key') + if (key === null) invalid.searchParams.delete('authKey') + else invalid.searchParams.set('authKey', key) + const response = await realFetch(invalid, { signal: AbortSignal.timeout(2000) }) + assert.equal(response.status, 404) + await response.text() + assert.equal(settled, false) + assert.equal(calls, 1) + } + } finally { + release() + await (await pending).text() + } + assert.equal((await result).type, 'success') +}) + +for (const [name, upstream] of [ + ['business failure despite HTTP 200', () => Response.json({ code: 7, data: { userId: 'test-account', pk: 'private-marker' } })], + ['missing user identity', () => Response.json({ code: 0, data: { pk: 'private-marker' } })], + ['non-JSON response', () => new Response('')], + ['HTTP failure despite success body', () => Response.json({ code: 0, data: { userId: 'test-account' } }, { status: 401 })], + ['network failure', () => { throw new Error('private-marker') }], +]) { + test(`${name} settles as failed without exposing upstream data`, async (t) => { + const login = await simulateLogin(t, upstream) + assert.match(login.html, /登录失败/) + assert.doesNotMatch(login.html, /private-marker|test-ticket/) + const result = await login.result() + assert.equal(result.type, 'failed') + assert.doesNotMatch(result.error, /private-marker|test-ticket/) + }) +} diff --git a/packages/joycode/models.test.mjs b/packages/joycode/models.test.mjs new file mode 100644 index 0000000..5299da1 --- /dev/null +++ b/packages/joycode/models.test.mjs @@ -0,0 +1,61 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import plugin from './index.mjs' + +const catalogue = [ + { chatApiModel: 'JoyAI-Code-1.6', label: 'JoyAI-Code-1.6', maxTotalTokens: 200000, respMaxTokens: 64000, features: ['function_call'] }, + { chatApiModel: 'GLM-5.3-agent', label: 'GLM-5.3', maxTotalTokens: 200000, respMaxTokens: 64000, features: ['function_call'] }, +] +const billingRate = { excludeTenants: ['JD'], billingRates: [ + { chatApiModel: 'JoyAI-Code-1.6', billingRate: '0x' }, + { chatApiModel: 'GLM-5.3-agent', billingRate: '0.6x' }, + { chatApiModel: 'unavailable-model', billingRate: '0.2x' }, +] } +async function load(t, { tenant = 'personal', failRates = false, failList = false, list = catalogue } = {}) { + t.mock.method(globalThis, 'fetch', async (url, init) => { + const fn = new URL(url).searchParams.get('functionId') + assert.equal(init.headers.tenant, tenant) + if (fn === 'joycode_modelList') { + if (failList) throw new Error('offline') + assert.equal(init.body, '{}') + return Response.json({ code: 0, data: list }) + } + assert.equal(fn, 'plugin_config') + assert.deepEqual(JSON.parse(init.body), { sceneType: 'billingRate' }) + if (failRates) throw new Error('offline') + return Response.json({ code: 0, data: { billingRate } }) + }) + const hooks = await plugin.server({}) + const cfg = {} + await hooks.config(cfg) + const provider = cfg.provider.joycode + assert.equal(typeof hooks.provider?.models, 'function') + return { provider, models: await hooks.provider.models(provider, { auth: { type: 'api', key: 'fake', metadata: { tenant } } }) } +} + +test('sync current model multipliers including zero without adding pricing-only models', async t => { + const { models } = await load(t) + assert.deepEqual(Object.keys(models), ['JoyAI-Code-1.6', 'GLM-5.3-agent']) + assert.equal(models['JoyAI-Code-1.6'].rate, 0) + assert.equal(models['JoyAI-Code-1.6'].free, true) + assert.equal(models['GLM-5.3-agent'].rate, 0.6) + assert.equal(models['GLM-5.3-agent'].capabilities.input.image, false) +}) +test('excluded tenants do not inherit public pricing', async t => { + const { models } = await load(t, { tenant: 'JD' }) + assert.equal(models['GLM-5.3-agent'].rate, undefined) + assert.notEqual(models['JoyAI-Code-1.6'].free, true) +}) +test('model-specific billing rate takes priority', async t => { + const { models } = await load(t, { list: [{ ...catalogue[1], billingRate: '0.3x' }] }) + assert.equal(models['GLM-5.3-agent'].rate, 0.3) +}) +test('pricing fetch failure retains models without invented rates', async t => { + const { models } = await load(t, { failRates: true }) + assert.equal(Object.keys(models).length, 2) + assert.equal(models['GLM-5.3-agent'].rate, undefined) +}) +test('catalogue fetch failure returns original fallback model list', async t => { + const { models, provider } = await load(t, { failList: true }) + assert.equal(models, provider.models) +}) diff --git a/packages/joycode/package.json b/packages/joycode/package.json new file mode 100644 index 0000000..9b98b5e --- /dev/null +++ b/packages/joycode/package.json @@ -0,0 +1,31 @@ +{ + "name": "@magpie-community/opencode-joycode-auth", + "version": "0.1.1", + "description": "OpenCode provider plugin: JoyCode (JD Cloud JoyCoder IDE credits)", + "type": "module", + "main": "./index.mjs", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/joycode" + }, + "scripts": { + "test": "bun test" + }, + "files": [ + "index.mjs", + "README.md", + "CHANGELOG.md", + "icon.png" + ], + "keywords": [ + "opencode", + "opencode-plugin", + "joycode" + ], + "license": "MIT", + "magpie": { + "maxConcurrency": 4, + "icon": "data:image/png;base64,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" + } +} diff --git a/packages/joycode/usage.test.mjs b/packages/joycode/usage.test.mjs new file mode 100644 index 0000000..3a16fd3 --- /dev/null +++ b/packages/joycode/usage.test.mjs @@ -0,0 +1,80 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import plugin from './index.mjs' + +const auth = { type: 'api', key: 'fake-ticket', metadata: { tenant: '测试租户', loginType: 'PIN_JD_CLOUD' } } +const item = { type: 'seatPackage', title: '套餐积分', badge: '团队版(限免)', used: 0, total: 10000, remain: 10000, usedPercent: 0, expireText: '有效期至 2026年11月11日' } + +async function query(t, response, account = auth) { + t.mock.method(globalThis, 'fetch', async (url, init) => { + assert.equal(new URL(url).origin, 'https://api-ai.jd.com') + assert.equal(new URL(url).searchParams.get('functionId'), 'get_newpoint_ide') + assert.equal(init.method, 'POST') + assert.equal(init.body, '{}') + assert.equal(init.headers.ptkey, account.key) + assert.equal(init.headers.tenant, encodeURIComponent(account.metadata.tenant)) + assert.equal(init.headers.logintype, account.metadata.loginType) + assert.ok(init.signal) + return response() + }) + const hooks = await plugin.server({}) + assert.equal(typeof hooks.auth.usage, 'function') + return hooks.auth.usage(async () => account) +} + +test('maps actual IDE quota schema including zero usage and expiry text', async (t) => { + const result = await query(t, () => Response.json({ code: 0, data: { usageItems: [item] } })) + assert.equal(result.plan, '团队版(限免)') + assert.equal(result.balance, '10,000 积分') + assert.equal(result.windows[0].used, 0) + assert.equal(result.windows[0].amount, 0) + assert.equal(result.windows[0].limit, 10000) + assert.match(result.windows[0].display, /剩余 10,000/) + assert.match(result.windows[0].display, /2026年11月11日/) + assert.equal(result.windows[0].resetsAt, undefined) +}) + +test('multiple pools preserve balances without one exhausted pool blocking the account', async (t) => { + const result = await query(t, () => Response.json({ code: 0, data: { usageItems: [ + { ...item, used: 10000, remain: 0, usedPercent: 100 }, + { title: '加油包', used: 250, total: 1000, remain: 750, usedPercent: 25 }, + ] } })) + assert.equal(result.balance, undefined) + assert.deepEqual(result.windows.map(w => w.used), [100, 25]) + assert.ok(result.windows.every(w => w.aside === true)) +}) + +test('missing numeric values never become fake zero quota', async (t) => { + const result = await query(t, () => Response.json({ code: 0, data: { usageItems: [{ title: '套餐积分' }] } })) + assert.ok(result.error) + assert.deepEqual(result.windows, []) + assert.equal(result.balance, undefined) +}) + +for (const field of ['msg', 'message']) { + test(`business error preserves ${field} without exposing account data`, async t => { + const result = await query(t, () => Response.json({ code: 9, [field]: '套餐不可用', data: { private: 'private-marker' } })) + assert.equal(result.error, 'JoyCode 数据查询失败(HTTP 200):套餐不可用') + assert.equal(result.signIn, 'kept') + assert.deepEqual(result.windows, []) + assert.doesNotMatch(JSON.stringify(result), /private-marker|fake-ticket/) + }) +} + +for (const [name, response, signIn] of [ + ['401', () => new Response('private-marker', { status: 401 }), 'expired'], + ['403 permission error', () => new Response('private-marker', { status: 403 }), 'kept'], + ['business error with malformed message', () => Response.json({ code: 9, msg: { private: 'private-marker' } }), 'kept'], + ['invalid JSON', () => new Response('private-marker'), 'kept'], + ['network failure', () => { throw new Error('private-marker') }, 'kept'], + ['empty quota', () => Response.json({ code: 0, data: { usageItems: [] } }), 'kept'], +]) { + test(`${name} reports a safe error without fake balances`, async (t) => { + const result = await query(t, response) + assert.ok(result.error) + assert.equal(result.signIn, signIn) + assert.deepEqual(result.windows, []) + assert.equal(result.balance, undefined) + assert.doesNotMatch(JSON.stringify(result), /private-marker|fake-ticket/) + }) +} diff --git a/registry.json b/registry.json index f29b260..afb2867 100644 --- a/registry.json +++ b/registry.json @@ -1,6 +1,8 @@ { "version": 1, "plugins": [ + { "package": "@magpie-community/opencode-joycode-auth", "name": "JoyCode", "providers": ["joycode"], "community": true, + "summary": { "en": "Unofficial JoyCode provider: JD account browser sign-in, live models and credit multipliers, plan credits and streaming tool calls.", "zh": "非官方 JoyCode 插件:京东账号浏览器登录,动态模型与积分倍率、套餐额度及流式工具调用。" } }, {"package": "@magpie-community/opencode-kimi-work-auth", "name": "Kimi Work", "icon": "kimi", "providers": ["kimi-work"], "community": true, "summary": {"en": "Kimi desktop Work subscription through its local sign-in, with live Work models and shared membership usage. Separate from Kimi Code.", "zh": "使用本机普通 Kimi 桌面版的 Work 登录,自动读取 Work 模型和会员共享用量;独立于 Kimi Code。"}}, { "package": "@magpie-community/opencode-zen-free-auth", "name": "OpenCode Zen Free", "icon": "opencode", "providers": ["opencode-zen-free"], "community": true, "summary": { "en": "OpenCode Zen's free models with the public credential, automatic discovery and native streaming protocols.", "zh": "使用 public 凭证接入 OpenCode Zen 免费模型,自动发现模型并支持原生流式协议。" } },