@seayoo-io/combo-sdk-node 0.2.1 → 0.3.1

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
@@ -7,6 +7,7 @@
7
7
  - 请求 Server REST API 并解析响应
8
8
  - 接收 Server Notifications 并回复响应
9
9
  - 验证世游服务端签发的 Identity Token 和 Ads Token
10
+ - 接收 Server GM Command 指令并回复响应
10
11
 
11
12
  ## 安装
12
13
 
@@ -208,8 +209,8 @@ app.post("/path/to/your/notify/url", expressHandler)
208
209
 
209
210
  // 或,使用 Koa 处理函数
210
211
  import { getNotificationHandlerForKoa } from "@seayoo-io/combo-sdk-node"
211
- const expressHandler = getNotificationHandlerForKoa(config, notificationHandler)
212
- app.post("/path/to/your/notify/url", expressHandler)
212
+ const koaHandler = getNotificationHandlerForKoa(config, notificationHandler)
213
+ app.post("/path/to/your/notify/url", koaHandler)
213
214
  ```
214
215
 
215
216
  > ⚠️ 注意事项
@@ -246,7 +247,7 @@ import { getNotificationMiddlewareForExpress } from "@seayoo-io/combo-sdk-node"
246
247
  const notifyMiddleware = getNotificationMiddlewareForExpress(
247
248
  "/path/to/your/notify/url",
248
249
  config,
249
- handler
250
+ notificationHandler
250
251
  );
251
252
  app.use(notifyMiddleware);
252
253
 
@@ -255,7 +256,7 @@ import { getNotificationMiddlewareForKoa } from "@seayoo-io/combo-sdk-node"
255
256
  const notifyMiddleware = getNotificationMiddlewareForKoa(
256
257
  "/path/to/your/notify/url",
257
258
  config,
258
- handler
259
+ notificationHandler
259
260
  );
260
261
  app.use(notifyMiddleware);
261
262
  ```
@@ -357,4 +358,107 @@ interface AdPayload {
357
358
  /** impression_id 是世游服务端创建的,标识单次广告播放的唯一 ID。*/
358
359
  impression_id: string
359
360
  }
360
- ```
361
+ ```
362
+
363
+ ## GM
364
+
365
+ GM 模块使用方式类似于 Notify 模块。
366
+
367
+ ### Step 1 准备
368
+
369
+ ```js
370
+ import { GMError } from "@seayoo-io/combo-sdk-node"
371
+
372
+ // 1.1 定义 GM 处理函数
373
+ function gmCommandHandler(command, args, requestId, version) {
374
+ // requestId 每次 GM 请求的唯一 ID。游戏侧可用此值来对请求进行去重。
375
+ // version 对应的是世游 GM 服务的版本号,目前固定是 1.0
376
+ // command 对应的是 GM 协议中定义的方法名,区分大小写
377
+ switch(command) {
378
+ case "SomeCmdName":
379
+ // 参数 args 由协议定义,在使用前需要做严格的格式和逻辑校验
380
+ // 返回值需要根据协议定义进行响应,通常是一个包含了多个字段的 object
381
+ return await execSomeCommand(args);
382
+ case "OtherCmdName":
383
+ // 抛出自定义错误有三种方式:
384
+ // 1. 返回一个 Error 对象,最终响应以 500(internalServerError)作为 http status
385
+ return new Error("自定义错误信息")
386
+ // 2. 返回一个自定义消息体 (预设的消息类型见下描述),推荐使用此方式
387
+ return { error: GMError.ThrottleError, message: "请求过于频繁,请稍后再试" }
388
+ // 3. 直接抛出错误,用于处理异常场景,最终响应以 500 作为 http status
389
+ // 相比于方式1,此流程会打印一条错误日志
390
+ throw new Error("some unknown error")
391
+ ...
392
+ default: // 不识别的指令进行返回
393
+ return { error: GMError.InvalidCommand, message: "不识别的指令"+ command }
394
+ }
395
+ }
396
+
397
+ /** GM 预设错误类型枚举 */
398
+ const enum GMError {
399
+ /** 请求的 HTTP 方法不正确。例如,期望收到 POST 请求,但实际收到了 GET 请求。*/
400
+ InvalidHttpMethod = "invalid_http_method",
401
+ /** 请求的 Content-Type 不正确。例如,期望收到 application/json,但实际收到了 text/plain。*/
402
+ InvalidContentType = "invalid_content_type",
403
+ /** 对 HTTP 请求的签名验证不通过。这意味着 HTTP 请求不可信。 */
404
+ InvalidSignature = "invalid_signature",
405
+ /** 请求的结构不正确。例如,缺少必要的字段,或字段类型不正确。 */
406
+ InvalidRequest = "invalid_request",
407
+ /** 游戏侧不认识请求中的 GM 命令。 */
408
+ InvalidCommand = "invalid_command",
409
+ /** GM 命令的参数不正确。例如,缺少必要的字段,或字段类型不正确。 */
410
+ InvalidArgs = "invalid_args",
411
+
412
+ /** 网络通信错误。 */
413
+ NetworkError = "network_error",
414
+ /** 数据库操作异常。 */
415
+ DatabaseError = "database_error",
416
+ /** GM 命令处理超时。 */
417
+ TimeoutError = "timeout_error",
418
+ /** GM 命令发送频率过高,被游戏侧限流,命令未被处理。 */
419
+ ThrottleError = "throttle_error",
420
+ /** 处理 GM 命令时内部出错。可作为通用错误类型。*/
421
+ InternalError = "internal_error",
422
+ }
423
+
424
+ // 1.2 创建配置,相比于 Notify 模块,此处不需要 endpoint 配置
425
+ const config = {
426
+ game: "<GameId>",
427
+ secret: "<SecretKey>",
428
+ }
429
+ ```
430
+
431
+ ### Step 2 绑定处理函数
432
+
433
+ 绑定方式同 Notify 类似,提供三种不同的方式来对接 http 服务。推荐使用方式 3。
434
+
435
+ ```js
436
+ // 方式 1. 使用 http 模块处理函数
437
+ import { getGMCommandHandler } from "@seayoo-io/combo-sdk-node"
438
+ const handler = getGMCommandHandler(config, gmCommandHandler)
439
+ http.createServer(async function(req, res){
440
+ if(req.path === "<YourNotifyUrl>" && req.method === "POST") {
441
+ await handler(req, res)
442
+ }
443
+ })
444
+
445
+ // 方式 2. 使用 express / koa 的 handler
446
+ import { getGMHandlerForExpress } from "@seayoo-io/combo-sdk-node"
447
+ const expressHandler = getGMHandlerForExpress(config, gmCommandHandler)
448
+ app.post("/path/to/your/gm/url", expressHandler)
449
+
450
+ import { getGMHandlerForKoa } from "@seayoo-io/combo-sdk-node"
451
+ const koaHandler = getGMHandlerForKoa(config, gmCommandHandler)
452
+ app.post("/path/to/your/gm/url", koaHandler)
453
+
454
+ // 方式 3. 使用 expres / koa 的中间件,推荐
455
+ import { getGMMiddlewareForExpress } from "@seayoo-io/combo-sdk-node"
456
+ const gmMiddleware = getGMMiddlewareForExpress("/path/to/your/gm/url", config, gmCommandHandler);
457
+ app.use(gmMiddleware);
458
+
459
+ import { getGMMiddlewareForKoa } from "@seayoo-io/combo-sdk-node"
460
+ const gmMiddleware = getGMMiddlewareForKoa("/path/to/your/gm/url", config, gmCommandHandler);
461
+ app.use(gmMiddleware);
462
+
463
+ ```
464
+
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 = "0.2.1";
4
+ export declare const SDKVersion = "0.3.1";
5
5
  /**
6
6
  * 世游支持的服务端点列表
7
7
  */
