strategy.test.mjs 19 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
/**
 * 方案策略 / 签名策略注册表的钉值测试。
 *
 * 关注点:门面只做委托,策略自带默认语义;消费层用 createStrategy.xxx({...}) 只传环境参数。
 * 同时守住「逐字节兼容」:内置 rop-sha1 必须与 points 旧 getData 的签名完全一致。
 */
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import test from 'node:test';

const require = createRequire(import.meta.url);
const core = require('../dist/index.cjs');
const {
  Request,
  createRequest,
  createStrategy,
  createSigner,
  RequestError,
  registerGateway,
  prepareRpcCall,
  createRpcDispatcher,
} = core;

const HERE = path.dirname(fileURLToPath(import.meta.url));

function makeSender(responder) {
  const calls = [];
  const sender = {
    async send(req) {
      calls.push(req);
      const res = typeof responder === 'function' ? responder(req) : responder;
      return res ?? { status: 200, data: { code: '0', data: {} } };
    },
  };
  return { calls, sender };
}

// ---------------------------------------------------------------------------
// 1. 注册表
// ---------------------------------------------------------------------------

test('ST-REG-001 内置方案与签名策略都已注册', () => {
  assert.deepEqual(createStrategy.list(), ['plain', 'rop', 'gsc', 'web-host', 'rpc-gateway']);
  assert.deepEqual(createStrategy.signature.list(), [
    'none', 'sha1', 'md5', 'sdk', 'hmac-sha256', 'gsc-hmac', 'rop-sha1',
  ]);
});

test('ST-REG-002 未知策略名明确报错,不悄悄退化', () => {
  assert.throws(
    () => new Request({ strategy: 'not-exist' }),
    /未知的网关方案策略/,
  );
  assert.throws(
    () => createStrategy.signature.resolve('not-exist'),
    /未知的签名策略/,
  );
});

test('ST-REG-003 自定义方案策略:注册后按名字使用,门面只做委托', async () => {
  const { calls, sender } = makeSender(() => ({ status: 200, data: { errcode: 0, data: { ok: 1 } } }));
  createStrategy.register(createStrategy.define({
    id: 'custom-gateway',
    defaults: { response: { codeKey: 'errcode', successCodes: [0], dataMode: 'envelope' } },
    async prepare(config) {
      return {
        url: `https://custom.test/${String(config.url).replace(/^\//, '')}`,
        method: 'POST',
        data: config.data,
        headers: { 'X-Strategy': 'custom-gateway' },
        resource: String(config.url),
      };
    },
  }));

  const api = createRequest({ strategy: 'custom-gateway', sender });
  const res = await api.post('/hello', { a: 1 });

  assert.equal(calls[0].url, 'https://custom.test/hello');
  assert.equal(calls[0].headers['X-Strategy'], 'custom-gateway');
  // 策略自带的 codeKey / dataMode 生效,且响应归一仍是门面那一条 pipeline
  assert.deepEqual(res, { errcode: 0, data: { ok: 1 } });
});

test('ST-REG-004 自定义签名策略:实现注册一次,装配层只写名字', async () => {
  const { calls, sender } = makeSender();
  createStrategy.signature.register('demo-sign', {
    bodySign: (params, secret) => ({ ...params, sign: `demo:${secret}` }),
  });

  const api = new Request(createStrategy({ kind: 'rop', sender,
    hosts: { scrm: 'https://api.test' },
    defaultCredential: { appKey: 'k', secret: 's' },
    signature: 'demo-sign',
  }));
  await api.post('scrm.api.shopmall.order.list', { pageNo: 1 });

  assert.equal(calls[0].data.sign, 'demo:s');
  assert.equal(calls[0].data.method, 'scrm.api.shopmall.order.list');
  assert.equal(calls[0].url, 'https://api.test/rop-scrm-shopmall/router?method=scrm.api.shopmall.order.list');
});

// ---------------------------------------------------------------------------
// 2. 消费层预设:方案自带语义,环境参数可覆盖
// ---------------------------------------------------------------------------

