normalizeAuthOrigin function

String normalizeAuthOrigin(
  1. Uri origin, {
  2. required bool requireHttps,
})

Normalizes an HTTP or HTTPS origin for boundary comparisons.

Rejects credentials, paths other than /, queries, fragments, and empty hosts. Scheme and host are lowercased and default ports are omitted. Throws ArgumentError when the origin is invalid or violates requireHttps.

Implementation

String normalizeAuthOrigin(Uri origin, {required bool requireHttps}) {
  final scheme = origin.scheme.toLowerCase();
  if ((scheme != 'http' && scheme != 'https') ||
      (requireHttps && scheme != 'https') ||
      origin.host.isEmpty ||
      origin.userInfo.isNotEmpty ||
      origin.query.isNotEmpty ||
      origin.fragment.isNotEmpty ||
      (origin.path.isNotEmpty && origin.path != '/')) {
    throw ArgumentError.value(
      origin,
      'trustedOrigins',
      requireHttps
          ? 'must be an HTTPS origin without credentials, path, query, or fragment'
          : 'must be an HTTP origin without credentials, path, query, or fragment',
    );
  }
  final defaultPort = scheme == 'https' ? 443 : 80;
  final port = origin.hasPort && origin.port != defaultPort
      ? ':${origin.port}'
      : '';
  final normalizedHost = origin.host.contains(':')
      ? '[${origin.host.toLowerCase()}]'
      : origin.host.toLowerCase();
  return '$scheme://$normalizedHost$port';
}