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.
Files changed (49) hide show
  1. package/DISCLAIMER.md +47 -0
  2. package/LICENSE +21 -0
  3. package/README.md +169 -2
  4. package/SECURITY.md +45 -0
  5. package/THIRD_PARTY_NOTICES.md +64 -0
  6. package/client.js +3491 -0
  7. package/cordis.patch.yml +10 -0
  8. package/docs/DETAIL.md +24 -0
  9. package/docs/DETAIL.zh.md +24 -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 +715 -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 +15 -0
  31. package/src/index.js +1029 -0
  32. package/src/models.js +147 -0
  33. package/src/paths.js +36 -0
  34. package/src/preferences.js +87 -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/test/accounts.test.mjs +344 -0
  41. package/test/adapter.test.mjs +234 -0
  42. package/test/assembler.test.mjs +86 -0
  43. package/test/features.test.mjs +240 -0
  44. package/test/live-probe.mjs +55 -0
  45. package/test/protocol.test.mjs +167 -0
  46. package/test/registration.test.mjs +303 -0
  47. package/test/sm4.test.mjs +64 -0
  48. package/test/ui.test.mjs +732 -0
  49. package/test/visual.test.mjs +420 -0
@@ -0,0 +1,303 @@
1
+ /**
2
+ * Host-half registration checks.
3
+ *
4
+ * The llm service has THREE separate registries, and a provider is only fully
5
+ * installed when all of the ones that apply are declared:
6
+ *
7
+ * registerAdapter — makes the route routable; feeds the model picker
8
+ * registerConfigurableProviders — creates the row in Settings → Models
9
+ * registerModelDiscovery — lets a settings surface interrogate the catalog
10
+ *
11
+ * Registering only the adapter leaves the plugin half-installed, and the two
12
+ * symptoms look unrelated to a user ("the model is not in the picker" vs "the
13
+ * provider is not in Settings"), so this test asserts all three.
14
+ */
15
+
16
+ import assert from 'node:assert/strict'
17
+ import { mkdtempSync, rmSync } from 'node:fs'
18
+ import { tmpdir } from 'node:os'
19
+ import { join } from 'node:path'
20
+
21
+ const results = []
22
+ const check = async (name, fn) => {
23
+ try {
24
+ await fn()
25
+ results.push(`✓ ${name}`)
26
+ } catch (error) {
27
+ results.push(`✗ ${name}\n ${error.message}`)
28
+ process.exitCode = 1
29
+ }
30
+ }
31
+
32
+ const scratch = mkdtempSync(join(tmpdir(), 'dca-reg-'))
33
+ process.env.APPDATA = scratch
34
+ process.env.DSH_CONNECT_CODEARTS_LEGACY_CREDENTIAL = join(scratch, 'legacy.json')
35
+
36
+ const plugin = await import('../src/index.js')
37
+
38
+ /** Apply the plugin against a recording context. */
39
+ function activate() {
40
+ const recorder = { adapters: [], directories: [], discoveries: [] }
41
+ const ctx = {
42
+ effect: (fn) => {
43
+ const disposer = fn()
44
+ return typeof disposer === 'function' ? disposer : () => {}
45
+ },
46
+ get: () => undefined,
47
+ llm: {
48
+ registerAdapter(providers, adapter) {
49
+ recorder.adapters.push({ providers, adapter })
50
+ return () => {}
51
+ },
52
+ registerConfigurableProviders(entries) {
53
+ recorder.directories.push(entries)
54
+ return () => {}
55
+ },
56
+ registerModelDiscovery(ns, discover) {
57
+ recorder.discoveries.push({ ns, discover })
58
+ return () => {}
59
+ },
60
+ },
61
+ inject() {},
62
+ emit() {},
63
+ }
64
+ plugin.apply(ctx, {})
65
+ return recorder
66
+ }
67
+
68
+ /**
69
+ * Apply the plugin against a context that reports a Loader entry id, the way a
70
+ * real Loader-mounted row does.
71
+ */
72
+ function activateUnderEntryId(entryId) {
73
+ const recorder = { adapters: [], directories: [], discoveries: [] }
74
+ const ctx = {
75
+ fiber: { entry: { options: { id: entryId } } },
76
+ effect: (fn) => {
77
+ const disposer = fn()
78
+ return typeof disposer === 'function' ? disposer : () => {}
79
+ },
80
+ get: () => undefined,
81
+ llm: {
82
+ registerAdapter(providers, adapter) {
83
+ recorder.adapters.push({ providers, adapter })
84
+ return () => {}
85
+ },
86
+ registerConfigurableProviders(entries) {
87
+ recorder.directories.push(entries)
88
+ return () => {}
89
+ },
90
+ registerModelDiscovery(ns, discover) {
91
+ recorder.discoveries.push({ ns, discover })
92
+ return () => {}
93
+ },
94
+ },
95
+ inject() {},
96
+ emit() {},
97
+ }
98
+ plugin.apply(ctx, {})
99
+ return recorder
100
+ }
101
+
102
+ await check('the settings namespace follows the Loader entry id', async () => {
103
+ // Settings → Models addresses a provider's form by this namespace. Hard-coding
104
+ // it means the row silently stops resolving the moment a user renames the
105
+ // entry in cordis.patch.yml — which is exactly what the row's `id` is for.
106
+ const { directories, discoveries } = activateUnderEntryId('a-renamed-row')
107
+ assert.equal(directories[0][0].settingsNs, 'a-renamed-row')
108
+ assert.equal(discoveries[0].ns, 'a-renamed-row', 'discovery must follow the same namespace')
109
+ })
110
+
111
+ await check('a host that mounts the plugin directly still gets a namespace', async () => {
112
+ // `ctx.fiber.entry` is added by the Loader, so it is absent under ctx.plugin()
113
+ // or a test harness. The fallback is what keeps the row registering there.
114
+ const { directories } = activate()
115
+ assert.equal(directories[0][0].settingsNs, 'dsh-connect-codearts')
116
+ })
117
+
118
+ await check('the adapter is registered for exactly this provider route', async () => {
119
+ const { adapters } = activate()
120
+ assert.equal(adapters.length, 1, 'exactly one adapter')
121
+ assert.deepEqual(adapters[0].providers, ['codearts'])
122
+ })
123
+
124
+ await check('the provider is declared in the configurable directory', async () => {
125
+ const { directories } = activate()
126
+ assert.equal(directories.length, 1, 'Settings → Models needs this row to exist')
127
+ const entry = directories[0][0]
128
+ assert.equal(entry.provider, 'codearts')
129
+ assert.ok(entry.displayName.length > 0)
130
+ assert.ok(entry.settingsNs.length > 0, 'a row without a namespace cannot be edited')
131
+ assert.deepEqual(entry.settingsPath, [])
132
+ })
133
+
134
+ await check('model discovery is offered under the same namespace as the directory row', async () => {
135
+ const { directories, discoveries } = activate()
136
+ assert.equal(discoveries.length, 1)
137
+ assert.equal(
138
+ discoveries[0].ns,
139
+ directories[0][0].settingsNs,
140
+ 'discovery and the directory row must agree on the namespace, or the page cannot use it',
141
+ )
142
+ })
143
+
144
+ await check('discovery returns the catalog in the shape discovery consumers expect', async () => {
145
+ // Discovery is credential-backed: without one the catalog stays on the static
146
+ // fallback, which is still a valid answer. Assert the SHAPE rather than a
147
+ // count, so this runs in CI without any key.
148
+ const { adapters, discoveries } = activate()
149
+ // Wait for the startup catalog refresh so there is something to report.
150
+ for (let i = 0; i < 60; i += 1) {
151
+ const models = await adapters[0].adapter.listModels('codearts')
152
+ if (models.length > 0) break
153
+ await new Promise((resolve) => setTimeout(resolve, 250))
154
+ }
155
+ const discovered = await discoveries[0].discover({})
156
+ assert.ok(Array.isArray(discovered), 'discovery must answer with an array')
157
+ for (const model of discovered) {
158
+ assert.equal(typeof model.id, 'string')
159
+ assert.ok(model.id.length > 0)
160
+ if (model.contextWindow !== undefined) assert.ok(model.contextWindow > 0)
161
+ if (model.inputModalities !== undefined) assert.ok(Array.isArray(model.inputModalities))
162
+ }
163
+ })
164
+
165
+ rmSync(scratch, { recursive: true, force: true })
166
+ await check('every route is registered exact, so paths cannot shadow each other', async () => {
167
+ // THE BUG THIS CATCHES: with `prefix` registrations, `/models` also claims
168
+ // `/models/select`. A save POST then lands on the read route, which answers
169
+ // `{ ok: true, models: [...] }` — the client sees success and nothing was
170
+ // written. `exact` makes a missing route answer 404 instead of a neighbour's
171
+ // payload.
172
+ const kinds = new Set()
173
+ const seen = []
174
+ const ctx = {
175
+ effect: (fn) => {
176
+ const d = fn()
177
+ return typeof d === 'function' ? d : () => {}
178
+ },
179
+ get: () => undefined,
180
+ llm: {
181
+ registerAdapter: () => () => {},
182
+ registerConfigurableProviders: () => () => {},
183
+ registerModelDiscovery: () => () => {},
184
+ },
185
+ inject(deps, cb) {
186
+ cb({
187
+ effect: (fn) => {
188
+ fn()
189
+ return () => {}
190
+ },
191
+ webServer: {
192
+ register(route) {
193
+ kinds.add(route.kind)
194
+ seen.push(route.path)
195
+ return () => {}
196
+ },
197
+ },
198
+ })
199
+ },
200
+ emit() {},
201
+ }
202
+ plugin.apply(ctx, {})
203
+ assert.deepEqual([...kinds], ['exact'], `expected only exact routes, got: ${[...kinds].join(', ')}`)
204
+ assert.ok(seen.includes('/plugins/dsh-connect-codearts/models/select'), 'the save route is registered')
205
+ })
206
+
207
+ await check('a Config schema is declared, so the settings namespace exists', async () => {
208
+ // THE BUG THIS CATCHES: Settings → Models resolves a provider row's form by
209
+ // looking its `settingsNs` up in the Host settings service, which only holds
210
+ // namespaces for plugins with a Config schema. Without one the page hits
211
+ // `if (namespace === undefined) return null` and skips the row SILENTLY —
212
+ // the provider is routable, its models are selectable, and the card where a
213
+ // user manages it never appears, with no error anywhere.
214
+ assert.equal(typeof plugin.Config, 'function', 'Config must be a Schemastery schema')
215
+ const resolved = plugin.Config({})
216
+ assert.equal(typeof resolved, 'object', 'the schema must resolve defaults')
217
+ assert.equal(resolved.enabled, true, 'defaults must be applied')
218
+ assert.ok('composerChip' in resolved, 'the fields the card reads must be declared')
219
+ })
220
+
221
+ await check('Config satisfies the two gates Settings → Models applies', async () => {
222
+ // The page hides a provider row without ever naming it, at two gates:
223
+ //
224
+ // 1. settings.describe() only emits a namespace for an entry whose
225
+ // `entry.fiber.runtime.Config` exists AND has `toJSON` —
226
+ // `if (namespace === undefined) return null`
227
+ // 2. the page then requires `row.configured`, i.e. that namespace
228
+ //
229
+ // So the schema must be a real Schemastery schema, not merely exported. Both
230
+ // gates are asserted here because either one hides the card silently.
231
+ const schema = plugin.Config
232
+ assert.equal(typeof schema, 'function', 'a Schemastery schema is callable')
233
+ assert.equal(typeof schema.toJSON, 'function', 'gate 1: the Host requires toJSON')
234
+ const json = schema.toJSON()
235
+ assert.equal(typeof json, 'object', 'gate 1: toJSON must produce a schema document')
236
+ // Gate 2 needs the schema to resolve the values the card reads.
237
+ assert.ok(!('autoCheckin' in plugin.DEFAULTS), 'removed automatic preference has no default')
238
+ const values = schema({})
239
+ assert.ok(!('autoCheckin' in values), 'removed automatic preference is not offered by settings')
240
+ for (const field of ['enabled', 'composerChip', 'registerProvider']) {
241
+ assert.ok(field in values, `gate 2: ${field} must resolve from the schema`)
242
+ }
243
+ })
244
+
245
+ await check('the adapter carries every method the Host calls unconditionally', async () => {
246
+ // The bug this catches is a mid-session crash, not a load failure: a plain
247
+ // class that merely looks like an adapter registers and streams fine, then
248
+ // dies when another code path asks for `imageRequestPricing`.
249
+ const { createCodeArtsAdapter } = await import('../src/adapter.js')
250
+ const adapter = createCodeArtsAdapter({
251
+ catalog: { find: () => null, models: () => [], visible: () => [] },
252
+ credentials: {},
253
+ gateway: () => undefined,
254
+ })
255
+ for (const method of ['imageRequestPricing', 'imageRequestTarget', 'providerInfo', 'providerRetryPolicy']) {
256
+ assert.equal(typeof adapter[method], 'function', `${method} must exist`)
257
+ }
258
+ assert.equal(adapter.imageRequestPricing('codearts', 'x'), undefined, 'no image pricing is the honest answer')
259
+ })
260
+
261
+ await check('the last good catalog survives a restart', async () => {
262
+ // Without this a restart begins on the static fallback table and the picker is
263
+ // wrong until the first refresh lands.
264
+ const { mkdtempSync, writeFileSync } = await import('node:fs')
265
+ const { tmpdir } = await import('node:os')
266
+ const { join } = await import('node:path')
267
+ const { Catalog } = await import('../src/catalog.js')
268
+ const cache = join(mkdtempSync(join(tmpdir(), 'dca-cat-')), 'catalog.json')
269
+
270
+ const first = new Catalog({})
271
+ first.current = [{ id: 'saved-model', name: 'S', context: 1000, maxOutput: 10, supportsImages: false, strengths: [] }]
272
+ first.source = 'gateway'
273
+ first.persist(cache)
274
+
275
+ const second = new Catalog({})
276
+ assert.equal(second.loadPersisted(cache), true, 'the cached catalog must load')
277
+ assert.deepEqual(second.models().map((m) => m.id), ['saved-model'])
278
+ assert.equal(second.source, 'cache', 'the source says where it came from')
279
+
280
+ // A corrupt file must not replace a working catalog with nothing.
281
+ writeFileSync(cache, '{ not json')
282
+ const third = new Catalog({})
283
+ third.current = [{ id: 'keep' }]
284
+ assert.equal(third.loadPersisted(cache), false, 'a corrupt cache is refused')
285
+ assert.deepEqual(third.models().map((m) => m.id), ['keep'], 'and leaves the catalog intact')
286
+
287
+ // A fallback catalog is never persisted: it is not worth restoring.
288
+ const fourth = new Catalog({})
289
+ fourth.persist(join(mkdtempSync(join(tmpdir(), 'dca-cat2-')), 'never.json'))
290
+ })
291
+
292
+ await check('the status route reports both settings gates', async () => {
293
+ // A missing card has two silent causes; reporting the facts means the next
294
+ // diagnosis does not have to guess which one it was.
295
+ const { readFileSync } = await import('node:fs')
296
+ const host = readFileSync(new URL('../src/index.js', import.meta.url), 'utf8')
297
+ assert.ok(host.includes('configSchema:'), 'reports whether a Config schema is exported')
298
+ assert.ok(host.includes('registration:'), 'exposes a registration block at all')
299
+ })
300
+
301
+ console.log(results.join('\n'))
302
+ if (process.exitCode) console.log('\nregistration: some checks failed')
303
+ else console.log('\nregistration: all checks passed')
@@ -0,0 +1,64 @@
1
+ import assert from 'node:assert/strict';
2
+ import { sm4GcmEncrypt, sm4GcmDecrypt } from '../src/protocol/sm4.js';
3
+ import { createCipheriv, createDecipheriv } from 'node:crypto';
4
+
5
+ const hex = (u8) => Buffer.from(u8).toString('hex');
6
+
7
+ // 1) round-trip over a UTF-8 payload longer than one block
8
+ {
9
+ const key = Buffer.from('0123456789abcdeffedcba9876543210', 'hex');
10
+ const iv = Buffer.alloc(12, 7);
11
+ const pt = Buffer.from('hello 码道 SM4-GCM — a payload longer than sixteen bytes', 'utf8');
12
+ const aad = Buffer.from('aad-header');
13
+ const { ciphertext, tag } = sm4GcmEncrypt(key, iv, pt, aad);
14
+ const back = Buffer.from(sm4GcmDecrypt(key, iv, ciphertext, tag, aad));
15
+ assert.equal(back.toString('utf8'), pt.toString('utf8'));
16
+ console.log('✓ round-trip');
17
+ }
18
+
19
+ // 2) byte-identical to OpenSSL's native sm4-gcm (skipped when absent)
20
+ {
21
+ const key = Buffer.from('0123456789abcdeffedcba9876543210', 'hex');
22
+ const iv = Buffer.alloc(12, 7);
23
+ const pt = Buffer.from('cross-check against native', 'utf8');
24
+ const aad = Buffer.from('aad');
25
+ const mine = sm4GcmEncrypt(key, iv, pt, aad);
26
+ try {
27
+ const c = createCipheriv('sm4-gcm', key, iv);
28
+ c.setAAD(aad);
29
+ const ct = Buffer.concat([c.update(pt), c.final()]);
30
+ assert.equal(hex(ct), hex(mine.ciphertext), 'ciphertext');
31
+ assert.equal(hex(c.getAuthTag()), hex(mine.tag), 'tag');
32
+ console.log('✓ byte-identical to native sm4-gcm');
33
+ } catch (e) {
34
+ if (e.code === 'ERR_CRYPTO_UNKNOWN_CIPHER' || /Unknown cipher/.test(e.message)) {
35
+ console.log('- native sm4-gcm unavailable, cross-check skipped');
36
+ } else throw e;
37
+ }
38
+ }
39
+
40
+ // 3) tampering and a wrong AAD both fail authentication
41
+ {
42
+ const key = Buffer.alloc(16, 3);
43
+ const iv = Buffer.alloc(12, 9);
44
+ const pt = Buffer.from('payload');
45
+ const { ciphertext, tag } = sm4GcmEncrypt(key, iv, pt, Buffer.from('aad'));
46
+ assert.throws(() => sm4GcmDecrypt(key, iv, ciphertext, Buffer.alloc(16), Buffer.from('aad')), /authentication failed/);
47
+ assert.throws(() => sm4GcmDecrypt(key, iv, ciphertext, tag, Buffer.from('other')), /authentication failed/);
48
+ const bad = Uint8Array.from(ciphertext); bad[0] ^= 1;
49
+ assert.throws(() => sm4GcmDecrypt(key, iv, bad, tag, Buffer.from('aad')), /authentication failed/);
50
+ console.log('✓ tamper and wrong-AAD rejected');
51
+ }
52
+
53
+ // 4) the exact AAD shape 码道 uses on SSE chunks: `${keyId}|${chunkIndex}`
54
+ {
55
+ const key = Buffer.alloc(16, 1);
56
+ const iv = Buffer.alloc(12, 2);
57
+ const aad = Buffer.from('abc123|7');
58
+ const pt = Buffer.from('{"type":"text-delta"}');
59
+ const { ciphertext, tag } = sm4GcmEncrypt(key, iv, pt, aad);
60
+ const back = Buffer.from(sm4GcmDecrypt(key, iv, ciphertext, tag, aad));
61
+ assert.equal(back.toString(), pt.toString());
62
+ console.log('✓ 码道 AAD shape');
63
+ }
64
+ console.log('sm4: all checks passed');