test('ST-PRESET-005 rop 预设:业务码 / 登出码 / transport 由策略内置', async () => {
  const { sender } = makeSender(() => ({ status: 200, data: { code: '0', data: { id: 7 } } }));
  const config = createStrategy({ kind: 'rop', sender,
    hosts: { scrm: 'https://api.test' },
    signature: 'none',
    loginReplay: true,
  });

  assert.equal(config.strategy, 'rop');
  assert.equal(config.response.logoutPending, true);
  assert.equal(config.response.errorPending, true);

  const api = new Request(config);
  // 策略 defaults 在构造时并入;显式传入的语义开关不会被吃掉
  assert.equal(api.defaults.config.response.codeKey, 'code');
  assert.deepEqual(api.defaults.config.response.successCodes, ['0']);
  assert.deepEqual(api.defaults.config.response.logoutCodes, [20, 21]);
  assert.equal(api.defaults.config.response.logoutPending, true);
  assert.equal(api.defaults.config.transport, 'auto');

  const res = await api.post('scrm.api.shopmall.order.list', {});
  assert.deepEqual(res, { id: 7 });
});

test('ST-PRESET-006 legacyEnvelope:成功返回完整信封,其它业务码 resolve', async () => {
  const toasts = [];
  const { sender } = makeSender(() => ({
    status: 200,
    data: { code: '-1', message: '库存不足', data: { sku: 9 } },
  }));
  const config = createStrategy({ kind: 'rop', sender,
    hosts: { scrm: 'https://api.test' },
    legacyEnvelope: true,
    response: { toastOnOtherCodes: ['-1'] },
    ui: { toast: (m) => toasts.push(m) },
  });

  assert.equal(config.response.dataMode, 'envelope');
  assert.equal(config.response.resolveOnOther, true);
  assert.deepEqual(config.response.toastOnOtherCodes, ['-1']);

  const api = new Request(config);
  const res = await api.post('scrm.api.shopmall.order.list', {});
  assert.equal(res.code, '-1');
  assert.deepEqual(toasts, ['库存不足']);
});

test('ST-PRESET-007 webHost 预设:ApiResult 信封 / 401 登出 / 业务错误不 toast', async () => {
  const toasts = [];
  const { sender } = makeSender((req) =>
    req.url.includes('/fail')
      ? { status: 200, data: { code: 500, message: '库存不足', data: { sku: 9 } }, headers: { 'content-type': 'application/json' } }
      : { status: 200, data: { code: 200, message: 'ok', data: { list: [1, 2] } }, headers: { 'content-type': 'application/json' } },
  );
  const api = new Request(createStrategy({ kind: 'web-host', sender,
    baseURL: 'https://host.test',
    contextPath: '/youjia',
    ui: { toast: (m) => toasts.push(m) },
  }));

  assert.deepEqual(api.defaults.config.response.successCodes, [200]);
  assert.deepEqual(api.defaults.config.response.logoutCodes, [401, 10002]);
  assert.equal(api.defaults.config.response.dataMode, 'envelope');
  assert.equal(api.defaults.config.response.binaryHeaders, true);
  assert.equal(api.defaults.config.response.toastOnError, false);
  assert.equal(api.defaults.config.contentType, false);
  assert.equal(api.defaults.config.timeout, 20000);
  assert.equal(typeof api.defaults.config.errorHandler, 'function');

  const ok = await api.get('/store/listing/page');
  assert.equal(ok.code, 200);
  assert.deepEqual(ok.data, { list: [1, 2] });

  await assert.rejects(
    () => api.post('/store/listing/fail', {}),
    (err) => err instanceof RequestError && err.code === 500 && err.message === '库存不足',
  );
  assert.deepEqual(toasts, []);
});

test('ST-PRESET-008 rest 预设极简:只选 plain,其余走门面默认', async () => {
  const { calls, sender } = makeSender(() => ({ status: 200, data: { id: 3 } }));
  const config = createStrategy({ kind: 'rest', sender, baseURL: 'https://api.test' });
  assert.equal(config.strategy, 'plain');

  const res = await new Request(config).get('/users/3');
  assert.equal(calls[0].url, 'https://api.test/users/3');
  assert.deepEqual(res, { id: 3 }); // 普通 REST 无 code 字段 → 原样返回
});

