net#isIPv4 TypeScript Examples

The following examples show how to use net#isIPv4. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: write-events-prepublish.service.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
private getCloudEventMetadata(event: T): EventMetadataDto {
    try {
      const { version: defaultVersion, time } = createEventDefaultMetadata();
      const version = event?.metadata?.version ?? defaultVersion;
      const hostnameRaw = this.context.get(CONTEXT_HOSTNAME);
      const hostname = isIPv4(hostnameRaw)
        ? `${hostnameRaw.split(/[.]/).join('-')}.ip`
        : hostnameRaw;
      const hostnameArr = hostname.split('.');
      const eventType = `${hostnameArr[1] ? hostnameArr[1] + '.' : ''}${
        hostnameArr[0]
      }.${this.config.serviceName ?? this.context.get(CONTEXT_BIN)}.${
        event.eventType
      }.${version}`;
      const source = `${hostname}${this.context.get(CONTEXT_PATH)}`;
      return {
        specversion: 1,
        time,
        version,
        correlation_id: this.context.get(CONTEXT_CORRELATION_ID),
        type: eventType,
        source,
        created_at: new Date().toISOString(),
      };
    } catch (e) {
      this.logger.error(e);
      throw e;
    }
  }
Example #2
Source File: nodestatus.ts    From nodestatus with MIT License 4 votes vote down vote up
public launch(): Promise<void> {
    const { interval, pingInterval } = this.options;

    setupHeartbeat(this.ioConn, pingInterval);
    setupHeartbeat(this.ioPub, pingInterval);

    this.server.on('upgrade', (request, socket, head) => {
      const pathname = request.url;
      if (pathname === '/connect') {
        this.ioConn.handleUpgrade(request, socket, head, (ws: IWebSocket) => {
          ws.ipAddress = (request.headers['x-forwarded-for'] as any)?.split(',')?.[0]?.trim() || request.socket.remoteAddress;
          this.ioConn.emit('connection', ws);
        });
      } else if (pathname === '/public') {
        this.ioPub.handleUpgrade(request, socket, head, ws => {
          this.ioPub.emit('connection', ws);
        });
      } else {
        socket.destroy();
      }
    });

    this.ioConn.on('connection', (socket: IWebSocket) => {
      const address = socket.ipAddress;
      if (typeof address === 'undefined') {
        return socket.close();
      }
      callHook(this, 'onServerConnect', socket);
      socket.send('Authentication required');
      loggerConnecting.debug(`Address: ${address}`);
      socket.once('message', async (buf: Buffer) => {
        if (this.isBanned.get(address)) {
          socket.send('You are banned. Please try connecting after 60 / 120 seconds');
          return socket.close();
        }
        let username = '', password = '';
        try {
          ({ username, password } = decode(buf) as any);
          username = username.trim();
          password = password.trim();
          if (!this.servers[username]) {
            socket.send('Wrong username and/or password.');
            return this.setBan(socket, address, 120, 'Wrong username and/or password.');
          }
          /*
          * 当客户端与服务端断开连接时,客户端会自动重连。但是服务端可能需要等待下一个心跳检测周期才能断开与客户端的连接
          * Temporary Fix
          * Work in Progress
          *   */
          if (Object.keys(this.servers[username]?.status || {}).length) {
            const preSocket = this.userMap.get(username);
            if (preSocket) {
              if (preSocket.ipAddress === address) {
                preSocket.terminate();
              } else {
                preSocket.isAlive = false;
                preSocket.ping();
                const ac = new AbortController();
                const promise = timers.setTimeout((pingInterval + 5) * 1000, null, { signal: ac.signal });
                preSocket.on('close', () => ac.abort());
                try {
                  await promise;
                  socket.send('Only one connection per user allowed.');
                  return this.setBan(socket, address, 120, 'Only one connection per user allowed.');
                  // eslint-disable-next-line no-empty
                } catch (error: any) {
                }
              }
            }
          }
        } catch (error: any) {
          socket.send('Please check your login details.');
          return this.setBan(socket, address, 120, 'it is an idiot.');
        }
        if (!await authServer(username, password)) {
          socket.send('Wrong username and/or password.');
          return this.setBan(socket, address, 60, 'use wrong username and/or password.');
        }
        socket.send('Authentication successful. Access granted.');
        let ipType = 'IPv6';
        if (isIPv4(address) || IPv6.parse(address).isIPv4MappedAddress()) {
          ipType = 'IPv4';
        }
        socket.send(`You are connecting via: ${ipType}`);
        loggerConnected.info(`Username: ${username} | Address: ${address}`);
        resolveEvent(username).then();
        socket.on('message', (buf: Buffer) => this.servers[username].status = decode(buf) as ServerItem['status']);
        this.userMap.set(username, socket);

        callHook(this, 'onServerConnected', socket, username);
        callHook(this, '_serverConnectedPush', socket, username);

        socket.once('close', () => {
          this.userMap.delete(username);
          this.servers[username] && (this.servers[username].status = {});
          loggerDisconnected.warn(`Username: ${username} | Address: ${address}`);

          callHook(this, 'onServerDisconnected', socket, username);
          callHook(this, '_serverDisconnectedPush', socket, username, (now: Date) => createNewEvent(username, now).then());
        });
      });
    });

    this.ioPub.on('connection', socket => {
      const runPush = () => socket.send(JSON.stringify({
        servers: this.serversPub,
        updated: ~~(Date.now() / 1000)
      }));
      runPush();
      const id = setInterval(runPush, interval);
      socket.on('close', () => clearInterval(id));
    });

    return this.updateStatus();
  }