dsh-codearts-dock 0.0.0-stage → 1.0.1
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.
- package/DISCLAIMER.md +47 -0
- package/LICENSE +21 -0
- package/README.md +169 -2
- package/SECURITY.md +45 -0
- package/THIRD_PARTY_NOTICES.md +64 -0
- package/client.js +3491 -0
- package/cordis.patch.yml +10 -0
- package/docs/DETAIL.md +24 -0
- package/docs/DETAIL.zh.md +24 -0
- package/docs/PUBLISHING.md +43 -0
- package/docs/preview.svg +78 -0
- package/icons/dsh-connect-codearts-128.png +0 -0
- package/icons/dsh-connect-codearts-256.png +0 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +88 -4
- package/scripts/build-market-index.mjs +24 -0
- package/scripts/check-legal.sh +33 -0
- package/scripts/check-release.mjs +29 -0
- package/scripts/test.mjs +11 -0
- package/src/account.js +217 -0
- package/src/accounts.js +481 -0
- package/src/adapter.js +715 -0
- package/src/backup.js +89 -0
- package/src/catalog.js +269 -0
- package/src/checkin.js +271 -0
- package/src/credentials.js +435 -0
- package/src/features.js +79 -0
- package/src/gateway.js +521 -0
- package/src/health.js +15 -0
- package/src/index.js +1029 -0
- package/src/models.js +147 -0
- package/src/paths.js +36 -0
- package/src/preferences.js +87 -0
- package/src/protocol/crypto.js +160 -0
- package/src/protocol/sign.js +176 -0
- package/src/protocol/sm4.js +264 -0
- package/src/protocol/sse.js +134 -0
- package/src/sts.js +118 -0
- package/test/accounts.test.mjs +344 -0
- package/test/adapter.test.mjs +234 -0
- package/test/assembler.test.mjs +86 -0
- package/test/features.test.mjs +240 -0
- package/test/live-probe.mjs +55 -0
- package/test/protocol.test.mjs +167 -0
- package/test/registration.test.mjs +303 -0
- package/test/sm4.test.mjs +64 -0
- package/test/ui.test.mjs +732 -0
- package/test/visual.test.mjs +420 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/** Account health, model presets and encrypted migration against isolated local storage. */
|
|
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 { accountHealth } = await import('../src/health.js')
|
|
17
|
+
const { readCredit } = await import('../src/account.js')
|
|
18
|
+
const accounts = await import('../src/accounts.js')
|
|
19
|
+
const results = []
|
|
20
|
+
const check = async (name, fn) => {
|
|
21
|
+
try { await fn(); results.push(`✓ ${name}`) } catch (error) { results.push(`✗ ${name}\n${error.stack}`); process.exitCode = 1 }
|
|
22
|
+
}
|
|
23
|
+
const settings = { ...FEATURE_DEFAULTS, enabledModelIds: null, modelOverrides: {}, composerChip: true, refreshIntervalMs: 300000 }
|
|
24
|
+
const preferences = portablePreferences(settings)
|
|
25
|
+
const secretAccount = { ak: 'TEST_BACKUP_AK_123456789', sk: 'TEST_BACKUP_SK_987654321', label: 'Example' }
|
|
26
|
+
|
|
27
|
+
await check('preferences validate retained settings and ignore retired alert and history fields', async () => {
|
|
28
|
+
for (const invalid of [-1, 0, '60000', 86400001]) assert.throws(() => validatePreferences({ refreshIntervalMs: invalid }))
|
|
29
|
+
assert.throws(() => validatePreferences({ composerChip: 'true' }))
|
|
30
|
+
for (const favoriteModelIds of [null, 'model', [5], ['__proto__'], Array(501).fill('model')]) assert.throws(() => validatePreferences({ favoriteModelIds }))
|
|
31
|
+
assert.deepEqual(validatePreferences({ favoriteModelIds: ['b', 'a', 'b'] }), { favoriteModelIds: ['b', 'a'] })
|
|
32
|
+
assert.throws(() => validatePreferences({ enabledModelIds: [], modelOverrides: {} }))
|
|
33
|
+
assert.throws(() => validatePreferences(JSON.parse('{"modelOverrides":{"__proto__":{"images":true}}}')))
|
|
34
|
+
assert.throws(() => validatePreferences({ modelPresets: Array(21).fill({}) }))
|
|
35
|
+
assert.deepEqual(validatePreferences({ lowBalanceEnabled: true, lowBalanceThreshold: 500, usageEnabled: true, autoCheckin: true, composerChip: true }), { composerChip: true })
|
|
36
|
+
const portable = portablePreferences({ ...settings, lowBalanceEnabled: true, usageEnabled: true, autoCheckin: true })
|
|
37
|
+
assert.ok(!('lowBalanceEnabled' in portable))
|
|
38
|
+
assert.ok(!('usageEnabled' in portable))
|
|
39
|
+
assert.ok(!('autoCheckin' in portable))
|
|
40
|
+
})
|
|
41
|
+
await check('concurrent preference writes are atomic, private, and do not lose other keys', async () => {
|
|
42
|
+
await Promise.all([persistPreferences({ refreshIntervalMs: 120000 }), persistPreferences({ composerChip: false }), persistPreferences({ modelPresets: [] })])
|
|
43
|
+
assert.equal(readPreferences().refreshIntervalMs, 120000)
|
|
44
|
+
assert.equal(readPreferences().composerChip, 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
|
+
const legacy = { ...plain, preferences: { ...plain.preferences, lowBalanceEnabled: true, lowBalanceThreshold: 500, usageEnabled: true, autoCheckin: true } }
|
|
65
|
+
assert.deepEqual((await decodeBackup(JSON.stringify(legacy))).preferences, preferences)
|
|
66
|
+
await assert.rejects(encodeBackup({ preferences, accounts: [secretAccount], includeCredentials: true, password: '' }))
|
|
67
|
+
await assert.rejects(encodeBackup({ preferences, accounts: [secretAccount, { ...secretAccount, ak: ` ${secretAccount.ak} ` }], includeCredentials: true, password: 'test-password-123' }), /重复账号/)
|
|
68
|
+
const encrypted = await encodeBackup({ preferences, accounts: [secretAccount], activeAccountId: accounts.accountIdOf(secretAccount.ak), includeCredentials: true, password: 'test-password-123' })
|
|
69
|
+
assert.ok(!JSON.stringify(encrypted).includes(secretAccount.sk))
|
|
70
|
+
const decoded = await decodeBackup(JSON.stringify(encrypted), 'test-password-123')
|
|
71
|
+
assert.deepEqual(decoded.accounts, [secretAccount])
|
|
72
|
+
assert.equal(decoded.activeAccountId, accounts.accountIdOf(secretAccount.ak))
|
|
73
|
+
await assert.rejects(decodeBackup(JSON.stringify(encrypted), 'wrong-password'), /密码错误/)
|
|
74
|
+
const data = Buffer.from(encrypted.data, 'base64'); data[0] ^= 1
|
|
75
|
+
await assert.rejects(decodeBackup(JSON.stringify({ ...encrypted, data: data.toString('base64') }), 'test-password-123'), /密码错误/)
|
|
76
|
+
await assert.rejects(decodeBackup(JSON.stringify({ ...plain, accounts: [secretAccount] })), /必须为加密/)
|
|
77
|
+
await assert.rejects(decodeBackup(JSON.stringify({ ...plain, version: 99 })))
|
|
78
|
+
})
|
|
79
|
+
await check('concurrent account imports and name discovery cannot overwrite other accounts', async () => {
|
|
80
|
+
const [one] = await Promise.all([accounts.addAccount(secretAccount), accounts.addAccount({ ak: 'SECOND_TEST_AK', sk: 'SECOND_TEST_SK' })])
|
|
81
|
+
await Promise.all([accounts.rememberAccountName(one.account.id, 'Example name'), accounts.addAccount({ ak: 'THIRD_TEST_AK', sk: 'THIRD_TEST_SK' })])
|
|
82
|
+
assert.equal(accounts.readStore().accounts.length, 3)
|
|
83
|
+
assert.equal(accounts.readStore().accounts.find((entry) => entry.id === one.account.id).accountName, 'Example name')
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
const originalFetch = globalThis.fetch
|
|
87
|
+
const disposers = []
|
|
88
|
+
let creditStatus = 200
|
|
89
|
+
let creditReads = 0
|
|
90
|
+
let creditGate = null
|
|
91
|
+
let creditRemain = 50
|
|
92
|
+
let iamReads = 0
|
|
93
|
+
let benefitReads = 0
|
|
94
|
+
const jsonResponse = (value, status = 200) => new Response(JSON.stringify(value), { status })
|
|
95
|
+
globalThis.fetch = async (input) => {
|
|
96
|
+
const url = String(input)
|
|
97
|
+
if (url.includes('iam.cn-north-4.myhuaweicloud.com')) {
|
|
98
|
+
iamReads += 1
|
|
99
|
+
return jsonResponse({ credential: { access: 'TEMP_TEST_AK', secret: 'TEMP_TEST_SK', securitytoken: 'TEMP_TEST_TOKEN', expires_at: new Date(Date.now() + 3600000).toISOString() } })
|
|
100
|
+
}
|
|
101
|
+
if (url.includes('/statistics/plugin')) {
|
|
102
|
+
creditReads += 1
|
|
103
|
+
const remain = creditRemain
|
|
104
|
+
await creditGate
|
|
105
|
+
if (creditStatus !== 200) return jsonResponse({ message: 'mock failure' }, creditStatus)
|
|
106
|
+
return jsonResponse({ metrics: [{ name: 'usageTotalPackageCredit', package_credit_amount: 1000, package_credit_used: 950, package_credit_remain: remain }] })
|
|
107
|
+
}
|
|
108
|
+
if (url.includes('/v1/model/builtin') || url.includes('/v1/model/thinking-variants')) return jsonResponse([])
|
|
109
|
+
if (url.includes('/v1/ops/delivery')) { benefitReads += 1; return jsonResponse([]) }
|
|
110
|
+
if (url.includes('/member/roles')) return jsonResponse([])
|
|
111
|
+
throw new Error('Offline test blocked an unexpected gateway request')
|
|
112
|
+
}
|
|
113
|
+
const routes = new Map()
|
|
114
|
+
const plugin = await import('../src/index.js')
|
|
115
|
+
const effect = (fn) => { const dispose = fn(); if (typeof dispose === 'function') disposers.push(dispose); return dispose }
|
|
116
|
+
plugin.apply({ effect, get: () => undefined, emit() {}, inject: (_, callback) => callback({ effect, webServer: { register: (route) => { routes.set(route.path, route.handler); return () => {} } } }) }, { registerProvider: false, autoCheckin: true })
|
|
117
|
+
for (const path of ['/usage', '/usage/clear', '/checkin/auto']) assert.ok(!routes.has(`/plugins/dsh-connect-codearts${path}`), `Retired route registered: ${path}`)
|
|
118
|
+
const request = (path, body, method = body === undefined ? 'GET' : 'POST', options = {}) => new Promise((resolve, reject) => {
|
|
119
|
+
const handler = routes.get(`/plugins/dsh-connect-codearts${path}`)
|
|
120
|
+
if (!handler) return reject(new Error(`Unknown route ${path}`))
|
|
121
|
+
const req = Readable.from(options.raw !== undefined ? [Buffer.from(options.raw)] : body === undefined ? [] : [Buffer.from(JSON.stringify(body))])
|
|
122
|
+
Object.assign(req, { method, url: `/plugins/dsh-connect-codearts${path}`, socket: { remoteAddress: options.remoteAddress ?? '127.0.0.1' } })
|
|
123
|
+
let status
|
|
124
|
+
handler(req, { setHeader() {}, writeHead: (value) => { status = value }, end: (text) => resolve({ status, body: JSON.parse(text) }) })
|
|
125
|
+
})
|
|
126
|
+
await check('legacy automatic check-in settings cause no background benefit requests', async () => {
|
|
127
|
+
await new Promise(setImmediate)
|
|
128
|
+
assert.equal(benefitReads, 0, 'legacy autoCheckin=true must not run a claim sweep on startup')
|
|
129
|
+
const result = await request('/preferences')
|
|
130
|
+
assert.ok(!('autoCheckin' in result.body.preferences))
|
|
131
|
+
assert.equal((await request('/checkin/claim-all', {})).status, 200, 'manual batch route remains available')
|
|
132
|
+
assert.ok(benefitReads > 0, 'the manual request checks upstream eligibility')
|
|
133
|
+
})
|
|
134
|
+
await check('feature routes enforce POST, validate preferences, and persist presets without changing the live selection', async () => {
|
|
135
|
+
for (const path of ['/preferences/save', '/presets', '/backup/export', '/backup/preview', '/backup/restore', '/accounts/check', '/checkin/claim-all']) assert.equal((await request(path)).status, 405)
|
|
136
|
+
assert.equal((await request('/preferences/save', { refreshIntervalMs: -1 })).status, 400)
|
|
137
|
+
const preferenceSave = await request('/preferences/save', { refreshIntervalMs: 75000, composerChip: true })
|
|
138
|
+
assert.equal(preferenceSave.body.preferences.refreshIntervalMs, 75000)
|
|
139
|
+
const preset = await request('/presets', { action: 'save', name: 'Daily', enabledModelIds: ['test-model'], modelOverrides: { 'test-model': { images: true, defaultStrength: 'high' } } })
|
|
140
|
+
assert.equal(preset.status, 200)
|
|
141
|
+
assert.equal(preset.body.presets.length, 1)
|
|
142
|
+
assert.equal((await request('/models')).body.enabledIds, null)
|
|
143
|
+
const id = preset.body.presets[0].id
|
|
144
|
+
assert.equal((await request('/presets', { action: 'delete', id })).body.presets.length, 0)
|
|
145
|
+
})
|
|
146
|
+
await check('pinned models persist without changing model selection and travel with backups', async () => {
|
|
147
|
+
const before = (await request('/models')).body.enabledIds
|
|
148
|
+
const saved = await request('/preferences/save', { favoriteModelIds: ['test-model', 'temporarily-unavailable'] })
|
|
149
|
+
assert.deepEqual(saved.body.preferences.favoriteModelIds, ['test-model', 'temporarily-unavailable'])
|
|
150
|
+
assert.deepEqual(readPreferences().favoriteModelIds, ['test-model', 'temporarily-unavailable'])
|
|
151
|
+
assert.deepEqual((await request('/models')).body.favoriteModelIds, ['test-model', 'temporarily-unavailable'])
|
|
152
|
+
assert.deepEqual((await request('/models')).body.enabledIds, before)
|
|
153
|
+
const exported = await request('/backup/export', {})
|
|
154
|
+
assert.deepEqual(exported.body.backup.preferences.favoriteModelIds, ['test-model', 'temporarily-unavailable'])
|
|
155
|
+
await request('/preferences/save', { favoriteModelIds: [] })
|
|
156
|
+
const restored = await request('/backup/restore', { text: JSON.stringify(exported.body.backup) })
|
|
157
|
+
assert.equal(restored.status, 200)
|
|
158
|
+
assert.deepEqual((await request('/models')).body.favoriteModelIds, ['test-model', 'temporarily-unavailable'])
|
|
159
|
+
})
|
|
160
|
+
await check('malformed, non-object, oversized and remote feature requests are rejected without mutations', async () => {
|
|
161
|
+
const before = JSON.stringify((await request('/preferences')).body)
|
|
162
|
+
for (const path of ['/preferences/save', '/presets', '/backup/export', '/backup/preview', '/backup/restore', '/accounts/check', '/checkin/claim-all']) {
|
|
163
|
+
for (const body of [null, [], 42, 'invalid']) {
|
|
164
|
+
assert.equal((await request(path, body)).status, 400, `${path} must reject ${JSON.stringify(body)}`)
|
|
165
|
+
}
|
|
166
|
+
assert.equal((await request(path, {}, 'POST', { raw: '{bad-json' })).status, 400)
|
|
167
|
+
}
|
|
168
|
+
assert.equal((await request('/preferences/save', { ignored: 'x'.repeat(65536) })).status, 413)
|
|
169
|
+
assert.equal((await request('/backup/preview', { text: 'x'.repeat(1024 * 1024) })).status, 413)
|
|
170
|
+
assert.equal((await request('/preferences/save', { refreshIntervalMs: 123000 }, 'POST', { remoteAddress: '192.0.2.1' })).status, 403)
|
|
171
|
+
assert.equal(JSON.stringify((await request('/preferences')).body), before)
|
|
172
|
+
})
|
|
173
|
+
await check('account checks use one probe for concurrent clicks, expose actionable status, and keep the credit overview', async () => {
|
|
174
|
+
const id = accounts.readStore().accounts[0].id
|
|
175
|
+
await new Promise(setImmediate)
|
|
176
|
+
const creditsBefore = creditReads, iamBefore = iamReads
|
|
177
|
+
const [a, b] = await Promise.all([request('/accounts/check', { id }), request('/accounts/check', { id })])
|
|
178
|
+
assert.equal(a.body.account.health.state, 'available')
|
|
179
|
+
assert.equal(b.body.account.credit.remain, 50)
|
|
180
|
+
assert.ok(b.body.account.creditCheckedAt > 0)
|
|
181
|
+
assert.equal(typeof b.body.account.creditIdentity, 'string')
|
|
182
|
+
assert.ok(!('lowBalance' in b.body.account))
|
|
183
|
+
assert.equal(creditReads - creditsBefore, 1)
|
|
184
|
+
assert.equal(iamReads - iamBefore, 1)
|
|
185
|
+
creditStatus = 429
|
|
186
|
+
assert.equal((await request('/accounts/check', { id })).body.account.health.state, 'rate_limited')
|
|
187
|
+
creditStatus = 200
|
|
188
|
+
const active = (await request('/account')).body
|
|
189
|
+
assert.equal(active.credit.remain, 50)
|
|
190
|
+
assert.ok(!('lowBalanceThreshold' in active))
|
|
191
|
+
})
|
|
192
|
+
await check('an invalidated in-flight health probe cannot repopulate stale account state', async () => {
|
|
193
|
+
const account = accounts.readStore().accounts[0]
|
|
194
|
+
let release
|
|
195
|
+
creditGate = new Promise((resolve) => { release = resolve })
|
|
196
|
+
const oldProbe = request('/accounts/check', { id: account.id })
|
|
197
|
+
await new Promise(setImmediate)
|
|
198
|
+
assert.equal((await request('/accounts/add', { ak: account.ak, sk: account.sk, label: account.label })).status, 200)
|
|
199
|
+
creditRemain = 500
|
|
200
|
+
creditGate = null
|
|
201
|
+
release()
|
|
202
|
+
await oldProbe
|
|
203
|
+
const pool = await request('/accounts')
|
|
204
|
+
assert.equal(pool.body.accounts.find((entry) => entry.id === account.id).credit.remain, 500)
|
|
205
|
+
creditRemain = 50
|
|
206
|
+
})
|
|
207
|
+
await check('backup preview writes nothing; restore merges accounts, preferences and presets, while wrong passwords do not mutate', async () => {
|
|
208
|
+
const exportResponse = await request('/backup/export', { includeCredentials: true, password: 'test-password-123' })
|
|
209
|
+
assert.equal(exportResponse.status, 200)
|
|
210
|
+
const text = JSON.stringify(exportResponse.body.backup)
|
|
211
|
+
const before = JSON.stringify(accounts.readStore())
|
|
212
|
+
assert.equal((await request('/backup/preview', { text, password: 'wrong-password' })).status, 400)
|
|
213
|
+
assert.equal(JSON.stringify(accounts.readStore()), before)
|
|
214
|
+
const preview = await request('/backup/preview', { text, password: 'test-password-123' })
|
|
215
|
+
assert.equal(preview.body.accounts.updated, 3)
|
|
216
|
+
assert.equal(JSON.stringify(accounts.readStore()), before)
|
|
217
|
+
assert.ok(!JSON.stringify(preview.body).includes(secretAccount.sk))
|
|
218
|
+
await request('/preferences/save', { refreshIntervalMs: 999000 })
|
|
219
|
+
const preservedId = accounts.readStore().accounts.at(-1).id
|
|
220
|
+
await accounts.setActiveAccount(preservedId)
|
|
221
|
+
const restore = await request('/backup/restore', { text, password: 'test-password-123' })
|
|
222
|
+
assert.equal(restore.status, 200)
|
|
223
|
+
assert.equal(restore.body.updated, 3)
|
|
224
|
+
assert.equal((await request('/preferences')).body.preferences.refreshIntervalMs, 75000)
|
|
225
|
+
assert.equal(accounts.readStore().accounts.length, 3)
|
|
226
|
+
assert.equal(accounts.readStore().activeId, preservedId)
|
|
227
|
+
|
|
228
|
+
// Simulate a new installation using only this suite's temporary account store.
|
|
229
|
+
for (const account of accounts.readStore().accounts) await accounts.removeAccount(account.id)
|
|
230
|
+
const fresh = await request('/backup/restore', { text, password: 'test-password-123' })
|
|
231
|
+
assert.equal(fresh.status, 200)
|
|
232
|
+
assert.equal(fresh.body.added, 3)
|
|
233
|
+
assert.equal(accounts.readStore().activeId, accounts.accountIdOf(secretAccount.ak))
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
for (const dispose of disposers.reverse()) dispose()
|
|
237
|
+
globalThis.fetch = originalFetch
|
|
238
|
+
await rm(scratch, { recursive: true, force: true })
|
|
239
|
+
console.log(results.join('\n'))
|
|
240
|
+
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')
|