@@ -41,3 +41,46 @@ export declare enum IdP {
41
41
  /** 微信登录 */
42
42
  Weixin = "weixin"
43
43
  }
44
+ /** GM 错误类型枚举 */
45
+ export declare const enum GMError {
46
+ /** 请求的 HTTP 方法不正确。例如,期望收到 POST 请求,但实际收到了 GET 请求。*/
47
+ InvalidHttpMethod = "invalid_http_method",
48
+ /** 请求的 Content-Type 不正确。例如,期望收到 application/json,但实际收到了 text/plain。*/
49
+ InvalidContentType = "invalid_content_type",
50
+ /** 对 HTTP 请求的签名验证不通过。这意味着 HTTP 请求不可信。 */
51
+ InvalidSignature = "invalid_signature",
52
+ /** 请求的结构不正确。例如,缺少必要的字段,或字段类型不正确。 */
53
+ InvalidRequest = "invalid_request",
54
+ /** 游戏侧不认识请求中的 GM 命令。 */
55
+ InvalidCommand = "invalid_command",
56
+ /** GM 命令的参数不正确。例如,缺少必要的字段,或字段类型不正确。 */
57
+ InvalidArgs = "invalid_args",
58
+ /** 网络通信错误。 */
59
+ NetworkError = "network_error",
60
+ /** 数据库操作异常。 */
61
+ DatabaseError = "database_error",
62
+ /** GM 命令处理超时。 */
63
+ TimeoutError = "timeout_error",
64
+ /** GM 命令发送频率过高,被游戏侧限流,命令未被处理。 */
65
+ ThrottleError = "throttle_error",
66
+ /** 处理 GM 命令时内部出错。可作为通用错误类型。*/
67
+ InternalError = "internal_error"
68
+ }
69
+ export declare const enum HttpStatus {
70
+ OK = 200,
71
+ Accepted = 202,
72
+ NoContent = 204,
73
+ BadRequest = 400,
74
+ Unauthorized = 401,
75
+ Forbidden = 403,
76
+ NotFound = 404,
77
+ MethodNotAllowed = 405,
78
+ NotAcceptable = 406,
79
+ RequestTimeout = 408,
80
+ Conflict = 409,
81
+ UnsupportedMediaType = 415,
82
+ TooManyRequests = 429,
83
+ InternalServerError = 500,
84
+ BadGateway = 502,
85
+ ServiceUnavailable = 503
86
+ }
@@ -0,0 +1,51 @@
1
+ import { type SDKBaseConfig } from "../utils";
2
+ import type { IncomingMessage, ServerResponse } from "http";
3
+ import type { GMCommandHandler } from "./types";
4
+ import type { ParameterizedContext, Next } from "koa";
5
+ import type { Request as ExpressRequest, Response as ExpressResponse, NextFunction as ExpressNextFunction } from "express";
6
+ type SDKMinConfig = Omit<SDKBaseConfig, "endpoint">;
7
+ /**
8
+ * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
9
+ *
10
+ * 另有 express 和 koa2 版本的处理函数可以使用。
11
+ *
12
+ * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
13
+ */
14
+ export declare function getGMCommandHandler(config: SDKMinConfig, handler: GMCommandHandler): (req: IncomingMessage, res: ServerResponse, rawBodyString?: string) => Promise<void>;
15
+ /**
16
+ * 获取基于 express 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
17
+ *
18
+ * 如需自定义处理,可以使用 getGMCommandHandler 方法,
19
+ *
20
+ * 如果 express 使用全局的 bodyParse 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
21
+ *
22
+ * 处理方法可以参考
23
+ *
24
+ * https://cloud.tencent.com/developer/ask/sof/110062928
25
+ */
26
+ export declare function getGMHandlerForExpress(config: SDKMinConfig, handler: GMCommandHandler): (req: ExpressRequest & {
27
+ rawBody?: string;
28
+ }, res: ExpressResponse) => Promise<void>;
29
+ /**
30
+ * 获取基于 express 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
31
+ *
32
+ * 需要先于 body-parse 等类似插件加载
33
+ */
34
+ export declare function getGMMiddlewareForExpress(paths: string | string[], config: SDKMinConfig, handler: GMCommandHandler): (req: ExpressRequest, res: ServerResponse, next: ExpressNextFunction) => Promise<void>;
35
+ /**
36
+ * 获取基于 koa2 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
37
+ *
38
+ * 如需自定义处理,可以使用 getGMCommandHandler 方法
39
+ *
40
+ * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
41
+ */
42
+ export declare function getGMHandlerForKoa(config: SDKMinConfig, handler: GMCommandHandler): (ctx: Pick<ParameterizedContext, "req" | "res"> & {
43
+ rawBody?: string;
44
+ }) => Promise<void>;
45
+ /**
46
+ * 获取基于 koa2 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
47
+ *
48
+ * 需要先于 koa-body 等类似插件加载
49
+ */
50
+ export declare function getGMMiddlewareForKoa(paths: string | string[], config: SDKMinConfig, handler: GMCommandHandler): (ctx: Pick<ParameterizedContext, "method" | "path" | "req" | "res">, next: Next) => Promise<void>;
51
+ export {};
@@ -0,0 +1,16 @@
1
+ import { GMError } from "../const";
2
+ import { MaybePromise } from "../utils";
3
+ export interface GMErrorResponse {
4
+ /** 错误类型。对应内置定义好的 GmError 枚举值 */
5
+ error: GMError;
6
+ /** 错误描述信息。预期是给人看的,便于联调和问题排查。*/
7
+ message: string;
8
+ }
9
+ /**
10
+ * 自定义 GM 执行函数,需要返回执行结果,其结构由协议中对应 rpc 的 Response 定义。
11
+ *
12
+ * 如果遇到错误可以返回错误结构 ({ error, message }) 或 Error 对象
13
+ */
14
+ export type GMCommandHandler = {
15
+ (command: string, args: Record<string, unknown>, requestId: string, version: string): MaybePromise<Record<string, unknown> | GMErrorResponse | Error>;
16
+ };
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 = "0.2.1";
15
+ const SDKVersion = "0.3.1";
16
16
  /**
17
17
  * 世游支持的服务端点列表
18
18
  */
