๐Ÿ“ฆ socketio / socket.io-deno

๐Ÿ“„ server.ts ยท 367 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367import { ConnInfo, getLogger, Handler } from "../../../deps.ts";
import { EventEmitter } from "../../event-emitter/mod.ts";
import { Socket } from "./socket.ts";
import { Polling } from "./transports/polling.ts";
import { WS } from "./transports/websocket.ts";
import { addCorsHeaders, CorsOptions } from "./cors.ts";
import { Transport } from "./transport.ts";
import { generateId } from "./util.ts";

const TRANSPORTS = ["polling", "websocket"];

export interface ServerOptions {
  /**
   * Name of the request path to handle
   * @default "/engine.io/"
   */
  path: string;
  /**
   * Duration in milliseconds without a pong packet to consider the connection closed
   * @default 20000
   */
  pingTimeout: number;
  /**
   * Duration in milliseconds before sending a new ping packet
   * @default 25000
   */
  pingInterval: number;
  /**
   * Duration in milliseconds before an uncompleted transport upgrade is cancelled
   * @default 10000
   */
  upgradeTimeout: number;
  /**
   * Maximum size in bytes or number of characters a message can be, before closing the session (to avoid DoS).
   * @default 1e6 (1 MB)
   */
  maxHttpBufferSize: number;
  /**
   * A function that receives a given handshake or upgrade request as its first parameter,
   * and can decide whether to continue or not.
   */
  allowRequest?: (
    req: Request,
    connInfo: ConnInfo,
  ) => Promise<void>;
  /**
   * The options related to Cross-Origin Resource Sharing (CORS)
   */
  cors?: CorsOptions;
  /**
   * A function that allows to edit the response headers of the handshake request
   */
  editHandshakeHeaders?: (
    responseHeaders: Headers,
    req: Request,
    connInfo: ConnInfo,
  ) => void | Promise<void>;
  /**
   * A function that allows to edit the response headers of all requests
   */
  editResponseHeaders?: (
    responseHeaders: Headers,
    req: Request,
    connInfo: ConnInfo,
  ) => void | Promise<void>;
}

interface ConnectionError {
  req: Request;
  code: number;
  message: string;
  context: Record<string, unknown>;
}

interface ServerReservedEvents {
  connection: (socket: Socket, request: Request, connInfo: ConnInfo) => void;
  connection_error: (err: ConnectionError) => void;
}

const enum ERROR_CODES {
  UNKNOWN_TRANSPORT = 0,
  UNKNOWN_SID,
  BAD_HANDSHAKE_METHOD,
  BAD_REQUEST,
  FORBIDDEN,
  UNSUPPORTED_PROTOCOL_VERSION,
}

const ERROR_MESSAGES = new Map<ERROR_CODES, string>([
  [ERROR_CODES.UNKNOWN_TRANSPORT, "Transport unknown"],
  [ERROR_CODES.UNKNOWN_SID, "Session ID unknown"],
  [ERROR_CODES.BAD_HANDSHAKE_METHOD, "Bad handshake method"],
  [ERROR_CODES.BAD_REQUEST, "Bad request"],
  [ERROR_CODES.FORBIDDEN, "Forbidden"],
  [ERROR_CODES.UNSUPPORTED_PROTOCOL_VERSION, "Unsupported protocol version"],
]);

export class Server extends EventEmitter<
  Record<never, never>,
  Record<never, never>,
  ServerReservedEvents
