dsh-zcode-startplan 0.5.2 → 1.0.3

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 (51) hide show
  1. package/CHANGELOG.md +1963 -672
  2. package/README.md +92 -472
  3. package/bin/cli.mjs +509 -450
  4. package/client.js +2459 -1002
  5. package/cordis.patch.yml +4 -2
  6. package/index.js +109 -11
  7. package/lib/adapter.js +476 -449
  8. package/lib/anthropic-body.js +513 -469
  9. package/lib/assemble.js +808 -542
  10. package/lib/auto-claim.js +229 -0
  11. package/lib/captcha/minter.js +61 -7
  12. package/lib/distribution-keys.js +202 -0
  13. package/lib/errors.js +281 -125
  14. package/lib/fallback.js +120 -0
  15. package/lib/local-endpoint.js +367 -352
  16. package/lib/manage-routes.js +1245 -652
  17. package/lib/model-catalog.js +57 -0
  18. package/lib/openai-gateway.js +776 -0
  19. package/lib/plan-client.js +942 -532
  20. package/lib/pool.js +771 -478
  21. package/lib/sse.js +429 -317
  22. package/lib/upstream-api.js +948 -611
  23. package/lib/upstream.js +294 -134
  24. package/lib/version-probe.js +110 -0
  25. package/package.json +84 -81
  26. package/scripts/analyze-grant-intervals.mjs +171 -0
  27. package/scripts/check-compat-rc3.mjs +21 -11
  28. package/scripts/debug-claimable.mjs +130 -0
  29. package/scripts/probe-marketing.mjs +203 -0
  30. package/scripts/restart-dsh.ps1 +119 -116
  31. package/scripts/test-claimed-pending.mjs +152 -0
  32. package/scripts/verify_compat.mjs +75 -64
  33. package/scripts/watch-marketing.mjs +155 -0
  34. package/tests/auto-claim.test.mjs +318 -0
  35. package/tests/claim-routes.test.mjs +438 -293
  36. package/tests/client-panel.test.mjs +1141 -356
  37. package/tests/distribution-keys.test.mjs +123 -0
  38. package/tests/e2e.test.mjs +388 -353
  39. package/tests/fallback-scrub.test.mjs +105 -0
  40. package/tests/launch-command.test.mjs +68 -0
  41. package/tests/openai-gateway.test.mjs +454 -0
  42. package/tests/pinned-models.test.mjs +505 -497
  43. package/tests/plan-client.test.mjs +582 -222
  44. package/tests/pool.test.mjs +319 -93
  45. package/tests/quota-blackhole.test.mjs +409 -0
  46. package/tests/restart-script.test.mjs +53 -0
  47. package/tests/routing-quota.test.mjs +251 -0
  48. package/tests/support/hanging-stream.mjs +48 -0
  49. package/tests/upstream-error-200.test.mjs +164 -125
  50. package/tests/upstream.test.mjs +330 -250
  51. package/tests/version-probe.test.mjs +172 -0
