224 lines
7.2 KiB
JavaScript
224 lines
7.2 KiB
JavaScript
'use strict';
|
||
|
||
const crypto = require('node:crypto');
|
||
const { XMLParser } = require('fast-xml-parser');
|
||
|
||
/**
|
||
* 微信开放平台第三方平台消息加解密工具(Node 版 WXBizMsgCrypt)。
|
||
* 对应微信官方示例(PHP WXBizMsgCrypt)能力:
|
||
* - URL 有效性验证(首次配置服务器地址时的 echostr 校验)
|
||
* - 事件推送消息解密(AES-256-CBC + PKCS#7,密文格式:
|
||
* 16 字节随机串 + 4 字节大端消息长度 + 明文 XML + component_appid)
|
||
*
|
||
* 错误码沿用微信官方定义:
|
||
* -40001 签名验证错误 / -40004 encodingAesKey 非法 / -40005 appid 校验错误 /
|
||
* -40007 AES 解密失败 / -40008 解密后 buffer 非法 / -40010 base64 解码失败。
|
||
*/
|
||
|
||
const ERROR_CODES = {
|
||
OK: 0,
|
||
VALIDATE_SIGNATURE_ERROR: -40001,
|
||
ILLEGAL_AES_KEY: -40004,
|
||
VALIDATE_APPID_ERROR: -40005,
|
||
DECRYPT_AES_ERROR: -40007,
|
||
ILLEGAL_BUFFER: -40008,
|
||
DECODE_BASE64_ERROR: -40010,
|
||
};
|
||
|
||
/**
|
||
* 计算 SHA1(hex)。
|
||
* @param {string} input 输入字符串。
|
||
* @return {string} SHA1 摘要。
|
||
*/
|
||
function sha1(input) {
|
||
return crypto.createHash('sha1').update(input, 'utf8').digest('hex');
|
||
}
|
||
|
||
/**
|
||
* 生成消息签名:sha1(sort(token, timestamp, nonce, encrypt))。
|
||
* @param {string} token 第三方平台消息校验 Token。
|
||
* @param {string} timestamp 时间戳。
|
||
* @param {string} nonce 随机串。
|
||
* @param {string} [encrypt=''] 加密内容(URL 验证时为空)。
|
||
* @return {string} 签名。
|
||
*/
|
||
function getSignature(token, timestamp, nonce, encrypt = '') {
|
||
const arr = [ token, String(timestamp), String(nonce), String(encrypt || '') ].sort();
|
||
return sha1(arr.join(''));
|
||
}
|
||
|
||
/**
|
||
* 校验 URL 有效性签名:signature === sha1(sort(token, timestamp, nonce))。
|
||
* @param {string} token 第三方平台消息校验 Token。
|
||
* @param {string} signature 微信回传的 signature。
|
||
* @param {string} timestamp 时间戳。
|
||
* @param {string} nonce 随机串。
|
||
* @return {boolean} 是否通过。
|
||
*/
|
||
function verifyUrlSignature(token, signature, timestamp, nonce) {
|
||
if (!token || !signature || timestamp === undefined || timestamp === null || nonce === undefined || nonce === null) {
|
||
return false;
|
||
}
|
||
const expected = getSignature(token, timestamp, nonce);
|
||
return expected === String(signature);
|
||
}
|
||
|
||
/**
|
||
* 解析加密推送 XML,提取 <Encrypt> 内容。
|
||
* @param {string} encryptedXml 微信推送的加密 XML。
|
||
* @return {string} Encrypt 密文(base64 字符串)。
|
||
*/
|
||
function extractEncrypt(encryptedXml) {
|
||
if (!encryptedXml) return '';
|
||
const parser = new XMLParser({
|
||
ignoreAttributes: false,
|
||
parseTagValue: false,
|
||
parseAttributeValue: false,
|
||
trimValues: false,
|
||
});
|
||
let parsed;
|
||
try {
|
||
parsed = parser.parse(encryptedXml.trim());
|
||
} catch (e) {
|
||
return '';
|
||
}
|
||
return (parsed && parsed.xml && parsed.xml.Encrypt) || '';
|
||
}
|
||
|
||
/**
|
||
* PKCS#7 去除填充。
|
||
* @param {Buffer} buf 解密后的带填充 buffer。
|
||
* @return {Buffer} 去填充后的 buffer。
|
||
*/
|
||
function pkcs7Decode(buf) {
|
||
const pad = buf[buf.length - 1];
|
||
if (pad >= 1 && pad <= 32) {
|
||
return buf.subarray(0, buf.length - pad);
|
||
}
|
||
return buf;
|
||
}
|
||
|
||
/**
|
||
* AES-256-CBC 解密微信密文。
|
||
* @param {string} encrypted base64 密文。
|
||
* @param {Buffer} aesKey 32 字节 AES Key。
|
||
* @return {{ code: number, buf: Buffer }} 解密结果(失败时 buf 为空 Buffer)。
|
||
*/
|
||
function aesDecrypt(encrypted, aesKey) {
|
||
const encryptedBuf = Buffer.from(String(encrypted), 'base64');
|
||
if (!encryptedBuf.length) {
|
||
return { code: ERROR_CODES.DECODE_BASE64_ERROR, buf: Buffer.alloc(0) };
|
||
}
|
||
try {
|
||
const iv = aesKey.subarray(0, 16);
|
||
const decipher = crypto.createDecipheriv('aes-256-cbc', aesKey, iv);
|
||
decipher.setAutoPadding(false);
|
||
const decoded = pkcs7Decode(Buffer.concat([ decipher.update(encryptedBuf), decipher.final() ]));
|
||
return { code: ERROR_CODES.OK, buf: decoded };
|
||
} catch (e) {
|
||
return { code: ERROR_CODES.DECRYPT_AES_ERROR, buf: Buffer.alloc(0) };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 解密事件推送消息(完整流程:签名校验 → base64/AES 解密 → 报文解析 → appid 校验)。
|
||
* @param {object} opts 参数。
|
||
* @param {string} opts.token 第三方平台消息校验 Token。
|
||
* @param {string} opts.encodingAesKey 第三方平台消息加解密 Key(43 位)。
|
||
* @param {string} opts.componentAppid 第三方平台 AppID。
|
||
* @param {string} opts.msgSignature 消息签名 msg_signature。
|
||
* @param {string|number} opts.timestamp 时间戳。
|
||
* @param {string} opts.nonce 随机串。
|
||
* @param {string} opts.encryptedXml 微信推送的加密 XML。
|
||
* @return {{ code: number, msg: string }} code=0 时 msg 为解密后的明文 XML。
|
||
*/
|
||
function decryptMsg(opts) {
|
||
const {
|
||
token,
|
||
encodingAesKey,
|
||
componentAppid,
|
||
msgSignature,
|
||
timestamp,
|
||
nonce,
|
||
encryptedXml,
|
||
} = opts || {};
|
||
|
||
const encrypt = extractEncrypt(encryptedXml);
|
||
if (!encrypt) {
|
||
return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '加密 XML 中未找到 Encrypt 内容' };
|
||
}
|
||
|
||
// 1. 校验消息签名
|
||
const expectedSignature = getSignature(token, timestamp, nonce, encrypt);
|
||
if (expectedSignature !== String(msgSignature)) {
|
||
return { code: ERROR_CODES.VALIDATE_SIGNATURE_ERROR, msg: '消息签名校验失败' };
|
||
}
|
||
|
||
// 2. AES Key(encodingAesKey 43 位补 '=' 后 base64 解码为 32 字节)
|
||
let aesKey;
|
||
try {
|
||
aesKey = Buffer.from(String(encodingAesKey) + '=', 'base64');
|
||
} catch (e) {
|
||
return { code: ERROR_CODES.ILLEGAL_AES_KEY, msg: 'encodingAesKey 非法' };
|
||
}
|
||
if (aesKey.length !== 32) {
|
||
return { code: ERROR_CODES.ILLEGAL_AES_KEY, msg: 'encodingAesKey 解码后长度不是 32 字节' };
|
||
}
|
||
|
||
// 3. AES 解密
|
||
const decrypted = aesDecrypt(encrypt, aesKey);
|
||
if (decrypted.code !== ERROR_CODES.OK) {
|
||
return { code: decrypted.code, msg: 'AES 解密失败' };
|
||
}
|
||
|
||
// 4. 解析明文(二进制 buffer):16 字节随机串 + 4 字节大端长度 + 消息体 + appid
|
||
const content = decrypted.buf;
|
||
if (content.length < 20) {
|
||
return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '解密后 buffer 长度非法' };
|
||
}
|
||
const msgLen = content.readUInt32BE(16);
|
||
if (20 + msgLen > content.length) {
|
||
return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '解密后消息长度非法' };
|
||
}
|
||
const xmlContent = content.subarray(20, 20 + msgLen).toString('utf8');
|
||
const fromAppid = content.subarray(20 + msgLen).toString('utf8');
|
||
|
||
// 5. 校验 appid
|
||
if (fromAppid !== String(componentAppid)) {
|
||
return { code: ERROR_CODES.VALIDATE_APPID_ERROR, msg: `appid 校验失败: ${fromAppid}` };
|
||
}
|
||
|
||
return { code: ERROR_CODES.OK, msg: xmlContent };
|
||
}
|
||
|
||
/**
|
||
* 解析明文 XML 为对象({ AppId, InfoType, ... })。
|
||
* @param {string} xml 明文 XML。
|
||
* @return {object} 解析后的对象(失败返回空对象)。
|
||
*/
|
||
function parseXml(xml) {
|
||
if (!xml) return {};
|
||
const parser = new XMLParser({
|
||
ignoreAttributes: false,
|
||
parseTagValue: false,
|
||
parseAttributeValue: false,
|
||
trimValues: false,
|
||
});
|
||
try {
|
||
const parsed = parser.parse(xml.trim());
|
||
return (parsed && parsed.xml) || {};
|
||
} catch (e) {
|
||
return {};
|
||
}
|
||
}
|
||
|
||
module.exports = {
|
||
ERROR_CODES,
|
||
sha1,
|
||
getSignature,
|
||
verifyUrlSignature,
|
||
extractEncrypt,
|
||
decryptMsg,
|
||
parseXml,
|
||
};
|