153 lines
6.2 KiB
TypeScript
153 lines
6.2 KiB
TypeScript
import { lookup } from 'node:dns/promises'
|
||
import type { LookupAddress } from 'node:dns'
|
||
import { request as httpRequest, validateHeaderName, validateHeaderValue } from 'node:http'
|
||
import { request as httpsRequest } from 'node:https'
|
||
import { BlockList, isIP } from 'node:net'
|
||
import { isPublicRoutableIp } from '@/lib/proxy-media-security'
|
||
|
||
const CALLBACK_TIMEOUT_MS = 8_000
|
||
const CALLBACK_TIMEOUT = '回调请求超时'
|
||
const CALLBACK_UNREACHABLE = '无法连接回调地址,请检查网络和证书'
|
||
const CALLBACK_DNS_FAILED = '无法解析回调域名'
|
||
const CALLBACK_UNSAFE = '回调地址指向受保护的网络'
|
||
const INTERNAL_ORIGINS_ENV = 'AUTO_LISTING_INTERNAL_CALLBACK_ORIGINS'
|
||
|
||
const internalAddresses = new BlockList()
|
||
internalAddresses.addSubnet('10.0.0.0', 8)
|
||
internalAddresses.addSubnet('172.16.0.0', 12)
|
||
internalAddresses.addSubnet('192.168.0.0', 16)
|
||
internalAddresses.addSubnet('fc00::', 7, 'ipv6')
|
||
|
||
const protectedAddresses = new BlockList()
|
||
protectedAddresses.addAddress('168.63.129.16')
|
||
protectedAddresses.addSubnet('2001::', 23, 'ipv6')
|
||
protectedAddresses.addSubnet('2002::', 16, 'ipv6')
|
||
|
||
const reservedHeaders = /^(?:host|content-(?:length|type|encoding)|connection|keep-alive|transfer-encoding|te|trailer|upgrade|expect|forwarded|x-forwarded-.+|proxy-.+)$/i
|
||
|
||
export class AutoListingCallbackError extends Error {
|
||
constructor(message: string, readonly status = 400) {
|
||
super(message)
|
||
}
|
||
}
|
||
|
||
export function validateCallbackAuth(headerName: string, headerValue: string) {
|
||
try {
|
||
validateHeaderName(headerName)
|
||
validateHeaderValue(headerName, headerValue)
|
||
} catch {
|
||
throw new AutoListingCallbackError('鉴权请求头的名称或值格式不正确')
|
||
}
|
||
if (reservedHeaders.test(headerName)) {
|
||
throw new AutoListingCallbackError('该请求头由素材库设置,请使用其他鉴权请求头')
|
||
}
|
||
}
|
||
|
||
function isTrustedInternalOrigin(origin: string) {
|
||
return (process.env[INTERNAL_ORIGINS_ENV] ?? '').split(',').some((value) => value.trim() === origin)
|
||
}
|
||
|
||
function isAllowedAddress(address: string, trustedInternal: boolean) {
|
||
const family = isIP(address) === 6 ? 'ipv6' : 'ipv4'
|
||
if (protectedAddresses.check(address, family)) return false
|
||
if (trustedInternal) return internalAddresses.check(address, family)
|
||
return isPublicRoutableIp(address)
|
||
}
|
||
|
||
export function normalizeAutoListingCallbackUrl(value: string) {
|
||
let url: URL
|
||
try {
|
||
if (!/^https?:\/\//i.test(value.trim()) || /[\\\u0000-\u001f\u007f]/.test(value)) throw new Error()
|
||
url = new URL(value.trim())
|
||
} catch {
|
||
throw new AutoListingCallbackError('回调地址仅支持完整的 HTTP 或 HTTPS 地址')
|
||
}
|
||
|
||
if (url.username || url.password || url.href.includes('?') || url.href.includes('#')) {
|
||
throw new AutoListingCallbackError('回调地址不能包含账号、密码、查询参数或片段,请在鉴权设置中填写凭据')
|
||
}
|
||
|
||
const trustedInternal = isTrustedInternalOrigin(url.origin)
|
||
if (!trustedInternal && url.protocol !== 'https:') {
|
||
throw new AutoListingCallbackError('公网回调须使用 HTTPS,内网回调须由运维授权')
|
||
}
|
||
|
||
const hostname = url.hostname.replace(/^\[|\]$/g, '')
|
||
if (
|
||
hostname.endsWith('.') ||
|
||
hostname === 'localhost' || hostname.endsWith('.localhost') ||
|
||
(isIP(hostname) ? !isAllowedAddress(hostname, trustedInternal)
|
||
: !trustedInternal && (!hostname.includes('.') || hostname.endsWith('.local') || hostname.endsWith('.internal')))
|
||
) {
|
||
throw new AutoListingCallbackError(CALLBACK_UNSAFE)
|
||
}
|
||
|
||
return url
|
||
}
|
||
|
||
async function resolveCallbackAddress(url: URL, signal: AbortSignal) {
|
||
const hostname = url.hostname.replace(/^\[|\]$/g, '')
|
||
const family = isIP(hostname)
|
||
if (family) return { address: hostname, family }
|
||
|
||
const trustedInternal = isTrustedInternalOrigin(url.origin)
|
||
const addresses = await new Promise<LookupAddress[]>((resolve, reject) => {
|
||
const onTimeout = () => reject(new AutoListingCallbackError(CALLBACK_TIMEOUT))
|
||
signal.addEventListener('abort', onTimeout, { once: true })
|
||
lookup(hostname, { all: true })
|
||
.then(resolve, () => reject(new AutoListingCallbackError(CALLBACK_DNS_FAILED)))
|
||
.finally(() => signal.removeEventListener('abort', onTimeout))
|
||
})
|
||
|
||
if (!addresses.length || addresses.some(({ address }) => !isAllowedAddress(address, trustedInternal))) {
|
||
throw new AutoListingCallbackError(CALLBACK_UNSAFE)
|
||
}
|
||
return addresses[0]
|
||
}
|
||
|
||
export async function validateAutoListingCallbackUrl(value: string) {
|
||
const url = normalizeAutoListingCallbackUrl(value)
|
||
await resolveCallbackAddress(url, AbortSignal.timeout(CALLBACK_TIMEOUT_MS))
|
||
return url.href
|
||
}
|
||
|
||
export async function postAutoListingCallback(
|
||
callbackUrl: string,
|
||
headers: Record<string, string>,
|
||
payload: unknown,
|
||
): Promise<number> {
|
||
const url = normalizeAutoListingCallbackUrl(callbackUrl)
|
||
const signal = AbortSignal.timeout(CALLBACK_TIMEOUT_MS)
|
||
const { address, family } = await resolveCallbackAddress(url, signal)
|
||
const send = url.protocol === 'https:' ? httpsRequest : httpRequest
|
||
const body = JSON.stringify(payload)
|
||
|
||
return new Promise((resolve, reject) => {
|
||
const request = send(url, {
|
||
method: 'POST',
|
||
headers: { ...headers, 'Content-Length': Buffer.byteLength(body) },
|
||
agent: false,
|
||
family,
|
||
signal,
|
||
// Connect to the checked IP and keep the original host for TLS and the Host header.
|
||
lookup: (_hostname, _options, callback) => callback(null, address, family),
|
||
}, (response) => {
|
||
resolve(response.statusCode!)
|
||
response.destroy()
|
||
})
|
||
request.on('error', () => reject(new AutoListingCallbackError(signal.aborted ? CALLBACK_TIMEOUT : CALLBACK_UNREACHABLE, 502)))
|
||
request.end(body)
|
||
})
|
||
}
|
||
|
||
export function summarizeAutoListingCallbackError(error: string | null, statusCode: number | null) {
|
||
if (statusCode !== null && (statusCode < 200 || statusCode >= 300)) {
|
||
return statusCode >= 300 && statusCode < 400 ? '回调返回重定向,请配置最终地址' : `接收方返回 HTTP ${statusCode}`
|
||
}
|
||
if (!error) return null
|
||
if ([CALLBACK_TIMEOUT, CALLBACK_UNREACHABLE, CALLBACK_DNS_FAILED, CALLBACK_UNSAFE, '素材已不可对外提供', '回调鉴权凭据不可用,请重新填写'].includes(error)) {
|
||
return error
|
||
}
|
||
return '投递失败,请检查回调配置和接收服务'
|
||
}
|