unis-oa/frontend/src/utils/url.ts

170 lines
6.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* 验证并规范化 URL
* 默认只接受绝对 URL(以 http:// 或 https:// 开头),可按需允许相对路径
* @param value 用户输入的 URL
* @returns 规范化后的 URL,如果无效则返回空字符串
*/
type SanitizeOptions = {
allowRelative?: boolean
allowDataUrl?: boolean
}
/** 查询串与片段里的键值:`URLSearchParams` 不在时也读得出来(免登票据就挂在片段里)。 */
function queryReader(search: string, hash: string): LooseUrlQuery {
const read = (source: string, key: string): string | null => {
const text = String(source || '').replace(/^[?#]/, '')
if (!text) return null
const needle = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const match = new RegExp('(?:^|[&;])' + needle + '(?:=([^&;]*))?(?:[&;]|$)').exec(text)
if (!match) return null
const raw = (match[1] || '').replace(/\+/g, ' ')
try {
return decodeURIComponent(raw)
} catch {
return raw
}
}
return {
get: (key: string) => {
const fromSearch = read(search, key)
if (fromSearch !== null) return fromSearch
return read(String(hash || '').replace(/^#/, ''), key)
},
}
}
/**
* 拆一个 http(s) 地址。
*
* `new URL()` 在 IE 上整个不存在(不是"选项不全",是构造函数都没有),而这一层是链接格子、
* 带出值里那串网址、嵌入页回填的 origin 校验共用的读法:少了它,老引擎上这些地址一律
* 变成"看不见的链接"。这里保留原生 `URL` 的规范化结果(现代浏览器一字不变),
* 原生没有就照 RFC 3986 那几位自己拆,拆不出来才回 null。
*/
export interface LooseUrlQuery {
get(key: string): string | null
}
export interface LooseUrl {
href: string
origin: string
protocol: string
host: string
hostname: string
port: string
pathname: string
search: string
hash: string
/** 只给到读值这一手:`URLSearchParams` 在老引擎上不存在,这里自带一份。 */
searchParams: LooseUrlQuery
}
const URL_SHAPE = /^(https?):\/\/([^/?#]+)([^?#]*)(\?[^#]*)?(#.*)?$/i
const HOST_SHAPE = /^([^:@/]+)(?::(\d+))?$/
/** 相对地址需要一个基准;调用方没给且当前也不在浏览器里,就只能认绝对地址。 */
export function parseHttpUrl(value: unknown, base?: string): LooseUrl | null {
const raw = String(value ?? '').trim()
if (!raw) return null
if (typeof URL === 'function') {
// 原生在,就以它为准:它说"这地址不行"就是不行(`https://v1.2` 这种末段是纯数字的
// 主机名会被拒),不能再由下面的正则翻案。
try {
const parsed = base ? new URL(raw, base) : new URL(raw)
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null
return {
searchParams: queryReader(parsed.search, parsed.hash),
href: parsed.href,
origin: parsed.origin,
protocol: parsed.protocol,
host: parsed.host,
hostname: parsed.hostname,
port: parsed.port,
pathname: parsed.pathname,
search: parsed.search,
hash: parsed.hash,
}
} catch {
return null
}
}
// 走到这里只剩一种可能:这台引擎根本没有 `URL`(IE 那一档),自己拆
const absolute = URL_SHAPE.exec(raw)
if (absolute) {
const protocol = `${absolute[1].toLowerCase()}:`
const authority = absolute[2]
const hostMatch = HOST_SHAPE.exec(authority)
if (!hostMatch) return null
const hostname = hostMatch[1]
const port = hostMatch[2] || ''
const pathname = absolute[3] || '/'
const search = absolute[4] || ''
const hash = absolute[5] || ''
return {
searchParams: queryReader(search, hash),
href: `${protocol}//${authority}${pathname}${search}${hash}`,
origin: port ? `${protocol}//${hostname}:${port}` : `${protocol}//${hostname}`,
protocol,
host: port ? `${hostname}:${port}` : hostname,
hostname,
port,
pathname,
search,
hash,
}
}
// 相对地址:原生 URL 不在时,拿基准(通常是本站 origin)拼一个出来
const baseInfo = base ? URL_SHAPE.exec(String(base).trim()) : null
if (!baseInfo || !/^[/?#]/.test(raw)) return null
const protocol = `${baseInfo[1].toLowerCase()}:`
const host = baseInfo[2]
const pathname = raw.startsWith('/') ? raw.split(/[?#]/)[0] : baseInfo[3].replace(/\/[^/]*$/, '') + raw.split(/[?#]/)[0]
const queryIndex = raw.search(/[?#]/)
const tail = queryIndex === -1 ? '' : raw.slice(queryIndex)
return {
searchParams: queryReader(tail.indexOf('?') === 0 ? tail : '', tail.indexOf('#') === -1 ? '' : tail.slice(tail.indexOf('#'))),
href: `${protocol}//${host}${pathname}${tail}`,
origin: `${protocol}//${host}`,
protocol,
host,
hostname: HOST_SHAPE.exec(host)?.[1] || host,
port: '',
pathname,
search: tail.startsWith('?') ? tail.split('#')[0] : '',
hash: tail.includes('#') ? tail.slice(tail.indexOf('#')) : '',
}
}
/** 只要 origin(嵌入页 postMessage 的 targetOrigin 就吃它):认不出来回空串。 */
export function httpOrigin(value: unknown, base?: string): string {
const parsed = parseHttpUrl(value, base)
if (parsed?.origin && parsed.origin !== 'null') return parsed.origin
const fallback = typeof base === 'string' ? base : (typeof window !== 'undefined' ? window.location.origin : '')
return String(fallback || '').replace(/\/+$/, '')
}
export function sanitizeUrl(value: string, options: SanitizeOptions = {}): string {
const trimmed = value.trim()
if (!trimmed) {
return ''
}
if (options.allowRelative && trimmed.startsWith('/') && !trimmed.startsWith('//')) {
return trimmed
}
// 允许 data:image/ 开头的 data URL(仅限图片类型)
if (options.allowDataUrl && trimmed.startsWith('data:image/')) {
return trimmed
}
// 只接受绝对 URL,不使用 base URL 来避免相对路径被解析为当前域名
// 检查是否以 http:// 或 https:// 开头
if (!trimmed.match(/^https?:\/\//i)) {
return ''
}
const parsed = parseHttpUrl(trimmed)
return parsed ? parsed.href : ''
}