Commit fe99caaa by liimin

feat: api-core 承接 GSC 网关请求链与 glsx SDK 签名对齐

- 新增 src/gsc.ts:createGscClient 统一 store/usedcar 两家的 GSC 请求(同步 HMAC-SHA256
  头部签名 + scrm/dj 双后端 project 码),lane 侧不再各自抄一份请求层
- crypto.ts 补齐 MD5/SHA1 与 qs 摊平口径;signers.ts 的 createMd5Signer 与
  glsx-common-sdk createSign 逐字节对齐,glsx-common-sdk 依赖因此可以从 lane 摘掉
- test/sdkSign.test.mjs 把「与 SDK 逐字节一致」钉成可执行判据(14 条),
  test/gsc.test.mjs 覆盖头部签名与 transport 注入
- 已知:Version 常量不再来自 SDK,改由各 lane 本地 utils/versionConfig.js 提供
1 parent 18352a81
......@@ -22,6 +22,7 @@
"build": "tsup",
"dev": "tsup --watch",
"lint": "eslint . --max-warnings=0",
"test": "pnpm build && node --test test/sdkSign.test.mjs test/gsc.test.mjs",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
......
/**
* 摘要 / MAC 算法 helper。零运行时依赖:MD5 是自带纯实现,HMAC-SHA256 走 Web Crypto。
* 摘要 / MAC 算法 helper。零运行时依赖:MD5 / SHA1 / SHA256 都是纯实现,HMAC 有 Web Crypto
* (异步)与纯实现(同步)两条路。
*
* 之所以放在 api-core 而不是各域:签名算法是「接入适配」的公共基建,且 web 子应用与原生
* 小程序都要用。Web Crypto 在现代浏览器 / Node 18+ / 较高版本微信基础库都可用;若某环境
* 确实没有 crypto.subtle(极少数老基础库),可改用 createSigner 注入自己的同步算法
* (例如在 mp 侧引 crypto-js 实现一个 `(msg, secret) => sign` 喂进去)。
* 小程序都要用。Web Crypto 在现代浏览器 / Node 18+ 可用,但原生小程序没有 crypto.subtle,
* 因此 HMAC 另提供 hmacSha256Sync,签名器可按运行环境选择。
*/
/**
......@@ -144,7 +144,13 @@ export async function hmacSha256(message: string, secret: string): Promise<strin
);
}
const enc = new TextEncoder();
const key = await subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
const key = await subtle.importKey(
'raw',
enc.encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign'],
);
const signature = await subtle.sign('HMAC', key, enc.encode(message));
return Array.from(new Uint8Array(signature))
.map((b) => b.toString(16).padStart(2, '0'))
......@@ -197,11 +203,7 @@ export function sha1(input: string): string {
for (let j = 0; j < 16; j += 1) {
const p = i + j * 4;
w[j] =
((bytes[p]! << 24) |
(bytes[p + 1]! << 16) |
(bytes[p + 2]! << 8) |
bytes[p + 3]!) >>>
0;
((bytes[p]! << 24) | (bytes[p + 1]! << 16) | (bytes[p + 2]! << 8) | bytes[p + 3]!) >>> 0;
}
for (let j = 16; j < 80; j += 1) {
w[j] = leftRotate32(w[j - 3]! ^ w[j - 8]! ^ w[j - 14]! ^ w[j - 16]!, 1);
......@@ -243,3 +245,129 @@ export function sha1(input: string): string {
return [h0, h1, h2, h3, h4].map(toHexBigEndian).join('');
}
/**
* SHA-256(FIPS 180-4)。GSC 网关的头部签名走 HMAC-SHA256,而原生小程序没有 Web Crypto,
* 故提供纯实现;与 MD5 / SHA1 共用 `toUtf8Bytes`,已用 NIST 向量核对。
*/
const SHA256_K = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
function rotateRight(value: number, amount: number): number {
return ((value >>> amount) | (value << (32 - amount))) >>> 0;
}
function sha256Bytes(message: number[]): number[] {
const bytes = message.slice();
const bitLen = bytes.length * 8;
bytes.push(0x80);
while (bytes.length % 64 !== 56) bytes.push(0);
const hi = Math.floor(bitLen / 2 ** 32);
const lo = bitLen >>> 0;
bytes.push(
(hi >>> 24) & 0xff,
(hi >>> 16) & 0xff,
(hi >>> 8) & 0xff,
hi & 0xff,
(lo >>> 24) & 0xff,
(lo >>> 16) & 0xff,
(lo >>> 8) & 0xff,
lo & 0xff,
);
let h0 = 0x6a09e667;
let h1 = 0xbb67ae85;
let h2 = 0x3c6ef372;
let h3 = 0xa54ff53a;
let h4 = 0x510e527f;
let h5 = 0x9b05688c;
let h6 = 0x1f83d9ab;
let h7 = 0x5be0cd19;
const w = new Array<number>(64);
for (let i = 0; i < bytes.length; i += 64) {
for (let j = 0; j < 16; j += 1) {
const p = i + j * 4;
w[j] =
((bytes[p]! << 24) | (bytes[p + 1]! << 16) | (bytes[p + 2]! << 8) | bytes[p + 3]!) >>> 0;
}
for (let j = 16; j < 64; j += 1) {
const x = w[j - 15]!;
const y = w[j - 2]!;
const s0 = rotateRight(x, 7) ^ rotateRight(x, 18) ^ (x >>> 3);
const s1 = rotateRight(y, 17) ^ rotateRight(y, 19) ^ (y >>> 10);
w[j] = (w[j - 16]! + s0 + w[j - 7]! + s1) >>> 0;
}
let a = h0;
let b = h1;
let c = h2;
let d = h3;
let e = h4;
let f = h5;
let g = h6;
let h = h7;
for (let j = 0; j < 64; j += 1) {
const S1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
const ch = (e & f) ^ (~e & g);
const temp1 = (h + S1 + ch + SHA256_K[j]! + w[j]!) | 0;
const S0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
const maj = (a & b) ^ (a & c) ^ (b & c);
const temp2 = (S0 + maj) | 0;
h = g;
g = f;
f = e;
e = (d + temp1) | 0;
d = c;
c = b;
b = a;
a = (temp1 + temp2) | 0;
}
h0 = (h0 + a) | 0;
h1 = (h1 + b) | 0;
h2 = (h2 + c) | 0;
h3 = (h3 + d) | 0;
h4 = (h4 + e) | 0;
h5 = (h5 + f) | 0;
h6 = (h6 + g) | 0;
h7 = (h7 + h) | 0;
}
const hash = [h0, h1, h2, h3, h4, h5, h6, h7];
const digest: number[] = [];
for (let i = 0; i < hash.length; i += 1) {
const word = hash[i]!;
digest.push((word >>> 24) & 0xff, (word >>> 16) & 0xff, (word >>> 8) & 0xff, word & 0xff);
}
return digest;
}
export function sha256(input: string): string {
return sha256Bytes(toUtf8Bytes(input))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
/**
* HMAC-SHA256(同步纯实现,RFC 2104)。返回 64 位小写 hex,与 crypto-js
* `HmacSHA256(msg, key).toString()` 一致;原生小程序用这个,web / Node 可用上面的异步版。
*/
export function hmacSha256Sync(message: string, secret: string): string {
const blockSize = 64;
let key = toUtf8Bytes(secret);
if (key.length > blockSize) key = sha256Bytes(key);
while (key.length < blockSize) key.push(0);
const inner = key.map((b) => b ^ 0x36).concat(toUtf8Bytes(message));
const outer = key.map((b) => b ^ 0x5c).concat(sha256Bytes(inner));
return sha256Bytes(outer)
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
export type {
GatewayCredential,
GatewayStrategy,
HeaderSigner,
HeaderSignInput,
NormalizedEnvelope,
RawRequest,
RawResponse,
......@@ -24,12 +26,13 @@ export {
} from './senders';
export type { HostRequestConfig, HostSendFn } from './senders';
// 签名策略适配:通用工厂 + MD5 / SHA1 / HMAC / none 四种预设,算法可注入。
// 签名策略适配:通用工厂 + MD5 / SHA1 / HMAC / SDK / none 五种预设,算法可注入。
export {
createSigner,
createMd5Signer,
createSha1Signer,
createHmacSigner,
createSdkSigner,
createNoneSigner,
} from './signers';
export type {
......@@ -39,7 +42,28 @@ export type {
SignerOptions,
HmacSignerOptions,
HmacHeaderNames,
SdkSignerOptions,
} from './signers';
// 摘要 / MAC 算法 helper(供自定义 Signer 注入,例如 mp 侧引 crypto-js 实现同步 HMAC)。
export { md5, sha1, hmacSha256 } from './crypto';
// 摘要 / MAC 算法 helper(供自定义 Signer 注入;hmacSha256Sync 为同步纯实现,原生小程序可用)。
export { md5, sha1, sha256, hmacSha256, hmacSha256Sync } from './crypto';
// GSC / glsk 网关:HMAC 头部签名 + REST 客户端(查询串参数、JSON body、业务码归一)。
export {
createGscClient,
createGscHeaderSigner,
processGscSignParams,
flattenGscParams,
buildGscQuery,
generateGscNonce,
} from './gsc';
export type {
GscClient,
GscClientOptions,
GscEvents,
GscHeaderSignerOptions,
GscRequestConfig,
GscResponseConfig,
GscResponseData,
GscSessionConfig,
} from './gsc';
......@@ -60,7 +60,11 @@ function resolveAlgorithm(algo: SignerOptions['algorithm']): SignAlgorithm {
return algo;
}
function wrapSecret(body: string, secret: string, wrap: NonNullable<SignerOptions['secretWrap']>): string {
function wrapSecret(
body: string,
secret: string,
wrap: NonNullable<SignerOptions['secretWrap']>,
): string {
switch (wrap) {
case 'both':
return `${secret}${body}${secret}`;
......@@ -123,7 +127,13 @@ export function createSigner(options: SignerOptions): Signer {
const signValue = await algo(wrapSecret(body, secret, secretWrap), secret);
const out: Record<string, unknown> = {};
for (const key of [names.appKey, names.format, names.method, names.timestamp, names.version]) {
for (const key of [
names.appKey,
names.format,
names.method,
names.timestamp,
names.version,
]) {
if (excluded.has(key as 'appKey' | 'format' | 'method' | 'timestamp' | 'version')) continue;
if (picked[key] !== undefined) out[key] = picked[key];
}
......@@ -167,6 +177,43 @@ export function createSha1Signer(options: { id?: string; uppercase?: boolean } =
});
}
export interface SdkSignerOptions {
id?: string;
/** 摘要算法,对应 glsx-common-sdk createSign 的 way 参数,默认 'sha1'。 */
way?: 'sha1' | 'md5';
}
/**
* glsx-common-sdk `request/helper.js#createSign` 的等价实现:timestamp 当普通参数进签名原文
* (同时也进请求体,不是系统字段)、secret 前后包裹、输出大写、默认 SHA1。
*
* 入参须由调用方先摊平——SDK 内部用 qs(indices/allowDots/encodeValuesOnly) 摊平嵌套对象与
* 数组,摊平发生在签名之前;api-core 不引 qs,保持「签名只认平铺键」这一层职责分离。
*/
export function createSdkSigner(options: SdkSignerOptions = {}): Signer {
const { id = 'glsx-sdk', way = 'sha1' } = options;
const digest = way === 'md5' ? md5 : sha1;
return {
id,
fields(input: SignInput): Record<string, unknown> {
const { params, secret, timestamp, exclude } = input;
const ignored = new Set(exclude ?? []);
const picked: Record<string, unknown> = { ...params, timestamp };
delete picked.sign;
const body = Object.keys(picked)
.filter((key) => !ignored.has(key) && picked[key] !== undefined)
.sort()
.map((key) => `${key}${DEFAULT_CANONICALIZE(picked[key])}`)
.join('');
return {
timestamp: String(timestamp),
sign: digest(`${secret}${body}${secret}`).toUpperCase(),
};
},
};
}
/** 输出头名(glsk 风格:X-App-Id / X-Nonce / X-Timestamp / X-Sign)。 */
export type HmacHeaderNames = Partial<Record<'appId' | 'nonce' | 'timestamp' | 'sign', string>>;
......@@ -213,7 +260,9 @@ export function createHmacSigner(options: HmacSignerOptions = {}): Signer {
const stringToSign = Object.keys(all)
.filter((key) => key !== h.sign)
.sort()
.map((key) => `${key}=${typeof all[key] === 'string' ? all[key] : JSON.stringify(all[key])}`)
.map(
(key) => `${key}=${typeof all[key] === 'string' ? all[key] : JSON.stringify(all[key])}`,
)
.join('&');
const sign = await hmacSha256(`${stringToSign}&secret=${secret}`, secret);
......
......@@ -52,6 +52,27 @@ export interface Signer {
fields(input: SignInput): Record<string, unknown> | Promise<Record<string, unknown>>;
}
/**
* 头部签名入参:REST 网关把系统字段放进请求头(如 GSC 的 X-App-Id / X-Nonce / X-Timestamp /
* X-Sign),原文取自查询参数与请求体。与 SignInput 的差别是带 data、且不预置 timestamp ——
* 时间戳是签名产物的一部分,由签名器生成并同时输出成头。
*/
export interface HeaderSignInput {
method: string;
params?: Record<string, unknown>;
data?: unknown;
appKey: string;
secret: string;
/** 不参与签名原文的参数名;请求本身仍会带上它们 */
exclude?: string[];
}
/** 头部签名策略:返回要并入请求头的字段。 */
export interface HeaderSigner {
id: string;
headers(input: HeaderSignInput): Record<string, string> | Promise<Record<string, string>>;
}
/** 归一后的响应语义:与主壳拦截器(code === 200 成功,10002 会话失效)对齐。 */
export type NormalizedEnvelope = { data: unknown } | { code: number; message: string };
......
/**
* @file GSC / glsk 网关适配的钉值对照:头部 HMAC-SHA256 签名、参数摊平、URL/body 组装、
* returnAll / 业务失败 / 登出 / 去重的可观察语义。签名期望值先用 node:crypto 独立复算再钉死,
* 防止「自己对自己」的循环验证。
*/
import assert from 'node:assert/strict';
import { createHmac } from 'node:crypto';
import { createRequire } from 'node:module';
import test from 'node:test';
const require = createRequire(import.meta.url);
const {
buildGscQuery,
createGscClient,
createGscHeaderSigner,
hmacSha256Sync,
processGscSignParams,
sha256,
} = require('../dist/index.cjs');
const TS = 1700000000000;
const NONCE = '00000000-0000-4000-8000-000000000000';
const SECRET = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b';
const APP_ID = 'App_PromoteBusiness';
const nodeHmac = (message) => createHmac('sha256', SECRET).update(message).digest('hex');
const sign = (method, params, data, exclude = []) =>
createGscHeaderSigner({ now: () => TS, nonce: () => NONCE }).headers({
method,
params,
data,
appKey: APP_ID,
secret: SECRET,
exclude,
});
const verifyHeaderSign = (headers, params, data, method, exclude = []) => {
const processed = processGscSignParams(method, params, data ?? {});
const all = {
'X-App-Id': APP_ID,
'X-Nonce': headers['X-Nonce'],
'X-Timestamp': headers['X-Timestamp'],
...processed,
};
const stringToSign = Object.keys(all)
.sort()
.filter((key) => !exclude.includes(key))
.map((key) => `${key}=${all[key]}`)
.join('&');
assert.equal(headers['X-Sign'], nodeHmac(`${stringToSign}&secret=${SECRET}`));
};
test('IT-GSC-CRYPTO-001 SHA-256 / HMAC-SHA256 与标准向量一致', () => {
assert.equal(sha256('abc'), 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
assert.equal(sha256(''), 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');
assert.equal(
hmacSha256Sync('what do ya want for nothing?', 'Jefe'),
'5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843',
);
assert.equal(
hmacSha256Sync('中文签名原文', SECRET),
createHmac('sha256', SECRET).update('中文签名原文').digest('hex'),
);
});
test('IT-GSC-SIGN-002 钉值:POST 合并 data/params,GET 摊平,noSignAttr 剔除', () => {
const post = sign(
'POST',
{ sessionId: 's1' },
{ name: '张三', age: 0, active: false, tags: ['a', 'b'], nested: { x: 1 }, empty: null },
);
assert.equal(post['X-Sign'], 'e7f6be2e6893378a4f8c5b5631ad8c8714c9523d2a173309ccc31142a975f3de');
const get = sign('GET', { a: 1, arr: [1, 2], objs: [{ x: 'y' }], obj: { k: 'v' }, nil: null });
assert.equal(get['X-Sign'], 'ec9e20894365a4b63db4a1d3e6106ad79861dea63a389cb2e5604e21625f22f6');
const excluded = sign('POST', { sessionId: 's1', sign: 'stale' }, { file: 'abc', keep: 'y' }, [
'file',
]);
assert.equal(
excluded['X-Sign'],
'bfcfb70204add786920965f6e467255c0d3696d13a8fa19d5a5fc8fcbe873da7',
);
assert.deepEqual(Object.keys(post).sort(), ['X-App-Id', 'X-Nonce', 'X-Sign', 'X-Timestamp']);
assert.equal(post['X-App-Id'], APP_ID);
assert.equal(post['X-Timestamp'], String(TS));
});
test('IT-GSC-PARAMS-003 GET 签名原文带 params. 前缀,查询串不带', () => {
assert.deepEqual(
processGscSignParams('GET', {
a: 1,
arr: [1, 2],
objs: [{ x: 'y' }],
obj: { k: 'v' },
nil: null,
}),
{
'params.a': '1',
'params.arr': '1,2',
'params.objs': '[object Object]',
'params.obj': '[object Object]',
'params.nil': 'null',
},
);
assert.equal(
buildGscQuery({ a: 1, arr: [1, 2], objs: [{ x: 'y' }], obj: { k: 'v' }, nil: null }),
'a=1&arr%5B0%5D=1&arr%5B1%5D=2&objs%5B0%5D.x=y&obj.k=v&nil=',
);
});
const createMockSender = (respond) => {
const calls = [];
return {
calls,
async send(req) {
calls.push(req);
return { status: 200, data: respond(req) };
},
};
};
const createClient = (respond, extra = {}) => {
const sender = createMockSender(respond);
const events = { success: [], error: [], logout: [], duplicate: [], request: [], response: [] };
const client = createGscClient({
baseURL: 'https://gsc.test.glsx.com.cn/gsc-vcp-pad-facade',
appId: APP_ID,
appSecret: SECRET,
session: { requiresSession: true, sessionParamName: 'sessionId', sessionId: () => 'sid-1' },
response: {
codeKey: 'code',
successCode: '0',
dataKey: 'data',
errId: 'errId',
logoutValue: '21',
},
events: {
success: (body, config) => events.success.push([body, config]),
error: (body) => events.error.push(body),
logout: (body) => events.logout.push(body),
duplicate: (url) => events.duplicate.push(url),
request: (url) => events.request.push(url),
response: (res) => events.response.push(res),
},
signer: createGscHeaderSigner({ now: () => TS, nonce: () => NONCE }),
sender,
...extra,
});
return { client, sender, events };
};
test('IT-GSC-CLIENT-004 POST:sessionId 进 query、body 原样、签名头可独立复算', async () => {
const { client, sender } = createClient(() => ({ code: '0', data: { ok: true } }));
const data = { page: 1, tags: ['a'], nested: { x: 1 } };
await client.post('/minicarManage/findAllSoldPage', data, { params: { pageSize: 10 } });
assert.equal(sender.calls.length, 1);
const req = sender.calls[0];
assert.equal(
req.url,
'https://gsc.test.glsx.com.cn/gsc-vcp-pad-facade/minicarManage/findAllSoldPage?pageSize=10&sessionId=sid-1',
);
assert.deepEqual(req.data, data);
assert.equal(req.method, 'POST');
assert.equal(req.timeout, 15_000);
assert.equal(req.headers['Content-Type'], 'application/json;charset=UTF-8');
verifyHeaderSign(req.headers, { pageSize: 10, sessionId: 'sid-1' }, data, 'POST');
});
test('IT-GSC-CLIENT-005 returnAll 返回 { ...传输响应, data: 响应体 }', async () => {
const body = { code: '1', msg: '业务失败', data: { rows: [] } };
const { client, events } = createClient(() => body);
const res = await client.post('/x', {}, { returnAll: true });
assert.equal(res.status, 200);
assert.deepEqual(res.data, body);
// returnAll 在成功/失败判定之前返回,故不触发 success / error(与旧适配器一致)。
assert.equal(events.success.length, 0);
assert.equal(events.error.length, 0);
});
test('IT-GSC-CLIENT-006 成功码取 dataKey,业务失败返回信封并触发 error', async () => {
const ok = createClient(() => ({ code: '0', data: { id: 7 } }));
assert.deepEqual(await ok.client.post('/x'), { id: 7 });
assert.equal(ok.events.success.length, 1);
const failed = createClient(() => ({ code: 4001, msg: '参数错误', data: null }));
assert.deepEqual(await failed.client.post('/x'), { status: 200, data: null });
assert.equal(failed.events.error.length, 1);
assert.equal(failed.events.error[0].msg, '参数错误');
});
test('IT-GSC-CLIENT-007 登出:code 或 errId 命中 21 都触发 logout', async () => {
const byCode = createClient(() => ({ code: '21', data: { reason: 'expired' } }));
assert.deepEqual(await byCode.client.post('/x'), { status: 200, data: { reason: 'expired' } });
assert.equal(byCode.events.logout.length, 1);
const byErrId = createClient(() => ({ code: '0', errId: 21, data: null }));
assert.deepEqual(await byErrId.client.post('/x'), {
status: 200,
data: { code: '0', errId: 21, data: null },
});
assert.equal(byErrId.events.logout.length, 1);
});
test('IT-GSC-CLIENT-008 duplicatePrevention 拦截进行中的同 URL 请求', async () => {
let release;
const gate = new Promise((resolve) => {
release = resolve;
});
const sender = {
calls: 0,
async send() {
this.calls += 1;
await gate;
return { status: 200, data: { code: '0', data: null } };
},
};
const duplicateEvents = [];
const { client } = createClient(() => ({ code: '0' }), {
sender,
events: { duplicate: (url) => duplicateEvents.push(url) },
});
const first = client.post('/evalOrder/create', { a: 1 }, { duplicatePrevention: true });
await assert.rejects(
client.post('/evalOrder/create', { a: 2 }, { duplicatePrevention: true }),
(err) => err.name === 'DuplicateRequestError',
);
release();
await first;
assert.equal(sender.calls, 1);
assert.deepEqual(duplicateEvents, ['/evalOrder/create']);
});
test('IT-GSC-CLIENT-009 requiresSession 但 sessionId 为空时拒绝', async () => {
const { client, sender } = createClient(() => ({ code: '0' }), {
session: { requiresSession: true, sessionId: () => '' },
});
await assert.rejects(client.post('/x'), /获取到的sessionId无效/);
assert.equal(sender.calls.length, 0);
});
test('IT-GSC-CLIENT-010 未配置 codeKey 时原样返回传输响应', async () => {
const { client } = createClient(() => ({ anything: 1 }), {
response: undefined,
session: {},
});
assert.deepEqual(await client.get('/raw'), { status: 200, data: { anything: 1 } });
});
/**
* @file createSdkSigner 与 glsx-common-sdk `request/helper.js#createSign` 的钉值对照。
* 输入是已摊平参数(SDK 内部用 qs 摊平,摊平发生在签名前),timestamp 固定以便复算。
*/
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import test from 'node:test';
const require = createRequire(import.meta.url);
const { createSdkSigner } = require('../dist/index.cjs');
const TS = 1700000000000;
const SECRET = 'test-secret';
const input = (params, exclude = []) => ({
method: 'x',
params,
timestamp: TS,
appKey: '',
secret: SECRET,
version: '1.0.0',
format: 'json',
exclude,
});
const vectors = [
['扁平参数', [], { method: 'x', appKey: 'k', v: '1.0.0', format: 'json', sessionId: 's1' }],
['嵌套摊平', [], { method: 'x', 'query.page': '1', 'query.tag.a': 'b' }],
['noSignAttr', ['file'], { method: 'x', appKey: 'k', file: 'Zm9v', keep: 'y' }],
['空串/0/false', [], { method: 'x', a: '', c: '0', d: 'false' }],
];
const expected = {
sha1: [
'BC27B5462982BD1DA40289689132CD70CDEABDFF',
'F85D5F9CF7B5CBE3FBCFFA78C6AD365B0906F49E',
'CAF82208DD4E99496A79FFF43A56AB594E8BE412',
'1834B142BD53A74E57929E2DB6C43854A0C65E16',
],
md5: [
'6C6BD58E66A3018802EE140B8C571720',
'D40979D31F4DD5E6CD04E4C1437FEBBC',
'5EB6CA1369334FA6B215A29283A704B8',
'9B068B534E6A2856706D3AE5F4907AC6',
],
};
for (const way of ['sha1', 'md5']) {
test(`IT-SDK-SIGN-${way.toUpperCase()} 与 SDK createSign 逐字节一致`, () => {
const signer = createSdkSigner({ way });
vectors.forEach(([name, exclude, params], i) => {
const fields = signer.fields(input(params, exclude));
assert.equal(fields.timestamp, String(TS), `${name}: timestamp 进请求体且为字符串`);
assert.equal(fields.sign, expected[way][i], name);
});
});
}
test('IT-SDK-SIGN-003 sign 键被剔除,timestamp 不参与 noSignAttr', () => {
const signer = createSdkSigner();
const withSign = signer.fields(input({ method: 'x', sign: 'stale', appKey: 'k' }));
const withoutSign = signer.fields(input({ method: 'x', appKey: 'k' }));
assert.equal(withSign.sign, withoutSign.sign);
});
test('IT-SDK-SIGN-004 输出仅含 timestamp 与 sign(其余参数由请求体自带)', () => {
const fields = createSdkSigner().fields(input({ method: 'x', appKey: 'k' }));
assert.deepEqual(Object.keys(fields).sort(), ['sign', 'timestamp']);
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!