'use strict'; const Service = require('egg').Service; const apiSignLib = require('../../lib/api_sign'); const API_APP_CACHE_PREFIX = 'openapi:api-app'; const API_APP_CACHE_TTL_SECONDS = 300; const OPENAPI_INTERFACE_TYPE_ID = 2; class ApiSignService extends Service { /** * 构建 API 应用配置缓存键。 * @param {string} appKey 开放接口 app_key。 * @return {string} 缓存键。 */ getApiAppCacheKey(appKey) { return `${API_APP_CACHE_PREFIX}:${String(appKey || '').trim()}`; } /** * 根据 app_key 查询 API 应用可用配置(带缓存)。 * @param {string} appKey 开放接口 app_key。 * @return {Promise} 查询结果,包含应用主键与密钥。 */ async getApiAppConfigByAppKey(appKey) { const normalizedAppKey = String(appKey || '').trim(); if (!normalizedAppKey) { throw new Error('appKey 不能为空'); } const cacheKey = this.getApiAppCacheKey(normalizedAppKey); if (this.app && typeof this.app.getCacheAsync === 'function') { try { const cached = await this.app.getCacheAsync(cacheKey); if (cached && typeof cached === 'object') { return cached; } } catch (error) { this.ctx.logger.warn(`[api_sign] 读取缓存失败,降级查库: ${error.message}`); } } const row = await this.ctx.model.ApiApp.findOne({ attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id' ], where: { self_app_key: normalizedAppKey, }, raw: true, }); if (!row) { throw new Error('未找到对应的 API 应用配置'); } if (Number(row.is_enabled) !== 1) { throw new Error('API 应用已禁用'); } if (Number(row.interface_type_id) !== OPENAPI_INTERFACE_TYPE_ID) { throw new Error('app_key 无效或不可用'); } if (!row.self_app_secret) { throw new Error('API 应用缺少 self_app_secret 配置'); } const appConfig = { id: row.id, appKey: row.self_app_key, selfAppSecret: row.self_app_secret, }; if (this.app && typeof this.app.setCacheAsync === 'function') { this.app.setCacheAsync(cacheKey, appConfig, API_APP_CACHE_TTL_SECONDS) .catch(error => { this.ctx.logger.warn(`[api_sign] 写入缓存失败: ${error.message}`); }); } return appConfig; } /** * 根据 app_key 查询 API 应用密钥信息。 * @param {string} appKey 开放接口 app_key。 * @return {Promise} 查询结果,包含应用主键与密钥。 */ async getApiAppSecretByAppKey(appKey) { return await this.getApiAppConfigByAppKey(appKey); } /** * 使用 app_key 读取密钥并执行签名验证。 * @param {Object} options 验签参数。 * @param {string} options.appKey 开放接口 app_key。 * @param {Object} [options.query={}] 请求 query 参数。 * @param {*} [options.body] 请求体。 * @param {string} options.providedSign 请求中携带的 sign。 * @param {string[]} [options.ignoreKeys] 额外忽略的 query 字段。 * @return {Promise} 验签结果。 */ async verifyRequestSignByAppKey({ appKey, query = {}, body, providedSign, ignoreKeys } = {}) { let appConfig; try { appConfig = await this.getApiAppSecretByAppKey(appKey); } catch (error) { return { ok: false, code: 'APP_CONFIG_INVALID', message: error.message, }; } const verifyResult = apiSignLib.verifyRequestSign({ query, body, providedSign, selfAppSecret: appConfig.selfAppSecret, ignoreKeys, }); if (!verifyResult.ok) { return { ok: false, code: 'SIGN_INVALID', message: verifyResult.message, expectedSign: verifyResult.expectedSign, providedSign: verifyResult.providedSign, appId: appConfig.id, }; } return { ok: true, code: 'OK', message: verifyResult.message, sign: verifyResult.expectedSign, appId: appConfig.id, appKey: appConfig.appKey, }; } } module.exports = ApiSignService;