@seayoo-io/combo-sdk-node 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -381,6 +381,7 @@ import { GMError } from "@seayoo-io/combo-sdk-node"
381
381
  function gmCommandHandler(command, args, requestId, idempotencyKey, version) {
382
382
  // requestId 本次 GM 请求的唯一 ID。游戏侧可用此值来对请求进行去重。
383
383
  // idempotencyKey 本次 GM 请求的 Idempotency Key。如果有非空值则应当执行幂等处理逻辑。
384
+ // SDK 已经内置了 idempotencyKey 的处理工具和配置,详细见下描述
384
385
  // version 对应的是世游 GM 服务的版本号,目前固定是 2.0
385
386
  // command 对应的是 GM 协议中定义的方法名,区分大小写
386
387
  switch(command) {
@@ -443,14 +444,55 @@ const config = {
443
444
  }
444
445
  ```
445
446
 
446
- ### Step 2 绑定处理函数
447
+ ### Step 2 创建 Store Helper 以启用 idempotencyKey 处理逻辑
448
+
449
+ ```js
450
+ // SDK 内置 idempotencyKey 处理逻辑,其需要相关存储来实现,比如 Redis。
451
+ // 创建 Store Helper 用于启用内置的 idempotencyKey 处理逻辑
452
+ // store helper 需要实现以下方法即可:
453
+ interface IdempotencyKeyStoreHelper {
454
+ /**
455
+ * setNX 用于原子性地存储幂等记录并返回旧值。
456
+ * value 仅在 key 不存在时才会被存储 (Only set the key if it does not already exist)。
457
+ * 返回值是 key 存在时的旧值。如果 key 不存在则返回空字符串。
458
+ */
459
+ setNX: (key: string, value: string) => Promise<string>
460
+
461
+ /**
462
+ * setXX 用于原子性地更新已存在的幂等记录。
463
+ * value 仅在 key 存在时才会被存储 (Only set the key if it already exists)。
464
+ */
465
+ setXX: (key: string, value: string) => Promise<void>
466
+ }
467
+
468
+ // SDK 内置实现了两个工具类
469
+ import { MemoryIdempotencyStore, RedisIdempotencyStore } from "@seayoo-io/combo-sdk-node"
470
+
471
+ // MemoryIdempotencyStore 仅仅用于本地调试
472
+ const storeHelper = new MemoryIdempotencyStore()
473
+ // RedisIdempotencyStore 基于 ioredis 实现
474
+ const storeHelper = new RedisIdempotencyStore({
475
+ /** 超时设定,单位秒,推荐不低于24小时 */
476
+ ttl?: number
477
+ /** ioredis 客户端 */
478
+ client: Redis
479
+ /** key 前缀 */
480
+ prefix?: string
481
+ })
482
+
483
+ // 当然可以直接自行实现上述 store helper 方法
484
+ ```
485
+
486
+ ### Step 3 绑定处理函数
447
487
 
448
488
  绑定方式同 Notify 类似,提供三种不同的方式来对接 http 服务。推荐使用方式 3。
449
489
 
450
490
  ```js
451
491
  // 方式 1. 使用 http 模块处理函数
452
492
  import { getGMCommandHandler } from "@seayoo-io/combo-sdk-node"
453
- const handler = getGMCommandHandler(config, gmCommandHandler)
493
+ // storeHelper 类型为 IdempotencyKeyStoreHelper
494
+ // 可不传递,如果不提供则不会启用内置的 idempotencyKey 处理逻辑,下同
495
+ const handler = getGMCommandHandler(config, gmCommandHandler, storeHelper)
454
496
  http.createServer(async function(req, res){
455
497
  if(req.path === "<YourNotifyUrl>" && req.method === "POST") {
456
498
  await handler(req, res)
@@ -459,20 +501,20 @@ http.createServer(async function(req, res){
459
501
 
460
502
  // 方式 2. 使用 express / koa 的 handler
461
503
  import { getGMHandlerForExpress } from "@seayoo-io/combo-sdk-node"
462
- const expressHandler = getGMHandlerForExpress(config, gmCommandHandler)
504
+ const expressHandler = getGMHandlerForExpress(config, gmCommandHandler, storeHelper)
463
505
  app.post("/path/to/your/gm/url", expressHandler)
464
506
 
465
507
  import { getGMHandlerForKoa } from "@seayoo-io/combo-sdk-node"
466
- const koaHandler = getGMHandlerForKoa(config, gmCommandHandler)
508
+ const koaHandler = getGMHandlerForKoa(config, gmCommandHandler, storeHelper)
467
509
  app.post("/path/to/your/gm/url", koaHandler)
468
510
 
469
511
  // 方式 3. 使用 expres / koa 的中间件,推荐
470
512
  import { getGMMiddlewareForExpress } from "@seayoo-io/combo-sdk-node"
471
- const gmMiddleware = getGMMiddlewareForExpress("/path/to/your/gm/url", config, gmCommandHandler);
513
+ const gmMiddleware = getGMMiddlewareForExpress("/path/to/your/gm/url", config, gmCommandHandler, storeHelper);
472
514
  app.use(gmMiddleware);
473
515
 
474
516
  import { getGMMiddlewareForKoa } from "@seayoo-io/combo-sdk-node"
475
- const gmMiddleware = getGMMiddlewareForKoa("/path/to/your/gm/url", config, gmCommandHandler);
517
+ const gmMiddleware = getGMMiddlewareForKoa("/path/to/your/gm/url", config, gmCommandHandler, storeHelper);
476
518
  app.use(gmMiddleware);
477
519
 
478
520
  ```
package/dist/const.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** SDK 名称 */
2
2
  export declare const SDKName = "combo-sdk-node";
3
3
  /** SDK 版本,在编译前会被动态替换 */
4
- export declare const SDKVersion = "1.0.0";
4
+ export declare const SDKVersion = "1.2.0";
5
5
  /**
6
6
  * 世游支持的服务端点列表
7
7
  */
@@ -1,17 +1,17 @@
1
1
  import { type SDKBaseConfig } from "../utils";
2
2
  import type { IncomingMessage, ServerResponse } from "http";
3
- import type { GMCommandHandler } from "./types";
3
+ import { type GMCommandHandler, type IdempotencyKeyStoreHelper } from "./types";
4
4
  import type { ParameterizedContext, Next } from "koa";
5
5
  import type { Request as ExpressRequest, Response as ExpressResponse, NextFunction as ExpressNextFunction } from "express";
6
6
  type SDKMinConfig = Omit<SDKBaseConfig, "endpoint">;
7
7
  /**
8
- * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
8
+ * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知,storeHelper 提供存储支持以实现幂等key(idempotencyKey)的自动化处理
9
9
  *
10
10
  * 另有 express 和 koa2 版本的处理函数可以使用。
11
11
  *
12
12
  * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
13
13
  */
14
- export declare function getGMCommandHandler(config: SDKMinConfig, handler: GMCommandHandler): (req: IncomingMessage, res: ServerResponse, rawBodyString?: string) => Promise<void>;
14
+ export declare function getGMCommandHandler(config: SDKMinConfig, handler: GMCommandHandler, storeHelper?: IdempotencyKeyStoreHelper): (req: IncomingMessage, res: ServerResponse, rawBodyString?: string) => Promise<void>;
15
15
  /**
16
16
  * 获取基于 express 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
17
17
  *
@@ -23,7 +23,7 @@ export declare function getGMCommandHandler(config: SDKMinConfig, handler: GMCom
23
23
  *
24
24
  * https://cloud.tencent.com/developer/ask/sof/110062928
25
25
  */
26
- export declare function getGMHandlerForExpress(config: SDKMinConfig, handler: GMCommandHandler): (req: ExpressRequest & {
26
+ export declare function getGMHandlerForExpress(config: SDKMinConfig, handler: GMCommandHandler, storeHelper?: IdempotencyKeyStoreHelper): (req: ExpressRequest & {
27
27
  rawBody?: string;
28
28
  }, res: ExpressResponse) => Promise<void>;
29
29
  /**
@@ -31,7 +31,7 @@ export declare function getGMHandlerForExpress(config: SDKMinConfig, handler: GM
31
31
  *
32
32
  * 需要先于 body-parse 等类似插件加载
33
33
  */
34
- export declare function getGMMiddlewareForExpress(paths: string | string[], config: SDKMinConfig, handler: GMCommandHandler): (req: ExpressRequest, res: ServerResponse, next: ExpressNextFunction) => Promise<void>;
34
+ export declare function getGMMiddlewareForExpress(paths: string | string[], config: SDKMinConfig, handler: GMCommandHandler, storeHelper?: IdempotencyKeyStoreHelper): (req: ExpressRequest, res: ServerResponse, next: ExpressNextFunction) => Promise<void>;
35
35
  /**
36
36
  * 获取基于 koa2 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
37
37
  *
@@ -39,7 +39,7 @@ export declare function getGMMiddlewareForExpress(paths: string | string[], conf
39
39
  *
40
40
  * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
41
41
  */
42
- export declare function getGMHandlerForKoa(config: SDKMinConfig, handler: GMCommandHandler): (ctx: Pick<ParameterizedContext, "req" | "res"> & {
42
+ export declare function getGMHandlerForKoa(config: SDKMinConfig, handler: GMCommandHandler, storeHelper?: IdempotencyKeyStoreHelper): (ctx: Pick<ParameterizedContext, "req" | "res"> & {
43
43
  rawBody?: string;
44
44
  }) => Promise<void>;
45
45
  /**
@@ -47,5 +47,5 @@ export declare function getGMHandlerForKoa(config: SDKMinConfig, handler: GMComm
47
47
  *
48
48
  * 需要先于 koa-body 等类似插件加载
49
49
  */
50
- export declare function getGMMiddlewareForKoa(paths: string | string[], config: SDKMinConfig, handler: GMCommandHandler): (ctx: Pick<ParameterizedContext, "method" | "path" | "req" | "res">, next: Next) => Promise<void>;
50
+ export declare function getGMMiddlewareForKoa(paths: string | string[], config: SDKMinConfig, handler: GMCommandHandler, storeHelper?: IdempotencyKeyStoreHelper): (ctx: Pick<ParameterizedContext, "method" | "path" | "req" | "res">, next: Next) => Promise<void>;
51
51
  export {};
@@ -1,11 +1,25 @@
1
1
  import { GMError } from "../const";
2
2
  import { MaybePromise } from "../utils";
3
+ export interface GMRequestBody {
4
+ /** version 是世游 GM 服务的版本号,目前固定 2.0 */
5
+ version: string;
6
+ /** 本次 GM 请求的唯一 ID。游戏侧可用此值来对请求进行去重 */
7
+ request_id: string;
8
+ /** 本次 GM 请求的 Idempotency Key。如果有非空值则应当执行幂等处理逻辑。 */
9
+ idempotency_key?: string;
10
+ /** GM 命令标识。取值和 GM 协议文件中的 rpc 名称对应,大小写敏感 */
11
+ command: string;
12
+ /** args 是和 cmd 对应的命令参数,具体值取决于协议中对应 rpc 的 Request 定义 */
13
+ args: Record<string, unknown>;
14
+ }
15
+ export declare function isGMRequestBody(data: unknown): data is GMRequestBody;
3
16
  export interface GMErrorResponse {
4
17
  /** 错误类型。对应内置定义好的 GmError 枚举值 */
5
18
  error: GMError;
6
19
  /** 错误描述信息。预期是给人看的,便于联调和问题排查。*/
7
20
  message: string;
8
21
  }
22
+ export declare function isGMErrorResponse(data: unknown): data is GMErrorResponse;
9
23
  /**
10
24
  * 自定义 GM 执行函数,需要返回执行结果,其结构由协议中对应 rpc 的 Response 定义。
11
25
  *
@@ -14,3 +28,29 @@ export interface GMErrorResponse {
14
28
  export type GMCommandHandler = {
15
29
  (command: string, args: Record<string, unknown>, requestId: string, idempotencyKey: string, version: string): MaybePromise<Record<string, unknown> | GMErrorResponse | Error>;
16
30
  };
31
+ /**
32
+ * 在处理幂等性时,需要使用储存支持,比如 Reis
33
+ */
34
+ export interface IdempotencyKeyStoreHelper {
35
+ /**
36
+ * setNX 用于原子性地存储幂等记录并返回旧值。
37
+ * value 仅在 key 不存在时才会被存储 (Only set the key if it does not already exist)。
38
+ * 返回值是 key 存在时的旧值。如果 key 不存在则返回空字符串。
39
+ */
40
+ setNX: (key: string, value: string) => Promise<string>;
41
+ /**
42
+ * setXX 用于原子性地更新已存在的幂等记录。
43
+ * value 仅在 key 存在时才会被存储 (Only set the key if it already exists)。
44
+ */
45
+ setXX: (key: string, value: string) => Promise<void>;
46
+ }
47
+ /** 幂等key 记录 */
48
+ export interface IdempotencyRecord {
49
+ noce: string;
50
+ key: string;
51
+ id: string;
52
+ cmd: string;
53
+ args: string;
54
+ resp?: Record<string, unknown> | GMErrorResponse | Error;
55
+ }
56
+ export declare function isIdempotencyRecord(data: unknown): data is IdempotencyRecord;
@@ -0,0 +1,27 @@
1
+ import { IdempotencyKeyStoreHelper } from "./types";
2
+ import type { Redis } from "ioredis";
3
+ export declare function verifyStoreHelper(storeHelper: unknown): void;
4
+ export declare function toString(data: object): string;
5
+ /** 提供基于内存的 store helper,仅供本地调试使用,不支持 ttl 超时功能 */
6
+ export declare class MemoryIdempotencyStore implements IdempotencyKeyStoreHelper {
7
+ mc: Record<string, string>;
8
+ constructor();
9
+ setNX(key: string, value: string): Promise<string>;
10
+ setXX(key: string, value: string): Promise<void>;
11
+ }
12
+ /** 基于 ioredis 的 store helper */
13
+ export declare class RedisIdempotencyStore implements IdempotencyKeyStoreHelper {
14
+ client: Redis;
15
+ ttl: number;
16
+ prefix: string;
17
+ constructor(options: {
18
+ /** 超时设定,单位秒,推荐不低于24小时 */
19
+ ttl?: number;
20
+ /** ioredis 客户端 */
21
+ client: Redis;
22
+ /** key 前缀 */
23
+ prefix?: string;
24
+ });
25
+ setNX(key: string, value: string): Promise<string>;
26
+ setXX(key: string, value: string): Promise<void>;
27
+ }
package/dist/index.cjs CHANGED
@@ -12,7 +12,7 @@ var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
12
12
  /** SDK 名称 */
13
13
  const SDKName = "combo-sdk-node";
14
14
  /** SDK 版本,在编译前会被动态替换 */
15
- const SDKVersion = "1.0.0";
15
+ const SDKVersion = "1.2.0";
16
16
  /**
17
17
  * 世游支持的服务端点列表
18
18
  */
@@ -374,14 +374,18 @@ async function repsonseJson(res, data, statusCode = 200) {
374
374
  res.end();
375
375
  }
376
376
 
377
- /**
378
- * 生成一个 SessionID 以用作用户上下线的上报标记
379
- */
377
+ /** 生成一个 SessionID 以用作用户上下线的上报标记 */
380
378
  function genSessionID(comboId) {
381
379
  const ts = process.hrtime.bigint();
382
380
  const r = Math.random() + Math.random();
383
381
  return crypto.createHash("md5").update(`${comboId}${ts}${r}`).digest("hex").toLowerCase();
384
382
  }
383
+ /** 生成一个随机id */
384
+ function genNonceString() {
385
+ const ts = process.hrtime.bigint();
386
+ const r = Math.random() + Math.random();
387
+ return crypto.createHash("md5").update(`${ts}${r}`).digest("hex").toLowerCase();
388
+ }
385
389
 
386
390
  const defaultDataField = "data";
387
391
  const defaultMessageField = "message";
@@ -1133,7 +1137,8 @@ class TokenVerifier {
1133
1137
  external_name: payload.external_name,
1134
1138
  weixin_unionid: payload.weixin_unionid || "",
1135
1139
  distro: payload.distro || "",
1136
- variant: payload.variant || ""
1140
+ variant: payload.variant || "",
1141
+ age: payload.age || 0
1137
1142
  };
1138
1143
  } catch (error) {
1139
1144
  return new Error(`IdentityToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
@@ -1325,6 +1330,66 @@ function isGMRequestBody(data) {
1325
1330
  function isGMErrorResponse(data) {
1326
1331
  return isObject(data) && Object.keys(data).length === 2 && "error" in data && "message" in data;
1327
1332
  }
1333
+ function isIdempotencyRecord(data) {
1334
+ return isObject(data) && "key" in data && "id" in data && "cmd" in data && "args" in data;
1335
+ }
1336
+
1337
+ function verifyStoreHelper(storeHelper) {
1338
+ if (storeHelper) {
1339
+ if (typeof storeHelper !== "object" || !("setXX" in storeHelper) || !("setNX" in storeHelper)) {
1340
+ throw new Error("store helper should be { setXX, setNX }");
1341
+ }
1342
+ if (typeof storeHelper.setNX !== "function" || storeHelper.setNX.length !== 2) {
1343
+ throw new Error("store.setNX should be (key, value) => string");
1344
+ }
1345
+ if (typeof storeHelper.setXX !== "function" || storeHelper.setXX.length !== 2) {
1346
+ throw new Error("store.setXX should be (key, value) => void");
1347
+ }
1348
+ }
1349
+ }
1350
+ function toString(data) {
1351
+ return JSON.stringify(data);
1352
+ }
1353
+ /** 提供基于内存的 store helper,仅供本地调试使用,不支持 ttl 超时功能 */
1354
+ class MemoryIdempotencyStore {
1355
+ constructor() {
1356
+ this.mc = void 0;
1357
+ this.mc = {};
1358
+ }
1359
+ async setNX(key, value) {
1360
+ const r = this.mc[key];
1361
+ if (!r) {
1362
+ this.mc[key] = value;
1363
+ return "";
1364
+ }
1365
+ return r;
1366
+ }
1367
+ async setXX(key, value) {
1368
+ const r = this.mc[key];
1369
+ if (r) {
1370
+ this.mc[key] = value;
1371
+ }
1372
+ }
1373
+ }
1374
+ /** 基于 ioredis 的 store helper */
1375
+ class RedisIdempotencyStore {
1376
+ constructor(options) {
1377
+ var _options$ttl;
1378
+ this.client = void 0;
1379
+ this.ttl = void 0;
1380
+ this.prefix = void 0;
1381
+ this.client = options.client;
1382
+ this.ttl = Math.max(24 * 3600, (_options$ttl = options.ttl) != null ? _options$ttl : 0);
1383
+ this.prefix = options.prefix || "";
1384
+ }
1385
+ async setNX(key, value) {
1386
+ return (await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "NX", "GET")) || "";
1387
+ }
1388
+ async setXX(key, value) {
1389
+ await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "XX");
1390
+ }
1391
+ }
1392
+
1328
1393
  const error2httpStatus = {
1329
1394
  ["invalid_http_method" /* GMError.InvalidHttpMethod */]: 405 /* HttpStatus.MethodNotAllowed */,
1330
1395
  ["invalid_content_type" /* GMError.InvalidContentType */]: 415 /* HttpStatus.UnsupportedMediaType */,
@@ -1342,14 +1407,15 @@ const error2httpStatus = {
1342
1407
  ["internal_error" /* GMError.InternalError */]: 500 /* HttpStatus.InternalServerError */
1343
1408
  };
1344
1409
  /**
1345
- * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1410
+ * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知,storeHelper 提供存储支持以实现幂等key(idempotencyKey)的自动化处理
1346
1411
  *
1347
1412
  * 另有 express 和 koa2 版本的处理函数可以使用。
1348
1413
  *
1349
1414
  * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1350
1415
  */
1351
- function getGMCommandHandler(config, handler) {
1416
+ function getGMCommandHandler(config, handler, storeHelper) {
1352
1417
  verifyConfigWithoutEndpoint(config);
1418
+ verifyStoreHelper(storeHelper);
1353
1419
  return async function (req, res, rawBodyString) {
1354
1420
  if (req.method !== "POST") {
1355
1421
  responseError(res, 405 /* HttpStatus.MethodNotAllowed */, "invalid_http_method" /* GMError.InvalidHttpMethod */, `Expecting POST, got ${req.method}`);
@@ -1379,9 +1445,56 @@ function getGMCommandHandler(config, handler) {
1379
1445
  responseError(res, 400 /* HttpStatus.BadRequest */, "invalid_request" /* GMError.InvalidRequest */, `GM request body format error`);
1380
1446
  return;
1381
1447
  }
1448
+ // 处理幂等key
1449
+ const currentRecord = {
1450
+ noce: genNonceString(),
1451
+ key: gmRequest.idempotency_key || "",
1452
+ id: gmRequest.request_id,
1453
+ cmd: gmRequest.command,
1454
+ args: toString(gmRequest.args)
1455
+ };
1456
+ let oldResponse = null;
1457
+ if (storeHelper && gmRequest.idempotency_key) {
1458
+ const oldRecordStr = await storeHelper.setNX(gmRequest.idempotency_key, toString(currentRecord)).catch(e => e instanceof Error ? e : new Error(String(e)));
1459
+ if (oldRecordStr instanceof Error) {
1460
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) setNX error`, oldRecordStr);
1461
+ responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, oldRecordStr.message);
1462
+ return;
1463
+ }
1464
+ const oldRecord = oldRecordStr ? parseJSON(oldRecordStr, isIdempotencyRecord) : null;
1465
+ if (!oldRecord && oldRecordStr) {
1466
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) parse old idempotency record failed: ${oldRecordStr}`);
1467
+ responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, "parse old idempotency record failed");
1468
+ return;
1469
+ }
1470
+ // 检查是否为首次请求
1471
+ const isFirstRequest = oldRecordStr === "" || (oldRecord == null ? void 0 : oldRecord.noce) === currentRecord.noce;
1472
+ if (!isFirstRequest && oldRecord) {
1473
+ if (!oldRecord.resp) {
1474
+ responseError(res, error2httpStatus["idempotency_conflict" /* GMError.IdempotencyConflict */], "idempotency_conflict" /* GMError.IdempotencyConflict */, "previous request is not completed");
1475
+ return;
1476
+ }
1477
+ if (oldRecord.cmd !== gmRequest.command) {
1478
+ responseError(res, error2httpStatus["idempotency_mismatch" /* GMError.IdempotencyMismatch */], "idempotency_mismatch" /* GMError.IdempotencyMismatch */, `cmd mismatch, expecting ${oldRecord.cmd}, got ${gmRequest.command}`);
1479
+ return;
1480
+ }
1481
+ if (oldRecord.args !== currentRecord.args) {
1482
+ responseError(res, error2httpStatus["idempotency_mismatch" /* GMError.IdempotencyMismatch */], "idempotency_mismatch" /* GMError.IdempotencyMismatch */, `args mismatch, expecting ${oldRecord.args}, got ${currentRecord.args}`);
1483
+ return;
1484
+ }
1485
+ oldResponse = oldRecord.resp;
1486
+ }
1487
+ }
1382
1488
  // 所有错误检查完毕,通知游戏处理函数
1383
1489
  try {
1384
- const result = await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.idempotency_key || "", gmRequest.version);
1490
+ const result = oldResponse || (await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.idempotency_key || "", gmRequest.version));
1491
+ // 记录handler返回的结果以备下次检查使用,setXX出现错误也不再中断请求
1492
+ if (storeHelper && gmRequest.idempotency_key) {
1493
+ currentRecord.resp = result;
1494
+ storeHelper.setXX(gmRequest.idempotency_key, toString(currentRecord)).catch(err => {
1495
+ console.error("failed to setXX idempotency record", err, currentRecord);
1496
+ });
1497
+ }
1385
1498
  // 游戏主动抛错不打印日志信息
1386
1499
  if (result instanceof Error) {
1387
1500
  responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, result.message);
@@ -1419,8 +1532,8 @@ function getGMCommandHandler(config, handler) {
1419
1532
  *
1420
1533
  * https://cloud.tencent.com/developer/ask/sof/110062928
1421
1534
  */
1422
- function getGMHandlerForExpress(config, handler) {
1423
- const func = getGMCommandHandler(config, handler);
1535
+ function getGMHandlerForExpress(config, handler, storeHelper) {
1536
+ const func = getGMCommandHandler(config, handler, storeHelper);
1424
1537
  return async function (req, res) {
1425
1538
  await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1426
1539
  };
@@ -1430,8 +1543,8 @@ function getGMHandlerForExpress(config, handler) {
1430
1543
  *
1431
1544
  * 需要先于 body-parse 等类似插件加载
1432
1545
  */
1433
- function getGMMiddlewareForExpress(paths, config, handler) {
1434
- const func = getGMCommandHandler(config, handler);
1546
+ function getGMMiddlewareForExpress(paths, config, handler, storeHelper) {
1547
+ const func = getGMCommandHandler(config, handler, storeHelper);
1435
1548
  const matchPaths = Array.isArray(paths) ? paths : [paths];
1436
1549
  return async function (req, res, next) {
1437
1550
  if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
@@ -1448,8 +1561,8 @@ function getGMMiddlewareForExpress(paths, config, handler) {
1448
1561
  *
1449
1562
  * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1450
1563
  */
1451
- function getGMHandlerForKoa(config, handler) {
1452
- const func = getGMCommandHandler(config, handler);
1564
+ function getGMHandlerForKoa(config, handler, storeHelper) {
1565
+ const func = getGMCommandHandler(config, handler, storeHelper);
1453
1566
  return async function (ctx) {
1454
1567
  await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1455
1568
  };
@@ -1459,8 +1572,8 @@ function getGMHandlerForKoa(config, handler) {
1459
1572
  *
1460
1573
  * 需要先于 koa-body 等类似插件加载
1461
1574
  */
1462
- function getGMMiddlewareForKoa(paths, config, handler) {
1463
- const func = getGMCommandHandler(config, handler);
1575
+ function getGMMiddlewareForKoa(paths, config, handler, storeHelper) {
1576
+ const func = getGMCommandHandler(config, handler, storeHelper);
1464
1577
  const matchPaths = Array.isArray(paths) ? paths : [paths];
1465
1578
  return async function (ctx, next) {
1466
1579
  if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
@@ -1472,6 +1585,8 @@ function getGMMiddlewareForKoa(paths, config, handler) {
1472
1585
  }
1473
1586
 
1474
1587
  exports.ApiClient = ApiClient;
1588
+ exports.MemoryIdempotencyStore = MemoryIdempotencyStore;
1589
+ exports.RedisIdempotencyStore = RedisIdempotencyStore;
1475
1590
  exports.TokenVerifier = TokenVerifier;
1476
1591
  exports.calcAuthorizationHeader = calcAuthorizationHeader;
1477
1592
  exports.checkHttpAuthInfo = checkHttpAuthInfo;
package/dist/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export { getNotificationHandler, getNotificationHandlerForExpress, getNotificati
8
8
  export { NotificationType } from "./notify/types";
9
9
  export type { NotificationHandler } from "./notify/types";
10
10
  export { getGMCommandHandler, getGMHandlerForExpress, getGMMiddlewareForExpress, getGMHandlerForKoa, getGMMiddlewareForKoa } from "./gm";
11
+ export { RedisIdempotencyStore, MemoryIdempotencyStore } from "./gm/utils";
11
12
  export type { SDKBaseConfig } from "./utils";
12
13
  export { Endpoint, Platform, IdP, GMError } from "./const";
13
14
  export { genSessionID, parseAuthorizationHeader, calcAuthorizationHeader, checkHttpAuthInfo } from "./utils";
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import { verify } from 'jsonwebtoken';
7
7
  /** SDK 名称 */
8
8
  const SDKName = "combo-sdk-node";
9
9
  /** SDK 版本,在编译前会被动态替换 */
10
- const SDKVersion = "1.0.0";
10
+ const SDKVersion = "1.2.0";
11
11
  /**
12
12
  * 世游支持的服务端点列表
13
13
  */
@@ -369,14 +369,18 @@ async function repsonseJson(res, data, statusCode = 200) {
369
369
  res.end();
370
370
  }
371
371
 
372
- /**
373
- * 生成一个 SessionID 以用作用户上下线的上报标记
374
- */
372
+ /** 生成一个 SessionID 以用作用户上下线的上报标记 */
375
373
  function genSessionID(comboId) {
376
374
  const ts = process.hrtime.bigint();
377
375
  const r = Math.random() + Math.random();
378
376
  return createHash("md5").update(`${comboId}${ts}${r}`).digest("hex").toLowerCase();
379
377
  }
378
+ /** 生成一个随机id */
379
+ function genNonceString() {
380
+ const ts = process.hrtime.bigint();
381
+ const r = Math.random() + Math.random();
382
+ return createHash("md5").update(`${ts}${r}`).digest("hex").toLowerCase();
383
+ }
380
384
 
381
385
  const defaultDataField = "data";
382
386
  const defaultMessageField = "message";
@@ -1128,7 +1132,8 @@ class TokenVerifier {
1128
1132
  external_name: payload.external_name,
1129
1133
  weixin_unionid: payload.weixin_unionid || "",
1130
1134
  distro: payload.distro || "",
1131
- variant: payload.variant || ""
1135
+ variant: payload.variant || "",
1136
+ age: payload.age || 0
1132
1137
  };
1133
1138
  } catch (error) {
1134
1139
  return new Error(`IdentityToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
@@ -1320,6 +1325,66 @@ function isGMRequestBody(data) {
1320
1325
  function isGMErrorResponse(data) {
1321
1326
  return isObject(data) && Object.keys(data).length === 2 && "error" in data && "message" in data;
1322
1327
  }
1328
+ function isIdempotencyRecord(data) {
1329
+ return isObject(data) && "key" in data && "id" in data && "cmd" in data && "args" in data;
1330
+ }
1331
+
1332
+ function verifyStoreHelper(storeHelper) {
1333
+ if (storeHelper) {
1334
+ if (typeof storeHelper !== "object" || !("setXX" in storeHelper) || !("setNX" in storeHelper)) {
1335
+ throw new Error("store helper should be { setXX, setNX }");
1336
+ }
1337
+ if (typeof storeHelper.setNX !== "function" || storeHelper.setNX.length !== 2) {
1338
+ throw new Error("store.setNX should be (key, value) => string");
1339
+ }
1340
+ if (typeof storeHelper.setXX !== "function" || storeHelper.setXX.length !== 2) {
1341
+ throw new Error("store.setXX should be (key, value) => void");
1342
+ }
1343
+ }
1344
+ }
1345
+ function toString(data) {
1346
+ return JSON.stringify(data);
1347
+ }
1348
+ /** 提供基于内存的 store helper,仅供本地调试使用,不支持 ttl 超时功能 */
1349
+ class MemoryIdempotencyStore {
1350
+ constructor() {
1351
+ this.mc = void 0;
1352
+ this.mc = {};
1353
+ }
1354
+ async setNX(key, value) {
1355
+ const r = this.mc[key];
1356
+ if (!r) {
1357
+ this.mc[key] = value;
1358
+ return "";
1359
+ }
1360
+ return r;
1361
+ }
1362
+ async setXX(key, value) {
1363
+ const r = this.mc[key];
1364
+ if (r) {
1365
+ this.mc[key] = value;
1366
+ }
1367
+ }
1368
+ }
1369
+ /** 基于 ioredis 的 store helper */
1370
+ class RedisIdempotencyStore {
1371
+ constructor(options) {
1372
+ var _options$ttl;
1373
+ this.client = void 0;
1374
+ this.ttl = void 0;
1375
+ this.prefix = void 0;
1376
+ this.client = options.client;
1377
+ this.ttl = Math.max(24 * 3600, (_options$ttl = options.ttl) != null ? _options$ttl : 0);
1378
+ this.prefix = options.prefix || "";
1379
+ }
1380
+ async setNX(key, value) {
1381
+ return (await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "NX", "GET")) || "";
1382
+ }
1383
+ async setXX(key, value) {
1384
+ await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "XX");
1385
+ }
1386
+ }
1387
+
1323
1388
  const error2httpStatus = {
1324
1389
  ["invalid_http_method" /* GMError.InvalidHttpMethod */]: 405 /* HttpStatus.MethodNotAllowed */,
1325
1390
  ["invalid_content_type" /* GMError.InvalidContentType */]: 415 /* HttpStatus.UnsupportedMediaType */,
@@ -1337,14 +1402,15 @@ const error2httpStatus = {
1337
1402
  ["internal_error" /* GMError.InternalError */]: 500 /* HttpStatus.InternalServerError */
1338
1403
  };
1339
1404
  /**
1340
- * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1405
+ * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知,storeHelper 提供存储支持以实现幂等key(idempotencyKey)的自动化处理
1341
1406
  *
1342
1407
  * 另有 express 和 koa2 版本的处理函数可以使用。
1343
1408
  *
1344
1409
  * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1345
1410
  */
1346
- function getGMCommandHandler(config, handler) {
1411
+ function getGMCommandHandler(config, handler, storeHelper) {
1347
1412
  verifyConfigWithoutEndpoint(config);
1413
+ verifyStoreHelper(storeHelper);
1348
1414
  return async function (req, res, rawBodyString) {
1349
1415
  if (req.method !== "POST") {
1350
1416
  responseError(res, 405 /* HttpStatus.MethodNotAllowed */, "invalid_http_method" /* GMError.InvalidHttpMethod */, `Expecting POST, got ${req.method}`);
@@ -1374,9 +1440,56 @@ function getGMCommandHandler(config, handler) {
1374
1440
  responseError(res, 400 /* HttpStatus.BadRequest */, "invalid_request" /* GMError.InvalidRequest */, `GM request body format error`);
1375
1441
  return;
1376
1442
  }
1443
+ // 处理幂等key
1444
+ const currentRecord = {
1445
+ noce: genNonceString(),
1446
+ key: gmRequest.idempotency_key || "",
1447
+ id: gmRequest.request_id,
1448
+ cmd: gmRequest.command,
1449
+ args: toString(gmRequest.args)
1450
+ };
1451
+ let oldResponse = null;
1452
+ if (storeHelper && gmRequest.idempotency_key) {
1453
+ const oldRecordStr = await storeHelper.setNX(gmRequest.idempotency_key, toString(currentRecord)).catch(e => e instanceof Error ? e : new Error(String(e)));
1454
+ if (oldRecordStr instanceof Error) {
1455
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) setNX error`, oldRecordStr);
1456
+ responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, oldRecordStr.message);
1457
+ return;
1458
+ }
1459
+ const oldRecord = oldRecordStr ? parseJSON(oldRecordStr, isIdempotencyRecord) : null;
1460
+ if (!oldRecord && oldRecordStr) {
1461
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) parse old idempotency record failed: ${oldRecordStr}`);
1462
+ responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, "parse old idempotency record failed");
1463
+ return;
1464
+ }
1465
+ // 检查是否为首次请求
1466
+ const isFirstRequest = oldRecordStr === "" || (oldRecord == null ? void 0 : oldRecord.noce) === currentRecord.noce;
1467
+ if (!isFirstRequest && oldRecord) {
1468
+ if (!oldRecord.resp) {
1469
+ responseError(res, error2httpStatus["idempotency_conflict" /* GMError.IdempotencyConflict */], "idempotency_conflict" /* GMError.IdempotencyConflict */, "previous request is not completed");
1470
+ return;
1471
+ }
1472
+ if (oldRecord.cmd !== gmRequest.command) {
1473
+ responseError(res, error2httpStatus["idempotency_mismatch" /* GMError.IdempotencyMismatch */], "idempotency_mismatch" /* GMError.IdempotencyMismatch */, `cmd mismatch, expecting ${oldRecord.cmd}, got ${gmRequest.command}`);
1474
+ return;
1475
+ }
1476
+ if (oldRecord.args !== currentRecord.args) {
1477
+ responseError(res, error2httpStatus["idempotency_mismatch" /* GMError.IdempotencyMismatch */], "idempotency_mismatch" /* GMError.IdempotencyMismatch */, `args mismatch, expecting ${oldRecord.args}, got ${currentRecord.args}`);
1478
+ return;
1479
+ }
1480
+ oldResponse = oldRecord.resp;
1481
+ }
1482
+ }
1377
1483
  // 所有错误检查完毕,通知游戏处理函数
1378
1484
  try {
1379
- const result = await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.idempotency_key || "", gmRequest.version);
1485
+ const result = oldResponse || (await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.idempotency_key || "", gmRequest.version));
1486
+ // 记录handler返回的结果以备下次检查使用,setXX出现错误也不再中断请求
1487
+ if (storeHelper && gmRequest.idempotency_key) {
1488
+ currentRecord.resp = result;
1489
+ storeHelper.setXX(gmRequest.idempotency_key, toString(currentRecord)).catch(err => {
1490
+ console.error("failed to setXX idempotency record", err, currentRecord);
1491
+ });
1492
+ }
1380
1493
  // 游戏主动抛错不打印日志信息
1381
1494
  if (result instanceof Error) {
1382
1495
  responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, result.message);
@@ -1414,8 +1527,8 @@ function getGMCommandHandler(config, handler) {
1414
1527
  *
1415
1528
  * https://cloud.tencent.com/developer/ask/sof/110062928
1416
1529
  */
1417
- function getGMHandlerForExpress(config, handler) {
1418
- const func = getGMCommandHandler(config, handler);
1530
+ function getGMHandlerForExpress(config, handler, storeHelper) {
1531
+ const func = getGMCommandHandler(config, handler, storeHelper);
1419
1532
  return async function (req, res) {
1420
1533
  await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1421
1534
  };
@@ -1425,8 +1538,8 @@ function getGMHandlerForExpress(config, handler) {
1425
1538
  *
1426
1539
  * 需要先于 body-parse 等类似插件加载
1427
1540
  */
1428
- function getGMMiddlewareForExpress(paths, config, handler) {
1429
- const func = getGMCommandHandler(config, handler);
1541
+ function getGMMiddlewareForExpress(paths, config, handler, storeHelper) {
1542
+ const func = getGMCommandHandler(config, handler, storeHelper);
1430
1543
  const matchPaths = Array.isArray(paths) ? paths : [paths];
1431
1544
  return async function (req, res, next) {
1432
1545
  if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
@@ -1443,8 +1556,8 @@ function getGMMiddlewareForExpress(paths, config, handler) {
1443
1556
  *
1444
1557
  * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1445
1558
  */
1446
- function getGMHandlerForKoa(config, handler) {
1447
- const func = getGMCommandHandler(config, handler);
1559
+ function getGMHandlerForKoa(config, handler, storeHelper) {
1560
+ const func = getGMCommandHandler(config, handler, storeHelper);
1448
1561
  return async function (ctx) {
1449
1562
  await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1450
1563
  };
@@ -1454,8 +1567,8 @@ function getGMHandlerForKoa(config, handler) {
1454
1567
  *
1455
1568
  * 需要先于 koa-body 等类似插件加载
1456
1569
  */
1457
- function getGMMiddlewareForKoa(paths, config, handler) {
1458
- const func = getGMCommandHandler(config, handler);
1570
+ function getGMMiddlewareForKoa(paths, config, handler, storeHelper) {
1571
+ const func = getGMCommandHandler(config, handler, storeHelper);
1459
1572
  const matchPaths = Array.isArray(paths) ? paths : [paths];
1460
1573
  return async function (ctx, next) {
1461
1574
  if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
@@ -1466,4 +1579,4 @@ function getGMMiddlewareForKoa(paths, config, handler) {
1466
1579
  };
1467
1580
  }
1468
1581
 
1469
- export { ApiClient, Endpoint, IdP, Platform, TokenVerifier, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };
1582
+ export { ApiClient, Endpoint, IdP, MemoryIdempotencyStore, Platform, RedisIdempotencyStore, TokenVerifier, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };
@@ -3,7 +3,7 @@ export * from "./types";
3
3
  export * from "./config";
4
4
  export * from "./signer";
5
5
  export * from "./http";
6
- /**
7
- * 生成一个 SessionID 以用作用户上下线的上报标记
8
- */
6
+ /** 生成一个 SessionID 以用作用户上下线的上报标记 */
9
7
  export declare function genSessionID(comboId: string): string;
8
+ /** 生成一个随机id */
9
+ export declare function genNonceString(): string;
@@ -45,9 +45,24 @@ export interface IdentityPayload {
45
45
  * variant 是游戏客户端的分包标识。
46
46
  * 游戏侧可将 variant 用于服务端数据埋点,以及特定的业务逻辑判断。
47
47
  *
48
- * 注意:Variant 只在客户端是分包时才会有值。当客户端不是分包的情况下,variant 为空字符串。
48
+ * 注意:variant 只在客户端是分包时才会有值。当客户端不是分包的情况下,variant 为空字符串。
49
49
  */
50
50
  variant: string;
51
+ /**
52
+ * age 是根据用户的实名认证信息得到的年龄。
53
+ *
54
+ * 0 表示未知。
55
+ *
56
+ * 在某些特殊场景下,游戏侧可用 age 来自行处理防沉迷。
57
+ *
58
+ * 注意:age 不保证返回精确的年龄信息,仅保证用于防沉迷处理时的准确度够用。
59
+ *
60
+ * 例如:
61
+ *
62
+ * 当某个用户真实年龄为 35 岁时,age 可能返回 18,
63
+ * 当某个用户真实年龄为 17 岁时,age 可能返回 16。
64
+ */
65
+ age: number;
51
66
  }
52
67
  export type IdentityJwtPayload = JwtPayload & Omit<IdentityPayload, "combo_id"> & {
53
68
  scope: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-io/combo-sdk-node",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Combo SDK for Node.js",
5
5
  "type": "module",
6
6
  "source": "./src/index.ts",
@@ -50,6 +50,7 @@
50
50
  "eslint": "^8.56.0",
51
51
  "eslint-config-prettier": "^9.1.0",
52
52
  "eslint-plugin-prettier": "^5.1.2",
53
+ "ioredis": "^5.4.1",
53
54
  "lint-staged": "^15.2.0",
54
55
  "microbundle": "^0.15.1",
55
56
  "msw": "^2.0.12",