@midwayjs/ws 3.20.8 → 3.20.10

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.
@@ -2,11 +2,12 @@
2
2
  /// <reference types="node" />
3
3
  import { BaseFramework, CommonMiddlewareUnion, ContextMiddlewareManager, IMidwayBootstrapOptions, MidwayFrameworkType } from '@midwayjs/core';
4
4
  import * as http from 'http';
5
- import { Application, Context, IMidwayWSApplication, IMidwayWSConfigurationOptions, NextFunction } from './interface';
5
+ import { Application, Context, IMidwayWSApplication, IMidwayWSConfigurationOptions, NextFunction, UpgradeAuthHandler } from './interface';
6
6
  export declare class MidwayWSFramework extends BaseFramework<Application, Context, IMidwayWSConfigurationOptions> {
7
7
  server: http.Server;
8
8
  protected heartBeatInterval: NodeJS.Timeout;
9
9
  protected connectionMiddlewareManager: ContextMiddlewareManager<Context, unknown, unknown>;
10
+ protected upgradeAuthHandler: UpgradeAuthHandler | null;
10
11
  configure(): IMidwayWSConfigurationOptions;
11
12
  applicationInitialize(options: IMidwayBootstrapOptions): void;
12
13
  app: IMidwayWSApplication;
@@ -14,6 +15,11 @@ export declare class MidwayWSFramework extends BaseFramework<Application, Contex
14
15
  run(): Promise<void>;
15
16
  protected beforeStop(): Promise<void>;
16
17
  getFrameworkType(): MidwayFrameworkType;
18
+ /**
19
+ * 设置升级前鉴权处理函数
20
+ * @param handler 鉴权处理函数,传入 null 可以禁用鉴权
21
+ */
22
+ onWebSocketUpgrade(handler: UpgradeAuthHandler | null): void;
17
23
  private loadMidwayController;
18
24
  private addNamespace;
19
25
  private bindSocketResponse;
package/dist/framework.js CHANGED
@@ -16,6 +16,7 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
16
16
  constructor() {
17
17
  super(...arguments);
18
18
  this.connectionMiddlewareManager = this.createMiddlewareManager();
19
+ this.upgradeAuthHandler = null;
19
20
  }
20
21
  configure() {
21
22
  return this.configService.getConfiguration('webSocket');
@@ -31,6 +32,9 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
31
32
  getConnectionMiddleware: () => {
32
33
  return this.getConnectionMiddleware();
33
34
  },
35
+ onWebSocketUpgrade: (handler) => {
36
+ return this.onWebSocketUpgrade(handler);
37
+ },
34
38
  });
35
39
  }
