Ssh-chat, частка 2

Прывітанне, Хабр. Гэта 2 артыкул з цыклу ssh-chat.

Што мы зробім:

  • Дадамо магчымасць стварэння сваіх функцый афармлення
  • Дадамо падтрымку markdown
  • Дадамо падтрымку ботаў
  • Павялічым бяспеку пароляў(хэш і соль)
    Нажаль, але адпраўкі файлаў не будзе

Карыстальніцкія функцыі афармлення

На дадзены момант рэалізавана падтрымка наступных функцый афармлення:

  • @color
  • @bold
  • @underline
  • @hex
  • @box
    Але варта дадаць магчымасць стварэння сваіх функцый:
    Усе функцыі захоўваюцца ў объекте под названием methods
    Так што будзе дастаткова стварыць функцыю registerMethod:

// parserExec.js at end
module.exports.registerMethod  =  function(name, func) {
  methods[name] =  func
}

Таксама трэба гэты метад вяртаць пасля стварэння сервера

// index.js at require part
const { registerMethod } = require('./parserExec')

// index.js at end
module.exports.registerMethod  =  registerMethod

Цяпер пры стварэнні сервера мы можам рэгістраваць метады фарматавання. Прыклад:

const  chat  =  require('.')
const { formatNick } =  require('./format')

chat({})

chat.registerMethod('hello', function(p, name){
  return  'Hi, '  +  formatNick(name) +  '!'
})

Ssh-chat, частка 2

Падтрымка markdown

Markdown ну вельмі зручны так што дадамо яго з дапамогай marked terminal

// format.js near require
const marked = require('marked');
const TerminalRenderer = require('marked-terminal');

marked.setOptions({
  renderer: new TerminalRenderer()
});

// format.js line 23
message = marked(message)

Ssh-chat, частка 2

боты

Як гэта будзе працаваць

let writeBotBob = chat.registerBot({
  name: 'botBob',

  onConnect(nick, write){
    write('@hello{' + nick + '}')
  },

  onDisconnect(nick, write){},

  onMessage(nick, message, write) {
    if(message == 'botBob!') write('I'm here')
  },

  onCommand(command, write) {
    write('Doing ' + command)
  }
})

onCommand можна выклікаць з дапамогай @bot(botBob){Command}

Усё для працы з ботамі апісана ў файле:

let bots = []; // Все боты

let onWrite = () => {}; 

function getWrite(bot) { // Генерирует метод отправки сообщения для бота
  return msg => {
    onWrite(bot.name, msg);
  };
}

module.exports.message = function message(nick, message) { // index.js выполнит эту функцию после отправки сообщения
  bots.forEach(bot => {
    try {
      bot.onMessage(nick, message, getWrite(bot));
    } catch (e) {
      console.error(e);
    }
  });
};

module.exports.connect = function message(nick) { // При соединении
  bots.forEach(bot => {
    try {
      bot.onConnect(nick, getWrite(bot));
    } catch (e) {
      console.error(e);
    }
  });
};

module.exports.disConnect = function message(nick) { // При отсоединении
  bots.forEach(bot => {
    try {
      bot.onDisconnect(nick, message, getWrite(bot));
    } catch (e) {
      console.error(e);
    }
  });
};

module.exports.command = function message(name, message) { // При выполнении команды
  bots.forEach(bot => {
    if (bot.name == name) {
      try {
        bot.onCommand(message, getWrite(bot));
      } catch (e) {
        console.error(e);
      }
    }
  });
};

module.exports.registerBot = function(bot) {
  bots.push(bot);
  return  getWrite(bot)
};

module.exports.onMessage = func => {
  onWrite = func;
};

Ssh-chat, частка 2

Што можна зрабіць з ботамі:

  • Манітор нагрузкі
  • разгортванне
  • Дошку задач

Хеш і соль

Чаму не ssh ключы? Таму што ssh ключы будуць на розных прыладах розныя
Створым файл у які будзе адказваць за праверку і стварэнне пароляў

// crypto.js
const crypto = require('crypto');

function genRandomString(length) {
  return crypto
    .randomBytes(Math.ceil(length / 2))
    .toString('hex')
    .slice(0, length);
}

function sha512(password, salt){
  const hash = crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */
  hash.update(password);
  const value = hash.digest('hex');
  return value
};

function checkPass(pass, obj){
  return obj.password == sha512(pass, obj.salt)
}

function encodePass(pass){
  const salt = genRandomString(16)
  return JSON.stringify({
    salt,
    password: sha512(pass, salt)
  })
}

module.exports.encodePass = encodePass
module.exports.checkPass = checkPass

Таксама скрыпт для салення і хэшавання пароля

// To generate password run node ./encryptPassword password
const { encodePass } =require('./crypto')
console.log(encodePass(process.argv[2]))

Абнаўляем у users.json і замест параўнання ў lobby.js выкарыстоўваем checkPassword

Вынік

У выніку ў нас есць чат па ssh з магчымасцямі па афармленні і ботамі.
Фінальны рэпазітар

Крыніца: habr.com

Дадаць каментар