Ir para o conteúdo

CódigoNão tentada

isSafeUrl (allowlist contra SSRF)

Dificuldade: fácil

Escreva isSafeUrl(input) para um servidor que busca URLs enviadas por usuários. Retorne true somente para URLs https: válidas cujo host seja exatamente um dos ALLOWED_HOSTS. Imitações como api.stripe.com.evil.com devem falhar. Dica: faça o parse com new URL() em vez de checar a string.

Ver solução de referência
// Hosts the server is allowed to call on a user's behalf.
export const ALLOWED_HOSTS = ['api.stripe.com', 'images.example.com'];
export function isSafeUrl(input: string): boolean {
let url: URL;
try {
url = new URL(input);
} catch {
return false; // not a valid absolute URL
}
if (url.protocol !== 'https:') return false;
// Compare the parsed hostname exactly. A string check like input.includes('api.stripe.com')
// would let through https://api.stripe.com.evil.com or https://evil.com/?api.stripe.com
return ALLOWED_HOSTS.includes(url.hostname);
}
Carregando editor…