@im-more/dsh-dingtalk 0.0.0-stage → 0.1.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 (292) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +11 -0
  3. package/lib/index.js +2765 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/api/alitrip.d.ts +397 -0
  6. package/lib/types/api/alitrip.d.ts.map +1 -0
  7. package/lib/types/api/alitrip.js +21 -0
  8. package/lib/types/api/alitrip.js.map +1 -0
  9. package/lib/types/api/attendance.d.ts +63 -0
  10. package/lib/types/api/attendance.d.ts.map +1 -0
  11. package/lib/types/api/attendance.js +8 -0
  12. package/lib/types/api/attendance.js.map +1 -0
  13. package/lib/types/api/badge.d.ts +233 -0
  14. package/lib/types/api/badge.d.ts.map +1 -0
  15. package/lib/types/api/badge.js +19 -0
  16. package/lib/types/api/badge.js.map +1 -0
  17. package/lib/types/api/blackboard.d.ts +17 -0
  18. package/lib/types/api/blackboard.d.ts.map +1 -0
  19. package/lib/types/api/blackboard.js +6 -0
  20. package/lib/types/api/blackboard.js.map +1 -0
  21. package/lib/types/api/calendar.d.ts +621 -0
  22. package/lib/types/api/calendar.d.ts.map +1 -0
  23. package/lib/types/api/calendar.js +57 -0
  24. package/lib/types/api/calendar.js.map +1 -0
  25. package/lib/types/api/card.d.ts +185 -0
  26. package/lib/types/api/card.d.ts.map +1 -0
  27. package/lib/types/api/card.js +13 -0
  28. package/lib/types/api/card.js.map +1 -0
  29. package/lib/types/api/conference.d.ts +404 -0
  30. package/lib/types/api/conference.d.ts.map +1 -0
  31. package/lib/types/api/conference.js +60 -0
  32. package/lib/types/api/conference.js.map +1 -0
  33. package/lib/types/api/connector.d.ts +79 -0
  34. package/lib/types/api/connector.d.ts.map +1 -0
  35. package/lib/types/api/connector.js +8 -0
  36. package/lib/types/api/connector.js.map +1 -0
  37. package/lib/types/api/contact.d.ts +40 -0
  38. package/lib/types/api/contact.d.ts.map +1 -0
  39. package/lib/types/api/contact.js +9 -0
  40. package/lib/types/api/contact.js.map +1 -0
  41. package/lib/types/api/convFile.d.ts +135 -0
  42. package/lib/types/api/convFile.d.ts.map +1 -0
  43. package/lib/types/api/convFile.js +9 -0
  44. package/lib/types/api/convFile.js.map +1 -0
  45. package/lib/types/api/crm.d.ts +662 -0
  46. package/lib/types/api/crm.d.ts.map +1 -0
  47. package/lib/types/api/crm.js +59 -0
  48. package/lib/types/api/crm.js.map +1 -0
  49. package/lib/types/api/customerService.d.ts +128 -0
  50. package/lib/types/api/customerService.d.ts.map +1 -0
  51. package/lib/types/api/customerService.js +13 -0
  52. package/lib/types/api/customerService.js.map +1 -0
  53. package/lib/types/api/datacenter.d.ts +506 -0
  54. package/lib/types/api/datacenter.d.ts.map +1 -0
  55. package/lib/types/api/datacenter.js +61 -0
  56. package/lib/types/api/datacenter.js.map +1 -0
  57. package/lib/types/api/devicemng.d.ts +161 -0
  58. package/lib/types/api/devicemng.d.ts.map +1 -0
  59. package/lib/types/api/devicemng.js +20 -0
  60. package/lib/types/api/devicemng.js.map +1 -0
  61. package/lib/types/api/diot.d.ts +13 -0
  62. package/lib/types/api/diot.d.ts.map +1 -0
  63. package/lib/types/api/diot.js +4 -0
  64. package/lib/types/api/diot.js.map +1 -0
  65. package/lib/types/api/doc.d.ts +141 -0
  66. package/lib/types/api/doc.d.ts.map +1 -0
  67. package/lib/types/api/doc.js +27 -0
  68. package/lib/types/api/doc.js.map +1 -0
  69. package/lib/types/api/drive.d.ts +88 -0
  70. package/lib/types/api/drive.d.ts.map +1 -0
  71. package/lib/types/api/drive.js +11 -0
  72. package/lib/types/api/drive.js.map +1 -0
  73. package/lib/types/api/edu.d.ts +23 -0
  74. package/lib/types/api/edu.d.ts.map +1 -0
  75. package/lib/types/api/edu.js +4 -0
  76. package/lib/types/api/edu.js.map +1 -0
  77. package/lib/types/api/esign.d.ts +34 -0
  78. package/lib/types/api/esign.d.ts.map +1 -0
  79. package/lib/types/api/esign.js +7 -0
  80. package/lib/types/api/esign.js.map +1 -0
  81. package/lib/types/api/exclusive.d.ts +304 -0
  82. package/lib/types/api/exclusive.d.ts.map +1 -0
  83. package/lib/types/api/exclusive.js +27 -0
  84. package/lib/types/api/exclusive.js.map +1 -0
  85. package/lib/types/api/h3yun.d.ts +438 -0
  86. package/lib/types/api/h3yun.d.ts.map +1 -0
  87. package/lib/types/api/h3yun.js +33 -0
  88. package/lib/types/api/h3yun.js.map +1 -0
  89. package/lib/types/api/hrm.d.ts +215 -0
  90. package/lib/types/api/hrm.d.ts.map +1 -0
  91. package/lib/types/api/hrm.js +20 -0
  92. package/lib/types/api/hrm.js.map +1 -0
  93. package/lib/types/api/im.d.ts +773 -0
  94. package/lib/types/api/im.d.ts.map +1 -0
  95. package/lib/types/api/im.js +72 -0
  96. package/lib/types/api/im.js.map +1 -0
  97. package/lib/types/api/industry.d.ts +118 -0
  98. package/lib/types/api/industry.d.ts.map +1 -0
  99. package/lib/types/api/industry.js +14 -0
  100. package/lib/types/api/industry.js.map +1 -0
  101. package/lib/types/api/jzcrm.d.ts +255 -0
  102. package/lib/types/api/jzcrm.d.ts.map +1 -0
  103. package/lib/types/api/jzcrm.js +18 -0
  104. package/lib/types/api/jzcrm.js.map +1 -0
  105. package/lib/types/api/link.d.ts +73 -0
  106. package/lib/types/api/link.d.ts.map +1 -0
  107. package/lib/types/api/link.js +9 -0
  108. package/lib/types/api/link.js.map +1 -0
  109. package/lib/types/api/live.d.ts +132 -0
  110. package/lib/types/api/live.d.ts.map +1 -0
  111. package/lib/types/api/live.js +13 -0
  112. package/lib/types/api/live.js.map +1 -0
  113. package/lib/types/api/microApp.d.ts +240 -0
  114. package/lib/types/api/microApp.d.ts.map +1 -0
  115. package/lib/types/api/microApp.js +29 -0
  116. package/lib/types/api/microApp.js.map +1 -0
  117. package/lib/types/api/oapi.d.ts +3362 -0
  118. package/lib/types/api/oapi.d.ts.map +1 -0
  119. package/lib/types/api/oapi.js +247 -0
  120. package/lib/types/api/oapi.js.map +1 -0
  121. package/lib/types/api/oauth2.d.ts +115 -0
  122. package/lib/types/api/oauth2.d.ts.map +1 -0
  123. package/lib/types/api/oauth2.js +12 -0
  124. package/lib/types/api/oauth2.js.map +1 -0
  125. package/lib/types/api/pedia.d.ts +186 -0
  126. package/lib/types/api/pedia.d.ts.map +1 -0
  127. package/lib/types/api/pedia.js +13 -0
  128. package/lib/types/api/pedia.js.map +1 -0
  129. package/lib/types/api/project.d.ts +1119 -0
  130. package/lib/types/api/project.d.ts.map +1 -0
  131. package/lib/types/api/project.js +135 -0
  132. package/lib/types/api/project.js.map +1 -0
  133. package/lib/types/api/resident.d.ts +107 -0
  134. package/lib/types/api/resident.d.ts.map +1 -0
  135. package/lib/types/api/resident.js +10 -0
  136. package/lib/types/api/resident.js.map +1 -0
  137. package/lib/types/api/robot.d.ts +256 -0
  138. package/lib/types/api/robot.d.ts.map +1 -0
  139. package/lib/types/api/robot.js +21 -0
  140. package/lib/types/api/robot.js.map +1 -0
  141. package/lib/types/api/rooms.d.ts +256 -0
  142. package/lib/types/api/rooms.d.ts.map +1 -0
  143. package/lib/types/api/rooms.js +23 -0
  144. package/lib/types/api/rooms.js.map +1 -0
  145. package/lib/types/api/serviceGroup.d.ts +176 -0
  146. package/lib/types/api/serviceGroup.d.ts.map +1 -0
  147. package/lib/types/api/serviceGroup.js +15 -0
  148. package/lib/types/api/serviceGroup.js.map +1 -0
  149. package/lib/types/api/storage.d.ts +1241 -0
  150. package/lib/types/api/storage.d.ts.map +1 -0
  151. package/lib/types/api/storage.js +128 -0
  152. package/lib/types/api/storage.js.map +1 -0
  153. package/lib/types/api/swform.d.ts +71 -0
  154. package/lib/types/api/swform.d.ts.map +1 -0
  155. package/lib/types/api/swform.js +8 -0
  156. package/lib/types/api/swform.js.map +1 -0
  157. package/lib/types/api/todo.d.ts +169 -0
  158. package/lib/types/api/todo.d.ts.map +1 -0
  159. package/lib/types/api/todo.js +16 -0
  160. package/lib/types/api/todo.js.map +1 -0
  161. package/lib/types/api/wiki.d.ts +195 -0
  162. package/lib/types/api/wiki.d.ts.map +1 -0
  163. package/lib/types/api/wiki.js +11 -0
  164. package/lib/types/api/wiki.js.map +1 -0
  165. package/lib/types/api/workbench.d.ts +46 -0
  166. package/lib/types/api/workbench.d.ts.map +1 -0
  167. package/lib/types/api/workbench.js +14 -0
  168. package/lib/types/api/workbench.js.map +1 -0
  169. package/lib/types/api/yida.d.ts +1838 -0
  170. package/lib/types/api/yida.d.ts.map +1 -0
  171. package/lib/types/api/yida.js +103 -0
  172. package/lib/types/api/yida.js.map +1 -0
  173. package/lib/types/bot.d.ts +62 -0
  174. package/lib/types/bot.d.ts.map +1 -0
  175. package/lib/types/bot.js +134 -0
  176. package/lib/types/bot.js.map +1 -0
  177. package/lib/types/config.d.ts +47 -0
  178. package/lib/types/config.d.ts.map +1 -0
  179. package/lib/types/config.js +53 -0
  180. package/lib/types/config.js.map +1 -0
  181. package/lib/types/decode.d.ts +36 -0
  182. package/lib/types/decode.d.ts.map +1 -0
  183. package/lib/types/decode.js +200 -0
  184. package/lib/types/decode.js.map +1 -0
  185. package/lib/types/errors.d.ts +77 -0
  186. package/lib/types/errors.d.ts.map +1 -0
  187. package/lib/types/errors.js +249 -0
  188. package/lib/types/errors.js.map +1 -0
  189. package/lib/types/index.d.ts +22 -0
  190. package/lib/types/index.d.ts.map +1 -0
  191. package/lib/types/index.js +22 -0
  192. package/lib/types/index.js.map +1 -0
  193. package/lib/types/internal.d.ts +15 -0
  194. package/lib/types/internal.d.ts.map +1 -0
  195. package/lib/types/internal.js +57 -0
  196. package/lib/types/internal.js.map +1 -0
  197. package/lib/types/media.d.ts +57 -0
  198. package/lib/types/media.d.ts.map +1 -0
  199. package/lib/types/media.js +99 -0
  200. package/lib/types/media.js.map +1 -0
  201. package/lib/types/modes/markdown.d.ts +12 -0
  202. package/lib/types/modes/markdown.d.ts.map +1 -0
  203. package/lib/types/modes/markdown.js +148 -0
  204. package/lib/types/modes/markdown.js.map +1 -0
  205. package/lib/types/modes/shared.d.ts +183 -0
  206. package/lib/types/modes/shared.d.ts.map +1 -0
  207. package/lib/types/modes/shared.js +358 -0
  208. package/lib/types/modes/shared.js.map +1 -0
  209. package/lib/types/request.d.ts +63 -0
  210. package/lib/types/request.d.ts.map +1 -0
  211. package/lib/types/request.js +182 -0
  212. package/lib/types/request.js.map +1 -0
  213. package/lib/types/send.d.ts +38 -0
  214. package/lib/types/send.d.ts.map +1 -0
  215. package/lib/types/send.js +128 -0
  216. package/lib/types/send.js.map +1 -0
  217. package/lib/types/token.d.ts +32 -0
  218. package/lib/types/token.d.ts.map +1 -0
  219. package/lib/types/token.js +62 -0
  220. package/lib/types/token.js.map +1 -0
  221. package/lib/types/transport/stream.d.ts +89 -0
  222. package/lib/types/transport/stream.d.ts.map +1 -0
  223. package/lib/types/transport/stream.js +345 -0
  224. package/lib/types/transport/stream.js.map +1 -0
  225. package/lib/types/transport/webhook.d.ts +54 -0
  226. package/lib/types/transport/webhook.d.ts.map +1 -0
  227. package/lib/types/transport/webhook.js +159 -0
  228. package/lib/types/transport/webhook.js.map +1 -0
  229. package/lib/types/types/index.d.ts +150 -0
  230. package/lib/types/types/index.d.ts.map +1 -0
  231. package/lib/types/types/index.js +43 -0
  232. package/lib/types/types/index.js.map +1 -0
  233. package/package.json +61 -3
  234. package/src/api/.eslintrc.yml +2 -0
  235. package/src/api/alitrip.ts +467 -0
  236. package/src/api/attendance.ts +81 -0
  237. package/src/api/badge.ts +285 -0
  238. package/src/api/blackboard.ts +28 -0
  239. package/src/api/calendar.ts +817 -0
  240. package/src/api/card.ts +215 -0
  241. package/src/api/conference.ts +561 -0
  242. package/src/api/connector.ts +97 -0
  243. package/src/api/contact.ts +56 -0
  244. package/src/api/convFile.ts +166 -0
  245. package/src/api/crm.ts +830 -0
  246. package/src/api/customerService.ts +156 -0
  247. package/src/api/datacenter.ts +672 -0
  248. package/src/api/devicemng.ts +202 -0
  249. package/src/api/diot.ts +19 -0
  250. package/src/api/doc.ts +232 -0
  251. package/src/api/drive.ts +109 -0
  252. package/src/api/edu.ts +30 -0
  253. package/src/api/esign.ts +44 -0
  254. package/src/api/exclusive.ts +372 -0
  255. package/src/api/h3yun.ts +537 -0
  256. package/src/api/hrm.ts +272 -0
  257. package/src/api/im.ts +978 -0
  258. package/src/api/industry.ts +153 -0
  259. package/src/api/jzcrm.ts +304 -0
  260. package/src/api/link.ts +94 -0
  261. package/src/api/live.ts +162 -0
  262. package/src/api/microApp.ts +309 -0
  263. package/src/api/oapi.ts +4083 -0
  264. package/src/api/oauth2.ts +146 -0
  265. package/src/api/pedia.ts +222 -0
  266. package/src/api/project.ts +1519 -0
  267. package/src/api/resident.ts +133 -0
  268. package/src/api/robot.ts +326 -0
  269. package/src/api/rooms.ts +334 -0
  270. package/src/api/serviceGroup.ts +216 -0
  271. package/src/api/storage.ts +1701 -0
  272. package/src/api/swform.ts +94 -0
  273. package/src/api/todo.ts +220 -0
  274. package/src/api/wiki.ts +231 -0
  275. package/src/api/workbench.ts +73 -0
  276. package/src/api/yida.ts +2165 -0
  277. package/src/bot.ts +211 -0
  278. package/src/config.ts +88 -0
  279. package/src/decode.ts +250 -0
  280. package/src/errors.ts +282 -0
  281. package/src/index.ts +82 -0
  282. package/src/internal.ts +60 -0
  283. package/src/media.ts +149 -0
  284. package/src/modes/markdown.ts +173 -0
  285. package/src/modes/shared.ts +473 -0
  286. package/src/request.ts +262 -0
  287. package/src/send.ts +195 -0
  288. package/src/token.ts +72 -0
  289. package/src/transport/stream.ts +436 -0
  290. package/src/transport/webhook.ts +198 -0
  291. package/src/types/index.ts +165 -0
  292. package/README.md +0 -3
