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.
- package/CHANGELOG.md +1963 -672
- package/README.md +92 -472
- package/bin/cli.mjs +509 -450
- package/client.js +2459 -1002
- package/cordis.patch.yml +4 -2
- package/index.js +109 -11
- package/lib/adapter.js +476 -449
- package/lib/anthropic-body.js +513 -469
- package/lib/assemble.js +808 -542
- package/lib/auto-claim.js +229 -0
- package/lib/captcha/minter.js +61 -7
- package/lib/distribution-keys.js +202 -0
- package/lib/errors.js +281 -125
- package/lib/fallback.js +120 -0
- package/lib/local-endpoint.js +367 -352
- package/lib/manage-routes.js +1245 -652
- package/lib/model-catalog.js +57 -0
- package/lib/openai-gateway.js +776 -0
- package/lib/plan-client.js +942 -532
- package/lib/pool.js +771 -478
- package/lib/sse.js +429 -317
- package/lib/upstream-api.js +948 -611
- package/lib/upstream.js +294 -134
- package/lib/version-probe.js +110 -0
- package/package.json +84 -81
- package/scripts/analyze-grant-intervals.mjs +171 -0
- package/scripts/check-compat-rc3.mjs +21 -11
- package/scripts/debug-claimable.mjs +130 -0
- package/scripts/probe-marketing.mjs +203 -0
- package/scripts/restart-dsh.ps1 +119 -116
- package/scripts/test-claimed-pending.mjs +152 -0
- package/scripts/verify_compat.mjs +75 -64
- package/scripts/watch-marketing.mjs +155 -0
- package/tests/auto-claim.test.mjs +318 -0
- package/tests/claim-routes.test.mjs +438 -293
- package/tests/client-panel.test.mjs +1141 -356
- package/tests/distribution-keys.test.mjs +123 -0
- package/tests/e2e.test.mjs +388 -353
- package/tests/fallback-scrub.test.mjs +105 -0
- package/tests/launch-command.test.mjs +68 -0
- package/tests/openai-gateway.test.mjs +454 -0
- package/tests/pinned-models.test.mjs +505 -497
- package/tests/plan-client.test.mjs +582 -222
- package/tests/pool.test.mjs +319 -93
- package/tests/quota-blackhole.test.mjs +409 -0
- package/tests/restart-script.test.mjs +53 -0
- package/tests/routing-quota.test.mjs +251 -0
- package/tests/support/hanging-stream.mjs +48 -0
- package/tests/upstream-error-200.test.mjs +164 -125
- package/tests/upstream.test.mjs +330 -250
- package/tests/version-probe.test.mjs +172 -0
|
@@ -1,64 +1,75 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* DSH 兼容性门禁(离线,不发网络请求)。
|
|
3
|
-
*
|
|
4
|
-
* DSH 在加载 bundle 时会用 `evaluatePluginCompatibility` 检查 `peerDependencies` 里
|
|
5
|
-
* 所有 `@deepseek-ai/dsh-*` 项,并用 `includePrerelease: true` 比较版本 ——
|
|
6
|
-
* 所以写 `^0.2.0` 会把 `0.2.0-rc.2` 判成**不兼容**并静默跳过本 bundle。
|
|
7
|
-
* 本脚本在重启前把这件事提前暴露出来。
|
|
8
|
-
*
|
|
9
|
-
* ```powershell
|
|
10
|
-
* node scripts/verify_compat.mjs
|
|
11
|
-
* ```
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
import { readFileSync } from 'node:fs'
|
|
15
|
-
import { fileURLToPath } from 'node:url'
|
|
16
|
-
import { dirname, join } from 'node:path'
|
|
17
|
-
|
|
18
|
-
const here = dirname(fileURLToPath(import.meta.url))
|
|
19
|
-
const root = join(here, '..')
|
|
20
|
-
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
|
|
21
|
-
|
|
22
|
-
/** 本插件实际使用、且会被门禁检查的宿主包。 */
|
|
23
|
-
const REQUIRED_HOST_PACKAGES = ['@deepseek-ai/dsh-llm']
|
|
24
|
-
|
|
25
|
-
const failures = []
|
|
26
|
-
const notes = []
|
|
27
|
-
|
|
28
|
-
const peers = pkg.peerDependencies ?? {}
|
|
29
|
-
for (const name of REQUIRED_HOST_PACKAGES) {
|
|
30
|
-
if (typeof peers[name] !== 'string') {
|
|
31
|
-
failures.push(`peerDependencies 缺 ${name} —— DSH 不会报错,但本插件依赖它的契约`)
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
for (const [name, range] of Object.entries(peers)) {
|
|
36
|
-
if (!name.startsWith('@deepseek-ai/dsh-')) continue
|
|
37
|
-
/**
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
|
|
1
|
+
/**
|
|
2
|
+
* DSH 兼容性门禁(离线,不发网络请求)。
|
|
3
|
+
*
|
|
4
|
+
* DSH 在加载 bundle 时会用 `evaluatePluginCompatibility` 检查 `peerDependencies` 里
|
|
5
|
+
* 所有 `@deepseek-ai/dsh-*` 项,并用 `includePrerelease: true` 比较版本 ——
|
|
6
|
+
* 所以写 `^0.2.0` 会把 `0.2.0-rc.2` 判成**不兼容**并静默跳过本 bundle。
|
|
7
|
+
* 本脚本在重启前把这件事提前暴露出来。
|
|
8
|
+
*
|
|
9
|
+
* ```powershell
|
|
10
|
+
* node scripts/verify_compat.mjs
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { readFileSync } from 'node:fs'
|
|
15
|
+
import { fileURLToPath } from 'node:url'
|
|
16
|
+
import { dirname, join } from 'node:path'
|
|
17
|
+
|
|
18
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
19
|
+
const root = join(here, '..')
|
|
20
|
+
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
|
|
21
|
+
|
|
22
|
+
/** 本插件实际使用、且会被门禁检查的宿主包。 */
|
|
23
|
+
const REQUIRED_HOST_PACKAGES = ['@deepseek-ai/dsh-llm']
|
|
24
|
+
|
|
25
|
+
const failures = []
|
|
26
|
+
const notes = []
|
|
27
|
+
|
|
28
|
+
const peers = pkg.peerDependencies ?? {}
|
|
29
|
+
for (const name of REQUIRED_HOST_PACKAGES) {
|
|
30
|
+
if (typeof peers[name] !== 'string') {
|
|
31
|
+
failures.push(`peerDependencies 缺 ${name} —— DSH 不会报错,但本插件依赖它的契约`)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
for (const [name, range] of Object.entries(peers)) {
|
|
36
|
+
if (!name.startsWith('@deepseek-ai/dsh-')) continue
|
|
37
|
+
/**
|
|
38
|
+
* prerelease 陷阱:区间里没有与宿主 `major.minor.patch` 元组一致的 prerelease
|
|
39
|
+
* 比较符时,rc / alpha 版会被判为不满足 —— 而且 `^0.2.1-rc.3` 这类写法还会漏掉
|
|
40
|
+
* 下一个元组(`0.2.2-rc.1` 不满足它)。正确写法是按元组列出显式 prerelease 分支,
|
|
41
|
+
* 例如 `>=0.2.1-alpha.1 <0.2.2 || >=0.2.2-0 <0.3.0-0`。
|
|
42
|
+
*/
|
|
43
|
+
const tuples = [...range.matchAll(/(\d+\.\d+\.\d+)-[0-9A-Za-z.-]+/g)]
|
|
44
|
+
if (/^\^?\d+\.\d+\.\d+$/.test(range)) {
|
|
45
|
+
notes.push(
|
|
46
|
+
`${name}: "${range}" 不含 prerelease 段;若宿主是 0.x 的 rc / alpha 版本会被判不兼容`,
|
|
47
|
+
)
|
|
48
|
+
} else if (tuples.length === 1) {
|
|
49
|
+
notes.push(
|
|
50
|
+
`${name}: "${range}" 只覆盖了 ${tuples[0][1]} 这一个元组;下一个元组的预发布版` +
|
|
51
|
+
`(如 0.2.2-rc.1)会被漏掉,建议改成按元组分列的 || 形式`,
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 本地实现必须能 `node --check` 通过(语法错误的 bundle 会被静默跳过)。 */
|
|
57
|
+
const entry = join(root, pkg.main ?? 'index.js')
|
|
58
|
+
try {
|
|
59
|
+
readFileSync(entry)
|
|
60
|
+
} catch {
|
|
61
|
+
failures.push(`入口文件不存在:${entry}`)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (notes.length > 0) {
|
|
65
|
+
process.stdout.write('注意:\n')
|
|
66
|
+
for (const note of notes) process.stdout.write(` · ${note}\n`)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (failures.length > 0) {
|
|
70
|
+
process.stderr.write('兼容性门禁失败:\n')
|
|
71
|
+
for (const failure of failures) process.stderr.write(` ✗ ${failure}\n`)
|
|
72
|
+
process.exit(1)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
process.stdout.write('✓ 兼容性门禁通过(peerDependencies 不会被判不兼容)\n')
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 盯守某个账号是否被投放活动(只读)。
|
|
4
|
+
*
|
|
5
|
+
* 用途:区分「还没轮到」和「不会被轮到」—— 前者 deliveries/plans 会在某次轮询里
|
|
6
|
+
* 变非空,后者永远不会。森也的 1103 是 00:04:53 才被授予的,说明服务端是分批下发,
|
|
7
|
+
* 单次探测为空不足以判断资格。
|
|
8
|
+
*
|
|
9
|
+
* 用法:
|
|
10
|
+
* node scripts/watch-marketing.mjs <ACCOUNT_ID> [--interval 60] [--for 60]
|
|
11
|
+
*
|
|
12
|
+
* --interval 秒,默认 60
|
|
13
|
+
* --for 最多跑多少分钟,默认 60(到点自动停)
|
|
14
|
+
*
|
|
15
|
+
* 只读:不 claim、不 mint captcha、不发 marketing touch/action(confirm/cancel 都会
|
|
16
|
+
* 改变服务端对后续投放的行为,这里一律不碰)。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { existsSync } from 'node:fs'
|
|
20
|
+
import { join } from 'node:path'
|
|
21
|
+
|
|
22
|
+
const GATED_MIN = '3.16.3'
|
|
23
|
+
const ORIGIN = 'https://zcode.z.ai'
|
|
24
|
+
|
|
25
|
+
const accountId = process.argv[2]
|
|
26
|
+
const flag = (name, fallback) => {
|
|
27
|
+
const index = process.argv.indexOf(`--${name}`)
|
|
28
|
+
if (index === -1) return fallback
|
|
29
|
+
const value = Number(process.argv[index + 1])
|
|
30
|
+
return Number.isFinite(value) && value > 0 ? value : fallback
|
|
31
|
+
}
|
|
32
|
+
const intervalSec = flag('interval', 60)
|
|
33
|
+
const forMinutes = flag('for', 60)
|
|
34
|
+
|
|
35
|
+
if (typeof accountId !== 'string' || !/^[0-9a-f-]{36}$/.test(accountId)) {
|
|
36
|
+
console.error('用法:node scripts/watch-marketing.mjs <ACCOUNT_ID> [--interval 60] [--for 60]')
|
|
37
|
+
process.exit(2)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function cmpVersion(a, b) {
|
|
41
|
+
const seg = (v) => String(v).split('.').map((p) => { const m = /^\s*(\d+)/.exec(p); return m ? Number(m[1]) : 0 })
|
|
42
|
+
const l = seg(a), r = seg(b)
|
|
43
|
+
for (let i = 0; i < Math.max(l.length, r.length); i += 1) {
|
|
44
|
+
const x = l[i] ?? 0, y = r[i] ?? 0
|
|
45
|
+
if (x !== y) return x < y ? -1 : 1
|
|
46
|
+
}
|
|
47
|
+
return 0
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function gatedVersion(credential) {
|
|
51
|
+
const v = typeof credential?.app_version === 'string' ? credential.app_version.trim() : ''
|
|
52
|
+
if (!/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/.test(v)) return GATED_MIN
|
|
53
|
+
return cmpVersion(v, GATED_MIN) < 0 ? GATED_MIN : v
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function loadCredential(id) {
|
|
57
|
+
const dataDir = [join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh', 'zcode-start-plan')]
|
|
58
|
+
.find((dir) => existsSync(dir))
|
|
59
|
+
if (dataDir === undefined) throw new Error('找不到 ~/.dsh/zcode-start-plan')
|
|
60
|
+
const { DatabaseSync } = await import('node:sqlite')
|
|
61
|
+
const db = new DatabaseSync(join(dataDir, 'accounts.db'), { readOnly: true })
|
|
62
|
+
const row = db.prepare('select * from accounts where id = ?').get(id)
|
|
63
|
+
db.close()
|
|
64
|
+
if (row === undefined) throw new Error(`账号不存在:${id}`)
|
|
65
|
+
const credential = typeof row.credential === 'string' ? JSON.parse(row.credential) : row.credential
|
|
66
|
+
return { credential, nickname: row.nickname ?? id }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function headersFor(credential) {
|
|
70
|
+
const version = gatedVersion(credential)
|
|
71
|
+
return {
|
|
72
|
+
'User-Agent': `ZCode/${version}`,
|
|
73
|
+
'HTTP-Referer': ORIGIN,
|
|
74
|
+
'X-Title': 'Z Code@electron',
|
|
75
|
+
'X-ZCode-App-Version': version,
|
|
76
|
+
'X-Release-Channel': 'production',
|
|
77
|
+
'X-Client-Language': 'zh-CN',
|
|
78
|
+
'X-Client-Timezone': 'Asia/Shanghai',
|
|
79
|
+
'X-Device-Mid': credential.device_mid,
|
|
80
|
+
'X-Platform': 'win32-x64',
|
|
81
|
+
'X-Os-Category': 'windows',
|
|
82
|
+
'X-Os-Version': '10.0.19045',
|
|
83
|
+
'X-ZCode-Agent': 'glm',
|
|
84
|
+
'X-Session-Id': credential.session_id ?? crypto.randomUUID(),
|
|
85
|
+
'X-ZCode-Session-Type': 'other',
|
|
86
|
+
'X-Request-Id': crypto.randomUUID(),
|
|
87
|
+
'X-ZCode-Trace-Id': crypto.randomUUID(),
|
|
88
|
+
'anthropic-version': '2023-06-01',
|
|
89
|
+
Accept: 'application/json',
|
|
90
|
+
authorization: `Bearer ${credential.zcode_jwt}`,
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function findClaimButtons(node, depth = 0, out = []) {
|
|
95
|
+
if (depth > 10 || node === null || typeof node !== 'object') return out
|
|
96
|
+
if (Array.isArray(node)) { for (const item of node) findClaimButtons(item, depth + 1, out); return out }
|
|
97
|
+
const type = node.action?.type ?? node.action_type ?? node.type
|
|
98
|
+
if (typeof type === 'string' && /claim/i.test(type)) out.push(node)
|
|
99
|
+
for (const value of Object.values(node)) findClaimButtons(value, depth + 1, out)
|
|
100
|
+
return out
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const fmt = (sec) => (typeof sec === 'number' && sec > 0 ? new Date(sec * 1000).toLocaleString([], { hour12: false }) : '-')
|
|
104
|
+
|
|
105
|
+
async function once(credential) {
|
|
106
|
+
const headers = headersFor(credential)
|
|
107
|
+
const [marketing, balance] = await Promise.all([
|
|
108
|
+
fetch(`${ORIGIN}/api/v1/marketing/touch?seq=0`, { headers, signal: AbortSignal.timeout(25_000) })
|
|
109
|
+
.then(async (r) => ({ status: r.status, json: await r.json().catch(() => undefined) }))
|
|
110
|
+
.catch((e) => ({ status: undefined, error: String(e?.message ?? e) })),
|
|
111
|
+
fetch(`${ORIGIN}/api/v1/zcode-plan/billing/balance`, { headers, signal: AbortSignal.timeout(25_000) })
|
|
112
|
+
.then(async (r) => ({ status: r.status, json: await r.json().catch(() => undefined) }))
|
|
113
|
+
.catch((e) => ({ status: undefined, error: String(e?.message ?? e) })),
|
|
114
|
+
])
|
|
115
|
+
const deliveries = marketing.json?.data?.deliveries
|
|
116
|
+
const plans = Array.isArray(balance.json?.data?.plans) ? balance.json.data.plans : []
|
|
117
|
+
const buckets = Array.isArray(balance.json?.data?.balances) ? balance.json.data.balances : []
|
|
118
|
+
const claims = Array.isArray(deliveries) ? deliveries.flatMap((d) => findClaimButtons(d)) : []
|
|
119
|
+
return {
|
|
120
|
+
serverTime: balance.json?.data?.server_time ?? marketing.json?.data?.server_time,
|
|
121
|
+
marketingStatus: marketing.status,
|
|
122
|
+
deliveries: Array.isArray(deliveries) ? deliveries.length : `非数组(${typeof deliveries})`,
|
|
123
|
+
claimButtons: claims.length,
|
|
124
|
+
plans: plans.map((p) => ({ id: p.plan_id, status: p.status, starts_at: fmt(p.starts_at), ends_at: fmt(p.ends_at) })),
|
|
125
|
+
buckets: buckets.map((b) => ({ plan: b.plan_id, total: b.total_units, used: b.used_units, remaining: b.remaining_units })),
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const { credential, nickname } = await loadCredential(accountId)
|
|
130
|
+
const deadline = Date.now() + forMinutes * 60_000
|
|
131
|
+
console.log(`盯守 ${nickname} (${accountId}) 间隔 ${intervalSec}s 上限 ${forMinutes} 分钟`)
|
|
132
|
+
console.log('(只读:不 claim、不 mint captcha、不发 confirm/cancel)\n')
|
|
133
|
+
|
|
134
|
+
let round = 0
|
|
135
|
+
while (Date.now() < deadline) {
|
|
136
|
+
round += 1
|
|
137
|
+
const startedAt = new Date().toLocaleTimeString([], { hour12: false })
|
|
138
|
+
const result = await once(credential)
|
|
139
|
+
const hit = result.claimButtons > 0 || result.plans.length > 0 || result.buckets.length > 0
|
|
140
|
+
console.log(
|
|
141
|
+
`[${startedAt}] #${round} server_time=${result.serverTime} ` +
|
|
142
|
+
`deliveries=${result.deliveries} claimButtons=${result.claimButtons} plans=${result.plans.length} buckets=${result.buckets.length}` +
|
|
143
|
+
`${hit ? ' ← 命中' : ''}`,
|
|
144
|
+
)
|
|
145
|
+
if (result.plans.length > 0) console.log(` plans: ${JSON.stringify(result.plans)}`)
|
|
146
|
+
if (result.buckets.length > 0) console.log(` buckets: ${JSON.stringify(result.buckets)}`)
|
|
147
|
+
if (hit) {
|
|
148
|
+
console.log('\n已观察到活动投放/权益,停止盯守。')
|
|
149
|
+
process.exit(0)
|
|
150
|
+
}
|
|
151
|
+
const wait = Math.min(intervalSec * 1000, deadline - Date.now())
|
|
152
|
+
if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait))
|
|
153
|
+
}
|
|
154
|
+
console.log(`\n${forMinutes} 分钟内未观察到任何投放或权益 —— 该账号在此期间确实没有被下发。`)
|
|
155
|
+
process.exitCode = 0
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 营销活动发现(marketing/touch)与自动领取状态机。
|
|
3
|
+
*
|
|
4
|
+
* 实证来源:ZCode 客户端 3.16.3 反编译(`createMarketingTouchService` / 分发按钮
|
|
5
|
+
* schema `{type:"claim_zcode_plan", args:{plan_id}}`)。响应形状:
|
|
6
|
+
* `{code:0, data:{server_time, language, deliveries:[{campaign_id, priority,
|
|
7
|
+
* resource_position, banner|popup:{buttons:[…]}]}}}`
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import test from 'node:test'
|
|
11
|
+
import assert from 'node:assert/strict'
|
|
12
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
13
|
+
import { tmpdir } from 'node:os'
|
|
14
|
+
import { join } from 'node:path'
|
|
15
|
+
|
|
16
|
+
import { fetchClaimablePlans } from '../lib/upstream-api.js'
|
|
17
|
+
import { createAutoClaim, loadAutoClaimState, saveAutoClaimState } from '../lib/auto-claim.js'
|
|
18
|
+
|
|
19
|
+
const CREDENTIAL = { zcode_jwt: 'jwt-1', device_mid: 'dev-1', user_id: 'u-1' }
|
|
20
|
+
|
|
21
|
+
/** 构造一个官方形状的 marketing/touch 响应体。 */
|
|
22
|
+
const touchResponse = (deliveries, { withAuth = false } = {}) => ({
|
|
23
|
+
code: 0,
|
|
24
|
+
data: {
|
|
25
|
+
server_time: 1790000000,
|
|
26
|
+
language: 'zh-CN',
|
|
27
|
+
deliveries,
|
|
28
|
+
},
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
const delivery = ({ planId, campaignId = 'camp-1', priority = 50, position = 'popup', label = '立即领取' }) => ({
|
|
32
|
+
campaign_id: campaignId,
|
|
33
|
+
priority,
|
|
34
|
+
resource_position: position,
|
|
35
|
+
...(position === 'popup'
|
|
36
|
+
? { popup: { title: { format: 'plaintext', content: '活动' }, buttons: [
|
|
37
|
+
{ text: { format: 'plaintext', content: '关闭' }, action: { type: 'close' } },
|
|
38
|
+
{ text: { format: 'plaintext', content: label }, action: { type: 'claim_zcode_plan', args: { plan_id: planId } } },
|
|
39
|
+
] } }
|
|
40
|
+
: { banner: { background: { type: 'image', image: { default: { src: 'https://x/y.png', sha256: 'a'.repeat(64) } } }, buttons: [
|
|
41
|
+
{ text: { format: 'plaintext', content: label }, action: { type: 'claim_zcode_plan', args: { plan_id: planId } } },
|
|
42
|
+
] } }),
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
const response = (body, { status = 200, seenHeaders } = {}) => ({
|
|
46
|
+
ok: status >= 200 && status < 300,
|
|
47
|
+
status,
|
|
48
|
+
headers: new Headers({ 'content-type': 'application/json' }),
|
|
49
|
+
json: async () => (typeof body === 'string' ? JSON.parse(body) : body),
|
|
50
|
+
text: async () => JSON.stringify(body),
|
|
51
|
+
...(seenHeaders ? {} : {}),
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
test('fetchClaimablePlans: 从 marketing/touch 投放按钮里提取 plan_id', async () => {
|
|
55
|
+
let seen
|
|
56
|
+
const fetchImpl = async (_url, init) => {
|
|
57
|
+
seen = init.headers
|
|
58
|
+
return response(touchResponse([
|
|
59
|
+
delivery({ planId: 'plan-a', priority: 90 }),
|
|
60
|
+
delivery({ planId: 'plan-b', campaignId: 'camp-2', priority: 30, position: 'banner' }),
|
|
61
|
+
]))
|
|
62
|
+
}
|
|
63
|
+
const plans = await fetchClaimablePlans(CREDENTIAL, fetchImpl)
|
|
64
|
+
assert.deepEqual(plans.map((plan) => plan.planId), ['plan-a', 'plan-b'], '按 priority 降序')
|
|
65
|
+
assert.equal(plans[0].campaignId, 'camp-1')
|
|
66
|
+
assert.equal(plans[0].name, '立即领取', '按钮文案作为活动名')
|
|
67
|
+
assert.equal(seen['X-Device-Mid'], 'dev-1')
|
|
68
|
+
assert.equal(seen['X-Client-Language'], 'zh-CN', '服务端按语言过滤投放')
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
test('fetchClaimablePlans: 同 planId 去重;非 claim 按钮忽略(双来源后同 plan 保留首见 campaign)', async () => {
|
|
72
|
+
const fetchImpl = async () => response(touchResponse([
|
|
73
|
+
delivery({ planId: 'plan-a', campaignId: 'camp-low', priority: 10 }),
|
|
74
|
+
delivery({ planId: 'plan-a', campaignId: 'camp-high', priority: 80 }),
|
|
75
|
+
delivery({ planId: '', priority: 99 }),
|
|
76
|
+
]))
|
|
77
|
+
const plans = await fetchClaimablePlans(CREDENTIAL, fetchImpl)
|
|
78
|
+
assert.equal(plans.length, 1)
|
|
79
|
+
/**
|
|
80
|
+
* 0.8.0 对齐参考实现的合并语义:同 planId **preview 优先 / 首见保留**,
|
|
81
|
+
* 只补 campaignId,不再按 priority 覆盖 —— 领取成功后回执要发到
|
|
82
|
+
* 「第一次见到它」的那个 campaign。
|
|
83
|
+
*/
|
|
84
|
+
assert.equal(plans[0].campaignId, 'camp-low')
|
|
85
|
+
assert.equal(plans[0].priority, 10)
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
test('fetchClaimablePlans: 非 200 / 坏 JSON / 空投放 → 空数组不抛错', async () => {
|
|
89
|
+
assert.deepEqual(await fetchClaimablePlans(CREDENTIAL, async () => response('no', { status: 500 })), [])
|
|
90
|
+
const badJson = { ok: true, status: 200, headers: new Headers(), json: async () => { throw new Error('x') }, text: async () => 'x' }
|
|
91
|
+
assert.deepEqual(await fetchClaimablePlans(CREDENTIAL, async () => badJson), [])
|
|
92
|
+
assert.deepEqual(await fetchClaimablePlans(CREDENTIAL, async () => response(touchResponse([]))), [])
|
|
93
|
+
const networkFail = async () => { throw new Error('ECONNRESET') }
|
|
94
|
+
assert.deepEqual(await fetchClaimablePlans(CREDENTIAL, networkFail), [])
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
/** autoClaim 的最小池。 */
|
|
98
|
+
function fakePool(credentials = [{ id: 'acct-a', credential: CREDENTIAL }]) {
|
|
99
|
+
const state = credentials.map((entry) => ({ nickname: entry.id, enabled: true, ...entry }))
|
|
100
|
+
return {
|
|
101
|
+
list: (_options) => state,
|
|
102
|
+
get: (id) => state.find((entry) => entry.id === id),
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 开关语义:探测永远自动,**领取是开关项**(用例验证领取侧,故显式开启)。 */
|
|
107
|
+
const enabled = (extra) => ({ enabled: true, ...extra })
|
|
108
|
+
|
|
109
|
+
function withStateDir(fn) {
|
|
110
|
+
return async () => {
|
|
111
|
+
const dir = mkdtempSync(join(tmpdir(), 'zsp-auto-claim-'))
|
|
112
|
+
try {
|
|
113
|
+
await fn(dir)
|
|
114
|
+
} finally {
|
|
115
|
+
rmSync(dir, { recursive: true, force: true })
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
test('autoClaim: 默认关闭 —— tick 空转,绝不代替用户领取;拨盘即时生效', withStateDir(async (dir) => {
|
|
121
|
+
const stateFile = join(dir, 'auto-claim-state.json')
|
|
122
|
+
const pool = fakePool()
|
|
123
|
+
let minted = 0
|
|
124
|
+
let claimed = 0
|
|
125
|
+
let scanned = 0
|
|
126
|
+
const autoClaim = createAutoClaim({
|
|
127
|
+
pool,
|
|
128
|
+
client: { mintCaptcha: async () => { minted += 1; return { param: 'p', region: 'cn' } } },
|
|
129
|
+
fetchClaimablePlans: async () => { scanned += 1; return [{ planId: 'plan-a' }] },
|
|
130
|
+
claimPlan: async () => { claimed += 1; return { ok: true, code: 0 } },
|
|
131
|
+
stateFile,
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
assert.equal(autoClaim.isEnabled(), false, '未显式开启 = 关')
|
|
135
|
+
assert.deepEqual(await autoClaim.tick(), [], '关闭时 tick 不扫、不领')
|
|
136
|
+
assert.equal(scanned, 0, '关闭时连探测都不做(探测由面板/CLI 触发)')
|
|
137
|
+
assert.equal(minted, 0, '绝不烧 captcha')
|
|
138
|
+
assert.equal(claimed, 0)
|
|
139
|
+
|
|
140
|
+
/** 打开后立即生效(无需重启);已领集合从空开始正常记录。 */
|
|
141
|
+
assert.equal(autoClaim.setEnabled(true), true)
|
|
142
|
+
await autoClaim.tick()
|
|
143
|
+
assert.equal(claimed, 1, '开启后才真正领取')
|
|
144
|
+
assert.equal(autoClaim.stats().enabled, true)
|
|
145
|
+
|
|
146
|
+
/** 再关掉:记录保留,不再新增。 */
|
|
147
|
+
assert.equal(autoClaim.setEnabled(false), false)
|
|
148
|
+
assert.deepEqual(await autoClaim.tick(), [])
|
|
149
|
+
assert.equal(claimed, 1)
|
|
150
|
+
assert.equal(autoClaim.stats().seenCount, 1, '关掉不清历史记录')
|
|
151
|
+
assert.equal(autoClaim.stats().enabled, false)
|
|
152
|
+
}))
|
|
153
|
+
|
|
154
|
+
test('autoClaim: 发现新 planId 才烧 captcha;终态码记 seen 不再重试', withStateDir(async (dir) => {
|
|
155
|
+
const stateFile = join(dir, 'auto-claim-state.json')
|
|
156
|
+
const pool = fakePool()
|
|
157
|
+
const mints = []
|
|
158
|
+
const claims = []
|
|
159
|
+
const autoClaim = createAutoClaim(enabled({
|
|
160
|
+
pool,
|
|
161
|
+
client: { mintCaptcha: async () => { mints.push(1); return { param: `p-${mints.length}`, region: 'cn' } } },
|
|
162
|
+
fetchClaimablePlans: async () => [{ planId: 'plan-a', campaignId: 'camp-1', name: '活动A' }],
|
|
163
|
+
claimPlan: async (_credential, planId) => {
|
|
164
|
+
claims.push(planId)
|
|
165
|
+
return { ok: true, code: 0 }
|
|
166
|
+
},
|
|
167
|
+
stateFile,
|
|
168
|
+
now: () => 1_000,
|
|
169
|
+
}))
|
|
170
|
+
|
|
171
|
+
const first = await autoClaim.tick()
|
|
172
|
+
assert.equal(claims.length, 1)
|
|
173
|
+
assert.equal(first[0].ok, true)
|
|
174
|
+
assert.equal(autoClaim.seenSnapshot()['acct-a']['plan-a'].code, 0)
|
|
175
|
+
assert.equal(readFileSync(stateFile, 'utf8').includes('plan-a'), true, '已持久化')
|
|
176
|
+
|
|
177
|
+
/** 第二轮:同一 planId 已是终态 → 不再 mint、不再 claim。 */
|
|
178
|
+
await autoClaim.tick()
|
|
179
|
+
assert.equal(mints.length, 1, 'captcha 不重复烧')
|
|
180
|
+
assert.equal(claims.length, 1)
|
|
181
|
+
}))
|
|
182
|
+
|
|
183
|
+
test('autoClaim: 非终态码(网络/异常)不记 seen,下轮重试', withStateDir(async (dir) => {
|
|
184
|
+
const stateFile = join(dir, 'auto-claim-state.json')
|
|
185
|
+
const pool = fakePool()
|
|
186
|
+
let calls = 0
|
|
187
|
+
const autoClaim = createAutoClaim(enabled({
|
|
188
|
+
pool,
|
|
189
|
+
client: { mintCaptcha: async () => ({ param: 'p', region: 'cn' }) },
|
|
190
|
+
fetchClaimablePlans: async () => [{ planId: 'plan-x' }],
|
|
191
|
+
claimPlan: async () => {
|
|
192
|
+
calls += 1
|
|
193
|
+
return { ok: false, code: 999, message: '服务器开小差' }
|
|
194
|
+
},
|
|
195
|
+
stateFile,
|
|
196
|
+
}))
|
|
197
|
+
await autoClaim.tick()
|
|
198
|
+
await autoClaim.tick()
|
|
199
|
+
assert.equal(calls, 2, '非终态 → 每轮重试')
|
|
200
|
+
assert.equal(autoClaim.seenSnapshot()['acct-a']?.['plan-x'], undefined, '非终态绝不入 seen')
|
|
201
|
+
|
|
202
|
+
/** captcha 失败同样不记 seen。 */
|
|
203
|
+
let mintCalls = 0
|
|
204
|
+
const failingCaptcha = createAutoClaim(enabled({
|
|
205
|
+
pool,
|
|
206
|
+
client: { mintCaptcha: async () => { mintCalls += 1; throw new Error('CDP 不可达') } },
|
|
207
|
+
fetchClaimablePlans: async () => [{ planId: 'plan-y' }],
|
|
208
|
+
claimPlan: async () => { throw new Error('should not be called') },
|
|
209
|
+
stateFile,
|
|
210
|
+
}))
|
|
211
|
+
const results = await failingCaptcha.tick()
|
|
212
|
+
assert.equal(results[0].ok, false)
|
|
213
|
+
assert.match(results[0].error, /CDP 不可达/)
|
|
214
|
+
assert.equal(failingCaptcha.seenSnapshot()['acct-a']?.['plan-y'], undefined, 'captcha 失败绝不入 seen')
|
|
215
|
+
assert.equal(failingCaptcha.stats().seenCount, 0)
|
|
216
|
+
}))
|
|
217
|
+
|
|
218
|
+
test('autoClaim: 1003(已领过)与 1005(领完)同样入终态', withStateDir(async (dir) => {
|
|
219
|
+
const pool = fakePool([
|
|
220
|
+
{ id: 'acct-a', credential: CREDENTIAL },
|
|
221
|
+
{ id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
|
|
222
|
+
])
|
|
223
|
+
const autoClaim = createAutoClaim(enabled({
|
|
224
|
+
pool,
|
|
225
|
+
client: { mintCaptcha: async () => ({ param: 'p', region: 'cn' }) },
|
|
226
|
+
fetchClaimablePlans: async (credential) => [
|
|
227
|
+
{ planId: credential.user_id === 'u-1' ? 'plan-claimed' : 'plan-gone' },
|
|
228
|
+
],
|
|
229
|
+
claimPlan: async (credential) => (credential.user_id === 'u-1' ? { ok: true, code: 1003, alreadyClaimed: true } : { ok: false, code: 1005 }),
|
|
230
|
+
stateFile: join(dir, 'state.json'),
|
|
231
|
+
}))
|
|
232
|
+
await autoClaim.tick()
|
|
233
|
+
const seen = autoClaim.seenSnapshot()
|
|
234
|
+
assert.equal(seen['acct-a']['plan-claimed'].code, 1003)
|
|
235
|
+
assert.equal(seen['acct-b']['plan-gone'].code, 1005)
|
|
236
|
+
assert.equal(autoClaim.stats().seenCount, 2)
|
|
237
|
+
}))
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* confirm 回执纪律(docs/upstream-protocol.md「领取与活动发现」):
|
|
241
|
+
* **只在 `0`/`1003` 后发 `confirm`**。失败时发 = 叫服务端别再投了(白丢机会);
|
|
242
|
+
* 成功不发 = 服务端重复投放(每轮白烧 captcha)。
|
|
243
|
+
*/
|
|
244
|
+
test('autoClaim: confirm 只在 0/1003 后发;1005/网络失败绝不发', withStateDir(async (dir) => {
|
|
245
|
+
const pool = fakePool([
|
|
246
|
+
{ id: 'acct-a', credential: CREDENTIAL },
|
|
247
|
+
{ id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
|
|
248
|
+
{ id: 'acct-c', credential: { ...CREDENTIAL, user_id: 'u-3' } },
|
|
249
|
+
])
|
|
250
|
+
const confirms = []
|
|
251
|
+
const autoClaim = createAutoClaim(enabled({
|
|
252
|
+
pool,
|
|
253
|
+
client: { mintCaptcha: async () => ({ param: 'p', region: 'cn' }) },
|
|
254
|
+
fetchClaimablePlans: async (credential) => [
|
|
255
|
+
{ planId: `plan-${credential.user_id}`, campaignId: `camp-${credential.user_id}` },
|
|
256
|
+
],
|
|
257
|
+
claimPlan: async (credential) => {
|
|
258
|
+
if (credential.user_id === 'u-1') return { ok: true, code: 0 }
|
|
259
|
+
if (credential.user_id === 'u-2') return { ok: true, code: 1003, alreadyClaimed: true }
|
|
260
|
+
return { ok: false, code: 1005 }
|
|
261
|
+
},
|
|
262
|
+
reportMarketingAction: async (_credential, campaignId) => { confirms.push(campaignId) },
|
|
263
|
+
stateFile: join(dir, 'state.json'),
|
|
264
|
+
}))
|
|
265
|
+
await autoClaim.tick()
|
|
266
|
+
assert.deepEqual(confirms.sort(), ['camp-u-1', 'camp-u-2'], '0/1003 发 confirm,1005 不发')
|
|
267
|
+
}))
|
|
268
|
+
|
|
269
|
+
test('autoClaim: 查投放前补活跃上报(不补则 preview 恒空,自动领取静默失效)', withStateDir(async (dir) => {
|
|
270
|
+
const pool = fakePool()
|
|
271
|
+
const activations = []
|
|
272
|
+
let sawPlansFirst = false
|
|
273
|
+
let activationBeforePlans = true
|
|
274
|
+
const autoClaim = createAutoClaim(enabled({
|
|
275
|
+
pool,
|
|
276
|
+
client: { mintCaptcha: async () => ({ param: 'p', region: 'cn' }) },
|
|
277
|
+
reportActivation: async () => { activations.push(1) },
|
|
278
|
+
fetchClaimablePlans: async () => {
|
|
279
|
+
if (activations.length === 0) activationBeforePlans = false
|
|
280
|
+
return []
|
|
281
|
+
},
|
|
282
|
+
stateFile: join(dir, 'state.json'),
|
|
283
|
+
}))
|
|
284
|
+
await autoClaim.tick()
|
|
285
|
+
assert.equal(activations.length, 1, '每个启用账号每轮补一次')
|
|
286
|
+
assert.equal(activationBeforePlans, true, 'reportActivation 必须先于 fetchClaimablePlans')
|
|
287
|
+
assert.equal(sawPlansFirst, false)
|
|
288
|
+
}))
|
|
289
|
+
|
|
290
|
+
test('autoClaim: 状态文件坏 / 版本不识别 → 空状态起跑;禁用账号跳过', withStateDir(async (dir) => {
|
|
291
|
+
const stateFile = join(dir, 'state.json')
|
|
292
|
+
writeFileSync(stateFile, '{broken json')
|
|
293
|
+
assert.deepEqual(loadAutoClaimState(stateFile), {})
|
|
294
|
+
writeFileSync(stateFile, JSON.stringify({ version: 99, seen: { a: { p: { code: 0 } } } }))
|
|
295
|
+
assert.deepEqual(loadAutoClaimState(stateFile), {})
|
|
296
|
+
/** 非终态码(如 999)在加载时被剔除。 */
|
|
297
|
+
writeFileSync(stateFile, JSON.stringify({ version: 1, seen: { acct: { keep: { code: 1003, at: 5 }, drop: { code: 999, at: 5 } } } }))
|
|
298
|
+
assert.deepEqual(loadAutoClaimState(stateFile), { acct: { keep: { code: 1003, at: 5 } } })
|
|
299
|
+
|
|
300
|
+
const pool = fakePool([
|
|
301
|
+
{ id: 'acct-on', credential: CREDENTIAL },
|
|
302
|
+
{ id: 'acct-off', credential: { ...CREDENTIAL, user_id: 'u-2' }, enabled: false },
|
|
303
|
+
])
|
|
304
|
+
const probed = []
|
|
305
|
+
const autoClaim = createAutoClaim(enabled({
|
|
306
|
+
pool,
|
|
307
|
+
client: { mintCaptcha: async () => ({ param: 'p', region: 'cn' }) },
|
|
308
|
+
fetchClaimablePlans: async (credential) => { probed.push(credential.user_id); return [] },
|
|
309
|
+
claimPlan: async () => ({}),
|
|
310
|
+
stateFile,
|
|
311
|
+
}))
|
|
312
|
+
await autoClaim.tick()
|
|
313
|
+
assert.deepEqual(probed, ['u-1'], '停用账号不参与扫描')
|
|
314
|
+
/** 父路径是文件 → mkdir 必失败 → 返回 false 而不是抛(轮询链路绝不能崩)。 */
|
|
315
|
+
const blocker = join(dir, 'blocker.txt')
|
|
316
|
+
writeFileSync(blocker, 'x')
|
|
317
|
+
assert.equal(saveAutoClaimState(join(blocker, 'child', 's.json'), {}), false, '目录建不出时报告失败而不是抛')
|
|
318
|
+
}))
|