server.d.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import { EventEmitter } from "events";
  2. import { Socket } from "./socket";
  3. import type { IncomingMessage, Server as HttpServer, ServerResponse } from "http";
  4. import type { CorsOptions, CorsOptionsDelegate } from "cors";
  5. import type { Duplex } from "stream";
  6. import type { EngineRequest } from "./transport";
  7. import type { CookieSerializeOptions } from "./contrib/types.cookie";
  8. type Transport = "polling" | "websocket" | "webtransport";
  9. export interface AttachOptions {
  10. /**
  11. * name of the path to capture
  12. * @default "/engine.io"
  13. */
  14. path?: string;
  15. /**
  16. * destroy unhandled upgrade requests
  17. * @default true
  18. */
  19. destroyUpgrade?: boolean;
  20. /**
  21. * milliseconds after which unhandled requests are ended
  22. * @default 1000
  23. */
  24. destroyUpgradeTimeout?: number;
  25. /**
  26. * Whether we should add a trailing slash to the request path.
  27. * @default true
  28. */
  29. addTrailingSlash?: boolean;
  30. }
  31. export interface ServerOptions {
  32. /**
  33. * how many ms without a pong packet to consider the connection closed
  34. * @default 20000
  35. */
  36. pingTimeout?: number;
  37. /**
  38. * how many ms before sending a new ping packet
  39. * @default 25000
  40. */
  41. pingInterval?: number;
  42. /**
  43. * how many ms before an uncompleted transport upgrade is cancelled
  44. * @default 10000
  45. */
  46. upgradeTimeout?: number;
  47. /**
  48. * how many bytes or characters a message can be, before closing the session (to avoid DoS).
  49. * @default 1e5 (100 KB)
  50. */
  51. maxHttpBufferSize?: number;
  52. /**
  53. * A function that receives a given handshake or upgrade request as its first parameter,
  54. * and can decide whether to continue or not. The second argument is a function that needs
  55. * to be called with the decided information: fn(err, success), where success is a boolean
  56. * value where false means that the request is rejected, and err is an error code.
  57. */
  58. allowRequest?: (req: IncomingMessage, fn: (err: string | null | undefined, success: boolean) => void) => void;
  59. /**
  60. * The low-level transports that are enabled. WebTransport is disabled by default and must be manually enabled:
  61. *
  62. * @example
  63. * new Server({
  64. * transports: ["polling", "websocket", "webtransport"]
  65. * });
  66. *
  67. * @default ["polling", "websocket"]
  68. */
  69. transports?: Transport[];
  70. /**
  71. * whether to allow transport upgrades
  72. * @default true
  73. */
  74. allowUpgrades?: boolean;
  75. /**
  76. * parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable.
  77. * @default false
  78. */
  79. perMessageDeflate?: boolean | object;
  80. /**
  81. * parameters of the http compression for the polling transports (see zlib api docs). Set to false to disable.
  82. * @default true
  83. */
  84. httpCompression?: boolean | object;
  85. /**
  86. * what WebSocket server implementation to use. Specified module must
  87. * conform to the ws interface (see ws module api docs).
  88. * An alternative c++ addon is also available by installing eiows module.
  89. *
  90. * @default `require("ws").Server`
  91. */
  92. wsEngine?: any;
  93. /**
  94. * an optional packet which will be concatenated to the handshake packet emitted by Engine.IO.
  95. */
  96. initialPacket?: any;
  97. /**
  98. * configuration of the cookie that contains the client sid to send as part of handshake response headers. This cookie
  99. * might be used for sticky-session. Defaults to not sending any cookie.
  100. * @default false
  101. */
  102. cookie?: (CookieSerializeOptions & {
  103. name: string;
  104. }) | boolean;
  105. /**
  106. * the options that will be forwarded to the cors module
  107. */
  108. cors?: CorsOptions | CorsOptionsDelegate;
  109. /**
  110. * whether to enable compatibility with Socket.IO v2 clients
  111. * @default false
  112. */
  113. allowEIO3?: boolean;
  114. }
  115. /**
  116. * An Express-compatible middleware.
  117. *
  118. * Middleware functions are functions that have access to the request object (req), the response object (res), and the
  119. * next middleware function in the application’s request-response cycle.
  120. *
  121. * @see https://expressjs.com/en/guide/using-middleware.html
  122. */
  123. type Middleware = (req: IncomingMessage, res: ServerResponse, next: (err?: any) => void) => void;
  124. export declare abstract class BaseServer extends EventEmitter {
  125. opts: ServerOptions;
  126. protected clients: Record<string, Socket>;
  127. clientsCount: number;
  128. protected middlewares: Middleware[];
  129. /**
  130. * Server constructor.
  131. *
  132. * @param {Object} opts - options
  133. */
  134. constructor(opts?: ServerOptions);
  135. protected abstract init(): any;
  136. /**
  137. * Compute the pathname of the requests that are handled by the server
  138. * @param options
  139. * @protected
  140. */
  141. protected _computePath(options: AttachOptions): string;
  142. /**
  143. * Returns a list of available transports for upgrade given a certain transport.
  144. *
  145. * @return {Array}
  146. */
  147. upgrades(transport: string): any;
  148. /**
  149. * Verifies a request.
  150. *
  151. * @param {EngineRequest} req
  152. * @param upgrade - whether it's an upgrade request
  153. * @param fn
  154. * @protected
  155. */
  156. protected verify(req: any, upgrade: boolean, fn: (errorCode?: number, errorContext?: any) => void): void;
  157. /**
  158. * Adds a new middleware.
  159. *
  160. * @example
  161. * import helmet from "helmet";
  162. *
  163. * engine.use(helmet());
  164. *
  165. * @param fn
  166. */
  167. use(fn: any): void;
  168. /**
  169. * Apply the middlewares to the request.
  170. *
  171. * @param req
  172. * @param res
  173. * @param callback
  174. * @protected
  175. */
  176. protected _applyMiddlewares(req: IncomingMessage, res: ServerResponse, callback: (err?: any) => void): void;
  177. /**
  178. * Closes all clients.
  179. */
  180. close(): this;
  181. protected abstract cleanup(): any;
  182. /**
  183. * generate a socket id.
  184. * Overwrite this method to generate your custom socket id
  185. *
  186. * @param {IncomingMessage} req - the request object
  187. */
  188. generateId(req: IncomingMessage): any;
  189. /**
  190. * Handshakes a new client.
  191. *
  192. * @param {String} transportName
  193. * @param {Object} req - the request object
  194. * @param {Function} closeConnection
  195. *
  196. * @protected
  197. */
  198. protected handshake(transportName: string, req: any, closeConnection: (errorCode?: number, errorContext?: any) => void): Promise<any>;
  199. onWebTransportSession(session: any): Promise<any>;
  200. protected abstract createTransport(transportName: any, req: any): any;
  201. /**
  202. * Protocol errors mappings.
  203. */
  204. static errors: {
  205. UNKNOWN_TRANSPORT: number;
  206. UNKNOWN_SID: number;
  207. BAD_HANDSHAKE_METHOD: number;
  208. BAD_REQUEST: number;
  209. FORBIDDEN: number;
  210. UNSUPPORTED_PROTOCOL_VERSION: number;
  211. };
  212. static errorMessages: {
  213. 0: string;
  214. 1: string;
  215. 2: string;
  216. 3: string;
  217. 4: string;
  218. 5: string;
  219. };
  220. }
  221. /**
  222. * An Engine.IO server based on Node.js built-in HTTP server and the `ws` package for WebSocket connections.
  223. */
  224. export declare class Server extends BaseServer {
  225. httpServer?: HttpServer;
  226. private ws;
  227. /**
  228. * Initialize websocket server
  229. *
  230. * @protected
  231. */
  232. protected init(): void;
  233. protected cleanup(): void;
  234. /**
  235. * Prepares a request by processing the query string.
  236. *
  237. * @private
  238. */
  239. private prepare;
  240. protected createTransport(transportName: string, req: IncomingMessage): any;
  241. /**
  242. * Handles an Engine.IO HTTP request.
  243. *
  244. * @param {EngineRequest} req
  245. * @param {ServerResponse} res
  246. */
  247. handleRequest(req: EngineRequest, res: ServerResponse): void;
  248. /**
  249. * Handles an Engine.IO HTTP Upgrade.
  250. */
  251. handleUpgrade(req: EngineRequest, socket: Duplex, upgradeHead: Buffer): void;
  252. /**
  253. * Called upon a ws.io connection.
  254. *
  255. * @param {ws.Socket} websocket
  256. * @private
  257. */
  258. private onWebSocket;
  259. /**
  260. * Captures upgrade requests for a http.Server.
  261. *
  262. * @param {http.Server} server
  263. * @param {Object} options
  264. */
  265. attach(server: HttpServer, options?: AttachOptions): void;
  266. }
  267. export {};