test('ST-PRESET-009 显式 strategy 覆盖自动推断', async () => {
  const { calls, sender } = makeSender();
  const api = new Request({
    sender,
    strategy: 'plain',
    hosts: { scrm: 'https://api.test' }, // 有 hosts 本应自动判 rop
    baseURL: 'https://api.test',
  });
  await api.post('/custom/path', { a: 1 });
  assert.equal(calls[0].url, 'https://api.test/custom/path');
  assert.ok(!calls[0].url.includes('router?method='));
});

test('ST-PRESET-010 三种方案共用同一条响应归一 pipeline', async () => {
  const { sender } = makeSender(() => ({ status: 200, data: { code: '0', data: { same: true } } }));
  for (const [name, config] of [
    ['rop', createStrategy({ kind: 'rop', sender, hosts: { scrm: 'https://api.test' } })],
    ['gsc', createStrategy({ kind: 'gsc', sender, baseURL: 'https://api.test' })],
    ['plain', createStrategy({ kind: 'rest', sender, baseURL: 'https://api.test' })],
  ]) {
    const res = await new Request(config).post('/x', {});
    assert.deepEqual(res, { same: true }, `${name} 应同样剔包`);
  }
});

// ---------------------------------------------------------------------------
// 3. 逐字节兼容 & 导出契约
// ---------------------------------------------------------------------------

test('ST-COMPAT-011 内置 rop-sha1 与 points 旧 getData 签名逐字节一致', async () => {
  const APP_KEY = '48e5e13229b82c1b4e6e8c96151f0637';
  const SECRET = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b';
  const oldSigner = createSigner({ kind: 'rop', id: 'points-sha1' });
  const legacy = async (params, secret, noSignAttr = []) => {
    const signed = await oldSigner.fields({
      method: params.method, appKey: params.appKey, secret,
      version: params.v, format: params.format, params, exclude: noSignAttr,
    });
    return { ...params, sign: signed.sign };
  };
  const builtin = createStrategy.signature.resolve('rop-sha1');
  assert.equal(builtin.id, 'rop-sha1');

  const cases = [
    {
      name: '普通请求',
      params: {
        method: 'scrm.api.shopmall.pointswallet.get', userId: 'u1', pageNo: 1,
        v: '1.0.0', format: 'json', locale: 'zh_CN', source: 'dj-wechat',
        appKey: APP_KEY, sessionId: 'sess-9',
      },
      exclude: [],
    },
    {
      name: 'noSignAttr(file)',
      params: {
        method: 'scrm.api.carlife.common.uploadImg', file: 'BASE64_DATA',
        v: '1.0.0', format: 'json', appKey: APP_KEY, sessionId: 'sess-9',
      },
      exclude: ['file'],
    },
  ];
  for (const { name, params, exclude } of cases) {
    const before = await legacy({ ...params }, SECRET, exclude);
    const after = await builtin.bodySign({ ...params }, SECRET, exclude);
    assert.deepEqual(after, before, `${name} :: body + sign 必须逐字节一致`);
    assert.ok(after.sign, `${name} :: sign 必须存在`);
  }
});

test('ST-COMPAT-012 旧 profile / sign 字段仍可用(向后兼容)', async () => {
  const { calls, sender } = makeSender();
  const api = new Request({ sender, profile: 'rop', sign: 'none', hosts: { scrm: 'https://api.test' } });
  await api.post('a.b.c', { p: 1 });
  assert.equal(calls[0].url, 'https://api.test/rop-scrm-c/router?method=a.b.c');
  assert.ok(!('sign' in calls[0].data));
});

test('ST-COMPAT-013 @uj/api-core/Request 子路径与主入口是同一个 bundle', () => {
  const pkg = JSON.parse(readFileSync(path.join(HERE, '../package.json'), 'utf8'));
  const sub = pkg.exports['./Request'];
  assert.equal(sub.import, './dist/index.js');
  assert.equal(sub.require, './dist/index.cjs');
  assert.equal(core.default, Request);
  assert.equal(typeof core.createStrategy, 'function');
});

// ---------------------------------------------------------------------------
// 5. rpc-gateway:消费层只传参,装配知识全在 GatewayStrategy
// ---------------------------------------------------------------------------

/** 模拟传输层已执行归一(host 的 transformResponse / wx 的响应回调)。 */
function makeEnvelopeSender(respond) {
  const calls = [];
  const sender = {
    async send(req) {
      calls.push(req);
      const raw = respond ? respond(req) : { code: '0', data: { id: 7, ok: true } };
      const data = req.normalize ? req.normalize(raw) : raw;
      return { status: 200, data, headers: {} };
    },
  };
  return { calls, sender };
}

