sameHostUrl function
url when it points to the same host as the host header, else null.
- a path like
/formis kept.//evil.comand/\evil.comare not paths, browsers read them as other sites. - an
httporhttpsurl is kept when its host and port are the same ashost. - anything else (other sites,
javascript:, bad urls) gives null.
Implementation
String? sameHostUrl(String? url, String? host) {
if (url == null) return null;
String u = url.trim();
if (u.isEmpty || u.contains('\\') || _hasControlChar(u)) return null;
if (u.startsWith('/')) {
return u.startsWith('//') ? null : u;
}
if (host == null || host.trim().isEmpty) return null;
Uri? uri = Uri.tryParse(u);
if (uri == null || !(uri.isScheme('http') || uri.isScheme('https'))) {
return null;
}
if (uri.host.isEmpty || uri.userInfo.isNotEmpty) return null;
Uri? hostUri = Uri.tryParse('${uri.scheme}://${host.trim()}');
if (hostUri == null) return null;
if (uri.host.toLowerCase() != hostUri.host.toLowerCase()) return null;
if (uri.port != hostUri.port) return null;
return u;
}