Skip to content

Commit 422c551

Browse files
authored
Merge commit from fork
GHSA-jgmv-j7ww-jx2x close #1892
1 parent 6e51eb1 commit 422c551

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

__tests__/response/back.test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,22 @@ describe('ctx.back([alt])', () => {
1212
assert.equal(ctx.response.header.location, '/login')
1313
})
1414

15+
it('should redirect to the same origin referrer', () => {
16+
const ctx = context()
17+
ctx.req.headers.host = 'example.com'
18+
ctx.req.headers.referrer = 'https://example.com/login'
19+
ctx.back()
20+
assert.equal(ctx.response.header.location, 'https://example.com/login')
21+
})
22+
23+
it('should redirect to root if the same origin referrer is not present', () => {
24+
const ctx = context()
25+
ctx.req.headers.host = 'example.com'
26+
ctx.req.headers.referrer = 'https://other.com/login'
27+
ctx.back()
28+
assert.equal(ctx.response.header.location, '/')
29+
})
30+
1531
it('should redirect to Referer', () => {
1632
const ctx = context()
1733
ctx.req.headers.referer = '/login'

lib/response.js

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -320,8 +320,24 @@ module.exports = {
320320
*/
321321

322322
back (alt) {
323-
const url = this.ctx.get('Referrer') || alt || '/'
324-
this.redirect(url)
323+
const referrer = this.ctx.get('Referrer')
324+
if (referrer) {
325+
// referrer is a relative path
326+
if (referrer.startsWith('/')) {
327+
this.redirect(referrer)
328+
return
329+
}
330+
331+
// referrer is an absolute URL, check if it's the same origin
332+
const url = new URL(referrer, this.ctx.href)
333+
if (url.host === this.ctx.host) {
334+
this.redirect(referrer)
335+
return
336+
}
337+
}
338+
339+
// no referrer, use alt or '/'
340+
this.redirect(alt || '/')
325341
},
326342

327343
/**

0 commit comments

Comments
 (0)