I need to write a function in Python that makes sure the user entered a valid JavaScript origin. If I understand it correctly, the origin includes the scheme, hostname and port (port and scheme might be implicit, defaulting to 80 and http respectively), so would this be a correct way to validate it?
import urlparse
def validate_javascript_origin(origin):
parsed = urlparse.urlsplit(origin)
if parsed.scheme and parsed.scheme not in ["http", "https"]:
raise ValueError("Only the http and https url schemes are supported.")
if not parsed.netloc:
raise ValueError("The origin must include a hostname.")
if parsed.path or parsed.query or parsed.fragment:
raise ValueError("The origin must not contain a path, query string or fragment.")
The origin will be used to pass as the preferredOrigin to window.postMessage.
The main thing I'm worried about is that I'm not sure how credentials in the url (username:[email protected]) are handled.
Going to http://[email protected]
, and getting location.origin
in javascript returns http://frederikcreemers.be
, so the origin doesn't include credentials. Would it be sufficient to add a condition like this to the function above:
if "@" in parsed.netloc:
raise ValueError("The origin must not contain credentials.")