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

115 lines
4.6 KiB
JavaScript

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('<script>private-marker</script>')],
['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/)
})
}