@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
package/src/bot.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
2
|
+
import { Adapter } from '@deepseek-ai/cordis-plugin-im-core'
|
|
3
|
+
import type {
|
|
4
|
+
ChatRef,
|
|
5
|
+
MembersPage,
|
|
6
|
+
MessageHandle,
|
|
7
|
+
Mode,
|
|
8
|
+
PrepareContext,
|
|
9
|
+
ResolvedResource,
|
|
10
|
+
ResourceKind,
|
|
11
|
+
ResourceRef,
|
|
12
|
+
SendContext,
|
|
13
|
+
SentPart,
|
|
14
|
+
Target,
|
|
15
|
+
} from '@deepseek-ai/cordis-plugin-im-core'
|
|
16
|
+
import { Config, configError } from './config.ts'
|
|
17
|
+
import { classifyWecomError } from './errors.ts'
|
|
18
|
+
import { verifyIdentity } from './identity.ts'
|
|
19
|
+
import { Internal } from './internal.ts'
|
|
20
|
+
import { serveMedia, uploadMedia } from './media.ts'
|
|
21
|
+
import { createMarkdownMode } from './modes/markdown.ts'
|
|
22
|
+
import type { WecomModeTypes, WecomPayload } from './modes/shared.ts'
|
|
23
|
+
import { deletePart, members, sendPayload } from './send.ts'
|
|
24
|
+
import { AccessTokenCache } from './token.ts'
|
|
25
|
+
import { WecomWebhook } from './transport/webhook.ts'
|
|
26
|
+
import type { WebServerLike } from './transport/webhook.ts'
|
|
27
|
+
|
|
28
|
+
/** The single mode this adapter always registers. */
|
|
29
|
+
export interface WecomModes {
|
|
30
|
+
[mode: string]: Mode<WecomModeTypes>
|
|
31
|
+
markdown: Mode<WecomModeTypes>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Message of any caught value, for a log line. */
|
|
35
|
+
function messageOf(error: unknown): string {
|
|
36
|
+
return error instanceof Error ? error.message : String(error)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** One internal-route path segment back as the value it names. */
|
|
40
|
+
function decodeSegment(segment: string): string {
|
|
41
|
+
try {
|
|
42
|
+
return decodeURIComponent(segment)
|
|
43
|
+
} catch {
|
|
44
|
+
// The segment was written unencoded: it names itself rather than a malformed escape.
|
|
45
|
+
return segment
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* WeCom self-built application adapter.
|
|
51
|
+
*
|
|
52
|
+
* The application is identified by configuration (`agentId`), confirmed with `agent/get` on connect. The encrypted XML
|
|
53
|
+
* callback is the only transport, `markdown` is the only mode, and every reply is a proactive `message/send`: a passive
|
|
54
|
+
* reply would have to answer inside the platform's five-second window, while a turn takes minutes. Media uploads to
|
|
55
|
+
* `media/upload` and carries a three-day `media_id`; inbound media is read from the bot's own `satori:` route.
|
|
56
|
+
*/
|
|
57
|
+
export class WecomBot extends Adapter<Config, WecomModes> {
|
|
58
|
+
/** The adapter needs the Satori service and the isolated `http` service. */
|
|
59
|
+
static override inject = ['satori', 'http']
|
|
60
|
+
/** The Loader applies this schema to a profile row's `config` before the constructor runs. */
|
|
61
|
+
static readonly Config = Config
|
|
62
|
+
|
|
63
|
+
readonly modes: WecomModes
|
|
64
|
+
readonly modeOrder = ['markdown'] as const
|
|
65
|
+
|
|
66
|
+
/** The mapped platform API surface. */
|
|
67
|
+
override readonly internal: Internal
|
|
68
|
+
/** The application `access_token` every `cgi-bin` call carries. */
|
|
69
|
+
readonly tokens: AccessTokenCache
|
|
70
|
+
|
|
71
|
+
private webhook: WecomWebhook | undefined
|
|
72
|
+
|
|
73
|
+
constructor(ctx: Context, config: Config) {
|
|
74
|
+
super(ctx, config, {
|
|
75
|
+
id: `wecom:${config.agentId}`,
|
|
76
|
+
platform: 'wecom',
|
|
77
|
+
adapter: 'wecom',
|
|
78
|
+
})
|
|
79
|
+
// `bot.id` has to be fixed at construction, so the application is configured rather than discovered; `connect`
|
|
80
|
+
// proves the credentials belong to it.
|
|
81
|
+
this.selfId = config.agentId
|
|
82
|
+
this.internal = new Internal(this)
|
|
83
|
+
this.tokens = new AccessTokenCache(async () => {
|
|
84
|
+
return await this.internal.getToken({
|
|
85
|
+
corpid: config.corpId,
|
|
86
|
+
corpsecret: config.secret,
|
|
87
|
+
})
|
|
88
|
+
})
|
|
89
|
+
this.modes = { markdown: createMarkdownMode(config) }
|
|
90
|
+
this.defineInternalRoute('/assets/:mediaId', async ({ params }) =>
|
|
91
|
+
serveMedia(this, decodeSegment(params.mediaId)),
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
override async connect(): Promise<void> {
|
|
96
|
+
const invalid = configError(this.config)
|
|
97
|
+
if (invalid !== undefined) {
|
|
98
|
+
// `Bot.start` only stores a connect failure on `bot.error`, so log it here.
|
|
99
|
+
this.ctx.logger.error('wecom: connect failed: %s', invalid.message)
|
|
100
|
+
throw invalid
|
|
101
|
+
}
|
|
102
|
+
const webServer = this.ctx.get('webServer') as WebServerLike | undefined
|
|
103
|
+
if (webServer === undefined) {
|
|
104
|
+
const error = new Error(
|
|
105
|
+
'wecom: this adapter needs a profile-provided webServer; WeCom has only the callback transport, so add a ' +
|
|
106
|
+
'webServer row to the profile and make the callback path reachable from the enterprise network',
|
|
107
|
+
)
|
|
108
|
+
this.ctx.logger.error(error.message)
|
|
109
|
+
throw error
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
// A profile that cannot mint a token cannot answer a callback either, so the failure surfaces here.
|
|
113
|
+
await this.tokens.get()
|
|
114
|
+
const answer = await this.internal.agentGet({
|
|
115
|
+
agentid: Number(this.config.agentId),
|
|
116
|
+
})
|
|
117
|
+
this.user = verifyIdentity(this.config.agentId, answer)
|
|
118
|
+
const webhook = new WecomWebhook(this, webServer)
|
|
119
|
+
webhook.start()
|
|
120
|
+
this.webhook = webhook
|
|
121
|
+
this.online()
|
|
122
|
+
} catch (error) {
|
|
123
|
+
this.ctx.logger.error('wecom: connect failed: %s', messageOf(error))
|
|
124
|
+
throw error
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
override async disconnect(): Promise<void> {
|
|
129
|
+
const webhook = this.webhook
|
|
130
|
+
this.webhook = undefined
|
|
131
|
+
webhook?.stop()
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Upload one outbound attachment to the platform's media endpoint.
|
|
136
|
+
*
|
|
137
|
+
* A `media_id` is an application-level resource, so the scope is the bot rather than the chat.
|
|
138
|
+
*/
|
|
139
|
+
override async upload(
|
|
140
|
+
ref: ResourceRef,
|
|
141
|
+
_scope: string,
|
|
142
|
+
ctx: PrepareContext,
|
|
143
|
+
): Promise<ResolvedResource> {
|
|
144
|
+
return await uploadMedia(this, ref, ctx)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
override resourceScope(_target: Target, _kind: ResourceKind): string {
|
|
148
|
+
return this.id
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
override async sendPayload(
|
|
152
|
+
payload: unknown,
|
|
153
|
+
target: Target,
|
|
154
|
+
ctx: SendContext,
|
|
155
|
+
): Promise<SentPart> {
|
|
156
|
+
return await sendPayload(
|
|
157
|
+
{ internal: this.internal, config: this.config },
|
|
158
|
+
payload as WecomPayload,
|
|
159
|
+
target,
|
|
160
|
+
ctx,
|
|
161
|
+
)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
override async deletePart(
|
|
165
|
+
part: SentPart,
|
|
166
|
+
handle: MessageHandle,
|
|
167
|
+
): Promise<void> {
|
|
168
|
+
await deletePart(
|
|
169
|
+
{ internal: this.internal, config: this.config },
|
|
170
|
+
part,
|
|
171
|
+
handle,
|
|
172
|
+
)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
override async members(
|
|
176
|
+
chat: ChatRef,
|
|
177
|
+
cursor?: string,
|
|
178
|
+
limit?: number,
|
|
179
|
+
): Promise<MembersPage> {
|
|
180
|
+
return await members(
|
|
181
|
+
{ internal: this.internal, config: this.config },
|
|
182
|
+
chat,
|
|
183
|
+
cursor,
|
|
184
|
+
limit,
|
|
185
|
+
)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
override classify(error: unknown) {
|
|
189
|
+
return classifyWecomError(error)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export { Config }
|
|
194
|
+
|
|
195
|
+
export default WecomBot
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import z from '@deepseek-ai/schemastery'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* One WeCom self-built application: the `AgentID` of the application page, its secret, and the callback credentials of
|
|
5
|
+
* 「接收消息 → 设置API接收」.
|
|
6
|
+
*
|
|
7
|
+
* There is no transport switch: a self-built application can only be reached through the encrypted XML callback, so a
|
|
8
|
+
* profile without `webServer` cannot use this adapter at all.
|
|
9
|
+
*/
|
|
10
|
+
export interface Config {
|
|
11
|
+
/** Enterprise id (`ww…`): the `corpid` of `gettoken` and the `receiveid` a callback must decrypt to. */
|
|
12
|
+
corpId: string
|
|
13
|
+
/** Application `AgentID`: `selfId`, `bot.id`, the `agentid` of every send and the outer `AgentID` filter. */
|
|
14
|
+
agentId: string
|
|
15
|
+
/** Application secret (`corpsecret`). */
|
|
16
|
+
secret: string
|
|
17
|
+
/** Callback token: one component of `msg_signature`. */
|
|
18
|
+
token: string
|
|
19
|
+
/** Callback `EncodingAESKey`: 43 characters, decoded to the 32-byte AES key. */
|
|
20
|
+
aesKey: string
|
|
21
|
+
/** Inbound callback path, absolute and without a trailing slash. */
|
|
22
|
+
path: string
|
|
23
|
+
/** API root every `cgi-bin` call is made against. */
|
|
24
|
+
apiBaseUrl: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Validated WeCom adapter configuration. */
|
|
28
|
+
export const Config: z<Config> = z.object({
|
|
29
|
+
corpId: z.string().required(),
|
|
30
|
+
agentId: z.string().required(),
|
|
31
|
+
secret: z.string().role('secret').required(),
|
|
32
|
+
token: z.string().role('secret').required(),
|
|
33
|
+
aesKey: z.string().role('secret').required(),
|
|
34
|
+
path: z.string().default('/wecom'),
|
|
35
|
+
apiBaseUrl: z.string().role('url').default('https://qyapi.weixin.qq.com'),
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
/** Length of an `EncodingAESKey`, which is the Base64 form of the 32-byte AES key without its padding. */
|
|
39
|
+
export const AES_KEY_CHARS = 43
|
|
40
|
+
|
|
41
|
+
/** Maximum length of a callback `Token` the platform accepts. */
|
|
42
|
+
export const TOKEN_MAX_CHARS = 32
|
|
43
|
+
|
|
44
|
+
/** The alphanumerical alphabet both callback credentials are drawn from. */
|
|
45
|
+
const CREDENTIAL_ALPHABET = /^[0-9A-Za-z]+$/
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Normalize a route path: absolute, no trailing slash.
|
|
49
|
+
*
|
|
50
|
+
* @param path - a configured path.
|
|
51
|
+
* @returns the pathname to register on the web server.
|
|
52
|
+
*/
|
|
53
|
+
export function routePath(path: string): string {
|
|
54
|
+
const withSlash = path.startsWith('/') ? path : `/${path}`
|
|
55
|
+
return withSlash.length > 1 ? withSlash.replace(/\/+$/, '') : withSlash
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The configuration the adapter cannot work from, as far as it can tell locally.
|
|
60
|
+
*
|
|
61
|
+
* The check runs when the bot starts, not on the first callback: the callback is the only inbound path, so a profile
|
|
62
|
+
* that cannot answer one has no way to receive anything.
|
|
63
|
+
*
|
|
64
|
+
* @param config - the validated configuration.
|
|
65
|
+
* @returns the configuration error, or undefined when the configuration is usable.
|
|
66
|
+
*/
|
|
67
|
+
export function configError(config: Config): Error | undefined {
|
|
68
|
+
if (config.corpId === '') {
|
|
69
|
+
return new Error(
|
|
70
|
+
'wecom: corpId is required (the enterprise id "ww…" of 我的企业 → 企业信息)',
|
|
71
|
+
)
|
|
72
|
+
}
|
|
73
|
+
if (config.agentId === '') {
|
|
74
|
+
return new Error(
|
|
75
|
+
'wecom: agentId is required (the AgentID of the self-built application)',
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
if (!/^[1-9][0-9]*$/.test(config.agentId)) {
|
|
79
|
+
return new Error(
|
|
80
|
+
`wecom: agentId must be a positive integer string, got "${config.agentId}" (message/send takes the numeric AgentID)`,
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
if (config.secret === '') {
|
|
84
|
+
return new Error(
|
|
85
|
+
'wecom: secret is required (the application secret, which every access_token is minted with)',
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
if (config.token === '') {
|
|
89
|
+
return new Error(
|
|
90
|
+
'wecom: token is required (the callback Token of 接收消息 → 设置API接收)',
|
|
91
|
+
)
|
|
92
|
+
}
|
|
93
|
+
if (config.token.length > TOKEN_MAX_CHARS) {
|
|
94
|
+
return new Error(
|
|
95
|
+
`wecom: token must be at most ${TOKEN_MAX_CHARS} characters, got ${config.token.length}`,
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
if (config.aesKey === '') {
|
|
99
|
+
return new Error(
|
|
100
|
+
'wecom: aesKey is required (the EncodingAESKey of 接收消息 → 设置API接收)',
|
|
101
|
+
)
|
|
102
|
+
}
|
|
103
|
+
if (
|
|
104
|
+
config.aesKey.length !== AES_KEY_CHARS ||
|
|
105
|
+
!CREDENTIAL_ALPHABET.test(config.aesKey)
|
|
106
|
+
) {
|
|
107
|
+
return new Error(
|
|
108
|
+
`wecom: aesKey must be exactly ${AES_KEY_CHARS} letters or digits, got ${config.aesKey.length} characters`,
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
if (!config.apiBaseUrl.startsWith('https://')) {
|
|
112
|
+
return new Error(
|
|
113
|
+
`wecom: apiBaseUrl must be an https URL, got "${config.apiBaseUrl}"`,
|
|
114
|
+
)
|
|
115
|
+
}
|
|
116
|
+
return undefined
|
|
117
|
+
}
|
package/src/crypto.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Callback authentication and decryption, implemented on `node:crypto`.
|
|
3
|
+
*
|
|
4
|
+
* The platform hands every callback over in one encrypted envelope, and the adapter is the only place that can say
|
|
5
|
+
* whether the bytes came from the platform:
|
|
6
|
+
*
|
|
7
|
+
* - `msg_signature = sha1(sort(token, timestamp, nonce, msg_encrypt).join(''))`, compared in constant time;
|
|
8
|
+
* - `AES-256-CBC` keyed by `Base64_Decode(EncodingAESKey + "=")` with `IV = AESKey[0:16]` and PKCS#7 padding to
|
|
9
|
+
* **32-byte** blocks (not the usual 16);
|
|
10
|
+
* - the plaintext is `random(16) + msg_len(4, big endian) + msg + receiveid`, and `receiveid` must equal `corpId` for an
|
|
11
|
+
* application callback.
|
|
12
|
+
*
|
|
13
|
+
* `tests/crypto.spec.ts` proves the three steps against the vectors the platform documents.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { createDecipheriv, createHash, timingSafeEqual } from 'node:crypto'
|
|
17
|
+
|
|
18
|
+
/** Length of the decoded AES key. */
|
|
19
|
+
const AES_KEY_BYTES = 32
|
|
20
|
+
|
|
21
|
+
/** Length of the initialisation vector, which is the first part of the key. */
|
|
22
|
+
const IV_BYTES = 16
|
|
23
|
+
|
|
24
|
+
/** The padding block size this platform uses: 32 bytes, not the 16 of a plain AES-CBC block. */
|
|
25
|
+
export const PKCS7_BLOCK_BYTES = 32
|
|
26
|
+
|
|
27
|
+
/** Length of the random prefix of the plaintext. */
|
|
28
|
+
const RANDOM_BYTES = 16
|
|
29
|
+
|
|
30
|
+
/** Length of the big-endian message length between the random prefix and the message. */
|
|
31
|
+
const LENGTH_BYTES = 4
|
|
32
|
+
|
|
33
|
+
/** One callback payload that could not be decrypted. */
|
|
34
|
+
export class WecomCryptoError extends Error {
|
|
35
|
+
constructor(message: string, options: ErrorOptions = {}) {
|
|
36
|
+
super(message, options)
|
|
37
|
+
this.name = 'WecomCryptoError'
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Decode an `EncodingAESKey` into the AES key it stands for.
|
|
43
|
+
*
|
|
44
|
+
* The platform stores the Base64 key without its `=` padding, so the padding is restored before decoding.
|
|
45
|
+
*
|
|
46
|
+
* @param aesKey - the configured 43-character `EncodingAESKey`.
|
|
47
|
+
* @returns the 32-byte AES key.
|
|
48
|
+
* @throws WecomCryptoError when the decoded key is not 32 bytes.
|
|
49
|
+
*/
|
|
50
|
+
export function aesKeyOf(aesKey: string): Buffer {
|
|
51
|
+
const key = Buffer.from(`${aesKey}=`, 'base64')
|
|
52
|
+
if (key.length !== AES_KEY_BYTES) {
|
|
53
|
+
throw new WecomCryptoError(
|
|
54
|
+
`wecom: the EncodingAESKey decodes to ${key.length} bytes, expected ${AES_KEY_BYTES}`,
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
return key
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The `msg_signature` of one callback.
|
|
62
|
+
*
|
|
63
|
+
* The four components are sorted lexicographically as strings and concatenated without a separator, then hashed with
|
|
64
|
+
* SHA-1 and printed as lowercase hex.
|
|
65
|
+
*
|
|
66
|
+
* @param token - the configured callback token.
|
|
67
|
+
* @param timestamp - the `timestamp` the platform sent.
|
|
68
|
+
* @param nonce - the `nonce` the platform sent.
|
|
69
|
+
* @param encrypt - the `echostr` or outer `Encrypt` value the signature covers.
|
|
70
|
+
* @returns the lowercase hexadecimal SHA-1 digest.
|
|
71
|
+
*/
|
|
72
|
+
export function signatureOf(
|
|
73
|
+
token: string,
|
|
74
|
+
timestamp: string,
|
|
75
|
+
nonce: string,
|
|
76
|
+
encrypt: string,
|
|
77
|
+
): string {
|
|
78
|
+
return createHash('sha1')
|
|
79
|
+
.update([token, timestamp, nonce, encrypt].sort().join(''))
|
|
80
|
+
.digest('hex')
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Compare a computed signature with the one the request carried without leaking where they differ.
|
|
85
|
+
*
|
|
86
|
+
* @param expected - the signature computed from the request.
|
|
87
|
+
* @param received - the `msg_signature` parameter, if the request carried one.
|
|
88
|
+
* @returns whether the request signature matches.
|
|
89
|
+
*/
|
|
90
|
+
export function matchesSignature(
|
|
91
|
+
expected: string,
|
|
92
|
+
received: string | undefined,
|
|
93
|
+
): boolean {
|
|
94
|
+
if (received === undefined) return false
|
|
95
|
+
const left = Buffer.from(expected, 'utf8')
|
|
96
|
+
const right = Buffer.from(received, 'utf8')
|
|
97
|
+
if (left.length !== right.length) return false
|
|
98
|
+
return timingSafeEqual(left, right)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** One decrypted callback payload: the message XML and the id the key belongs to. */
|
|
102
|
+
export interface DecryptedPayload {
|
|
103
|
+
/** The message body, which is itself an `<xml>` document (or the `echostr` plaintext). */
|
|
104
|
+
message: string
|
|
105
|
+
/** `corpId` for an application callback; compared with the configured enterprise id before the body is read. */
|
|
106
|
+
receiveId: string
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Decrypt one callback payload.
|
|
111
|
+
*
|
|
112
|
+
* @param aesKey - the configured `EncodingAESKey`.
|
|
113
|
+
* @param encrypt - the Base64 ciphertext the callback carried.
|
|
114
|
+
* @returns the message and the `receiveid` it was encrypted for.
|
|
115
|
+
* @throws WecomCryptoError when the ciphertext is malformed, the padding is inconsistent, or the announced length
|
|
116
|
+
* exceeds the plaintext.
|
|
117
|
+
*/
|
|
118
|
+
export function decryptPayload(
|
|
119
|
+
aesKey: string,
|
|
120
|
+
encrypt: string,
|
|
121
|
+
): DecryptedPayload {
|
|
122
|
+
const key = aesKeyOf(aesKey)
|
|
123
|
+
const cipher = Buffer.from(encrypt.trim(), 'base64')
|
|
124
|
+
if (cipher.length === 0 || cipher.length % IV_BYTES !== 0) {
|
|
125
|
+
throw new WecomCryptoError(
|
|
126
|
+
`wecom: the callback ciphertext is ${cipher.length} bytes, which is not a whole number of AES blocks`,
|
|
127
|
+
)
|
|
128
|
+
}
|
|
129
|
+
const decipher = createDecipheriv(
|
|
130
|
+
'aes-256-cbc',
|
|
131
|
+
key,
|
|
132
|
+
key.subarray(0, IV_BYTES),
|
|
133
|
+
)
|
|
134
|
+
decipher.setAutoPadding(false)
|
|
135
|
+
let padded: Buffer
|
|
136
|
+
try {
|
|
137
|
+
padded = Buffer.concat([decipher.update(cipher), decipher.final()])
|
|
138
|
+
} catch (cause) {
|
|
139
|
+
throw new WecomCryptoError(
|
|
140
|
+
'wecom: the callback payload could not be decrypted',
|
|
141
|
+
{ cause },
|
|
142
|
+
)
|
|
143
|
+
}
|
|
144
|
+
if (padded.length === 0 || padded.length % PKCS7_BLOCK_BYTES !== 0) {
|
|
145
|
+
throw new WecomCryptoError(
|
|
146
|
+
`wecom: the decrypted payload is ${padded.length} bytes, which is not padded to ${PKCS7_BLOCK_BYTES}-byte blocks`,
|
|
147
|
+
)
|
|
148
|
+
}
|
|
149
|
+
const padding = padded[padded.length - 1]!
|
|
150
|
+
if (padding < 1 || padding > PKCS7_BLOCK_BYTES || padding > padded.length) {
|
|
151
|
+
throw new WecomCryptoError(`wecom: the callback padding byte is ${padding}`)
|
|
152
|
+
}
|
|
153
|
+
const plaintext = padded.subarray(0, padded.length - padding)
|
|
154
|
+
if (plaintext.length < RANDOM_BYTES + LENGTH_BYTES) {
|
|
155
|
+
throw new WecomCryptoError(
|
|
156
|
+
`wecom: the decrypted payload is ${plaintext.length} bytes, shorter than its own header`,
|
|
157
|
+
)
|
|
158
|
+
}
|
|
159
|
+
const length = plaintext.readUInt32BE(RANDOM_BYTES)
|
|
160
|
+
const end = RANDOM_BYTES + LENGTH_BYTES + length
|
|
161
|
+
if (end > plaintext.length) {
|
|
162
|
+
throw new WecomCryptoError(
|
|
163
|
+
`wecom: the decrypted payload announces ${length} bytes of message but carries ${plaintext.length - RANDOM_BYTES - LENGTH_BYTES}`,
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
message: plaintext
|
|
168
|
+
.subarray(RANDOM_BYTES + LENGTH_BYTES, end)
|
|
169
|
+
.toString('utf8'),
|
|
170
|
+
receiveId: plaintext.subarray(end).toString('utf8'),
|
|
171
|
+
}
|
|
172
|
+
}
|