@zhin.js/core 1.5.16 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (334) hide show
  1. package/README.md +78 -195
  2. package/lib/ai-completion-contract.d.ts +135 -0
  3. package/lib/ai-completion-contract.js +69 -0
  4. package/lib/built/ai-access.d.ts +2 -21
  5. package/lib/built/ai-access.js +1 -46
  6. package/lib/built/ai-outbound/index.d.ts +0 -2
  7. package/lib/built/ai-outbound/index.js +0 -2
  8. package/lib/built/ai-outbound/prompt.d.ts +2 -0
  9. package/lib/built/ai-outbound/prompt.js +2 -0
  10. package/lib/built/ai-outbound/types.d.ts +1 -10
  11. package/lib/built/ai-trigger.d.ts +39 -78
  12. package/lib/built/ai-trigger.js +3 -254
  13. package/lib/built/common-adapter-tools.d.ts +21 -6
  14. package/lib/built/common-adapter-tools.js +28 -17
  15. package/lib/built/generic-segment-mapper.js +4 -1
  16. package/lib/built/html-segment-fallback.d.ts +6 -7
  17. package/lib/built/html-segment-fallback.js +1 -16
  18. package/lib/built/html-to-text.d.ts +0 -3
  19. package/lib/built/html-to-text.js +131 -40
  20. package/lib/built/interaction-messages.d.ts +1 -0
  21. package/lib/built/interaction-messages.js +30 -0
  22. package/lib/built/interactive-segments/action.d.ts +3 -4
  23. package/lib/built/interactive-segments/action.js +2 -5
  24. package/lib/built/interactive-segments/index.d.ts +0 -2
  25. package/lib/built/interactive-segments/index.js +0 -2
  26. package/lib/built/interactive-segments/keyboard-segment.d.ts +0 -1
  27. package/lib/built/interactive-segments/keyboard-segment.js +0 -1
  28. package/lib/built/interactive-segments/onebot-keyboard.d.ts +0 -1
  29. package/lib/built/interactive-segments/onebot-keyboard.js +0 -2
  30. package/lib/built/interactive-segments/resolve.d.ts +2 -3
  31. package/lib/built/interactive-segments/resolve.js +21 -14
  32. package/lib/built/interactive-segments/types.d.ts +2 -7
  33. package/lib/built/interactive-segments/types.js +22 -2
  34. package/lib/built/login-assist.d.ts +330 -25
  35. package/lib/built/login-assist.js +1156 -75
  36. package/lib/built/login-captcha.d.ts +62 -0
  37. package/lib/built/login-captcha.js +107 -0
  38. package/lib/built/message-enrich.d.ts +24 -27
  39. package/lib/built/message-enrich.js +53 -49
  40. package/lib/built/outbound-content-arrays.d.ts +4 -0
  41. package/lib/built/outbound-content-arrays.js +32 -0
  42. package/lib/built/outbound-media-trust.d.ts +46 -0
  43. package/lib/built/outbound-media-trust.js +245 -0
  44. package/lib/built/outbound-media-utils.d.ts +5 -3
  45. package/lib/built/outbound-media-utils.js +5 -3
  46. package/lib/built/readable-link.d.ts +4 -0
  47. package/lib/built/readable-link.js +32 -0
  48. package/lib/built/rich-segments/markdown-to-text.d.ts +1 -2
  49. package/lib/built/rich-segments/markdown-to-text.js +141 -17
  50. package/lib/built/roles.d.ts +141 -12
  51. package/lib/built/roles.js +253 -52
  52. package/lib/built/segment-contract/assert.js +8 -2
  53. package/lib/built/segment-contract/delivery.js +1 -0
  54. package/lib/built/segment-contract/index.d.ts +3 -3
  55. package/lib/built/segment-contract/index.js +2 -2
  56. package/lib/built/segment-contract/json-schema.d.ts +39 -5
  57. package/lib/built/segment-contract/json-schema.js +207 -24
  58. package/lib/built/segment-contract/preview.js +8 -1
  59. package/lib/built/segment-contract/text.js +1 -1
  60. package/lib/built/segment-contract/types.d.ts +2 -2
  61. package/lib/built/segment-contract/validate.d.ts +1553 -224
  62. package/lib/built/segment-contract/validate.js +39 -3
  63. package/lib/built/tool-access.d.ts +5 -0
  64. package/lib/built/tool-access.js +17 -0
  65. package/lib/built/user-interaction.d.ts +5 -4
  66. package/lib/built/user-interaction.js +64 -52
  67. package/lib/errors.d.ts +1 -18
  68. package/lib/errors.js +1 -26
  69. package/lib/feature/command-public-api.d.ts +5 -0
  70. package/lib/feature/command-public-api.js +5 -0
  71. package/lib/feature/command.d.ts +2 -0
  72. package/lib/feature/command.js +1 -0
  73. package/lib/feature/component.d.ts +1 -0
  74. package/lib/feature/component.js +1 -0
  75. package/lib/feature/handler.d.ts +13 -7
  76. package/lib/feature/handler.js +2 -1
  77. package/lib/feature/middleware-public-api.d.ts +6 -0
  78. package/lib/feature/middleware-public-api.js +6 -0
  79. package/lib/feature/middleware.d.ts +22 -2
  80. package/lib/feature/middleware.js +7 -2
  81. package/lib/im-scene.d.ts +4 -3
  82. package/lib/im-scene.js +9 -9
  83. package/lib/im-session-id.d.ts +20 -12
  84. package/lib/im-session-id.js +8 -8
  85. package/lib/index.d.ts +20 -48
  86. package/lib/index.js +15 -41
  87. package/lib/jsx/intrinsic-elements.d.ts +83 -0
  88. package/lib/jsx/message-renderer.d.ts +13 -0
  89. package/lib/jsx/message-renderer.js +128 -0
  90. package/lib/jsx/message-tags.d.ts +133 -0
  91. package/lib/jsx/message-tags.js +50 -0
  92. package/lib/jsx-dev-runtime.d.ts +2 -2
  93. package/lib/jsx-dev-runtime.js +1 -2
  94. package/lib/jsx-runtime.d.ts +2 -12
  95. package/lib/jsx-runtime.js +1 -10
  96. package/lib/jsx.d.ts +6 -30
  97. package/lib/jsx.js +3 -93
  98. package/lib/message.d.ts +0 -40
  99. package/lib/message.js +1 -27
  100. package/lib/models/system-log.d.ts +0 -2
  101. package/lib/models/system-log.js +1 -8
  102. package/lib/models/user.d.ts +0 -2
  103. package/lib/models/user.js +1 -7
  104. package/lib/notice.d.ts +38 -33
  105. package/lib/notice.js +23 -7
  106. package/lib/plugin-runtime/im/command-feedback.d.ts +59 -0
  107. package/lib/plugin-runtime/im/command-feedback.js +148 -0
  108. package/lib/plugin-runtime/im/contracts.d.ts +217 -32
  109. package/lib/plugin-runtime/im/contracts.js +141 -23
  110. package/lib/plugin-runtime/im/conversation-runtime.d.ts +42 -0
  111. package/lib/plugin-runtime/im/conversation-runtime.js +451 -0
  112. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +112 -0
  113. package/lib/plugin-runtime/im/endpoint-runtime.js +434 -0
  114. package/lib/plugin-runtime/im/feature-gate.d.ts +21 -0
  115. package/lib/plugin-runtime/im/feature-gate.js +88 -0
  116. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  117. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  118. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  119. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  120. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  121. package/lib/plugin-runtime/im/host/database-config.js +152 -0
  122. package/lib/plugin-runtime/im/host/database-console-schema.d.ts +79 -0
  123. package/lib/plugin-runtime/im/host/database-console-schema.js +477 -0
  124. package/lib/plugin-runtime/im/host/database-console-sql.d.ts +66 -0
  125. package/lib/plugin-runtime/im/host/database-console-sql.js +459 -0
  126. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +60 -0
  127. package/lib/plugin-runtime/im/host/database-host-installer.js +1166 -0
  128. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  129. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  130. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  131. package/lib/plugin-runtime/im/host/index.js +8 -0
  132. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  133. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  134. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  135. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  136. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +34 -0
  137. package/lib/plugin-runtime/im/host/sender-enrichment.js +82 -0
  138. package/lib/plugin-runtime/im/im-runtime.d.ts +40 -111
  139. package/lib/plugin-runtime/im/im-runtime.js +235 -1059
  140. package/lib/plugin-runtime/im/inbound-dedup.d.ts +84 -0
  141. package/lib/plugin-runtime/im/inbound-dedup.js +322 -0
  142. package/lib/plugin-runtime/im/inbound-origin.d.ts +150 -0
  143. package/lib/plugin-runtime/im/inbound-origin.js +183 -0
  144. package/lib/plugin-runtime/im/inbound-runtime.d.ts +59 -0
  145. package/lib/plugin-runtime/im/inbound-runtime.js +478 -0
  146. package/lib/plugin-runtime/im/inbound-spine.d.ts +196 -0
  147. package/lib/plugin-runtime/im/inbound-spine.js +335 -0
  148. package/lib/plugin-runtime/im/index.d.ts +15 -4
  149. package/lib/plugin-runtime/im/index.js +11 -4
  150. package/lib/plugin-runtime/im/interaction-runtime.d.ts +50 -0
  151. package/lib/plugin-runtime/im/interaction-runtime.js +390 -0
  152. package/lib/plugin-runtime/im/interactive-router.d.ts +81 -0
  153. package/lib/plugin-runtime/im/interactive-router.js +382 -0
  154. package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
  155. package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
  156. package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -4
  157. package/lib/plugin-runtime/im/message-dispatcher.js +138 -20
  158. package/lib/plugin-runtime/im/message-events.d.ts +85 -0
  159. package/lib/plugin-runtime/im/message-events.js +113 -0
  160. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +39 -0
  161. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +450 -0
  162. package/lib/plugin-runtime/im/outbound-renderer.d.ts +52 -3
  163. package/lib/plugin-runtime/im/outbound-renderer.js +188 -8
  164. package/lib/plugin-runtime/im/outbound-segments.d.ts +29 -5
  165. package/lib/plugin-runtime/im/outbound-segments.js +130 -36
  166. package/lib/plugin-runtime/im/progressive-reply.d.ts +58 -0
  167. package/lib/plugin-runtime/im/progressive-reply.js +501 -0
  168. package/lib/plugin-runtime/im/public-api.d.ts +1 -1
  169. package/lib/request.d.ts +27 -36
  170. package/lib/request.js +14 -6
  171. package/lib/side-event/base.d.ts +64 -44
  172. package/lib/side-event/base.js +72 -19
  173. package/lib/side-event/index.d.ts +1 -1
  174. package/lib/side-event/index.js +1 -1
  175. package/lib/side-event/normalize.d.ts +7 -38
  176. package/lib/side-event/normalize.js +4 -109
  177. package/lib/side-event/scene-events.d.ts +40 -0
  178. package/lib/side-event/scene-events.js +147 -0
  179. package/lib/side-event/types.d.ts +4 -13
  180. package/lib/side-event/types.js +1 -55
  181. package/lib/system-event.d.ts +17 -12
  182. package/lib/system-event.js +8 -6
  183. package/lib/types.d.ts +23 -167
  184. package/lib/utils.d.ts +50 -33
  185. package/lib/utils.js +12 -185
  186. package/lib/venue/contracts.d.ts +21 -0
  187. package/lib/venue/contracts.js +3 -0
  188. package/lib/venue/floor-controller.d.ts +11 -0
  189. package/lib/venue/floor-controller.js +63 -0
  190. package/lib/venue/index.d.ts +13 -0
  191. package/lib/venue/index.js +11 -0
  192. package/lib/venue/membership-port.d.ts +23 -0
  193. package/lib/venue/membership-port.js +141 -0
  194. package/lib/venue/projector.d.ts +38 -0
  195. package/lib/venue/projector.js +45 -0
  196. package/lib/venue/registry.d.ts +16 -0
  197. package/lib/venue/registry.js +63 -0
  198. package/lib/venue/router.d.ts +19 -0
  199. package/lib/venue/router.js +101 -0
  200. package/lib/venue/send-limiter.d.ts +17 -0
  201. package/lib/venue/send-limiter.js +73 -0
  202. package/lib/venue/validator.d.ts +6 -0
  203. package/lib/venue/validator.js +160 -0
  204. package/package.json +24 -50
  205. package/lib/adapter.d.ts +0 -145
  206. package/lib/adapter.js +0 -377
  207. package/lib/built/adapter-process.d.ts +0 -58
  208. package/lib/built/adapter-process.js +0 -128
  209. package/lib/built/agent-preset.d.ts +0 -64
  210. package/lib/built/agent-preset.js +0 -79
  211. package/lib/built/ai-outbound/adapter-access.d.ts +0 -3
  212. package/lib/built/ai-outbound/adapter-access.js +0 -9
  213. package/lib/built/ai-outbound/extensions/qq-message.d.ts +0 -3
  214. package/lib/built/ai-outbound/extensions/qq-message.js +0 -23
  215. package/lib/built/authorization.d.ts +0 -10
  216. package/lib/built/authorization.js +0 -76
  217. package/lib/built/command.d.ts +0 -72
  218. package/lib/built/command.js +0 -105
  219. package/lib/built/component.d.ts +0 -67
  220. package/lib/built/component.js +0 -97
  221. package/lib/built/config.d.ts +0 -98
  222. package/lib/built/config.js +0 -372
  223. package/lib/built/connect-endpoint-instance.d.ts +0 -17
  224. package/lib/built/connect-endpoint-instance.js +0 -42
  225. package/lib/built/database.d.ts +0 -68
  226. package/lib/built/database.js +0 -106
  227. package/lib/built/dispatcher.d.ts +0 -141
  228. package/lib/built/dispatcher.js +0 -383
  229. package/lib/built/endpoint-commands.d.ts +0 -3
  230. package/lib/built/endpoint-commands.js +0 -99
  231. package/lib/built/endpoint-lifecycle-service.d.ts +0 -28
  232. package/lib/built/endpoint-lifecycle-service.js +0 -242
  233. package/lib/built/endpoint-lifecycle.d.ts +0 -27
  234. package/lib/built/endpoint-lifecycle.js +0 -36
  235. package/lib/built/endpoint-manager.d.ts +0 -34
  236. package/lib/built/html-renderer-loader.d.ts +0 -13
  237. package/lib/built/html-renderer-loader.js +0 -33
  238. package/lib/built/inbound-pipeline.d.ts +0 -37
  239. package/lib/built/inbound-pipeline.js +0 -63
  240. package/lib/built/inbound-runner.d.ts +0 -22
  241. package/lib/built/inbound-runner.js +0 -34
  242. package/lib/built/interactive-segment-contract.d.ts +0 -6
  243. package/lib/built/interactive-segment-contract.js +0 -9
  244. package/lib/built/interactive-segments/fallback-store.d.ts +0 -29
  245. package/lib/built/interactive-segments/fallback-store.js +0 -63
  246. package/lib/built/interactive-segments/handlers.d.ts +0 -16
  247. package/lib/built/interactive-segments/handlers.js +0 -74
  248. package/lib/built/introspection-format.d.ts +0 -10
  249. package/lib/built/introspection-format.js +0 -28
  250. package/lib/built/management-command-guard.d.ts +0 -15
  251. package/lib/built/management-command-guard.js +0 -25
  252. package/lib/built/message-filter.d.ts +0 -176
  253. package/lib/built/message-filter.js +0 -239
  254. package/lib/built/optional-peer-import.d.ts +0 -3
  255. package/lib/built/optional-peer-import.js +0 -33
  256. package/lib/built/outbound-media-contract.d.ts +0 -22
  257. package/lib/built/outbound-media-contract.js +0 -10
  258. package/lib/built/permission.d.ts +0 -51
  259. package/lib/built/permission.js +0 -99
  260. package/lib/built/permit-check.d.ts +0 -7
  261. package/lib/built/permit-check.js +0 -35
  262. package/lib/built/permit-parse.d.ts +0 -16
  263. package/lib/built/permit-parse.js +0 -32
  264. package/lib/built/platform-permit.d.ts +0 -20
  265. package/lib/built/platform-permit.js +0 -91
  266. package/lib/built/queue-im-field-contract.d.ts +0 -32
  267. package/lib/built/queue-im-field-contract.js +0 -67
  268. package/lib/built/rich-segments/adapter-policies.d.ts +0 -9
  269. package/lib/built/rich-segments/adapter-policies.js +0 -27
  270. package/lib/built/rich-segments/base.d.ts +0 -11
  271. package/lib/built/rich-segments/base.js +0 -24
  272. package/lib/built/rich-segments/builtins.d.ts +0 -4
  273. package/lib/built/rich-segments/builtins.js +0 -40
  274. package/lib/built/rich-segments/capabilities.d.ts +0 -6
  275. package/lib/built/rich-segments/capabilities.js +0 -38
  276. package/lib/built/rich-segments/html-segment.d.ts +0 -15
  277. package/lib/built/rich-segments/html-segment.js +0 -62
  278. package/lib/built/rich-segments/index.d.ts +0 -13
  279. package/lib/built/rich-segments/index.js +0 -13
  280. package/lib/built/rich-segments/markdown-segment.d.ts +0 -14
  281. package/lib/built/rich-segments/markdown-segment.js +0 -58
  282. package/lib/built/rich-segments/qrcode-segment.d.ts +0 -18
  283. package/lib/built/rich-segments/qrcode-segment.js +0 -73
  284. package/lib/built/rich-segments/registry.d.ts +0 -16
  285. package/lib/built/rich-segments/registry.js +0 -52
  286. package/lib/built/rich-segments/resolve.d.ts +0 -5
  287. package/lib/built/rich-segments/resolve.js +0 -87
  288. package/lib/built/rich-segments/tts-segment.d.ts +0 -13
  289. package/lib/built/rich-segments/tts-segment.js +0 -51
  290. package/lib/built/rich-segments/types.d.ts +0 -79
  291. package/lib/built/rich-segments/types.js +0 -17
  292. package/lib/built/runtime-io.d.ts +0 -9
  293. package/lib/built/runtime-io.js +0 -67
  294. package/lib/built/schedule.d.ts +0 -54
  295. package/lib/built/schedule.js +0 -112
  296. package/lib/built/schema-endpoint-manager.d.ts +0 -17
  297. package/lib/built/schema-endpoint-manager.js +0 -73
  298. package/lib/built/schema-feature.d.ts +0 -77
  299. package/lib/built/schema-feature.js +0 -130
  300. package/lib/built/skill.d.ts +0 -120
  301. package/lib/built/skill.js +0 -151
  302. package/lib/built/speech-loader.d.ts +0 -14
  303. package/lib/built/speech-loader.js +0 -32
  304. package/lib/built/tool.d.ts +0 -151
  305. package/lib/built/tool.js +0 -388
  306. package/lib/command.d.ts +0 -50
  307. package/lib/command.js +0 -106
  308. package/lib/component.d.ts +0 -26
  309. package/lib/component.js +0 -583
  310. package/lib/endpoint-capabilities.d.ts +0 -46
  311. package/lib/endpoint-capabilities.js +0 -55
  312. package/lib/endpoint.d.ts +0 -19
  313. package/lib/endpoint.js +0 -3
  314. package/lib/host-plugin-registry.d.ts +0 -8
  315. package/lib/host-plugin-registry.js +0 -12
  316. package/lib/plugin-context.d.ts +0 -27
  317. package/lib/plugin-context.js +0 -64
  318. package/lib/plugin-runtime/im/interactive.d.ts +0 -26
  319. package/lib/plugin-runtime/im/interactive.js +0 -46
  320. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  321. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  322. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  323. package/lib/plugin-runtime/im/message-bus.js +0 -40
  324. package/lib/plugin-runtime/im/service-tokens.d.ts +0 -18
  325. package/lib/plugin-runtime/im/service-tokens.js +0 -13
  326. package/lib/plugin.d.ts +0 -268
  327. package/lib/plugin.js +0 -583
  328. package/lib/schema-interaction.d.ts +0 -117
  329. package/lib/schema-interaction.js +0 -247
  330. package/lib/side-event/dispatch.d.ts +0 -15
  331. package/lib/side-event/dispatch.js +0 -140
  332. package/lib/tool-zod.d.ts +0 -43
  333. package/lib/tool-zod.js +0 -184
  334. /package/lib/{built/endpoint-manager.js → jsx/intrinsic-elements.js} +0 -0
