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
34 changes: 19 additions & 15 deletions lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -283,25 +283,29 @@ res.jsonp = function jsonp(obj) {

// 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 = ''
} else if (typeof body === 'string') {
// replace chars not allowed in JavaScript that are in JSON
body = body
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
// sanitizing can empty the callback (eg. `?callback=!!!`), which would
// produce a syntactically invalid response, so fall back to plain JSON
if (callback.length !== 0) {
this.set('X-Content-Type-Options', 'nosniff');
this.set('Content-Type', 'text/javascript');

if (body === undefined) {
// empty argument
body = ''
} else if (typeof body === 'string') {
// replace chars not allowed in JavaScript that are in JSON
body = body
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}

// the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"
// the typeof check is just to reduce client error noise
body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
// the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"
// the typeof check is just to reduce client error noise
body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
}
}

return this.send(body);
Expand Down
26 changes: 26 additions & 0 deletions test/res.jsonp.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,32 @@ describe('res', function(){
.expect(200, /foobar\(\{\}\);/, done);
})

it('should fall back to json when the sanitized callback is empty', function(done){
var app = express();

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

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

it('should still use a partially sanitized callback', function(done){
var app = express();

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

request(app)
.get('/?callback=%20foo%20')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /^\/\*\*\/ typeof foo === 'function' && foo\(\{"count":1\}\);$/, done);
})

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

Expand Down