@@ -0,0 +1,436 @@
1
+ /**
2
+ * Stream Mode transport (`protocol: 'ws'`).
3
+ *
4
+ * The adapter registers a fresh connection before every dial: the platform's ticket is single-use and expires within 90
5
+ * seconds, so it can never be cached. The loop dials again forever — `ws.retryTimes` is a fast-retry budget, not a
6
+ * give-up count — and only a credential refusal stops it.
7
+ *
8
+ * A callback frame is acknowledged only after `bot.receive` accepted the message (`Bot.receive` waits for the intake
9
+ * listeners), so an acknowledgement always means the message is stored. Robot messages are fire-and-forget: the platform
10
+ * does not redeliver an acknowledged frame.
11
+ */
12
+
13
+ import { Status } from '@deepseek-ai/cordis-plugin-im-core'
14
+ import type {} from '@deepseek-ai/cordis-plugin-http'
15
+ import type { DingtalkBot } from '../bot.ts'
16
+ import { decodeMessage } from '../decode.ts'
17
+ import { isAuthRefusal, isCredentialRefusal } from '../errors.ts'
18
+ import { invoke } from '../request.ts'
19
+ import type { Message } from '../types/index.ts'
20
+
21
+ /** The one topic this adapter subscribes to. */
22
+ export const CALLBACK_TOPIC = '/v1.0/im/bot/messages/get'
23
+
24
+ /** System topics the protocol defines. */
25
+ const PING_TOPIC = 'ping'
26
+ const DISCONNECT_TOPIC = 'disconnect'
27
+
28
+ /**
29
+ * The `ua` of the connection registration (`name-sdk-lang/version`). Keep the version in step with `package.json`.
30
+ */
31
+ export const CLIENT_USER_AGENT = 'dsh-im-more/dingtalk/0.1.0'
32
+
33
+ /** The code of a protocol acknowledgement. */
34
+ export type AckCode = 200 | 404 | 500
35
+
36
+ /** The acknowledgement the protocol expects for one frame. */
37
+ export interface DingtalkAck {
38
+ code: AckCode
39
+ headers: { messageId?: string; contentType: string }
40
+ message: string
41
+ data?: string
42
+ }
43
+
44
+ /** One frame the platform pushes. `data` is a JSON string, so a callback body is parsed a second time. */
45
+ export interface DingtalkFrame {
46
+ specVersion?: string
47
+ type?: string
48
+ headers?: {
49
+ topic?: string
50
+ messageId?: string
51
+ contentType?: string
52
+ time?: string
53
+ }
54
+ data?: string
55
+ }
56
+
57
+ /** The answer of the connection registration. */
58
+ export interface DingtalkConnection {
59
+ endpoint?: string
60
+ ticket?: string
61
+ }
62
+
63
+ /** Waitable sleep that resolves early on abort. */
64
+ function sleep(ms: number, signal: AbortSignal): Promise<void> {
65
+ return new Promise((resolve) => {
66
+ if (signal.aborted) {
67
+ resolve()
68
+ return
69
+ }
70
+ const timer = setTimeout(() => {
71
+ signal.removeEventListener('abort', onAbort)
72
+ resolve()
73
+ }, ms)
74
+ const onAbort = (): void => {
75
+ clearTimeout(timer)
76
+ resolve()
77
+ }
78
+ signal.addEventListener('abort', onAbort, { once: true })
79
+ })
80
+ }
81
+
82
+ /** Message of any caught value, for a log line. */
83
+ function messageOf(error: unknown): string {
84
+ return error instanceof Error ? error.message : String(error)
85
+ }
86
+
87
+ /** The WebSocket the `http` service opens. */
88
+ type DingtalkSocket = ReturnType<DingtalkBot['ctx']['http']['ws']>
89
+
90
+ /** The Stream Mode client of one bot. */
91
+ export class DingtalkStream {
92
+ private controller: AbortController | undefined
93
+ private running: Promise<void> | undefined
94
+ private socket: DingtalkSocket | undefined
95
+ /** Set by a `disconnect` frame: the redial follows at once instead of waiting out the retry interval. */
96
+ private redialImmediately = false
97
+
98
+ constructor(private readonly bot: DingtalkBot) {}
99
+
100
+ /**
101
+ * Start the reconnect loop.
102
+ *
103
+ * Returning before the first dial is deliberate: `Bot.start` awaits `connect()`, and waiting here would hold plugin
104
+ * initialization for as long as the platform is unreachable.
105
+ */
106
+ async start(): Promise<void> {
107
+ this.controller = new AbortController()
108
+ this.running = this.loop(this.controller.signal)
109
+ }
110
+
111
+ /** Stop the loop and wait for it to unwind. */
112
+ async stop(): Promise<void> {
113
+ this.controller?.abort()
114
+ this.controller = undefined
115
+ this.closeSocket()
116
+ await this.running?.catch(() => undefined)
117
+ this.running = undefined
118
+ }
119
+
120
+ private async loop(signal: AbortSignal): Promise<void> {
121
+ let failures = 0
122
+ let authFailures = 0
123
+ while (!signal.aborted) {
124
+ try {
125
+ const url = await this.openUrl(signal)
126
+ const socket = await this.dial(url, signal)
127
+ this.socket = socket
128
+ this.bot.online()
129
+ failures = 0
130
+ authFailures = 0
131
+ await this.accept(socket, signal)
132
+ this.socket = undefined
133
+ if (signal.aborted) return
134
+ this.bot.ctx.logger.warn(
135
+ 'dingtalk: the Stream Mode connection closed; reconnecting',
136
+ )
137
+ this.bot.status = Status.RECONNECT
138
+ if (this.redialImmediately) {
139
+ this.redialImmediately = false
140
+ continue
141
+ }
142
+ await sleep(this.intervalOf(failures), signal)
143
+ } catch (error) {
144
+ if (signal.aborted) return
145
+ if (isCredentialRefusal(error)) {
146
+ // A rejected client id or secret cannot be fixed by reconnecting: report it and stop until the profile is
147
+ // edited.
148
+ this.bot.ctx.logger.error('dingtalk: %s', messageOf(error))
149
+ this.bot.offline(error)
150
+ return
151
+ }
152
+ authFailures = isAuthRefusal(error) ? authFailures + 1 : 0
153
+ failures += 1
154
+ this.bot.ctx.logger.warn('dingtalk: %s; reconnecting', messageOf(error))
155
+ this.bot.status = Status.RECONNECT
156
+ if (authFailures >= this.bot.config.ws.retryTimes) {
157
+ this.bot.ctx.logger.error(
158
+ 'dingtalk: %s consecutive authentication refusals; check appkey and secret, then restart the bot',
159
+ String(authFailures),
160
+ )
161
+ this.bot.offline(error)
162
+ return
163
+ }
164
+ await sleep(this.intervalOf(failures), signal)
165
+ }
166
+ }
167
+ }
168
+
169
+ /** Delay before the next dial: the fast interval while the failure budget lasts, the lazy one after it. */
170
+ private intervalOf(failures: number): number {
171
+ const { ws } = this.bot.config
172
+ return failures < ws.retryTimes ? ws.retryInterval : ws.retryLazy
173
+ }
174
+
175
+ /** Register one connection and give back the socket URL its single-use ticket belongs to. */
176
+ private async openUrl(signal: AbortSignal): Promise<string> {
177
+ const answer = await invoke<DingtalkConnection>(
178
+ this.bot,
179
+ 'api',
180
+ 'POST',
181
+ '/v1.0/gateway/connections/open',
182
+ {
183
+ data: {
184
+ clientId: this.bot.config.appkey,
185
+ clientSecret: this.bot.config.secret,
186
+ subscriptions: [{ type: 'CALLBACK', topic: CALLBACK_TOPIC }],
187
+ ua: CLIENT_USER_AGENT,
188
+ },
189
+ signal,
190
+ },
191
+ )
192
+ if (!answer.endpoint || !answer.ticket) {
193
+ throw new Error(
194
+ 'dingtalk: gateway/connections/open answered without an endpoint and ticket',
195
+ )
196
+ }
197
+ return `${answer.endpoint}?ticket=${encodeURIComponent(answer.ticket)}`
198
+ }
199
+
200
+ /** Dial the connection URL and resolve once the socket is open. */
201
+ private dial(url: string, signal: AbortSignal): Promise<DingtalkSocket> {
202
+ const socket = this.bot.ctx.http.ws(url)
203
+ return new Promise<DingtalkSocket>((resolve, reject) => {
204
+ const cleanup = (): void => {
205
+ socket.removeEventListener('open', onOpen)
206
+ socket.removeEventListener('error', onError)
207
+ socket.removeEventListener('close', onClose)
208
+ signal.removeEventListener('abort', onAbort)
209
+ }
210
+ const onOpen = (): void => {
211
+ cleanup()
212
+ resolve(socket)
213
+ }
214
+ const onError = (event: { message?: string }): void => {
215
+ cleanup()
216
+ reject(
217
+ new Error(
218
+ `dingtalk: WebSocket error${event.message === undefined ? '' : `: ${event.message}`}`,
219
+ ),
220
+ )
221
+ }
222
+ const onClose = (event: { code: number }): void => {
223
+ cleanup()
224
+ reject(
225
+ new Error(
226
+ `dingtalk: WebSocket closed before opening (code ${String(event.code)})`,
227
+ ),
228
+ )
229
+ }
230
+ const onAbort = (): void => {
231
+ cleanup()
232
+ reject(signal.reason ?? new Error('dingtalk: adapter stopped'))
233
+ }
234
+ if (signal.aborted) {
235
+ onAbort()
236
+ return
237
+ }
238
+ socket.addEventListener('open', onOpen)
239
+ socket.addEventListener('error', onError)
240
+ socket.addEventListener('close', onClose)
241
+ signal.addEventListener('abort', onAbort, { once: true })
242
+ })
243
+ }
244
+
245
+ /** Serve one open connection until it closes. */
246
+ private async accept(
247
+ socket: DingtalkSocket,
248
+ signal: AbortSignal,
249
+ ): Promise<void> {
250
+ const closed = new Promise<void>((resolve) => {
251
+ socket.addEventListener('close', () => {
252
+ resolve()
253
+ })
254
+ })
255
+ socket.addEventListener('message', (event) => {
256
+ this.handleFrame(socket, String(event.data))
257
+ })
258
+ const onAbort = (): void => {
259
+ this.closeSocket()
260
+ }
261
+ signal.addEventListener('abort', onAbort, { once: true })
262
+ try {
263
+ await closed
264
+ } finally {
265
+ signal.removeEventListener('abort', onAbort)
266
+ }
267
+ }
268
+
269
+ /** Dispatch one received frame: a system notice, a callback, or a topic this adapter does not subscribe to. */
270
+ private handleFrame(socket: DingtalkSocket, text: string): void {
271
+ let frame: DingtalkFrame
272
+ try {
273
+ frame = JSON.parse(text) as DingtalkFrame
274
+ } catch (error) {
275
+ this.bot.ctx.logger.warn(
276
+ 'dingtalk: cannot parse a Stream frame: %s',
277
+ messageOf(error),
278
+ )
279
+ return
280
+ }
281
+ if (typeof frame !== 'object' || frame === null) return
282
+ const topic = frame.headers?.topic
283
+ if (frame.type === 'SYSTEM' && topic === PING_TOPIC) {
284
+ this.acknowledge(socket, frame, {
285
+ code: 200,
286
+ message: 'OK',
287
+ data: opaqueEcho(frame.data),
288
+ })
289
+ return
290
+ }
291
+ if (frame.type === 'SYSTEM' && topic === DISCONNECT_TOPIC) {
292
+ // The platform closes the TCP connection ten seconds after this notice; closing now trades that window for one
293
+ // handshake.
294
+ this.bot.ctx.logger.info(
295
+ 'dingtalk: the platform announced the connection expiry; redialing',
296
+ )
297
+ this.redialImmediately = true
298
+ this.closeSocket()
299
+ return
300
+ }
301
+ if (frame.type === 'SYSTEM') {
302
+ // `CONNECTED`/`REGISTERED`-style notices need no answer; the set of topics is not documented.
303
+ this.bot.ctx.logger.debug(
304
+ 'dingtalk: ignored a system frame of topic "%s"',
305
+ topic ?? 'unknown',
306
+ )
307
+ return
308
+ }
309
+ if (frame.type === 'CALLBACK' && topic === CALLBACK_TOPIC) {
310
+ void this.deliver(socket, frame)
311
+ return
312
+ }
313
+ this.bot.ctx.logger.debug(
314
+ 'dingtalk: ignored a frame of type "%s" and topic "%s"',
315
+ frame.type ?? 'unknown',
316
+ topic ?? 'unknown',
317
+ )
318
+ this.acknowledge(socket, frame, {
319
+ code: 404,
320
+ message: 'topic not supported',
321
+ })
322
+ }
323
+
324
+ /**
325
+ * Hand one callback frame to intake, then acknowledge it.
326
+ *
327
+ * The acknowledgement goes out after `receive` resolved: the host stores a message before `receive` returns, so an
328
+ * acknowledged frame is a stored message. A failed intake is only logged, because no acknowledgement means the
329
+ * platform will not redeliver anyway (robot messages are fire-and-forget).
330
+ */
331
+ private async deliver(
332
+ socket: DingtalkSocket,
333
+ frame: DingtalkFrame,
334
+ ): Promise<void> {
335
+ let body: Message
336
+ try {
337
+ body = JSON.parse(frame.data ?? '') as Message
338
+ } catch (error) {
339
+ this.bot.ctx.logger.error(
340
+ 'dingtalk: cannot parse a callback body: %s',
341
+ messageOf(error),
342
+ )
343
+ this.acknowledge(socket, frame, { code: 500, message: 'internal error' })
344
+ return
345
+ }
346
+ let session
347
+ try {
348
+ session = decodeMessage(this.bot, body)
349
+ } catch (error) {
350
+ this.bot.ctx.logger.error(
351
+ 'dingtalk: cannot decode a callback: %s',
352
+ messageOf(error),
353
+ )
354
+ this.acknowledge(socket, frame, { code: 500, message: 'internal error' })
355
+ return
356
+ }
357
+ if (session === undefined) {
358
+ // A quota failure or an unsupported msgtype: the frame was handled, there is just nothing to store.
359
+ this.acknowledge(socket, frame, {
360
+ code: 200,
361
+ message: 'OK',
362
+ data: '{"response":null}',
363
+ })
364
+ return
365
+ }
366
+ try {
367
+ await this.bot.receive(session)
368
+ } catch (error) {
369
+ this.bot.ctx.logger.error('dingtalk: intake failed: %s', messageOf(error))
370
+ return
371
+ }
372
+ this.acknowledge(socket, frame, {
373
+ code: 200,
374
+ message: 'OK',
375
+ data: '{"response":null}',
376
+ })
377
+ }
378
+
379
+ /** Send one acknowledgement; a socket that already closed cannot carry it, which is only logged. */
380
+ private acknowledge(
381
+ socket: DingtalkSocket,
382
+ frame: DingtalkFrame,
383
+ body: { code: AckCode; message: string; data?: string },
384
+ ): void {
385
+ const ack: DingtalkAck = {
386
+ code: body.code,
387
+ headers: {
388
+ ...(frame.headers?.messageId === undefined
389
+ ? {}
390
+ : { messageId: frame.headers.messageId }),
391
+ contentType: 'application/json',
392
+ },
393
+ message: body.message,
394
+ ...(body.data === undefined ? {} : { data: body.data }),
395
+ }
396
+ try {
397
+ socket.send(JSON.stringify(ack))
398
+ } catch (error) {
399
+ this.bot.ctx.logger.warn(
400
+ 'dingtalk: could not acknowledge a frame: %s',
401
+ messageOf(error),
402
+ )
403
+ }
404
+ }
405
+
406
+ private closeSocket(): void {
407
+ const socket = this.socket
408
+ this.socket = undefined
409
+ try {
410
+ socket?.close(1000, 'adapter stopped')
411
+ } catch (error) {
412
+ // The socket is already closed or closing; nothing left to release.
413
+ error
414
+ }
415
+ }
416
+ }
417
+
418
+ /**
419
+ * The acknowledgement body of a `ping`: the frame's `opaque` value echoed back.
420
+ *
421
+ * @param data - the frame's JSON-string `data`, expected to carry `opaque`.
422
+ * @returns a JSON string carrying the same `opaque`, or the original string when it cannot be read.
423
+ */
424
+ function opaqueEcho(data: string | undefined): string {
425
+ if (data === undefined) return '{"opaque":null}'
426
+ try {
427
+ const parsed = JSON.parse(data) as { opaque?: unknown }
428
+ if (typeof parsed === 'object' && parsed !== null && 'opaque' in parsed) {
429
+ return JSON.stringify({ opaque: parsed.opaque })
430
+ }
431
+ } catch (error) {
432
+ // Not JSON: the frame cannot be echoed structurally; the raw string is the closest answer.
433
+ error
434
+ }
435
+ return data
436
+ }
@@ -0,0 +1,198 @@
1
+ /**
2
+ * HTTP callback transport (`protocol: 'http'`).
3
+ *
4
+ * The platform posts bot messages to a URL configured in the developer console; the adapter registers that path on the
5
+ * profile's `webServer` and verifies the request with the platform's own `secret`
6
+ * (`Base64(HMAC-SHA256(key = secret, message = timestamp + "\n" + secret))`).
7
+ *
8
+ * The handler answers `200` once the message is stored and `500` when intake failed, so a retrying platform can resend;
9
+ * every refusal is answered before any work is done.
10
+ */
11
+
12
+ import { createHmac, timingSafeEqual } from 'node:crypto'
13
+ import type { IncomingMessage, ServerResponse } from 'node:http'
14
+ import type { DingtalkBot } from '../bot.ts'
15
+ import { routePath } from '../config.ts'
16
+ import { decodeMessage } from '../decode.ts'
17
+ import type { Message } from '../types/index.ts'
18
+
19
+ /** The part of `ctx.webServer` this adapter uses. */
20
+ interface WebServerLike {
21
+ register(route: {
22
+ kind: 'exact'
23
+ path: string
24
+ auth: 'anonymous'
25
+ handler: (
26
+ request: IncomingMessage,
27
+ response: ServerResponse,
28
+ ) => void | Promise<void>
29
+ }): () => void
30
+ }
31
+
32
+ /** How far a request's `timestamp` may be from now; the platform documents an hour. */
33
+ export const TIMESTAMP_WINDOW_MS = 60 * 60 * 1_000
34
+
35
+ /**
36
+ * The `sign` header value of one request.
37
+ *
38
+ * @param secret - the application Client Secret.
39
+ * @param timestamp - the request's `timestamp` header.
40
+ * @returns the base64 HMAC-SHA256 of `timestamp + "\n" + secret`.
41
+ */
42
+ export function signOf(secret: string, timestamp: string): string {
43
+ return createHmac('sha256', secret)
44
+ .update(`${timestamp}\n${secret}`)
45
+ .digest('base64')
46
+ }
47
+
48
+ /**
49
+ * Compare two signatures without leaking where they differ.
50
+ *
51
+ * @param expected - the signature computed from the headers.
52
+ * @param received - the signature the request carried.
53
+ * @returns whether they are equal.
54
+ */
55
+ export function matchesSign(expected: string, received: string): boolean {
56
+ const left = Buffer.from(expected, 'utf8')
57
+ const right = Buffer.from(received, 'utf8')
58
+ if (left.length !== right.length) return false
59
+ return timingSafeEqual(left, right)
60
+ }
61
+
62
+ /** One header of an inbound request, when it arrived exactly once. */
63
+ function headerOf(request: IncomingMessage, name: string): string | undefined {
64
+ const value = request.headers[name]
65
+ return typeof value === 'string' ? value : undefined
66
+ }
67
+
68
+ /** Read a request body to its end. The adapter imposes no size limit of its own. */
69
+ async function readBody(request: IncomingMessage): Promise<string> {
70
+ const chunks: Buffer[] = []
71
+ for await (const chunk of request) {
72
+ chunks.push(
73
+ Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array),
74
+ )
75
+ }
76
+ return Buffer.concat(chunks).toString('utf8')
77
+ }
78
+
79
+ /** Write one bodiless answer. */
80
+ function writeStatus(
81
+ response: ServerResponse,
82
+ status: number,
83
+ headers: Record<string, string> = {},
84
+ ): void {
85
+ response.writeHead(status, headers)
86
+ response.end()
87
+ }
88
+
89
+ /** Message of any caught value, for a log line. */
90
+ function messageOf(error: unknown): string {
91
+ return error instanceof Error ? error.message : String(error)
92
+ }
93
+
94
+ /**
95
+ * The HTTP callback transport.
96
+ *
97
+ * The route is anonymous at the Web server layer and authenticated by the platform's signature, so a profile without
98
+ * `webServer` fails loudly instead of silently receiving nothing.
99
+ */
100
+ export class DingtalkWebhook {
101
+ private dispose: (() => void) | undefined
102
+
103
+ constructor(private readonly bot: DingtalkBot) {}
104
+
105
+ /** Register the route over the profile's `webServer`. */
106
+ async start(): Promise<void> {
107
+ const webServer = this.bot.ctx.get('webServer') as WebServerLike | undefined
108
+ if (webServer === undefined) {
109
+ throw this.failStart(
110
+ 'dingtalk: protocol "http" needs a profile-provided webServer; use protocol "ws" instead',
111
+ )
112
+ }
113
+ // A profile that cannot mint a token cannot answer a callback either, so the failure surfaces at start rather than
114
+ // on the first incoming message.
115
+ await this.bot.tokens.get()
116
+ this.dispose = webServer.register({
117
+ kind: 'exact',
118
+ path: routePath(this.bot.config.path),
119
+ auth: 'anonymous',
120
+ handler: (request, response) => this.handle(request, response),
121
+ })
122
+ this.bot.online()
123
+ }
124
+
125
+ /** Release the route. */
126
+ async stop(): Promise<void> {
127
+ this.dispose?.()
128
+ this.dispose = undefined
129
+ }
130
+
131
+ /**
132
+ * Log a fatal start failure before the caller throws it, because `Bot.start` only stores a connect failure on
133
+ * `bot.error`.
134
+ *
135
+ * @param message - error text that also names the corrective action.
136
+ * @returns the error for the caller to throw.
137
+ */
138
+ private failStart(message: string): Error {
139
+ this.bot.ctx.logger.error(message)
140
+ return new Error(message)
141
+ }
142
+
143
+ private async handle(
144
+ request: IncomingMessage,
145
+ response: ServerResponse,
146
+ ): Promise<void> {
147
+ try {
148
+ if (request.method !== 'POST') {
149
+ writeStatus(response, 405, { allow: 'POST' })
150
+ return
151
+ }
152
+ const timestamp = headerOf(request, 'timestamp')
153
+ const sign = headerOf(request, 'sign')
154
+ if (timestamp === undefined || sign === undefined) {
155
+ writeStatus(response, 401)
156
+ return
157
+ }
158
+ const sentAt = Number(timestamp)
159
+ if (
160
+ !Number.isFinite(sentAt) ||
161
+ Math.abs(Date.now() - sentAt) > TIMESTAMP_WINDOW_MS
162
+ ) {
163
+ writeStatus(response, 401)
164
+ return
165
+ }
166
+ const body = await readBody(request)
167
+ let parsed: unknown
168
+ try {
169
+ parsed = JSON.parse(body)
170
+ } catch (error) {
171
+ this.bot.ctx.logger.warn(
172
+ 'dingtalk: cannot parse a callback request: %s',
173
+ messageOf(error),
174
+ )
175
+ writeStatus(response, 400)
176
+ return
177
+ }
178
+ if (typeof parsed !== 'object' || parsed === null) {
179
+ writeStatus(response, 400)
180
+ return
181
+ }
182
+ if (!matchesSign(signOf(this.bot.config.secret, timestamp), sign)) {
183
+ writeStatus(response, 401)
184
+ return
185
+ }
186
+ const session = decodeMessage(this.bot, parsed as Message)
187
+ if (session !== undefined) await this.bot.receive(session)
188
+ writeStatus(response, 200)
189
+ } catch (error) {
190
+ this.bot.ctx.logger.warn(
191
+ 'dingtalk: HTTP callback delivery failed: %s',
192
+ messageOf(error),
193
+ )
194
+ if (!response.headersSent) writeStatus(response, 500)
195
+ else response.end()
196
+ }
197
+ }
198
+ }