@@ -1,16 +1,31 @@
1
- /**
2
- * LoginAssist — 登录辅助生产者-消费者
3
- *
4
- * 适配器在需要人为辅助登录时(扫码、短信、滑块等)作为生产者投递待办;
5
- * Web 控制台、命令行等作为消费者拉取待办并提交结果。
6
- * 待办未消费前会一直保留,刷新页面后仍可继续消费。
7
- *
8
- * 事件:
9
- * endpoint.login.pending — 有新待办时触发,payload: PendingLoginTask
10
- * endpoint.login.expired — 超时自动取消时触发,payload: PendingLoginTask
11
- */
1
+ import { randomUUID } from 'node:crypto';
2
+ import { isValidCaptchaHelperUrl } from './login-captcha.js';
12
3
  /** 默认 5 分钟;扫码/滑块长期挂起会泄漏 Promise 与 Map 条目 */
13
4
  export const DEFAULT_LOGIN_ASSIST_TIMEOUT_MS = 5 * 60 * 1000;
5
+ /** 提交后多久仍无结果即标记「结果待确认」(不是失败)。 */
6
+ export const DEFAULT_LOGIN_VERIFY_TIMEOUT_MS = 20 * 1000;
7
+ /** 每个流程保留的时间线步骤上限。 */
8
+ export const LOGIN_FLOW_STEP_LIMIT = 20;
9
+ export const LOGIN_ERROR_CODES = Object.freeze([
10
+ 'code_invalid', 'rate_limited', 'challenge_expired', 'risk_blocked', 'credential_invalid', 'network', 'unknown',
11
+ ]);
12
+ /** Thrown by `submit` when an answer does not fit the challenge. The message never contains the value. */
13
+ export class LoginSubmissionError extends Error {
14
+ code;
15
+ constructor(code, message) {
16
+ super(message);
17
+ this.code = code;
18
+ this.name = 'LoginSubmissionError';
19
+ }
20
+ }
21
+ /** Raised from a challenge promise when a newer challenge replaced it. */
22
+ export class LoginChallengeReplacedError extends Error {
23
+ constructor() {
24
+ super('replaced');
25
+ this.name = 'LoginChallengeReplacedError';
26
+ }
27
+ }
28
+ const TERMINAL = new Set(['online', 'failed', 'cancelled']);
14
29
  // ============================================================================
