Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -277,14 +277,17 @@ res.jsonp = function jsonp(obj) {
callback = callback[0];
}

// sanitize callback before entering JSONP branch
if (typeof callback === 'string' && callback.length !== 0) {
// restrict callback charset
callback = callback.replace(/[^\[\]\w$.]/g, '');
}

// jsonp
if (typeof callback === 'string' && callback.length !== 0) {
this.set('X-Content-Type-Options', 'nosniff');
this.set('Content-Type', 'text/javascript');

// restrict callback charset
callback = callback.replace(/[^\[\]\w$.]/g, '');

if (body === undefined) {
// empty argument
body = ''
Expand Down
41 changes: 41 additions & 0 deletions test/res.jsonp.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,47 @@ describe('res', function(){
.expect(200, /foobar\(\{\}\);/, done);
})

it('should fall back to JSON when callback sanitizes to empty', function(done){
var app = express();

app.use(function(req, res){
res.jsonp({ count: 1 });
});

request(app)
.get('/?callback=!!!')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '{"count":1}', done);
})

it('should fall back to JSON for callback with only special chars', function(done){
var app = express();

app.get('/', function(req, res){
res.type('application/vnd.example+json');
res.jsonp({ hello: 'world' });
});

request(app)
.get('/?callback=%3C%3E%21%40%23')
.expect('Content-Type', 'application/vnd.example+json; charset=utf-8')
.expect(utils.shouldNotHaveHeader('X-Content-Type-Options'))
.expect(200, '{"hello":"world"}', done);
})

it('should use sanitized callback with mixed valid/invalid chars', function(done){
var app = express();

app.use(function(req, res){
res.jsonp({ count: 1 });
});

request(app)
.get('/?callback=foo!bar')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /foobar\(\{"count":1\}\);/, done);
})

it('should escape utf whitespace', function(done){
var app = express();

Expand Down