@@ -169,12 +169,18 @@ function getTypeGuard(typeGuard, defaultMessage = "数据未能正确识别") {
169
169
  * 校验通用配置,如果有错误,则直接 throw Error
170
170
  */
171
171
  function verifyConfig(config) {
172
- if (!isObject(config)) {
173
- throw Error("Config Missing");
174
- }
172
+ verifyConfigWithoutEndpoint(config);
175
173
  if (!isFullURL(config.endpoint)) {
176
174
  throw Error(`Config.endpoint Error, Should be url, Preset Values: ${exports.Endpoint.China}, ${exports.Endpoint.Global}}`);
177
175
  }
176
+ }
177
+ /**
178
+ * 校验通用配置,如果有错误,则直接 throw Error
179
+ */
180
+ function verifyConfigWithoutEndpoint(config) {
181
+ if (!isObject(config)) {
182
+ throw Error("Config Missing");
183
+ }
178
184
  if (!config.game) {
179
185
  throw Error(`Config.game Error, Missing Required GameId`);
180
186
  }
@@ -348,6 +354,25 @@ async function done(res, statusCode, message) {
348
354
  }
349
355
  res.end();
350
356
  }
357
+ async function responseError(res, statusCode, error, message) {
358
+ res.statusCode = statusCode;
359
+ if (statusCode !== 204) {
360
+ res.setHeader("Content-Type", "application/json");
361
+ res.write(JSON.stringify({
362
+ error,
363
+ message
364
+ }));
365
+ }
366
+ res.end();
367
+ }
368
+ async function repsonseJson(res, data, statusCode = 200) {
369
+ res.statusCode = statusCode;
370
+ if (statusCode !== 204) {
371
+ res.setHeader("Content-Type", "application/json");
372
+ res.write(JSON.stringify(data));
373
+ }
374
+ res.end();
375
+ }
351
376
 
352
377
  /**
353
378
  * 生成一个 SessionID 以用作用户上下线的上报标记
@@ -1185,12 +1210,12 @@ function getNotificationHandler(config, handler) {
1185
1210
  */
1186
1211
  return async function (req, res, rawBodyString) {
1187
1212
  if (req.method !== "POST") {
1188
- done(res, 405);
1213
+ done(res, 405 /* HttpStatus.MethodNotAllowed */);
1189
1214
  return;
1190
1215
  }
1191
1216
  const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1192
1217
  if (!contentType || !contentType.startsWith("application/json")) {
1193
- done(res, 415);
1218
+ done(res, 415 /* HttpStatus.UnsupportedMediaType */);
1194
1219
  return;
1195
1220
  }
1196
1221
  const authString = req.headers[AuthorizationField] || req.headers[AuthorizationField.toLowerCase()];
@@ -1204,29 +1229,30 @@ function getNotificationHandler(config, handler) {
1204
1229
  url: req.url || "",
1205
1230
  data: body
1206
1231
  })) {
1207
- done(res, 401);
1232
+ done(res, 401 /* HttpStatus.Unauthorized */);
1208
1233
  return;
1209
1234
  }
