dsh-codearts-dock 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/DISCLAIMER.md +47 -0
  2. package/LICENSE +21 -0
  3. package/README.md +172 -2
  4. package/SECURITY.md +47 -0
  5. package/THIRD_PARTY_NOTICES.md +64 -0
  6. package/client.js +3519 -0
  7. package/cordis.patch.yml +10 -0
  8. package/docs/DETAIL.md +25 -0
  9. package/docs/DETAIL.zh.md +25 -0
  10. package/docs/PUBLISHING.md +43 -0
  11. package/docs/preview.svg +78 -0
  12. package/icons/dsh-connect-codearts-128.png +0 -0
  13. package/icons/dsh-connect-codearts-256.png +0 -0
  14. package/locale/en.json +7 -0
  15. package/locale/zh.json +7 -0
  16. package/package.json +88 -4
  17. package/scripts/build-market-index.mjs +24 -0
  18. package/scripts/check-legal.sh +33 -0
  19. package/scripts/check-release.mjs +29 -0
  20. package/scripts/test.mjs +11 -0
  21. package/src/account.js +217 -0
  22. package/src/accounts.js +481 -0
  23. package/src/adapter.js +742 -0
  24. package/src/backup.js +89 -0
  25. package/src/catalog.js +269 -0
  26. package/src/checkin.js +271 -0
  27. package/src/credentials.js +435 -0
  28. package/src/features.js +79 -0
  29. package/src/gateway.js +521 -0
  30. package/src/health.js +18 -0
  31. package/src/index.js +1108 -0
  32. package/src/models.js +147 -0
  33. package/src/paths.js +36 -0
  34. package/src/preferences.js +90 -0
  35. package/src/protocol/crypto.js +160 -0
  36. package/src/protocol/sign.js +176 -0
  37. package/src/protocol/sm4.js +264 -0
  38. package/src/protocol/sse.js +134 -0
  39. package/src/sts.js +118 -0
  40. package/src/usage.js +55 -0
  41. package/test/accounts.test.mjs +322 -0
  42. package/test/adapter.test.mjs +234 -0
  43. package/test/assembler.test.mjs +86 -0
  44. package/test/features.test.mjs +257 -0
  45. package/test/live-probe.mjs +55 -0
  46. package/test/protocol.test.mjs +167 -0
  47. package/test/registration.test.mjs +301 -0
  48. package/test/sm4.test.mjs +64 -0
  49. package/test/ui.test.mjs +370 -0
  50. package/test/visual.test.mjs +438 -0
