'use strict'; const crypto = require('crypto'); /** * 微信登录网关(公众号网页静默授权)接入封装。 * * 链路:后端申请临时码 → 前端把 pageUrl 渲染成二维码 → 用户用手机微信扫码确认 * → 网关带着签名 POST 到本系统的通知接口(/api/wx/notify)。 * 说明: * 1. appKey / appSecret 只保存在服务端,任何情况下都不下发到前端; * 2. 临时码一次性、扫码会话与通知结果都存在 Redis,过期即失效; * 3. 通知必须校验签名与时间戳,签名密钥是 sha256(appSecret)(与网关约定一致)。 */ /** Redis key 前缀(与 oms:email:* / oms:cache:* 区分) */ const PREFIX = 'oms:wx'; /** 扫码场景:登录 / 绑定 */ const SCENE_LOGIN = 'login'; const SCENE_BIND = 'bind'; /** 网关业务错误码 → 面向用户的提示 */ const GATEWAY_ERROR_MESSAGES = { 40005: '二维码或授权会话已失效,请刷新后重试', 40010: '绑定码不存在、已过期或已被使用', 40011: '绑定码已被使用', 40012: '临时码与绑定码不能混用', 40014: '二维码已失效,请刷新后重试', 40102: '微信网关未配置应用凭证(appKey / appSecret)', 40103: '微信网关应用凭证不正确,请检查 WX_GATEWAY_APP_KEY / WX_GATEWAY_APP_SECRET', 40301: '微信网关应用已停用,请联系管理员', 40302: '回调地址不在微信网关白名单内,请联系管理员', 40401: '微信网关应用不存在,请检查 WX_GATEWAY_APP_KEY', }; /** 网关调用异常(status 为建议返回给前端的 HTTP 状态码) */ class WechatGatewayError extends Error { /** * @param {String} message 面向用户的提示 * @param {Number} status 建议的 HTTP 状态码 */ constructor(message, status = 502) { super(message); this.name = 'WechatGatewayError'; this.status = status; } } /** * 取微信网关配置 * @param {Egg.Application} app egg application * @return {Object} 微信网关配置 */ function gatewayConfig(app) { return app.config.wechatGateway || {}; } /** * 是否已配置微信网关(未配置时相关接口只提示配置,不影响其它登录方式) * @param {Egg.Application} app egg application * @return {Boolean} 是否可用 */ function isEnabled(app) { const cfg = gatewayConfig(app); return Boolean(cfg.appKey && cfg.appSecret); } /** * 取配置,未配置时抛出可直接返回给前端的异常 * @param {Egg.Application} app egg application * @return {Object} 微信网关配置 */ function requireConfig(app) { const cfg = gatewayConfig(app); if (!cfg.appKey || !cfg.appSecret) { throw new WechatGatewayError('未配置微信登录网关,请先在服务端 .env 中填写 WX_GATEWAY_APP_KEY / WX_GATEWAY_APP_SECRET', 400); } return cfg; } /** @return {String} 一次性扫码会话标识(回传用,不包含任何业务信息) */ function newState() { return crypto.randomBytes(16).toString('hex'); } /** @param {String} state 扫描会话标识 @return {String} redis key */ function stateKey(state) { return `${PREFIX}:state:${state}`; } /** @param {String} state 扫描会话标识 @return {String} redis key */ function loginKey(state) { return `${PREFIX}:login:${state}`; } /** @param {String} state 扫描会话标识 @return {String} redis key */ function bindKey(state) { return `${PREFIX}:bind:${state}`; } /** * 公共扫码接口的限流 key(按场景 + IP 统计) * @param {String} scope 场景 * @param {String} ip 客户端IP * @return {String} redis key */ function rateLimitKey(scope, ip) { return `${PREFIX}:limit:${scope}:${ip}`; } /** * 判断是否超出频率限制(固定窗口计数,防止刷接口消耗网关临时码配额) * @param {Egg.Application} app egg application * @param {String} scope 场景 * @param {String} ip 客户端IP * @param {Number} limit 窗口内允许的次数 * @param {Number} window 窗口秒数 * @return {Promise} true 表示已超限 */ async function isRateLimited(app, scope, ip, limit, window) { if (!(limit > 0)) return false; const key = rateLimitKey(scope, ip); const count = await app.redis.incr(key); if (count === 1) await app.redis.expire(key, window > 0 ? window : 600); return count > limit; } /** * 写入扫码会话(scene + 发起人) * @param {Egg.Application} app egg application * @param {String} state 会话标识 * @param {Object} payload { scene, user_id } * @return {Promise} 无返回值 */ async function saveState(app, state, payload) { const { stateTtl } = gatewayConfig(app); await app.redis.set(stateKey(state), JSON.stringify(payload), 'EX', stateTtl); } /** * 读取扫码会话 * @param {Egg.Application} app egg application * @param {String} state 会话标识 * @return {Promise} 会话内容,不存在或已过期返回 null */ async function readState(app, state) { if (!state) return null; const raw = await app.redis.get(stateKey(state)); if (!raw) return null; try { return JSON.parse(raw); } catch { return null; } } /** * 删除扫码会话 * @param {Egg.Application} app egg application * @param {String} state 会话标识 * @return {Promise} 无返回值 */ async function clearState(app, state) { await app.redis.del(stateKey(state)); } /** * 写入通知结果(登录成功 / 未绑定,绑定成功 / 冲突),供前端轮询取走 * @param {Egg.Application} app egg application * @param {String} key redis key * @param {Object} payload 结果内容 * @return {Promise} 无返回值 */ async function writeResult(app, key, payload) { const { stateTtl } = gatewayConfig(app); await app.redis.set(key, JSON.stringify(payload), 'EX', stateTtl); } /** * 读取并清除通知结果(一次性,避免同一结果被重复兑换成登录态) * @param {Egg.Application} app egg application * @param {String} key redis key * @return {Promise} 结果内容 */ async function takeResult(app, key) { const raw = await app.redis.get(key); if (!raw) return null; await app.redis.del(key); try { return JSON.parse(raw); } catch { return null; } } /** * 申请临时码(二维码内容由网关返回的 pageUrl 决定) * @param {Egg.Application} app egg application * @param {Object} options 申请参数 * @param {String} options.scene 场景:login 登录 / bind 绑定 * @param {String} options.state 扫码会话标识,网关会在通知里原样回传 * @return {Promise} 网关返回的临时码数据(tempCode / pageUrl / expiresIn …) */ async function createTempCode(app, { scene, state }) { const cfg = requireConfig(app); const url = `${cfg.baseUrl}/api/auth/temp-code`; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), cfg.timeout); let resp; let text = ''; try { resp = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-App-Key': cfg.appKey, 'X-App-Secret': cfg.appSecret, }, body: JSON.stringify({ scene, state }), signal: controller.signal, }); text = await resp.text(); } catch (err) { const message = err.name === 'AbortError' ? '微信网关响应超时,请稍后重试' : `微信网关请求失败:${err.message}`; throw new WechatGatewayError(message); } finally { clearTimeout(timer); } let json; try { json = JSON.parse(text); } catch { throw new WechatGatewayError(`微信网关返回非 JSON 响应(HTTP ${resp.status})`); } if (json.code !== 0) { const message = GATEWAY_ERROR_MESSAGES[json.code] || json.message || `微信网关返回错误码 ${json.code}`; // 凭证类错误属于配置问题,按 400 返回,方便前端直接提示管理员检查配置 throw new WechatGatewayError(message, [ 40102, 40103, 40301, 40401 ].includes(json.code) ? 400 : 502); } const data = json.data || {}; if (!data.tempCode || !data.pageUrl) { throw new WechatGatewayError('微信网关未返回可用的二维码地址'); } return data; } /** * 通知签名原文:appKey.userId.bindCode.timestamp.nonce(与网关保持一致,含 join 的隐式空串处理) * @param {Object} body 通知报文 * @return {String} 待签名串 */ function signMessage(body) { return [ body.appKey, body.userId, body.bindCode, body.timestamp, body.nonce ].join('.'); } /** * 计算通知签名 * @param {String} appSecret 应用密钥 * @param {Object} body 通知报文 * @return {String} hex 签名 */ function computeSign(appSecret, body) { const secretHash = crypto.createHash('sha256').update(String(appSecret)).digest('hex'); return crypto.createHmac('sha256', secretHash).update(signMessage(body)).digest('hex'); } /** * 定长安全比较,避免签名比较泄露时序信息 * @param {String} a 字符串A * @param {String} b 字符串B * @return {Boolean} 是否相同 */ function safeEqual(a, b) { const bufA = Buffer.from(String(a || '')); const bufB = Buffer.from(String(b || '')); if (!bufA.length || bufA.length !== bufB.length) return false; return crypto.timingSafeEqual(bufA, bufB); } /** * 校验网关通知:应用标识 + 签名 + 时间戳(防重放) * @param {Egg.Application} app egg application * @param {Object} body 通知报文 * @param {Object} headers 请求头 * @return {Object} { ok, message } */ function verifyNotify(app, body, headers = {}) { const cfg = requireConfig(app); if (body.appKey !== cfg.appKey) return { ok: false, message: '通知的应用标识不匹配' }; const timestamp = Number(body.timestamp); if (!timestamp || Math.abs(Date.now() - timestamp) > cfg.notifyTolerance) { return { ok: false, message: '通知已过期' }; } const expected = computeSign(cfg.appSecret, body); if (!safeEqual(expected, body.sign)) return { ok: false, message: '通知签名校验失败' }; const headerSign = headers['x-gateway-signature']; if (headerSign && !safeEqual(expected, headerSign)) return { ok: false, message: '通知签名校验失败' }; return { ok: true, message: '' }; } /** * openid 脱敏展示(只保留首尾,避免完整标识出现在页面与日志中) * @param {String} openid 微信 openid * @return {String} 脱敏后的 openid */ function maskOpenid(openid) { const value = String(openid || ''); if (value.length <= 10) return value ? `${value.slice(0, 2)}****` : ''; return `${value.slice(0, 6)}****${value.slice(-4)}`; } module.exports = { SCENE_LOGIN, SCENE_BIND, WechatGatewayError, gatewayConfig, isEnabled, requireConfig, newState, stateKey, loginKey, bindKey, rateLimitKey, isRateLimited, saveState, readState, clearState, writeResult, takeResult, createTempCode, computeSign, verifyNotify, maskOpenid, };