- PVSM.RU - https://www.pvsm.ru -
Привет. Это 2 статья из цикла ssh-chat.
Что мы сделаем:
На данный момент реализована поддержка следующих функций оформления:
@color
@bold
@underline
@hex
@box
объекте под названием methods
[1]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) + '!'
})
Markdown ну очень удобен так что добавим его с помощью marked terminal [2]
// 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)
Как это будет работать
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 ключи? Потому что 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 с возможностями по оформлению и ботами.
Финальный репозиторий [3]
Автор: maximmasterr
Источник [4]
Сайт-источник PVSM.RU: https://www.pvsm.ru
Путь до страницы источника: https://www.pvsm.ru/ssh/330108
Ссылки в тексте:
[1] объекте под названием methods
: https://github.com/maximmasterr/ssh-server/blob/9d494e08b13b39b91e5fd7081d52d01ece5f79b9/parserExec.js#L4-L28
[2] marked terminal: https://www.npmjs.com/package/marked-terminal
[3] Финальный репозиторий: https://github.com/maximmasterr/ssh-server/tree/v2
[4] Источник: https://habr.com/ru/post/467543/?utm_source=habrahabr&utm_medium=rss&utm_campaign=467543
Нажмите здесь для печати.