safeReturnToUrl.ts raw

   1  // Parses a return_to URL and only returns it if it is a
   2  // http or https URL. Relative URLs are resolved against the
   3  // current origin.
   4  export function safeReturnToUrl(returnTo: string | null): string | undefined {
   5    if (!returnTo) {
   6      return undefined;
   7    }
   8    try {
   9      const url = new URL(returnTo, window.location.origin);
  10      if (url.protocol === "http:" || url.protocol === "https:") {
  11        return url.toString();
  12      }
  13    } catch {
  14      // ignore invalid URLs
  15    }
  16    return undefined;
  17  }
  18