> {
  public readonly opts: ServerOptions;

  private clients: Map<string, Socket> = new Map();

  constructor(opts: Partial<ServerOptions> = {}) {
    super();

    this.opts = Object.assign(
      {
        path: "/engine.io/",
        pingTimeout: 20000,
        pingInterval: 25000,
        upgradeTimeout: 10000,
        maxHttpBufferSize: 1e6,
      },
      opts,
    );
  }

  /**
   * Returns a request handler.
   *
   * @param additionalHandler - another handler which will receive the request if the path does not match
   */
  public handler(additionalHandler?: Handler) {
    return (req: Request, connInfo: ConnInfo): Response | Promise<Response> => {
      const url = new URL(req.url);
      if (url.pathname === this.opts.path) {
        return this.handleRequest(req, connInfo, url);
      } else if (additionalHandler) {
        return additionalHandler(req, connInfo);
      } else {
        return new Response(null, { status: 404 });
      }
    };
  }

  /**
   * Handles an HTTP request.
   *
   * @param req
   * @param connInfo
   * @param url
   * @private
   */
  private async handleRequest(
    req: Request,
    connInfo: ConnInfo,
    url: URL,
  ): Promise<Response> {
    getLogger("engine.io").debug(`[server] handling ${req.method} ${req.url}`);

    const responseHeaders = new Headers();
    if (this.opts.cors) {
      addCorsHeaders(responseHeaders, this.opts.cors, req);

      if (req.method === "OPTIONS") {
        return new Response(null, { status: 204, headers: responseHeaders });
      }
    }

    if (this.opts.editResponseHeaders) {
      await this.opts.editResponseHeaders(responseHeaders, req, connInfo);
    }

    try {
      await this.verify(req, url);
    } catch (err) {
      const { code, context } = err as {
        code: ERROR_CODES;
        context: Record<string, unknown>;
      };
      const message = ERROR_MESSAGES.get(code)!;
      this.emitReserved("connection_error", {
        req,
        code,
        message,
        context,
      });
      const body = JSON.stringify({
        code,
        message,
      });
      responseHeaders.set("Content-Type", "application/json");
      return new Response(body, {
        status: 400,
        headers: responseHeaders,
      });
    }

    if (this.opts.allowRequest) {
      try {
        await this.opts.allowRequest(req, connInfo);
      } catch (reason) {
        this.emitReserved("connection_error", {
          req,
          code: ERROR_CODES.FORBIDDEN,
          message: ERROR_MESSAGES.get(ERROR_CODES.FORBIDDEN)!,
          context: {
            message: reason,
          },
        });
        const body = JSON.stringify({
          code: ERROR_CODES.FORBIDDEN,
          message: reason,
        });
        responseHeaders.set("Content-Type", "application/json");
        return new Response(body, {
          status: 403,
          headers: responseHeaders,
        });
      }
    }

    const sid = url.searchParams.get("sid");
    if (sid) {
      // the client must exist since we have checked it in the verify method
      const socket = this.clients.get(sid)!;

      if (req.headers.has("upgrade")) {
        const transport = new WS(this.opts);

        const promise = transport.onRequest(req);

        socket._maybeUpgrade(transport);

        return promise;
      }

      getLogger("engine.io").debug(
        "[server] setting new request for existing socket",
      );

      return socket.transport.onRequest(req, responseHeaders);
    } else {
      return this.handshake(req, connInfo, responseHeaders);
    }
  }

  /**
   * Verifies a request.
   *
   * @param req
   * @param url
   * @private
   */
  private verify(req: Request, url: URL): Promise<void> {
    const transport = url.searchParams.get("transport") || "";
    if (!TRANSPORTS.includes(transport)) {
      getLogger("engine.io").debug(`unknown transport "${transport}"`);
      return Promise.reject({
        code: ERROR_CODES.UNKNOWN_TRANSPORT,
        context: {
          transport,
        },
      });
    }

    const sid = url.searchParams.get("sid");
    if (sid) {
      const client = this.clients.get(sid);
      if (!client) {
        getLogger("engine.io").debug(`[server] unknown client with sid ${sid}`);
        return Promise.reject({
          code: ERROR_CODES.UNKNOWN_SID,
          context: {
            sid,
          },
        });
      }
      const previousTransport = client.transport.name;
      if (previousTransport === "websocket") {
        getLogger("engine.io").debug(
          "[server] unexpected transport without upgrade",
        );
        return Promise.reject(
          {
            code: ERROR_CODES.BAD_REQUEST,
            context: {
              name: "TRANSPORT_MISMATCH",
              transport,
              previousTransport,
            },
          },
        );
      }
    } else {
      // handshake is GET only
      if (req.method !== "GET") {
        return Promise.reject({
          code: ERROR_CODES.BAD_HANDSHAKE_METHOD,
          context: {
            method: req.method,
          },
        });
      }

      const protocol = url.searchParams.get("EIO") === "4" ? 4 : 3; // 3rd revision by default
      if (protocol === 3) {
        return Promise.reject({
          code: ERROR_CODES.UNSUPPORTED_PROTOCOL_VERSION,
          context: {
            protocol,
          },
        });
      }
    }

    return Promise.resolve();
  }

  /**
   * Handshakes a new client.
   *
   * @param req
   * @param connInfo
   * @param responseHeaders
   * @private
   */
  private async handshake(
    req: Request,
    connInfo: ConnInfo,
    responseHeaders: Headers,
  ): Promise<Response> {
    const id = generateId();

    let transport: Transport;
    if (req.headers.has("upgrade")) {
      transport = new WS(this.opts);
    } else {
      transport = new Polling(this.opts);
    }

    getLogger("engine.io").info(`[server] new socket ${id}`);

    const socket = new Socket(id, this.opts, transport);
    this.clients.set(id, socket);

    socket.once("close", (reason) => {
      getLogger("engine.io").info(
        `[server] socket ${id} closed due to ${reason}`,
      );
      this.clients.delete(id);
    });

    if (this.opts.editHandshakeHeaders) {
      await this.opts.editHandshakeHeaders(responseHeaders, req, connInfo);
    }

    const promise = transport.onRequest(req, responseHeaders);

    this.emitReserved("connection", socket, req, connInfo);

    return promise;
  }

  /**
   * Closes all clients.
   */
  public close() {
    getLogger("engine.io").debug("[server] closing all open clients");
    this.clients.forEach((client) => client.close());
  }
}