From aa6e05532ee7b71add6024d5002e69f4b033cc01 Mon Sep 17 00:00:00 2001 From: John Bayly <3430117+oobayly@users.noreply.github.com.> Date: Mon, 23 Sep 2024 16:00:54 +0100 Subject: [PATCH] issue/910: Fix CORS warning for localhost See maplibre/maputnik#910 Don't show CORS warning for localhost --- src/components/InputUrl.tsx | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/src/components/InputUrl.tsx b/src/components/InputUrl.tsx index a11239db..83c71bb2 100644 --- a/src/components/InputUrl.tsx +++ b/src/components/InputUrl.tsx @@ -10,16 +10,22 @@ function validate(url: string, t: TFunction): JSX.Element | undefined { } let error; - const getProtocol = (url: string) => { + const getUrlParams = (url: string) => { + let protocol: string | undefined; + let isLocal = false; + try { const urlObj = new URL(url); - return urlObj.protocol; - } - catch (err) { - return undefined; + + protocol = urlObj.protocol; + // Basic check against localhost; 127.0.0.1/8 and IPv6 localhost [::1] + isLocal = /^(localhost|\[::1\]|127(.[0-9]{1,3}){3})/i.test(urlObj.hostname); + } catch (err) { } + + return { protocol, isLocal }; }; - const protocol = getProtocol(url); + const {protocol, isLocal} = getUrlParams(url); const isSsl = window.location.protocol === "https:"; if (!protocol) { @@ -40,7 +46,8 @@ function validate(url: string, t: TFunction): JSX.Element | undefined { else if ( protocol && protocol === "http:" && - window.location.protocol === "https:" + window.location.protocol === "https:" && + !isLocal ) { error = ( @@ -76,10 +83,10 @@ type FieldUrlState = { class FieldUrlInternal extends React.Component { static defaultProps = { - onInput: () => {}, + onInput: () => { }, } - constructor (props: FieldUrlInternalProps) { + constructor(props: FieldUrlInternalProps) { super(props); this.state = { error: validate(props.value, props.t), @@ -100,7 +107,7 @@ class FieldUrlInternal extends React.Component