@@ -0,0 +1,257 @@
1
+ /** All five features against real local storage and fake gateway/host boundaries. */
2
+ import assert from 'node:assert/strict'
3
+ import { mkdtemp, readFile, stat, rm } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import { Readable } from 'node:stream'
7
+
8
+ const scratch = await mkdtemp(join(tmpdir(), 'dca-features-'))
9
+ process.env.APPDATA = scratch
10
+ process.env.DSH_CONNECT_CODEARTS_LEGACY_CREDENTIAL = join(scratch, 'no-legacy.json')
11
+ delete process.env.CODEARTS_AK
12
+ delete process.env.CODEARTS_SK
13
+ delete process.env.CODEARTS_SECURITY_TOKEN
14
+ const { FEATURE_DEFAULTS, validatePreferences, persistPreferences, readPreferences, portablePreferences } = await import('../src/preferences.js')
15
+ const { encodeBackup, decodeBackup } = await import('../src/backup.js')
16
+ const { createUsageStore, USAGE_LIMIT } = await import('../src/usage.js')
17
+ const { accountHealth, isLowBalance } = await import('../src/health.js')
18
+ const { readCredit } = await import('../src/account.js')
19
+ const accounts = await import('../src/accounts.js')
20
+ const { createCodeArtsAdapter } = await import('../src/adapter.js')
21
+ const { Catalog } = await import('../src/catalog.js')
22
+ const results = []
23
+ const check = async (name, fn) => {
24
+ try { await fn(); results.push(`✓ ${name}`) } catch (error) { results.push(`✗ ${name}\n${error.stack}`); process.exitCode = 1 }
25
+ }
26
+ const settings = { ...FEATURE_DEFAULTS, enabledModelIds: null, modelOverrides: {}, autoCheckin: false, composerChip: true, refreshIntervalMs: 300000 }
27
+ const preferences = portablePreferences(settings)
28
+ const secretAccount = { ak: 'TEST_BACKUP_AK_123456789', sk: 'TEST_BACKUP_SK_987654321', label: 'Example' }
29
+
30
+ await check('alert thresholds reject invalid data and distinguish unknown from zero balance', async () => {
31
+ assert.equal(isLowBalance({ remain: 10 }, { ...settings, lowBalanceThreshold: 20 }), true)
32
+ assert.equal(isLowBalance({ remain: 20 }, { ...settings, lowBalanceThreshold: 20 }), false)
33
+ assert.equal(isLowBalance({ remain: 0 }, settings), true)
34
+ assert.equal(isLowBalance(null, settings), false)
35
+ assert.equal(isLowBalance({ remain: 10 }, { ...settings, lowBalanceEnabled: false }), false)
36
+ for (const invalid of [-1, NaN, Infinity, '500', 1e10]) assert.throws(() => validatePreferences({ lowBalanceThreshold: invalid }))
37
+ assert.throws(() => validatePreferences({ enabledModelIds: [], modelOverrides: {} }))
38
+ assert.throws(() => validatePreferences(JSON.parse('{"modelOverrides":{"__proto__":{"images":true}}}')))
39
+ assert.throws(() => validatePreferences({ modelPresets: Array(21).fill({}) }))
40
+ })
41
+ await check('concurrent preference writes are atomic, private, and do not lose other keys', async () => {
42
+ await Promise.all([persistPreferences({ lowBalanceThreshold: 250 }), persistPreferences({ usageEnabled: false }), persistPreferences({ autoCheckin: false })])
43
+ assert.equal(readPreferences().lowBalanceThreshold, 250)
44
+ assert.equal(readPreferences().usageEnabled, false)
45
+ const mode = (await stat(join(scratch, 'dsh-connect-codearts', 'preferences.json'))).mode & 0o777
46
+ assert.equal(mode, 0o600)
47
+ })
48
+ await check('account health separates credentials, throttling, quota, network, and upstream failures', async () => {
49
+ assert.equal(accountHealth({ credit: { remain: 10 } }).state, 'available')
50
+ assert.equal(accountHealth({ credit: { remain: 0 } }).state, 'insufficient')
51
+ assert.equal(accountHealth().state, 'unknown')
52
+ for (const [error, state] of [[{ status: 401 }, 'credentials'], [{ status: 403 }, 'credentials'], [{ status: 429 }, 'rate_limited'], [{ status: 402 }, 'insufficient'], [{ code: 'ECONNRESET' }, 'network'], [{ status: 503 }, 'gateway'], [{ name: 'StsError', message: '无法连接华为云 IAM' }, 'network']]) {
53
+ assert.equal(accountHealth({ error }).state, state)
54
+ }
55
+ const failing = { getJson: async () => { throw new Error('network test') } }
56
+ assert.equal(await readCredit(failing), null)
57
+ await assert.rejects(readCredit(failing, { strict: true }), /network test/)
58
+ })
59
+ await check('plain backups contain only preferences, encrypted backups round-trip credentials and reject tampering', async () => {
60
+ const plain = await encodeBackup({ preferences, accounts: [secretAccount] })
61
+ assert.equal(plain.accounts, undefined)
62
+ assert.ok(!JSON.stringify(plain).includes(secretAccount.ak))
63
+ assert.deepEqual((await decodeBackup(JSON.stringify(plain))).preferences, preferences)
64
+ await assert.rejects(encodeBackup({ preferences, accounts: [secretAccount], includeCredentials: true, password: '' }))
65
+ await assert.rejects(encodeBackup({ preferences, accounts: [secretAccount, { ...secretAccount, ak: ` ${secretAccount.ak} ` }], includeCredentials: true, password: 'test-password-123' }), /重复账号/)
66
+ const encrypted = await encodeBackup({ preferences, accounts: [secretAccount], activeAccountId: accounts.accountIdOf(secretAccount.ak), includeCredentials: true, password: 'test-password-123' })
67
+ assert.ok(!JSON.stringify(encrypted).includes(secretAccount.sk))
68
+ const decoded = await decodeBackup(JSON.stringify(encrypted), 'test-password-123')
69
+ assert.deepEqual(decoded.accounts, [secretAccount])
70
+ assert.equal(decoded.activeAccountId, accounts.accountIdOf(secretAccount.ak))
71
+ await assert.rejects(decodeBackup(JSON.stringify(encrypted), 'wrong-password'), /密码错误/)
72
+ const data = Buffer.from(encrypted.data, 'base64'); data[0] ^= 1
73
+ await assert.rejects(decodeBackup(JSON.stringify({ ...encrypted, data: data.toString('base64') }), 'test-password-123'), /密码错误/)
74
+ await assert.rejects(decodeBackup(JSON.stringify({ ...plain, accounts: [secretAccount] })), /必须为加密/)
75
+ await assert.rejects(decodeBackup(JSON.stringify({ ...plain, version: 99 })))
76
+ })
77
+ await check('usage is bounded and stores only metadata, with disable and in-flight clear guards', async () => {
78
+ let enabled = true
79
+ const usage = createUsageStore({ directory: join(scratch, 'usage-tests'), enabled: () => enabled })
80
+ const epoch = usage.generation()
81
+ await usage.record({ at: Date.now(), model: 'test-model', status: 'success', durationMs: 50, inputTokens: 10, outputTokens: 2, prompt: 'PRIVATE_PROMPT', account: 'PRIVATE_ACCOUNT', sk: 'PRIVATE_SK' }, epoch)
82
+ const saved = await readFile(join(scratch, 'usage-tests', 'usage.json'), 'utf8')
83
+ assert.ok(!saved.includes('PRIVATE'))
84
+ assert.equal((await stat(join(scratch, 'usage-tests', 'usage.json'))).mode & 0o777, 0o600)
85
+ enabled = false
86
+ const disabledEpoch = usage.generation()
87
+ await usage.record({ model: 'not-recorded' }, epoch)
88
+ assert.equal(usage.list().records.length, 1)
89
+ enabled = true
90
+ await usage.record({ model: 'started-while-disabled' }, disabledEpoch)
91
+ assert.equal(usage.list().records.length, 1)
92
+ await usage.clear()
93
+ await usage.record({ model: 'stale-in-flight' }, epoch)
94
+ assert.equal(usage.list().records.length, 0)
95
+ // Queue several writes together to exercise disk ordering without a gateway.
96
+ await Promise.all(Array.from({ length: USAGE_LIMIT + 3 }, (_, i) => usage.record({ model: `model-${i}`, status: 'success' })))
97
+ assert.equal(usage.list().records.length, USAGE_LIMIT)
98
+ assert.equal(usage.list().records[0].model, `model-${USAGE_LIMIT + 2}`)
99
+ assert.equal(createUsageStore({ directory: join(scratch, 'usage-tests') }).list().records.length, USAGE_LIMIT)
100
+ })
101
+ await check('real adapter records success, upstream failure, credential failure and cancellation without contents', async () => {
102
+ const catalog = new Catalog(); catalog.current = [{ id: 'm', name: 'Model', strengths: [] }]
103
+ async function run(chunks, failCredentials = false, cancel = false) {
104
+ const recorded = []
105
+ const adapter = createCodeArtsAdapter({
106
+ catalog, credentials: { resolve: async () => { if (failCredentials) throw new Error('PRIVATE_CREDENTIAL'); return { key: { ak: 'TEST', sk: 'TEST' } } } },
107
+ createClient: () => ({ heartbeat: async () => {}, streamChat: async function* () { for (const chunk of chunks) { if (chunk instanceof Error) throw chunk; yield chunk } } }),
108
+ usage: { generation: () => 0, record: async (row) => recorded.push(row) },
109
+ })
110
+ try {
111
+ for await (const chunk of adapter.stream({ model: 'm', provider: 'codearts', messages: [{ role: 'user', content: [{ type: 'text', text: 'PRIVATE_PROMPT' }] }] })) { if (cancel) break }
112
+ } catch {}
113
+ return recorded
114
+ }
115
+ const success = await run([{ text: 'PRIVATE_OUTPUT' }, { usage: { inputTokens: 8, outputTokens: 2 } }, { finish: 'stop' }])
116
+ assert.equal(success[0].status, 'success')
117
+ assert.equal(success[0].inputTokens, 8)
118
+ assert.ok(!JSON.stringify(success).includes('PRIVATE'))
119
+ assert.equal((await run([new Error('PRIVATE_UPSTREAM')]))[0].status, 'error')
120
+ assert.equal((await run([], true))[0].status, 'error')
121
+ assert.equal((await run([{ text: 'x' }], false, true))[0].status, 'aborted')
122
+ })
123
+ await check('concurrent account imports and name discovery cannot overwrite other accounts', async () => {
124
+ const [one] = await Promise.all([accounts.addAccount(secretAccount), accounts.addAccount({ ak: 'SECOND_TEST_AK', sk: 'SECOND_TEST_SK' })])
125
+ await Promise.all([accounts.rememberAccountName(one.account.id, 'Example name'), accounts.addAccount({ ak: 'THIRD_TEST_AK', sk: 'THIRD_TEST_SK' })])
126
+ assert.equal(accounts.readStore().accounts.length, 3)
127
+ assert.equal(accounts.readStore().accounts.find((entry) => entry.id === one.account.id).accountName, 'Example name')
128
+ })
129
+
130
+ const originalFetch = globalThis.fetch
131
+ const disposers = []
132
+ let creditStatus = 200
133
+ let creditReads = 0
134
+ let creditGate = null
135
+ let creditRemain = 50
136
+ let iamReads = 0
137
+ const jsonResponse = (value, status = 200) => new Response(JSON.stringify(value), { status })
138
+ globalThis.fetch = async (input) => {
139
+ const url = String(input)
140
+ if (url.includes('iam.cn-north-4.myhuaweicloud.com')) {
141
+ iamReads += 1
142
+ return jsonResponse({ credential: { access: 'TEMP_TEST_AK', secret: 'TEMP_TEST_SK', securitytoken: 'TEMP_TEST_TOKEN', expires_at: new Date(Date.now() + 3600000).toISOString() } })
143
+ }
144
+ if (url.includes('/statistics/plugin')) {
145
+ creditReads += 1
146
+ const remain = creditRemain
147
+ await creditGate
148
+ if (creditStatus !== 200) return jsonResponse({ message: 'mock failure' }, creditStatus)
149
+ return jsonResponse({ metrics: [{ name: 'usageTotalPackageCredit', package_credit_amount: 1000, package_credit_used: 950, package_credit_remain: remain }] })
150
+ }
151
+ if (url.includes('/v1/model/builtin') || url.includes('/v1/model/thinking-variants')) return jsonResponse([])
152
+ if (url.includes('/v1/ops/delivery')) return jsonResponse([])
153
+ if (url.includes('/member/roles')) return jsonResponse([])
154
+ throw new Error('Offline test blocked an unexpected gateway request')
155
+ }
156
+ const routes = new Map()
157
+ const plugin = await import('../src/index.js')
158
+ const effect = (fn) => { const dispose = fn(); if (typeof dispose === 'function') disposers.push(dispose); return dispose }
159
+ plugin.apply({ effect, get: () => undefined, emit() {}, inject: (_, callback) => callback({ effect, webServer: { register: (route) => { routes.set(route.path, route.handler); return () => {} } } }) }, { registerProvider: false })
160
+ const request = (path, body, method = body === undefined ? 'GET' : 'POST', options = {}) => new Promise((resolve, reject) => {
161
+ const handler = routes.get(`/plugins/dsh-connect-codearts${path}`)
162
+ if (!handler) return reject(new Error(`Unknown route ${path}`))
163
+ const req = Readable.from(options.raw !== undefined ? [Buffer.from(options.raw)] : body === undefined ? [] : [Buffer.from(JSON.stringify(body))])
164
+ Object.assign(req, { method, url: `/plugins/dsh-connect-codearts${path}`, socket: { remoteAddress: options.remoteAddress ?? '127.0.0.1' } })
165
+ let status
166
+ handler(req, { setHeader() {}, writeHead: (value) => { status = value }, end: (text) => resolve({ status, body: JSON.parse(text) }) })
167
+ })
168
+ await check('feature routes enforce POST, validate preferences, and persist presets without changing the live selection', async () => {
169
+ for (const path of ['/preferences/save', '/usage/clear', '/presets', '/backup/export', '/backup/preview', '/backup/restore', '/accounts/check']) assert.equal((await request(path)).status, 405)
170
+ assert.equal((await request('/preferences/save', { lowBalanceThreshold: -1 })).status, 400)
171
+ const preferenceSave = await request('/preferences/save', { lowBalanceThreshold: 75, usageEnabled: true })
172
+ assert.equal(preferenceSave.body.preferences.lowBalanceThreshold, 75)
173
+ const preset = await request('/presets', { action: 'save', name: 'Daily', enabledModelIds: ['test-model'], modelOverrides: { 'test-model': { images: true, defaultStrength: 'high' } } })
174
+ assert.equal(preset.status, 200)
175
+ assert.equal(preset.body.presets.length, 1)
176
+ assert.equal((await request('/models')).body.enabledIds, null)
177
+ const id = preset.body.presets[0].id
178
+ assert.equal((await request('/presets', { action: 'delete', id })).body.presets.length, 0)
179
+ })
180
+ await check('malformed, non-object, oversized and remote feature requests are rejected without mutations', async () => {
181
+ const before = JSON.stringify((await request('/preferences')).body)
182
+ for (const path of ['/preferences/save', '/presets', '/backup/export', '/backup/preview', '/backup/restore', '/accounts/check']) {
183
+ for (const body of [null, [], 42, 'invalid']) {
184
+ assert.equal((await request(path, body)).status, 400, `${path} must reject ${JSON.stringify(body)}`)
185
+ }
186
+ assert.equal((await request(path, {}, 'POST', { raw: '{bad-json' })).status, 400)
187
+ }
188
+ assert.equal((await request('/preferences/save', { ignored: 'x'.repeat(65536) })).status, 413)
189
+ assert.equal((await request('/backup/preview', { text: 'x'.repeat(1024 * 1024) })).status, 413)
190
+ assert.equal((await request('/preferences/save', { lowBalanceThreshold: 123 }, 'POST', { remoteAddress: '192.0.2.1' })).status, 403)
191
+ assert.equal(JSON.stringify((await request('/preferences')).body), before)
192
+ })
193
+ await check('account checks use one probe for concurrent clicks, expose actionable status, and report low balances', async () => {
194
+ const id = accounts.readStore().accounts[0].id
195
+ await new Promise(setImmediate)
196
+ const creditsBefore = creditReads, iamBefore = iamReads
197
+ const [a, b] = await Promise.all([request('/accounts/check', { id }), request('/accounts/check', { id })])
198
+ assert.equal(a.body.account.health.state, 'available')
199
+ assert.equal(b.body.account.lowBalance, true)
200
+ assert.equal(creditReads - creditsBefore, 1)
201
+ assert.equal(iamReads - iamBefore, 1)
202
+ creditStatus = 429
203
+ assert.equal((await request('/accounts/check', { id })).body.account.health.state, 'rate_limited')
204
+ creditStatus = 200
205
+ const active = (await request('/account')).body
206
+ assert.equal(active.lowBalance, true)
207
+ assert.equal(active.lowBalanceThreshold, 75)
208
+ })
209
+ await check('an invalidated in-flight health probe cannot repopulate stale account state', async () => {
210
+ const account = accounts.readStore().accounts[0]
211
+ let release
212
+ creditGate = new Promise((resolve) => { release = resolve })
213
+ const oldProbe = request('/accounts/check', { id: account.id })
214
+ await new Promise(setImmediate)
215
+ assert.equal((await request('/accounts/add', { ak: account.ak, sk: account.sk, label: account.label })).status, 200)
216
+ creditRemain = 500
217
+ creditGate = null
218
+ release()
219
+ await oldProbe
220
+ const pool = await request('/accounts')
221
+ assert.equal(pool.body.accounts.find((entry) => entry.id === account.id).credit.remain, 500)
222
+ creditRemain = 50
223
+ })
224
+ await check('backup preview writes nothing; restore merges accounts, preferences and presets, while wrong passwords do not mutate', async () => {
225
+ const exportResponse = await request('/backup/export', { includeCredentials: true, password: 'test-password-123' })
226
+ assert.equal(exportResponse.status, 200)
227
+ const text = JSON.stringify(exportResponse.body.backup)
228
+ const before = JSON.stringify(accounts.readStore())
229
+ assert.equal((await request('/backup/preview', { text, password: 'wrong-password' })).status, 400)
230
+ assert.equal(JSON.stringify(accounts.readStore()), before)
231
+ const preview = await request('/backup/preview', { text, password: 'test-password-123' })
232
+ assert.equal(preview.body.accounts.updated, 3)
233
+ assert.equal(JSON.stringify(accounts.readStore()), before)
234
+ assert.ok(!JSON.stringify(preview.body).includes(secretAccount.sk))
235
+ await request('/preferences/save', { lowBalanceThreshold: 999 })
236
+ const preservedId = accounts.readStore().accounts.at(-1).id
237
+ await accounts.setActiveAccount(preservedId)
238
+ const restore = await request('/backup/restore', { text, password: 'test-password-123' })
239
+ assert.equal(restore.status, 200)
240
+ assert.equal(restore.body.updated, 3)
241
+ assert.equal((await request('/preferences')).body.preferences.lowBalanceThreshold, 75)
242
+ assert.equal(accounts.readStore().accounts.length, 3)
243
+ assert.equal(accounts.readStore().activeId, preservedId)
244
+
245
+ // Simulate a new installation using only this suite's temporary account store.
246
+ for (const account of accounts.readStore().accounts) await accounts.removeAccount(account.id)
247
+ const fresh = await request('/backup/restore', { text, password: 'test-password-123' })
248
+ assert.equal(fresh.status, 200)
249
+ assert.equal(fresh.body.added, 3)
250
+ assert.equal(accounts.readStore().activeId, accounts.accountIdOf(secretAccount.ak))
251
+ })
252
+
253
+ for (const dispose of disposers.reverse()) dispose()
254
+ globalThis.fetch = originalFetch
255
+ await rm(scratch, { recursive: true, force: true })
256
+ console.log(results.join('\n'))
257
+ console.log(process.exitCode ? '\nfeatures: checks failed' : '\nfeatures: all checks passed')
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Live end-to-end probe against the real 码道 gateway.
3
+ *
4
+ * Not part of `npm test`: it spends real credit and needs working credentials.
5
+ * Run it after a protocol change to confirm the whole chain still holds:
6
+ *
7
+ * CODEARTS_AK=... CODEARTS_SK=... node --no-warnings test/live-probe.mjs
8
+ */
9
+
10
+ import { getSts } from '../src/sts.js'
11
+ import { MadaoClient } from '../src/gateway.js'
12
+
13
+ const ak = process.env.CODEARTS_AK
14
+ const sk = process.env.CODEARTS_SK
15
+ if (!ak || !sk) {
16
+ console.error('设置 CODEARTS_AK / CODEARTS_SK 后再跑这个探针。')
17
+ process.exit(2)
18
+ }
19
+
20
+ const started = Date.now()
21
+ const sts = await getSts(ak, sk)
22
+ console.log(`✓ STS(${Date.now() - started}ms)`)
23
+
24
+ const client = new MadaoClient({
25
+ credentials: { ak: sts.ak, sk: sts.sk, securityToken: sts.securityToken },
26
+ })
27
+
28
+ const key = await client.ensureSessionKey()
29
+ console.log(`✓ 会话密钥 keyId=${key.keyId}`)
30
+
31
+ const models = await client.getJson('/v1/model/builtin')
32
+ console.log(`✓ 模型清单 ${models?.builtinModels?.length} 个`)
33
+
34
+ let text = ''
35
+ let reasoning = ''
36
+ let usage = null
37
+ let finish = null
38
+ const chatStarted = Date.now()
39
+ for await (const event of client.streamChat({
40
+ model: 'glm-5.3-flash',
41
+ messages: [{ role: 'user', content: '用一句话介绍你自己。' }],
42
+ maxTokens: 2000,
43
+ })) {
44
+ if (event.text) text += event.text
45
+ if (event.reasoning) reasoning += event.reasoning
46
+ if (event.usage) usage = event.usage
47
+ if (event.finish) finish = event.finish
48
+ if (event.done) break
49
+ }
50
+ console.log(`✓ 对话流式返回(${Date.now() - chatStarted}ms)finish=${finish}`)
51
+ console.log(` usage=${JSON.stringify(usage)}`)
52
+ console.log(` reasoning ${reasoning.length} 字符`)
53
+ console.log(` text=${JSON.stringify(text.slice(0, 160))}`)
54
+
55
+ await client.heartbeat('idle')
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Offline tests for the transport envelope: signing, key agreement, and SSE
3
+ * frame handling. The live gateway is exercised separately by `npm run test:live`.
4
+ */
5
+
6
+ import assert from 'node:assert/strict'
7
+ import { createHash, createHmac } from 'node:crypto'
8
+ import { canonicalUri, formatSdkDate, signRequest } from '../src/protocol/sign.js'
9
+ import { deriveSessionKey, deriveRequestEnvelope, openChunk } from '../src/protocol/crypto.js'
10
+ import { parseStreamEvent, splitSseEvents } from '../src/protocol/sse.js'
11
+
12
+ const results = []
13
+ const check = (name, fn) => {
14
+ try {
15
+ fn()
16
+ results.push(`✓ ${name}`)
17
+ } catch (error) {
18
+ results.push(`✗ ${name}\n ${error.message}`)
19
+ process.exitCode = 1
20
+ }
21
+ }
22
+
23
+ // ── signing ─────────────────────────────────────────────────────────────────
24
+
25
+ check('canonical URI adds a trailing slash', () => {
26
+ assert.equal(canonicalUri('/api/v2/chat/completions'), '/api/v2/chat/completions/')
27
+ assert.equal(canonicalUri('/api/v2/chat/completions/'), '/api/v2/chat/completions/')
28
+ })
29
+
30
+ check('canonical URI percent-encodes per segment, not the separators', () => {
31
+ assert.equal(canonicalUri('/a b/c d'), '/a%20b/c%20d/')
32
+ })
33
+
34
+ check('SDK date is UTC second precision', () => {
35
+ const d = new Date(Date.UTC(2026, 10, 18, 7, 8, 9))
36
+ assert.equal(formatSdkDate(d), '20261118T070809Z')
37
+ })
38
+
39
+ check('signature is deterministic and covers the real body hash', () => {
40
+ const url = new URL('https://example.test/api/v2/chat/completions')
41
+ const credentials = { ak: 'AKID', sk: 'SECRET', securityToken: 'TOKEN' }
42
+ const a = signRequest({ method: 'POST', url, contentType: 'application/json', body: '{"a":1}', credentials, sdkDate: '20261118T070809Z' })
43
+ const b = signRequest({ method: 'POST', url, contentType: 'application/json', body: '{"a":1}', credentials, sdkDate: '20261118T070809Z' })
44
+ assert.deepEqual(a, b)
45
+
46
+ // Recompute the expected signature by hand from the documented canonical
47
+ // form; a mismatch here means the canonical request drifted.
48
+ const payloadHash = createHash('sha256').update('{"a":1}').digest('hex')
49
+ const names = ['content-type', 'host', 'x-sdk-date', 'x-security-token']
50
+ const block = [
51
+ 'content-type:application/json\n',
52
+ 'host:example.test\n',
53
+ 'x-sdk-date:20261118T070809Z\n',
54
+ 'x-security-token:TOKEN\n',
55
+ ].join('')
56
+ const canonical = ['POST', '/api/v2/chat/completions/', '', block, names.join(';'), payloadHash].join('\n')
57
+ const stringToSign = ['SDK-HMAC-SHA256', '20261118T070809Z', createHash('sha256').update(canonical).digest('hex')].join('\n')
58
+ const expected = createHmac('sha256', 'SECRET').update(stringToSign).digest('hex')
59
+ assert.ok(a.Authorization.includes(`Signature=${expected}`), a.Authorization)
60
+ })
61
+
62
+ check('different bodies produce different signatures', () => {
63
+ const url = new URL('https://example.test/x')
64
+ const credentials = { ak: 'AKID', sk: 'SECRET', securityToken: 'TOKEN' }
65
+ const a = signRequest({ method: 'POST', url, contentType: 'application/json', body: '{"a":1}', credentials, sdkDate: '20260101T000000Z' })
66
+ const b = signRequest({ method: 'POST', url, contentType: 'application/json', body: '{"a":2}', credentials, sdkDate: '20260101T000000Z' })
67
+ assert.notEqual(a.Authorization, b.Authorization)
68
+ })
69
+
70
+ check('a non-default port joins the Host header', () => {
71
+ const headers = signRequest({
72
+ method: 'GET',
73
+ url: new URL('https://example.test:8443/x'),
74
+ contentType: null,
75
+ credentials: { ak: 'A', sk: 'S', securityToken: 'T' },
76
+ sdkDate: '20260101T000000Z',
77
+ })
78
+ assert.equal(headers.Host, 'example.test:8443')
79
+ })
80
+
81
+ // ── key agreement ───────────────────────────────────────────────────────────
82
+
83
+ check('session key is the first 16 bytes of the SHA-256 of the secret', () => {
84
+ const secret = Buffer.from('shared-secret-bytes')
85
+ const expected = createHash('sha256').update(secret).digest().subarray(0, 16)
86
+ assert.deepEqual(deriveSessionKey(secret), expected)
87
+ assert.equal(deriveSessionKey(secret).length, 16)
88
+ })
89
+
90
+ // ── envelope ────────────────────────────────────────────────────────────────
91
+
92
+ check('a request envelope round-trips through its own chunk AAD shape', () => {
93
+ // The request AAD binds method/path/timestamp, so a chunk sealed with it is
94
+ // only openable by a frame claiming that exact identity. Prove the envelope
95
+ // is well formed rather than asserting a cross-AAD decrypt.
96
+ const envelope = deriveRequestEnvelope({
97
+ key: Buffer.alloc(16, 5),
98
+ keyId: 'key-1',
99
+ method: 'POST',
100
+ pathname: '/api/v2/chat/completions',
101
+ timestamp: 1700000000000,
102
+ plaintext: '{"model":"m"}',
103
+ })
104
+ assert.equal(envelope.headers['X-Encrypt-Algo'], 'sm4-gcm')
105
+ assert.equal(envelope.headers['X-Encrypt-Key-Id'], 'key-1')
106
+ assert.equal(envelope.headers['X-Encrypt-Ts'], '1700000000000')
107
+ assert.equal(envelope.headers['Content-Type'], 'application/octet-stream')
108
+ assert.ok(/^[A-Za-z0-9+/=]+$/.test(envelope.body), 'body must be base64 text')
109
+ })
110
+
111
+ check('openChunk ignores a frame that is not a triple', () => {
112
+ assert.equal(openChunk('[DONE]', Buffer.alloc(16), 'k', 0), null)
113
+ assert.equal(openChunk('', Buffer.alloc(16), 'k', 0), null)
114
+ assert.equal(openChunk('a:b:c:d', Buffer.alloc(16), 'k', 0), null)
115
+ })
116
+
117
+ // ── SSE ─────────────────────────────────────────────────────────────────────
118
+
119
+ check('the splitter keeps sealed frames, which carry no data: prefix', () => {
120
+ const { blocks, rest } = splitSseEvents('aaa:bbb:ccc\n\n')
121
+ assert.deepEqual(blocks, ['aaa:bbb:ccc'])
122
+ assert.equal(rest, '')
123
+ })
124
+
125
+ check('the splitter leaves a partial trailing block', () => {
126
+ const { blocks, rest } = splitSseEvents('one\n\ntw')
127
+ assert.deepEqual(blocks, ['one'])
128
+ assert.equal(rest, 'tw')
129
+ })
130
+
131
+ check('a plain OpenAI chunk yields text, finish reason, and usage', () => {
132
+ const text = parseStreamEvent('{"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}')
133
+ assert.equal(text.text, 'hi')
134
+
135
+ const finish = parseStreamEvent('{"choices":[{"delta":{},"finish_reason":"stop"}]}')
136
+ assert.equal(finish.finish, 'stop')
137
+
138
+ const usage = parseStreamEvent('{"choices":[],"usage":{"prompt_tokens":3,"completion_tokens":4,"total_tokens":7}}')
139
+ assert.deepEqual(usage.usage, { inputTokens: 3, outputTokens: 4, totalTokens: 7 })
140
+ })
141
+
142
+ check('reasoning and tool calls survive parsing', () => {
143
+ const reasoning = parseStreamEvent('{"choices":[{"delta":{"reasoning_content":"think"}}]}')
144
+ assert.equal(reasoning.reasoning, 'think')
145
+
146
+ const toolCall = parseStreamEvent('{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"f","arguments":"{}"}}]}}]}')
147
+ assert.equal(toolCall.toolCalls.length, 1)
148
+ assert.equal(toolCall.toolCalls[0].id, 'c1')
149
+ })
150
+
151
+ check('[DONE] is recognised as the terminal sentinel', () => {
152
+ assert.deepEqual(parseStreamEvent('[DONE]'), { done: true })
153
+ })
154
+
155
+ check('an upstream error frame is surfaced', () => {
156
+ const event = parseStreamEvent('{"error":{"message":"quota"}}')
157
+ assert.equal(event.error, 'quota')
158
+ })
159
+
160
+ check('an unrecognised frame yields nothing rather than throwing', () => {
161
+ assert.deepEqual(parseStreamEvent('not json'), {})
162
+ assert.deepEqual(parseStreamEvent('{"unrelated":true}'), {})
163
+ })
164
+
165
+ console.log(results.join('\n'))
166
+ if (process.exitCode) console.log('\nsome checks failed')
167
+ else console.log('\nprotocol: all checks passed')