196 lines
5.6 KiB
JavaScript
196 lines
5.6 KiB
JavaScript
'use strict';
|
|
|
|
const crypto = require('crypto');
|
|
|
|
const DEFAULT_IGNORE_KEYS = [ 'sign', 'signature' ];
|
|
|
|
/**
|
|
* 判断输入是否为普通对象。
|
|
* @param {*} value 任意输入值。
|
|
* @return {boolean} 是否为普通对象。
|
|
*/
|
|
function isPlainObject(value) {
|
|
return Object.prototype.toString.call(value) === '[object Object]';
|
|
}
|
|
|
|
/**
|
|
* 将忽略字段列表归一化为小写集合。
|
|
* @param {string[]} [ignoreKeys=[]] 忽略字段数组。
|
|
* @return {Set<string>} 小写忽略字段集合。
|
|
*/
|
|
function normalizeIgnoreKeySet(ignoreKeys = []) {
|
|
const rawKeys = Array.isArray(ignoreKeys)
|
|
? ignoreKeys
|
|
: [];
|
|
|
|
return new Set(rawKeys.map(key => String(key).toLowerCase()));
|
|
}
|
|
|
|
/**
|
|
* 对任意值做稳定序列化,确保对象键顺序固定。
|
|
* @param {*} value 待序列化值。
|
|
* @return {string} 稳定序列化后的字符串。
|
|
*/
|
|
function stableStringify(value) {
|
|
if (value === undefined) {
|
|
return '';
|
|
}
|
|
|
|
if (value === null || typeof value !== 'object') {
|
|
return JSON.stringify(value);
|
|
}
|
|
|
|
if (Array.isArray(value)) {
|
|
const serializedItems = value.map(item => stableStringify(item));
|
|
return `[${serializedItems.join(',')}]`;
|
|
}
|
|
|
|
if (!isPlainObject(value)) {
|
|
return JSON.stringify(value);
|
|
}
|
|
|
|
const keys = Object.keys(value).sort();
|
|
const serializedFields = keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`);
|
|
return `{${serializedFields.join(',')}}`;
|
|
}
|
|
|
|
/**
|
|
* 归一化参数值为可拼接字符串。
|
|
* @param {*} value 参数值。
|
|
* @return {string} 归一化后的字符串。
|
|
*/
|
|
function normalizeParamValue(value) {
|
|
if (value === undefined || value === null) {
|
|
return '';
|
|
}
|
|
|
|
if (typeof value === 'object') {
|
|
return stableStringify(value);
|
|
}
|
|
|
|
return String(value);
|
|
}
|
|
|
|
/**
|
|
* 构建按 key 字母序排列的 query 参数串。
|
|
* @param {Object} [params={}] 请求 query 参数对象。
|
|
* @param {string[]} [ignoreKeys=[]] 需要忽略的字段名列表。
|
|
* @return {string} 规范化后的 query 串,格式为 key=value&key2=value2。
|
|
*/
|
|
function buildCanonicalQuery(params = {}, ignoreKeys = []) {
|
|
if (!isPlainObject(params)) {
|
|
throw new Error('query 参数必须是对象');
|
|
}
|
|
|
|
const ignoreKeySet = normalizeIgnoreKeySet(ignoreKeys);
|
|
const keys = Object.keys(params)
|
|
.filter(key => !ignoreKeySet.has(String(key).toLowerCase()))
|
|
.filter(key => params[key] !== undefined)
|
|
.sort();
|
|
|
|
return keys.map(key => `${key}=${normalizeParamValue(params[key])}`).join('&');
|
|
}
|
|
|
|
/**
|
|
* 构建请求体签名,算法为 md5(稳定序列化后的 body)。
|
|
* @param {*} body 请求体,可为对象、数组、字符串或空值。
|
|
* @return {string} 小写十六进制 body 签名。
|
|
*/
|
|
function buildBodySign(body) {
|
|
const serializedBody = typeof body === 'string'
|
|
? body
|
|
: stableStringify(body);
|
|
|
|
return crypto.createHash('md5').update(serializedBody, 'utf8').digest('hex')
|
|
.toLowerCase();
|
|
}
|
|
|
|
/**
|
|
* 计算请求签名。
|
|
* 参与签名字符串 = canonicalQuery + selfAppSecret + bodySign。
|
|
* 最终签名 = md5(参与签名字符串)。
|
|
* @param {Object} options 签名参数。
|
|
* @param {Object} [options.query={}] 请求 query 参数。
|
|
* @param {*} [options.body] 请求体。
|
|
* @param {string} options.selfAppSecret 密钥。
|
|
* @param {string[]} [options.ignoreKeys] 需要忽略的 query 字段。
|
|
* @return {{ canonicalQuery: string, bodySign: string, sign: string }} 计算结果。
|
|
*/
|
|
function signRequest({ query = {}, body, selfAppSecret, ignoreKeys } = {}) {
|
|
const normalizedSecret = String(selfAppSecret || '').trim();
|
|
if (!normalizedSecret) {
|
|
throw new Error('selfAppSecret 不能为空');
|
|
}
|
|
|
|
const mergedIgnoreKeys = [ ...DEFAULT_IGNORE_KEYS, ...(Array.isArray(ignoreKeys) ? ignoreKeys : []) ];
|
|
const canonicalQuery = buildCanonicalQuery(query, mergedIgnoreKeys);
|
|
const bodySign = buildBodySign(body);
|
|
const signText = `${canonicalQuery}${normalizedSecret}${bodySign}`;
|
|
const sign = crypto.createHash('md5').update(signText, 'utf8').digest('hex')
|
|
.toLowerCase();
|
|
|
|
return {
|
|
canonicalQuery,
|
|
bodySign,
|
|
sign,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 验证请求签名。
|
|
* @param {Object} options 验签参数。
|
|
* @param {Object} [options.query={}] 请求 query 参数。
|
|
* @param {*} [options.body] 请求体。
|
|
* @param {string} options.providedSign 调用方提供的签名。
|
|
* @param {string} options.selfAppSecret 密钥。
|
|
* @param {string[]} [options.ignoreKeys] 需要忽略的 query 字段。
|
|
* @return {{ ok: boolean, expectedSign: string, providedSign: string, message: string }} 验签结果。
|
|
*/
|
|
function verifyRequestSign({ query = {}, body, providedSign, selfAppSecret, ignoreKeys } = {}) {
|
|
const normalizedProvidedSign = String(providedSign || '').trim().toLowerCase();
|
|
if (!normalizedProvidedSign) {
|
|
return {
|
|
ok: false,
|
|
expectedSign: '',
|
|
providedSign: '',
|
|
message: 'providedSign 不能为空',
|
|
};
|
|
}
|
|
|
|
let expected;
|
|
try {
|
|
expected = signRequest({ query, body, selfAppSecret, ignoreKeys }).sign;
|
|
} catch (error) {
|
|
return {
|
|
ok: false,
|
|
expectedSign: '',
|
|
providedSign: normalizedProvidedSign,
|
|
message: error.message,
|
|
};
|
|
}
|
|
|
|
if (expected !== normalizedProvidedSign) {
|
|
return {
|
|
ok: false,
|
|
expectedSign: expected,
|
|
providedSign: normalizedProvidedSign,
|
|
message: '签名不匹配',
|
|
};
|
|
}
|
|
|
|
return {
|
|
ok: true,
|
|
expectedSign: expected,
|
|
providedSign: normalizedProvidedSign,
|
|
message: '签名验证通过',
|
|
};
|
|
}
|
|
|
|
module.exports = {
|
|
DEFAULT_IGNORE_KEYS,
|
|
buildCanonicalQuery,
|
|
buildBodySign,
|
|
signRequest,
|
|
verifyRequestSign,
|
|
};
|