const rpcSignInputs = [];
registerGateway({
  id: 'st-rpc',
  router: 'rop-st/router',
  tokenHeader: 'token',
  fixedParams: { locale: 'zh_CN', source: 'st' },
  signer: {
    id: 'st-rpc-signer',
    fields(input) {
      rpcSignInputs.push(input);
      // 故意不含 timestamp:两次组装的签名字段必须完全一致,便于逐字节对比。
      return { appKey: input.appKey, sign: `${input.method}#${input.secret}` };
    },
  },
  normalize(raw) {
    // 主壳 transport 为验签保留原始响应串,真实网关归一(glsx)会先解析字符串。
    const body = typeof raw === 'string' ? JSON.parse(raw) : raw;
    if (String(body?.code) === '0') return { data: body.data };
    return { code: 10002, message: body?.message || '登录已失效' };
  },
});

const rpcCredential = () => ({
  origin: 'https://rpc.test/', appKey: 'k', secret: 's', version: '1.0.0', format: 'json',
});
const rpcToken = () => 'T-1';
const rpcDeps = { resolveCredential: rpcCredential, resolveToken: rpcToken, timeout: 180000 };

function makeRpcApi(extra = {}) {
  const { calls, sender } = makeEnvelopeSender();
  const api = new Request(createStrategy({ sender, gatewayCredential: rpcCredential, gatewayToken: rpcToken,
    timeout: 180000, contentType: false, ...extra,
  }));
  return { calls, sender, api };
}

test('ST-RPC-001 createStrategy 不传参即默认最新版 rpc-gateway 方案', () => {
  assert.equal(typeof createStrategy, 'function');
  assert.equal(typeof core.createStrategy, 'function');
  assert.equal(createStrategy().strategy, 'rpc-gateway');
  assert.ok(createStrategy.list().includes('rpc-gateway'));
});

test('ST-RPC-002 消费层只传 gateway + 方法名 + 参数:落点/加签/令牌/信封全由网关策略决定', async () => {
  rpcSignInputs.length = 0;
  const { calls, api } = makeRpcApi();
  const result = await api.post('scrm.api.st.order.page', { pageNo: 1 }, { gateway: 'st-rpc' });

  const req = calls[0];
  assert.equal(req.url, 'https://rpc.test/rop-st/router');
  assert.equal(req.method, 'POST');
  assert.deepEqual(req.data, {
    locale: 'zh_CN', source: 'st', pageNo: 1,
    method: 'scrm.api.st.order.page',
    appKey: 'k', sign: 'scrm.api.st.order.page#s',
  });
  assert.equal(req.headers.token, 'T-1');
  assert.equal(req.timeout, 180000);
  assert.equal(typeof req.normalize, 'function');
  // 信封已由传输层归一,门面再解一层 → post() 直接拿到业务数据
  assert.deepEqual(result, { id: 7, ok: true });
  assert.equal(rpcSignInputs.length, 1);
  assert.equal(rpcSignInputs[0].appKey, 'k');
  assert.equal(rpcSignInputs[0].secret, 's');
  assert.deepEqual(rpcSignInputs[0].params, { locale: 'zh_CN', source: 'st', pageNo: 1 });
});

test('ST-RPC-003 signed:false 免签;unsignedKeys 透传 exclude;业务参数可覆盖 fixedParams', async () => {
  const off = makeRpcApi();
  await off.api.post('m.no.sign', { file: 'BASE64' }, { gateway: 'st-rpc', signed: false });
  assert.ok(!('sign' in off.calls[0].data));
  assert.ok(!('appKey' in off.calls[0].data));
  assert.equal(off.calls[0].data.file, 'BASE64');

  rpcSignInputs.length = 0;
  const excluded = makeRpcApi();
  await excluded.api.post('m.with.exclude', { locale: 'en_US', file: 'BASE64' }, {
    gateway: 'st-rpc', unsignedKeys: ['file'],
  });
  assert.equal(excluded.calls[0].data.locale, 'en_US');
  assert.deepEqual(rpcSignInputs[0].exclude, ['file']);
  assert.deepEqual(rpcSignInputs[0].params, { locale: 'en_US', source: 'st', file: 'BASE64' });
});

