signCanonical.ts 5.91 KB
// 请求签名 canonical 构造工具(规范 §三/§五)
// 集中封装「签名算什么」所需的纯函数,与 http.ts 的请求拦截解耦,便于单测与排错。
// 本模块不依赖 axios 实例、不持有模块级状态,输入 config 输出字符串,无副作用。

// ---------- query 序列化:与 axios 线上编码同源 ----------

// 仅对纯对象按 key 升序排列(与后端 canonical 顺序一致);数组 / URLSearchParams 等保持原样交给序列化器。
function sortParamsByKey(params: any): any {
  if (
    !params ||
    typeof params !== 'object' ||
    Array.isArray(params) ||
    params instanceof URLSearchParams
  ) {
    return params;
  }
  const out: Record<string, any> = {};
  Object.keys(params)
    .filter((k) => params[k] !== undefined && params[k] !== null)
    .sort()
    .forEach((k) => (out[k] = params[k]));
  return out;
}

// 复用 axios 自身将使用的 paramsSerializer,确保「签名算什么」==「线上发什么」。
// 未显式配置 serializer 时退化为 axios 默认口径(encodeURIComponent per key/value)。
export function serializeRequestParams(config: any): string {
  const params = sortParamsByKey(config.params);
  const ps = config.paramsSerializer;
  if (ps && typeof ps === 'object' && typeof ps.serialize === 'function') {
    return ps.serialize(params) || '';
  }
  if (typeof ps === 'function') return ps(params) || '';
  if (params && typeof params === 'object') {
    return Object.keys(params)
      .filter((k) => params[k] !== undefined && params[k] !== null)
      .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(params[k]))}`)
      .join('&');
  }
  return '';
}

// ---------- 路径与 query 解析 ----------

function normalizeBase(baseURL?: string): string {
  return (baseURL || '').replace(/\/$/, '');
}

// 摘出 path + 内联 query:绝对 URL 取 pathname+search;相对路径去掉前导斜杠(交给下方 base 拼接)。
function normalizeUrlPath(url?: string): string {
  let urlPath = url || '';
  if (/^https?:\/\//i.test(urlPath)) {
    const u = new URL(urlPath);
    urlPath = u.pathname + u.search;
  } else {
    urlPath = urlPath.replace(/^\//, '');
  }
  return urlPath;
}

export interface CanonicalTarget {
  canonPath: string;
  query: string;
}

// 解析「签名 canonical 第 2 行 path」与「第 3 行 query」,二者同源、一次算清。
// 关键约束:
// 1) 路径只压缩「前面不是冒号」的重复斜杠(/(^|[^:])\/{2,}/g)——basePath 为完整地址时若全局替换会把
//    'http://' 压成 'http:/',new URL() 随即把 host:port 误当 path,canonical 第 2 行变成
//    '/192.168.1.117:8788/system/auth/login'(正确应为 '/system/auth/login')→ 后端验签必失败。
// 2) query 必须与 axios 实际发出的 query 逐字节一致,否则后端验签 10011。
//    根因:同一份 params,URLSearchParams 与 axios 默认(encodeURIComponent)对部分字符编码口径不同:
//      半角括号 ()  → URLSearchParams=%28%29 / axios=( )        ★ 已爆出的 10011
//      空格        → URLSearchParams=+       / axios=%20
//      单引号 '    → URLSearchParams=%27     / axios='
//      波浪号 ~    → URLSearchParams=%7E     / axios=~
//      叹号 !      → URLSearchParams=%21     / axios=!
//    故一律复用 axios 自身的 paramsSerializer 序列化 config.params(数组/特殊字符等所有情况与线上同源),
//    再与内联在 config.url 里的 ?x=y(原样保留,axios 不会重编码它)合并、按 key 升序排序。
export function buildCanonicalTarget(config: any): CanonicalTarget {
  const basePath = normalizeBase(config.baseURL);
  const urlPath = normalizeUrlPath(config.url);
  // 只压缩「前面不是冒号」的重复斜杠,跳过协议里的 //。
  const full = new URL(`${basePath}/${urlPath}`.replace(/(^|[^:])\/{2,}/g, '$1/'), 'http://_');
  const path = full.pathname; // 浏览器侧完整路径,直连模式下为 /system/auth/login(无 /api 前缀)
  // 直连模式下 baseURL 是完整地址(如 http://192.168.1.117:8788),path 不含 /api,直接作为 canonical 第 2 行;
  // 与参考 sign-client.html(直连 /system/auth/login)对齐。若走代理(baseURL='/api')则此处会再摘掉 /api 前缀。
  const canonPath = basePath && path.startsWith(basePath) ? path.slice(basePath.length) : path;

  const inlineQuery = full.search.replace(/^\?/, '');
  const paramsQuery = serializeRequestParams(config);
  const tokens: string[] = [];
  if (inlineQuery) tokens.push(...inlineQuery.split('&').filter(Boolean));
  if (paramsQuery) tokens.push(...paramsQuery.split('&').filter(Boolean));
  return { canonPath, query: tokens.sort().join('&') };
}

// ---------- Content-Type(仅取媒体类型) ----------

// 文件上传固定 multipart/form-data 且请求体不参与签名;其余取已有 Content-Type 或按是否有 body 补 application/json。
export function extractMediaType(
  headers: Record<string, any>,
  isForm: boolean,
  hasBody: boolean,
): string {
  const existingCt = headers['Content-Type'] || headers['content-type'];
  return isForm
    ? 'multipart/form-data'
    : (existingCt || (hasBody ? 'application/json' : '')).split(';')[0].trim().toLowerCase();
}

// ---------- canonical 拼接与脱敏 ----------

export interface SignParts {
  method: string;
  path: string;
  query: string;
  media: string;
  timestamp: string;
  nonce: string;
  appId: string;
  body: string;
}

// 待签名原文:8 行 \n 连接,末尾不加换行(§3.1)。
export function buildSignCanonical(p: SignParts): string {
  return [p.method, p.path, p.query, p.media, p.timestamp, p.nonce, p.appId, p.body].join('\n');
}

// 调试脱敏:把 canonical 里的明文密码替换为 ***(VITE_SIGN_DEBUG=true 时打印用)。
export function maskDebugCanonical(canonical: string): string {
  return canonical.replace(/"password"\s*:\s*"[^"]*"/g, '"password":"***"');
}