assertSameOrigin function

void assertSameOrigin(
  1. String url,
  2. String apiUrl,
  3. String parameterName
)

Throws unless url points at the same origin as apiUrl.

Requests carry the signed-in user's access token and the API key, so a URL that arrived as data - a download URL read out of a record another user wrote - must be checked before it is used, or those credentials go wherever it points. Scheme, host and port all have to match.

Implementation

void assertSameOrigin(String url, String apiUrl, String parameterName) {
  final target = Uri.tryParse(url);
  final api = Uri.tryParse(apiUrl);

  if (target == null || !target.hasScheme || target.host.isEmpty) {
    throw ArgumentError.value(url, parameterName, 'Is not a valid URL');
  }

  if (api == null) {
    throw ArgumentError.value(apiUrl, 'apiUrl', 'Is not a valid URL');
  }

  final matches =
      target.scheme == api.scheme &&
      target.host == api.host &&
      target.port == api.port;

  if (!matches) {
    throw ArgumentError.value(
      url,
      parameterName,
      'Must point at the Appstrax API (${api.origin})',
    );
  }
}