0

正如标题所说,我用 sockets.io 做了一个简单的聊天室,唯一的问题是我没有 xss 保护,而且我的伙伴们一直把无限循环作为用户名,所以你可以想象这有多么可怕:P。这是我的 app.js

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
var io  = require('socket.io').listen(server);

var usernames = {};

io.sockets.on('connection', function (socket) {
  // When the client emits 'sendchat' this listens and  executes
  socket.on('sendchat', function(data) {
    io.sockets.emit('updatechat', socket.username, data);
  });

  // When the client emites 'adduser' this listens and executes
  socket.on('adduser', function(username) {
    // Store the username in the socket session for this client
    socket.username = username;
    // add the client's username to the global list
    usernames[username] = username;
    // echo to the client they've connected
    socket.emit('updatechat', 'SERVER', 'you have connected');
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
    // update the list of users in chat, client-side
    io.sockets.emit('updateusers', usernames);
  });

  socket.on('disconnect', function() {
    // remove the username from global usernames list
    delete usernames[socket.username];
    // update list of users in chat, client-side
    io.sockets.emit('updateusers', usernames);
    // echo globally that the client has left
    socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
  });
});

我如何清理他们的输入以防止此类事情发生,我尝试使用谷歌搜索 XSS 保护预防、清理 html 输入和其他内容,但我什么也找不到!

客户代码:

socket.on('updatechat', function(username, data) {
  $('#conversation').append('<b>'+username+ ':</b>' + data.replace() + '<br>');
});
4

1 回答 1

2

正如我在评论中提到的,不要从您的服务器发送整个消息。您正在浪费带宽并将您的表示层混合到您的服务器中,这将使以后的事情变得非常麻烦。

而不是这个updatechat发射,尝试发送一些更有用userDisconnected的东西,比如用户名。让客户端代码显示客户端已断开连接的消息。

现在对于您的客户,请执行以下操作:

socket.on('userDisconnected', function(username, data) {
  $('#conversation').append(
    $('<span>').addClass('serverMessage').text(username + ' has disconnected'),
  );
});

这里的关键是你$.text()用来设置innerText。HTML变得无关紧要。

于 2013-05-12T23:25:49.617 回答