http.ts 5.5 KB
// 统一 HTTP 客户端:内置 RSA 请求加签 + 响应验签(规范 §三/§五)
import axios, { type AxiosInstance } from 'axios';
import { message } from 'antd';
import {
  ALGORITHM,
  APP_ID,
  isSignReady,
  isVerifyReady,
  rsaSign,
  rsaVerify,
  setServerPublicKey,
  uuid,
} from './sign';
import { SIGN_CONFIG } from './config';
import { getAuthorization } from '../../access/session';

const http: AxiosInstance = axios.create({
  baseURL: SIGN_CONFIG.BASE_URL,
  timeout: 20000,
  // 关键:保留原始响应文本,供验签(禁止 JSON.parse 后再 stringify,参见 §3.2/§9)
  transformResponse: [(raw: string) => raw],
});

// ---------- 请求拦截:前端加签 ----------
http.interceptors.request.use((config: any) => {
  const authorization = getAuthorization();
  if (authorization) {
    config.headers = { ...(config.headers || {}), Authorization: authorization };
  }
  // 未配置客户端私钥时不签名(开发 LENIENT 模式放行;生产 STRICT 下服务端会返回 10010)
  if (!isSignReady()) return config;

  const isForm = typeof FormData !== 'undefined' && config.data instanceof FormData;

  // 1) 对象体统一先序列化为字符串,保证签名与实际发送内容逐字节一致(§3.1/§9.1)
  if (config.data && typeof config.data === 'object' && !isForm) {
    config.data = JSON.stringify(config.data);
  }

  // 2) 解析真实 path(含 context-path)与查询串(来自 url + params,按字典序升序)
  const basePath = (config.baseURL || '').replace(/\/$/, '');
  let urlPath = config.url || '';
  if (/^https?:\/\//i.test(urlPath)) {
    const u = new URL(urlPath);
    urlPath = u.pathname + u.search;
  } else {
    urlPath = urlPath.replace(/^\//, '');
  }
  const full = new URL(`${basePath}/${urlPath}`.replace(/\/{2,}/g, '/'), 'http://_');
  if (config.params && typeof config.params === 'object') {
    Object.entries(config.params).forEach(([k, v]) => {
      if (v !== undefined && v !== null) full.searchParams.append(String(k), String(v));
    });
  }
  const path = full.pathname;
  const query = full.search.slice(1).split('&').filter(Boolean).sort().join('&');

  // 3) Content-Type 仅取媒体类型;文件上传固定 multipart/form-data,且请求体不参与签名(§3.1/§9.6)
  const headers: Record<string, any> = config.headers || {};
  const existingCt = headers['Content-Type'] || headers['content-type'];
  const media = isForm
    ? 'multipart/form-data'
    : (existingCt || (config.data ? 'application/json' : '')).split(';')[0].trim().toLowerCase();

  const timestamp = String(Date.now());
  const nonce = uuid();
  const bodyStr = isForm ? '' : config.data || '';

  // 待签名原文:8 行 \n 连接,末尾不加换行(§3.1)
  const canonical = [
    (config.method || 'GET').toUpperCase(),
    path,
    query,
    media,
    timestamp,
    nonce,
    APP_ID,
    bodyStr,
  ].join('\n');

  headers['X-App-Id'] = APP_ID;
  headers['X-Timestamp'] = timestamp;
  headers['X-Nonce'] = nonce;
  headers['X-Sign'] = rsaSign(canonical);
  headers['X-Sign-Algorithm'] = ALGORITHM;
  if (config.data && !isForm && !existingCt) {
    headers['Content-Type'] = 'application/json';
  }
  config.headers = headers;
  return config;
});

// ---------- 响应拦截:服务端验签 + 统一错误 ----------
http.interceptors.response.use(
  (response: any) => {
    const ct = (response.headers['content-type'] || '') as string;
    // 二进制/文件流(模板下载、导出):服务端不签名,直接返回(§4.3)
    if (!ct.includes('application/json')) {
      return response.data;
    }

    const raw = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
    const sign = response.headers['x-sign'];
    const ts = response.headers['x-sign-timestamp'];
    const nonce = response.headers['x-sign-nonce'];

    // if (sign) {
    //   if (!ts || !nonce || !isVerifyReady()) {
    //     return Promise.reject(new Error('响应缺少签名头,无法验签'));
    //   }
    //   // 待验签原文:3 行 \n 连接,末尾保留一个换行(§3.2)
    //   const canonical = [ts, nonce, raw, ''].join('\n');
    //   if (!rsaVerify(canonical, sign)) {
    //     return Promise.reject(new Error('响应签名校验失败,数据可能被篡改'));
    //   }
    // }

    const body = raw ? JSON.parse(raw) : null;
    if (body && typeof body === 'object' && 'code' in body && body.code !== 200) {
      const err: any = new Error(body.message || '请求失败');
      err.code = body.code;
      err.data = body.data;
      return Promise.reject(err);
    }
    console.log('body', body);
    return body;
  },
  (error: any) => {
    // 仅对传输层/网络错误做全局提示;业务错误(带 ApiResult.code)交由各调用方决定如何提示,避免重复 Toast
    if (!error.response) {
      message.error('网络异常,请检查连接后重试');
    }
    return Promise.reject(error);
  },
);

// 启动时拉取服务端公钥(免签接口,§5.1/§6),用于响应验签
export async function initSign(): Promise<void> {
  try {
    const res = await fetch(`${SIGN_CONFIG.BASE_URL}/system/sign/public-key`);
    const text = await res.text();
    const json = JSON.parse(text);
    const pub =
      json?.data?.publicKey ??
      json?.data?.serverPublicKeyPem ??
      json?.data?.serverPublicKey ??
      json?.serverPublicKey;
    if (pub) setServerPublicKey(pub);
  } catch (e) {
    console.warn('[sign] 获取服务端公钥失败,响应验签将跳过', e);
  }
}

export { http };