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,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SM4-GCM, implemented in plain JavaScript.
|
|
3
|
+
*
|
|
4
|
+
* WHY NOT `node:crypto`: the Harness Host runs on Electron's bundled Node,
|
|
5
|
+
* whose OpenSSL exposes sm4 / sm4-cbc / sm4-cfb / sm4-ctr / sm4-ecb / sm4-ofb
|
|
6
|
+
* but NOT `sm4-gcm` — `createCipheriv('sm4-gcm', ...)` throws "Unknown
|
|
7
|
+
* cipher". A system Node may have it; the Host does not, and this file runs
|
|
8
|
+
* inside the Host process. So the cipher is here, not in the runtime.
|
|
9
|
+
*
|
|
10
|
+
* SCOPE: exactly what the 码道 gateway uses — SM4 block cipher
|
|
11
|
+
* (GB/T 32907-2016, 128-bit key and block, 32 rounds) and GCM
|
|
12
|
+
* (NIST SP 800-38D) with a 12-byte IV and a 16-byte tag. The output is
|
|
13
|
+
* byte-identical to OpenSSL's `sm4-gcm` (cross-checked in the tests).
|
|
14
|
+
*
|
|
15
|
+
* Source of the constants: the published GB/T 32907 S-box and round
|
|
16
|
+
* constants. This is a standard implementation, not a reverse-engineered one.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
// ── SM4 block cipher ─────────────────────────────────────────────────────────
|
|
20
|
+
|
|
21
|
+
const SBOX = new Uint8Array([
|
|
22
|
+
0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05,
|
|
23
|
+
0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99,
|
|
24
|
+
0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62,
|
|
25
|
+
0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6,
|
|
26
|
+
0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8,
|
|
27
|
+
0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35,
|
|
28
|
+
0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87,
|
|
29
|
+
0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e,
|
|
30
|
+
0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1,
|
|
31
|
+
0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3,
|
|
32
|
+
0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f,
|
|
33
|
+
0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51,
|
|
34
|
+
0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8,
|
|
35
|
+
0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0,
|
|
36
|
+
0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84,
|
|
37
|
+
0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48,
|
|
38
|
+
])
|
|
39
|
+
|
|
40
|
+
const CK = new Uint32Array([
|
|
41
|
+
0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269,
|
|
42
|
+
0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9,
|
|
43
|
+
0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249,
|
|
44
|
+
0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9,
|
|
45
|
+
0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229,
|
|
46
|
+
0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299,
|
|
47
|
+
0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209,
|
|
48
|
+
0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279,
|
|
49
|
+
])
|
|
50
|
+
|
|
51
|
+
/** 32-bit left rotation. */
|
|
52
|
+
function rotl(x, n) {
|
|
53
|
+
return (x << n) | (x >>> (32 - n))
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The `tau` substitution: byte-wise S-box application. */
|
|
57
|
+
function tau(a) {
|
|
58
|
+
return (
|
|
59
|
+
((SBOX[(a >>> 24) & 0xff] << 24) |
|
|
60
|
+
(SBOX[(a >>> 16) & 0xff] << 16) |
|
|
61
|
+
(SBOX[(a >>> 8) & 0xff] << 8) |
|
|
62
|
+
SBOX[a & 0xff]) >>>
|
|
63
|
+
0
|
|
64
|
+
)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The `L` transform (encryption/key schedule) and its reverse. */
|
|
68
|
+
function L(b) {
|
|
69
|
+
return (b ^ rotl(b, 2) ^ rotl(b, 10) ^ rotl(b, 18) ^ rotl(b, 24)) >>> 0
|
|
70
|
+
}
|
|
71
|
+
function LPrime(b) {
|
|
72
|
+
return (b ^ rotl(b, 13) ^ rotl(b, 23)) >>> 0
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The linear-transform-round helper shared by encryption and key schedule. */
|
|
76
|
+
function t(a) {
|
|
77
|
+
return L(tau(a))
|
|
78
|
+
}
|
|
79
|
+
function tPrime(a) {
|
|
80
|
+
return LPrime(tau(a))
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The fixed system parameter `FK` of GB/T 32907. */
|
|
84
|
+
const FK = [0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc]
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Expand a 16-byte key into 32 round keys.
|
|
88
|
+
*
|
|
89
|
+
* GB/T 32907 key schedule: K[0..3] = MK[0..3] ^ FK[0..3], then
|
|
90
|
+
* rk[i] = K[i+4] = K[i] ^ T'(K[i+1] ^ K[i+2] ^ K[i+3] ^ CK[i]).
|
|
91
|
+
*/
|
|
92
|
+
function expandKey(key) {
|
|
93
|
+
const K = new Uint32Array(36)
|
|
94
|
+
for (let i = 0; i < 4; i++) {
|
|
95
|
+
K[i] = (((key[i * 4] << 24) | (key[i * 4 + 1] << 16) | (key[i * 4 + 2] << 8) | key[i * 4 + 3]) >>> 0) ^ FK[i]
|
|
96
|
+
}
|
|
97
|
+
const rk = new Uint32Array(32)
|
|
98
|
+
for (let i = 0; i < 32; i++) {
|
|
99
|
+
K[i + 4] = (K[i] ^ tPrime((K[i + 1] ^ K[i + 2] ^ K[i + 3] ^ CK[i]) >>> 0)) >>> 0
|
|
100
|
+
rk[i] = K[i + 4]
|
|
101
|
+
}
|
|
102
|
+
return rk
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Encrypt one 16-byte block in place through `out`. */
|
|
106
|
+
function encryptBlock(rk, block, out, offset = 0) {
|
|
107
|
+
let x0 = ((block[0] << 24) | (block[1] << 16) | (block[2] << 8) | block[3]) >>> 0
|
|
108
|
+
let x1 = ((block[4] << 24) | (block[5] << 16) | (block[6] << 8) | block[7]) >>> 0
|
|
109
|
+
let x2 = ((block[8] << 24) | (block[9] << 16) | (block[10] << 8) | block[11]) >>> 0
|
|
110
|
+
let x3 = ((block[12] << 24) | (block[13] << 16) | (block[14] << 8) | block[15]) >>> 0
|
|
111
|
+
|
|
112
|
+
for (let i = 0; i < 32; i++) {
|
|
113
|
+
const x = (x0 ^ t((x1 ^ x2 ^ x3 ^ rk[i]) >>> 0)) >>> 0
|
|
114
|
+
x0 = x1
|
|
115
|
+
x1 = x2
|
|
116
|
+
x2 = x3
|
|
117
|
+
x3 = x
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// The final round reverses the word order: (x35, x34, x33, x32).
|
|
121
|
+
const words = [x3, x2, x1, x0]
|
|
122
|
+
for (let i = 0; i < 4; i++) {
|
|
123
|
+
const w = words[i]
|
|
124
|
+
out[offset + i * 4] = (w >>> 24) & 0xff
|
|
125
|
+
out[offset + i * 4 + 1] = (w >>> 16) & 0xff
|
|
126
|
+
out[offset + i * 4 + 2] = (w >>> 8) & 0xff
|
|
127
|
+
out[offset + i * 4 + 3] = w & 0xff
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ── GHASH ────────────────────────────────────────────────────────────────────
|
|
132
|
+
|
|
133
|
+
/** Multiply two GF(2^128) elements in the GCM bit order. */
|
|
134
|
+
function gfMul(x, y) {
|
|
135
|
+
let z = 0n
|
|
136
|
+
let v = y
|
|
137
|
+
for (let i = 0; i < 128; i++) {
|
|
138
|
+
if ((x >> BigInt(127 - i)) & 1n) z ^= v
|
|
139
|
+
const lsb = v & 1n
|
|
140
|
+
v >>= 1n
|
|
141
|
+
if (lsb) v ^= 0xe1000000000000000000000000000000n
|
|
142
|
+
}
|
|
143
|
+
return z
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function bytesToBigInt(buf) {
|
|
147
|
+
let n = 0n
|
|
148
|
+
for (const b of buf) n = (n << 8n) | BigInt(b)
|
|
149
|
+
return n
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function bigIntToBytes(n, len) {
|
|
153
|
+
const out = new Uint8Array(len)
|
|
154
|
+
for (let i = len - 1; i >= 0; i--) {
|
|
155
|
+
out[i] = Number(n & 0xffn)
|
|
156
|
+
n >>= 8n
|
|
157
|
+
}
|
|
158
|
+
return out
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Compute GHASH over `aad || ciphertext || lengths`. */
|
|
162
|
+
function ghash(hBytes, aad, ciphertext) {
|
|
163
|
+
const h = bytesToBigInt(hBytes)
|
|
164
|
+
let y = 0n
|
|
165
|
+
const push = (data) => {
|
|
166
|
+
for (let i = 0; i < data.length; i += 16) {
|
|
167
|
+
const chunk = new Uint8Array(16)
|
|
168
|
+
chunk.set(data.subarray(i, i + 16))
|
|
169
|
+
y = gfMul(y ^ bytesToBigInt(chunk), h)
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
push(aad)
|
|
173
|
+
push(ciphertext)
|
|
174
|
+
const lens = new Uint8Array(16)
|
|
175
|
+
const aadBits = BigInt(aad.length) * 8n
|
|
176
|
+
const ctBits = BigInt(ciphertext.length) * 8n
|
|
177
|
+
lens.set(bigIntToBytes(aadBits, 8), 0)
|
|
178
|
+
lens.set(bigIntToBytes(ctBits, 8), 8)
|
|
179
|
+
y = gfMul(y ^ bytesToBigInt(lens), h)
|
|
180
|
+
return bigIntToBytes(y, 16)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The GCM initial counter block: J0 = IV || 0^31 || 1 for a 96-bit IV. */
|
|
184
|
+
function counterBlock(iv) {
|
|
185
|
+
const j0 = new Uint8Array(16)
|
|
186
|
+
j0.set(iv.subarray(0, 12), 0)
|
|
187
|
+
j0[15] = 1
|
|
188
|
+
return j0
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Increment the low 32 bits of a counter block. */
|
|
192
|
+
function inc32(block) {
|
|
193
|
+
for (let i = 15; i >= 12; i--) {
|
|
194
|
+
block[i] = (block[i] + 1) & 0xff
|
|
195
|
+
if (block[i] !== 0) break
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Run CTR mode over `input`, starting from `j0` incremented once. */
|
|
200
|
+
function ctrCrypt(rk, j0, input) {
|
|
201
|
+
const out = new Uint8Array(input.length)
|
|
202
|
+
const counter = j0.slice()
|
|
203
|
+
const block = new Uint8Array(16)
|
|
204
|
+
for (let i = 0; i < input.length; i += 16) {
|
|
205
|
+
inc32(counter)
|
|
206
|
+
encryptBlock(rk, counter, block, 0)
|
|
207
|
+
const end = Math.min(16, input.length - i)
|
|
208
|
+
for (let j = 0; j < end; j++) out[i + j] = input[i + j] ^ block[j]
|
|
209
|
+
}
|
|
210
|
+
return out
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ── public API ───────────────────────────────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Encrypt with SM4-GCM.
|
|
217
|
+
* @param {Uint8Array} key 16-byte key.
|
|
218
|
+
* @param {Uint8Array} iv 12-byte IV.
|
|
219
|
+
* @param {Uint8Array} plaintext data to seal.
|
|
220
|
+
* @param {Uint8Array} aad additional authenticated data.
|
|
221
|
+
* @returns {{ciphertext: Uint8Array, tag: Uint8Array}} ciphertext and the 16-byte tag.
|
|
222
|
+
*/
|
|
223
|
+
export function sm4GcmEncrypt(key, iv, plaintext, aad = new Uint8Array(0)) {
|
|
224
|
+
if (key.length !== 16) throw new Error('SM4 key must be 16 bytes')
|
|
225
|
+
if (iv.length !== 12) throw new Error('SM4-GCM IV must be 12 bytes')
|
|
226
|
+
const rk = expandKey(key)
|
|
227
|
+
const j0 = counterBlock(iv)
|
|
228
|
+
const ciphertext = ctrCrypt(rk, j0, plaintext)
|
|
229
|
+
const h = new Uint8Array(16)
|
|
230
|
+
encryptBlock(rk, new Uint8Array(16), h, 0)
|
|
231
|
+
const s = ghash(h, aad, ciphertext)
|
|
232
|
+
const ek = new Uint8Array(16)
|
|
233
|
+
encryptBlock(rk, j0, ek, 0)
|
|
234
|
+
const tag = new Uint8Array(16)
|
|
235
|
+
for (let i = 0; i < 16; i++) tag[i] = s[i] ^ ek[i]
|
|
236
|
+
return { ciphertext, tag }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Decrypt with SM4-GCM and verify the tag.
|
|
241
|
+
* @throws when the tag does not match (tampering or a wrong key/AAD).
|
|
242
|
+
*/
|
|
243
|
+
export function sm4GcmDecrypt(key, iv, ciphertext, tag, aad = new Uint8Array(0)) {
|
|
244
|
+
if (key.length !== 16) throw new Error('SM4 key must be 16 bytes')
|
|
245
|
+
if (iv.length !== 12) throw new Error('SM4-GCM IV must be 12 bytes')
|
|
246
|
+
if (tag.length !== 16) throw new Error('SM4-GCM tag must be 16 bytes')
|
|
247
|
+
const rk = expandKey(key)
|
|
248
|
+
const j0 = counterBlock(iv)
|
|
249
|
+
const h = new Uint8Array(16)
|
|
250
|
+
encryptBlock(rk, new Uint8Array(16), h, 0)
|
|
251
|
+
const s = ghash(h, aad, ciphertext)
|
|
252
|
+
const ek = new Uint8Array(16)
|
|
253
|
+
encryptBlock(rk, j0, ek, 0)
|
|
254
|
+
const expected = new Uint8Array(16)
|
|
255
|
+
for (let i = 0; i < 16; i++) expected[i] = s[i] ^ ek[i]
|
|
256
|
+
|
|
257
|
+
// Constant-time tag comparison: a length-or-content early return would leak
|
|
258
|
+
// how much of the tag matched.
|
|
259
|
+
let diff = 0
|
|
260
|
+
for (let i = 0; i < 16; i++) diff |= expected[i] ^ tag[i]
|
|
261
|
+
if (diff !== 0) throw new Error('SM4-GCM authentication failed')
|
|
262
|
+
|
|
263
|
+
return ctrCrypt(rk, j0, ciphertext)
|
|
264
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-sent-event parsing for the 码道 chat stream.
|
|
3
|
+
*
|
|
4
|
+
* The gateway streams OpenAI-shaped chunks (`data: {...}`), so the parser
|
|
5
|
+
* reads that shape first and keeps a tolerant fallback for an ai-sdk-shaped
|
|
6
|
+
* event, which the same endpoint has been observed to emit. An unrecognised
|
|
7
|
+
* event yields nothing rather than throwing: a single unknown frame must not
|
|
8
|
+
* abort an otherwise healthy response.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @typedef {object} ParsedEvent
|
|
13
|
+
* @property {string} [text] visible text delta.
|
|
14
|
+
* @property {string} [reasoning] reasoning delta.
|
|
15
|
+
* @property {Array<object>} [toolCalls] tool-call deltas, passed through verbatim.
|
|
16
|
+
* @property {string} [finish] finish reason.
|
|
17
|
+
* @property {{inputTokens: number, outputTokens: number, totalTokens: number}} [usage] usage.
|
|
18
|
+
* @property {string} [error] upstream error text.
|
|
19
|
+
* @property {boolean} [done] the `[DONE]` sentinel was seen.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Split a stream buffer into complete blocks, returning the remainder.
|
|
24
|
+
*
|
|
25
|
+
* A block is whatever sits between two blank lines. It is NOT required to
|
|
26
|
+
* carry a `data:` prefix: a sealed 码道 frame is an `iv:tag:ciphertext`
|
|
27
|
+
* triple, and only the plaintext behind it is SSE-shaped. Filtering here by
|
|
28
|
+
* prefix would silently discard every sealed frame.
|
|
29
|
+
*
|
|
30
|
+
* @param {string} buffer accumulated stream text.
|
|
31
|
+
* @returns {{blocks: string[], rest: string}} complete blocks and the trailing partial.
|
|
32
|
+
*/
|
|
33
|
+
export function splitSseEvents(buffer) {
|
|
34
|
+
const blocks = []
|
|
35
|
+
let rest = buffer
|
|
36
|
+
for (;;) {
|
|
37
|
+
const match = /\r?\n\r?\n/.exec(rest)
|
|
38
|
+
if (!match) break
|
|
39
|
+
const raw = rest.slice(0, match.index)
|
|
40
|
+
rest = rest.slice(match.index + match[0].length)
|
|
41
|
+
if (raw.trim() !== '') blocks.push(raw.trim())
|
|
42
|
+
}
|
|
43
|
+
return { blocks, rest }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Parse one SSE payload.
|
|
48
|
+
* @param {string} data the text after `data:`, already joined.
|
|
49
|
+
* @returns {ParsedEvent} whatever the frame carries; empty when unrecognised.
|
|
50
|
+
*/
|
|
51
|
+
export function parseStreamEvent(data) {
|
|
52
|
+
const trimmed = data.trim()
|
|
53
|
+
if (trimmed === '') return {}
|
|
54
|
+
if (trimmed === '[DONE]') return { done: true }
|
|
55
|
+
|
|
56
|
+
let obj
|
|
57
|
+
try {
|
|
58
|
+
obj = JSON.parse(trimmed)
|
|
59
|
+
} catch {
|
|
60
|
+
return {}
|
|
61
|
+
}
|
|
62
|
+
if (obj === null || typeof obj !== 'object') return {}
|
|
63
|
+
|
|
64
|
+
/** @type {ParsedEvent} */
|
|
65
|
+
const out = {}
|
|
66
|
+
|
|
67
|
+
// An upstream failure can arrive as a normal-looking frame.
|
|
68
|
+
if (obj.error) {
|
|
69
|
+
const error = obj.error
|
|
70
|
+
out.error = typeof error === 'string' ? error : (error.message ?? JSON.stringify(error))
|
|
71
|
+
return out
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// ── OpenAI chat-completions chunk ────────────────────────────────────────
|
|
75
|
+
if (Array.isArray(obj.choices)) {
|
|
76
|
+
// Usage arrives on its own frame with an empty `choices` array.
|
|
77
|
+
if (obj.usage) out.usage = readUsage(obj.usage)
|
|
78
|
+
|
|
79
|
+
const choice = obj.choices[0]
|
|
80
|
+
if (!choice) return out
|
|
81
|
+
|
|
82
|
+
const delta = choice.delta ?? choice.message ?? {}
|
|
83
|
+
if (typeof delta.content === 'string' && delta.content !== '') out.text = delta.content
|
|
84
|
+
if (typeof delta.reasoning_content === 'string' && delta.reasoning_content !== '') {
|
|
85
|
+
out.reasoning = delta.reasoning_content
|
|
86
|
+
}
|
|
87
|
+
if (typeof delta.reasoning === 'string' && delta.reasoning !== '') out.reasoning = delta.reasoning
|
|
88
|
+
// Tool calls must pass through untouched: dropping them loses every
|
|
89
|
+
// action the model asked for and surfaces as `finish_reason: tool_calls`
|
|
90
|
+
// with empty content, which the host reports as a broken response.
|
|
91
|
+
if (Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0) {
|
|
92
|
+
out.toolCalls = delta.tool_calls
|
|
93
|
+
}
|
|
94
|
+
if (choice.finish_reason) out.finish = String(choice.finish_reason)
|
|
95
|
+
return out
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ── ai-sdk event shapes ──────────────────────────────────────────────────
|
|
99
|
+
const type = typeof obj.type === 'string' ? obj.type : ''
|
|
100
|
+
if (type === 'text-delta' || type === 'text_delta') {
|
|
101
|
+
out.text = obj.delta ?? obj.textDelta ?? obj.text ?? ''
|
|
102
|
+
return out
|
|
103
|
+
}
|
|
104
|
+
if (type === 'reasoning' || type === 'reasoning-delta') {
|
|
105
|
+
out.reasoning = obj.delta ?? obj.textDelta ?? obj.text ?? ''
|
|
106
|
+
return out
|
|
107
|
+
}
|
|
108
|
+
if (type === 'finish' || type === 'finish-step') {
|
|
109
|
+
out.finish = obj.finishReason ?? obj.finish_reason ?? 'stop'
|
|
110
|
+
if (obj.usage) out.usage = readUsage(obj.usage)
|
|
111
|
+
return out
|
|
112
|
+
}
|
|
113
|
+
if (type === 'error') {
|
|
114
|
+
out.error = obj.error ?? obj.message ?? 'upstream stream error'
|
|
115
|
+
return out
|
|
116
|
+
}
|
|
117
|
+
if (type === 'message.part.updated') {
|
|
118
|
+
const part = obj.part ?? obj.properties?.part ?? {}
|
|
119
|
+
if (part.type === 'text' && typeof part.text === 'string') out.text = part.text
|
|
120
|
+
if (part.type === 'reasoning' && typeof part.text === 'string') out.reasoning = part.text
|
|
121
|
+
return out
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return out
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Normalise a usage object, accepting both snake_case and camelCase. */
|
|
128
|
+
function readUsage(usage) {
|
|
129
|
+
return {
|
|
130
|
+
inputTokens: usage.prompt_tokens ?? usage.promptTokens ?? usage.inputTokens ?? 0,
|
|
131
|
+
outputTokens: usage.completion_tokens ?? usage.completionTokens ?? usage.outputTokens ?? 0,
|
|
132
|
+
totalTokens: usage.total_tokens ?? usage.totalTokens ?? 0,
|
|
133
|
+
}
|
|
134
|
+
}
|
package/src/sts.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exchange a permanent Huawei Cloud AK/SK pair for temporary STS credentials.
|
|
3
|
+
*
|
|
4
|
+
* Endpoint: POST /v3.0/OS-CREDENTIAL/securitytokens
|
|
5
|
+
*
|
|
6
|
+
* Two facts about this exchange are counter-intuitive and both cost real
|
|
7
|
+
* debugging time:
|
|
8
|
+
*
|
|
9
|
+
* 1. The SIGNED canonical URI carries a trailing slash; the request itself
|
|
10
|
+
* does not. A mismatch answers `401 verify ak sk signature failed`.
|
|
11
|
+
* 2. The body must declare `methods: ["token"]`. `["hw_ak_sk"]` is
|
|
12
|
+
* rejected with `Unsupported method`. The AK/SK prove themselves in the
|
|
13
|
+
* signature, not in the body.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { signHuawei } from './protocol/sign.js'
|
|
17
|
+
|
|
18
|
+
const IAM_HOST = 'iam.cn-north-4.myhuaweicloud.com'
|
|
19
|
+
const IAM_REQUEST_PATH = '/v3.0/OS-CREDENTIAL/securitytokens'
|
|
20
|
+
/** The signed form: the request path plus a trailing slash. */
|
|
21
|
+
const IAM_SIGN_PATH = `${IAM_REQUEST_PATH}/`
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @typedef {object} TemporaryCredential
|
|
25
|
+
* @property {string} ak temporary access key id.
|
|
26
|
+
* @property {string} sk temporary secret access key.
|
|
27
|
+
* @property {string} securityToken the STS token, sent as `X-Security-Token`.
|
|
28
|
+
* @property {string} expiresAt ISO-8601 expiry.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/** A failure from the IAM exchange, with the upstream text preserved. */
|
|
32
|
+
export class StsError extends Error {
|
|
33
|
+
constructor(message) {
|
|
34
|
+
super(message)
|
|
35
|
+
this.name = 'StsError'
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Exchange permanent credentials for STS credentials.
|
|
41
|
+
* @param {string} ak permanent access key id.
|
|
42
|
+
* @param {string} sk permanent secret access key.
|
|
43
|
+
* @param {number} [durationSeconds] requested lifetime; 3600 default, 86400 max.
|
|
44
|
+
* @param {typeof fetch} [fetchImpl] fetch implementation, for tests.
|
|
45
|
+
* @returns {Promise<TemporaryCredential>} the temporary triple.
|
|
46
|
+
*/
|
|
47
|
+
export async function getSts(ak, sk, durationSeconds = 3600, fetchImpl = globalThis.fetch) {
|
|
48
|
+
const body = JSON.stringify({
|
|
49
|
+
auth: {
|
|
50
|
+
identity: {
|
|
51
|
+
methods: ['token'],
|
|
52
|
+
token: { duration_seconds: durationSeconds },
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
const headers = signHuawei({
|
|
58
|
+
method: 'POST',
|
|
59
|
+
host: IAM_HOST,
|
|
60
|
+
path: IAM_SIGN_PATH,
|
|
61
|
+
contentType: 'application/json;charset=utf8',
|
|
62
|
+
body,
|
|
63
|
+
ak,
|
|
64
|
+
sk,
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
let response
|
|
68
|
+
try {
|
|
69
|
+
response = await fetchImpl(`https://${IAM_HOST}${IAM_REQUEST_PATH}`, {
|
|
70
|
+
method: 'POST',
|
|
71
|
+
headers,
|
|
72
|
+
body,
|
|
73
|
+
})
|
|
74
|
+
} catch (error) {
|
|
75
|
+
throw new StsError(`无法连接华为云 IAM(${IAM_HOST}):${error?.message ?? error}`)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const text = await response.text()
|
|
79
|
+
if (!response.ok) {
|
|
80
|
+
throw new StsError(describeIamFailure(response.status, text))
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let payload
|
|
84
|
+
try {
|
|
85
|
+
payload = JSON.parse(text)
|
|
86
|
+
} catch {
|
|
87
|
+
throw new StsError(`IAM 返回非 JSON:${text.slice(0, 300)}`)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const credential = payload?.credential
|
|
91
|
+
if (!credential?.access || !credential?.secret || !credential?.securitytoken) {
|
|
92
|
+
throw new StsError(`IAM 响应缺少 credential 字段:${text.slice(0, 500)}`)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
ak: credential.access,
|
|
97
|
+
sk: credential.secret,
|
|
98
|
+
securityToken: credential.securitytoken,
|
|
99
|
+
expiresAt: credential.expires_at ?? '',
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Explain the common IAM rejections instead of relaying a raw status. */
|
|
104
|
+
function describeIamFailure(status, text) {
|
|
105
|
+
const raw = text.slice(0, 500)
|
|
106
|
+
if (status === 403 || /forbidden/i.test(text)) {
|
|
107
|
+
return (
|
|
108
|
+
`IAM 拒绝了这次换 STS 请求(HTTP ${status})。常见原因:\n` +
|
|
109
|
+
' · AK/SK 不正确或已被停用 —— 到「我的凭证 → 访问密钥」核对\n' +
|
|
110
|
+
' · 短时间内换得太频繁,触发了频率限制 —— 等约 1 分钟再试\n' +
|
|
111
|
+
`上游原文:${raw}`
|
|
112
|
+
)
|
|
113
|
+
}
|
|
114
|
+
if (status === 401) {
|
|
115
|
+
return `IAM 签名校验失败(HTTP 401)。AK/SK 可能抄错,或不是同一对。上游原文:${raw}`
|
|
116
|
+
}
|
|
117
|
+
return `IAM 换 STS 失败(HTTP ${status})。上游原文:${raw}`
|
|
118
|
+
}
|