15
30
  // LoginAssist 服务
16
31
  // ============================================================================
@@ -18,17 +33,24 @@ export class LoginAssist {
18
33
  bus;
19
34
  pending = new Map();
20
35
  local = new Map();
21
- idSeq = 0;
22
36
  /** 构造时默认超时;可被 waitForInput options 覆盖 */
23
37
  defaultTimeoutMs;
38
+ #verifyTimeoutMs;
39
+ #verifyingTitle;
40
+ #captchaHelperUrl;
41
+ #flows = new Map();
42
+ #seq = 0;
24
43
  constructor(bus, options) {
25
44
  this.bus = bus ?? null;
26
45
  this.defaultTimeoutMs = options?.defaultTimeoutMs ?? DEFAULT_LOGIN_ASSIST_TIMEOUT_MS;
46
+ this.#verifyTimeoutMs = options?.verifyTimeoutMs ?? DEFAULT_LOGIN_VERIFY_TIMEOUT_MS;
47
+ this.#verifyingTitle = options?.verifyingTitle ?? '验证中…';
48
+ this.configure({ captchaHelperUrl: options?.captchaHelperUrl });
49
+ }
50
+ /** Host configuration (`console.loginAssist`); an invalid helper URL is ignored. */
51
+ configure(options) {
52
+ this.#captchaHelperUrl = isValidCaptchaHelperUrl(options.captchaHelperUrl) ? options.captchaHelperUrl : undefined;
27
53
  }
28
- /**
29
- * Subscribe without requiring a Plugin EventEmitter.
30
- * Returns unsubscribe.
31
- */
32
54
  subscribe(name, listener) {
33
55
  let set = this.local.get(name);
34
56
  if (!set) {
@@ -40,89 +62,188 @@ export class LoginAssist {
40
62
  set.delete(listener);
41
63
  };
42
64
  }
65
+ // --------------------------------------------------------------------------
66
+ // Producer: flows
67
+ // --------------------------------------------------------------------------
68
+ /**
69
+ * Start the login flow of one Endpoint. A previous unfinished flow of the same Endpoint instance
70
+ * (owner) is ended as `superseded`; the attempt counter continues unless the last flow went online.
71
+ */
72
+ beginFlow(options) {
73
+ options.signal?.throwIfAborted();
74
+ return this.#handle(this.#createFlow(options, false));
75
+ }
76
+ /** Latest flow per Endpoint (all states). Snapshots include the active challenge's material. */
77
+ listFlows() {
78
+ return [...this.#latestFlows().values()].map((flow) => this.#snapshot(flow));
79
+ }
80
+ getFlow(adapter, endpointKey) {
81
+ const flow = this.#latestFlows().get(endpointKeyOf(adapter, endpointKey));
82
+ return flow ? this.#snapshot(flow) : undefined;
83
+ }
84
+ getFlowById(id) {
85
+ const flow = this.#flows.get(id);
86
+ return flow ? this.#snapshot(flow) : undefined;
87
+ }
88
+ /**
89
+ * Event-safe form of a snapshot ({@link withoutLoginMedia}): what Console readers without
90
+ * `endpoint.operate` on the flow's Endpoint receive from `login.flow.*` (ADR 0058 §8).
91
+ */
92
+ eventSafeFlow(flow) {
93
+ return withoutLoginMedia(flow);
94
+ }
95
+ /** Flow a pending task belongs to. */
96
+ flowOfTask(taskId) {
97
+ const entry = this.pending.get(taskId);
98
+ return entry ? this.#snapshot(entry.flow) : undefined;
99
+ }
100
+ /**
101
+ * True while an unfinished flow of this Endpoint waits for an answer. Adapters use it to
102
+ * suppress automatic relogin while a person is answering a challenge.
103
+ */
104
+ hasActiveChallenge(endpointKey, adapter) {
105
+ for (const flow of this.#flows.values()) {
106
+ if (flow.endpointKey !== endpointKey || (adapter !== undefined && flow.adapter !== adapter))
107
+ continue;
108
+ if (!TERMINAL.has(flow.state) && flow.activeTaskId && this.pending.has(flow.activeTaskId))
109
+ return true;
110
+ }
111
+ return false;
112
+ }
113
+ // --------------------------------------------------------------------------
114
+ // Producer: legacy one-shot API
115
+ // --------------------------------------------------------------------------
43
116
  /**
44
117
  * 生产者:等待用户输入后 resolve。会发出 endpoint.login.pending 事件,未消费前可被 listPending 拉取(刷新后可继续消费)。
45
118
  * 超时后 reject 并 emit `endpoint.login.expired`。
119
+ *
120
+ * ADR 0058: the task is a challenge of the Endpoint's current flow (an implicit flow when the
121
+ * Adapter never called `beginFlow`); the payload is mapped to a challenge descriptor.
46
122
  */
47
123
  waitForInput(adapter, endpointKey, type, payload, options) {
48
- const id = `login-${Date.now()}-${++this.idSeq}`;
49
- const timeoutMs = resolveTimeoutMs(options?.timeoutMs, this.defaultTimeoutMs);
50
- const createdAt = Date.now();
51
- const task = {
52
- id,
53
- adapter,
54
- endpointKey,
55
- type,
56
- payload: { message: payload.message ?? '', ...payload },
57
- createdAt,
58
- ...(timeoutMs != null ? { expiresAt: createdAt + timeoutMs } : {}),
59
- };
60
- const promise = new Promise((resolve, reject) => {
61
- const entry = { task, owner: options.owner, resolve, reject };
62
- if (timeoutMs != null) {
63
- entry.timer = setTimeout(() => {
64
- if (!this.pending.has(id))
65
- return;
66
- this.pending.delete(id);
67
- try {
68
- this.#notify('endpoint.login.expired', task);
69
- }
70
- catch {
71
- /* observer failure must not leave the producer hanging forever */
72
- }
73
- reject(new Error(`LoginAssist task timed out after ${timeoutMs}ms`));
74
- }, timeoutMs);
75
- // Node: 不阻止进程退出
76
- entry.timer.unref?.();
77
- }
78
- this.pending.set(id, entry);
79
- this.#notify('endpoint.login.pending', task);
80
- });
81
- return promise;
124
+ options.signal?.throwIfAborted();
125
+ const flow = this.#currentFlowFor(adapter, endpointKey, options.owner)
126
+ ?? this.#createFlow({ adapter, endpointKey, owner: options.owner, endpointIdentity: options.endpointIdentity }, true);
127
+ return this.#openChallenge(flow, legacyDescriptor(type, payload), {
128
+ timeoutMs: options.timeoutMs,
129
+ signal: options.signal,
130
+ endpointIdentity: options.endpointIdentity,
131
+ legacy: { type, payload },
132
+ }).then(legacyValue);
82
133
  }
134
+ // --------------------------------------------------------------------------
135
+ // Consumer
136
+ // --------------------------------------------------------------------------
83
137
  /**
84
- * 消费者:提交结果,对应 waitForInput 的 Promise 会 resolve。
138
+ * 消费者:提交结果,对应 waitForInput / challenge 的 Promise 会 resolve。
139
+ * `value` is a string (legacy) or `{ action, values }`. An answer that does not fit a
140
+ * `beginFlow` challenge throws {@link LoginSubmissionError} and leaves the challenge open.
85
141
  */
86
- submit(id, value) {
142
+ submit(id, value, endpointIdentity) {
87
143
  const entry = this.pending.get(id);
88
- if (!entry)
144
+ if (!entry || !matchesIdentity(entry.task.endpointIdentity, endpointIdentity))
89
145
  return false;
146
+ const step = entry.flow.steps.find((item) => item.id === entry.stepId);
147
+ const answer = resolveAnswer(step?.challenge, value, !entry.legacy);
90
148
  this.pending.delete(id);
91
- if (entry.timer)
92
- clearTimeout(entry.timer);
93
- entry.resolve(value);
149
+ this.#detach(entry);
150
+ const flow = entry.flow;
151
+ for (const text of Object.values(answer.values))
152
+ rememberSecret(flow, text);
153
+ if (typeof value === 'string')
154
+ rememberSecret(flow, value);
155
+ if (step) {
156
+ step.status = 'done';
157
+ step.endedAt = Date.now();
158
+ delete step.taskId;
159
+ dropMedia(step);
160
+ }
161
+ if (flow.activeTaskId === id)
162
+ delete flow.activeTaskId;
163
+ this.#addVerifying(flow, this.#verifyingTitle, 'login.verifying');
164
+ this.#armVerifyTimer(flow);
165
+ entry.resolve({ raw: value, answer });
94
166
  this.#notify('endpoint.login.resolved', entry.task);
167
+ this.#emitFlow(flow);
95
168
  return true;
96
169
  }
97
170
  /**
98
- * 消费者:取消某条待办,对应 Promise 会 reject。
171
+ * Submit and wait for the flow's next result (outcome, online, failure, end or a following
172
+ * challenge) for at most `timeoutMs` (default 15 s). Without a result: `pending: true`.
173
+ */
174
+ async submitAndWait(id, value, options = {}) {
175
+ const flow = this.pending.get(id)?.flow;
176
+ let settle;
177
+ const settled = new Promise((resolve) => { settle = resolve; });
178
+ flow?.waiters.add(settle);
179
+ let accepted;
180
+ try {
181
+ accepted = this.submit(id, value, options.endpointIdentity);
182
+ }
183
+ catch (error) {
184
+ flow?.waiters.delete(settle);
185
+ throw error;
186
+ }
187
+ if (!accepted || !flow) {
188
+ flow?.waiters.delete(settle);
189
+ return { accepted };
190
+ }
191
+ let timer;
192
+ const timeout = new Promise((resolve) => {
193
+ timer = setTimeout(() => resolve(null), options.timeoutMs ?? 15_000);
194
+ timer.unref?.();
195
+ });
196
+ const result = await Promise.race([settled, timeout]);
197
+ if (timer)
198
+ clearTimeout(timer);
199
+ flow.waiters.delete(settle);
200
+ const snapshot = this.#snapshot(flow);
201
+ if (!result)
202
+ return { accepted: true, pending: true, flow: snapshot };
203
+ return { accepted: true, ...(result.outcome ? { outcome: result.outcome } : {}), flow: snapshot };
204
+ }
205
+ /**
206
+ * 消费者:取消某条待办,对应 Promise 会 reject;所属流程以 `cancelled` 结束。
99
207
  */
100
- cancel(id, reason = 'cancelled') {
208
+ cancel(id, reason = 'cancelled', endpointIdentity) {
101
209
  const entry = this.pending.get(id);
102
- if (!entry)
210
+ if (!entry || !matchesIdentity(entry.task.endpointIdentity, endpointIdentity))
103
211
  return false;
104
- this.pending.delete(id);
105
- if (entry.timer)
106
- clearTimeout(entry.timer);
107
- entry.reject(new Error(reason));
108
- this.#notify('endpoint.login.resolved', entry.task);
212
+ this.#rejectEntry(entry, new Error(reason), 'skipped');
213
+ this.#endFlow(entry.flow, 'cancelled', reason);
109
214
  return true;
110
215
  }
111
216
  /**
112
217
  * Cancel pending tasks created by one exact Endpoint instance.
218
+ *
219
+ * Flow mapping of the reason: `replaced_by_*` only retires the active challenge (a new one
220
+ * follows); `online` reports the flow online; `login_error` fails it; anything else ends it.
113
221
  */
114
222
  cancelOwned(owner, reason = 'superseded') {
115
223
  let count = 0;
116
- for (const [id, entry] of [...this.pending]) {
224
+ for (const [, entry] of [...this.pending]) {
117
225
  if (entry.owner !== owner)
118
226
  continue;
119
- this.pending.delete(id);
120
- if (entry.timer)
121
- clearTimeout(entry.timer);
122
- entry.reject(new Error(reason));
123
- this.#notify('endpoint.login.resolved', entry.task);
227
+ this.#rejectEntry(entry, new Error(reason), 'skipped');
124
228
  count += 1;
125
229
  }
230
+ if (reason.startsWith('replaced_by_')) {
231
+ if (count > 0)
232
+ for (const flow of this.#flows.values())
233
+ if (flow.owner === owner)
234
+ this.#emitFlow(flow);
235
+ return count;
236
+ }
237
+ for (const flow of [...this.#flows.values()]) {
238
+ if (flow.owner !== owner || TERMINAL.has(flow.state))
239
+ continue;
240
+ if (reason === 'online')
241
+ this.#online(flow);
242
+ else if (reason === 'login_error')
243
+ this.#outcome(flow, { result: 'failed', code: 'unknown', next: 'relogin' });
244
+ else
245
+ this.#endFlow(flow, 'cancelled', reason);
246
+ }
126
247
  return count;
127
248
  }
128
249
  /**
@@ -145,23 +266,461 @@ export class LoginAssist {
145
266
  }
146
267
  dispose() {
147
268
  for (const [, entry] of this.pending) {
148
- if (entry.timer)
149
- clearTimeout(entry.timer);
269
+ this.#detach(entry);
150
270
  entry.reject(new Error('LoginAssist disposed'));
151
271
  }
152
272
  this.pending.clear();
273
+ for (const flow of this.#flows.values()) {
274
+ if (flow.verifyTimer)
275
+ clearTimeout(flow.verifyTimer);
276
+ flow.detachAbort?.();
277
+ for (const waiter of [...flow.waiters])
278
+ waiter({});
279
+ flow.secrets = [];
280
+ }
281
+ this.#flows.clear();
153
282
  this.local.clear();
154
283
  }
155
- #notify(name, task) {
284
+ // --------------------------------------------------------------------------
285
+ // Internals
286
+ // --------------------------------------------------------------------------
287
+ #latestFlows() {
288
+ const latest = new Map();
289
+ for (const flow of this.#flows.values()) {
290
+ const key = endpointKeyOf(flow.adapter, flow.endpointKey);
291
+ const current = latest.get(key);
292
+ if (!current || flow.seq > current.seq)
293
+ latest.set(key, flow);
294
+ }
295
+ return latest;
296
+ }
297
+ #currentFlowFor(adapter, endpointKey, owner) {
298
+ let found;
299
+ for (const flow of this.#flows.values()) {
300
+ if (flow.adapter !== adapter || flow.endpointKey !== endpointKey || flow.owner !== owner)
301
+ continue;
302
+ if (TERMINAL.has(flow.state))
303
+ continue;
304
+ if (!found || flow.seq > found.seq)
305
+ found = flow;
306
+ }
307
+ return found;
308
+ }
309
+ #createFlow(options, implicit) {
310
+ let previous;
311
+ for (const flow of [...this.#flows.values()]) {
312
+ if (flow.adapter !== options.adapter || flow.endpointKey !== options.endpointKey)
313
+ continue;
314
+ if (!previous || flow.seq > previous.seq)
315
+ previous = flow;
316
+ // The same Endpoint instance has one flow; finished flows of a replaced instance are dropped.
317
+ // An unfinished flow of another instance (rollover) stays until that instance cancels it.
318
+ if (flow.owner === options.owner || TERMINAL.has(flow.state)) {
319
+ if (!TERMINAL.has(flow.state))
320
+ this.#endFlow(flow, 'cancelled', 'superseded');
321
+ this.#flows.delete(flow.id);
322
+ }
323
+ }
324
+ const now = Date.now();
325
+ const flow = {
326
+ id: `flow-${randomUUID()}`,
327
+ adapter: options.adapter,
328
+ endpointKey: options.endpointKey,
329
+ ...(options.endpointIdentity ? { endpointIdentity: Object.freeze({ ...options.endpointIdentity }) } : {}),
330
+ owner: options.owner,
331
+ startedAt: now,
332
+ seq: ++this.#seq,
333
+ attempt: previous && previous.state !== 'online' ? previous.attempt + 1 : 1,
334
+ implicit,
335
+ updatedAt: now,
336
+ revision: 0,
337
+ state: 'active',
338
+ steps: [],
339
+ pendingConfirmation: false,
340
+ waiters: new Set(),
341
+ secrets: [],
342
+ };
343
+ this.#flows.set(flow.id, flow);
344
+ if (options.signal) {
345
+ const signal = options.signal;
346
+ const abort = () => { this.#endFlow(flow, 'cancelled', 'endpoint_retired'); };
347
+ signal.addEventListener('abort', abort, { once: true });
348
+ flow.detachAbort = () => signal.removeEventListener('abort', abort);
349
+ }
350
+ this.#emitFlow(flow);
351
+ return flow;
352
+ }
353
+ #handle(flow) {
354
+ if (flow.handle)
355
+ return flow.handle;
356
+ const live = () => this.#flows.get(flow.id) === flow && !TERMINAL.has(flow.state);
357
+ const handle = {
358
+ id: flow.id,
359
+ snapshot: () => this.#snapshot(flow),
360
+ step: (kind, title, detail, titleKey) => (live() ? this.#addStep(flow, kind, title, detail, titleKey) : ''),
361
+ challenge: async (descriptor, options) => {
362
+ if (!live())
363
+ throw new Error('login flow has ended');
364
+ const value = await this.#openChallenge(flow, descriptor, { timeoutMs: options?.timeoutMs });
365
+ return value.answer;
366
+ },
367
+ verifying: (label) => {
368
+ if (!live())
369
+ return;
370
+ this.#addVerifying(flow, label);
371
+ this.#emitFlow(flow);
372
+ },
373
+ outcome: (outcome) => { if (live())
374
+ this.#outcome(flow, outcome); },
375
+ online: () => { if (live())
376
+ this.#online(flow); },
377
+ fail: (code, message, next) => {
378
+ if (live())
379
+ this.#outcome(flow, { result: 'failed', code, ...(message ? { message } : {}), next: next ?? defaultNext(code) });
380
+ },
381
+ end: (reason = 'cancelled') => {
382
+ if (live())
383
+ this.#endFlow(flow, reason === 'expired' ? 'expired' : 'cancelled', reason);
384
+ },
385
+ };
386
+ flow.handle = Object.freeze(handle);
387
+ return flow.handle;
388
+ }
389
+ #openChallenge(flow, descriptor, options) {
390
+ const timeoutMs = resolveTimeoutMs(options.timeoutMs, this.defaultTimeoutMs);
391
+ const createdAt = Date.now();
392
+ const normalized = normalizeChallenge(descriptor, flow.secrets, this.#captchaHelperUrl);
393
+ const expiresAt = normalized.expiresAt ?? (timeoutMs != null ? createdAt + timeoutMs : undefined);
394
+ const challenge = Object.freeze({ ...normalized, ...(expiresAt !== undefined ? { expiresAt } : {}) });
395
+ // One active challenge per flow: the previous one is replaced, not silently cancelled.
396
+ if (flow.activeTaskId) {
397
+ const previous = this.pending.get(flow.activeTaskId);
398
+ if (previous)
399
+ this.#rejectEntry(previous, new LoginChallengeReplacedError(), 'skipped');
400
+ }
401
+ // A challenge that follows a submit means the answer was accepted and the flow moved on.
402
+ const verifying = lastActive(flow, 'verifying');
403
+ const accepted = verifying && !verifying.outcome
404
+ ? Object.freeze({ result: 'accepted' }) : undefined;
405
+ if (verifying && accepted)
406
+ verifying.outcome = accepted;
407
+ this.#closeActive(flow, ['verifying', 'connect'], 'done');
408
+ if (accepted)
409
+ this.#settle(flow, { outcome: accepted });
410
+ if (flow.verifyTimer) {
411
+ clearTimeout(flow.verifyTimer);
412
+ delete flow.verifyTimer;
413
+ }
414
+ flow.pendingConfirmation = false;
415
+ if (flow.state === 'expired')
416
+ flow.state = 'active';
417
+ const id = `login-${randomUUID()}`;
418
+ const stepId = `step-${randomUUID()}`;
419
+ const identity = options.endpointIdentity ?? flow.endpointIdentity;
420
+ const legacy = options.legacy;
421
+ const task = {
422
+ id,
423
+ adapter: flow.adapter,
424
+ endpointKey: flow.endpointKey,
425
+ ...(identity ? { endpointIdentity: Object.freeze({ ...identity }) } : {}),
426
+ type: legacy?.type ?? legacyTypeOf(challenge),
427
+ payload: legacy
428
+ ? { message: legacy.payload.message ?? '', ...legacy.payload }
429
+ : legacyPayloadOf(challenge),
430
+ createdAt,
431
+ ...(expiresAt !== undefined ? { expiresAt } : {}),
432
+ flowId: flow.id,
433
+ challengeId: challenge.id,
434
+ };
435
+ this.#pushStep(flow, {
436
+ id: stepId, kind: 'challenge', status: 'active', title: challenge.title, at: createdAt,
437
+ challenge, taskId: id,
438
+ });
439
+ flow.activeTaskId = id;
440
+ const effectiveTimeout = expiresAt !== undefined ? Math.max(0, expiresAt - createdAt) : undefined;
441
+ return new Promise((resolve, reject) => {
442
+ const entry = { task, owner: flow.owner, flow, stepId, legacy: !!legacy, resolve, reject };
443
+ if (effectiveTimeout !== undefined) {
444
+ // setTimeout overflows above 2^31-1 ms (~24.8 days) and would fire at once: re-arm in steps.
445
+ let remaining = effectiveTimeout;
446
+ const arm = () => {
447
+ const step = Math.min(remaining, MAX_TIMER_DELAY_MS);
448
+ remaining -= step;
449
+ entry.timer = setTimeout(() => {
450
+ if (remaining > 0) {
451
+ if (this.pending.get(id) === entry)
452
+ arm();
453
+ return;
454
+ }
455
+ expire();
456
+ }, step);
457
+ // Node: 不阻止进程退出
458
+ entry.timer.unref?.();
459
+ };
460
+ const expire = () => {
461
+ if (!this.pending.has(id))
462
+ return;
463
+ this.pending.delete(id);
464
+ this.#detach(entry);
465
+ try {
466
+ this.#notify('endpoint.login.expired', task);
467
+ }
468
+ catch {
469
+ /* observer failure must not leave the producer hanging forever */
470
+ }
471
+ this.#expireChallenge(flow, stepId, id);
472
+ reject(new Error(`LoginAssist task timed out after ${effectiveTimeout}ms`));
473
+ };
474
+ arm();
475
+ }
476
+ this.pending.set(id, entry);
477
+ if (options.signal) {
478
+ const signal = options.signal;
479
+ const abort = () => { this.cancel(id, 'endpoint_retired'); };
480
+ signal.addEventListener('abort', abort, { once: true });
481
+ entry.detachAbort = () => signal.removeEventListener('abort', abort);
482
+ if (signal.aborted)
483
+ abort();
484
+ }
485
+ if (this.pending.has(id)) {
486
+ this.#notify('endpoint.login.pending', task);
487
+ this.#emitFlow(flow);
488
+ }
489
+ });
490
+ }
491
+ #expireChallenge(flow, stepId, taskId) {
492
+ const step = flow.steps.find((item) => item.id === stepId);
493
+ const outcome = Object.freeze({
494
+ result: 'expired', code: 'challenge_expired',
495
+ next: step?.challenge?.media?.refreshable ? 'refresh_challenge' : 'relogin',
496
+ });
497
+ if (step) {
498
+ step.status = 'failed';
499
+ step.endedAt = Date.now();
500
+ step.outcome = outcome;
501
+ delete step.taskId;
502
+ dropMedia(step);
503
+ }
504
+ if (flow.activeTaskId === taskId)
505
+ delete flow.activeTaskId;
506
+ flow.lastOutcome = outcome;
507
+ if (!TERMINAL.has(flow.state))
508
+ flow.state = 'expired';
509
+ this.#settle(flow, { outcome });
510
+ this.#emitFlow(flow);
511
+ }
512
+ /** Reject one pending entry and retire its challenge step (no flow state change). */
513
+ #rejectEntry(entry, error, status) {
514
+ if (this.pending.get(entry.task.id) !== entry)
515
+ return;
516
+ this.pending.delete(entry.task.id);
517
+ this.#detach(entry);
518
+ const step = entry.flow.steps.find((item) => item.id === entry.stepId);
519
+ if (step && step.status === 'active') {
520
+ step.status = status;
521
+ step.endedAt = Date.now();
522
+ delete step.taskId;
523
+ dropMedia(step);
524
+ }
525
+ if (entry.flow.activeTaskId === entry.task.id)
526
+ delete entry.flow.activeTaskId;
527
+ entry.reject(error);
528
+ this.#notify('endpoint.login.resolved', entry.task);
529
+ }
530
+ #addStep(flow, kind, title, detail, titleKey) {
531
+ const id = `step-${randomUUID()}`;
532
+ if (kind !== 'info')
533
+ this.#closeActive(flow, ['connect', 'verifying'], 'done');
534
+ if (flow.state === 'expired')
535
+ flow.state = 'active';
536
+ const cleanDetail = detail ? sanitizeText(detail, flow.secrets) : '';
537
+ this.#pushStep(flow, {
538
+ id, kind, status: kind === 'info' ? 'done' : 'active',
539
+ title: sanitizeText(title, flow.secrets, 120) || kind,
540
+ ...(titleKey ? { titleKey } : {}),
541
+ ...(cleanDetail ? { detail: cleanDetail } : {}),
542
+ at: Date.now(),
543
+ });
544
+ this.#emitFlow(flow);
545
+ return id;
546
+ }
547
+ #addVerifying(flow, title, titleKey) {
548
+ const last = lastActive(flow, 'verifying');
549
+ if (last) {
550
+ last.title = sanitizeText(title, flow.secrets, 120) || last.title;
551
+ if (titleKey)
552
+ last.titleKey = titleKey;
553
+ else
554
+ delete last.titleKey;
555
+ return;
556
+ }
557
+ this.#closeActive(flow, ['connect'], 'done');
558
+ this.#pushStep(flow, {
559
+ id: `step-${randomUUID()}`, kind: 'verifying', status: 'active',
560
+ title: sanitizeText(title, flow.secrets, 120) || this.#verifyingTitle,
561
+ ...(titleKey ? { titleKey } : {}),
562
+ at: Date.now(),
563
+ });
564
+ }
565
+ #armVerifyTimer(flow) {
566
+ if (flow.verifyTimer)
567
+ clearTimeout(flow.verifyTimer);
568
+ delete flow.verifyTimer;
569
+ flow.pendingConfirmation = false;
570
+ if (!(this.#verifyTimeoutMs > 0) || !Number.isFinite(this.#verifyTimeoutMs))
571
+ return;
572
+ flow.verifyTimer = setTimeout(() => {
573
+ delete flow.verifyTimer;
574
+ if (TERMINAL.has(flow.state) || this.#flows.get(flow.id) !== flow)
575
+ return;
576
+ if (!lastActive(flow, 'verifying'))
577
+ return;
578
+ flow.pendingConfirmation = true;
579
+ this.#emitFlow(flow);
580
+ }, Math.min(this.#verifyTimeoutMs, MAX_TIMER_DELAY_MS));
581
+ flow.verifyTimer.unref?.();
582
+ }
583
+ #outcome(flow, input) {
584
+ const outcome = normalizeOutcome(input, flow.secrets);
585
+ if (outcome.result === 'online') {
586
+ this.#online(flow, outcome);
587
+ return;
588
+ }
589
+ const target = lastActive(flow, 'verifying')
590
+ ?? [...flow.steps].reverse().find((step) => step.kind === 'verifying' || step.kind === 'challenge')
591
+ ?? flow.steps.at(-1);
592
+ if (target) {
593
+ target.outcome = outcome;
594
+ if (target.status === 'active' || target.kind === 'verifying') {
595
+ target.status = outcome.result === 'accepted' ? 'done' : 'failed';
596
+ target.endedAt = Date.now();
597
+ }
598
+ }
599
+ flow.lastOutcome = outcome;
600
+ if (flow.verifyTimer) {
601
+ clearTimeout(flow.verifyTimer);
602
+ delete flow.verifyTimer;
603
+ }
604
+ flow.pendingConfirmation = false;
605
+ if (outcome.result === 'failed') {
606
+ this.#retireActiveChallenge(flow, 'login_failed');
607
+ this.#closeActive(flow, ['connect', 'verifying'], 'failed');
608
+ flow.state = 'failed';
609
+ this.#finish(flow);
610
+ }
611
+ else if (outcome.result === 'expired' && !flow.activeTaskId) {
612
+ flow.state = 'expired';
613
+ }
614
+ this.#settle(flow, { outcome });
615
+ this.#emitFlow(flow);
616
+ }
617
+ #online(flow, outcome = Object.freeze({ result: 'online' })) {
618
+ this.#retireActiveChallenge(flow, 'online');
619
+ const verifying = lastActive(flow, 'verifying');
620
+ if (verifying)
621
+ verifying.outcome = outcome;
622
+ this.#closeActive(flow, ['connect', 'verifying'], 'done');
623
+ if (flow.verifyTimer) {
624
+ clearTimeout(flow.verifyTimer);
625
+ delete flow.verifyTimer;
626
+ }
627
+ flow.pendingConfirmation = false;
628
+ flow.lastOutcome = outcome;
629
+ flow.state = 'online';
630
+ this.#finish(flow);
631
+ this.#settle(flow, { outcome });
632
+ this.#emitFlow(flow);
633
+ }
634
+ #endFlow(flow, state, reason) {
635
+ if (TERMINAL.has(flow.state))
636
+ return;
637
+ this.#retireActiveChallenge(flow, reason);
638
+ this.#closeActive(flow, ['connect', 'verifying'], 'skipped');
639
+ if (flow.verifyTimer) {
640
+ clearTimeout(flow.verifyTimer);
641
+ delete flow.verifyTimer;
642
+ }
643
+ flow.pendingConfirmation = false;
644
+ flow.state = state;
645
+ if (state === 'cancelled')
646
+ this.#finish(flow);
647
+ this.#settle(flow, {});
648
+ this.#emitFlow(flow);
649
+ }
650
+ #retireActiveChallenge(flow, reason) {
651
+ if (!flow.activeTaskId)
652
+ return;
653
+ const entry = this.pending.get(flow.activeTaskId);
654
+ if (entry)
655
+ this.#rejectEntry(entry, new Error(reason), 'skipped');
656
+ delete flow.activeTaskId;
657
+ }
658
+ #closeActive(flow, kinds, status) {
659
+ const now = Date.now();
660
+ for (const step of flow.steps) {
661
+ if (step.status !== 'active' || !kinds.includes(step.kind))
662
+ continue;
663
+ step.status = status;
664
+ step.endedAt = now;
665
+ }
666
+ }
667
+ #pushStep(flow, step) {
668
+ flow.steps.push(step);
669
+ while (flow.steps.length > LOGIN_FLOW_STEP_LIMIT) {
670
+ const index = flow.steps.findIndex((item) => item.status !== 'active');
671
+ flow.steps.splice(index < 0 ? 0 : index, 1);
672
+ }
673
+ }
674
+ #settle(flow, settled) {
675
+ for (const waiter of [...flow.waiters]) {
676
+ flow.waiters.delete(waiter);
677
+ waiter(settled);
678
+ }
679
+ }
680
+ #finish(flow) {
681
+ flow.detachAbort?.();
682
+ delete flow.detachAbort;
683
+ flow.secrets = [];
684
+ }
685
+ #snapshot(flow) {
686
+ const current = [...flow.steps].reverse().find((step) => step.status === 'active') ?? flow.steps.at(-1);
687
+ return Object.freeze({
688
+ id: flow.id,
689
+ adapter: flow.adapter,
690
+ endpointKey: flow.endpointKey,
691
+ ...(flow.endpointIdentity ? { endpointIdentity: flow.endpointIdentity } : {}),
692
+ startedAt: flow.startedAt,
693
+ updatedAt: flow.updatedAt,
694
+ revision: flow.revision,
695
+ attempt: flow.attempt,
696
+ state: flow.state,
697
+ ...(current ? { currentStep: current.id } : {}),
698
+ steps: Object.freeze(flow.steps.map((step) => freezeStep(step))),
699
+ ...(flow.lastOutcome ? { lastOutcome: flow.lastOutcome } : {}),
700
+ ...(flow.pendingConfirmation ? { pendingConfirmation: true } : {}),
701
+ ...(flow.activeTaskId ? { activeTaskId: flow.activeTaskId } : {}),
702
+ });
703
+ }
704
+ #emitFlow(flow) {
705
+ flow.revision += 1;
706
+ flow.updatedAt = Date.now();
707
+ this.#notify('endpoint.login.flow', this.#snapshot(flow));
708
+ }
709
+ #detach(entry) {
710
+ if (entry.timer)
711
+ clearTimeout(entry.timer);
712
+ entry.detachAbort?.();
713
+ }
714
+ #notify(name, payload) {
156
715
  try {
157
- this.bus?.emit(name, task);
716
+ this.bus?.emit(name, payload);
158
717
  }
