1.0.3 • Published 3 years ago

@project-christopher/server-library v1.0.3

Weekly downloads
-
License
Apache 2.0
Repository
github
Last release
3 years ago

Introduction

Server Library | Encrypted communication tool (server side)

The project is maintained by Project Christopher.

Installation

To use server-library, you will need to import it from a separate NodeJS App.

To install it, use: npm i @project-christopherg/server-lirary or yarn add @project-christopherg/server-lirary.

Then, you can import it using:

import {Server} from "@project-christopherg/server-lirary"

Usage

Initialize

Create an object for the library and initialize the library with the appropriate configuration.

Using default values:

let server: Server = new Server({encryption: {private_key: ""}});

or declare a path that points to your configuration file:

let server: Server = new Server("path/to/configuration.json");

or pass a JSON object directly

let server: Server = new Server({ ... });

An error will be thrown is case of invalid configuration.

Register events

The event must be string type, it can be random. but the library has blacklisted some events. These events are decided from each server driver. For example for socket.io driver is connection, connect, connect_error, disconnect, disconnecting, newListener, removeListener.

server.on('connection', async (client: Client, error_: string) => {
  if (!error_)
    console.log('Client with id ' + client.id + ' and ip address ' + client.address + ' authenticated successfully.');
  else
    console.log('Client with ip address ' + client.address + ' failed authentication, error code: ' + error_);
});

server.on('disconnect', async (client: Client, reason: string) =>
        console.log('Client with id ' + client.id + ' disconnected. Reason: ' + reason))

and a random event to receive data:

server.on('data', async (data: object, callback: any) => {
  // encrypted is an error_ if it is typeof string
  if (data.error_)
    return console.log('Encountered error for id', data.client.id, 'with error code:', data.error_);
  // Decrypt data
  let plainData = await data.decrypt();

  // Respond with an encrypted message (json or string).
  callback({message: 'Hello, World!'});
});

If you want to add some authorization on connection add a verification function:

server.setConnectVerification(client =>
        client.id === 'client-1' && client.auth.token === "12345");

Listen and Close

// Make the server to listen to a port
server.listen((port: number) => {
  console.log(`Server listening at port:`, port);
});

// and to stop listening
await server.close();

Emit

let clientId = 'client-id';
let event = 'data';
let dataToSend = 'Hello, World!'

// Emit data to a client
await server.emit(clientId, event, dataToSend);

// Emit data to a client and wait for reponse
await server.emit(clientId, event, dataToSend
        , async (response: object|string) => console.log(response))

In case of an error, emit function will throw an appropriate exception.

Broadcasting

The server library also contains a broadcast function (not encrypted):

// The condition function which decides if a response will be returned.
let condtion = (message) => message === 'hey'; // can be async
let response = "Hello, World!";

server.broadcastListen(condition, response
        , port => console.log('Broadcast listening at port:', port));

// and to stop broadcasting
server.broadcastClose();

If condition is set to null then it will always return true. If response is set to null then it will respond with an empty string.

Extra functions

Server library provides some extra functionalities.

// Returns an array of all the connected clients' ids.
let ids = server.getClientIds()

// Returns an array of all the connected clients objects.
let clients = server.getClients()

// The configuration file can host other data except from the ones needed from the server library.
// You can access a copy of them using the following function:
let configuration: object = server.getConfiguration()

and the available drivers functions:

// Return the availale driver names.
console.log(Server.asyncEncryptionDrivers());
console.log(Server.syncEncryptionDrivers());
console.log(Server.serverDrivers());

Client class

class Client {
    /** The client's id. */
    declare id: string
    /** The extra data that the client sent during connection. */
    declare extra: any
    /** IP Address. */
    declare address: any
    /** The client object used by the driver to emit. */
    declare socket: any
    /** The disconnect function for the client. */
    declare disconnect: () => any
    /** The connection data. */
    declare connectData: {
        encrypted: any,
        decrypted: any
    }
    /** All the client's information about the authorization. */
    declare auth: {
        /** The public key. */
        public_key: any,
        /** The token string or object */
        token: any
    }
}

Configuration

The configuration format for initializing the library (default).

{
  "encryption" : {
    "disable": false,
    "asynchronous" : {
      "driver": "rsa",
      "bits": 2048,
      "private_key": ""
    },
    "synchronous" : {
      "driver": "aes-128-gcm",
      "key_bytes": 190
    }
  },
  "server": {
    "driver": "socket.io",
    "port": 5000,
    /* socket.io */
    "socket.io": { }
  },
  "broadcast": {
    "port": 8089
  }
}
  • encrytpion: all the information needed for the encrypted communication.
    • disable: if true, the drivers are auto set to none and no encryption is applied.
    • asynchronous: the information for the asynchronous encryption.
      • driver: the asynchronous encryption driver
      • bits: the size of the encryption keys in bits. .
      • private_key: The private key of the server.
  • synchronous: the information for the synchronous encryption.
    • driver: the synchronous encryption driver.
    • key_bytes: the length of the symmetric encryption key that will be generated, must not be greater than the asynchronous.bits / 8. If padding is applied then the number must be less.
  • server: the information needed for the communication server.
    • driver: The server driver.
    • port: The port where the server will listen.
    • socket.io: configuration for socket.io driver (not available)
  • broadcast: the information needed for the broadcast server.
    • port: The port where the broadcast server will listen.

Available Drivers

  • Asynchronous encryption: rsa, none
  • Synchronous encryption: aes-128-gcm, none
  • Server: socket.io

Create custom drivers

Create a file and put inside the driver folder (either for server or encryption). The file must export a class that extends the appropriate parent class, AsyncDriver, SyncDriver, ServerDriver. Then edit the appropriate driver file to return the driver.

1.0.2

3 years ago

1.0.1

3 years ago

3.0.2

3 years ago

3.0.1

3 years ago

3.0.0

3 years ago

1.0.3

3 years ago

2.1.0

3 years ago

2.0.2

3 years ago

2.0.1

3 years ago

2.0.0

3 years ago

1.2.2

3 years ago

1.2.1

3 years ago

1.2.0

3 years ago

1.1.0

3 years ago

1.0.0

3 years ago