dsh-zcode-startplan 0.0.0-stage → 0.4.5

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.
@@ -0,0 +1,654 @@
1
+ /**
2
+ * 阿里云 captcha 产出 —— 以**任意 Electron/Chromium 宿主**为载体(默认 DSH 自己的窗口)。
3
+ *
4
+ * ## 为什么不额外起浏览器
5
+ *
6
+ * captcha 是**网页 SDK**,不是 Electron 专有 API:
7
+ * script: https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js
8
+ * config: window.AliyunCaptchaConfig = { region, prefix }
9
+ * call: initAliyunCaptcha({ SceneId, mode, element, button, getInstance, success, ... })
10
+ * param: instance.startTracelessVerification() → success(param)
11
+ *
12
+ * 参考实现把这段脚本注入**开源 ZCode 自己的 Electron** 里的一个离屏隐藏 iframe
13
+ * (因为 Electron 不支持 `Target.createTarget` / `PUT /json/new`,且壳 renderer 的
14
+ * `file://` origin 会被风控拒绝)。DSH 侧同理:连 DSH 桌面端的 CDP 端口
15
+ * (`--remote-debugging-port`),在它的 renderer 里挂**离屏 iframe**。
16
+ *
17
+ * ## 实测硬约束(沿用参考实现,不要"优化")
18
+ *
19
+ * 1. 页面 origin 必须真实 https(`about:blank` 的 origin 是 "null",二次 mint 必 F001);
20
+ * 2. ~~同页空闲 >8s 后必失效~~ —— **该结论已被推翻**:F001 的真因是「DOM 被重置而
21
+ * SDK 全局实例仍在」,与空闲无关。故复用路径**绝不重置 DOM**(`prepared` 守卫);
22
+ * 3. mint 失败必须作废该帧(坏会话会传染),换新帧重试一次;
23
+ * 4. `--headless` 一律失败(宿主是真 GUI 进程,天然满足)。
24
+ */
25
+
26
+ import { CAPTCHA_SDK_URL, CAPTCHA_PAGE_ORIGIN } from './sdk-page.js'
27
+
28
+ /** 默认 CDP 端口(DSH 桌面端若以 --remote-debugging-port=9229 启动即命中)。 */
29
+ export const DEFAULT_DEBUG_PORT = 9229
30
+
31
+ const FRAME_ID_PREFIX = 'dsh-zcode-captcha-frame-'
32
+
33
+ /**
34
+ * 生产传输实现:flatten 模式的 CDP over WebSocket(Node 22+ 内置 WebSocket)。
35
+ */
36
+ class AttachedHostTransport {
37
+ #ws
38
+ #nextId = 0
39
+ #pending = new Map()
40
+ #iframeQueue = []
41
+ #iframeWaiters = []
42
+
43
+ constructor(ws) {
44
+ this.#ws = ws
45
+ ws.addEventListener('message', (event) => {
46
+ let message
47
+ try {
48
+ message = JSON.parse(String(event.data))
49
+ } catch {
50
+ return
51
+ }
52
+ if (message.method === 'Target.attachedToTarget') {
53
+ const sessionId = message.params?.sessionId
54
+ const type = message.params?.targetInfo?.type
55
+ if (typeof sessionId === 'string' && type === 'iframe') {
56
+ const waiter = this.#iframeWaiters.shift()
57
+ if (waiter !== undefined) waiter(sessionId)
58
+ else this.#iframeQueue.push(sessionId)
59
+ }
60
+ return
61
+ }
62
+ if (message.id === undefined) return
63
+ const slot = this.#pending.get(message.id)
64
+ if (slot === undefined) return
65
+ this.#pending.delete(message.id)
66
+ if (message.error !== undefined) slot.reject(new Error(JSON.stringify(message.error)))
67
+ else slot.resolve(message.result)
68
+ })
69
+ }
70
+
71
+ #sendRaw(method, params, sessionId, timeoutMs) {
72
+ const id = ++this.#nextId
73
+ return new Promise((resolve, reject) => {
74
+ this.#pending.set(id, { resolve, reject })
75
+ const payload = { id, method, params }
76
+ if (sessionId !== undefined) payload.sessionId = sessionId
77
+ try {
78
+ this.#ws.send(JSON.stringify(payload))
79
+ } catch (error) {
80
+ this.#pending.delete(id)
81
+ reject(error instanceof Error ? error : new Error(String(error)))
82
+ return
83
+ }
84
+ const timer = setTimeout(() => {
85
+ if (this.#pending.has(id)) {
86
+ this.#pending.delete(id)
87
+ reject(new Error(`CDP ${method} 超时(${timeoutMs}ms)`))
88
+ }
89
+ }, timeoutMs)
90
+ timer.unref?.()
91
+ })
92
+ }
93
+
94
+ send(method, params = {}, timeoutMs = 30_000) {
95
+ return this.#sendRaw(method, params, undefined, timeoutMs)
96
+ }
97
+
98
+ sendToSession(sessionId, method, params = {}, timeoutMs = 30_000) {
99
+ return this.#sendRaw(method, params, sessionId, timeoutMs)
100
+ }
101
+
102
+ async waitForIframeSession(timeoutMs) {
103
+ const queued = this.#iframeQueue.shift()
104
+ if (queued !== undefined) return queued
105
+ return await new Promise((resolve) => {
106
+ let settled = false
107
+ const onSession = (sessionId) => {
108
+ if (settled) return
109
+ settled = true
110
+ clearTimeout(timer)
111
+ resolve(sessionId)
112
+ }
113
+ const timer = setTimeout(() => {
114
+ if (settled) return
115
+ settled = true
116
+ this.#iframeWaiters = this.#iframeWaiters.filter((waiter) => waiter !== onSession)
117
+ resolve(undefined)
118
+ }, timeoutMs)
119
+ timer.unref?.()
120
+ this.#iframeWaiters.push(onSession)
121
+ })
122
+ }
123
+
124
+ close() {
125
+ try {
126
+ this.#ws.close()
127
+ } catch {
128
+ // 已关闭。
129
+ }
130
+ }
131
+ }
132
+
133
+ async function defaultHostTransportFactory(pageWebSocketDebuggerUrl) {
134
+ const ws = new WebSocket(pageWebSocketDebuggerUrl)
135
+ await new Promise((resolve, reject) => {
136
+ const timer = setTimeout(() => reject(new Error('连接调试端口超时(10s)')), 10_000)
137
+ timer.unref?.()
138
+ ws.addEventListener('open', () => {
139
+ clearTimeout(timer)
140
+ resolve()
141
+ }, { once: true })
142
+ ws.addEventListener('error', () => {
143
+ clearTimeout(timer)
144
+ reject(new Error('连接调试端口失败'))
145
+ }, { once: true })
146
+ })
147
+ return new AttachedHostTransport(ws)
148
+ }
149
+
150
+ /** 构造「创建离屏 iframe」的表达式(离屏、不可见、不可点、不参与布局)。 */
151
+ export function buildFrameCreateExpression(frameId, origin) {
152
+ return `(() => {
153
+ const id = ${JSON.stringify(frameId)};
154
+ document.getElementById(id)?.remove();
155
+ const frame = document.createElement('iframe');
156
+ frame.id = id;
157
+ frame.setAttribute('aria-hidden', 'true');
158
+ frame.setAttribute('tabindex', '-1');
159
+ frame.style.cssText = 'position:fixed;left:-99999px;top:0;width:1px;height:1px;'
160
+ + 'border:0;opacity:0;pointer-events:none;';
161
+ frame.src = ${JSON.stringify(origin)};
162
+ document.body.appendChild(frame);
163
+ return 'created';
164
+ })()`
165
+ }
166
+
167
+ /**
168
+ * captcha 产出器(连接宿主的 Electron,只在**自己的离屏 iframe** 内活动)。
169
+ *
170
+ * 生命周期:进程内**单实例**(captcha 是设备级的,并发无益且会互相踩页面)。
171
+ * `dispose()` 只移除**我们自己的** iframe 并关闭**我们自己的** CDP 连接,
172
+ * **绝不**杀宿主进程。
173
+ */
174
+ export class CaptchaMinter {
175
+ #debugPort
176
+ #origin
177
+ #idleReuseMs
178
+ #pageWaitTimeoutMs
179
+ #frameAttachTimeoutMs
180
+ #readyTimeoutMs
181
+ #transportFactory
182
+ #fetchImpl
183
+ #sleep
184
+ #now
185
+ #log
186
+ #frameIdPrefix
187
+ #host
188
+ #reusableFrame
189
+ #pageBusy = false
190
+
191
+ constructor(options = {}) {
192
+ const envPort = Number(process.env['ZCODE_START_PLAN_CDP_PORT'] ?? '')
193
+ this.#debugPort = options.debugPort ?? (Number.isFinite(envPort) && envPort > 0 ? envPort : DEFAULT_DEBUG_PORT)
194
+ this.#origin = options.origin ?? CAPTCHA_PAGE_ORIGIN
195
+ /** 默认 Infinity:**不因空闲换帧**(预测式换帧会让每次空闲后白付 2.7s)。 */
196
+ this.#idleReuseMs = options.idleReuseMs ?? Number.POSITIVE_INFINITY
197
+ this.#pageWaitTimeoutMs = options.pageWaitTimeoutMs ?? 30_000
198
+ this.#frameAttachTimeoutMs = options.frameAttachTimeoutMs ?? 10_000
199
+ this.#readyTimeoutMs = options.readyTimeoutMs ?? 10_000
200
+ this.#transportFactory = options.transportFactory ?? defaultHostTransportFactory
201
+ this.#fetchImpl = options.fetchImpl ?? globalThis.fetch
202
+ this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => {
203
+ const timer = setTimeout(resolve, ms)
204
+ timer.unref?.()
205
+ }))
206
+ this.#now = options.now ?? (() => Date.now())
207
+ this.#log = options.log ?? (() => {})
208
+ this.#frameIdPrefix = `${FRAME_ID_PREFIX}${Math.random().toString(36).slice(2, 10)}-`
209
+ }
210
+
211
+ get #baseUrl() {
212
+ return `http://127.0.0.1:${this.#debugPort}`
213
+ }
214
+
215
+ /** 探测宿主的调试端口与 renderer page target 是否可达(原因文案必须可操作)。 */
216
+ async probe() {
217
+ try {
218
+ const response = await this.#fetchImpl(`${this.#baseUrl}/json/version`, {
219
+ signal: AbortSignal.timeout(this.#readyTimeoutMs),
220
+ })
221
+ if (!response.ok) return { ok: false, reason: `调试端口返回 HTTP ${response.status}` }
222
+ const targets = await this.#listTargets()
223
+ if (targets.find((item) => item.type === 'page') === undefined) {
224
+ return { ok: false, reason: '调试端口可达,但没有找到 renderer 页面目标(宿主可能还在启动中)' }
225
+ }
226
+ return { ok: true }
227
+ } catch (error) {
228
+ return {
229
+ ok: false,
230
+ reason:
231
+ `连不上宿主的调试端口(127.0.0.1:${this.#debugPort}):` +
232
+ `${error instanceof Error ? error.message : String(error)}。` +
233
+ '请以 --remote-debugging-port 启动 DSH 桌面端(或设 ZCODE_START_PLAN_CDP_PORT)。',
234
+ }
235
+ }
236
+ }
237
+
238
+ async #listTargets() {
239
+ const response = await this.#fetchImpl(`${this.#baseUrl}/json/list`, {
240
+ signal: AbortSignal.timeout(this.#readyTimeoutMs),
241
+ })
242
+ if (!response.ok) throw new Error(`读取目标列表失败(HTTP ${response.status})`)
243
+ const parsed = await response.json()
244
+ return Array.isArray(parsed) ? parsed : []
245
+ }
246
+
247
+ async #ensureHost() {
248
+ if (this.#host !== undefined) return this.#host
249
+ const targets = await this.#listTargets()
250
+ const page = targets.find((item) => item.type === 'page' && typeof item.webSocketDebuggerUrl === 'string')
251
+ if (page === undefined) throw new Error('没有找到宿主的 renderer 页面目标')
252
+ const host = await this.#transportFactory(page.webSocketDebuggerUrl)
253
+ await host.send('Target.setAutoAttach', { autoAttach: true, flatten: true, waitForDebuggerOnStart: false })
254
+ this.#host = host
255
+ return host
256
+ }
257
+
258
+ /**
259
+ * 产出一个**新鲜**的 captcha param。
260
+ *
261
+ * 复用策略:失败重试 → 丢弃旧帧建新帧;空闲超窗口 → 建新帧;否则复用(不重置 DOM)。
262
+ * 任一次失败 → 作废帧 + 换新帧重试一次(自愈链)。
263
+ */
264
+ async mint(config, options = {}) {
265
+ const attempts = 2
266
+ let lastError
267
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
268
+ if (options.signal?.aborted === true) throw lastError ?? new Error('captcha 产出已取消')
269
+ let frame
270
+ try {
271
+ frame = await this.#acquireFrame(attempt > 1)
272
+ } catch (error) {
273
+ lastError = error instanceof Error ? error : new Error(String(error))
274
+ if (attempt < attempts) {
275
+ await this.#sleep(300)
276
+ continue
277
+ }
278
+ throw lastError
279
+ }
280
+ try {
281
+ const outcome = await this.#mintInFrame(frame, config)
282
+ frame.lastUsedAt = this.#now()
283
+ return outcome
284
+ } catch (error) {
285
+ lastError = error instanceof Error ? error : new Error(String(error))
286
+ await this.#discardFrame(frame)
287
+ if (attempt < attempts) await this.#sleep(300)
288
+ } finally {
289
+ /** ⚠ 必须无条件复位(只在部分路径复位会让后续 mint 死等)。 */
290
+ this.#pageBusy = false
291
+ }
292
+ }
293
+ throw lastError ?? new Error('captcha 产出失败(未知原因)')
294
+ }
295
+
296
+ async #mintInFrame(frame, config) {
297
+ const host = await this.#ensureHost()
298
+ const session = frame.sessionId
299
+
300
+ if (!frame.prepared) {
301
+ await this.#prepareFrame(host, session)
302
+ frame.prepared = true
303
+ } else if (!(await this.#frameStillUsable(host, session))) {
304
+ /** 帧内站点自己导航过 ⇒ 新文档 ⇒ 重新完整准备(无副作用)。 */
305
+ await this.#prepareFrame(host, session)
306
+ frame.prepared = true
307
+ }
308
+
309
+ const minted = await host.sendToSession(session, 'Runtime.evaluate', {
310
+ expression: buildMintExpression(config),
311
+ awaitPromise: true,
312
+ returnByValue: true,
313
+ }, 75_000)
314
+
315
+ const raw = minted?.result?.value
316
+ let parsed
317
+ try {
318
+ parsed = JSON.parse(String(raw))
319
+ } catch {
320
+ throw new Error(`captcha 结果无法解析(${String(raw).slice(0, 160)})`)
321
+ }
322
+ if (parsed.stage !== 'success' || typeof parsed.param !== 'string') {
323
+ throw new Error(
324
+ `captcha 产出失败(stage=${parsed.stage ?? '?'}${parsed.err !== undefined ? `, err=${parsed.err}` : ''})`,
325
+ )
326
+ }
327
+ const verdict = validateCaptchaParam(parsed.param)
328
+ if (!verdict.ok) throw new Error(`captcha param 不可用(${verdict.reason ?? '未知'})`)
329
+ return { param: parsed.param, interactive: parsed.interactive === true }
330
+ }
331
+
332
+ /**
333
+ * 完整准备一个帧(stealth → 重置 DOM → 注入 SDK)。
334
+ * ⚠ 只应在**新文档**上调用;同一文档上重复准备会造出 F001(见文件头)。
335
+ * ⚠ OOPIF 上不支持 `Page.addScriptToEvaluateOnNewDocument`,故 stealth 只能直接求值。
336
+ */
337
+ async #prepareFrame(host, sessionId) {
338
+ await host.sendToSession(sessionId, 'Runtime.evaluate', {
339
+ expression: `${STEALTH_PATCH}; 'patched'`,
340
+ returnByValue: true,
341
+ })
342
+ await host.sendToSession(sessionId, 'Runtime.evaluate', {
343
+ expression: buildDomExpression(),
344
+ returnByValue: true,
345
+ })
346
+ const injected = await host.sendToSession(sessionId, 'Runtime.evaluate', {
347
+ expression: buildSdkInjectExpression(),
348
+ awaitPromise: true,
349
+ returnByValue: true,
350
+ })
351
+ const injectedType = injected?.result?.value
352
+ if (injectedType !== 'function' && injectedType !== 'already') {
353
+ throw new Error(`阿里云 captcha SDK 未加载(${String(injectedType)})`)
354
+ }
355
+ }
356
+
357
+ /** 帧是否仍然就绪(元素与 SDK 都还在);探测失败一律按「不就绪」处理。 */
358
+ async #frameStillUsable(host, sessionId) {
359
+ try {
360
+ const result = await host.sendToSession(sessionId, 'Runtime.evaluate', {
361
+ expression: buildFrameProbeExpression(),
362
+ returnByValue: true,
363
+ }, 5_000)
364
+ const parsed = JSON.parse(String(result?.result?.value))
365
+ return parsed.sdk === 'function' && parsed.el === true && parsed.btn === true
366
+ } catch {
367
+ return false
368
+ }
369
+ }
370
+
371
+ async #acquireFrame(forceFresh = false) {
372
+ const deadline = this.#now() + this.#pageWaitTimeoutMs
373
+ while (this.#pageBusy) {
374
+ if (this.#now() >= deadline) {
375
+ throw new Error(`captcha 页面被占用超过 ${this.#pageWaitTimeoutMs}ms(疑似上一次 mint 未归还)`)
376
+ }
377
+ await this.#sleep(50)
378
+ }
379
+ this.#pageBusy = true
380
+
381
+ try {
382
+ const existing = this.#reusableFrame
383
+ if (existing !== undefined) {
384
+ /** 严格小于:`idleReuseMs = 0` 的语义才是「每次都新建帧」。 */
385
+ const idle = this.#now() - existing.lastUsedAt
386
+ if (!forceFresh && idle < this.#idleReuseMs) return existing
387
+ await this.#discardFrame(existing)
388
+ }
389
+ return await this.#createFrame()
390
+ } catch (error) {
391
+ this.#pageBusy = false
392
+ throw error
393
+ }
394
+ }
395
+
396
+ async #createFrame() {
397
+ const host = await this.#ensureHost()
398
+ const frameId = `${this.#frameIdPrefix}${Math.random().toString(36).slice(2, 8)}`
399
+
400
+ const created = await host.send('Runtime.evaluate', {
401
+ expression: buildFrameCreateExpression(frameId, this.#origin),
402
+ returnByValue: true,
403
+ })
404
+ if (created?.result?.value !== 'created') {
405
+ throw new Error(`无法在宿主 renderer 里创建 captcha iframe(${String(created?.result?.value)})`)
406
+ }
407
+
408
+ const sessionId = await host.waitForIframeSession(this.#frameAttachTimeoutMs)
409
+ if (sessionId === undefined) {
410
+ await this.#removeFrameElement(frameId)
411
+ throw new Error('没有等到 captcha iframe 被 CDP 附加(可能是站点隔离未生效)')
412
+ }
413
+
414
+ try {
415
+ await this.#waitForFrameReady(host, sessionId)
416
+ } catch (error) {
417
+ await this.#removeFrameElement(frameId)
418
+ throw error instanceof Error ? error : new Error(String(error))
419
+ }
420
+
421
+ const frame = { frameId, sessionId, prepared: false, lastUsedAt: this.#now() }
422
+ this.#reusableFrame = frame
423
+ return frame
424
+ }
425
+
426
+ /** 轮询 iframe 文档直到可用(OOPIF 上不能用 Page.* 域)。 */
427
+ async #waitForFrameReady(host, sessionId) {
428
+ const deadline = this.#now() + this.#frameAttachTimeoutMs
429
+ for (;;) {
430
+ try {
431
+ const result = await host.sendToSession(sessionId, 'Runtime.evaluate', {
432
+ expression: 'document.readyState',
433
+ returnByValue: true,
434
+ }, 3_000)
435
+ const state = result?.result?.value
436
+ if (typeof state === 'string' && state !== 'loading') return
437
+ } catch {
438
+ // 文档可能还在初始化,重试。
439
+ }
440
+ if (this.#now() >= deadline) {
441
+ throw new Error(`captcha iframe 文档未在 ${this.#frameAttachTimeoutMs}ms 内就绪`)
442
+ }
443
+ await this.#sleep(150)
444
+ }
445
+ }
446
+
447
+ async #discardFrame(frame) {
448
+ if (this.#reusableFrame === frame) this.#reusableFrame = undefined
449
+ await this.#removeFrameElement(frame.frameId)
450
+ }
451
+
452
+ async #removeFrameElement(frameId) {
453
+ const host = this.#host
454
+ if (host === undefined) return
455
+ try {
456
+ await host.send('Runtime.evaluate', {
457
+ expression: `document.getElementById(${JSON.stringify(frameId)})?.remove(); 'removed'`,
458
+ returnByValue: true,
459
+ })
460
+ } catch {
461
+ // 宿主页面可能已重载/关闭。
462
+ }
463
+ }
464
+
465
+ /** 释放资源:**只**移除我们自己的 iframe 并关闭我们自己的连接。 */
466
+ dispose() {
467
+ const frame = this.#reusableFrame
468
+ this.#reusableFrame = undefined
469
+ this.#pageBusy = false
470
+ if (frame !== undefined) void this.#removeFrameElement(frame.frameId)
471
+ try {
472
+ this.#host?.close()
473
+ } catch {
474
+ // 已关闭。
475
+ }
476
+ this.#host = undefined
477
+ }
478
+
479
+ /**
480
+ * 用宿主的 Electron 直接打开一个可见窗口(**登录 / 粘贴凭据用**)。
481
+ *
482
+ * DSH 是 Electron 宿主:`Target.createTarget` 不被支持,但 `window.open` 在
483
+ * renderer 里可用(会开出新 BrowserWindow)。返回是否成功;失败时调用方
484
+ * 应当回退到「让用户在系统浏览器里打开链接」。用完即关(传入 closeAfterMs)。
485
+ */
486
+ async openWindow(url, options = {}) {
487
+ const host = await this.#ensureHost()
488
+ const host_ = await host.send('Runtime.evaluate', {
489
+ expression: `(() => { const w = window.open(${JSON.stringify(url)}, '_blank'); return w ? 'opened' : 'blocked'; })()`,
490
+ returnByValue: true,
491
+ })
492
+ const opened = host_?.result?.value === 'opened'
493
+ this.#log(`[captcha] openWindow(${url}) → ${opened ? 'opened' : 'blocked'}`)
494
+ if (opened && typeof options.closeAfterMs === 'number' && options.closeAfterMs > 0) {
495
+ setTimeout(() => {
496
+ void host.send('Runtime.evaluate', { expression: 'window.close()', returnByValue: true }).catch(() => {})
497
+ }, options.closeAfterMs).unref?.()
498
+ }
499
+ return opened
500
+ }
501
+ }
502
+
503
+ /** 反检测补丁(必须最先求值:SDK 的请求特征取决于它被加载时读到的值)。 */
504
+ export const STEALTH_PATCH = `
505
+ Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
506
+ Object.defineProperty(navigator, 'languages', { get: () => ['zh-CN', 'zh', 'en'] });
507
+ Object.defineProperty(navigator, 'plugins', {
508
+ get: () => [{ name: 'PDF Viewer' }, { name: 'Chrome PDF Viewer' }, { name: 'Chromium PDF Viewer' }],
509
+ });
510
+ Object.defineProperty(navigator, 'hardwareConcurrency', { get: () => 8 });
511
+ Object.defineProperty(navigator, 'deviceMemory', { get: () => 8 });
512
+ window.chrome = window.chrome ?? { runtime: {}, loadTimes: () => {}, csi: () => {} };
513
+ try {
514
+ const originalGetParameter = WebGLRenderingContext.prototype.getParameter;
515
+ WebGLRenderingContext.prototype.getParameter = function (parameter) {
516
+ if (parameter === 37445) return 'Intel Inc.';
517
+ if (parameter === 37446) return 'Intel Iris OpenGL Engine';
518
+ return originalGetParameter.call(this, parameter);
519
+ };
520
+ } catch (error) { /* 内核无 WebGL 时忽略 */ }
521
+ `
522
+
523
+ /** 构造请求体里那段「建 DOM」的表达式。 */
524
+ export function buildDomExpression() {
525
+ return `document.body.innerHTML =
526
+ '<div id="${CAPTCHA_CONTAINER_ID}" aria-hidden="true">' +
527
+ '<div id="${CAPTCHA_ELEMENT_ID}"></div>' +
528
+ '<button id="${CAPTCHA_BUTTON_ID}">verify</button></div>'; 'ok'`
529
+ }
530
+
531
+ /** 构造注入 SDK 的表达式(用 `<script src>`,简单可靠)。 */
532
+ export function buildSdkInjectExpression() {
533
+ return `new Promise((resolve) => {
534
+ if (typeof window.initAliyunCaptcha === 'function') { resolve('already'); return; }
535
+ const script = document.createElement('script');
536
+ script.src = ${JSON.stringify(CAPTCHA_SDK_URL)};
537
+ script.async = true;
538
+ script.onload = () => resolve(typeof window.initAliyunCaptcha);
539
+ script.onerror = () => resolve('onerror');
540
+ document.head.appendChild(script);
541
+ setTimeout(() => resolve('timeout'), 25000);
542
+ })`
543
+ }
544
+
545
+ /** 构造「帧是否仍然就绪」的探测表达式。 */
546
+ export function buildFrameProbeExpression() {
547
+ return `JSON.stringify({
548
+ sdk: typeof window.initAliyunCaptcha,
549
+ el: !!document.getElementById(${JSON.stringify(CAPTCHA_ELEMENT_ID)}),
550
+ btn: !!document.getElementById(${JSON.stringify(CAPTCHA_BUTTON_ID)}),
551
+ })`
552
+ }
553
+
554
+ /**
555
+ * 构造「触发无感验证并等 param」的表达式。
556
+ *
557
+ * 降级检测:我们调的是无感验证,但阿里云若判设备风险会**静默弹交互式验证**,
558
+ * 官方不给回调 ⇒ 只能自己轮询 DOM(用「曾经出现过」而非「此刻存在」)。
559
+ */
560
+ export function buildMintExpression(config) {
561
+ return `new Promise((resolve) => {
562
+ const done = (payload) => resolve(JSON.stringify(payload));
563
+ let sawInteractive = false;
564
+ const detectInteractive = () => {
565
+ try {
566
+ if (sawInteractive) return;
567
+ if (document.querySelector('#aliyunCaptcha-window-popup')
568
+ || document.querySelector('#aliyunCaptcha-sliding-slider')
569
+ || document.querySelector('#aliyunCaptcha-puzzle')) {
570
+ sawInteractive = true;
571
+ }
572
+ } catch (error) { /* 检测失败不影响产出 */ }
573
+ };
574
+ const pollTimer = setInterval(detectInteractive, 200);
575
+ try {
576
+ window.AliyunCaptchaConfig = ${JSON.stringify({ region: config.region, prefix: config.prefix })};
577
+ } catch (error) { done({ stage: 'cfg-throw', err: String(error) }); }
578
+ try {
579
+ initAliyunCaptcha({
580
+ SceneId: ${JSON.stringify(config.sceneId)},
581
+ mode: 'popup',
582
+ element: '#${CAPTCHA_ELEMENT_ID}',
583
+ button: document.getElementById('${CAPTCHA_BUTTON_ID}'),
584
+ getInstance: (instance) => {
585
+ try {
586
+ if (typeof instance.startTracelessVerification === 'function') {
587
+ instance.startTracelessVerification();
588
+ } else if (typeof instance.show === 'function') {
589
+ sawInteractive = true;
590
+ instance.show();
591
+ }
592
+ } catch (error) {
593
+ done({ stage: 'call-throw', err: String((error && error.message) || error) });
594
+ }
595
+ },
596
+ success: (param) => {
597
+ detectInteractive();
598
+ clearInterval(pollTimer);
599
+ done({ stage: 'success', param, interactive: sawInteractive });
600
+ },
601
+ fail: (error) => {
602
+ clearInterval(pollTimer);
603
+ done({ stage: 'fail', err: String((error && error.message) || JSON.stringify(error)), interactive: sawInteractive });
604
+ },
605
+ onError: (error) => {
606
+ clearInterval(pollTimer);
607
+ done({ stage: 'onError', err: String((error && error.message) || JSON.stringify(error)), interactive: sawInteractive });
608
+ },
609
+ });
610
+ } catch (error) {
611
+ clearInterval(pollTimer);
612
+ done({ stage: 'init-throw', err: String((error && error.message) || error) });
613
+ }
614
+ setTimeout(() => {
615
+ clearInterval(pollTimer);
616
+ done({ stage: 'timeout', interactive: sawInteractive });
617
+ }, 60000);
618
+ })`
619
+ }
620
+
621
+ /** SDK 需要的 DOM id(与官方 `zcode-aliyun-captcha-*` 一致)。 */
622
+ export const CAPTCHA_CONTAINER_ID = 'zcode-aliyun-captcha-container'
623
+ export const CAPTCHA_ELEMENT_ID = 'zcode-aliyun-captcha-element'
624
+ export const CAPTCHA_BUTTON_ID = 'zcode-aliyun-captcha-button'
625
+
626
+ /**
627
+ * captcha param 的合法判据(三条全中才算合法)。
628
+ * 任一条不中即判为降级 —— **不发请求**,省一次注定 3007 的往返。
629
+ */
630
+ export function validateCaptchaParam(param) {
631
+ if (typeof param !== 'string' || param.length === 0) return { ok: false, reason: 'captcha param 缺失' }
632
+ if (param.length < 200) {
633
+ return { ok: false, reason: `captcha param 长度 ${param.length} < 200(疑似 SDK 降级输出,发了必 3007)` }
634
+ }
635
+ let decoded
636
+ try {
637
+ decoded = Buffer.from(param, 'base64').toString('utf8')
638
+ } catch {
639
+ return { ok: false, reason: 'captcha param 不是合法 base64' }
640
+ }
641
+ let parsed
642
+ try {
643
+ parsed = JSON.parse(decoded)
644
+ } catch {
645
+ return { ok: false, reason: 'captcha param 解出的不是 JSON' }
646
+ }
647
+ if (typeof parsed.certifyId !== 'string' || parsed.certifyId.length === 0) {
648
+ return { ok: false, reason: 'captcha param 缺 certifyId' }
649
+ }
650
+ if (typeof parsed.securityToken !== 'string' || parsed.securityToken.length < 50) {
651
+ return { ok: false, reason: 'securityToken 缺失或过短(< 50)' }
652
+ }
653
+ return { ok: true }
654
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * 阿里云 captcha 网页侧脚本常量与兜底配置。
3
+ *
4
+ * 与参考实现逐字一致:SDK 地址、承载 origin、DOM id、兜底 sceneId/prefix。
5
+ * 其中 `ZCODE_CAPTCHA_FALLBACK` 是实测自本机账号的兜底值;运行时优先服务端下发
6
+ * (`GET /api/v1/client/configs`,60 秒 TTL,失败不缓存)。
7
+ */
8
+
9
+ /** 阿里云 captcha SDK 地址(与官方逐字一致)。 */
10
+ export const CAPTCHA_SDK_URL = 'https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js'
11
+
12
+ /** captcha 页面必须导航到的**真实 origin**(能否重复 mint 的关键)。 */
13
+ export const CAPTCHA_PAGE_ORIGIN = 'https://zcode.z.ai/'
14
+
15
+ /** 兜底 captcha 配置(运行时优先服务端下发)。 */
16
+ export const ZCODE_CAPTCHA_FALLBACK = Object.freeze({
17
+ region: 'cn',
18
+ prefix: 'no8xfe',
19
+ sceneId: '11xygtvd',
20
+ })