159
718
  catch {
160
719
  /* bus observers must not break producer */
161
720
  }
162
721
  for (const listener of this.local.get(name) ?? []) {
163
722
  try {
164
- listener(task);
723
+ listener(payload);
165
724
  }
166
725
  catch {
167
726
  /* same */
@@ -169,9 +728,531 @@ export class LoginAssist {
169
728
  }
170
729
  }
171
730
  }
731
+ // ============================================================================
732
+ // Helpers
733
+ // ============================================================================
734
+ function lastActive(flow, kind) {
735
+ for (let index = flow.steps.length - 1; index >= 0; index -= 1) {
736
+ const step = flow.steps[index];
737
+ if (step.kind === kind && step.status === 'active')
738
+ return step;
739
+ }
740
+ return undefined;
741
+ }
742
+ /**
743
+ * Event / history-safe copy of a flow snapshot: QR images are replaced by `qrImageOmitted`,
744
+ * sensitive copy blocks are redacted, and verification links (`media.link`, `media.captcha`, link
745
+ * blocks) of slider / device / auth / link_verify challenges — they carry a session id — are
746
+ * dropped with `linkOmitted`. Operators (`endpoint.operate` on the Endpoint) read
747
+ * the live material with `login.flow.get`; read-only Console callers receive this form there too.
748
+ */
749
+ export function withoutLoginMedia(flow) {
750
+ if (!flow.steps.some((step) => step.challenge?.media?.qrImage || step.challenge?.blocks?.some(isSensitiveBlock)
751
+ || (step.challenge && hasVerificationLink(step.challenge))))
752
+ return flow;
753
+ return Object.freeze({
754
+ ...flow,
755
+ steps: Object.freeze(flow.steps.map((step) => {
756
+ const challenge = step.challenge;
757
+ if (!challenge)
758
+ return step;
759
+ let next = challenge;
760
+ if (challenge.media?.qrImage) {
761
+ const { qrImage: _image, ...rest } = challenge.media;
762
+ next = { ...next, media: Object.freeze({ ...rest, qrImageOmitted: true }) };
763
+ }
764
+ if (challenge.blocks?.some(isSensitiveBlock))
765
+ next = { ...next, blocks: redactBlocks(challenge.blocks) };
766
+ if (hasVerificationLink(next)) {
767
+ // The captcha query is the slider link's query string: same session id.
768
+ const { link: _link, captcha: _captcha, ...media } = next.media ?? {};
769
+ const blocks = next.blocks?.filter((block) => block.kind !== 'link');
770
+ const { blocks: _blocks, ...rest } = next;
771
+ next = {
772
+ ...rest,
773
+ ...(blocks && blocks.length > 0 ? { blocks: Object.freeze(blocks) } : {}),
774
+ media: Object.freeze({ ...media, linkOmitted: true }),
775
+ };
776
+ }
777
+ return next === challenge ? step : Object.freeze({ ...step, challenge: Object.freeze(next) });
778
+ })),
779
+ });
780
+ }
781
+ /**
782
+ * Links events and history must not contain. Every kind: verification links carry a session id
783
+ * (`sid=`), a QR challenge's link is the QR content itself, and a legacy `waitForInput` url lands in
784
+ * `media.link` whatever its type — live links are read with `login.flow.get` (operators only).
785
+ */
786
+ function hasVerificationLink(challenge) {
787
+ return !!challenge.media?.link || !!challenge.media?.captcha || !!challenge.blocks?.some((block) => block.kind === 'link');
788
+ }
789
+ /** Alias that names the purpose: what may enter events, history and logs. */
790
+ export const eventSafeLoginFlow = withoutLoginMedia;
791
+ /** Default next action for an error code. */
792
+ export function defaultNext(code) {
793
+ switch (code) {
794
+ case 'code_invalid': return 'retry_input';
795
+ case 'challenge_expired': return 'refresh_challenge';
796
+ case 'rate_limited':
797
+ case 'network': return 'wait';
798
+ case 'risk_blocked': return 'none';
799
+ default: return 'relogin';
800
+ }
801
+ }
802
+ /**
803
+ * Pure parser behind `input.extract: 'ticket-json-or-url'` (shared by Console, SDK and stdin).
804
+ * Accepts a raw ticket, `ticket,randstr`, a JSON response body (`{ ticket, randstr }`, also nested
805
+ * one level under `data` / `result`), or a URL with a `ticket=` query parameter.
806
+ */
807
+ export function parseLoginTicket(raw) {
808
+ if (typeof raw !== 'string')
809
+ return Object.freeze({ ok: false, error: '请粘贴 ticket、验证返回的 JSON 或带 ticket 的链接' });
810
+ const text = raw.trim();
811
+ if (!text)
812
+ return Object.freeze({ ok: false, error: '请粘贴 ticket、验证返回的 JSON 或带 ticket 的链接' });
813
+ const done = (ticket, randstr) => {
814
+ const value = typeof ticket === 'string' ? ticket.trim() : '';
815
+ if (!value)
816
+ return Object.freeze({ ok: false, error: '没有找到 ticket' });
817
+ if (/\s/u.test(value))
818
+ return Object.freeze({ ok: false, error: 'ticket 不应包含空白字符,请只粘贴 ticket 本身' });
819
+ const extra = typeof randstr === 'string' && randstr.trim() ? { randstr: randstr.trim() } : {};
820
+ return Object.freeze({ ok: true, ticket: value, ...extra });
821
+ };
822
+ if (text.startsWith('{')) {
823
+ let parsed;
824
+ try {
825
+ parsed = JSON.parse(text);
826
+ }
827
+ catch {
828
+ return Object.freeze({ ok: false, error: 'JSON 格式不完整,请复制完整的返回内容' });
829
+ }
830
+ const candidates = [parsed, parsed?.data, parsed?.result];
831
+ for (const candidate of candidates) {
832
+ if (candidate && typeof candidate === 'object' && typeof candidate.ticket === 'string') {
833
+ const record = candidate;
834
+ return done(record.ticket, record.randstr);
835
+ }
836
+ }
837
+ return Object.freeze({ ok: false, error: 'JSON 中没有 ticket 字段' });
838
+ }
839
+ if (/^https?:\/\//iu.test(text)) {
840
+ let url;
841
+ try {
842
+ url = new URL(text);
843
+ }
844
+ catch {
845
+ return Object.freeze({ ok: false, error: '链接格式不正确' });
846
+ }
847
+ const hash = new URLSearchParams(url.hash.replace(/^#/u, ''));
848
+ const ticket = url.searchParams.get('ticket') ?? hash.get('ticket');
849
+ if (!ticket)
850
+ return Object.freeze({ ok: false, error: '链接中没有 ticket 参数' });
851
+ return done(ticket, url.searchParams.get('randstr') ?? hash.get('randstr') ?? undefined);
852
+ }
853
+ const comma = text.split(',');
854
+ if (comma.length === 2 && comma[0].trim() && comma[1].trim())
855
+ return done(comma[0], comma[1]);
856
+ if (comma.length > 2)
857
+ return Object.freeze({ ok: false, error: '格式应为 ticket 或 ticket,randstr' });
858
+ return done(text);
859
+ }
860
+ /** Ticket text for an input with `extract: 'ticket-json-or-url'` (the raw text when unparseable). */
861
+ export function extractLoginTicket(raw) {
862
+ const parsed = parseLoginTicket(raw);
863
+ return parsed.ok ? parsed.ticket : raw.trim();
864
+ }
865
+ function endpointKeyOf(adapter, endpointKey) {
866
+ return `${adapter}\u0000${endpointKey}`;
867
+ }
868
+ function rememberSecret(flow, value) {
869
+ const text = value.trim();
870
+ if (text.length >= 3 && !flow.secrets.includes(text))
871
+ flow.secrets.push(text);
872
+ if (flow.secrets.length > 16)
873
+ flow.secrets.shift();
874
+ }
875
+ /** A challenge that is no longer active keeps neither its QR image nor sensitive material. */
876
+ function dropMedia(step) {
877
+ if (step.challenge?.media?.qrImage) {
878
+ const { qrImage: _image, ...rest } = step.challenge.media;
879
+ step.challenge = Object.freeze({ ...step.challenge, media: Object.freeze(rest) });
880
+ }
881
+ if (step.challenge?.blocks?.some(isSensitiveBlock)) {
882
+ step.challenge = Object.freeze({ ...step.challenge, blocks: redactBlocks(step.challenge.blocks) });
883
+ }
884
+ }
885
+ function isSensitiveBlock(block) {
886
+ return block.kind === 'copy' && !!block.sensitive && !block.redacted;
887
+ }
888
+ function redactBlocks(blocks) {
889
+ return Object.freeze(blocks.map((block) => (isSensitiveBlock(block)
890
+ ? Object.freeze({ ...block, content: '', redacted: true }) : block)));
891
+ }
892
+ function freezeStep(step) {
893
+ const challenge = step.challenge ? Object.freeze({
894
+ ...step.challenge,
895
+ ...(step.challenge.media ? { media: Object.freeze({ ...step.challenge.media }) } : {}),
896
+ actions: Object.freeze(step.challenge.actions.map((action) => Object.freeze({ ...action }))),
897
+ }) : undefined;
898
+ return Object.freeze({ ...step, ...(challenge ? { challenge } : {}) });
899
+ }
900
+ /** Single line, no control characters, bounded, submitted values redacted. */
901
+ function sanitizeText(value, secrets = [], max = 300) {
902
+ if (typeof value !== 'string')
903
+ return '';
904
+ // eslint-disable-next-line no-control-regex
905
+ let text = value.replace(/[\u0000-\u001f\u007f]+/gu, ' ').replace(/\s+/gu, ' ').trim();
906
+ for (const secret of secrets)
907
+ if (secret)
908
+ text = text.split(secret).join('***');
909
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
910
+ }
911
+ function safeLink(url) {
912
+ if (typeof url !== 'string' || !url.trim())
913
+ return undefined;
914
+ try {
915
+ const parsed = new URL(url.trim());
916
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.toString() : undefined;
917
+ }
918
+ catch {
919
+ return undefined;
920
+ }
921
+ }
922
+ const CHALLENGE_KINDS = ['qrcode', 'link_verify', 'slider', 'sms', 'device', 'auth', 'confirm', 'other'];
923
+ const ACTION_VARIANTS = ['primary', 'secondary', 'danger'];
924
+ const INPUT_KINDS = ['none', 'code', 'ticket', 'text'];
925
+ function normalizeChallenge(descriptor, secrets, captchaHelperUrl) {
926
+ const kind = CHALLENGE_KINDS.includes(descriptor.kind) ? descriptor.kind : 'other';
927
+ const input = descriptor.input && INPUT_KINDS.includes(descriptor.input.kind) && descriptor.input.kind !== 'none'
928
+ ? Object.freeze({
929
+ kind: descriptor.input.kind,
930
+ label: sanitizeText(descriptor.input.label, secrets, 80) || '输入',
931
+ ...(typeof descriptor.input.pattern === 'string' && validPattern(descriptor.input.pattern) ? { pattern: descriptor.input.pattern } : {}),
932
+ ...(typeof descriptor.input.patternHint === 'string' && descriptor.input.patternHint.trim()
933
+ ? { patternHint: sanitizeText(descriptor.input.patternHint, secrets, 120) } : {}),
934
+ ...(Number.isSafeInteger(descriptor.input.length) && descriptor.input.length > 0 ? { length: descriptor.input.length } : {}),
935
+ ...(descriptor.input.secret ? { secret: true } : {}),
936
+ ...(descriptor.input.extract === 'ticket-json-or-url' ? { extract: 'ticket-json-or-url' } : {}),
937
+ })
938
+ : descriptor.input?.kind === 'none' ? Object.freeze({ kind: 'none', label: sanitizeText(descriptor.input.label, secrets, 80) }) : undefined;
939
+ const hasInput = !!input && input.kind !== 'none';
940
+ const declared = (descriptor.actions ?? []).filter((action) => action && typeof action.id === 'string' && action.id
941
+ && typeof action.label === 'string');
942
+ const actions = declared.length > 0
943
+ ? declared.map((action) => Object.freeze({
944
+ id: action.id,
945
+ label: sanitizeText(action.label, secrets, 40) || action.id,
946
+ variant: ACTION_VARIANTS.includes(action.variant) ? action.variant : 'secondary',
947
+ ...(action.requiresInput && hasInput ? { requiresInput: true } : {}),
948
+ ...(Number.isFinite(action.cooldownMs) && action.cooldownMs > 0 ? { cooldownMs: action.cooldownMs } : {}),
949
+ }))
950
+ : [hasInput
951
+ ? Object.freeze({ id: 'submit', label: '提交', variant: 'primary', requiresInput: true })
952
+ : Object.freeze({ id: 'confirm', label: '已完成', variant: 'primary' })];
953
+ const link = descriptor.media?.link ? safeLink(descriptor.media.link.url) : undefined;
954
+ const qrImage = typeof descriptor.media?.qrImage === 'string' && descriptor.media.qrImage.trim()
955
+ ? descriptor.media.qrImage.trim() : undefined;
956
+ const media = descriptor.media ? {
957
+ ...(qrImage ? { qrImage } : {}),
958
+ ...(link ? { link: Object.freeze({ url: link, label: sanitizeText(descriptor.media.link?.label, secrets, 80) || link }) } : {}),
959
+ ...(Number.isFinite(descriptor.media.expiresAt) ? { expiresAt: descriptor.media.expiresAt } : {}),
960
+ ...(descriptor.media.refreshable ? { refreshable: true } : {}),
961
+ ...normalizeCaptcha(descriptor.media.captcha, captchaHelperUrl),
962
+ } : undefined;
963
+ const blocks = normalizeBlocks(descriptor.blocks, secrets);
964
+ const blockIds = new Set(blocks.map((block) => block.id).filter((id) => !!id));
965
+ const help = descriptor.help && typeof descriptor.help.short === 'string'
966
+ ? Object.freeze({
967
+ short: sanitizeText(descriptor.help.short, secrets),
968
+ ...(Array.isArray(descriptor.help.steps)
969
+ ? { steps: Object.freeze(descriptor.help.steps.slice(0, 12).map((step) => normalizeHelpStep(step, blockIds, secrets))
970
+ .filter((step) => (typeof step === 'string' ? step : step.text))) }
971
+ : {}),
972
+ ...(typeof descriptor.help.warning === 'string' && descriptor.help.warning.trim()
973
+ ? { warning: sanitizeText(descriptor.help.warning, secrets) } : {}),
974
+ })
975
+ : undefined;
976
+ return {
977
+ id: typeof descriptor.id === 'string' && descriptor.id ? descriptor.id.slice(0, 128) : `challenge-${randomUUID()}`,
978
+ kind,
979
+ title: sanitizeText(descriptor.title, secrets, 120) || kind,
980
+ ...(help ? { help } : {}),
981
+ ...(blocks.length > 0 ? { blocks: Object.freeze(blocks) } : {}),
982
+ ...(media && Object.keys(media).length > 0 ? { media } : {}),
983
+ ...(input ? { input } : {}),
984
+ actions: Object.freeze(actions),
985
+ ...(Number.isFinite(descriptor.expiresAt) ? { expiresAt: descriptor.expiresAt } : {}),
986
+ };
987
+ }
988
+ /** Keeps a Tencent captcha query (no `?`, bounded) and a valid helper URL. */
989
+ function normalizeCaptcha(captcha, configured) {
990
+ if (!captcha || captcha.provider !== 'tencent' || typeof captcha.query !== 'string')
991
+ return {};
992
+ const query = captcha.query.replace(/^\?/u, '');
993
+ if (!query || query.length > 4096 || /[\s#]/u.test(query))
994
+ return {};
995
+ const helperUrl = isValidCaptchaHelperUrl(captcha.helperUrl) ? captcha.helperUrl : configured;
996
+ return { captcha: Object.freeze({ provider: 'tencent', query, ...(helperUrl ? { helperUrl } : {}) }) };
997
+ }
998
+ const COPY_FORMATS = ['json', 'script', 'text'];
999
+ /** Upper bound of one copy block (device JSON and helper scripts are a few KiB). */
1000
+ const COPY_BLOCK_LIMIT = 32 * 1024;
1001
+ function normalizeHelpStep(step, blockIds, secrets) {
1002
+ if (typeof step === 'string')
1003
+ return sanitizeText(step, secrets);
1004
+ if (!step || typeof step !== 'object')
1005
+ return '';
1006
+ const text = sanitizeText(step.text, secrets);
1007
+ const blockId = typeof step.blockId === 'string' && blockIds.has(step.blockId) ? step.blockId : undefined;
1008
+ const doneWhen = step.doneWhen === 'copied' || step.doneWhen === 'opened' || step.doneWhen === 'manual' ? step.doneWhen : undefined;
1009
+ return Object.freeze({ text, ...(blockId ? { blockId } : {}), ...(doneWhen ? { doneWhen } : {}) });
1010
+ }
1011
+ /** Keeps well-formed blocks only: http/https links, bounded copy text, `thenOpen` to a known link. */
1012
+ function normalizeBlocks(input, secrets) {
1013
+ if (!Array.isArray(input))
1014
+ return [];
1015
+ const blocks = [];
1016
+ const ids = new Set();
1017
+ const id = (value) => {
1018
+ if (typeof value !== 'string' || !value || value.length > 64 || ids.has(value))
1019
+ return undefined;
1020
+ ids.add(value);
1021
+ return value;
1022
+ };
1023
+ for (const block of input.slice(0, 12)) {
1024
+ if (!block || typeof block !== 'object')
1025
+ continue;
1026
+ if (block.kind === 'link') {
1027
+ const url = safeLink(block.url);
1028
+ if (!url)
1029
+ continue;
1030
+ const blockId = id(block.id);
1031
+ blocks.push(Object.freeze({
1032
+ kind: 'link', ...(blockId ? { id: blockId } : {}),
1033
+ label: sanitizeText(block.label, secrets, 80) || url, url,
1034
+ ...(block.showQr ? { showQr: true } : {}),
1035
+ }));
1036
+ }
1037
+ else if (block.kind === 'note') {
1038
+ const text = sanitizeText(block.text, secrets);
1039
+ if (!text)
1040
+ continue;
1041
+ const blockId = id(block.id);
1042
+ blocks.push(Object.freeze({
1043
+ kind: 'note', ...(blockId ? { id: blockId } : {}), text,
1044
+ ...(block.tone === 'warning' || block.tone === 'info' ? { tone: block.tone } : {}),
1045
+ }));
1046
+ }
1047
+ else if (block.kind === 'copy') {
1048
+ const blockId = id(block.id);
1049
+ if (!blockId || typeof block.content !== 'string' || !block.content || block.content.length > COPY_BLOCK_LIMIT)
1050
+ continue;
1051
+ if (!COPY_FORMATS.includes(block.format))
1052
+ continue;
1053
+ blocks.push(Object.freeze({
1054
+ kind: 'copy', id: blockId, label: sanitizeText(block.label, secrets, 80) || blockId,
1055
+ // Multi-line material is kept verbatim (it is copied, not rendered as markup).
1056
+ content: block.content, format: block.format,
1057
+ ...(block.sensitive ? { sensitive: true } : {}),
1058
+ ...(block.collapsed ? { collapsed: true } : {}),
1059
+ ...(typeof block.collapsedLabel === 'string' && block.collapsedLabel.trim()
1060
+ ? { collapsedLabel: sanitizeText(block.collapsedLabel, secrets, 80) } : {}),
1061
+ ...(block.bookmarklet && block.format === 'script' ? { bookmarklet: true } : {}),
1062
+ ...(typeof block.thenOpen === 'string' && block.thenOpen ? { thenOpen: block.thenOpen } : {}),
1063
+ }));
1064
+ }
1065
+ }
1066
+ // `thenOpen` must name a link block of this challenge.
1067
+ const links = new Set(blocks.filter((block) => block.kind === 'link' && block.id).map((block) => block.id));
1068
+ return blocks.map((block) => {
1069
+ if (block.kind !== 'copy' || !block.thenOpen || links.has(block.thenOpen))
1070
+ return block;
1071
+ const { thenOpen: _drop, ...rest } = block;
1072
+ return Object.freeze(rest);
1073
+ });
1074
+ }
1075
+ function validPattern(pattern) {
1076
+ if (pattern.length > 200)
1077
+ return false;
1078
+ try {
1079
+ new RegExp(pattern, 'u');
1080
+ return true;
1081
+ }
1082
+ catch {
1083
+ return false;
1084
+ }
1085
+ }
1086
+ function normalizeOutcome(input, secrets) {
1087
+ const message = sanitizeText(input.message, secrets);
1088
+ return Object.freeze({
1089
+ result: input.result,
1090
+ ...(input.code && LOGIN_ERROR_CODES.includes(input.code) ? { code: input.code } : input.code ? { code: 'unknown' } : {}),
1091
+ ...(message ? { message } : {}),
1092
+ ...(input.next ? { next: input.next } : {}),
1093
+ ...(Number.isFinite(input.retryAfterMs) && input.retryAfterMs > 0 ? { retryAfterMs: input.retryAfterMs } : {}),
1094
+ });
1095
+ }
1096
+ /** Map a legacy waitForInput payload to a descriptor. */
1097
+ function legacyDescriptor(type, payload) {
1098
+ const message = typeof payload.message === 'string' ? payload.message : '';
1099
+ const image = typeof payload.image === 'string' ? payload.image : undefined;
1100
+ const url = typeof payload.url === 'string' ? payload.url : undefined;
1101
+ const link = url ? { url, label: url } : undefined;
1102
+ const media = image || link ? { ...(image ? { qrImage: image } : {}), ...(link ? { link } : {}) } : undefined;
1103
+ switch (type) {
1104
+ case 'qrcode':
1105
+ case 'auth':
1106
+ return {
1107
+ kind: type, title: message || (type === 'qrcode' ? '请扫码登录' : '请完成验证'),
1108
+ ...(media ? { media } : {}),
1109
+ actions: [{ id: 'confirm', label: '已完成', variant: 'primary' }],
1110
+ };
1111
+ case 'slider':
1112
+ return {
1113
+ kind: 'slider', title: message || '请完成滑块验证', ...(media ? { media } : {}),
1114
+ input: { kind: 'ticket', label: 'ticket', extract: 'ticket-json-or-url' },
1115
+ actions: [{ id: 'submit', label: '提交', variant: 'primary', requiresInput: true }],
1116
+ };
1117
+ case 'sms':
1118
+ case 'device':
1119
+ return {
1120
+ kind: type, title: message || '请输入验证码', ...(media ? { media } : {}),
1121
+ input: { kind: 'code', label: '验证码' },
1122
+ actions: [{ id: 'submit', label: '提交', variant: 'primary', requiresInput: true }],
1123
+ };
1124
+ default:
1125
+ return {
1126
+ kind: 'other', title: message || '登录辅助', ...(media ? { media } : {}),
1127
+ input: { kind: 'text', label: '输入' },
1128
+ actions: [{ id: 'submit', label: '提交', variant: 'primary', requiresInput: true }],
1129
+ };
1130
+ }
1131
+ }
1132
+ function legacyTypeOf(challenge) {
1133
+ const hasInput = !!challenge.input && challenge.input.kind !== 'none';
1134
+ switch (challenge.kind) {
1135
+ case 'qrcode': return 'qrcode';
1136
+ case 'slider': return hasInput ? 'slider' : 'auth';
1137
+ case 'sms': return hasInput ? 'sms' : 'auth';
1138
+ case 'device': return hasInput ? 'device' : 'auth';
1139
+ default: return hasInput ? 'other' : 'auth';
1140
+ }
1141
+ }
1142
+ /**
1143
+ * Legacy task payload of a flow challenge (`login.list`, older Consoles, chat commands): the title
1144
+ * with the short help, the QR image, and the main link (`media.link`, else the first link block).
1145
+ */
1146
+ function legacyPayloadOf(challenge) {
1147
+ const url = challenge.media?.link?.url
1148
+ ?? challenge.blocks?.find((block) => block.kind === 'link')?.url;
1149
+ return {
1150
+ message: challenge.help?.short ? `${challenge.title}:${challenge.help.short}` : challenge.title,
1151
+ ...(challenge.media?.qrImage ? { image: challenge.media.qrImage } : {}),
1152
+ ...(url ? { url } : {}),
1153
+ };
1154
+ }
1155
+ /** What a legacy waitForInput caller receives. */
1156
+ function legacyValue(value) {
1157
+ const raw = value.raw;
1158
+ if (typeof raw === 'string' || !isStructured(raw))
1159
+ return raw;
1160
+ // Only the descriptor's own default actions collapse to the input; any other action is the
1161
+ // caller's own vocabulary (icqq's device lock reads `{ action: 'sms' }`) and passes through.
1162
+ if (raw.action !== 'submit' && raw.action !== 'confirm')
1163
+ return raw;
1164
+ return value.answer.values.input ?? 'ok';
1165
+ }
1166
+ function isStructured(value) {
1167
+ return !!value && typeof value === 'object' && !Array.isArray(value)
1168
+ && typeof value.action === 'string';
1169
+ }
1170
+ function defaultAction(challenge, hasInput) {
1171
+ const actions = challenge?.actions ?? [];
1172
+ return ((hasInput ? actions.find((action) => action.requiresInput) : undefined)
1173
+ ?? actions.find((action) => action.variant === 'primary' && !action.requiresInput)
1174
+ ?? actions.find((action) => action.variant === 'primary')
1175
+ ?? actions[0]
1176
+ ?? { id: hasInput ? 'submit' : 'confirm' }).id;
1177
+ }
1178
+ function resolveAnswer(challenge, value, validate) {
1179
+ const input = challenge?.input && challenge.input.kind !== 'none' ? challenge.input : undefined;
1180
+ /** Input values for one raw text; `validate` raises precise errors. */
1181
+ const inputValues = (raw, required) => {
1182
+ const text = raw.trim();
1183
+ if (!input)
1184
+ return {};
1185
+ if (!text) {
1186
+ if (required && validate)
1187
+ throw new LoginSubmissionError('input_required', `${input.label} is required`);
1188
+ return {};
1189
+ }
1190
+ if (input.extract === 'ticket-json-or-url') {
1191
+ const parsed = parseLoginTicket(text);
1192
+ if (!parsed.ok) {
1193
+ if (validate)
1194
+ throw new LoginSubmissionError('input_invalid', parsed.error);
1195
+ return { input: text };
1196
+ }
1197
+ return { input: parsed.ticket, ...(parsed.randstr ? { randstr: parsed.randstr } : {}) };
1198
+ }
1199
+ if (validate) {
1200
+ if (input.length && text.length !== input.length) {
1201
+ throw new LoginSubmissionError('input_invalid', input.patternHint ?? `${input.label} must have ${input.length} characters`);
1202
+ }
1203
+ if (input.pattern && !new RegExp(input.pattern, 'u').test(text)) {
1204
+ throw new LoginSubmissionError('input_invalid', input.patternHint ?? `${input.label} has an invalid format`);
1205
+ }
1206
+ }
1207
+ return { input: text };
1208
+ };
1209
+ if (isStructured(value)) {
1210
+ const action = challenge?.actions.find((item) => item.id === value.action);
1211
+ // A legacy waitForInput task keeps accepting any structured action (e.g. icqq's `{ action: 'sms' }`).
1212
+ if (!action && challenge && validate)
1213
+ throw new LoginSubmissionError('invalid_action', `unknown login action: ${value.action.slice(0, 64)}`);
1214
+ const values = {};
1215
+ for (const [key, item] of Object.entries(value.values ?? {})) {
1216
+ if (key !== 'input' && (typeof item === 'string' || typeof item === 'number'))
1217
+ values[key] = String(item);
1218
+ }
1219
+ // The captcha helper answers `{ ticket: 'ticket,randstr' }`; it is the input of a ticket challenge.
1220
+ const rawInput = value.values?.input ?? (input?.extract === 'ticket-json-or-url' ? value.values?.ticket : undefined);
1221
+ const text = typeof rawInput === 'string' || typeof rawInput === 'number' ? String(rawInput) : '';
1222
+ Object.assign(values, inputValues(text, !!action?.requiresInput));
1223
+ return Object.freeze({ actionId: value.action, values: Object.freeze(values) });
1224
+ }
1225
+ if (typeof value === 'string') {
1226
+ // A plain string naming one of the challenge's actions that takes no input selects it, so
1227
+ // text-only consumers (released Consoles, stdin, chat) can still pick e.g. `sms`.
1228
+ const named = challenge?.actions.find((action) => !action.requiresInput && action.id === value.trim());
1229
+ if (named)
1230
+ return Object.freeze({ actionId: named.id, values: Object.freeze({}) });
1231
+ if (input) {
1232
+ const values = inputValues(value, true);
1233
+ return Object.freeze({ actionId: defaultAction(challenge, true), values: Object.freeze(values) });
1234
+ }
1235
+ return Object.freeze({ actionId: defaultAction(challenge, false), values: Object.freeze({}) });
1236
+ }
1237
+ // Legacy record (`{ ticket }`, `{ code }`, …).
1238
+ const values = {};
1239
+ for (const [key, item] of Object.entries(value))
1240
+ if (typeof item === 'string')
1241
+ values[key] = item.trim();
1242
+ const text = values.ticket ?? values.code ?? values.value ?? values.input;
1243
+ if (text)
1244
+ Object.assign(values, inputValues(text, false));
1245
+ return Object.freeze({ actionId: defaultAction(challenge, !!input), values: Object.freeze(values) });
1246
+ }
1247
+ /** Largest delay `setTimeout` accepts (2^31-1 ms); longer ones fire immediately. */
1248
+ const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
172
1249
  function resolveTimeoutMs(explicit, fallback) {
173
1250
  const raw = explicit === undefined ? fallback : explicit;
174
1251
  if (!Number.isFinite(raw) || raw <= 0)
175
1252
  return undefined;
176
1253
  return raw;
177
1254
  }
1255
+ function matchesIdentity(actual, expected) {
1256
+ return expected === undefined || (actual !== undefined && actual.canonicalId === expected.canonicalId
1257
+ && actual.instanceId === expected.instanceId && actual.epoch === expected.epoch && actual.incarnationId === expected.incarnationId);
1258
+ }