Files
plugins/packages/joycode/chat.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

100 lines
5.4 KiB
JavaScript

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