正如标题所说,我用 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>');
});