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
package/src/models.js ADDED
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Model catalog discovery.
3
+ *
4
+ * The gateway publishes two rosters that have to be merged:
5
+ *
6
+ * 1. `GET /v1/model/builtin` — id, name, context window, output
7
+ * cap, image support, credit ratio
8
+ * 2. `POST /v1/model/thinking-variants` — the thinking levels each model
9
+ * accepts, and its default
10
+ *
11
+ * The merged result feeds three consumers: the adapter's catalog, the
12
+ * settings page's model table, and the diagnostics view. Discovered fresh on
13
+ * each refresh, because the upstream adds models and changes multipliers
14
+ * without notice; the fallback table exists only for the case where the
15
+ * gateway is unreachable on a first start.
16
+ */
17
+
18
+ import { MODELS_PATH, THINKING_VARIANTS_PATH } from './gateway.js'
19
+
20
+ /**
21
+ * How much of a model's output cap is reported to the Host.
22
+ *
23
+ * The gateway advertises 65536 for every model. The Host's compaction
24
+ * reserves `maxTokens` out of the context window and subtracts a headroom
25
+ * allowance on top, so reporting 65536 leaves a 202752-token model with only
26
+ * about 71k of usable conversation — switching to it then fails with
27
+ * `compaction still above threshold`. 32768 is roughly 24k Chinese
28
+ * characters, ample for one reply, and hands the rest back to the context.
29
+ */
30
+ const MAX_OUTPUT_CAP = 32768
31
+
32
+ /**
33
+ * @typedef {object} ModelInfo
34
+ * @property {string} id gateway model id.
35
+ * @property {string} name display name.
36
+ * @property {number} context context window in tokens.
37
+ * @property {number} maxOutput output cap reported to the Host.
38
+ * @property {string} [ratio] credit multiplier text, for display only.
39
+ * @property {boolean} supportsImages whether the model accepts images.
40
+ * @property {string[]} strengths accepted thinking levels; empty when none.
41
+ * @property {string} [defaultStrength] the upstream default level.
42
+ * @property {string} [description] one-line description.
43
+ */
44
+
45
+ /**
46
+ * The fallback roster, used only when the gateway cannot be reached.
47
+ *
48
+ * These are the models observed on a live account; they carry no thinking
49
+ * metadata, so a fallback model offers no level selection at all. A working
50
+ * credential always replaces this table with the live one.
51
+ * @type {ModelInfo[]}
52
+ */
53
+ export const FALLBACK_MODELS = [
54
+ { id: 'deepseek-v4.1-flash', name: 'DeepSeek-V4.1-Flash', context: 1048576, maxOutput: 32768, ratio: '0.18x', supportsImages: true, strengths: [] },
55
+ { id: 'deepseek-v4.1-flash-1017', name: 'DeepSeek-V4.1-Flash-1017', context: 1048576, maxOutput: 32768, ratio: '0.18x', supportsImages: true, strengths: [] },
56
+ { id: 'glm-5.3', name: 'GLM-5.3', context: 1048576, maxOutput: 32768, ratio: '0.79x', supportsImages: false, strengths: [] },
57
+ { id: 'glm-5.3-flash', name: 'GLM-5.3-Flash', context: 1048576, maxOutput: 32768, ratio: '0.08x', supportsImages: true, strengths: [] },
58
+ { id: 'GLM-5.2', name: 'GLM-5.2', context: 202752, maxOutput: 32768, ratio: '0.7x', supportsImages: false, strengths: ['high', 'max'], defaultStrength: 'high' },
59
+ { id: 'glm-5.2-sft-harmony', name: 'GLM-5.2-ArkTS-SPARK', context: 202752, maxOutput: 32768, ratio: '0.7x', supportsImages: false, strengths: ['high', 'max'], defaultStrength: 'high' },
60
+ { id: 'kimi-k3', name: 'Kimi-K3', context: 1048576, maxOutput: 32768, ratio: '2.38x', supportsImages: true, strengths: [] },
61
+ { id: 'kimi-k3.1-pro', name: 'Kimi-K3.1-Pro', context: 1048576, maxOutput: 32768, ratio: '1.63x', supportsImages: true, strengths: [] },
62
+ { id: 'openpangu-2.0-pro', name: 'OpenPangu-2.0-Pro', context: 524288, maxOutput: 32768, ratio: '0.7x', supportsImages: false, strengths: [] },
63
+ { id: 'openpangu-2.0-flash', name: 'OpenPangu-2.0-Flash', context: 524288, maxOutput: 32768, ratio: '0.32x', supportsImages: false, strengths: [] },
64
+ { id: 'speed', name: '智速模式', context: 1048576, maxOutput: 32768, ratio: '0.18x', supportsImages: false, strengths: [] },
65
+ ]
66
+
67
+ /**
68
+ * Clamp an advertised output cap to what the Host should reserve.
69
+ * @param {number|undefined} fromGateway advertised value.
70
+ * @param {number|undefined} fallback value to use when the gateway omits one.
71
+ * @returns {number} the reported cap.
72
+ */
73
+ function clampMaxOutput(fromGateway, fallback) {
74
+ const base = fromGateway && fromGateway > 0 ? fromGateway : (fallback ?? MAX_OUTPUT_CAP)
75
+ return Math.min(base, MAX_OUTPUT_CAP)
76
+ }
77
+
78
+ /**
79
+ * Read and merge the live catalog.
80
+ *
81
+ * The thinking roster is optional: when that call fails the models still
82
+ * load, they simply declare no levels. Failing the whole refresh because a
83
+ * secondary endpoint is down would hide every model.
84
+ *
85
+ * @param {import('./gateway.js').MadaoClient} client an authenticated client.
86
+ * @returns {Promise<{models: ModelInfo[], source: 'gateway'|'fallback', error?: string}>} the catalog.
87
+ */
88
+ export async function discoverModels(client) {
89
+ try {
90
+ const raw = await client.getJson(MODELS_PATH)
91
+ const list = raw?.builtinModels ?? raw?.data?.builtinModels ?? []
92
+ if (!Array.isArray(list) || list.length === 0) {
93
+ return { models: FALLBACK_MODELS, source: 'fallback', error: '网关返回了空模型清单' }
94
+ }
95
+
96
+ let variants = {}
97
+ try {
98
+ const reply = await client.postJson(THINKING_VARIANTS_PATH, {
99
+ model_names: list.map((model) => model.model_id).filter(Boolean),
100
+ })
101
+ variants = reply?.variants ?? reply?.data?.variants ?? {}
102
+ } catch {
103
+ // Thinking levels are an optional capability; their absence must not
104
+ // remove the models.
105
+ }
106
+
107
+ const models = list
108
+ .filter((model) => model?.model_id && model.enable !== false)
109
+ .map((model) => {
110
+ const variant = variants[model.model_id]
111
+ const fallback = FALLBACK_MODELS.find((entry) => entry.id === model.model_id)
112
+ return {
113
+ id: model.model_id,
114
+ name: model.model_name || model.model_id,
115
+ context: model.context_window ?? fallback?.context ?? 0,
116
+ maxOutput: clampMaxOutput(model.max_tokens, fallback?.maxOutput),
117
+ ratio: model.credit?.[0]?.ratio_display,
118
+ supportsImages: model.supports_images === true,
119
+ strengths: Array.isArray(variant?.strengths) ? variant.strengths : [],
120
+ defaultStrength: variant?.default_strength || undefined,
121
+ description: model.model_desc,
122
+ }
123
+ })
124
+
125
+ return { models, source: 'gateway' }
126
+ } catch (error) {
127
+ return {
128
+ models: FALLBACK_MODELS,
129
+ source: 'fallback',
130
+ error: error?.message ?? String(error),
131
+ }
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Merge discovered metadata over the fallback table.
137
+ *
138
+ * Used when a refresh fails after a successful one: the previous live
139
+ * catalog stays in service rather than being replaced by the stale static
140
+ * table.
141
+ * @param {ModelInfo[]} previous the catalog currently in use.
142
+ * @param {ModelInfo[]} discovered the newest discovery result.
143
+ * @returns {ModelInfo[]} the catalog to keep.
144
+ */
145
+ export function preferLive(previous, discovered) {
146
+ return discovered.length > 0 ? discovered : previous
147
+ }
package/src/paths.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Paths and environment names this plugin reads and writes.
3
+ *
4
+ * Extracted so the account store and the credential resolver can both use them
5
+ * without importing each other: the resolver needs the store to find the active
6
+ * account, and the store needs these paths to find its file. Keeping the
7
+ * constants here makes that a one-way dependency instead of a cycle.
8
+ */
9
+
10
+ import { homedir } from 'node:os'
11
+ import { join } from 'node:path'
12
+
13
+ /** Configuration directory for this plugin. */
14
+ export const CONFIG_DIR = join(
15
+ process.env.APPDATA || join(homedir(), '.config'),
16
+ 'dsh-connect-codearts',
17
+ )
18
+
19
+ /** Where the settings page writes the account store. */
20
+ export const CREDENTIAL_PATH = join(CONFIG_DIR, 'credentials.json')
21
+
22
+ /**
23
+ * Where builds before the account store wrote a single pair; read for migration.
24
+ *
25
+ * Overridable so a test can run against a scratch home: the store consults this
26
+ * file whenever the configured one is absent, and without an override a test
27
+ * would silently read the developer's real credential.
28
+ */
29
+ export const LEGACY_CREDENTIAL_PATH =
30
+ process.env.DSH_CONNECT_CODEARTS_LEGACY_CREDENTIAL ||
31
+ join(homedir(), '.dsh-connect-codearts', 'credentials.json')
32
+
33
+ /** Environment variable names, checked first. */
34
+ export const ENV_AK = 'CODEARTS_AK'
35
+ export const ENV_SK = 'CODEARTS_SK'
36
+ export const ENV_TOKEN = 'CODEARTS_SECURITY_TOKEN'
@@ -0,0 +1,90 @@
1
+ /** Validated, atomic, serialized preferences shared by settings and migration. */
2
+ import { readFileSync } from 'node:fs'
3
+ import { mkdir, writeFile, rename } from 'node:fs/promises'
4
+ import { join } from 'node:path'
5
+ import { randomUUID } from 'node:crypto'
6
+ import { CONFIG_DIR } from './paths.js'
7
+
8
+ export class InputError extends Error {}
9
+ export const FEATURE_DEFAULTS = Object.freeze({ lowBalanceEnabled: true, lowBalanceThreshold: 500, usageEnabled: true, modelPresets: [] })
10
+ const plain = (value) => value !== null && typeof value === 'object' && !Array.isArray(value)
11
+ const fail = (message) => { throw new InputError(message) }
12
+ const safeId = (id) => typeof id === 'string' && id.length > 0 && id.length <= 200 && !['__proto__', 'constructor', 'prototype'].includes(id)
13
+ export function validateSelection(value) {
14
+ if (!plain(value)) fail('模型配置格式不正确')
15
+ const ids = value.enabledModelIds
16
+ if (ids !== null && (!Array.isArray(ids) || ids.length > 500 || !ids.every(safeId) || !ids.length)) fail('至少启用一个模型;全部启用请使用 null')
17
+ if (!plain(value.modelOverrides) || Object.keys(value.modelOverrides).length > 500) fail('模型覆盖配置格式不正确')
18
+ const modelOverrides = {}
19
+ for (const [id, patch] of Object.entries(value.modelOverrides)) {
20
+ if (!safeId(id) || !plain(patch)) fail('模型覆盖配置格式不正确')
21
+ const entry = {}
22
+ for (const key of ['images', 'allowOff']) {
23
+ if (key in patch) {
24
+ if (typeof patch[key] !== 'boolean') fail('模型开关必须为布尔值')
25
+ entry[key] = patch[key]
26
+ }
27
+ }
28
+ if ('defaultStrength' in patch) {
29
+ if (typeof patch.defaultStrength !== 'string' || (!patch.defaultStrength.trim() || patch.defaultStrength.length > 64)) fail('推理强度不正确')
30
+ entry.defaultStrength = patch.defaultStrength
31
+ }
32
+ if (Object.keys(entry).length) modelOverrides[id] = entry
33
+ }
34
+ return { enabledModelIds: ids === null ? null : [...new Set(ids)], modelOverrides }
35
+ }
36
+ export function validatePreferences(input) {
37
+ if (!plain(input)) fail('偏好设置格式不正确')
38
+ const out = {}
39
+ for (const key of ['autoCheckin', 'composerChip', 'lowBalanceEnabled', 'usageEnabled']) {
40
+ if (key in input) {
41
+ if (typeof input[key] !== 'boolean') fail(`${key} 必须为布尔值`)
42
+ out[key] = input[key]
43
+ }
44
+ }
45
+ if ('lowBalanceThreshold' in input) {
46
+ if (!Number.isFinite(input.lowBalanceThreshold) || input.lowBalanceThreshold < 0 || input.lowBalanceThreshold > 1e9) fail('余额阈值必须在 0 到 10 亿之间')
47
+ out.lowBalanceThreshold = input.lowBalanceThreshold
48
+ }
49
+ if ('refreshIntervalMs' in input) {
50
+ if (!Number.isInteger(input.refreshIntervalMs) || input.refreshIntervalMs < 60000 || input.refreshIntervalMs > 86400000) fail('刷新间隔必须在 1 分钟到 24 小时之间')
51
+ out.refreshIntervalMs = input.refreshIntervalMs
52
+ }
53
+ if ('enabledModelIds' in input || 'modelOverrides' in input) Object.assign(out, validateSelection({ enabledModelIds: input.enabledModelIds ?? null, modelOverrides: input.modelOverrides ?? {} }))
54
+ if ('modelPresets' in input) {
55
+ if (!Array.isArray(input.modelPresets) || input.modelPresets.length > 20) fail('最多保存 20 套模型预设')
56
+ const ids = new Set()
57
+ out.modelPresets = input.modelPresets.map((preset) => {
58
+ if (!plain(preset) || !safeId(preset.id) || preset.id.startsWith('builtin:') || ids.has(preset.id) || typeof preset.name !== 'string' || !preset.name.trim() || preset.name.trim().length > 48) fail('模型预设格式不正确或名称重复')
59
+ ids.add(preset.id)
60
+ return { id: preset.id, name: preset.name.trim(), ...validateSelection(preset) }
61
+ })
62
+ }
63
+ return out
64
+ }
65
+ export const PREFERENCES_PATH = join(CONFIG_DIR, 'preferences.json')
66
+ export function readPreferences() {
67
+ try { const value = JSON.parse(readFileSync(PREFERENCES_PATH, 'utf8')); return plain(value) ? value : {} } catch { return {} }
68
+ }
69
+ let pending = Promise.resolve()
70
+ export function persistPreferences(patch) {
71
+ const write = pending.then(async () => {
72
+ await mkdir(CONFIG_DIR, { recursive: true })
73
+ const path = `${PREFERENCES_PATH}.${randomUUID()}.tmp`
74
+ const next = { ...readPreferences(), ...patch }
75
+ await writeFile(path, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 })
76
+ await rename(path, PREFERENCES_PATH)
77
+ return next
78
+ })
79
+ pending = write.catch(() => {})
80
+ return write
81
+ }
82
+ export function portablePreferences(settings) {
83
+ return validatePreferences({
84
+ autoCheckin: settings.autoCheckin === true, composerChip: settings.composerChip !== false,
85
+ lowBalanceEnabled: settings.lowBalanceEnabled !== false, lowBalanceThreshold: settings.lowBalanceThreshold ?? 500,
86
+ usageEnabled: settings.usageEnabled !== false, modelPresets: settings.modelPresets ?? [],
87
+ enabledModelIds: settings.enabledModelIds ?? null, modelOverrides: settings.modelOverrides ?? {},
88
+ refreshIntervalMs: Math.max(60000, Math.min(86400000, Number(settings.refreshIntervalMs) || 300000)),
89
+ })
90
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * The 码道 transport envelope: P-256 key agreement plus SM4-GCM payloads.
3
+ *
4
+ * Every parameter here was established by observing the real gateway, and
5
+ * three of them contradict what the public SDK shape suggests:
6
+ *
7
+ * curve: prime256v1 (P-256) — NOT X25519
8
+ * KDF: sessionKey = SHA256(sharedSecret)[0:16] — a bare truncation,
9
+ * NOT HKDF
10
+ * AAD (req): `${METHOD}|${pathname}|${timestamp}`
11
+ * AAD (resp): `${keyId}|${chunkIndex}` — independent of the request's
12
+ * method/path/timestamp, which is what makes streaming work
13
+ *
14
+ * The request body is sent as Base64 TEXT, not raw bytes.
15
+ */
16
+
17
+ import { createECDH, createHash, randomBytes, randomUUID } from 'node:crypto'
18
+ import { sm4GcmDecrypt, sm4GcmEncrypt } from './sm4.js'
19
+
20
+ /** The agreed curve. */
21
+ export const CURVE = 'prime256v1'
22
+ /** Session key length in bytes (SM4-128). */
23
+ export const KEY_BYTES = 16
24
+ /** GCM IV length in bytes. */
25
+ export const IV_BYTES = 12
26
+ /** GCM tag length in bytes. */
27
+ export const TAG_BYTES = 16
28
+
29
+ /**
30
+ * @typedef {object} SessionKey
31
+ * @property {string} keyId gateway-issued key identifier, echoed in AAD.
32
+ * @property {Buffer} key the 16-byte SM4 key.
33
+ * @property {number} expiresAt epoch ms when the gateway's key expires.
34
+ */
35
+
36
+ /** A fresh 12-byte GCM IV. */
37
+ export function randomIv() {
38
+ return randomBytes(IV_BYTES)
39
+ }
40
+
41
+ /**
42
+ * Derive the SM4 session key from the ECDH shared secret.
43
+ *
44
+ * The gateway uses a bare SHA-256 truncated to 16 bytes. Using HKDF here
45
+ * produces a key that decrypts to garbage, which surfaces as an
46
+ * authentication failure on the first response chunk.
47
+ *
48
+ * @param {Buffer} sharedSecret the ECDH secret.
49
+ * @returns {Buffer} the 16-byte key.
50
+ */
51
+ export function deriveSessionKey(sharedSecret) {
52
+ return createHash('sha256').update(sharedSecret).digest().subarray(0, KEY_BYTES)
53
+ }
54
+
55
+ /**
56
+ * Generate the client half of the key agreement.
57
+ * @returns {{ecdh: import('node:crypto').ECDH, publicKeyB64: string}} pair.
58
+ */
59
+ export function createEcdhPair() {
60
+ const ecdh = createECDH(CURVE)
61
+ const publicKey = ecdh.generateKeys()
62
+ return { ecdh, publicKeyB64: publicKey.toString('base64') }
63
+ }
64
+
65
+ /**
66
+ * Complete the agreement against the gateway's public key.
67
+ * @param {Buffer} sharedSecret result of `ecdh.computeSecret()`.
68
+ * @returns {Buffer} the SM4 key.
69
+ */
70
+ export function completeKeyExchange(sharedSecret) {
71
+ return deriveSessionKey(sharedSecret)
72
+ }
73
+
74
+ /** The request AAD: method, path, and timestamp joined by `|`. */
75
+ export function requestAad(method, pathname, timestamp) {
76
+ return Buffer.from(`${method.toUpperCase()}|${pathname}|${timestamp}`, 'utf8')
77
+ }
78
+
79
+ /** The response AAD for one stream chunk: key id and chunk index joined by `|`. */
80
+ export function chunkAad(keyId, index) {
81
+ return Buffer.from(`${keyId}|${index}`, 'utf8')
82
+ }
83
+
84
+ /**
85
+ * @typedef {object} RequestEnvelope
86
+ * @property {string} body Base64 ciphertext — the raw request body.
87
+ * @property {Record<string, string>} headers the `X-Encrypt-*` header set.
88
+ */
89
+
90
+ /**
91
+ * Seal a chat request body into its wire envelope.
92
+ *
93
+ * The ciphertext travels as Base64 TEXT in the body; the IV, tag, key id, and
94
+ * timestamp travel in headers. Every one of those headers must be sent —
95
+ * the gateway rejects a request that carries an unlabelled body.
96
+ *
97
+ * @param {object} options seal options.
98
+ * @param {Buffer} options.key 16-byte session key.
99
+ * @param {string} options.keyId key identifier for the header.
100
+ * @param {string} options.method HTTP method (part of the AAD).
101
+ * @param {string} options.pathname request path (part of the AAD).
102
+ * @param {string|number} options.timestamp request timestamp (part of the AAD).
103
+ * @param {string} options.plaintext the JSON body.
104
+ * @returns {RequestEnvelope} the body and headers to send.
105
+ */
106
+ export function deriveRequestEnvelope({ key, keyId, method, pathname, timestamp, plaintext }) {
107
+ const iv = randomIv()
108
+ const aad = requestAad(method, pathname, timestamp)
109
+ const { ciphertext, tag } = sm4GcmEncrypt(key, iv, Buffer.from(plaintext, 'utf8'), aad)
110
+ return {
111
+ body: Buffer.from(ciphertext).toString('base64'),
112
+ headers: {
113
+ 'Content-Type': 'application/octet-stream',
114
+ 'X-Encrypt-Algo': 'sm4-gcm',
115
+ 'X-Encrypt-Key-Id': keyId,
116
+ 'X-Encrypt-Iv': iv.toString('base64'),
117
+ 'X-Encrypt-Tag': Buffer.from(tag).toString('base64'),
118
+ 'X-Encrypt-Ts': String(timestamp),
119
+ },
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Open one response stream chunk.
125
+ *
126
+ * A sealed frame is an `iv:tag:ciphertext` triple of Base64 fields. The AAD
127
+ * for every chunk is `${keyId}|${chunkIndex}` — independent of the request's
128
+ * method, path, and timestamp, which is what makes chunk-wise decryption
129
+ * possible.
130
+ *
131
+ * @param {string} block the raw frame text.
132
+ * @param {Buffer} key the session key.
133
+ * @param {string} keyId key identifier (part of the AAD).
134
+ * @param {number} index chunk index (part of the AAD).
135
+ * @returns {string|null} the decrypted text, or null for a frame that is not sealed.
136
+ * @throws when the frame claims to be sealed and its tag does not verify.
137
+ */
138
+ export function openChunk(block, key, keyId, index) {
139
+ const trimmed = (block ?? '').trim()
140
+ if (trimmed === '') return null
141
+ const parts = trimmed.split(':')
142
+ if (parts.length !== 3) return null
143
+ const [ivPart, tagPart, ciphertextPart] = parts
144
+ const plaintext = sm4GcmDecrypt(
145
+ key,
146
+ Buffer.from(ivPart, 'base64'),
147
+ Buffer.from(ciphertextPart, 'base64'),
148
+ Buffer.from(tagPart, 'base64'),
149
+ chunkAad(keyId, index),
150
+ )
151
+ return Buffer.from(plaintext).toString('utf8')
152
+ }
153
+
154
+ /**
155
+ * A UUID stamped on each request as its message identity.
156
+ * @returns {string} a v4 UUID.
157
+ */
158
+ export function newRequestId() {
159
+ return randomUUID()
160
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Huawei Cloud APIG request signing (`SDK-HMAC-SHA256`).
3
+ *
4
+ * Used for both the 码道 gateway and the IAM STS exchange. The canonical
5
+ * request is:
6
+ *
7
+ * CanonicalRequest =
8
+ * METHOD \n
9
+ * CanonicalURI \n <- path WITH a trailing slash (the request itself sends none)
10
+ * CanonicalQueryString \n
11
+ * CanonicalHeaders \n <- "lowercase-name:value\n", sorted, only headers actually sent
12
+ * SignedHeaders \n
13
+ * HexEncode(SHA256(body)) <- the REAL body hash, not UNSIGNED-PAYLOAD
14
+ *
15
+ * StringToSign =
16
+ * "SDK-HMAC-SHA256" \n
17
+ * X-Sdk-Date \n
18
+ * HexEncode(SHA256(CanonicalRequest))
19
+ *
20
+ * Signature = HexEncode(HMAC-SHA256(SK, StringToSign))
21
+ *
22
+ * The four rules below cost real debugging time; each one is a 401 when
23
+ * violated, and the response body never says which:
24
+ *
25
+ * 1. SIGN the path with a trailing slash; SEND it without one.
26
+ * 2. Hash the real body — never the `UNSIGNED-PAYLOAD` literal.
27
+ * 3. SignedHeaders must match the headers actually sent, exactly.
28
+ * 4. Never sign `x-sdk-content-sha256`; an extra signed name is a 401.
29
+ */
30
+
31
+ import { createHash, createHmac } from 'node:crypto'
32
+
33
+ /** The signing algorithm identifier sent on the wire. */
34
+ export const SIGN_ALGORITHM = 'SDK-HMAC-SHA256'
35
+
36
+ /**
37
+ * Format the `X-Sdk-Date` header value (`YYYYMMDDTHHMMSSZ`, UTC).
38
+ * @param {Date} [date] instant to format; defaults to now.
39
+ * @returns {string} the header value.
40
+ */
41
+ export function formatSdkDate(date = new Date()) {
42
+ const p = (n) => String(n).padStart(2, '0')
43
+ return (
44
+ `${date.getUTCFullYear()}${p(date.getUTCMonth() + 1)}${p(date.getUTCDate())}T` +
45
+ `${p(date.getUTCHours())}${p(date.getUTCMinutes())}${p(date.getUTCSeconds())}Z`
46
+ )
47
+ }
48
+
49
+ /**
50
+ * Build the canonical URI: percent-encode each segment and add a trailing slash.
51
+ * @param {string} pathname request path without a query.
52
+ * @returns {string} the canonical form.
53
+ */
54
+ export function canonicalUri(pathname) {
55
+ const encoded = pathname.split('/').map((segment) => encodeURIComponent(segment)).join('/')
56
+ return encoded.endsWith('/') ? encoded : `${encoded}/`
57
+ }
58
+
59
+ /** Sort and join the headers into the canonical block plus the signed-name list. */
60
+ function canonicalHeaders(headers) {
61
+ const lower = new Map()
62
+ for (const [name, value] of Object.entries(headers)) lower.set(name.toLowerCase(), String(value))
63
+
64
+ const names = [...lower.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
65
+ const block = names.map((name) => `${name}:${(lower.get(name) ?? '').replace(/[\r\n]/g, ' ').trim()}\n`).join('')
66
+ return { block, signed: names.join(';') }
67
+ }
68
+
69
+ /** The `Host` header value: include the port only when it is not the protocol default. */
70
+ function hostHeader(url) {
71
+ const defaultPort = url.protocol === 'https:' ? '443' : url.protocol === 'http:' ? '80' : ''
72
+ return url.port && url.port !== defaultPort ? `${url.hostname}:${url.port}` : url.hostname
73
+ }
74
+
75
+ /**
76
+ * Produce the signed headers. Send exactly these on the request: adding or
77
+ * dropping any of them invalidates the signature.
78
+ *
79
+ * @param {object} input signature input.
80
+ * @param {string} input.method HTTP method.
81
+ * @param {URL} input.url request URL.
82
+ * @param {string|null} input.contentType `Content-Type` to sign, or `null` when the request sends none.
83
+ * @param {string} [input.body] request body text; ignored when `bodyBytes` is given.
84
+ * @param {Uint8Array} [input.bodyBytes] binary body (already-encrypted payloads); takes precedence over `body`.
85
+ * @param {{ak: string, sk: string, securityToken: string}} input.credentials temporary or permanent key triple.
86
+ * @param {string} [input.sdkDate] fixed timestamp, for tests.
87
+ * @returns {Record<string, string>} headers to send verbatim.
88
+ */
89
+ export function signRequest(input) {
90
+ const { method, url, contentType, credentials } = input
91
+ const sdkDate = input.sdkDate ?? formatSdkDate()
92
+ const payloadHash = input.bodyBytes
93
+ ? createHash('sha256').update(input.bodyBytes).digest('hex')
94
+ : createHash('sha256').update(input.body ?? '').digest('hex')
95
+
96
+ const headersToSign = {
97
+ Host: hostHeader(url),
98
+ 'X-Sdk-Date': sdkDate,
99
+ 'X-Security-Token': credentials.securityToken,
100
+ }
101
+ if (contentType) headersToSign['Content-Type'] = contentType
102
+
103
+ const { block, signed } = canonicalHeaders(headersToSign)
104
+ const canonicalRequest = [
105
+ method.toUpperCase(),
106
+ canonicalUri(url.pathname),
107
+ url.search ? url.search.slice(1) : '',
108
+ block,
109
+ signed,
110
+ payloadHash,
111
+ ].join('\n')
112
+
113
+ const stringToSign = [
114
+ SIGN_ALGORITHM,
115
+ sdkDate,
116
+ createHash('sha256').update(canonicalRequest).digest('hex'),
117
+ ].join('\n')
118
+
119
+ const signature = createHmac('sha256', credentials.sk).update(stringToSign).digest('hex')
120
+
121
+ return {
122
+ ...headersToSign,
123
+ Authorization: `${SIGN_ALGORITHM} Access=${credentials.ak}, SignedHeaders=${signed}, Signature=${signature}`,
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Sign a request for Huawei Cloud IAM (the STS exchange).
129
+ *
130
+ * Same algorithm, different header set: IAM takes no `X-Security-Token`
131
+ * because the caller is proving ownership of a permanent AK/SK pair.
132
+ *
133
+ * @param {object} input signature input.
134
+ * @param {string} input.method HTTP method.
135
+ * @param {string} input.host request host.
136
+ * @param {string} input.path canonical (trailing-slash) path.
137
+ * @param {string} input.contentType request content type.
138
+ * @param {string} input.body request body text.
139
+ * @param {string} input.ak permanent access key id.
140
+ * @param {string} input.sk permanent secret access key.
141
+ * @param {string} [input.sdkDate] fixed timestamp, for tests.
142
+ * @returns {Record<string, string>} headers to send verbatim.
143
+ */
144
+ export function signHuawei(input) {
145
+ const sdkDate = input.sdkDate ?? formatSdkDate()
146
+ const payloadHash = createHash('sha256').update(input.body).digest('hex')
147
+
148
+ const headersToSign = {
149
+ Host: input.host,
150
+ 'X-Sdk-Date': sdkDate,
151
+ 'Content-Type': input.contentType,
152
+ }
153
+
154
+ const { block, signed } = canonicalHeaders(headersToSign)
155
+ const canonicalRequest = [
156
+ input.method.toUpperCase(),
157
+ input.path,
158
+ '',
159
+ block,
160
+ signed,
161
+ payloadHash,
162
+ ].join('\n')
163
+
164
+ const stringToSign = [
165
+ SIGN_ALGORITHM,
166
+ sdkDate,
167
+ createHash('sha256').update(canonicalRequest).digest('hex'),
168
+ ].join('\n')
169
+
170
+ const signature = createHmac('sha256', input.sk).update(stringToSign).digest('hex')
171
+
172
+ return {
173
+ ...headersToSign,
174
+ Authorization: `${SIGN_ALGORITHM} Access=${input.ak}, SignedHeaders=${signed}, Signature=${signature}`,
175
+ }
176
+ }