@im-more/dsh-wecom 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.
- package/LICENSE +21 -0
- package/cordis.patch.yml +13 -0
- package/lib/index.js +2077 -0
- package/lib/index.js.map +1 -0
- package/lib/types/bot.d.ts +50 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +126 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +48 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +68 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/crypto.d.ts +69 -0
- package/lib/types/crypto.d.ts.map +1 -0
- package/lib/types/crypto.js +129 -0
- package/lib/types/crypto.js.map +1 -0
- package/lib/types/decode.d.ts +58 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +182 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +67 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +170 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/identity.d.ts +20 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +34 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/index.d.ts +19 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +18 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/internal.d.ts +154 -0
- package/lib/types/internal.d.ts.map +1 -0
- package/lib/types/internal.js +115 -0
- package/lib/types/internal.js.map +1 -0
- package/lib/types/media.d.ts +44 -0
- package/lib/types/media.d.ts.map +1 -0
- package/lib/types/media.js +116 -0
- package/lib/types/media.js.map +1 -0
- package/lib/types/modes/markdown.d.ts +20 -0
- package/lib/types/modes/markdown.d.ts.map +1 -0
- package/lib/types/modes/markdown.js +205 -0
- package/lib/types/modes/markdown.js.map +1 -0
- package/lib/types/modes/shared.d.ts +227 -0
- package/lib/types/modes/shared.d.ts.map +1 -0
- package/lib/types/modes/shared.js +487 -0
- package/lib/types/modes/shared.js.map +1 -0
- package/lib/types/request.d.ts +55 -0
- package/lib/types/request.d.ts.map +1 -0
- package/lib/types/request.js +202 -0
- package/lib/types/request.js.map +1 -0
- package/lib/types/send.d.ts +54 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +124 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/token.d.ts +34 -0
- package/lib/types/token.d.ts.map +1 -0
- package/lib/types/token.js +61 -0
- package/lib/types/token.js.map +1 -0
- package/lib/types/transport/webhook.d.ts +41 -0
- package/lib/types/transport/webhook.d.ts.map +1 -0
- package/lib/types/transport/webhook.js +216 -0
- package/lib/types/transport/webhook.js.map +1 -0
- package/lib/types/types.d.ts +58 -0
- package/lib/types/types.d.ts.map +1 -0
- package/lib/types/types.js +2 -0
- package/lib/types/types.js.map +1 -0
- package/lib/types/xml.d.ts +40 -0
- package/lib/types/xml.d.ts.map +1 -0
- package/lib/types/xml.js +82 -0
- package/lib/types/xml.js.map +1 -0
- package/package.json +65 -3
- package/src/bot.ts +195 -0
- package/src/config.ts +117 -0
- package/src/crypto.ts +172 -0
- package/src/decode.ts +238 -0
- package/src/errors.ts +199 -0
- package/src/identity.ts +41 -0
- package/src/index.ts +101 -0
- package/src/internal.ts +237 -0
- package/src/media.ts +157 -0
- package/src/modes/markdown.ts +263 -0
- package/src/modes/shared.ts +618 -0
- package/src/request.ts +291 -0
- package/src/send.ts +172 -0
- package/src/token.ts +75 -0
- package/src/transport/webhook.ts +292 -0
- package/src/types.ts +74 -0
- package/src/xml.ts +89 -0
- package/README.md +0 -3
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The callback transport.
|
|
3
|
+
*
|
|
4
|
+
* A self-built application has exactly one inbound path: the platform POSTs an encrypted XML envelope to the URL saved
|
|
5
|
+
* in 接收消息 → 设置API接收, and verifies that URL by a GET to the same address when the configuration is saved. Both
|
|
6
|
+
* methods are answered by one handler because a `WebRoute` does not match on the method, and splitting them into two
|
|
7
|
+
* routes of the same path would make the registration order decide which one sees the GET.
|
|
8
|
+
*
|
|
9
|
+
* The handler answers `200` only after `bot.receive` stored the message, so a platform that retries a timed-out delivery
|
|
10
|
+
* finds the repeat deduplicated by `${bot.id}|${event.id}`; an intake failure answers `500` instead of pretending.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
14
|
+
import type { WecomBot } from '../bot.ts'
|
|
15
|
+
import { routePath } from '../config.ts'
|
|
16
|
+
import { decryptPayload, matchesSignature, signatureOf } from '../crypto.ts'
|
|
17
|
+
import { decodeMessage } from '../decode.ts'
|
|
18
|
+
import { parseMessageXml, parseXml, WecomXmlError } from '../xml.ts'
|
|
19
|
+
import type { XmlFields } from '../xml.ts'
|
|
20
|
+
|
|
21
|
+
/** The part of `ctx.webServer` this adapter registers on. */
|
|
22
|
+
export interface WebServerLike {
|
|
23
|
+
register(route: WebHandlerRoute): () => void
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** One exact path answered by a handler that owns the whole response. */
|
|
27
|
+
export interface WebHandlerRoute {
|
|
28
|
+
kind: 'exact'
|
|
29
|
+
path: string
|
|
30
|
+
auth: 'anonymous'
|
|
31
|
+
handler: (
|
|
32
|
+
request: IncomingMessage,
|
|
33
|
+
response: ServerResponse,
|
|
34
|
+
) => void | Promise<void>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Message of any caught value, for a log line. */
|
|
38
|
+
function messageOf(error: unknown): string {
|
|
39
|
+
return error instanceof Error ? error.message : String(error)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Read a request body to its end. The callback body is small and the platform publishes no size limit. */
|
|
43
|
+
async function readBody(request: IncomingMessage): Promise<string> {
|
|
44
|
+
const chunks: Buffer[] = []
|
|
45
|
+
for await (const chunk of request) {
|
|
46
|
+
chunks.push(
|
|
47
|
+
Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array),
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Write one bodiless answer. */
|
|
54
|
+
function writeStatus(
|
|
55
|
+
response: ServerResponse,
|
|
56
|
+
status: number,
|
|
57
|
+
headers: Record<string, string> = {},
|
|
58
|
+
): void {
|
|
59
|
+
response.writeHead(status, headers)
|
|
60
|
+
response.end()
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Write one plain-text answer, verbatim.
|
|
65
|
+
*
|
|
66
|
+
* The platform requires the decrypted `echostr` back without quotes, a byte-order mark or a trailing newline.
|
|
67
|
+
*/
|
|
68
|
+
function writeText(
|
|
69
|
+
response: ServerResponse,
|
|
70
|
+
status: number,
|
|
71
|
+
text: string,
|
|
72
|
+
): void {
|
|
73
|
+
response.writeHead(status, {
|
|
74
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
75
|
+
'content-length': String(Buffer.byteLength(text, 'utf8')),
|
|
76
|
+
})
|
|
77
|
+
response.end(text)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The decoded query of one request. */
|
|
81
|
+
function queryOf(request: IncomingMessage): URLSearchParams {
|
|
82
|
+
try {
|
|
83
|
+
return new URL(request.url ?? '/', 'http://localhost').searchParams
|
|
84
|
+
} catch {
|
|
85
|
+
// A request target the URL parser refuses names no parameters at all.
|
|
86
|
+
return new URLSearchParams()
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The one callback route of {@link WecomWebhook}. */
|
|
91
|
+
export class WecomWebhook {
|
|
92
|
+
private dispose: (() => void) | undefined
|
|
93
|
+
|
|
94
|
+
constructor(
|
|
95
|
+
private readonly bot: WecomBot,
|
|
96
|
+
private readonly webServer: WebServerLike,
|
|
97
|
+
) {}
|
|
98
|
+
|
|
99
|
+
/** Register the route over the profile's web server. */
|
|
100
|
+
start(): void {
|
|
101
|
+
this.dispose = this.webServer.register({
|
|
102
|
+
kind: 'exact',
|
|
103
|
+
path: routePath(this.bot.config.path),
|
|
104
|
+
auth: 'anonymous',
|
|
105
|
+
handler: (request, response) => this.handle(request, response),
|
|
106
|
+
})
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Release the route. */
|
|
110
|
+
stop(): void {
|
|
111
|
+
this.dispose?.()
|
|
112
|
+
this.dispose = undefined
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private async handle(
|
|
116
|
+
request: IncomingMessage,
|
|
117
|
+
response: ServerResponse,
|
|
118
|
+
): Promise<void> {
|
|
119
|
+
try {
|
|
120
|
+
switch (request.method) {
|
|
121
|
+
case 'GET':
|
|
122
|
+
await this.handleVerify(request, response)
|
|
123
|
+
return
|
|
124
|
+
case 'POST':
|
|
125
|
+
await this.handleCallback(request, response)
|
|
126
|
+
return
|
|
127
|
+
default:
|
|
128
|
+
writeStatus(response, 405, { allow: 'GET, POST' })
|
|
129
|
+
}
|
|
130
|
+
} catch (error) {
|
|
131
|
+
this.bot.ctx.logger.warn(
|
|
132
|
+
'wecom: callback delivery failed: %s',
|
|
133
|
+
messageOf(error),
|
|
134
|
+
)
|
|
135
|
+
if (!response.headersSent) writeStatus(response, 500)
|
|
136
|
+
else response.end()
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The URL verification the platform sends when the callback configuration is saved. */
|
|
141
|
+
private async handleVerify(
|
|
142
|
+
request: IncomingMessage,
|
|
143
|
+
response: ServerResponse,
|
|
144
|
+
): Promise<void> {
|
|
145
|
+
const query = queryOf(request)
|
|
146
|
+
const msgSignature = query.get('msg_signature')
|
|
147
|
+
const timestamp = query.get('timestamp')
|
|
148
|
+
const nonce = query.get('nonce')
|
|
149
|
+
const echostr = query.get('echostr')
|
|
150
|
+
if (
|
|
151
|
+
msgSignature === null ||
|
|
152
|
+
msgSignature === '' ||
|
|
153
|
+
timestamp === null ||
|
|
154
|
+
timestamp === '' ||
|
|
155
|
+
nonce === null ||
|
|
156
|
+
nonce === '' ||
|
|
157
|
+
echostr === null ||
|
|
158
|
+
echostr === ''
|
|
159
|
+
) {
|
|
160
|
+
writeStatus(response, 400)
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
const expected = signatureOf(
|
|
164
|
+
this.bot.config.token,
|
|
165
|
+
timestamp,
|
|
166
|
+
nonce,
|
|
167
|
+
echostr,
|
|
168
|
+
)
|
|
169
|
+
if (!matchesSignature(expected, msgSignature)) {
|
|
170
|
+
writeStatus(response, 403)
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
let plaintext: string
|
|
174
|
+
let receiveId: string
|
|
175
|
+
try {
|
|
176
|
+
const decrypted = decryptPayload(this.bot.config.aesKey, echostr)
|
|
177
|
+
plaintext = decrypted.message
|
|
178
|
+
receiveId = decrypted.receiveId
|
|
179
|
+
} catch (error) {
|
|
180
|
+
this.bot.ctx.logger.warn(
|
|
181
|
+
'wecom: verification payload could not be decrypted: %s',
|
|
182
|
+
messageOf(error),
|
|
183
|
+
)
|
|
184
|
+
writeStatus(response, 400)
|
|
185
|
+
return
|
|
186
|
+
}
|
|
187
|
+
if (receiveId !== this.bot.config.corpId) {
|
|
188
|
+
this.bot.ctx.logger.warn(
|
|
189
|
+
'wecom: verification payload was encrypted for %s, not corpId %s',
|
|
190
|
+
receiveId,
|
|
191
|
+
this.bot.config.corpId,
|
|
192
|
+
)
|
|
193
|
+
writeStatus(response, 403)
|
|
194
|
+
return
|
|
195
|
+
}
|
|
196
|
+
writeText(response, 200, plaintext)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** One business callback. */
|
|
200
|
+
private async handleCallback(
|
|
201
|
+
request: IncomingMessage,
|
|
202
|
+
response: ServerResponse,
|
|
203
|
+
): Promise<void> {
|
|
204
|
+
const query = queryOf(request)
|
|
205
|
+
const body = await readBody(request)
|
|
206
|
+
let outer: XmlFields
|
|
207
|
+
try {
|
|
208
|
+
outer = await parseXml(body)
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (error instanceof WecomXmlError) {
|
|
211
|
+
this.bot.ctx.logger.warn(
|
|
212
|
+
'wecom: cannot parse a callback request: %s',
|
|
213
|
+
messageOf(error),
|
|
214
|
+
)
|
|
215
|
+
writeStatus(response, 400)
|
|
216
|
+
return
|
|
217
|
+
}
|
|
218
|
+
throw error
|
|
219
|
+
}
|
|
220
|
+
if (outer.AgentID !== this.bot.config.agentId) {
|
|
221
|
+
// Another application of the same enterprise posts to the same URL; the envelope names whose callback this is.
|
|
222
|
+
writeStatus(response, 403)
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
let fields = outer
|
|
226
|
+
const encrypt = outer.Encrypt
|
|
227
|
+
if (encrypt !== undefined && encrypt !== '') {
|
|
228
|
+
const msgSignature = query.get('msg_signature')
|
|
229
|
+
const timestamp = query.get('timestamp')
|
|
230
|
+
const nonce = query.get('nonce')
|
|
231
|
+
if (
|
|
232
|
+
msgSignature === null ||
|
|
233
|
+
msgSignature === '' ||
|
|
234
|
+
timestamp === null ||
|
|
235
|
+
timestamp === '' ||
|
|
236
|
+
nonce === null ||
|
|
237
|
+
nonce === ''
|
|
238
|
+
) {
|
|
239
|
+
writeStatus(response, 400)
|
|
240
|
+
return
|
|
241
|
+
}
|
|
242
|
+
const expected = signatureOf(
|
|
243
|
+
this.bot.config.token,
|
|
244
|
+
timestamp,
|
|
245
|
+
nonce,
|
|
246
|
+
encrypt,
|
|
247
|
+
)
|
|
248
|
+
if (!matchesSignature(expected, msgSignature)) {
|
|
249
|
+
writeStatus(response, 403)
|
|
250
|
+
return
|
|
251
|
+
}
|
|
252
|
+
let message: string
|
|
253
|
+
let receiveId: string
|
|
254
|
+
try {
|
|
255
|
+
const decrypted = decryptPayload(this.bot.config.aesKey, encrypt)
|
|
256
|
+
message = decrypted.message
|
|
257
|
+
receiveId = decrypted.receiveId
|
|
258
|
+
} catch (error) {
|
|
259
|
+
// The signature matched, so the platform sent these bytes: a payload this key cannot read names a wrong aesKey.
|
|
260
|
+
this.bot.ctx.logger.warn(
|
|
261
|
+
'wecom: callback payload could not be decrypted: %s',
|
|
262
|
+
messageOf(error),
|
|
263
|
+
)
|
|
264
|
+
writeStatus(response, 403)
|
|
265
|
+
return
|
|
266
|
+
}
|
|
267
|
+
if (receiveId !== this.bot.config.corpId) {
|
|
268
|
+
this.bot.ctx.logger.warn(
|
|
269
|
+
'wecom: callback was encrypted for %s, not corpId %s',
|
|
270
|
+
receiveId,
|
|
271
|
+
this.bot.config.corpId,
|
|
272
|
+
)
|
|
273
|
+
writeStatus(response, 403)
|
|
274
|
+
return
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
fields = await parseMessageXml(message)
|
|
278
|
+
} catch (error) {
|
|
279
|
+
this.bot.ctx.logger.warn(
|
|
280
|
+
'wecom: cannot parse a decrypted callback: %s',
|
|
281
|
+
messageOf(error),
|
|
282
|
+
)
|
|
283
|
+
writeStatus(response, 400)
|
|
284
|
+
return
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
const session = decodeMessage(this.bot, fields)
|
|
288
|
+
// An event this contract has no consumer for is acknowledged and dropped; the platform must not retry it.
|
|
289
|
+
if (session !== undefined) await this.bot.receive(session)
|
|
290
|
+
writeText(response, 200, 'success')
|
|
291
|
+
}
|
|
292
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
export interface BaseMessage {
|
|
2
|
+
ToUserName: string
|
|
3
|
+
AgentID: string
|
|
4
|
+
FromUserName: string
|
|
5
|
+
CreateTime: number
|
|
6
|
+
MsgId: string
|
|
7
|
+
Idx?: string
|
|
8
|
+
Encrypt?: string
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type Message =
|
|
12
|
+
| TextMessage
|
|
13
|
+
| ImageMessage
|
|
14
|
+
| VoiceMessage
|
|
15
|
+
| VideoMessage
|
|
16
|
+
| LocationMessage
|
|
17
|
+
| EventMessage
|
|
18
|
+
|
|
19
|
+
export interface TextMessage extends BaseMessage {
|
|
20
|
+
MsgType: 'text'
|
|
21
|
+
Content: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface ImageMessage extends BaseMessage {
|
|
25
|
+
MsgType: 'image'
|
|
26
|
+
PicUrl: string
|
|
27
|
+
MediaId: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface VoiceMessage extends BaseMessage {
|
|
31
|
+
MsgType: 'voice'
|
|
32
|
+
MediaId: string
|
|
33
|
+
Format: string
|
|
34
|
+
Recogonition?: string
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface VideoMessage extends BaseMessage {
|
|
38
|
+
MsgType: 'video'
|
|
39
|
+
MediaId: string
|
|
40
|
+
ThumbMediaId: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface EventMessage extends BaseMessage {
|
|
44
|
+
MsgType: 'event'
|
|
45
|
+
Event: 'subscribe' | 'unsubscribe'
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface LocationMessage extends BaseMessage {
|
|
49
|
+
MsgType: 'location'
|
|
50
|
+
Location_X: number
|
|
51
|
+
Location_Y: number
|
|
52
|
+
Scale: number
|
|
53
|
+
Label: string
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface BaseSendMessage {
|
|
57
|
+
ToUserName: string
|
|
58
|
+
FromUserName: string
|
|
59
|
+
CreateTime: number
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type SendMessage = TextSendMessage | ImageSendMessage
|
|
63
|
+
|
|
64
|
+
export interface TextSendMessage extends BaseSendMessage {
|
|
65
|
+
MsgType: 'text'
|
|
66
|
+
Content: string
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface ImageSendMessage extends BaseSendMessage {
|
|
70
|
+
MsgType: 'image'
|
|
71
|
+
Image: {
|
|
72
|
+
MediaId: string
|
|
73
|
+
}
|
|
74
|
+
}
|
package/src/xml.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* XML parsing of the callback envelopes.
|
|
3
|
+
*
|
|
4
|
+
* Both the outer envelope (`<xml><ToUserName/><AgentID/><Encrypt/></xml>`) and the decrypted message are a flat map of
|
|
5
|
+
* element name to text; `template_card_event`'s `SelectedItems` is the only nested value and no decision of this adapter
|
|
6
|
+
* reads it. The platform's real input includes entities, CDATA, self-closing tags and a byte-order mark, so the parsing
|
|
7
|
+
* is delegated to `xml2js` instead of a hand-written pattern.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import xml2js from 'xml2js'
|
|
11
|
+
|
|
12
|
+
/** The flat fields of one callback document. */
|
|
13
|
+
export type XmlFields = Record<string, string>
|
|
14
|
+
|
|
15
|
+
/** One callback document that is not a well-formed `<xml>` field map. */
|
|
16
|
+
export class WecomXmlError extends Error {
|
|
17
|
+
constructor(message: string, options: ErrorOptions = {}) {
|
|
18
|
+
super(message, options)
|
|
19
|
+
this.name = 'WecomXmlError'
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Message of any caught value, for a log line. */
|
|
24
|
+
function messageOf(error: unknown): string {
|
|
25
|
+
return error instanceof Error ? error.message : String(error)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** One parsed field value, when the value is a scalar rather than a nested element. */
|
|
29
|
+
function scalarOf(value: unknown): string | undefined {
|
|
30
|
+
if (typeof value === 'string') return value
|
|
31
|
+
if (typeof value === 'number' || typeof value === 'boolean')
|
|
32
|
+
return String(value)
|
|
33
|
+
return undefined
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Flatten the `xml` element of a parsed document.
|
|
38
|
+
*
|
|
39
|
+
* @param value - the parsed document.
|
|
40
|
+
* @returns its scalar fields, or undefined when the document is not an `<xml>` field map.
|
|
41
|
+
*/
|
|
42
|
+
export function fieldsOf(value: unknown): XmlFields | undefined {
|
|
43
|
+
if (typeof value !== 'object' || value === null) return undefined
|
|
44
|
+
const root = (value as Record<string, unknown>).xml
|
|
45
|
+
if (typeof root !== 'object' || root === null) return undefined
|
|
46
|
+
const fields: XmlFields = {}
|
|
47
|
+
for (const [name, raw] of Object.entries(root as Record<string, unknown>)) {
|
|
48
|
+
const field = scalarOf(raw)
|
|
49
|
+
if (field !== undefined) fields[name] = field
|
|
50
|
+
}
|
|
51
|
+
return fields
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Parse one callback document into its fields.
|
|
56
|
+
*
|
|
57
|
+
* @param text - the request body or the decrypted message.
|
|
58
|
+
* @returns the scalar fields of the `<xml>` root.
|
|
59
|
+
* @throws WecomXmlError when the document is not well-formed XML or carries no `<xml>` root.
|
|
60
|
+
*/
|
|
61
|
+
export async function parseXml(text: string): Promise<XmlFields> {
|
|
62
|
+
let parsed: unknown
|
|
63
|
+
try {
|
|
64
|
+
parsed = await xml2js.parseStringPromise(text, { explicitArray: false })
|
|
65
|
+
} catch (cause) {
|
|
66
|
+
throw new WecomXmlError(
|
|
67
|
+
`wecom: the callback body is not XML: ${messageOf(cause)}`,
|
|
68
|
+
{ cause },
|
|
69
|
+
)
|
|
70
|
+
}
|
|
71
|
+
const fields = fieldsOf(parsed)
|
|
72
|
+
if (fields === undefined) {
|
|
73
|
+
throw new WecomXmlError('wecom: the callback body has no <xml> root')
|
|
74
|
+
}
|
|
75
|
+
return fields
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Parse the plaintext of a decrypted message.
|
|
80
|
+
*
|
|
81
|
+
* The decrypted body is an `<xml>` document of its own, so it goes through the same parser as the outer envelope.
|
|
82
|
+
*
|
|
83
|
+
* @param message - the decrypted message.
|
|
84
|
+
* @returns its scalar fields.
|
|
85
|
+
* @throws WecomXmlError when the decrypted body is not XML.
|
|
86
|
+
*/
|
|
87
|
+
export async function parseMessageXml(message: string): Promise<XmlFields> {
|
|
88
|
+
return await parseXml(message)
|
|
89
|
+
}
|
package/README.md
DELETED