navigation-url.ts (2045B)
1 const maximumBytes = 8192; 2 const sentinel = 'https://navigation.invalid'; 3 4 function text(value: unknown): value is string { 5 if ( 6 typeof value !== 'string' || 7 value.length === 0 || 8 value.length > maximumBytes || 9 !value.isWellFormed() || 10 /\s/u.test(value) 11 ) 12 return false; 13 if (new TextEncoder().encode(value).length > maximumBytes) return false; 14 for (const character of value) { 15 const code = character.charCodeAt(0); 16 if (code <= 32 || (code >= 127 && code <= 159) || character === '\\') 17 return false; 18 } 19 try { 20 const decoded = decodeURIComponent(value); 21 for (const character of decoded) { 22 const code = character.charCodeAt(0); 23 if (code < 32 || (code >= 127 && code <= 159) || character === '\\') 24 return false; 25 } 26 } catch { 27 return false; 28 } 29 return true; 30 } 31 32 export function internalHref(value: unknown): string | undefined { 33 if (!text(value)) return undefined; 34 if (!( 35 (value[0] === '/' && value[1] !== '/') || 36 value[0] === '?' || 37 value[0] === '#' 38 )) 39 return undefined; 40 try { 41 const url = new URL(value, sentinel); 42 if (url.origin !== sentinel || url.username || url.password) 43 return undefined; 44 return value; 45 } catch { 46 return undefined; 47 } 48 } 49 50 export function navigationHref(value: unknown): string | undefined { 51 if (!text(value)) return undefined; 52 const internal = internalHref(value); 53 if (internal !== undefined) return internal; 54 if (!/^(https:\/\/|mailto:|tel:)/i.test(value)) return undefined; 55 if (/^https:/i.test(value) && !/^https:\/\/[^/?#]/i.test(value)) 56 return undefined; 57 try { 58 const url = new URL(value, sentinel); 59 if (url.username || url.password || /^https:\/\/[^/?#]*@/i.test(value)) 60 return undefined; 61 if (url.protocol === 'https:' && !url.hostname) return undefined; 62 if ( 63 (url.protocol === 'mailto:' || url.protocol === 'tel:') && 64 (!url.pathname || url.host !== '') 65 ) 66 return undefined; 67 return value; 68 } catch { 69 return undefined; 70 } 71 }