1210
1235
  const notification = parseJSON(body, isNotificationRequestBody);
1211
1236
  if (!notification) {
1212
- done(res, 400, `Notification body Format Error`);
1237
+ done(res, 400 /* HttpStatus.BadRequest */, `Notification body format error`);
1213
1238
  return;
1214
1239
  }
1215
1240
  const guardCfg = messageDataGuards[notification.notification_type];
1216
1241
  if (!guardCfg) {
1217
- done(res, 400, `Unknown Notification Type: ${notification.notification_type}`);
1242
+ done(res, 400 /* HttpStatus.BadRequest */, `Unknown notification type: ${notification.notification_type}`);
1218
1243
  return;
1219
1244
  }
1220
1245
  if (!guardCfg.guard(notification.data)) {
1221
- done(res, 400, guardCfg.message);
1246
+ done(res, 400 /* HttpStatus.BadRequest */, guardCfg.message);
1222
1247
  return;
1223
1248
  }
1224
1249
  // 所有错误检查完毕,通知游戏处理函数
1225
1250
  try {
1226
1251
  await handler(notification.notification_type, notification.data);
1227
- done(res, 200, "OK");
1252
+ done(res, 200 /* HttpStatus.OK */, "OK");
1228
1253
  } catch (e) {
1229
- done(res, 500, e instanceof Error ? e.message : String(e));
1254
+ console.error(`notify handler error`, e);
1255
+ done(res, 500 /* HttpStatus.InternalServerError */, e instanceof Error ? e.message : String(e));
1230
1256
  }
1231
1257
  };
1232
1258
  }
@@ -1293,11 +1319,165 @@ function getNotificationMiddlewareForKoa(paths, config, handler) {
1293
1319
  };
1294
1320
  }
1295
1321
 
