- 增加 CORS/CSP/安全响应头与代理信任配置 - 引入 URL 白名单与私网开关,校验上游与价格源 - 改善 API Key 处理与网关错误返回 - 管理端设置隐藏敏感字段并优化前端提示 - 增加计费熔断与相关配置示例 测试: go test ./...
38 lines
958 B
TypeScript
38 lines
958 B
TypeScript
/**
|
||
* 验证并规范化 URL
|
||
* 默认只接受绝对 URL(以 http:// 或 https:// 开头),可按需允许相对路径
|
||
* @param value 用户输入的 URL
|
||
* @returns 规范化后的 URL,如果无效则返回空字符串
|
||
*/
|
||
type SanitizeOptions = {
|
||
allowRelative?: boolean
|
||
}
|
||
|
||
export function sanitizeUrl(value: string, options: SanitizeOptions = {}): string {
|
||
const trimmed = value.trim()
|
||
if (!trimmed) {
|
||
return ''
|
||
}
|
||
|
||
if (options.allowRelative && trimmed.startsWith('/')) {
|
||
return trimmed
|
||
}
|
||
|
||
// 只接受绝对 URL,不使用 base URL 来避免相对路径被解析为当前域名
|
||
// 检查是否以 http:// 或 https:// 开头
|
||
if (!trimmed.match(/^https?:\/\//i)) {
|
||
return ''
|
||
}
|
||
|
||
try {
|
||
const parsed = new URL(trimmed)
|
||
const protocol = parsed.protocol.toLowerCase()
|
||
if (protocol !== 'http:' && protocol !== 'https:') {
|
||
return ''
|
||
}
|
||
return parsed.toString()
|
||
} catch {
|
||
return ''
|
||
}
|
||
}
|