@midwayjs/ws 3.20.4 → 3.20.9

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,24 @@ 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
+ server.on('upgrade', async (request, socket, head) => {
54
+ // check if the upgrade auth handler is set
55
+ if (this.upgradeAuthHandler) {
56
+ try {
57
+ const authResult = await this.upgradeAuthHandler(request, socket, head);
58
+ if (!authResult) {
59
+ this.logger.warn('[midway:ws] WebSocket upgrade authentication failed');
60
+ socket.destroy();
61
+ return;
62
+ }
63
+ this.logger.debug('[midway:ws] WebSocket upgrade authentication passed');
64
+ }
65
+ catch (error) {
66
+ this.logger.error('[midway:ws] WebSocket upgrade authentication error:', error);
67
+ socket.destroy();
68
+ return;
69
+ }
70
+ }
50
71
  this.app.handleUpgrade(request, socket, head, ws => {
51
72
  this.app.emit('connection', ws, request);
52
73
  });
@@ -77,6 +98,19 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
77
98
  getFrameworkType() {
78
99
  return core_1.MidwayFrameworkType.WS;
79
100
  }
101
+ /**
102
+ * 设置升级前鉴权处理函数
103
+ * @param handler 鉴权处理函数,传入 null 可以禁用鉴权
104
+ */
105
+ onWebSocketUpgrade(handler) {
106
+ this.upgradeAuthHandler = handler;
107
+ if (handler) {
108
+ this.logger.info('[midway:ws] WebSocket upgrade authentication handler set');
109
+ }
110
+ else {
111
+ this.logger.info('[midway:ws] WebSocket upgrade authentication handler removed');
112
+ }
113
+ }
80
114
  async loadMidwayController() {
81
115
  // create room
82
116
  const controllerModules = (0, core_1.listModule)(core_1.WS_CONTROLLER_KEY);
@@ -102,6 +136,7 @@ let MidwayWSFramework = class MidwayWSFramework extends core_1.BaseFramework {
102
136
  // create request context
103
137
  this.app.createAnonymousContext(socket);
104
138
  socket.requestContext.registerObject('socket', socket);
139
+ socket.request = request;
105
140
  socket.app = this.app;
106
141
  // run connection middleware
107
142
  const connectFn = await this.middlewareService.compose([
@@ -1,8 +1,13 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
1
4
  import * as WebSocket from 'ws';
2
5
  import { CommonMiddlewareUnion, ContextMiddlewareManager, IConfigurationOptions, IMidwayApplication, IMidwayContext, NextFunction as BaseNextFunction } from '@midwayjs/core';
6
+ import type { IncomingMessage } from 'http';
3
7
  export type IMidwayWSApplication = IMidwayApplication<IMidwayWSContext, {
4
8
  useConnectionMiddleware: (middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>) => void;
5
9
  getConnectionMiddleware: ContextMiddlewareManager<Context, NextFunction, undefined>;
10
+ onWebSocketUpgrade: (handler: UpgradeAuthHandler | null) => void;
6
11
  }> & WebSocket.Server;
7
12
  export type IMidwayWSConfigurationOptions = {
8
13
  pubClient?: any;
@@ -19,9 +24,14 @@ export type IMidwayWSConfigurationOptions = {
19
24
  export type IMidwayWSContext = IMidwayContext<WebSocket & {
20
25
  app: IMidwayWSApplication;
21
26
  isAlive: boolean;
27
+ request: IncomingMessage;
22
28
  }>;
23
29
  export type Application = IMidwayWSApplication;
24
30
  export type NextFunction = BaseNextFunction;
25
31
  export interface Context extends IMidwayWSContext {
26
32
  }
33
+ /**
34
+ * WebSocket 升级前鉴权处理函数类型
35
+ */
36
+ export type UpgradeAuthHandler = (request: IncomingMessage, socket: any, head: Buffer) => Promise<boolean>;
27
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.4",
3
+ "version": "3.20.9",
4
4
  "description": "Midway Web Framework for ws",
5
5
  "main": "dist/index.js",
6
6
  "typings": "index.d.ts",
@@ -39,5 +39,5 @@
39
39
  "engines": {
40
40
  "node": ">=12"
41
41
  },
42
- "gitHead": "c3fb65a7ada8829635f3c6af5ef83c65c3a43d79"
42
+ "gitHead": "d9032e8d591cb4e4997e31d757d7f055078536d6"
43
43
  }