@midwayjs/ws 4.0.0-beta.1 → 4.0.0-beta.11

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,4 +9,4 @@ Document: [https://midwayjs.org](https://midwayjs.org)
9
9
 
10
10
  ## License
11
11
 
12
- [MIT]((https://github.com/midwayjs/midway/blob/master/LICENSE))
12
+ [MIT](https://github.com/midwayjs/midway/blob/master/LICENSE)
@@ -1,18 +1,21 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  import { BaseFramework, CommonMiddlewareUnion, ContextMiddlewareManager, IMidwayBootstrapOptions } from '@midwayjs/core';
4
2
  import * as http from 'http';
5
- import { Application, Context, IMidwayWSApplication, IMidwayWSConfigurationOptions, NextFunction } from './interface';
3
+ import { Application, Context, IMidwayWSConfigurationOptions, NextFunction, UpgradeAuthHandler } from './interface';
6
4
  export declare class MidwayWSFramework extends BaseFramework<Application, Context, IMidwayWSConfigurationOptions> {
7
5
  server: http.Server;
8
6
  protected heartBeatInterval: NodeJS.Timeout;
9
7
  protected connectionMiddlewareManager: ContextMiddlewareManager<Context, unknown, unknown>;
8
+ protected upgradeAuthHandler: UpgradeAuthHandler | null;
10
9
  protected frameworkLoggerName: string;
11
10
  configure(): IMidwayWSConfigurationOptions;
12
11
  applicationInitialize(options: IMidwayBootstrapOptions): Promise<void>;
13
- app: IMidwayWSApplication;
14
12
  run(): Promise<void>;
15
13
  protected beforeStop(): Promise<void>;
14
+ /**
15
+ * 设置升级前鉴权处理函数
16
+ * @param handler 鉴权处理函数,传入 null 可以禁用鉴权
17
+ */
18
+ onWebSocketUpgrade(handler: UpgradeAuthHandler | null): void;
16
19
  private loadMidwayController;
17
20
  private addNamespace;
18
21
  private bindSocketResponse;
package/dist/framework.js CHANGED
@@ -13,11 +13,11 @@ const util_1 = require("util");
13
13
  const debug = (0, util_1.debuglog)('midway:debug');
14
14
  const WebSocket = require("ws");
15
15
  let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
16
- constructor() {
17
- super(...arguments);
18
- this.connectionMiddlewareManager = this.createMiddlewareManager();
19
- this.frameworkLoggerName = 'wsLogger';
20
- }
16
+ server;
17
+ heartBeatInterval;
18
+ connectionMiddlewareManager = this.createMiddlewareManager();
19
+ upgradeAuthHandler = null;
20
+ frameworkLoggerName = 'wsLogger';
21
21
  configure() {
22
22
  return this.configService.getConfiguration('webSocket');
23
23
  }
@@ -32,6 +32,9 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
32
32
  getConnectionMiddleware: () => {
33
33
  return this.getConnectionMiddleware();
34
34
  },
35
+ onWebSocketUpgrade: (handler) => {
36
+ return this.onWebSocketUpgrade(handler);
37
+ },
35
38
  });
36
39
  await this.loadMidwayController();
37
40
  }
@@ -44,7 +47,34 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
44
47
  else {
45
48
  server = this.configurationOptions.server ?? http.createServer();
46
49
  }
47
- server.on('upgrade', (request, socket, head) => {
50
+ if (this.configurationOptions.enableServerHeartbeatCheck) {
51
+ if (server.listening) {
52
+ this.startHeartBeat();
53
+ }
54
+ else {
55
+ server.on('listening', () => {
56
+ this.startHeartBeat();
57
+ });
58
+ }
59
+ }
60
+ server.on('upgrade', async (request, socket, head) => {
61
+ // check if the upgrade auth handler is set
62
+ if (this.upgradeAuthHandler) {
63
+ try {
64
+ const authResult = await this.upgradeAuthHandler(request, socket, head);
65
+ if (!authResult) {
66
+ this.logger.warn('[midway:ws] WebSocket upgrade authentication failed');
67
+ socket.destroy();
68
+ return;
69
+ }
70
+ this.logger.debug('[midway:ws] WebSocket upgrade authentication passed');
71
+ }
72
+ catch (error) {
73
+ this.logger.error('[midway:ws] WebSocket upgrade authentication error:', error);
74
+ socket.destroy();
75
+ return;
76
+ }
77
+ }
48
78
  this.app.handleUpgrade(request, socket, head, ws => {
49
79
  this.app.emit('connection', ws, request);
50
80
  });
@@ -54,13 +84,19 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
54
84
  await new Promise(resolve => {
55
85
  server.listen(this.configurationOptions.port, () => {
56
86
  this.logger.info(`[midway:ws] WebSocket server port = ${this.configurationOptions.port} start success.`);
57
- if (this.configurationOptions.enableServerHeartbeatCheck) {
58
- this.startHeartBeat();
59
- }
60
87
  resolve();
61
88
  });
62
89
  });
63
90
  }
91
+ this.app.on('error', err => {
92
+ this.logger.error('socket server got error', err);
93
+ });
94
+ this.app.on('close', () => {
95
+ if (this.heartBeatInterval) {
96
+ clearInterval(this.heartBeatInterval);
97
+ }
98
+ this.logger.info('socket server close');
99
+ });
64
100
  }
65
101
  async beforeStop() {
66
102
  return new Promise(resolve => {
@@ -72,6 +108,19 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
72
108
  this.server.close();
73
109
  });
74
110
  }
111
+ /**
112
+ * 设置升级前鉴权处理函数
113
+ * @param handler 鉴权处理函数,传入 null 可以禁用鉴权
114
+ */
115
+ onWebSocketUpgrade(handler) {
116
+ this.upgradeAuthHandler = handler;
117
+ if (handler) {
118
+ this.logger.info('[midway:ws] WebSocket upgrade authentication handler set');
119
+ }
120
+ else {
121
+ this.logger.info('[midway:ws] WebSocket upgrade authentication handler removed');
122
+ }
123
+ }
75
124
  async loadMidwayController() {
76
125
  // create room
77
126
  const controllerModules = core_1.DecoratorManager.listModule(core_1.WS_CONTROLLER_KEY);
@@ -95,6 +144,7 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
95
144
  // create request context
96
145
  this.app.createAnonymousContext(socket);
97
146
  socket.requestContext.registerObject('socket', socket);
147
+ socket.request = request;
98
148
  socket.app = this.app;
99
149
  // run connection middleware
100
150
  const connectFn = await this.middlewareService.compose([
@@ -182,15 +232,6 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
182
232
  }
183
233
  }
184
234
  });
185
- this.app.on('error', err => {
186
- this.logger.error('socket server got error', err);
187
- });
188
- this.app.on('close', () => {
189
- if (this.heartBeatInterval) {
190
- clearInterval(this.heartBeatInterval);
191
- }
192
- this.logger.info('socket server close');
193
- });
194
235
  }
195
236
  async bindSocketResponse(result, socket, propertyName, methodMap) {
196
237
  if (!result)
@@ -1,8 +1,10 @@
1
1
  import * as WebSocket from 'ws';
2
2
  import { CommonMiddlewareUnion, ContextMiddlewareManager, IConfigurationOptions, IMidwayApplication, IMidwayContext, NextFunction as BaseNextFunction } from '@midwayjs/core';
3
+ import type { IncomingMessage } from 'http';
3
4
  export type IMidwayWSApplication = IMidwayApplication<IMidwayWSContext, {
4
5
  useConnectionMiddleware: (middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>) => void;
5
6
  getConnectionMiddleware: ContextMiddlewareManager<Context, NextFunction, undefined>;
7
+ onWebSocketUpgrade: (handler: UpgradeAuthHandler | null) => void;
6
8
  }> & WebSocket.Server;
7
9
  export type IMidwayWSConfigurationOptions = {
8
10
  pubClient?: any;
@@ -19,9 +21,14 @@ export type IMidwayWSConfigurationOptions = {
19
21
  export type IMidwayWSContext = IMidwayContext<WebSocket & {
20
22
  app: IMidwayWSApplication;
21
23
  isAlive: boolean;
24
+ request: IncomingMessage;
22
25
  }>;
23
26
  export type Application = IMidwayWSApplication;
24
27
  export type NextFunction = BaseNextFunction;
25
28
  export interface Context extends IMidwayWSContext {
26
29
  }
30
+ /**
31
+ * WebSocket 升级前鉴权处理函数类型
32
+ */
33
+ export type UpgradeAuthHandler = (request: IncomingMessage, socket: any, head: Buffer) => Promise<boolean>;
27
34
  //# sourceMappingURL=interface.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/ws",
3
- "version": "4.0.0-beta.1",
3
+ "version": "4.0.0-beta.11",
4
4
  "description": "Midway Web Framework for ws",
5
5
  "main": "dist/index.js",
6
6
  "typings": "index.d.ts",
@@ -23,9 +23,10 @@
23
23
  ],
24
24
  "license": "MIT",
25
25
  "devDependencies": {
26
- "@midwayjs/core": "^4.0.0-beta.1",
27
- "@midwayjs/mock": "^4.0.0-beta.1",
28
- "fs-extra": "11.3.0"
26
+ "@midwayjs/core": "^4.0.0-beta.11",
27
+ "@midwayjs/koa": "^4.0.0-beta.11",
28
+ "@midwayjs/mock": "^4.0.0-beta.11",
29
+ "fs-extra": "11.3.3"
29
30
  },
30
31
  "dependencies": {
31
32
  "@types/ws": "8.5.14",
@@ -37,7 +38,7 @@
37
38
  "url": "https://github.com/midwayjs/midway.git"
38
39
  },
39
40
  "engines": {
40
- "node": ">=12"
41
+ "node": ">=20"
41
42
  },
42
- "gitHead": "832961ec3aff123c033197d8c00cb2bc9bad7ff8"
43
+ "gitHead": "6ef05719ca6e900f1ec34aff7a5c5a9614358c50"
43
44
  }