Files
juzi/h5/lib/taobao-auth.js
T
xsl 65ba3cc7a5 fix(taobao): default cloud gateway signature to the md5 form
真实网关请求不带 sign_method(2026-11-01 用 nginx access.log 抓到的真实请求离线复算确认),
缺省签名形式是 MD5(secret + content + secret),也就是 sign_method=md5 的算法,
而不是 MD5(content + secret)。旧实现按「空方法」走了后者,必然 mismatch,
真机登录一直卡在 401「淘宝身份校验失败」。

- h5/lib/taobao-auth.js:缺省 method 归一为 md5
- h5/test/taobao-auth.js:把抓包参数固化成回归测试(含旧算法的反例与 verify 正反例)
2026-11-01 23:30:29 +08:00

37 lines
2.2 KiB
JavaScript

'use strict';
const crypto = require('node:crypto');
// Cloud gateway query parameters + the exact, unread JSON body. Algorithm:
// https://developer.alibaba.com/docs/doc.htm?articleId=121746&docType=1&treeId=832
//
// 注意:真实网关请求不带 sign_method 参数(2026-11-01 从 nginx access.log 抓包确认:
// 参数只有 app_key/open_id/sign/env/request_id/... 没有 sign_method)。缺省时网关用的是
// md5(secret + content + secret),也就是 sign_method=md5 的形式,而不是 md5(content + secret)。
// 之前按「空方法 = md5(content+secret)」实现,导致所有请求都验签失败。
function signature(params, body, secret) {
const method = params.sign_method || 'md5';
if (!['md5', 'hmac', 'hmac_md5', 'hmac_sha256'].includes(method)) return null;
const content = Object.keys(params).filter(key => key !== 'sign' && params[key] !== '').sort()
.map(key => key + params[key]).join('') + body;
if (method === 'hmac' || method === 'hmac_md5' || method === 'hmac_sha256') {
return crypto.createHmac(method === 'hmac_sha256' ? 'sha256' : 'md5', secret).update(content).digest('hex').toUpperCase();
}
return crypto.createHash('md5').update(secret + content + secret).digest('hex').toUpperCase();
}
function verify(url, body, env = process.env) {
if (!env.TAOBAO_APP_KEY || !env.TAOBAO_APP_SECRET) return null;
const params = Object.create(null);
for (const [key, value] of new URL(url, 'http://localhost').searchParams) {
if (key in params) return null; // Never ambiguously verify duplicate parameters.
params[key] = value;
}
if (params.app_key !== env.TAOBAO_APP_KEY || !/^[A-Za-z0-9_-]{4,256}$/.test(params.open_id || '') ||
!/^[A-Fa-f0-9]{32,64}$/.test(params.sign || '')) return null;
const expected = signature(params, body, env.TAOBAO_APP_SECRET);
if (!expected || expected.length !== params.sign.length ||
!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(params.sign.toUpperCase()))) return null;
// Login challenge is single-use and signed inside the body, preventing replay.
return { providerKey: crypto.createHash('sha256').update(params.app_key + ':' + params.open_id).digest('hex') };
}
module.exports = { signature, verify };