@@ -0,0 +1,409 @@
1
+ /**
2
+ * issue #4:**额度用尽(1005)之后的上游黑洞**必须秒级 / 分秒级失败,且错误码保真。
3
+ *
4
+ * 真实事故形态(2026-11-08,单账号池,GLM-5.3-Flash 免费额度跑尽):
5
+ *
6
+ * ```
7
+ * 23:38:51 请求发出
8
+ * 23:43:53 attempt 1 失败:PROVIDER_ERROR「模型通道超时或不可用」(挂了 302s)
9
+ * 23:48:56 attempt 2(宿主 llm-retry)同样失败 (又挂 303s)
10
+ * 23:48:56 turn 以 error 结束
11
+ * ```
12
+ *
13
+ * 而同一时刻 `last_error` 里早就写着 `额度用尽(1005 exceed quota limit)`。
14
+ *
15
+ * ## 2026-11-10 判据变更(本文件已随之重写)
16
+ *
17
+ * 早期版本把 `last_error` 当作**选号前置判据**:历史文本里出现过 1005 就不发请求。
18
+ * 该判据已从 `pool.js` 删除 —— `last_error` 是无时间戳的历史文本,额度次日恢复后
19
+ * 那行仍写着 1005,于是账号会被**永久**卡死(误判一次的代价是「无限期不可用」,
20
+ * 比多付一次往返贵得多)。
21
+ *
22
+ * 权威判据只剩**上游本次响应**:真耗尽 → 1005 → 写当日硬标记(`model_rate_limits`)
23
+ * → 由硬标记挡住后续选号。所以本文件现在锁的是:
24
+ *
25
+ * 1. **`last_error` 不参与选号**:无论它写着 1005 / 1113 / 其它,请求都照样发出,
26
+ * 只有在真的吃回 1005 之后才落硬标记(「先验证、后下结论」);
27
+ * 2. **首内容超时**:上游 200 却永不出流 → 首内容超时(远小于宿主 ~300s)中止;
28
+ * 3. **错误码保真**:黑洞落 `TIMEOUT`(在回退名单里),不落 `PROVIDER_ERROR`;
29
+ * `last_error` 也**不**参与终态错误码 —— 否则用户会看到「额度用尽」而真因是超时。
30
+ */
31
+
32
+ import test from 'node:test'
33
+ import assert from 'node:assert/strict'
34
+
35
+ import { ZcodePlanClient } from '../lib/plan-client.js'
36
+ import { makeSseDecoder, readContentHead, HEAD_TIMEOUT_CODE, isHeadTimeoutError } from '../lib/sse.js'
37
+ import { isFallbackWorthyCode } from '../lib/errors.js'
38
+ import { HangingStream } from './support/hanging-stream.mjs'
39
+
40
+ const CREDENTIAL = { zcode_jwt: 'jwt-1', device_mid: 'dev-1', user_id: 'u-1' }
41
+
42
+ /**
43
+ * 内存版账号池,**只实现真池(`lib/pool.js`)导出给 plan-client 的那几个方法**。
44
+ *
45
+ * ⚠ 刻意不再实现 `hasQuotaError`、也不在 `pick` 里读 `last_error` ——
46
+ * 那正是被删掉的判据。替身若自己实现了它,测试就会「全绿但被测行为已不存在」
47
+ * (本次重写的原因)。替身必须与真池**同语义**:
48
+ * - 硬过滤只看 `model_rate_limits`(当日标记);
49
+ * - `last_error` 只是展示字段,选号时一律无视。
50
+ */
51
+ function fakePool(entries = [{ id: 'acct-a' }]) {
52
+ const state = entries.map((entry) => ({
53
+ nickname: entry.id,
54
+ enabled: true,
55
+ model_rate_limits: {},
56
+ ...entry,
57
+ /** 每个账号一份独立凭据(缺省共用同一份也没问题,这里给 user_id 换一个)。 */
58
+ credential: entry.credential ?? { ...CREDENTIAL, user_id: `u-${entry.id}` },
59
+ }))
60
+ return {
61
+ list: () => state,
62
+ get: (id) => state.find((entry) => entry.id === id),
63
+ /**
64
+ * 与真池同语义(`AccountPool.pick`):`(modelId, exclude) => { entry, credential } | null`。
65
+ * 判据只有「启用 + 未被 exclude + 该模型不在限流期」,**不看 `last_error`**。
66
+ */
67
+ pick(model, exclude) {
68
+ const excluded = exclude ?? new Set()
69
+ const now = Date.now()
70
+ const hit = state.find(
71
+ (entry) =>
72
+ entry.enabled &&
73
+ !excluded.has(entry.id) &&
74
+ !((entry.model_rate_limits[model] ?? 0) > now),
75
+ )
76
+ return hit === undefined ? null : { entry: hit, credential: hit.credential }
77
+ },
78
+ markModelRateLimited(accountId, modelId, resetAt) {
79
+ const hit = state.find((entry) => entry.id === accountId)
80
+ if (hit !== undefined) hit.model_rate_limits[modelId] = resetAt
81
+ },
82
+ noteError(accountId, message) {
83
+ const hit = state.find((entry) => entry.id === accountId)
84
+ if (hit !== undefined) hit.last_error = message
85
+ },
86
+ isEmptyContentWatched: () => false,
87
+ }
88
+ }
89
+
90
+ const minter = {
91
+ async mint() {
92
+ return { param: 'p', interactive: false }
93
+ },
94
+ async fetchConfig() {
95
+ return undefined
96
+ },
97
+ }
98
+
99
+ const baseOptions = { model: 'GLM-5.3-Flash', messages: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }] }
100
+
101
+ const okResponse = (body) => ({
102
+ ok: true,
103
+ status: 200,
104
+ headers: new Headers({ 'content-type': 'text/event-stream' }),
105
+ body,
106
+ })
107
+
108
+ /** 上游真回 1005 的那种响应(HTTP 200 包裹业务错误,本渠道实测形态)。 */
109
+ const quotaResponse = () => ({
110
+ ok: true,
111
+ status: 200,
112
+ headers: new Headers({ 'content-type': 'application/json' }),
113
+ body: new ReadableStream({
114
+ start(controller) {
115
+ controller.enqueue(new TextEncoder().encode('{"code":1005,"msg":"exceed quota limit"}'))
116
+ controller.close()
117
+ },
118
+ }),
119
+ })
120
+
121
+ const textStream = () =>
122
+ new ReadableStream({
123
+ start(controller) {
124
+ controller.enqueue(
125
+ new TextEncoder().encode(
126
+ 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}\n\n',
127
+ ),
128
+ )
129
+ controller.close()
130
+ },
131
+ })
132
+
133
+ // ────────────────── 1. `last_error` 不再是选号判据(先验证、后下结论) ──────────────────
134
+
135
+ test('#4 last_error 写着 1005 → **仍然发请求**(历史文本不是判据);上游真回 1005 才落硬标记', async () => {
136
+ const pool = fakePool([
137
+ // 硬标记表里**没有**这个模型的记录 —— 以前正是「漏过滤」才会发出去的那条路,
138
+ // 现在它是**唯一正确的路**:历史文本不许替上游下结论。
139
+ { id: 'acct-a', last_error: '额度用尽(1005 exceed quota limit)——该账号在这个模型上的免费额度已用完,请等待额度重置或更换账号。' },
140
+ ])
141
+ let calls = 0
142
+ const client = new ZcodePlanClient({
143
+ pool,
144
+ minter,
145
+ fetchImpl: async () => {
146
+ calls += 1
147
+ return quotaResponse()
148
+ },
149
+ })
150
+
151
+ const startedAt = Date.now()
152
+ /**
153
+ * ⚠ 断言跑在 **plugin 层**(`client.call` 的 code/message),不是终止块:
154
+ * 终止块会经 `adapter` 的脱敏闸换成中性文案(issue #2),细节只进日志。
155
+ */
156
+ const failure = await client.call({ options: baseOptions }).then(
157
+ () => assert.fail('上游已回 1005 时必须失败,而不是当成成功'),
158
+ (error) => error,
159
+ )
160
+ assert.equal(calls, 1, '`last_error` 写着 1005 也照常发请求 —— 判据是上游本次响应,不是历史文本')
161
+ assert.equal(failure.code, 'QUOTA', '额度用尽必须是 QUOTA,不能落成 PROVIDER_ERROR')
162
+ /** 终态文案来自「换轮」分支(已用尽 / 等待重置),真因(1005 原文)必须一并带上。 */
163
+ assert.match(failure.message, /已用尽|额度用尽/)
164
+ assert.match(failure.message, /1005/, '文案要带上真因(上游原文),别只给「已用尽」')
165
+ /** 现在证据来自**本次**上游响应,所以文案里带得出真因(含 1005 细节)。 */
166
+ assert.match(pool.list()[0].last_error, /1005/, '真回 1005 之后 last_error 才被改写成上游真因')
167
+ const mark = pool.list()[0].model_rate_limits['GLM-5.3-Flash']
168
+ assert.equal(typeof mark, 'number', '拿到 1005 才写当日硬标记')
169
+ assert.ok(mark > Date.now(), '硬标记必须落在未来(当日结束),下次选号才挡得住')
170
+ assert.ok(Date.now() - startedAt < 1_000, '快速失败路径必须秒级返回')
171
+ })
172
+
173
+ test('#4 last_error 写着 1113(余额不足)同样先发请求,不据它判死账号', async () => {
174
+ const pool = fakePool([{ id: 'acct-a', last_error: '余额不足或无可用资源包(1113)' }])
175
+ let calls = 0
176
+ const client = new ZcodePlanClient({
177
+ pool,
178
+ minter,
179
+ fetchImpl: async () => {
180
+ calls += 1
181
+ return quotaResponse()
182
+ },
183
+ })
184
+ await assert.rejects(() => client.call({ options: baseOptions }), { code: 'QUOTA' })
185
+ assert.equal(calls, 1, '1113 的历史文本同样不是判据')
186
+ })
187
+
188
+ test('#4 last_error 已是 1005、但上游这次正常 → 请求成功,硬标记保持干净', async () => {
189
+ /**
190
+ * 这条是「永久卡号」bug 的回归锁:额度次日恢复后 `last_error` 仍写着 1005,
191
+ * 若还按它前置过滤,账号会**永远**选不到 —— 这里必须能正常命中。
192
+ */
193
+ const pool = fakePool([{ id: 'acct-a', last_error: '额度用尽(1005 exceed quota limit)' }])
194
+ let calls = 0
195
+ const client = new ZcodePlanClient({
196
+ pool,
197
+ minter,
198
+ fetchImpl: async () => {
199
+ calls += 1
200
+ return okResponse(textStream())
201
+ },
202
+ })
203
+ const result = await client.call({ options: baseOptions })
204
+ assert.equal(result.accountId, 'acct-a')
205
+ assert.equal(calls, 1)
206
+ assert.equal(
207
+ pool.list()[0].model_rate_limits['GLM-5.3-Flash'],
208
+ undefined,
209
+ '上游没判额度用尽,就不许写硬标记',
210
+ )
211
+ })
212
+
213
+ test('#4 last_error 只是并发限流(3009)/网络抖动 → 照常发请求', async () => {
214
+ /** 3009 是瞬态,把它当额度用尽会把用户钉死在「等次日重置」上。 */
215
+ const pool = fakePool([{ id: 'acct-a', last_error: '上游并发限流(3009 model concurrency limit exceeded)' }])
216
+ let calls = 0
217
+ const client = new ZcodePlanClient({
218
+ pool,
219
+ minter,
220
+ concurrencyRetryBaseMs: 1,
221
+ fetchImpl: async () => {
222
+ calls += 1
223
+ return okResponse(textStream())
224
+ },
225
+ })
226
+ const result = await client.call({ options: baseOptions })
227
+ assert.equal(result.accountId, 'acct-a')
228
+ assert.equal(calls, 1)
229
+ })
230
+
231
+ test('#4 钉定账号:last_error 已是 1005 → **照常发请求**(钉定更不该被历史文本卡死)', async () => {
232
+ /**
233
+ * 钉定模式没有「换号」这条出路:若按 `last_error` 前置拦截,用户会看到
234
+ * 「已判额度用尽」而完全无法自救(只能手动清除)。这里锁死「先问上游」。
235
+ */
236
+ const pool = fakePool([{ id: 'acct-a', last_error: '额度用尽(1005 exceed quota limit)' }])
237
+ let calls = 0
238
+ const client = new ZcodePlanClient({
239
+ pool,
240
+ minter,
241
+ fetchImpl: async () => {
242
+ calls += 1
243
+ return okResponse(textStream())
244
+ },
245
+ })
246
+ const result = await client.call({ options: baseOptions, pinnedAccountId: 'acct-a' })
247
+ assert.equal(result.accountId, 'acct-a')
248
+ assert.equal(calls, 1, '钉定账号也必须先发请求再判 —— 不许据 last_error 直接报错')
249
+ })
250
+
251
+ // ─────────────────────────── 2. 首内容超时 ───────────────────────────
252
+
253
+ test('#4 首内容超时:上游 200 却永不出流 → head 返回 timeoutError(不是零内容)', async () => {
254
+ const head = await readContentHead(new HangingStream().stream, {
255
+ contentType: 'text/event-stream',
256
+ headTimeoutMs: 30,
257
+ })
258
+ assert.equal(head.hasContent, false)
259
+ assert.notEqual(head.timeoutError, undefined, '必须暴露 timeoutError,调用方才能按 TIMEOUT 处置')
260
+ assert.equal(isHeadTimeoutError(head.timeoutError), true)
261
+ assert.equal(head.timeoutError.code, HEAD_TIMEOUT_CODE)
262
+ assert.equal(head.elapsedMs >= 25, true)
263
+ })
264
+
265
+ test('#4 首内容超时:引擎的预算必须显著小于宿主 ~300s(默认 90s / 180s)', async () => {
266
+ const { DEFAULT_HEAD_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS } = await import('../lib/errors.js')
267
+ const { resolveConfig } = await import('../index.js')
268
+ assert.ok(DEFAULT_HEAD_TIMEOUT_MS < 300_000, '首内容超时必须早于宿主超时触发')
269
+ assert.ok(DEFAULT_HEAD_TIMEOUT_MS <= 120_000, '否则用户的等待体验与「黑洞」无异')
270
+ assert.ok(DEFAULT_READ_TIMEOUT_MS >= DEFAULT_HEAD_TIMEOUT_MS, '流内静默不该比首内容更严')
271
+ /** config 必须真的能把这两个值透传下去(否则用户无从调整)。 */
272
+ assert.equal(resolveConfig(undefined).headTimeoutMs, DEFAULT_HEAD_TIMEOUT_MS, 'schema 默认与运行时默认同一份')
273
+ assert.equal(resolveConfig({ headTimeoutMs: 5_000 }).headTimeoutMs, 5_000)
274
+ assert.equal(resolveConfig(undefined).readTimeoutMs, DEFAULT_READ_TIMEOUT_MS)
275
+ })
276
+
277
+ test('#4 首内容超时:见到首内容后预算切到流内静默(长思考不被误杀)', async () => {
278
+ /** 首事件在 headTimeoutMs 内到达;此后静默超过 headTimeoutMs、但小于 readTimeoutMs。 */
279
+ const encoder = new TextEncoder()
280
+ const stream = new ReadableStream({
281
+ start(controller) {
282
+ controller.enqueue(
283
+ encoder.encode('event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"a"}}\n\n'),
284
+ )
285
+ setTimeout(() => {
286
+ controller.enqueue(
287
+ encoder.encode('event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"b"}}\n\n'),
288
+ )
289
+ controller.close()
290
+ }, 120)
291
+ },
292
+ })
293
+ const decoder = makeSseDecoder(stream, { headTimeoutMs: 40, timeoutMs: 2_000 })
294
+ const first = await decoder.read()
295
+ assert.equal(first.done, false)
296
+ decoder.markContent()
297
+ const second = await decoder.read()
298
+ assert.equal(second.done, false, '流内静默 120ms 不该被 40ms 的首内容预算误杀')
299
+ await decoder.cancel()
300
+ })
301
+
302
+ // ─────────────────────────── 3. 错误码保真 ───────────────────────────
303
+
304
+ test('#4 错误码保真:黑洞落 TIMEOUT(可回退),不落 PROVIDER_ERROR', async () => {
305
+ const pool = fakePool([{ id: 'acct-a' }])
306
+ const client = new ZcodePlanClient({
307
+ pool,
308
+ minter,
309
+ headTimeoutMs: 30,
310
+ readTimeoutMs: 30,
311
+ fetchImpl: async () => okResponse(new HangingStream().stream),
312
+ })
313
+ await assert.rejects(
314
+ () => client.call({ options: baseOptions }),
315
+ (error) => {
316
+ assert.equal(error.code, 'TIMEOUT', `黑洞=没拿到内容,不是笼统的 PROVIDER_ERROR(实际:${error.message.slice(0, 160)})`)
317
+ assert.equal(isFallbackWorthyCode(error.code), true, 'TIMEOUT 在回退名单里,宿主才有机会改道')
318
+ assert.match(error.message, /没有产出任何内容/)
319
+ return true
320
+ },
321
+ )
322
+ assert.equal(
323
+ pool.list()[0].model_rate_limits['GLM-5.3-Flash'] ?? 0,
324
+ 0,
325
+ '黑洞不写当日硬标记:没有 1005 证据就不该锁一整天(抖动一次 = 白等一天)',
326
+ )
327
+ })
328
+
329
+ test('#4 黑洞的终态码**不受** last_error 影响(历史 1005 不许把 TIMEOUT 洗成 QUOTA)', async () => {
330
+ /**
331
+ * 以前「选号前置」若按 `last_error` 短路,黑洞会被报告成「额度用尽」——
332
+ * 用户于是去等次日重置,而真因是上游不出流(TIMEOUT 本可改道)。
333
+ * 这条锁死:终态码只由**本次**失败类型决定。
334
+ */
335
+ const pool = fakePool([{ id: 'acct-a', last_error: '额度用尽(1005 exceed quota limit)' }])
336
+ const client = new ZcodePlanClient({
337
+ pool,
338
+ minter,
339
+ headTimeoutMs: 20,
340
+ readTimeoutMs: 20,
341
+ fetchImpl: async () => okResponse(new HangingStream().stream),
342
+ })
343
+ await assert.rejects(
344
+ () => client.call({ options: baseOptions }),
345
+ (error) => {
346
+ assert.equal(error.code, 'TIMEOUT', '本次是黑洞 → TIMEOUT,与 last_error 里的 1005 无关')
347
+ assert.match(error.message, /没有产出任何内容/)
348
+ return true
349
+ },
350
+ )
351
+ })
352
+
353
+ test('#4 钉定账号黑洞:如实报 TIMEOUT,不换号', async () => {
354
+ const pool = fakePool([{ id: 'acct-a' }, { id: 'acct-b' }])
355
+ let calls = 0
356
+ const client = new ZcodePlanClient({
357
+ pool,
358
+ minter,
359
+ headTimeoutMs: 30,
360
+ readTimeoutMs: 30,
361
+ fetchImpl: async () => {
362
+ calls += 1
363
+ return okResponse(new HangingStream().stream)
364
+ },
365
+ })
366
+ await assert.rejects(() => client.call({ options: baseOptions, pinnedAccountId: 'acct-a' }), { code: 'TIMEOUT' })
367
+ assert.equal(calls, 1, '钉定模式绝不换号(换号会让「钉定」名存实亡)')
368
+ })
369
+
370
+ test('#4 统一选号黑洞:同账号撞满上限后换号,两个号都黑洞才报 TIMEOUT', async () => {
371
+ const pool = fakePool([{ id: 'acct-a' }, { id: 'acct-b' }])
372
+ const hits = []
373
+ const client = new ZcodePlanClient({
374
+ pool,
375
+ minter,
376
+ headTimeoutMs: 20,
377
+ readTimeoutMs: 20,
378
+ fetchImpl: async (_url, init) => {
379
+ hits.push(init.headers['authorization'])
380
+ return okResponse(new HangingStream().stream)
381
+ },
382
+ })
383
+ await assert.rejects(() => client.call({ options: baseOptions }), { code: 'TIMEOUT' })
384
+ assert.equal(hits.length, 4, '两个账号各撞 2 次(PER_ACCOUNT_FAIL_MAX),每次都远小于宿主超时')
385
+ assert.ok(
386
+ pool.list().every((entry) => (entry.model_rate_limits['GLM-5.3-Flash'] ?? 0) === 0),
387
+ '黑洞不证明额度用尽:只记失败原因,不写当日硬标记(避免抖动一次锁一整天)',
388
+ )
389
+ })
390
+
391
+ test('#4 网络层 AbortError(fetch 自身超时)同样落 TIMEOUT', async () => {
392
+ const pool = fakePool([{ id: 'acct-a' }])
393
+ const client = new ZcodePlanClient({
394
+ pool,
395
+ minter,
396
+ readTimeoutMs: 4_000,
397
+ fetchImpl: async () => {
398
+ throw Object.assign(new Error('The operation was aborted due to timeout'), { name: 'TimeoutError' })
399
+ },
400
+ })
401
+ await assert.rejects(
402
+ () => client.call({ options: baseOptions, pinnedAccountId: 'acct-a' }),
403
+ (error) => {
404
+ assert.equal(error.code, 'TIMEOUT')
405
+ assert.match(error.message, /4s/)
406
+ return true
407
+ },
408
+ )
409
+ })
@@ -0,0 +1,53 @@
1
+ /**
2
+ * `scripts/restart-dsh.ps1` 的**安全契约**测试。
3
+ *
4
+ * ## 背景(0.6.6)
5
+ *
6
+ * 旧版脚本做「杀宿主 → 等退出 → 拉起」,并叠加了计划任务、隐藏窗口、
7
+ * 临时 .cmd、`-ExecutionPolicy Bypass` —— 这组特征与恶意软件高度重合,
8
+ * **被火绒等 AV 拦截是正确行为**(用户实际遇到报毒)。新版只输出
9
+ * 「用户可手动执行的重启命令」,不再有任何高危动作。
10
+ *
11
+ * 这些用例锁住「无害」契约,防止将来有人把杀进程/计划任务加回来:
12
+ * 每一条都对应一个真实的误判特征。
13
+ */
14
+
15
+ import test from 'node:test'
16
+ import assert from 'node:assert/strict'
17
+ import { readFileSync } from 'node:fs'
18
+
19
+ const SCRIPT = new URL('../scripts/restart-dsh.ps1', import.meta.url)
20
+ const text = () => readFileSync(SCRIPT, 'utf8')
21
+ const bytes = () => readFileSync(SCRIPT)
22
+
23
+ test('restart-dsh.ps1: 文件带 UTF-8 BOM(否则 PowerShell 5.1 按 GBK 解码而解析失败)', () => {
24
+ const b = bytes()
25
+ assert.deepEqual(
26
+ [b[0], b[1], b[2]],
27
+ [0xef, 0xbb, 0xbf],
28
+ '缺 UTF-8 BOM:powershell.exe (5.1) 会把中文注释按 GBK 解码,导致整份脚本解析失败',
29
+ )
30
+ })
31
+
32
+ test('restart-dsh.ps1: 不结束任何进程(安全契约:杀进程是 AV 判毒的首要特征)', () => {
33
+ const t = text()
34
+ assert.doesNotMatch(t, /Stop-Process/, '不许 Stop-Process')
35
+ assert.doesNotMatch(t, /taskkill/i, '不许 taskkill')
36
+ assert.doesNotMatch(t, /\.Kill\(\)/, '不许 Process.Kill()')
37
+ })
38
+
39
+ test('restart-dsh.ps1: 不建计划任务、不隐藏窗口、不混淆(安全契约:持久化特征)', () => {
40
+ const t = text()
41
+ assert.doesNotMatch(t, /schtasks/i, '计划任务是 AV 最敏感的持久化特征')
42
+ assert.doesNotMatch(t, /Register-ScheduledTask/i, '同上')
43
+ assert.doesNotMatch(t, /-EncodedCommand/i, '编码命令是典型混淆手法')
44
+ assert.doesNotMatch(t, /-WindowStyle\s+Hidden/i, '隐藏窗口是典型恶意特征')
45
+ })
46
+
47
+ test('restart-dsh.ps1: 只输出指引,不执行重启(普通重启不依赖调试模式)', () => {
48
+ const t = text()
49
+ assert.match(t, /--remote-debugging-port=/, '要给出带端口的启动命令')
50
+ /** 普通重启 = 不带端口的命令也要能生成(DebugPort <= 0 分支)。 */
51
+ assert.match(t, /\$DebugPort\s+-gt\s+0/, 'DebugPort <= 0 = 普通重启指引')
52
+ assert.match(t, /手动/, '明确告知由用户手动执行')
53
+ })