@seayoo-io/combo-sdk-node 1.1.0 → 1.3.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
@@ -9,7 +9,7 @@
9
9
  - 验证世游服务端签发的 Identity Token 和 Ads Token
10
10
  - 接收 Server GM Command 指令并回复响应
11
11
 
12
- ## breaking change
12
+ ## breaking changes
13
13
 
14
14
  v1 新增 gm 模块的 [IdempotencyKey](https://docs.seayoo.com/combo/server/gm/#idempotency),主要改动包括:
15
15
 
@@ -184,6 +184,11 @@ interface ShipOrderNotification {
184
184
  amount: number
185
185
  /** 游戏侧创建订单时提供的订单上下文,透传回游戏 */
186
186
  context?: string
187
+ /**
188
+ * 是否是沙盒订单。沙盒订单意味着此订单并未产生真实的付款。
189
+ * 预期此字段仅用于记录日志和数据埋点。无论是否是沙盒订单,游戏侧都应当发货。
190
+ */
191
+ is_sandbox: boolean
187
192
  }
188
193
 
189
194
  interface RefundNotification {
@@ -299,7 +304,7 @@ if(identityPayload instanceof Error) {
299
304
  // do something
300
305
  }
301
306
  // 游客登录判断
302
- if(identityPayload.idp === IdP.Device) {
307
+ if(identityPayload.idp === IdP.Guest) {
303
308
  // do something
304
309
  }
305
310
  // 更多 IdP 枚举可以查看源码定义 src/const.ts
@@ -331,6 +336,10 @@ interface IdentityPayload {
331
336
  * 注意:weixin_unionid 只在 IdP 为 weixin 时才会有值。
332
337
  */
333
338
  weixin_unionid: string
339
+ /**
340
+ * device_id 是用户在登录时使用的设备的唯一 ID。
341
+ */
342
+ device_id: string
334
343
  /**
335
344
  * distro 是游戏客户端的发行版本标识。
336
345
  * 游戏侧可将 distro 用于服务端数据埋点,以及特定的业务逻辑判断。
@@ -381,6 +390,7 @@ import { GMError } from "@seayoo-io/combo-sdk-node"
381
390
  function gmCommandHandler(command, args, requestId, idempotencyKey, version) {
382
391
  // requestId 本次 GM 请求的唯一 ID。游戏侧可用此值来对请求进行去重。
383
392
  // idempotencyKey 本次 GM 请求的 Idempotency Key。如果有非空值则应当执行幂等处理逻辑。
393
+ // SDK 已经内置了 idempotencyKey 的处理工具和配置,详细见下描述
384
394
  // version 对应的是世游 GM 服务的版本号,目前固定是 2.0
385
395
  // command 对应的是 GM 协议中定义的方法名,区分大小写
386
396
  switch(command) {
@@ -443,14 +453,55 @@ const config = {
443
453
  }
444
454
  ```
445
455
 
446
- ### Step 2 绑定处理函数
456
+ ### Step 2 创建 Store Helper 以启用 idempotencyKey 处理逻辑
457
+
458
+ ```js
459
+ // SDK 内置 idempotencyKey 处理逻辑,其需要相关存储来实现,比如 Redis。
460
+ // 创建 Store Helper 用于启用内置的 idempotencyKey 处理逻辑
461
+ // store helper 需要实现以下方法即可:
462
+ interface IdempotencyKeyStoreHelper {
463
+ /**
464
+ * setNX 用于原子性地存储幂等记录并返回旧值。
465
+ * value 仅在 key 不存在时才会被存储 (Only set the key if it does not already exist)。
466
+ * 返回值是 key 存在时的旧值。如果 key 不存在则返回空字符串。
467
+ */
468
+ setNX: (key: string, value: string) => Promise<string>
469
+
470
+ /**
471
+ * setXX 用于原子性地更新已存在的幂等记录。
472
+ * value 仅在 key 存在时才会被存储 (Only set the key if it already exists)。
473
+ */
474
+ setXX: (key: string, value: string) => Promise<void>
475
+ }
476
+
477
+ // SDK 内置实现了两个工具类
478
+ import { MemoryIdempotencyStore, RedisIdempotencyStore } from "@seayoo-io/combo-sdk-node"
479
+
480
+ // MemoryIdempotencyStore 仅仅用于本地调试
481
+ const storeHelper = new MemoryIdempotencyStore()
482
+ // RedisIdempotencyStore 基于 ioredis 实现,需要 Redis 版本大于 7: https://redis.io/docs/latest/commands/set/
483
+ const storeHelper = new RedisIdempotencyStore({
484
+ /** 超时设定,单位秒,推荐不低于24小时 */
485
+ ttl?: number
486
+ /** ioredis 客户端 */
487
+ client: Redis
488
+ /** key 前缀 */
489
+ prefix?: string
490
+ })
491
+
492
+ // 当然可以直接自行实现上述 store helper 方法
493
+ ```
494
+
495
+ ### Step 3 绑定处理函数
447
496
 
448
497
  绑定方式同 Notify 类似,提供三种不同的方式来对接 http 服务。推荐使用方式 3。
449
498
 
450
499
  ```js
451
500
  // 方式 1. 使用 http 模块处理函数
452
501
  import { getGMCommandHandler } from "@seayoo-io/combo-sdk-node"
453
- const handler = getGMCommandHandler(config, gmCommandHandler)
502
+ // storeHelper 类型为 IdempotencyKeyStoreHelper
503
+ // 可不传递,如果不提供则不会启用内置的 idempotencyKey 处理逻辑,下同
504
+ const handler = getGMCommandHandler(config, gmCommandHandler, storeHelper)
454
505
  http.createServer(async function(req, res){
455
506
  if(req.path === "<YourNotifyUrl>" && req.method === "POST") {
456
507
  await handler(req, res)
@@ -459,20 +510,20 @@ http.createServer(async function(req, res){
459
510
 
460
511
  // 方式 2. 使用 express / koa 的 handler
461
512
  import { getGMHandlerForExpress } from "@seayoo-io/combo-sdk-node"
462
- const expressHandler = getGMHandlerForExpress(config, gmCommandHandler)
513
+ const expressHandler = getGMHandlerForExpress(config, gmCommandHandler, storeHelper)
463
514
  app.post("/path/to/your/gm/url", expressHandler)
464
515
 
465
516
  import { getGMHandlerForKoa } from "@seayoo-io/combo-sdk-node"
466
- const koaHandler = getGMHandlerForKoa(config, gmCommandHandler)
517
+ const koaHandler = getGMHandlerForKoa(config, gmCommandHandler, storeHelper)
467
518
  app.post("/path/to/your/gm/url", koaHandler)
468
519
 
469
520
  // 方式 3. 使用 expres / koa 的中间件,推荐
470
521
  import { getGMMiddlewareForExpress } from "@seayoo-io/combo-sdk-node"
471
- const gmMiddleware = getGMMiddlewareForExpress("/path/to/your/gm/url", config, gmCommandHandler);
522
+ const gmMiddleware = getGMMiddlewareForExpress("/path/to/your/gm/url", config, gmCommandHandler, storeHelper);
472
523
  app.use(gmMiddleware);
473
524
 
474
525
  import { getGMMiddlewareForKoa } from "@seayoo-io/combo-sdk-node"
475
- const gmMiddleware = getGMMiddlewareForKoa("/path/to/your/gm/url", config, gmCommandHandler);
526
+ const gmMiddleware = getGMMiddlewareForKoa("/path/to/your/gm/url", config, gmCommandHandler, storeHelper);
476
527
  app.use(gmMiddleware);
477
528
 
478
529
  ```
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.1.0";
4
+ export declare const SDKVersion = "1.3.0";
5
5
  /**
6
6
  * 世游支持的服务端点列表
7
7
  */
@@ -26,8 +26,8 @@ export declare enum Platform {
26
26
  }
27
27
  /** 支持的登录提供方 */
28
28
  export declare enum IdP {
29
- /** 设备登录(游客) */
30
- Device = "device",
29
+ /** 游客登录 */
30
+ Guest = "guest",
31
31
  /** 世游通行证 */
32
32
  Seayoo = "seayoo",
33
33
  /** Sign-in with Apple */
@@ -39,7 +39,37 @@ export declare enum IdP {
39
39
  /** 小米账号 */
40
40
  Xiaomi = "xiaomi",
41
41
  /** 微信登录 */
42
- Weixin = "weixin"
42
+ Weixin = "weixin",
43
+ /** OPPO 账号 */
44
+ Oppo = "oppo",
45
+ /** VIVO 账号 */
46
+ Vivo = "vivo",
47
+ /** 华为账号 */
48
+ Huawei = "huawei",
49
+ /** 荣耀账号 */
50
+ Honor = "honor",
51
+ /** UC(九游)登录 */
52
+ UC = "uc",
53
+ /** TapTap 登录 */
54
+ TapTap = "taptap",
55
+ /** 哔哩哔哩(B站)账号 */
56
+ Bilibili = "bilibili",
57
+ /** 应用宝 YSDK 登录 */
58
+ Yingyongbao = "yingyongbao",
59
+ /** 4399 账号登录 */
60
+ F4399 = "4399",
61
+ /** 雷电模拟器账号 */
62
+ Leidian = "leidian",
63
+ /** 猫窝游戏 */
64
+ Maowo = "maowo",
65
+ /** 联想 */
66
+ Lenovo = "lenovo",
67
+ /** 魅族 */
68
+ Meizu = "meizu",
69
+ /** 酷派 */
70
+ Coolpad = "coolpad",
71
+ /** 努比亚 */
72
+ Nubia = "nubia"
43
73
  }
44
74
  /** GM 错误类型枚举 */
45
75
  export declare const enum GMError {
@@ -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,31 @@
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
+ /**
13
+ * 基于 ioredis 的 store helper,
14
+ *
15
+ * 需要 Redis >= 7.0,见 https://redis.io/docs/latest/commands/set/
16
+ */
17
+ export declare class RedisIdempotencyStore implements IdempotencyKeyStoreHelper {
18
+ client: Redis;
19
+ ttl: number;
20
+ prefix: string;
21
+ constructor(options: {
22
+ /** 超时设定,单位秒,推荐不低于24小时 */
23
+ ttl?: number;
24
+ /** ioredis 客户端 */
25
+ client: Redis;
26
+ /** key 前缀 */
27
+ prefix?: string;
28
+ });
29
+ setNX(key: string, value: string): Promise<string>;
30
+ setXX(key: string, value: string): Promise<void>;
31
+ }
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.1.0";
15
+ const SDKVersion = "1.3.0";
16
16
  /**
17
17
  * 世游支持的服务端点列表
18
18
  */
@@ -40,8 +40,8 @@ exports.Platform = void 0;
40
40
  /** 支持的登录提供方 */
41
41
  exports.IdP = void 0;
42
42
  (function (IdP) {
43
- /** 设备登录(游客) */
44
- IdP["Device"] = "device";
43
+ /** 游客登录 */
44
+ IdP["Guest"] = "guest";
45
45
  /** 世游通行证 */
46
46
  IdP["Seayoo"] = "seayoo";
47
47
  /** Sign-in with Apple */
@@ -54,6 +54,36 @@ exports.IdP = void 0;
54
54
  IdP["Xiaomi"] = "xiaomi";
55
55
  /** 微信登录 */
56
56
  IdP["Weixin"] = "weixin";
57
+ /** OPPO 账号 */
58
+ IdP["Oppo"] = "oppo";
59
+ /** VIVO 账号 */
60
+ IdP["Vivo"] = "vivo";
61
+ /** 华为账号 */
62
+ IdP["Huawei"] = "huawei";
63
+ /** 荣耀账号 */
64
+ IdP["Honor"] = "honor";
65
+ /** UC(九游)登录 */
66
+ IdP["UC"] = "uc";
67
+ /** TapTap 登录 */
68
+ IdP["TapTap"] = "taptap";
69
+ /** 哔哩哔哩(B站)账号 */
70
+ IdP["Bilibili"] = "bilibili";
71
+ /** 应用宝 YSDK 登录 */
72
+ IdP["Yingyongbao"] = "yingyongbao";
73
+ /** 4399 账号登录 */
74
+ IdP["F4399"] = "4399";
75
+ /** 雷电模拟器账号 */
76
+ IdP["Leidian"] = "leidian";
77
+ /** 猫窝游戏 */
78
+ IdP["Maowo"] = "maowo";
79
+ /** 联想 */
80
+ IdP["Lenovo"] = "lenovo";
81
+ /** 魅族 */
82
+ IdP["Meizu"] = "meizu";
83
+ /** 酷派 */
84
+ IdP["Coolpad"] = "coolpad";
85
+ /** 努比亚 */
86
+ IdP["Nubia"] = "nubia";
57
87
  })(exports.IdP || (exports.IdP = {}));
58
88
 
59
89
  function getUserAgent(game) {
@@ -374,14 +404,18 @@ async function repsonseJson(res, data, statusCode = 200) {
374
404
  res.end();
375
405
  }
376
406
 
377
- /**
378
- * 生成一个 SessionID 以用作用户上下线的上报标记
379
- */
407
+ /** 生成一个 SessionID 以用作用户上下线的上报标记 */
380
408
  function genSessionID(comboId) {
381
409
  const ts = process.hrtime.bigint();
382
410
  const r = Math.random() + Math.random();
383
411
  return crypto.createHash("md5").update(`${comboId}${ts}${r}`).digest("hex").toLowerCase();
384
412
  }
413
+ /** 生成一个随机id */
414
+ function genNonceString() {
415
+ const ts = process.hrtime.bigint();
416
+ const r = Math.random() + Math.random();
417
+ return crypto.createHash("md5").update(`${ts}${r}`).digest("hex").toLowerCase();
418
+ }
385
419
 
386
420
  const defaultDataField = "data";
387
421
  const defaultMessageField = "message";
@@ -1083,7 +1117,7 @@ function isCreateOrderResponse(data) {
1083
1117
  }
1084
1118
 
1085
1119
  function isIdentityJwtPayload(payload) {
1086
- return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "idp" in payload && "external_id" in payload && "external_name" in payload;
1120
+ return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "idp" in payload && "device_id" in payload && "external_id" in payload && "external_name" in payload;
1087
1121
  }
1088
1122
 
1089
1123
  function isAdJwtPayload(payload) {
@@ -1134,6 +1168,7 @@ class TokenVerifier {
1134
1168
  weixin_unionid: payload.weixin_unionid || "",
1135
1169
  distro: payload.distro || "",
1136
1170
  variant: payload.variant || "",
1171
+ device_id: payload.device_id || "",
1137
1172
  age: payload.age || 0
1138
1173
  };
1139
1174
  } catch (error) {
@@ -1169,7 +1204,7 @@ class TokenVerifier {
1169
1204
  }
1170
1205
 
1171
1206
  function isShipOrderPayload(data) {
1172
- return isObject(data) && "order_id" in data && "reference_id" in data && "combo_id" in data && "product_id" in data && "quantity" in data && "currency" in data && "amount" in data && typeof data.order_id === "string" && typeof data.combo_id === "string" && typeof data.quantity === "number" && typeof data.amount === "number" && Number.isSafeInteger(data.quantity) && Number.isSafeInteger(data.amount) && !!data.order_id && !!data.combo_id;
1207
+ return isObject(data) && "order_id" in data && "reference_id" in data && "combo_id" in data && "product_id" in data && "quantity" in data && "currency" in data && "amount" in data && "is_sandbox" in data && typeof data.order_id === "string" && typeof data.combo_id === "string" && typeof data.quantity === "number" && typeof data.amount === "number" && typeof data.is_sandbox === "boolean" && Number.isSafeInteger(data.quantity) && Number.isSafeInteger(data.amount) && !!data.order_id && !!data.combo_id;
1173
1208
  }
1174
1209
 
1175
1210
  function isRefundPayload(data) {
@@ -1326,6 +1361,70 @@ function isGMRequestBody(data) {
1326
1361
  function isGMErrorResponse(data) {
1327
1362
  return isObject(data) && Object.keys(data).length === 2 && "error" in data && "message" in data;
1328
1363
  }
1364
+ function isIdempotencyRecord(data) {
1365
+ return isObject(data) && "key" in data && "id" in data && "cmd" in data && "args" in data;
1366
+ }
1367
+
1368
+ function verifyStoreHelper(storeHelper) {
1369
+ if (storeHelper) {
1370
+ if (typeof storeHelper !== "object" || !("setXX" in storeHelper) || !("setNX" in storeHelper)) {
1371
+ throw new Error("store helper should be { setXX, setNX }");
1372
+ }
1373
+ if (typeof storeHelper.setNX !== "function" || storeHelper.setNX.length !== 2) {
1374
+ throw new Error("store.setNX should be (key, value) => string");
1375
+ }
1376
+ if (typeof storeHelper.setXX !== "function" || storeHelper.setXX.length !== 2) {
1377
+ throw new Error("store.setXX should be (key, value) => void");
1378
+ }
1379
+ }
1380
+ }
1381
+ function toString(data) {
1382
+ return JSON.stringify(data);
1383
+ }
1384
+ /** 提供基于内存的 store helper,仅供本地调试使用,不支持 ttl 超时功能 */
1385
+ class MemoryIdempotencyStore {
1386
+ constructor() {
1387
+ this.mc = void 0;
1388
+ this.mc = {};
1389
+ }
1390
+ async setNX(key, value) {
1391
+ const r = this.mc[key];
1392
+ if (!r) {
1393
+ this.mc[key] = value;
1394
+ return "";
1395
+ }
1396
+ return r;
1397
+ }
1398
+ async setXX(key, value) {
1399
+ const r = this.mc[key];
1400
+ if (r) {
1401
+ this.mc[key] = value;
1402
+ }
1403
+ }
1404
+ }
1405
+ /**
1406
+ * 基于 ioredis 的 store helper,
1407
+ *
1408
+ * 需要 Redis >= 7.0,见 https://redis.io/docs/latest/commands/set/
1409
+ */
1410
+ class RedisIdempotencyStore {
1411
+ constructor(options) {
1412
+ var _options$ttl;
1413
+ this.client = void 0;
1414
+ this.ttl = void 0;
1415
+ this.prefix = void 0;
1416
+ this.client = options.client;
1417
+ this.ttl = Math.max(24 * 3600, (_options$ttl = options.ttl) != null ? _options$ttl : 0);
1418
+ this.prefix = options.prefix || "";
1419
+ }
1420
+ async setNX(key, value) {
1421
+ return (await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "NX", "GET")) || "";
1422
+ }
1423
+ async setXX(key, value) {
1424
+ await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "XX");
1425
+ }
1426
+ }
1427
+
1329
1428
  const error2httpStatus = {
1330
1429
  ["invalid_http_method" /* GMError.InvalidHttpMethod */]: 405 /* HttpStatus.MethodNotAllowed */,
1331
1430
  ["invalid_content_type" /* GMError.InvalidContentType */]: 415 /* HttpStatus.UnsupportedMediaType */,
@@ -1343,14 +1442,15 @@ const error2httpStatus = {
1343
1442
  ["internal_error" /* GMError.InternalError */]: 500 /* HttpStatus.InternalServerError */
1344
1443
  };
1345
1444
  /**
1346
- * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1445
+ * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知,storeHelper 提供存储支持以实现幂等key(idempotencyKey)的自动化处理
1347
1446
  *
1348
1447
  * 另有 express 和 koa2 版本的处理函数可以使用。
1349
1448
  *
1350
1449
  * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1351
1450
  */
1352
- function getGMCommandHandler(config, handler) {
1451
+ function getGMCommandHandler(config, handler, storeHelper) {
1353
1452
  verifyConfigWithoutEndpoint(config);
1453
+ verifyStoreHelper(storeHelper);
1354
1454
  return async function (req, res, rawBodyString) {
1355
1455
  if (req.method !== "POST") {
1356
1456
  responseError(res, 405 /* HttpStatus.MethodNotAllowed */, "invalid_http_method" /* GMError.InvalidHttpMethod */, `Expecting POST, got ${req.method}`);
@@ -1380,9 +1480,56 @@ function getGMCommandHandler(config, handler) {
1380
1480
  responseError(res, 400 /* HttpStatus.BadRequest */, "invalid_request" /* GMError.InvalidRequest */, `GM request body format error`);
1381
1481
  return;
1382
1482
  }
1483
+ // 处理幂等key
1484
+ const currentRecord = {
1485
+ noce: genNonceString(),
1486
+ key: gmRequest.idempotency_key || "",
1487
+ id: gmRequest.request_id,
1488
+ cmd: gmRequest.command,
1489
+ args: toString(gmRequest.args)
1490
+ };
1491
+ let oldResponse = null;
1492
+ if (storeHelper && gmRequest.idempotency_key) {
1493
+ const oldRecordStr = await storeHelper.setNX(gmRequest.idempotency_key, toString(currentRecord)).catch(e => e instanceof Error ? e : new Error(String(e)));
1494
+ if (oldRecordStr instanceof Error) {
1495
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) setNX error`, oldRecordStr);
1496
+ responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, oldRecordStr.message);
1497
+ return;
1498
+ }
1499
+ const oldRecord = oldRecordStr ? parseJSON(oldRecordStr, isIdempotencyRecord) : null;
1500
+ if (!oldRecord && oldRecordStr) {
1501
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) parse old idempotency record failed: ${oldRecordStr}`);
1502
+ responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, "parse old idempotency record failed");
1503
+ return;
1504
+ }
1505
+ // 检查是否为首次请求
1506
+ const isFirstRequest = oldRecordStr === "" || (oldRecord == null ? void 0 : oldRecord.noce) === currentRecord.noce;
1507
+ if (!isFirstRequest && oldRecord) {
1508
+ if (!oldRecord.resp) {
1509
+ responseError(res, error2httpStatus["idempotency_conflict" /* GMError.IdempotencyConflict */], "idempotency_conflict" /* GMError.IdempotencyConflict */, "previous request is not completed");
1510
+ return;
1511
+ }
1512
+ if (oldRecord.cmd !== gmRequest.command) {
1513
+ responseError(res, error2httpStatus["idempotency_mismatch" /* GMError.IdempotencyMismatch */], "idempotency_mismatch" /* GMError.IdempotencyMismatch */, `cmd mismatch, expecting ${oldRecord.cmd}, got ${gmRequest.command}`);
1514
+ return;
1515
+ }
1516
+ if (oldRecord.args !== currentRecord.args) {
1517
+ responseError(res, error2httpStatus["idempotency_mismatch" /* GMError.IdempotencyMismatch */], "idempotency_mismatch" /* GMError.IdempotencyMismatch */, `args mismatch, expecting ${oldRecord.args}, got ${currentRecord.args}`);
1518
+ return;
1519
+ }
1520
+ oldResponse = oldRecord.resp;
1521
+ }
1522
+ }
1383
1523
  // 所有错误检查完毕,通知游戏处理函数
1384
1524
  try {
1385
- const result = await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.idempotency_key || "", gmRequest.version);
1525
+ const result = oldResponse || (await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.idempotency_key || "", gmRequest.version));
1526
+ // 记录handler返回的结果以备下次检查使用,setXX出现错误也不再中断请求
1527
+ if (storeHelper && gmRequest.idempotency_key) {
1528
+ currentRecord.resp = result;
1529
+ storeHelper.setXX(gmRequest.idempotency_key, toString(currentRecord)).catch(err => {
1530
+ console.error("failed to setXX idempotency record", err, currentRecord);
1531
+ });
1532
+ }
1386
1533
  // 游戏主动抛错不打印日志信息
1387
1534
  if (result instanceof Error) {
1388
1535
  responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, result.message);
@@ -1420,8 +1567,8 @@ function getGMCommandHandler(config, handler) {
1420
1567
  *
1421
1568
  * https://cloud.tencent.com/developer/ask/sof/110062928
1422
1569
  */
1423
- function getGMHandlerForExpress(config, handler) {
1424
- const func = getGMCommandHandler(config, handler);
1570
+ function getGMHandlerForExpress(config, handler, storeHelper) {
1571
+ const func = getGMCommandHandler(config, handler, storeHelper);
1425
1572
  return async function (req, res) {
1426
1573
  await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1427
1574
  };
@@ -1431,8 +1578,8 @@ function getGMHandlerForExpress(config, handler) {
1431
1578
  *
1432
1579
  * 需要先于 body-parse 等类似插件加载
1433
1580
  */
1434
- function getGMMiddlewareForExpress(paths, config, handler) {
1435
- const func = getGMCommandHandler(config, handler);
1581
+ function getGMMiddlewareForExpress(paths, config, handler, storeHelper) {
1582
+ const func = getGMCommandHandler(config, handler, storeHelper);
1436
1583
  const matchPaths = Array.isArray(paths) ? paths : [paths];
1437
1584
  return async function (req, res, next) {
1438
1585
  if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
@@ -1449,8 +1596,8 @@ function getGMMiddlewareForExpress(paths, config, handler) {
1449
1596
  *
1450
1597
  * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1451
1598
  */
1452
- function getGMHandlerForKoa(config, handler) {
1453
- const func = getGMCommandHandler(config, handler);
1599
+ function getGMHandlerForKoa(config, handler, storeHelper) {
1600
+ const func = getGMCommandHandler(config, handler, storeHelper);
1454
1601
  return async function (ctx) {
1455
1602
  await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1456
1603
  };
@@ -1460,8 +1607,8 @@ function getGMHandlerForKoa(config, handler) {
1460
1607
  *
1461
1608
  * 需要先于 koa-body 等类似插件加载
1462
1609
  */
1463
- function getGMMiddlewareForKoa(paths, config, handler) {
1464
- const func = getGMCommandHandler(config, handler);
1610
+ function getGMMiddlewareForKoa(paths, config, handler, storeHelper) {
1611
+ const func = getGMCommandHandler(config, handler, storeHelper);
1465
1612
  const matchPaths = Array.isArray(paths) ? paths : [paths];
1466
1613
  return async function (ctx, next) {
1467
1614
  if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
@@ -1473,6 +1620,8 @@ function getGMMiddlewareForKoa(paths, config, handler) {
1473
1620
  }
1474
1621
 
1475
1622
  exports.ApiClient = ApiClient;
1623
+ exports.MemoryIdempotencyStore = MemoryIdempotencyStore;
1624
+ exports.RedisIdempotencyStore = RedisIdempotencyStore;
1476
1625
  exports.TokenVerifier = TokenVerifier;
1477
1626
  exports.calcAuthorizationHeader = calcAuthorizationHeader;
1478
1627
  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.1.0";
10
+ const SDKVersion = "1.3.0";
11
11
  /**
12
12
  * 世游支持的服务端点列表
13
13
  */
@@ -35,8 +35,8 @@ var Platform;
35
35
  /** 支持的登录提供方 */
36
36
  var IdP;
37
37
  (function (IdP) {
38
- /** 设备登录(游客) */
39
- IdP["Device"] = "device";
38
+ /** 游客登录 */
39
+ IdP["Guest"] = "guest";
40
40
  /** 世游通行证 */
41
41
  IdP["Seayoo"] = "seayoo";
42
42
  /** Sign-in with Apple */
@@ -49,6 +49,36 @@ var IdP;
49
49
  IdP["Xiaomi"] = "xiaomi";
50
50
  /** 微信登录 */
51
51
  IdP["Weixin"] = "weixin";
52
+ /** OPPO 账号 */
53
+ IdP["Oppo"] = "oppo";
54
+ /** VIVO 账号 */
55
+ IdP["Vivo"] = "vivo";
56
+ /** 华为账号 */
57
+ IdP["Huawei"] = "huawei";
58
+ /** 荣耀账号 */
59
+ IdP["Honor"] = "honor";
60
+ /** UC(九游)登录 */
61
+ IdP["UC"] = "uc";
62
+ /** TapTap 登录 */
63
+ IdP["TapTap"] = "taptap";
64
+ /** 哔哩哔哩(B站)账号 */
65
+ IdP["Bilibili"] = "bilibili";
66
+ /** 应用宝 YSDK 登录 */
67
+ IdP["Yingyongbao"] = "yingyongbao";
68
+ /** 4399 账号登录 */
69
+ IdP["F4399"] = "4399";
70
+ /** 雷电模拟器账号 */
71
+ IdP["Leidian"] = "leidian";
72
+ /** 猫窝游戏 */
73
+ IdP["Maowo"] = "maowo";
74
+ /** 联想 */
75
+ IdP["Lenovo"] = "lenovo";
76
+ /** 魅族 */
77
+ IdP["Meizu"] = "meizu";
78
+ /** 酷派 */
79
+ IdP["Coolpad"] = "coolpad";
80
+ /** 努比亚 */
81
+ IdP["Nubia"] = "nubia";
52
82
  })(IdP || (IdP = {}));
53
83
 
54
84
  function getUserAgent(game) {
@@ -369,14 +399,18 @@ async function repsonseJson(res, data, statusCode = 200) {
369
399
  res.end();
370
400
  }
371
401
 
372
- /**
373
- * 生成一个 SessionID 以用作用户上下线的上报标记
374
- */
402
+ /** 生成一个 SessionID 以用作用户上下线的上报标记 */
375
403
  function genSessionID(comboId) {
376
404
  const ts = process.hrtime.bigint();
377
405
  const r = Math.random() + Math.random();
378
406
  return createHash("md5").update(`${comboId}${ts}${r}`).digest("hex").toLowerCase();
379
407
  }
408
+ /** 生成一个随机id */
409
+ function genNonceString() {
410
+ const ts = process.hrtime.bigint();
411
+ const r = Math.random() + Math.random();
412
+ return createHash("md5").update(`${ts}${r}`).digest("hex").toLowerCase();
413
+ }
380
414
 
381
415
  const defaultDataField = "data";
382
416
  const defaultMessageField = "message";
@@ -1078,7 +1112,7 @@ function isCreateOrderResponse(data) {
1078
1112
  }
1079
1113
 
1080
1114
  function isIdentityJwtPayload(payload) {
1081
- return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "idp" in payload && "external_id" in payload && "external_name" in payload;
1115
+ return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "idp" in payload && "device_id" in payload && "external_id" in payload && "external_name" in payload;
1082
1116
  }
1083
1117
 
1084
1118
  function isAdJwtPayload(payload) {
@@ -1129,6 +1163,7 @@ class TokenVerifier {
1129
1163
  weixin_unionid: payload.weixin_unionid || "",
1130
1164
  distro: payload.distro || "",
1131
1165
  variant: payload.variant || "",
1166
+ device_id: payload.device_id || "",
1132
1167
  age: payload.age || 0
1133
1168
  };
1134
1169
  } catch (error) {
@@ -1164,7 +1199,7 @@ class TokenVerifier {
1164
1199
  }
1165
1200
 
1166
1201
  function isShipOrderPayload(data) {
1167
- return isObject(data) && "order_id" in data && "reference_id" in data && "combo_id" in data && "product_id" in data && "quantity" in data && "currency" in data && "amount" in data && typeof data.order_id === "string" && typeof data.combo_id === "string" && typeof data.quantity === "number" && typeof data.amount === "number" && Number.isSafeInteger(data.quantity) && Number.isSafeInteger(data.amount) && !!data.order_id && !!data.combo_id;
1202
+ return isObject(data) && "order_id" in data && "reference_id" in data && "combo_id" in data && "product_id" in data && "quantity" in data && "currency" in data && "amount" in data && "is_sandbox" in data && typeof data.order_id === "string" && typeof data.combo_id === "string" && typeof data.quantity === "number" && typeof data.amount === "number" && typeof data.is_sandbox === "boolean" && Number.isSafeInteger(data.quantity) && Number.isSafeInteger(data.amount) && !!data.order_id && !!data.combo_id;
1168
1203
  }
1169
1204
 
1170
1205
  function isRefundPayload(data) {
@@ -1321,6 +1356,70 @@ function isGMRequestBody(data) {
1321
1356
  function isGMErrorResponse(data) {
1322
1357
  return isObject(data) && Object.keys(data).length === 2 && "error" in data && "message" in data;
1323
1358
  }
1359
+ function isIdempotencyRecord(data) {
1360
+ return isObject(data) && "key" in data && "id" in data && "cmd" in data && "args" in data;
1361
+ }
1362
+
1363
+ function verifyStoreHelper(storeHelper) {
1364
+ if (storeHelper) {
1365
+ if (typeof storeHelper !== "object" || !("setXX" in storeHelper) || !("setNX" in storeHelper)) {
1366
+ throw new Error("store helper should be { setXX, setNX }");
1367
+ }
1368
+ if (typeof storeHelper.setNX !== "function" || storeHelper.setNX.length !== 2) {
1369
+ throw new Error("store.setNX should be (key, value) => string");
1370
+ }
1371
+ if (typeof storeHelper.setXX !== "function" || storeHelper.setXX.length !== 2) {
1372
+ throw new Error("store.setXX should be (key, value) => void");
1373
+ }
1374
+ }
1375
+ }
1376
+ function toString(data) {
1377
+ return JSON.stringify(data);
1378
+ }
1379
+ /** 提供基于内存的 store helper,仅供本地调试使用,不支持 ttl 超时功能 */
1380
+ class MemoryIdempotencyStore {
1381
+ constructor() {
1382
+ this.mc = void 0;
1383
+ this.mc = {};
1384
+ }
1385
+ async setNX(key, value) {
1386
+ const r = this.mc[key];
1387
+ if (!r) {
1388
+ this.mc[key] = value;
1389
+ return "";
1390
+ }
1391
+ return r;
1392
+ }
1393
+ async setXX(key, value) {
1394
+ const r = this.mc[key];
1395
+ if (r) {
1396
+ this.mc[key] = value;
1397
+ }
1398
+ }
1399
+ }
1400
+ /**
1401
+ * 基于 ioredis 的 store helper,
1402
+ *
1403
+ * 需要 Redis >= 7.0,见 https://redis.io/docs/latest/commands/set/
1404
+ */
1405
+ class RedisIdempotencyStore {
1406
+ constructor(options) {
1407
+ var _options$ttl;
1408
+ this.client = void 0;
1409
+ this.ttl = void 0;
1410
+ this.prefix = void 0;
1411
+ this.client = options.client;
1412
+ this.ttl = Math.max(24 * 3600, (_options$ttl = options.ttl) != null ? _options$ttl : 0);
1413
+ this.prefix = options.prefix || "";
1414
+ }
1415
+ async setNX(key, value) {
1416
+ return (await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "NX", "GET")) || "";
1417
+ }
1418
+ async setXX(key, value) {
1419
+ await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "XX");
1420
+ }
1421
+ }
1422
+
1324
1423
  const error2httpStatus = {
1325
1424
  ["invalid_http_method" /* GMError.InvalidHttpMethod */]: 405 /* HttpStatus.MethodNotAllowed */,
1326
1425
  ["invalid_content_type" /* GMError.InvalidContentType */]: 415 /* HttpStatus.UnsupportedMediaType */,
@@ -1338,14 +1437,15 @@ const error2httpStatus = {
1338
1437
  ["internal_error" /* GMError.InternalError */]: 500 /* HttpStatus.InternalServerError */
1339
1438
  };
1340
1439
  /**
1341
- * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1440
+ * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知,storeHelper 提供存储支持以实现幂等key(idempotencyKey)的自动化处理
1342
1441
  *
1343
1442
  * 另有 express 和 koa2 版本的处理函数可以使用。
1344
1443
  *
1345
1444
  * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1346
1445
  */
1347
- function getGMCommandHandler(config, handler) {
1446
+ function getGMCommandHandler(config, handler, storeHelper) {
1348
1447
  verifyConfigWithoutEndpoint(config);
1448
+ verifyStoreHelper(storeHelper);
1349
1449
  return async function (req, res, rawBodyString) {
1350
1450
  if (req.method !== "POST") {
1351
1451
  responseError(res, 405 /* HttpStatus.MethodNotAllowed */, "invalid_http_method" /* GMError.InvalidHttpMethod */, `Expecting POST, got ${req.method}`);
@@ -1375,9 +1475,56 @@ function getGMCommandHandler(config, handler) {
1375
1475
  responseError(res, 400 /* HttpStatus.BadRequest */, "invalid_request" /* GMError.InvalidRequest */, `GM request body format error`);
1376
1476
  return;
1377
1477
  }
1478
+ // 处理幂等key
1479
+ const currentRecord = {
1480
+ noce: genNonceString(),
1481
+ key: gmRequest.idempotency_key || "",
1482
+ id: gmRequest.request_id,
1483
+ cmd: gmRequest.command,
1484
+ args: toString(gmRequest.args)
1485
+ };
1486
+ let oldResponse = null;
1487
+ if (storeHelper && gmRequest.idempotency_key) {
1488
+ const oldRecordStr = await storeHelper.setNX(gmRequest.idempotency_key, toString(currentRecord)).catch(e => e instanceof Error ? e : new Error(String(e)));
1489
+ if (oldRecordStr instanceof Error) {
1490
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) setNX error`, oldRecordStr);
1491
+ responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, oldRecordStr.message);
1492
+ return;
1493
+ }
1494
+ const oldRecord = oldRecordStr ? parseJSON(oldRecordStr, isIdempotencyRecord) : null;
1495
+ if (!oldRecord && oldRecordStr) {
1496
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) parse old idempotency record failed: ${oldRecordStr}`);
1497
+ responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, "parse old idempotency record failed");
1498
+ return;
1499
+ }
1500
+ // 检查是否为首次请求
1501
+ const isFirstRequest = oldRecordStr === "" || (oldRecord == null ? void 0 : oldRecord.noce) === currentRecord.noce;
1502
+ if (!isFirstRequest && oldRecord) {
1503
+ if (!oldRecord.resp) {
1504
+ responseError(res, error2httpStatus["idempotency_conflict" /* GMError.IdempotencyConflict */], "idempotency_conflict" /* GMError.IdempotencyConflict */, "previous request is not completed");
1505
+ return;
1506
+ }
1507
+ if (oldRecord.cmd !== gmRequest.command) {
1508
+ responseError(res, error2httpStatus["idempotency_mismatch" /* GMError.IdempotencyMismatch */], "idempotency_mismatch" /* GMError.IdempotencyMismatch */, `cmd mismatch, expecting ${oldRecord.cmd}, got ${gmRequest.command}`);
1509
+ return;
1510
+ }
1511
+ if (oldRecord.args !== currentRecord.args) {
1512
+ responseError(res, error2httpStatus["idempotency_mismatch" /* GMError.IdempotencyMismatch */], "idempotency_mismatch" /* GMError.IdempotencyMismatch */, `args mismatch, expecting ${oldRecord.args}, got ${currentRecord.args}`);
1513
+ return;
1514
+ }
1515
+ oldResponse = oldRecord.resp;
1516
+ }
1517
+ }
1378
1518
  // 所有错误检查完毕,通知游戏处理函数
1379
1519
  try {
1380
- const result = await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.idempotency_key || "", gmRequest.version);
1520
+ const result = oldResponse || (await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.idempotency_key || "", gmRequest.version));
1521
+ // 记录handler返回的结果以备下次检查使用,setXX出现错误也不再中断请求
1522
+ if (storeHelper && gmRequest.idempotency_key) {
1523
+ currentRecord.resp = result;
1524
+ storeHelper.setXX(gmRequest.idempotency_key, toString(currentRecord)).catch(err => {
1525
+ console.error("failed to setXX idempotency record", err, currentRecord);
1526
+ });
1527
+ }
1381
1528
  // 游戏主动抛错不打印日志信息
1382
1529
  if (result instanceof Error) {
1383
1530
  responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, result.message);
@@ -1415,8 +1562,8 @@ function getGMCommandHandler(config, handler) {
1415
1562
  *
1416
1563
  * https://cloud.tencent.com/developer/ask/sof/110062928
1417
1564
  */
1418
- function getGMHandlerForExpress(config, handler) {
1419
- const func = getGMCommandHandler(config, handler);
1565
+ function getGMHandlerForExpress(config, handler, storeHelper) {
1566
+ const func = getGMCommandHandler(config, handler, storeHelper);
1420
1567
  return async function (req, res) {
1421
1568
  await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1422
1569
  };
@@ -1426,8 +1573,8 @@ function getGMHandlerForExpress(config, handler) {
1426
1573
  *
1427
1574
  * 需要先于 body-parse 等类似插件加载
1428
1575
  */
1429
- function getGMMiddlewareForExpress(paths, config, handler) {
1430
- const func = getGMCommandHandler(config, handler);
1576
+ function getGMMiddlewareForExpress(paths, config, handler, storeHelper) {
1577
+ const func = getGMCommandHandler(config, handler, storeHelper);
1431
1578
  const matchPaths = Array.isArray(paths) ? paths : [paths];
1432
1579
  return async function (req, res, next) {
1433
1580
  if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
@@ -1444,8 +1591,8 @@ function getGMMiddlewareForExpress(paths, config, handler) {
1444
1591
  *
1445
1592
  * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1446
1593
  */
1447
- function getGMHandlerForKoa(config, handler) {
1448
- const func = getGMCommandHandler(config, handler);
1594
+ function getGMHandlerForKoa(config, handler, storeHelper) {
1595
+ const func = getGMCommandHandler(config, handler, storeHelper);
1449
1596
  return async function (ctx) {
1450
1597
  await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1451
1598
  };
@@ -1455,8 +1602,8 @@ function getGMHandlerForKoa(config, handler) {
1455
1602
  *
1456
1603
  * 需要先于 koa-body 等类似插件加载
1457
1604
  */
1458
- function getGMMiddlewareForKoa(paths, config, handler) {
1459
- const func = getGMCommandHandler(config, handler);
1605
+ function getGMMiddlewareForKoa(paths, config, handler, storeHelper) {
1606
+ const func = getGMCommandHandler(config, handler, storeHelper);
1460
1607
  const matchPaths = Array.isArray(paths) ? paths : [paths];
1461
1608
  return async function (ctx, next) {
1462
1609
  if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
@@ -1467,4 +1614,4 @@ function getGMMiddlewareForKoa(paths, config, handler) {
1467
1614
  };
1468
1615
  }
1469
1616
 
1470
- export { ApiClient, Endpoint, IdP, Platform, TokenVerifier, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };
1617
+ export { ApiClient, Endpoint, IdP, MemoryIdempotencyStore, Platform, RedisIdempotencyStore, TokenVerifier, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };
@@ -16,5 +16,11 @@ export interface ShipOrderNotification {
16
16
  amount: number;
17
17
  /** 游戏侧创建订单时提供的订单上下文,透传回游戏 */
18
18
  context?: string;
19
+ /**
20
+ * 是否是沙盒订单。沙盒订单意味着此订单并未产生真实的付款。
21
+ *
22
+ * 预期此字段仅用于记录日志和数据埋点。无论是否是沙盒订单,游戏侧都应当发货。
23
+ */
24
+ is_sandbox: boolean;
19
25
  }
20
26
  export declare function isShipOrderPayload(data: unknown): data is ShipOrderNotification;
@@ -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;
@@ -4,7 +4,7 @@ export interface IdentityPayload {
4
4
  /**
5
5
  * combo_id 是世游分配的聚合用户 ID
6
6
  *
7
- * 游戏侧应当使用 combo_id 作为用户的唯一标识。
7
+ * 游戏侧应当使用 combo_id 作为用户的唯一标识,即游戏帐号。
8
8
  */
9
9
  combo_id: string;
10
10
  /**
@@ -36,6 +36,10 @@ export interface IdentityPayload {
36
36
  * 注意:weixin_unionid 只在 IdP 为 weixin 时才会有值。
37
37
  */
38
38
  weixin_unionid: string;
39
+ /**
40
+ * DeviceId 是用户在登录时使用的设备的唯一 ID。
41
+ */
42
+ device_id: string;
39
43
  /**
40
44
  * distro 是游戏客户端的发行版本标识。
41
45
  * 游戏侧可将 distro 用于服务端数据埋点,以及特定的业务逻辑判断。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-io/combo-sdk-node",
3
- "version": "1.1.0",
3
+ "version": "1.3.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",