fengmk2
2025-07-27 15:25:47 +08:00
committed by GitHub
parent 6e51eb1516
commit 422c551c63
2 changed files with 34 additions and 2 deletions

View File

@@ -12,6 +12,22 @@ describe('ctx.back([alt])', () => {
assert.equal(ctx.response.header.location, '/login')
})
it('should redirect to the same origin referrer', () => {
const ctx = context()
ctx.req.headers.host = 'example.com'
ctx.req.headers.referrer = 'https://example.com/login'
ctx.back()
assert.equal(ctx.response.header.location, 'https://example.com/login')
})
it('should redirect to root if the same origin referrer is not present', () => {
const ctx = context()
ctx.req.headers.host = 'example.com'
ctx.req.headers.referrer = 'https://other.com/login'
ctx.back()
assert.equal(ctx.response.header.location, '/')
})
it('should redirect to Referer', () => {
const ctx = context()
ctx.req.headers.referer = '/login'

View File

@@ -320,8 +320,24 @@ module.exports = {
*/
back (alt) {
const url = this.ctx.get('Referrer') || alt || '/'
this.redirect(url)
const referrer = this.ctx.get('Referrer')
if (referrer) {
// referrer is a relative path
if (referrer.startsWith('/')) {
this.redirect(referrer)
return
}
// referrer is an absolute URL, check if it's the same origin
const url = new URL(referrer, this.ctx.href)
if (url.host === this.ctx.host) {
this.redirect(referrer)
return
}
}
// no referrer, use alt or '/'
this.redirect(alt || '/')
},
/**