Files
plugins/packages/joycode/usage.test.mjs
T
kassama efa41e36e3 joycode 0.1.1: JoyCode (JD Cloud) with JD's browser sign-in, account models, credit multipliers and usage (#347)
New package @magpie-community/opencode-joycode-auth 0.1.1 (provider id `joycode`) and its registry entry (en and zh). JoyCode is JD Cloud's own coding IDE subscription (joycode.jd.com, api-ai.jd.com), not a relay.

- Browser sign-in through JoyCode's own login page. The page sends the browser to http://127.0.0.1:<authPort>/ with authKey and pt_key; I checked this against the page's bundle. A request without the right authKey gets a 404 and leaves the sign-in pending. A ptKey can also be pasted, with an optional tenant.
- Chat completions are signed per request (HMAC over a fresh t), with userId, tenant and orgFullName from joycode_userInfo. A bare JSON error sent as HTTP 200 SSE becomes an error reply: code 401 is 401 with sign-in expired, AI_GRAY_ACCESS_DENIED is 403, anything else is 502. JD's msg is kept as the error text.
- Account models come from joycode_modelList, credit multipliers from plugin_config billingRate, and credit usage from get_newpoint_ide (windows set aside).
- Contacts only JD's hosts. No runtime dependencies, no install scripts, no logging. The ptKey is kept only in magpie's plugin-auth.json.

Reviewed every line at c80068f and again at 1cac30c, which fixed all five review points: the README link, JD's `msg`, tests for the authKey check and for the HTTP 200 SSE code 401, the stale header comment, and stray loopback requests.

Run at the reviewed head 1cac30cce31a1f3efeb39b2c61df257963e655a, whose parent is main 57ec655:
- packages/joycode: `bun test` (Bun 1.4.2) 30 pass, 0 fail. `node --test` (Node 22) 30 pass.
- Whole repo, as CI runs it: `HOME=$(mktemp -d) bun test` 2373 pass, 0 fail. `bun scripts/check.mjs` all ✓.
- Broke the code by hand: removed the authKey check, made a wrong authKey end the sign-in, mapped the SSE code 401 to 502, and dropped `msg` in chat and in usage. Each one turns a test red.
- magpie built from main, in a sandbox HOME: `plugin add` lists `joycode (JoyCode, 5 models)`, and `plugin login joycode` offers both methods. With a made-up ptKey, provider.models, `provider test` and `quota` each fail with "JoyCode 登录已失效" and mark the sign-in expired. plugin-auth.json is mode 600.
- JD's gateway answered the made-up ptKey with HTTP 200 `{"code":401,"data":…,"msg":…}` on joycode_userInfo, chat_completions (as text/event-stream) and get_newpoint_ide.

Not tried: no JoyCode account was available, so no successful chat, model list, multiplier or quota read was made against JD. The author reports live JoyAI-Code-1.6 streaming and tool-call runs.
2026-10-24 03:34:36 +08:00

81 lines
3.9 KiB
JavaScript

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/)
})
}