'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; const WAREHOUSE_INTERFACE_TYPE_ID = 3; class ApiSignService extends Service { /** * 构建 API 应用配置缓存键。 * @param {string} appKey 开放接口 app_key。 * @param {number} [interfaceTypeId] 接口类型 ID,用于区分不同入口的缓存。 * @return {string} 缓存键。 */ getApiAppCacheKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) { const prefix = interfaceTypeId === WAREHOUSE_INTERFACE_TYPE_ID ? 'warehouse:api-app' : API_APP_CACHE_PREFIX; return `${prefix}:${String(appKey || '').trim()}`; } /** * 根据 app_key 查询 API 应用可用配置(带缓存)。 * @param {string} appKey 开放接口 app_key。 * @param {number} [interfaceTypeId=2] 接口类型 ID,2=货主级 / 3=仓库级。 * @return {Promise} 查询结果,包含应用主键与密钥。 */ async getApiAppConfigByAppKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) { const normalizedAppKey = String(appKey || '').trim(); if (!normalizedAppKey) { throw new Error('appKey 不能为空'); } const cacheKey = this.getApiAppCacheKey(normalizedAppKey, interfaceTypeId); 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', 'warehouse_id' ], where: { self_app_key: normalizedAppKey, interface_type_id: interfaceTypeId, }, raw: true, }); if (!row) { throw new Error('未找到对应的 API 应用配置'); } if (Number(row.is_enabled) !== 1) { throw new Error('API 应用已禁用'); } 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, interfaceTypeId: Number(row.interface_type_id), warehouseId: row.warehouse_id ? Number(row.warehouse_id) : null, }; 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。 * @param {number} [interfaceTypeId=2] 接口类型 ID。 * @return {Promise} 查询结果,包含应用主键与密钥。 */ async getApiAppSecretByAppKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) { return await this.getApiAppConfigByAppKey(appKey, interfaceTypeId); } /** * 使用 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 字段。 * @param {number} [options.interfaceTypeId=2] 接口类型 ID。 * @return {Promise} 验签结果。 */ async verifyRequestSignByAppKey({ appKey, query = {}, body, providedSign, ignoreKeys, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID } = {}) { let appConfig; try { appConfig = await this.getApiAppSecretByAppKey(appKey, interfaceTypeId); } 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, interfaceTypeId: appConfig.interfaceTypeId, warehouseId: appConfig.warehouseId, }; } } module.exports = ApiSignService;