Ssh-chat, cuid 2

Dia duit, Habr. Seo é an dara alt sa tsraith ssh-chat.

Cad a dhéanfaimid:

  • Cuirimis leis an gcumas do chuid feidhmeanna dearaidh féin a chruthú
  • Cuirimis tacaíocht marcála síos
  • Cuirimis tacaíocht bot leis
  • Méadaigh slándáil pasfhocail (hash agus salann)
    Tá brón orainn, ach ní bheidh aon chomhaid a sheoladh.

Gnéithe dearadh saincheaptha

Faoi láthair, tacaítear leis na feidhmeanna dearaidh seo a leanas:

  • @color
  • @bold
  • @underline
  • @hex
  • @box
    Ach is fiú an cumas chun do chuid feidhmeanna féin a chruthú a chur leis:
    Stóráiltear na feidhmeanna go léir i объекте под названием methods
    Mar sin beidh sé go leor chun feidhm a chruthú registerMethod:

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

Ní mór duit an modh seo a thabhairt ar ais freisin tar éis duit an freastalaí a chruthú

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

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

Anois, agus freastalaí á chruthú againn, is féidir linn modhanna formáidithe a chlárú. Sampla:

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

chat({})

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

Ssh-chat, cuid 2

tacaíocht marcála síos

Tá Markdown an-áisiúil, mar sin cuirimis é ag baint úsáide as críochfort marcáilte

// 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, cuid 2

Bots

Conas a oibreoidh sé

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 is féidir a bheith ar a dtugtar ag baint úsáide as @bot(botBob){Command}

Tá cur síos sa chomhad ar gach rud le haghaidh oibriú le róbónna:

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, cuid 2

Cad is féidir leat a dhéanamh le róbónna:

  • Monatóir luchtaithe
  • imscaradh
  • Clár tasc

Hash agus salann

Cén fáth nach bhfuil eochracha ssh? Toisc go mbeidh eochracha ssh difriúil ar ghléasanna éagsúla
Déanaimis comhad a chruthú a bheidh freagrach as pasfhocail a sheiceáil agus a chruthú

// 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

Chomh maith leis sin script le haghaidh shailleadh agus hashing an focal faire

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

Déanaimid nuashonrú in users.json agus in ionad comparáid a dhéanamh i lobby.js úsáidimid checkPassword

Iomlán na

Mar thoradh air sin, tá comhrá againn trí ssh le cumais dearaidh agus róbónna.
Stór deiridh

Foinse: will.com

Add a comment