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,481 @@
1
+ /**
2
+ * The account store: many credential pairs, one of them active.
3
+ *
4
+ * A 码道 user commonly has more than one Huawei Cloud account — a personal one
5
+ * and a work one, or several teammates' keys for a shared machine. Holding
6
+ * exactly one pair forced a delete-and-retype whenever they switched, which is
7
+ * also how a key gets lost.
8
+ *
9
+ * The file is one JSON document:
10
+ *
11
+ * { "version": 2,
12
+ * "activeId": "…",
13
+ * "accounts": [ { "id": "…", "ak": "…", "sk": "…", "label": "…" } ] }
14
+ *
15
+ * A v1 file (a bare `{ak, sk}`) is migrated into a single-account document on
16
+ * first read, so an existing install keeps working without the user noticing.
17
+ *
18
+ * SECURITY: this file holds permanent keys in plain text, exactly as the v1
19
+ * layout did. It is written mode 0600 inside the user's config directory, and
20
+ * the settings page never returns a full key to the browser — only a mask.
21
+ */
22
+
23
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
24
+ import { readFileSync, existsSync, statSync } from 'node:fs'
25
+ import { createHash, randomUUID } from 'node:crypto'
26
+ import { CONFIG_DIR, CREDENTIAL_PATH, LEGACY_CREDENTIAL_PATH } from './paths.js'
27
+
28
+ /** Current on-disk schema version. */
29
+ export const STORE_VERSION = 2
30
+
31
+ /**
32
+ * @typedef {object} Account
33
+ * @property {string} id stable local id, derived from the AK.
34
+ * @property {string} ak access key id.
35
+ * @property {string} sk secret access key.
36
+ * @property {string} [label] user-supplied name, else derived from the AK.
37
+ * @property {string} [accountName] the Huawei account name, once resolved.
38
+ * @property {number} [addedAt] epoch ms.
39
+ */
40
+
41
+ /**
42
+ * @typedef {object} StoreDocument
43
+ * @property {number} version
44
+ * @property {string|null} activeId
45
+ * @property {Account[]} accounts
46
+ */
47
+
48
+ /**
49
+ * A stable id for an account, so re-importing the same key updates that entry
50
+ * rather than stacking a duplicate. Derived from the AK only: the secret may be
51
+ * rotated in place and the account is still the same account.
52
+ * @param {string} ak access key id.
53
+ * @returns {string} the id.
54
+ */
55
+ export function accountIdOf(ak) {
56
+ return createHash('sha256').update(String(ak).trim()).digest('hex').slice(0, 16)
57
+ }
58
+
59
+ /** A short display label when the user has not named the account. */
60
+ export function defaultLabel(ak) {
61
+ const text = String(ak ?? '')
62
+ return text.length > 8 ? `${text.slice(0, 4)}…${text.slice(-4)}` : text
63
+ }
64
+
65
+ /** Mask a key for display: enough to recognise, not enough to reuse. */
66
+ export function maskKey(value) {
67
+ if (!value) return ''
68
+ const text = String(value)
69
+ if (text.length <= 8) return `${text.slice(0, 2)}****`
70
+ return `${text.slice(0, 4)}…${text.slice(-4)}`
71
+ }
72
+
73
+ /** An empty document. */
74
+ export function emptyStore() {
75
+ return { version: STORE_VERSION, activeId: null, accounts: [] }
76
+ }
77
+
78
+ /**
79
+ * Normalise anything read from disk into a v2 document.
80
+ *
81
+ * Accepts a v2 document, a v1 `{ak, sk}` pair, or an array of pairs, so
82
+ * hand-written files and older layouts both load.
83
+ *
84
+ * @param {unknown} parsed whatever JSON.parse produced.
85
+ * @returns {StoreDocument} a valid document.
86
+ */
87
+ export function normaliseStore(parsed) {
88
+ if (parsed === null || typeof parsed !== 'object') return emptyStore()
89
+
90
+ if (Array.isArray(parsed)) {
91
+ const accounts = parsed.map(accountFrom).filter(Boolean)
92
+ return { version: STORE_VERSION, activeId: accounts[0]?.id ?? null, accounts }
93
+ }
94
+
95
+ const record = parsed
96
+ if (Array.isArray(record.accounts)) {
97
+ const accounts = record.accounts.map(accountFrom).filter(Boolean)
98
+ const activeId =
99
+ typeof record.activeId === 'string' && accounts.some((a) => a.id === record.activeId)
100
+ ? record.activeId
101
+ : (accounts[0]?.id ?? null)
102
+ return { version: STORE_VERSION, activeId, accounts }
103
+ }
104
+
105
+ // v1: a bare pair. Promote it.
106
+ const single = accountFrom(record)
107
+ return single
108
+ ? { version: STORE_VERSION, activeId: single.id, accounts: [single] }
109
+ : emptyStore()
110
+ }
111
+
112
+ /**
113
+ * Turn one raw entry into an account, tolerating the field spellings a user may
114
+ * paste from the Huawei console or a CSV export.
115
+ * @returns {Account|null} the account, or null when it carries no usable pair.
116
+ */
117
+ function accountFrom(raw) {
118
+ if (raw === null || typeof raw !== 'object') return null
119
+ const ak = raw.ak ?? raw.accessKeyId ?? raw.access_key_id ?? raw['Access Key Id']
120
+ const sk = raw.sk ?? raw.secretAccessKey ?? raw.secret_access_key ?? raw['Secret Access Key']
121
+ if (!ak || !sk) return null
122
+ const trimmedAk = String(ak).trim()
123
+ const trimmedSk = String(sk).trim()
124
+ if (trimmedAk === '' || trimmedSk === '') return null
125
+ const label = typeof raw.label === 'string' && raw.label.trim() !== '' ? raw.label.trim() : undefined
126
+ const accountName =
127
+ typeof raw.accountName === 'string' && raw.accountName.trim() !== ''
128
+ ? raw.accountName.trim()
129
+ : typeof raw.account === 'string' && raw.account.trim() !== ''
130
+ ? raw.account.trim()
131
+ : undefined
132
+ return {
133
+ id: accountIdOf(trimmedAk),
134
+ ak: trimmedAk,
135
+ sk: trimmedSk,
136
+ ...(label ? { label } : {}),
137
+ ...(accountName ? { accountName } : {}),
138
+ ...(typeof raw.addedAt === 'number' ? { addedAt: raw.addedAt } : {}),
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Read the store, migrating a v1 file when that is what is there.
144
+ *
145
+ * Remembers which file answered, because reporting the configured path while
146
+ * silently reading the legacy one makes every path-based diagnosis wrong.
147
+ * @returns {StoreDocument} the document.
148
+ */
149
+ export function readStore() {
150
+ const located = locateStore()
151
+ return located.store
152
+ }
153
+
154
+ /**
155
+ * Find and parse the store file, reporting where it came from.
156
+ * @returns {{store: StoreDocument, path: string|null}} the document and its source file.
157
+ */
158
+ export function locateStore() {
159
+ for (const path of [CREDENTIAL_PATH, LEGACY_CREDENTIAL_PATH]) {
160
+ if (!existsSync(path)) continue
161
+ try {
162
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
163
+ return { store: normaliseStore(parsed), path }
164
+ } catch {
165
+ // A corrupt file is reported by the settings page rather than thrown at
166
+ // load time; another source may still work.
167
+ }
168
+ }
169
+ return { store: emptyStore(), path: null }
170
+ }
171
+
172
+ /** Write the store atomically, with owner-only permissions. */
173
+ async function writeStore(document) {
174
+ await mkdir(CONFIG_DIR, { recursive: true })
175
+ const body = `${JSON.stringify(document, null, 2)}\n`
176
+ const temp = `${CREDENTIAL_PATH}.tmp`
177
+ await writeFile(temp, body, { encoding: 'utf8', mode: 0o600 })
178
+ await rename(temp, CREDENTIAL_PATH)
179
+ try {
180
+ // rename preserves the temp file's mode, but be explicit: an existing file
181
+ // with looser permissions would otherwise keep them.
182
+ const mode = statSync(CREDENTIAL_PATH).mode & 0o777
183
+ if (mode !== 0o600) await writeFile(CREDENTIAL_PATH, body, { encoding: 'utf8', mode: 0o600 })
184
+ } catch {
185
+ // Permission tightening is best-effort.
186
+ }
187
+ return document
188
+ }
189
+
190
+ // Account checks and imports can overlap; serialize the complete read-modify-write.
191
+ let accountMutation = Promise.resolve()
192
+ function mutateAccounts(operation) {
193
+ const result = accountMutation.then(operation)
194
+ accountMutation = result.catch(() => {})
195
+ return result
196
+ }
197
+ export const addAccount = (...args) => mutateAccounts(() => addAccountUnlocked(...args))
198
+ export const addAccounts = (...args) => mutateAccounts(() => addAccountsUnlocked(...args))
199
+ export const removeAccount = (...args) => mutateAccounts(() => removeAccountUnlocked(...args))
200
+ export const setActiveAccount = (...args) => mutateAccounts(() => setActiveAccountUnlocked(...args))
201
+ export const renameAccount = (...args) => mutateAccounts(() => renameAccountUnlocked(...args))
202
+ export const rememberAccountName = (...args) => mutateAccounts(() => rememberAccountNameUnlocked(...args))
203
+
204
+ /**
205
+ * Add one account, or update it when the AK is already present.
206
+ * @param {object} input the pair plus optional label.
207
+ * @param {string} input.ak access key id.
208
+ * @param {string} input.sk secret access key.
209
+ * @param {string} [input.label] display name.
210
+ * @returns {Promise<{account: Account, added: boolean, store: StoreDocument}>} the outcome.
211
+ */
212
+ async function addAccountUnlocked({ ak, sk, label }) {
213
+ const candidate = accountFrom({ ak, sk, label, addedAt: Date.now() })
214
+ if (!candidate) throw new Error('Access Key ID 和 Secret Access Key 都要填。')
215
+
216
+ const store = readStore()
217
+ const existing = store.accounts.findIndex((account) => account.id === candidate.id)
218
+ const added = existing < 0
219
+ if (added) {
220
+ store.accounts.push(candidate)
221
+ } else {
222
+ // Same AK: refresh the secret and let an explicit new label win.
223
+ store.accounts[existing] = {
224
+ ...store.accounts[existing],
225
+ sk: candidate.sk,
226
+ ...(candidate.label ? { label: candidate.label } : {}),
227
+ }
228
+ }
229
+ // The first account added becomes active; adding more never steals focus.
230
+ store.activeId ??= candidate.id
231
+ await writeStore(store)
232
+ return { account: store.accounts[added ? store.accounts.length - 1 : existing], added, store }
233
+ }
234
+
235
+ /**
236
+ * Add several accounts at once, as an import does.
237
+ *
238
+ * @param {Array<object>} entries raw pairs, in the order supplied.
239
+ * @returns {Promise<{added: number, updated: number, skipped: number, store: StoreDocument}>} the outcome.
240
+ */
241
+ async function addAccountsUnlocked(entries) {
242
+ const store = readStore()
243
+ let added = 0
244
+ let updated = 0
245
+ let skipped = 0
246
+
247
+ for (const entry of entries ?? []) {
248
+ const candidate = accountFrom({ ...entry, addedAt: Date.now() })
249
+ if (!candidate) {
250
+ skipped += 1
251
+ continue
252
+ }
253
+ const existing = store.accounts.findIndex((account) => account.id === candidate.id)
254
+ if (existing < 0) {
255
+ store.accounts.push(candidate)
256
+ added += 1
257
+ } else {
258
+ store.accounts[existing] = {
259
+ ...store.accounts[existing],
260
+ sk: candidate.sk,
261
+ ...(candidate.label ? { label: candidate.label } : {}),
262
+ }
263
+ updated += 1
264
+ }
265
+ }
266
+
267
+ store.activeId ??= store.accounts[0]?.id ?? null
268
+ if (added > 0 || updated > 0) await writeStore(store)
269
+ return { added, updated, skipped, store }
270
+ }
271
+
272
+ /**
273
+ * Remove one account.
274
+ * @param {string} id account id.
275
+ * @returns {Promise<StoreDocument>} the store after removal.
276
+ */
277
+ async function removeAccountUnlocked(id) {
278
+ const store = readStore()
279
+ store.accounts = store.accounts.filter((account) => account.id !== id)
280
+ // Removing the active account promotes whatever is left, so the plugin never
281
+ // points at an id that no longer exists.
282
+ if (store.activeId !== null && !store.accounts.some((account) => account.id === store.activeId)) {
283
+ store.activeId = store.accounts[0]?.id ?? null
284
+ }
285
+ await writeStore(store)
286
+ return store
287
+ }
288
+
289
+ /**
290
+ * Choose which account requests use.
291
+ * @param {string} id account id.
292
+ * @returns {Promise<StoreDocument>} the updated store.
293
+ */
294
+ async function setActiveAccountUnlocked(id) {
295
+ const store = readStore()
296
+ if (!store.accounts.some((account) => account.id === id)) {
297
+ throw new Error(`没有这个账号:${id}`)
298
+ }
299
+ store.activeId = id
300
+ await writeStore(store)
301
+ return store
302
+ }
303
+
304
+ /**
305
+ * Give an account a display name.
306
+ * @param {string} id account id.
307
+ * @param {string} label the new name; an empty string clears it.
308
+ * @returns {Promise<StoreDocument>} the updated store.
309
+ */
310
+ async function renameAccountUnlocked(id, label) {
311
+ const store = readStore()
312
+ const account = store.accounts.find((entry) => entry.id === id)
313
+ if (!account) throw new Error(`没有这个账号:${id}`)
314
+ const trimmed = String(label ?? '').trim()
315
+ if (trimmed === '') delete account.label
316
+ else account.label = trimmed
317
+ await writeStore(store)
318
+ return store
319
+ }
320
+
321
+ /**
322
+ * Record the Huawei account name once the gateway reveals it, so the pool can
323
+ * show `hw045…` instead of a masked AK.
324
+ * @param {string} id account id.
325
+ * @param {string} accountName the name from the STS token.
326
+ * @returns {Promise<void>} resolves when written.
327
+ */
328
+ async function rememberAccountNameUnlocked(id, accountName) {
329
+ if (!accountName) return
330
+ const store = readStore()
331
+ const account = store.accounts.find((entry) => entry.id === id)
332
+ if (!account || account.accountName === accountName) return
333
+ account.accountName = accountName
334
+ await writeStore(store)
335
+ }
336
+
337
+ /** The active account, or null when none is configured. */
338
+ export function activeAccount(store = readStore()) {
339
+ if (store.activeId === null) return null
340
+ return store.accounts.find((account) => account.id === store.activeId) ?? null
341
+ }
342
+
343
+ /**
344
+ * Parse an import payload into credential pairs.
345
+ *
346
+ * Accepts the shapes a user actually has:
347
+ * - a JSON document (a v2 store, an array, a single pair, or `accounts`)
348
+ * - a Huawei `credentials.csv` with the Access Key Id / Secret Access Key headers
349
+ * - `AK,SK` lines, or `AK<TAB>SK`, with an optional trailing label
350
+ *
351
+ * @param {string} text the pasted or uploaded text.
352
+ * @returns {{accounts: Array<{ak: string, sk: string, label?: string}>, skipped: number}} parsed pairs and how many lines were unusable.
353
+ */
354
+ export function parseImport(text) {
355
+ const raw = String(text ?? '').trim()
356
+ if (raw === '') return { accounts: [], skipped: 0 }
357
+
358
+ // JSON first: it is unambiguous when it parses.
359
+ if (raw.startsWith('{') || raw.startsWith('[')) {
360
+ try {
361
+ const parsed = JSON.parse(raw)
362
+ const store = normaliseStore(parsed)
363
+ return {
364
+ accounts: store.accounts.map(({ ak, sk, label }) => ({ ak, sk, ...(label ? { label } : {}) })),
365
+ skipped: 0,
366
+ }
367
+ } catch {
368
+ // Fall through to the line formats.
369
+ }
370
+ }
371
+
372
+ const lines = raw.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== '')
373
+ if (lines.length === 0) return { accounts: [], skipped: 0 }
374
+
375
+ // A CSV header tells us which column is which; without it, assume AK first.
376
+ let akIndex = 0
377
+ let skIndex = 1
378
+ let labelIndex = 2
379
+ let start = 0
380
+ const header = lines[0].toLowerCase()
381
+ if (header.includes('access key') || header.includes('secret') || header.includes('ak')) {
382
+ const cells = splitLine(lines[0]).map((cell) => cell.toLowerCase())
383
+ const akAt = cells.findIndex((cell) => cell.includes('access key') || cell === 'ak')
384
+ const skAt = cells.findIndex((cell) => cell.includes('secret') || cell === 'sk')
385
+ if (akAt >= 0 && skAt >= 0) {
386
+ akIndex = akAt
387
+ skIndex = skAt
388
+ // A "User Name,Access Key Id,Secret Access Key" export names the account
389
+ // in an earlier column, which makes a far better label than a masked AK.
390
+ // Looking for it here rather than only in an `else` branch is what makes
391
+ // that worksheet import labelled.
392
+ const nameAt = cells.findIndex(
393
+ (cell) => cell.includes('user name') || cell.includes('username') || cell.includes('account'),
394
+ )
395
+ labelIndex = nameAt >= 0 ? nameAt : -1
396
+ start = 1
397
+ }
398
+ }
399
+
400
+ const accounts = []
401
+ let skipped = 0
402
+ for (const line of lines.slice(start)) {
403
+ const cells = splitLine(line)
404
+ const ak = (cells[akIndex] ?? '').trim()
405
+ const sk = (cells[skIndex] ?? '').trim()
406
+ const label = labelIndex >= 0 ? (cells[labelIndex] ?? '').trim() : ''
407
+ if (ak === '' || sk === '') {
408
+ skipped += 1
409
+ continue
410
+ }
411
+ accounts.push({ ak, sk, ...(label ? { label } : {}) })
412
+ }
413
+ return { accounts, skipped }
414
+ }
415
+
416
+ /** Split one delimiter-separated line, honouring simple quoting. */
417
+ function splitLine(line) {
418
+ const text = String(line)
419
+ if (text.includes('\t')) return text.split('\t')
420
+ if (text.includes(',')) {
421
+ const cells = []
422
+ let current = ''
423
+ let quoted = false
424
+ for (let i = 0; i < text.length; i += 1) {
425
+ const ch = text[i]
426
+ if (ch === '"') {
427
+ if (quoted && text[i + 1] === '"') {
428
+ current += '"'
429
+ i += 1
430
+ } else {
431
+ quoted = !quoted
432
+ }
433
+ } else if (ch === ',' && !quoted) {
434
+ cells.push(current)
435
+ current = ''
436
+ } else {
437
+ current += ch
438
+ }
439
+ }
440
+ cells.push(current)
441
+ return cells
442
+ }
443
+ return text.split(/\s+/)
444
+ }
445
+
446
+ /**
447
+ * Render the store as text a user can paste into another install.
448
+ *
449
+ * Deliberately the export format and the import format are the same document,
450
+ * so a round trip through the clipboard keeps labels and the active choice.
451
+ * @param {StoreDocument} [store] the store to export.
452
+ * @returns {string} JSON text.
453
+ */
454
+ export function exportStore(store = readStore()) {
455
+ return `${JSON.stringify(store, null, 2)}\n`
456
+ }
457
+
458
+ /** A public view of one account: no secret material. */
459
+ export function publicAccount(account, store) {
460
+ return {
461
+ id: account.id,
462
+ // `renameable: false` means the label shown is the derived fallback rather
463
+ // than a name the user chose — the editor uses that to start empty instead
464
+ // of prefilling a placeholder the user would have to delete.
465
+ renameable: typeof account.label === 'string' && account.label !== '',
466
+ label: account.label ?? defaultLabel(account.ak),
467
+ akMasked: maskKey(account.ak),
468
+ accountName: account.accountName ?? null,
469
+ active: store.activeId === account.id,
470
+ }
471
+ }
472
+
473
+ /** Where a new save would write, for the settings page. */
474
+ export function storeWritePath() {
475
+ return CREDENTIAL_PATH
476
+ }
477
+
478
+ /** A fresh local id for a file that has none. */
479
+ export function newLocalId() {
480
+ return randomUUID()
481
+ }