test('ST-RPC-004 与 prepareRpcCall / createRpcDispatcher 共用同一份组装实现(字节一致)', async () => {
  const call = {
    gateway: 'st-rpc', method: 'm.same', params: { a: 1, file: 'BASE64' },
    unsignedKeys: ['file'],
  };
  const direct = await prepareRpcCall(call, rpcDeps);

  const { calls, api } = makeRpcApi();
  await api.post(call.method, call.params, {
    gateway: call.gateway, unsignedKeys: call.unsignedKeys,
  });
  for (const key of ['url', 'method', 'headers', 'timeout']) {
    assert.deepEqual(calls[0][key], direct[key], `${key} 必须与 dispatcher 一致`);
  }
  assert.deepEqual(calls[0].data, direct.data, '加签后的请求体必须逐字段一致');

  // 小程序直连链路:换 sender 与解包,组装结果仍是同一份
  const dispatchCalls = [];
  const dispatch = createRpcDispatcher({
    sender: {
      async send(req) {
        dispatchCalls.push(req);
        return { status: 200, data: req.normalize({ code: '0', data: { ok: 1 } }), headers: {} };
      },
    },
    ...rpcDeps,
  });
  assert.deepEqual(await dispatch(call), { ok: 1 });
  assert.equal(dispatchCalls[0].url, direct.url);
  assert.deepEqual(dispatchCalls[0].data, direct.data);
  assert.deepEqual(dispatchCalls[0].headers, direct.headers);
});

test('ST-RPC-005 网关 / 凭据缺失时明确报错,不静默发出请求', async () => {
  const { api, calls } = makeRpcApi();
  await assert.rejects(() => api.post('m', {}, {}), /需要指定 gateway/);
  await assert.rejects(() => api.post('m', {}, { gateway: 'not-registered' }), /尚未接入/);
  assert.equal(calls.length, 0, '装配失败时一次都不该发出请求');

  const { sender } = makeEnvelopeSender();
  const noCred = new Request({ strategy: 'rpc-gateway', sender, gateway: 'st-rpc' });
  await assert.rejects(() => noCred.post('m', {}, { gateway: 'st-rpc' }), /gatewayCredential/);
});

test('ST-RPC-006 真实双层门面:rpcGateway → host sender → 主壳归一 → 业务数据', async () => {
  const hostCalls = [];
  // 模拟 wujie props.request:主壳门面执行子应用挂上的 transformResponse(= 网关 normalize),
  // 再把 { data } 信封交回 createHostSender。
  const hostSend = async (cfg) => {
    hostCalls.push(cfg);
    let body = '{"code":"0","data":{"id":9,"ok":true}}';
    for (const fn of cfg.transformResponse ?? []) body = fn(body, {});
    return { data: body?.data, headers: {} };
  };
  const api = new Request(createStrategy({ transport: 'host', hostSend,
    gatewayCredential: rpcCredential, gatewayToken: rpcToken,
    timeout: 180000, contentType: false,
  }));

  const res = await api.post('m.double', {}, { gateway: 'st-rpc' });
  assert.equal(hostCalls.length, 1);
  assert.equal(hostCalls[0].url, 'https://rpc.test/rop-st/router');
  assert.equal(hostCalls[0].method, 'POST');
  assert.equal(hostCalls[0].headers.token, 'T-1');
  assert.equal(typeof hostCalls[0].transformResponse?.[0], 'function',
    '网关的 normalize 必须挂到 transformResponse,先于主壳拦截器归一');
  assert.deepEqual(res, { id: 9, ok: true });
});

test('ST-RPC-007 失败信封经统一响应归一后,外部 errorHandler 仍能拿到业务码', async () => {
  const { calls, sender } = makeEnvelopeSender(() => ({ code: '21', message: '登录已失效' }));
  let seen;
  const api = new Request(createStrategy({ sender, gatewayCredential: rpcCredential,
    errorHandler: (err) => {
      seen = err;
      return { handled: true, code: err.code };
    },
  }));
  const res = await api.post('m.fail', {}, { gateway: 'st-rpc' });
  assert.equal(calls.length, 1);
  assert.equal(seen.code, 10002);
  assert.deepEqual(res, { handled: true, code: 10002 });
});