1322
+ function isGMRequestBody(data) {
1323
+ return isObject(data) && "version" in data && "request_id" in data && "command" in data && "args" in data && typeof data.request_id === "string" && typeof data.command === "string" && typeof data.args === "object" && data.args !== null;
1324
+ }
1325
+ function isGMErrorResponse(data) {
1326
+ return isObject(data) && Object.keys(data).length === 2 && "error" in data && "message" in data;
1327
+ }
1328
+ const error2httpStatus = {
1329
+ ["invalid_http_method" /* GMError.InvalidHttpMethod */]: 405 /* HttpStatus.MethodNotAllowed */,
1330
+ ["invalid_content_type" /* GMError.InvalidContentType */]: 415 /* HttpStatus.UnsupportedMediaType */,
1331
+ ["invalid_signature" /* GMError.InvalidSignature */]: 401 /* HttpStatus.Unauthorized */,
1332
+ ["invalid_request" /* GMError.InvalidRequest */]: 400 /* HttpStatus.BadRequest */,
1333
+ ["invalid_command" /* GMError.InvalidCommand */]: 400 /* HttpStatus.BadRequest */,
1334
+ ["invalid_args" /* GMError.InvalidArgs */]: 400 /* HttpStatus.BadRequest */,
1335
+ ["network_error" /* GMError.NetworkError */]: 500 /* HttpStatus.InternalServerError */,
1336
+ ["database_error" /* GMError.DatabaseError */]: 500 /* HttpStatus.InternalServerError */,
1337
+ ["timeout_error" /* GMError.TimeoutError */]: 500 /* HttpStatus.InternalServerError */,
1338
+ ["throttle_error" /* GMError.ThrottleError */]: 429 /* HttpStatus.TooManyRequests */,
1339
+ ["internal_error" /* GMError.InternalError */]: 500 /* HttpStatus.InternalServerError */
1340
+ };
1341
+ /**
1342
+ * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1343
+ *
1344
+ * 另有 express 和 koa2 版本的处理函数可以使用。
1345
+ *
1346
+ * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1347
+ */
1348
+ function getGMCommandHandler(config, handler) {
1349
+ verifyConfigWithoutEndpoint(config);
1350
+ return async function (req, res, rawBodyString) {
1351
+ if (req.method !== "POST") {
1352
+ responseError(res, 405 /* HttpStatus.MethodNotAllowed */, "invalid_http_method" /* GMError.InvalidHttpMethod */, `Expecting POST, got ${req.method}`);
1353
+ return;
1354
+ }
1355
+ const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1356
+ if (!contentType || !contentType.startsWith("application/json")) {
1357
+ responseError(res, 415 /* HttpStatus.UnsupportedMediaType */, "invalid_content_type" /* GMError.InvalidContentType */, `Expecting application/json, got ${contentType}`);
1358
+ return;
1359
+ }
1360
+ const authString = req.headers[AuthorizationField] || req.headers[AuthorizationField.toLowerCase()];
1361
+ const body = await readBody(req, rawBodyString);
1362
+ if (!body || !checkHttpAuthInfo(`${authString}`, {
1363
+ game: config.game,
1364
+ secret: config.secret,
1365
+ method: "POST",
1366
+ // 此处协议不参与计算不需要准确设定
1367
+ endpoint: `http://${req.headers.host}`,
1368
+ url: req.url || "",
1369
+ data: body
1370
+ })) {
1371
+ responseError(res, 401 /* HttpStatus.Unauthorized */, "invalid_signature" /* GMError.InvalidSignature */, "Signature failed");
1372
+ return;
1373
+ }
1374
+ const gmRequest = parseJSON(body, isGMRequestBody);
1375
+ if (!gmRequest) {
1376
+ responseError(res, 400 /* HttpStatus.BadRequest */, "invalid_request" /* GMError.InvalidRequest */, `GM request body format error`);
1377
+ return;
1378
+ }
1379
+ // 所有错误检查完毕,通知游戏处理函数
1380
+ try {
1381
+ const result = await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.version);
1382
+ // 游戏主动抛错不打印日志信息
1383
+ if (result instanceof Error) {
1384
+ responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, result.message);
1385
+ return;
1386
+ }
1387
+ if (isGMErrorResponse(result)) {
1388
+ responseError(res, error2httpStatus[result.error] || 500 /* HttpStatus.InternalServerError */, result.error || "internal_error" /* GMError.InternalError */, result.message);
1389
+ return;
1390
+ }
1391
+ // 对游戏处理函数进一步兼容处理,允许返回一个预定义的错误码
1392
+ // 但此逻辑不作为公开 api,仅作为内容兼容处理
1393
+ if (typeof result === "string" && result in error2httpStatus) {
1394
+ responseError(res, error2httpStatus[result], result, result);
1395
+ return;
1396
+ }
1397
+ // 如果 result 没有结果则进行提示然后继续
1398
+ if (!result) {
1399
+ console.warn(`gm command "${gmRequest.command}" should give back some data`);
1400
+ }
1401
+ repsonseJson(res, result != null ? result : {});
1402
+ } catch (e) {
1403
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}) exec error`, e);
1404
+ responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, e instanceof Error ? e.message : String(e));
1405
+ }
1406
+ };
1407
+ }
1408
+ /**
1409
+ * 获取基于 express 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1410
+ *
1411
+ * 如需自定义处理,可以使用 getGMCommandHandler 方法,
1412
+ *
1413
+ * 如果 express 使用全局的 bodyParse 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1414
+ *
1415
+ * 处理方法可以参考
1416
+ *
1417
+ * https://cloud.tencent.com/developer/ask/sof/110062928
1418
+ */
1419
+ function getGMHandlerForExpress(config, handler) {
1420
+ const func = getGMCommandHandler(config, handler);
1421
+ return async function (req, res) {
1422
+ await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1423
+ };
1424
+ }
1425
+ /**
1426
+ * 获取基于 express 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
1427
+ *
1428
+ * 需要先于 body-parse 等类似插件加载
1429
+ */
1430
+ function getGMMiddlewareForExpress(paths, config, handler) {
1431
+ const func = getGMCommandHandler(config, handler);
1432
+ const matchPaths = Array.isArray(paths) ? paths : [paths];
1433
+ return async function (req, res, next) {
1434
+ if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
1435
+ await func(req, res);
1436
+ return;
1437
+ }
1438
+ next();
1439
+ };
1440
+ }
1441
+ /**
1442
+ * 获取基于 koa2 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1443
+ *
1444
+ * 如需自定义处理,可以使用 getGMCommandHandler 方法
1445
+ *
1446
+ * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1447
+ */
1448
+ function getGMHandlerForKoa(config, handler) {
1449
+ const func = getGMCommandHandler(config, handler);
1450
+ return async function (ctx) {
1451
+ await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1452
+ };
1453
+ }
1454
+ /**
1455
+ * 获取基于 koa2 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
1456
+ *
1457
+ * 需要先于 koa-body 等类似插件加载
1458
+ */
1459
+ function getGMMiddlewareForKoa(paths, config, handler) {
1460
+ const func = getGMCommandHandler(config, handler);
1461
+ const matchPaths = Array.isArray(paths) ? paths : [paths];
1462
+ return async function (ctx, next) {
1463
+ if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
1464
+ await func(ctx.req, ctx.res);
1465
+ return;
1466
+ }
1467
+ await next();
1468
+ };
1469
+ }
1470
+
1296
1471
  exports.ApiClient = ApiClient;
1297
1472
  exports.TokenVerifier = TokenVerifier;
1298
1473
  exports.calcAuthorizationHeader = calcAuthorizationHeader;
1299
1474
  exports.checkHttpAuthInfo = checkHttpAuthInfo;
1300
1475
  exports.genSessionID = genSessionID;
1476
+ exports.getGMCommandHandler = getGMCommandHandler;
1477
+ exports.getGMHandlerForExpress = getGMHandlerForExpress;
1478
+ exports.getGMHandlerForKoa = getGMHandlerForKoa;
1479
+ exports.getGMMiddlewareForExpress = getGMMiddlewareForExpress;
1480
+ exports.getGMMiddlewareForKoa = getGMMiddlewareForKoa;
1301
1481
  exports.getNotificationHandler = getNotificationHandler;
1302
1482
  exports.getNotificationHandlerForExpress = getNotificationHandlerForExpress;
1303
1483
  exports.getNotificationHandlerForKoa = getNotificationHandlerForKoa;
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export type { AdPayload } from "./verify/ads";
7
7
  export { getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, } from "./notify";
8
8
  export { NotificationType } from "./notify/types";
9
9
  export type { NotificationHandler } from "./notify/types";
10
+ export { getGMCommandHandler, getGMHandlerForExpress, getGMMiddlewareForExpress, getGMHandlerForKoa, getGMMiddlewareForKoa } from "./gm";
10
11
  export type { SDKBaseConfig } from "./utils";
11
- export { Endpoint, Platform, IdP } from "./const";
12
+ export { Endpoint, Platform, IdP, GMError } from "./const";
12
13
  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 = "0.2.1";
10
+ const SDKVersion = "0.3.1";
11
11
  /**
12
12
  * 世游支持的服务端点列表
13
13
  */
@@ -164,12 +164,18 @@ function getTypeGuard(typeGuard, defaultMessage = "数据未能正确识别") {
164
164
  * 校验通用配置,如果有错误,则直接 throw Error
165
165
  */
166
166
  function verifyConfig(config) {
167
- if (!isObject(config)) {
168
- throw Error("Config Missing");
169
- }
167
+ verifyConfigWithoutEndpoint(config);
170
168
  if (!isFullURL(config.endpoint)) {
171
169
  throw Error(`Config.endpoint Error, Should be url, Preset Values: ${Endpoint.China}, ${Endpoint.Global}}`);
172
170
  }
171
+ }
172
+ /**
173
+ * 校验通用配置,如果有错误,则直接 throw Error
174
+ */
175
+ function verifyConfigWithoutEndpoint(config) {
176
+ if (!isObject(config)) {
177
+ throw Error("Config Missing");
178
+ }
173
179
  if (!config.game) {
174
180
  throw Error(`Config.game Error, Missing Required GameId`);
175
181
  }
@@ -343,6 +349,25 @@ async function done(res, statusCode, message) {
343
349
  }
344
350
  res.end();
345
351
  }
352
+ async function responseError(res, statusCode, error, message) {
353
+ res.statusCode = statusCode;
354
+ if (statusCode !== 204) {
355
+ res.setHeader("Content-Type", "application/json");
356
+ res.write(JSON.stringify({
357
+ error,
358
+ message
359
+ }));
360
+ }
361
+ res.end();
362
+ }
363
+ async function repsonseJson(res, data, statusCode = 200) {
364
+ res.statusCode = statusCode;
365
+ if (statusCode !== 204) {
366
+ res.setHeader("Content-Type", "application/json");
367
+ res.write(JSON.stringify(data));
368
+ }
369
+ res.end();
370
+ }
346
371
 
347
372
  /**
348
373
  * 生成一个 SessionID 以用作用户上下线的上报标记
@@ -1180,12 +1205,12 @@ function getNotificationHandler(config, handler) {
1180
1205
  */
1181
1206
  return async function (req, res, rawBodyString) {
1182
1207
  if (req.method !== "POST") {
1183
- done(res, 405);
1208
+ done(res, 405 /* HttpStatus.MethodNotAllowed */);
1184
1209
  return;
1185
1210
  }
1186
1211
  const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1187
1212
  if (!contentType || !contentType.startsWith("application/json")) {
1188
- done(res, 415);
1213
+ done(res, 415 /* HttpStatus.UnsupportedMediaType */);
1189
1214
  return;
1190
1215
  }
1191
1216
  const authString = req.headers[AuthorizationField] || req.headers[AuthorizationField.toLowerCase()];
@@ -1199,29 +1224,30 @@ function getNotificationHandler(config, handler) {
1199
1224
  url: req.url || "",
1200
1225
  data: body
1201
1226
  })) {
1202
- done(res, 401);
1227
+ done(res, 401 /* HttpStatus.Unauthorized */);
1203
1228
  return;
1204
1229
  }
1205
1230
  const notification = parseJSON(body, isNotificationRequestBody);
1206
1231
  if (!notification) {
1207
- done(res, 400, `Notification body Format Error`);
1232
+ done(res, 400 /* HttpStatus.BadRequest */, `Notification body format error`);
1208
1233
  return;
1209
1234
  }
1210
1235
  const guardCfg = messageDataGuards[notification.notification_type];
1211
1236
  if (!guardCfg) {
1212
- done(res, 400, `Unknown Notification Type: ${notification.notification_type}`);
1237
+ done(res, 400 /* HttpStatus.BadRequest */, `Unknown notification type: ${notification.notification_type}`);
1213
1238
  return;
1214
1239
  }
1215
1240
  if (!guardCfg.guard(notification.data)) {
1216
- done(res, 400, guardCfg.message);
1241
+ done(res, 400 /* HttpStatus.BadRequest */, guardCfg.message);
1217
1242
  return;
1218
1243
  }
1219
1244
  // 所有错误检查完毕,通知游戏处理函数
1220
1245
  try {
1221
1246
  await handler(notification.notification_type, notification.data);
1222
- done(res, 200, "OK");
1247
+ done(res, 200 /* HttpStatus.OK */, "OK");
1223
1248
  } catch (e) {
1224
- done(res, 500, e instanceof Error ? e.message : String(e));
1249
+ console.error(`notify handler error`, e);
1250
+ done(res, 500 /* HttpStatus.InternalServerError */, e instanceof Error ? e.message : String(e));
1225
1251
  }
1226
1252
  };
1227
1253
  }
@@ -1288,4 +1314,153 @@ function getNotificationMiddlewareForKoa(paths, config, handler) {
1288
1314
  };
1289
1315
  }
1290
1316
 
1291
- export { ApiClient, Endpoint, IdP, Platform, TokenVerifier, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };
1317
+ function isGMRequestBody(data) {
1318
+ return isObject(data) && "version" in data && "request_id" in data && "command" in data && "args" in data && typeof data.request_id === "string" && typeof data.command === "string" && typeof data.args === "object" && data.args !== null;
1319
+ }
1320
+ function isGMErrorResponse(data) {
1321
+ return isObject(data) && Object.keys(data).length === 2 && "error" in data && "message" in data;
1322
+ }
1323
+ const error2httpStatus = {
1324
+ ["invalid_http_method" /* GMError.InvalidHttpMethod */]: 405 /* HttpStatus.MethodNotAllowed */,
1325
+ ["invalid_content_type" /* GMError.InvalidContentType */]: 415 /* HttpStatus.UnsupportedMediaType */,
1326
+ ["invalid_signature" /* GMError.InvalidSignature */]: 401 /* HttpStatus.Unauthorized */,
1327
+ ["invalid_request" /* GMError.InvalidRequest */]: 400 /* HttpStatus.BadRequest */,
1328
+ ["invalid_command" /* GMError.InvalidCommand */]: 400 /* HttpStatus.BadRequest */,
1329
+ ["invalid_args" /* GMError.InvalidArgs */]: 400 /* HttpStatus.BadRequest */,
1330
+ ["network_error" /* GMError.NetworkError */]: 500 /* HttpStatus.InternalServerError */,
1331
+ ["database_error" /* GMError.DatabaseError */]: 500 /* HttpStatus.InternalServerError */,
1332
+ ["timeout_error" /* GMError.TimeoutError */]: 500 /* HttpStatus.InternalServerError */,
1333
+ ["throttle_error" /* GMError.ThrottleError */]: 429 /* HttpStatus.TooManyRequests */,
1334
+ ["internal_error" /* GMError.InternalError */]: 500 /* HttpStatus.InternalServerError */
1335
+ };
1336
+ /**
1337
+ * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1338
+ *
1339
+ * 另有 express 和 koa2 版本的处理函数可以使用。
1340
+ *
1341
+ * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1342
+ */
1343
+ function getGMCommandHandler(config, handler) {
1344
+ verifyConfigWithoutEndpoint(config);
1345
+ return async function (req, res, rawBodyString) {
1346
+ if (req.method !== "POST") {
1347
+ responseError(res, 405 /* HttpStatus.MethodNotAllowed */, "invalid_http_method" /* GMError.InvalidHttpMethod */, `Expecting POST, got ${req.method}`);
1348
+ return;
1349
+ }
1350
+ const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1351
+ if (!contentType || !contentType.startsWith("application/json")) {
1352
+ responseError(res, 415 /* HttpStatus.UnsupportedMediaType */, "invalid_content_type" /* GMError.InvalidContentType */, `Expecting application/json, got ${contentType}`);
1353
+ return;
1354
+ }
1355
+ const authString = req.headers[AuthorizationField] || req.headers[AuthorizationField.toLowerCase()];
1356
+ const body = await readBody(req, rawBodyString);
1357
+ if (!body || !checkHttpAuthInfo(`${authString}`, {
1358
+ game: config.game,
1359
+ secret: config.secret,
1360
+ method: "POST",
1361
+ // 此处协议不参与计算不需要准确设定
1362
+ endpoint: `http://${req.headers.host}`,
1363
+ url: req.url || "",
1364
+ data: body
1365
+ })) {
1366
+ responseError(res, 401 /* HttpStatus.Unauthorized */, "invalid_signature" /* GMError.InvalidSignature */, "Signature failed");
1367
+ return;
1368
+ }
1369
+ const gmRequest = parseJSON(body, isGMRequestBody);
1370
+ if (!gmRequest) {
1371
+ responseError(res, 400 /* HttpStatus.BadRequest */, "invalid_request" /* GMError.InvalidRequest */, `GM request body format error`);
1372
+ return;
1373
+ }
1374
+ // 所有错误检查完毕,通知游戏处理函数
1375
+ try {
1376
+ const result = await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.version);
1377
+ // 游戏主动抛错不打印日志信息
1378
+ if (result instanceof Error) {
1379
+ responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, result.message);
1380
+ return;
1381
+ }
1382
+ if (isGMErrorResponse(result)) {
1383
+ responseError(res, error2httpStatus[result.error] || 500 /* HttpStatus.InternalServerError */, result.error || "internal_error" /* GMError.InternalError */, result.message);
1384
+ return;
1385
+ }
1386
+ // 对游戏处理函数进一步兼容处理,允许返回一个预定义的错误码
1387
+ // 但此逻辑不作为公开 api,仅作为内容兼容处理
1388
+ if (typeof result === "string" && result in error2httpStatus) {
1389
+ responseError(res, error2httpStatus[result], result, result);
1390
+ return;
1391
+ }
1392
+ // 如果 result 没有结果则进行提示然后继续
1393
+ if (!result) {
1394
+ console.warn(`gm command "${gmRequest.command}" should give back some data`);
1395
+ }
1396
+ repsonseJson(res, result != null ? result : {});
1397
+ } catch (e) {
1398
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}) exec error`, e);
1399
+ responseError(res, 500 /* HttpStatus.InternalServerError */, "internal_error" /* GMError.InternalError */, e instanceof Error ? e.message : String(e));
1400
+ }
1401
+ };
1402
+ }
1403
+ /**
1404
+ * 获取基于 express 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1405
+ *
1406
+ * 如需自定义处理,可以使用 getGMCommandHandler 方法,
1407
+ *
1408
+ * 如果 express 使用全局的 bodyParse 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1409
+ *
1410
+ * 处理方法可以参考
1411
+ *
1412
+ * https://cloud.tencent.com/developer/ask/sof/110062928
1413
+ */
1414
+ function getGMHandlerForExpress(config, handler) {
1415
+ const func = getGMCommandHandler(config, handler);
1416
+ return async function (req, res) {
1417
+ await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1418
+ };
1419
+ }
1420
+ /**
1421
+ * 获取基于 express 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
1422
+ *
1423
+ * 需要先于 body-parse 等类似插件加载
1424
+ */
1425
+ function getGMMiddlewareForExpress(paths, config, handler) {
1426
+ const func = getGMCommandHandler(config, handler);
1427
+ const matchPaths = Array.isArray(paths) ? paths : [paths];
1428
+ return async function (req, res, next) {
1429
+ if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
1430
+ await func(req, res);
1431
+ return;
1432
+ }
1433
+ next();
1434
+ };
1435
+ }
1436
+ /**
1437
+ * 获取基于 koa2 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1438
+ *
1439
+ * 如需自定义处理,可以使用 getGMCommandHandler 方法
1440
+ *
1441
+ * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1442
+ */
1443
+ function getGMHandlerForKoa(config, handler) {
1444
+ const func = getGMCommandHandler(config, handler);
1445
+ return async function (ctx) {
1446
+ await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1447
+ };
1448
+ }
1449
+ /**
1450
+ * 获取基于 koa2 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
1451
+ *
1452
+ * 需要先于 koa-body 等类似插件加载
1453
+ */
1454
+ function getGMMiddlewareForKoa(paths, config, handler) {
1455
+ const func = getGMCommandHandler(config, handler);
1456
+ const matchPaths = Array.isArray(paths) ? paths : [paths];
1457
+ return async function (ctx, next) {
1458
+ if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
1459
+ await func(ctx.req, ctx.res);
1460
+ return;
1461
+ }
1462
+ await next();
1463
+ };
1464
+ }
1465
+
1466
+ export { ApiClient, Endpoint, IdP, Platform, TokenVerifier, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };
@@ -27,7 +27,7 @@ export interface ENotificationPayload {
27
27
  [NotificationType.Refund]: RefundNotification;
28
28
  }
29
29
  /**
30
- * 自定义处理函数
30
+ * 自定义通知处理函数
31
31
  *
32
32
  * 每种消息类型对应不同的 payload 以及返回值具体可以查看类型定义
33
33
  */
@@ -11,3 +11,7 @@ export interface SDKBaseConfig {
11
11
  * 校验通用配置,如果有错误,则直接 throw Error
12
12
  */
13
13
  export declare function verifyConfig(config: SDKBaseConfig): void;
14
+ /**
15
+ * 校验通用配置,如果有错误,则直接 throw Error
16
+ */
17
+ export declare function verifyConfigWithoutEndpoint(config: Omit<SDKBaseConfig, "endpoint">): void;
@@ -2,3 +2,5 @@
2
2
  import type { IncomingMessage, ServerResponse } from "http";
3
3
  export declare function readBody(req: IncomingMessage, backup?: string): Promise<string>;
4
4
  export declare function done(res: ServerResponse, statusCode: number, message?: string): Promise<void>;
5
+ export declare function responseError(res: ServerResponse, statusCode: number, error: string, message: string): Promise<void>;
6
+ export declare function repsonseJson(res: ServerResponse, data: unknown, statusCode?: number): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-io/combo-sdk-node",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "Combo SDK for Node.js",
5
5
  "type": "module",
6
6
  "source": "./src/index.ts",