validateUrl function

UrlValidation validateUrl(
  1. String urlString
)

Validate a URL for fetching.

Implementation

UrlValidation validateUrl(String urlString) {
  if (urlString.length > maxUrlLength) {
    return InvalidUrl('URL exceeds maximum length of $maxUrlLength characters');
  }

  Uri uri;
  try {
    uri = Uri.parse(urlString);
  } catch (_) {
    return const InvalidUrl('Invalid URL format');
  }

  if (!uri.hasScheme || (!uri.isScheme('http') && !uri.isScheme('https'))) {
    return const InvalidUrl('URL must use http or https scheme');
  }

  if (uri.host.isEmpty) {
    return const InvalidUrl('URL must have a hostname');
  }

  // Require at least 2 parts in hostname
  if (!uri.host.contains('.')) {
    return const InvalidUrl('Single-label hostname not allowed');
  }

  // Block embedded credentials
  if (uri.userInfo.isNotEmpty) {
    return const InvalidUrl('URLs with embedded credentials not allowed');
  }

  return ValidUrl(uri);
}