File tree Expand file tree Collapse file tree 2 files changed +34
-2
lines changed Expand file tree Collapse file tree 2 files changed +34
-2
lines changed Original file line number Diff line number Diff 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'
Original file line number Diff line number Diff 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 /**
You can’t perform that action at this time.
0 commit comments