36
40
  async afterContainerReady(options) {
@@ -46,7 +50,34 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
46
50
  else {
47
51
  server = (_a = this.configurationOptions.server) !== null && _a !== void 0 ? _a : http.createServer();
48
52
  }
49
- server.on('upgrade', (request, socket, head) => {
53
+ if (this.configurationOptions.enableServerHeartbeatCheck) {
54
+ if (server.listening) {
55
+ this.startHeartBeat();
56
+ }
57
+ else {
58
+ server.on('listening', () => {
59
+ this.startHeartBeat();
60
+ });
61
+ }
62
+ }
63
+ server.on('upgrade', async (request, socket, head) => {
64
+ // check if the upgrade auth handler is set
65
+ if (this.upgradeAuthHandler) {
66
+ try {
67
+ const authResult = await this.upgradeAuthHandler(request, socket, head);
68
+ if (!authResult) {
69
+ this.logger.warn('[midway:ws] WebSocket upgrade authentication failed');
70
+ socket.destroy();
71
+ return;
72
+ }
73
+ this.logger.debug('[midway:ws] WebSocket upgrade authentication passed');
74
+ }
75
+ catch (error) {
76
+ this.logger.error('[midway:ws] WebSocket upgrade authentication error:', error);
77
+ socket.destroy();
78
+ return;
79
+ }
80
+ }
50
81
  this.app.handleUpgrade(request, socket, head, ws => {
51
82
  this.app.emit('connection', ws, request);
52
83
  });
@@ -56,13 +87,19 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
56
87
  await new Promise(resolve => {
57
88
  server.listen(this.configurationOptions.port, () => {
58
89
  this.logger.info(`[midway:ws] WebSocket server port = ${this.configurationOptions.port} start success.`);
59
- if (this.configurationOptions.enableServerHeartbeatCheck) {
60
- this.startHeartBeat();
61
- }
62
90
  resolve();
63
91
  });
64
92
  });
65
93
  }
94
+ this.app.on('error', err => {
95
+ this.logger.error('socket server got error', err);
96
+ });
97
+ this.app.on('close', () => {
98
+ if (this.heartBeatInterval) {
99
+ clearInterval(this.heartBeatInterval);
100
+ }
101
+ this.logger.info('socket server close');
102
+ });
66
103
  }
67
104
  async beforeStop() {
68
105
  return new Promise(resolve => {
@@ -77,6 +114,19 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
77
114
  getFrameworkType() {
78
115
  return core_1.MidwayFrameworkType.WS;
79
116
  }
117
+ /**
118
+ * 设置升级前鉴权处理函数
119
+ * @param handler 鉴权处理函数,传入 null 可以禁用鉴权
120
+ */
121
+ onWebSocketUpgrade(handler) {
122
+ this.upgradeAuthHandler = handler;
123
+ if (handler) {
124
+ this.logger.info('[midway:ws] WebSocket upgrade authentication handler set');
125
+ }
126
+ else {
127
+ this.logger.info('[midway:ws] WebSocket upgrade authentication handler removed');
128
+ }
129
+ }
80
130
  async loadMidwayController() {
81
131
  // create room
82
132
  const controllerModules = (0, core_1.listModule)(core_1.WS_CONTROLLER_KEY);
@@ -191,15 +241,6 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
191
241
  }
192
242
  }
193
243
  });
194
- this.app.on('error', err => {
195
- this.logger.error('socket server got error', err);
196
- });
197
- this.app.on('close', () => {
198
- if (this.heartBeatInterval) {
199
- clearInterval(this.heartBeatInterval);
200
- }
201
- this.logger.info('socket server close');
202
- });
203
244
  }
204
245
  async bindSocketResponse(result, socket, propertyName, methodMap) {
205
246
  if (!result)
@@ -1,10 +1,13 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
2
4
  import * as WebSocket from 'ws';
3
5
  import { CommonMiddlewareUnion, ContextMiddlewareManager, IConfigurationOptions, IMidwayApplication, IMidwayContext, NextFunction as BaseNextFunction } from '@midwayjs/core';
4
6
  import type { IncomingMessage } from 'http';
5
7
  export type IMidwayWSApplication = IMidwayApplication<IMidwayWSContext, {
6
8
  useConnectionMiddleware: (middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>) => void;
7
9
  getConnectionMiddleware: ContextMiddlewareManager<Context, NextFunction, undefined>;
10
+ onWebSocketUpgrade: (handler: UpgradeAuthHandler | null) => void;
8
11
  }> & WebSocket.Server;
9
12
  export type IMidwayWSConfigurationOptions = {
10
13
  pubClient?: any;
@@ -27,4 +30,8 @@ export type Application = IMidwayWSApplication;
27
30
  export type NextFunction = BaseNextFunction;
28
31
  export interface Context extends IMidwayWSContext {
29
32
  }
33
+ /**
34
+ * WebSocket 升级前鉴权处理函数类型
35
+ */
36
+ export type UpgradeAuthHandler = (request: IncomingMessage, socket: any, head: Buffer) => Promise<boolean>;
30
37
  //# sourceMappingURL=interface.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/ws",
3
- "version": "3.20.8",
3
+ "version": "3.20.10",
4
4
  "description": "Midway Web Framework for ws",
5
5
  "main": "dist/index.js",
6
6
  "typings": "index.d.ts",
@@ -24,6 +24,7 @@
24
24
  "license": "MIT",
25
25
  "devDependencies": {
26
26
  "@midwayjs/core": "^3.20.4",
27
+ "@midwayjs/koa": "^3.20.4",
27
28
  "@midwayjs/mock": "^3.20.4",
28
29
  "fs-extra": "11.3.0"
29
30
  },
@@ -39,5 +40,5 @@
39
40
  "engines": {
40
41
  "node": ">=12"
41
42
  },
42
- "gitHead": "561d0e178875f28fcb98efaf6570e981b17b3870"
43
+ "gitHead": "60ef5c3dd5ebb2ee79388a4b942f07a9ef70b854"
43
44
  }