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

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;
});

// ---------- 响应拦截:服务端验签 + 统一错误 ----------
/**
 * 拦截器返回规则(统一 + 下游 getBlob/download 兼容):
 * - JSON 响应:返回 ApiResult 的解包结果 body(= {code,data,message} 或 throw err)
 * - 非 JSON(文件流 / Blob):返回 { data: Blob, headers: AxiosHeaders } 结构体,
 *     方便下游 ApiClient.getBlob 既能拿到原始 Blob,也能读到 content-disposition 拿文件名
 */
http.interceptors.response.use(
  (response: any) => {
    const ct = (response.headers['content-type'] || '') as string;
    // 二进制/文件流(模板下载、导出):服务端不签名,直接返回带 headers 的包装体(§4.3)
    if (!ct.includes('application/json')) {
      return {
        data: response.data,
        headers: response.headers ?? {},
      };
    }

    const raw = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
    // 保持当前后端联调模式:响应验签暂未启用。

    const body = raw ? parseStoreResponse(raw, response.config?.url) : null;
    if (body && typeof body === 'object' && 'code' in body && body.code !== 200) {
      const err: any = new Error(
        'message' in body && typeof body.message === 'string' && body.message
          ? body.message
          : '请求失败',
      );
      err.code = body.code;
      err.data = 'data' in body ? body.data : undefined;
      return Promise.reject(err);
    }
    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 };