gsc.ts
14.3 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
import { hmacSha256Sync } from '../signing/crypto';
import { createAutoSender } from '../transport/senders';
import type { HeaderSigner, RawRequest, RawResponse, RequestSender } from '../core/types';
/**
* GSC / glsk 网关适配:REST 落点 + 查询串参数 + HMAC-SHA256 头部签名。
*
* 这套语义来自 glsk-toolkit 1.0.5(store 直接引包、usedcar 把 CJS 产物 vendored 进
* packageUsedCar/newRequestIndex.js)。与 RPC 网关的差别:
* - 签名不进请求体,而是 X-App-Id / X-Nonce / X-Timestamp / X-Sign 四个头;
* - 参数走 URL query(GET / POST 都一样),POST 的请求体是 JSON data;
* - 业务码在响应体里,失败 / 登出**不 reject**,而是 resolve 成 `{...res, data}` 由调用方读取。
*
* 这里只保留两处真正在用的开关(returnAll / duplicatePrevention)与既有事件,
* 不搬 security 白名单(enable 恒 false)等死路径。
*/
/** GET / DELETE 的参数摊平:数组展开成 `k[i]`、对象数组展开成 `k[i].field`、对象展开成 `k.field`。 */
export function flattenGscParams(params: Record<string, unknown>): Record<string, string> {
const result: Record<string, string> = {};
for (const [key, value] of Object.entries(params)) {
if (value === null || value === undefined) {
result[key] = '';
} else if (Array.isArray(value)) {
value.forEach((item, index) => {
if (typeof item === 'object' && item !== null) {
for (const [field, fieldValue] of Object.entries(item as Record<string, unknown>)) {
result[`${key}[${index}].${field}`] = String(fieldValue);
}
} else {
result[`${key}[${index}]`] = String(item);
}
});
} else if (typeof value === 'object') {
for (const [field, fieldValue] of Object.entries(value as Record<string, unknown>)) {
result[`${key}.${field}`] = String(fieldValue);
}
} else {
result[key] = String(value);
}
}
return result;
}
/** URL 查询串:`encodeURIComponent(k)=encodeURIComponent(v)` 以 & 连接(与旧适配器一致)。 */
export function buildGscQuery(params: Record<string, unknown>): string {
return Object.entries(flattenGscParams(params))
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
}
function serializeGscValue(value: unknown, stringifyString: boolean): string {
if (typeof value === 'string') return stringifyString ? JSON.stringify(value) : value;
if (Array.isArray(value) || (typeof value === 'object' && value !== null)) {
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
return String(value);
}
/**
* 签名原文用的参数处理:
* - GET / DELETE:glsk 把 `{ params, data }` 整包交给摊平函数,键因此带 `params.` / `data.`
* 前缀(例如 `params.sessionId`),与真实查询串的无前缀键**不同**——这是旧网关的既定行为,
* 服务端按同一套规则验签,必须照搬;
* - POST / PUT / PATCH:data 与 params 合并(params 覆盖),data 的字符串值先 JSON.stringify,
* 其余对象 / 数组序列化成 JSON;null / undefined 跳过。
*/
export function processGscSignParams(
method: string,
params: Record<string, unknown> = {},
data: Record<string, unknown> = {},
): Record<string, string> {
const normalized = method.toUpperCase();
if (normalized === 'GET' || normalized === 'DELETE') {
return flattenGscParams({ params, data });
}
const result: Record<string, string> = {};
for (const [key, value] of Object.entries(data)) {
if (value === null || value === undefined) continue;
result[key] = serializeGscValue(value, true);
}
for (const [key, value] of Object.entries(params)) {
if (value === null || value === undefined) continue;
result[key] = serializeGscValue(value, false);
}
return result;
}
/** UUID v4 形式的 nonce;小程序无 crypto.getRandomValues 时退回 Math.random。 */
export function generateGscNonce(): string {
const cryptoObj = (globalThis as { crypto?: { getRandomValues?: (bytes: Uint8Array) => void } })
.crypto;
if (cryptoObj?.getRandomValues) {
const bytes = new Uint8Array(16);
cryptoObj.getRandomValues(bytes);
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (char) => {
const random = (Math.random() * 16) | 0;
const value = char === 'x' ? random : (random & 0x3) | 0x8;
return value.toString(16);
});
}
export interface GscHeaderSignerOptions {
id?: string;
/** 输出头名,默认 X-App-Id / X-Nonce / X-Timestamp / X-Sign。 */
headerNames?: Partial<Record<'appId' | 'nonce' | 'timestamp' | 'sign', string>>;
/** 时间戳来源,测试可注入固定值。 */
now?: () => number;
/** nonce 来源,测试可注入固定值。 */
nonce?: () => string;
}
/**
* GSC 头部签名(HMAC-SHA256,同步纯实现,原生小程序可直接用):
* 原文 = `X-App-Id=...&X-Nonce=...&X-Timestamp=...&<业务参数 k=v>` 按 key 排序以 & 连接,
* 末尾拼 `&secret=<appSecret>`,密钥同为 appSecret;签名小写 hex。
* 与 glsk `generateSignature` / vendored `Qe` 逐字节一致。
*/
export function createGscHeaderSigner(options: GscHeaderSignerOptions = {}): HeaderSigner {
const {
id = 'gsc-hmac-sha256',
headerNames = {},
now = () => Date.now(),
nonce = generateGscNonce,
} = options;
const names = {
appId: 'X-App-Id',
nonce: 'X-Nonce',
timestamp: 'X-Timestamp',
sign: 'X-Sign',
...headerNames,
};
return {
id,
headers(input): Record<string, string> {
const { method, params = {}, data = {}, appKey, secret, exclude = [] } = input;
const processed = processGscSignParams(
method,
params,
typeof data === 'object' && data !== null ? (data as Record<string, unknown>) : {},
);
const timestamp = String(now());
const nonceValue = nonce();
const all: Record<string, string> = {
[names.appId]: appKey,
[names.nonce]: nonceValue,
[names.timestamp]: timestamp,
...processed,
};
const stringToSign = Object.keys(all)
.sort()
.filter((key) => !exclude.includes(key))
.map((key) => `${key}=${all[key]}`)
.join('&');
const sign = hmacSha256Sync(`${stringToSign}&secret=${secret}`, secret);
return {
[names.appId]: appKey,
[names.nonce]: nonceValue,
[names.timestamp]: timestamp,
[names.sign]: sign,
};
},
};
}
export interface GscRequestConfig {
url: string;
method?: string;
params?: Record<string, unknown>;
data?: unknown;
headers?: Record<string, string>;
timeout?: number;
returnAll?: boolean;
noSignAttr?: string[];
duplicatePrevention?: boolean;
}
export interface GscResponseConfig {
/** 业务码字段名;缺省则不解析响应,原样返回传输响应。 */
codeKey?: string | string[];
successCode?: string | number;
dataKey?: string;
errId?: string;
logoutValue?: string | number;
}
export interface GscSessionConfig {
requiresSession?: boolean;
sessionParamName?: string;
sessionId?: string | (() => string | Promise<string>);
}
export interface GscResponseData {
data: unknown;
status: number;
}
/**
* 事件参数顺序与 glsk 一致:request(url, config)、response(responseData, config)、
* success/error/logout(body, config)、duplicate(url, config)。
*/
export interface GscEvents {
request?: (url: string, config: GscRequestConfig) => void;
response?: (response: GscResponseData, config: GscRequestConfig) => void;
success?: (body: Record<string, unknown>, config: GscRequestConfig) => void;
error?: (body: Record<string, unknown>, config: GscRequestConfig) => void;
logout?: (body: Record<string, unknown>, config: GscRequestConfig) => void;
duplicate?: (url: string, config: GscRequestConfig) => void;
}
export interface GscClientOptions {
baseURL: string;
appId: string;
appSecret: string;
timeout?: number;
headers?: Record<string, string>;
params?: Record<string, unknown>;
session?: GscSessionConfig;
response?: GscResponseConfig;
events?: GscEvents;
returnAll?: boolean;
noSignAttr?: string[];
signer?: HeaderSigner;
sender?: RequestSender;
}
export interface GscClient {
request<T = unknown>(config: GscRequestConfig): Promise<T>;
get<T = unknown>(url: string, config?: Omit<GscRequestConfig, 'url' | 'method'>): Promise<T>;
delete<T = unknown>(url: string, config?: Omit<GscRequestConfig, 'url' | 'method'>): Promise<T>;
post<T = unknown>(
url: string,
data?: unknown,
config?: Omit<GscRequestConfig, 'url' | 'method' | 'data'>,
): Promise<T>;
put<T = unknown>(
url: string,
data?: unknown,
config?: Omit<GscRequestConfig, 'url' | 'method' | 'data'>,
): Promise<T>;
patch<T = unknown>(
url: string,
data?: unknown,
config?: Omit<GscRequestConfig, 'url' | 'method' | 'data'>,
): Promise<T>;
}
function looseEquals(left: unknown, right: unknown): boolean {
if (left === right) return true;
if (left === null || left === undefined || right === null || right === undefined) return false;
return String(left) === String(right);
}
/**
* GSC 网关客户端:保留旧适配器的可观察语义 —— URL、JSON body、签名头、sessionId 进 query、
* returnAll / 业务失败 / 登出的事件与返回值,以及 duplicatePrevention 的进行中拦截。
*/
export function createGscClient(options: GscClientOptions): GscClient {
const {
baseURL,
appId,
appSecret,
timeout = 15_000,
headers: baseHeaders = {},
params: baseParams = {},
session = {},
response = {},
events = {},
returnAll: defaultReturnAll = false,
noSignAttr: baseNoSignAttr = [],
signer = createGscHeaderSigner(),
} = options;
const { codeKey, successCode = '0', dataKey = 'data', errId = 'errId', logoutValue } = response;
let sender = options.sender;
const activeUrls = new Set<string>();
const resolveSessionId = async (): Promise<string> => {
const provider = session.sessionId;
if (!provider) throw new Error('需要sessionId,但未提供获取方法');
const value = await Promise.resolve(typeof provider === 'function' ? provider() : provider);
if (typeof value !== 'string' || !value) throw new Error('获取到的sessionId无效');
return value;
};
const handleResponse = <T>(raw: RawResponse, config: GscRequestConfig): T => {
const responseData: GscResponseData = { data: raw.data, status: raw.status };
events.response?.(responseData, config);
const body = raw.data;
if (!codeKey) return responseData as T;
if (body === null || typeof body !== 'object') throw new Error('响应数据解析失败');
const record = body as Record<string, unknown>;
const matchedKey = Array.isArray(codeKey) ? codeKey.find((key) => key in record) : codeKey;
if (!matchedKey) return responseData as T;
const code = String(record[matchedKey]);
const isLogout = looseEquals(code, logoutValue) || looseEquals(record[errId], logoutValue);
if (isLogout) events.logout?.(record, config);
if (config.returnAll ?? defaultReturnAll) return { ...responseData, data: record } as T;
if (code === String(successCode)) {
events.success?.(record, config);
const payload = record[dataKey];
// 旧适配器对 null / undefined 的 data 会退回整包传输响应(业务动作类接口常见)。
return (payload === null || payload === undefined ? responseData : payload) as T;
}
if (isLogout) return { ...responseData, data: record[dataKey] } as T;
events.error?.(record, config);
return { ...responseData, data: record[dataKey] } as T;
};
const request = async <T>(config: GscRequestConfig): Promise<T> => {
const { url, method: rawMethod = 'GET' } = config;
const method = rawMethod.toUpperCase();
if (config.duplicatePrevention) {
if (activeUrls.has(url)) {
events.duplicate?.(url, config);
const error = new Error(`请求正在进行中,请勿重复提交。接口: ${url}`);
error.name = 'DuplicateRequestError';
throw error;
}
// 在首个 await 之前登记:连点两次时第二次也能看到第一次尚未发出的请求。
activeUrls.add(url);
}
try {
const sessionParams: Record<string, unknown> = {};
if (session.requiresSession) {
sessionParams[session.sessionParamName || 'sessionId'] = await resolveSessionId();
}
const params = { ...baseParams, ...config.params, ...sessionParams };
const headers: Record<string, string> = {
'Content-Type': 'application/json;charset=UTF-8',
...baseHeaders,
...config.headers,
};
const signature = await Promise.resolve(
signer.headers({
method,
params,
data: config.data,
appKey: appId,
secret: appSecret,
exclude: config.noSignAttr ?? baseNoSignAttr,
}),
);
Object.assign(headers, signature);
const query = buildGscQuery(params);
const path = `${baseURL}${url}`;
const fullURL = `${path}${query ? (path.includes('?') ? '&' : '?') + query : ''}`;
events.request?.(fullURL, config);
if (!sender) sender = createAutoSender();
const raw = await sender.send({
method: method as RawRequest['method'],
url: fullURL,
data: config.data ?? {},
headers,
timeout: config.timeout ?? timeout,
});
return handleResponse<T>(raw, config);
} finally {
if (config.duplicatePrevention) activeUrls.delete(url);
}
};
return {
request,
get: (url, config = {}) => request({ url, method: 'GET', ...config }),
delete: (url, config = {}) => request({ url, method: 'DELETE', ...config }),
post: (url, data = {}, config = {}) => request({ url, method: 'POST', data, ...config }),
put: (url, data = {}, config = {}) => request({ url, method: 'PUT', data, ...config }),
patch: (url, data = {}, config = {}) => request({ url, method: 'PATCH', data, ...config }),
};
}