Created
August 26, 2024 19:45
-
-
Save CristianoRC/0f54d686aee1370b23c518b99dfdc4a9 to your computer and use it in GitHub Desktop.
Código para correção de Open Redirect, permitindo apenas mesma origem ou páginas internas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const isUrl = (url) => { | |
try { | |
new URL(url); | |
return true; | |
} catch { | |
return false; | |
} | |
}; | |
const isSameOrigin = (url) => { | |
try { | |
const currentOrigin = window.location.origin; | |
const targetOrigin = new URL(url, currentOrigin).origin; | |
return currentOrigin === targetOrigin; | |
} catch { | |
return false; | |
} | |
}; | |
const formatPath = (path) => { | |
if (isUrl(path)) | |
return path; | |
return path.startsWith('/') ? path : `/${path}`; | |
}; | |
const redirect = (path) => { | |
if (isUrl(path) && !isSameOrigin(path)) { | |
return; | |
} | |
const formattedPath = formatPath(path) | |
window.location.href = formattedPath; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment