gongxiangp2/lib/product-package-remote-file.ts

149 lines
6.0 KiB
TypeScript

import type { LookupAddress } from 'node:dns'
import { lookup } from 'node:dns/promises'
import { createWriteStream } from 'node:fs'
import { request as httpRequest, type IncomingMessage } from 'node:http'
import { request as httpsRequest } from 'node:https'
import { BlockList, isIP } from 'node:net'
import { Transform } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { isPublicRoutableIp } from '@/lib/proxy-media-security'
const DOWNLOAD_TIMEOUT_MS = 60_000
const IDLE_TIMEOUT_MS = 10_000
const MAX_REDIRECTS = 3
const redirects = new Set([301, 302, 303, 307, 308])
const privateAddresses = new BlockList()
privateAddresses.addSubnet('10.0.0.0', 8)
privateAddresses.addSubnet('172.16.0.0', 12)
privateAddresses.addSubnet('192.168.0.0', 16)
privateAddresses.addSubnet('fc00::', 7, 'ipv6')
const protectedAddresses = new BlockList()
protectedAddresses.addAddress('168.63.129.16')
protectedAddresses.addSubnet('2001::', 23, 'ipv6')
protectedAddresses.addSubnet('2002::', 16, 'ipv6')
protectedAddresses.addSubnet('3fff::', 20, 'ipv6')
function hostname(url: URL) {
return url.hostname.replace(/^\[|\]$/g, '')
}
function isConfiguredInternalOrigin(url: URL) {
return (process.env.PRODUCT_PACKAGE_INTERNAL_DOWNLOAD_ORIGINS ?? '')
.split(',').some((origin) => origin.trim() === url.origin)
}
function assertAllowedAddress(address: string, url: URL) {
const family = isIP(address) === 6 ? 'ipv6' : 'ipv4'
if (protectedAddresses.check(address, family)
|| (!isPublicRoutableIp(address) && !(isConfiguredInternalOrigin(url) && privateAddresses.check(address, family)))) {
throw new Error('下载地址指向受保护的网络')
}
}
export function parseProductPackageRemoteUrl(value: string, base?: URL) {
const authority = /^(?:https?:)?\/\/([^/?#]*)/i.exec(value.trim())
if (!value.trim() || /[\\\u0000-\u001f\u007f]/.test(value)
|| (!base && !authority?.[1]) || authority?.[1].includes('@')) {
throw new Error('下载地址必须是无账号密码的 HTTP 或 HTTPS URL')
}
const url = URL.canParse(value, base) ? new URL(value, base) : null
if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:') || url.username || url.password) {
throw new Error('下载地址必须是无账号密码的 HTTP 或 HTTPS URL')
}
const host = hostname(url)
if (isIP(host)) {
assertAllowedAddress(host, url)
} else if (!isConfiguredInternalOrigin(url) && (
!host.includes('.') || /(?:\.localhost|\.local|\.internal|\.)$/.test(host)
)) {
throw new Error('下载地址指向受保护的网络')
}
return url
}
async function resolveAddress(url: URL, signal: AbortSignal) {
signal.throwIfAborted()
const host = hostname(url)
const family = isIP(host)
if (family) return { address: host, family }
const addresses = await new Promise<LookupAddress[]>((resolve, reject) => {
const abort = () => reject(new Error('下载文件已取消或超时'))
signal.addEventListener('abort', abort, { once: true })
lookup(host, { all: true }).then(resolve, () => reject(new Error('无法解析下载地址')))
.finally(() => signal.removeEventListener('abort', abort))
})
if (!addresses.length) throw new Error('无法解析下载地址')
for (const { address } of addresses) assertAllowedAddress(address, url)
return addresses[0]
}
async function requestFile(url: URL, signal: AbortSignal) {
const { address, family } = await resolveAddress(url, signal)
const send = url.protocol === 'https:' ? httpsRequest : httpRequest
return new Promise<IncomingMessage>((resolve, reject) => {
const req = send(url, {
method: 'GET',
agent: false,
family,
signal,
headers: { 'Accept-Encoding': 'identity' },
// Keep the original host for TLS and connect to the IP checked above.
lookup: (_hostname, _options, callback) => callback(null, address, family),
}, resolve)
req.setTimeout(IDLE_TIMEOUT_MS, () => {
const error = new Error('下载文件超时')
reject(error)
req.destroy(error)
})
req.on('error', () => {
reject(new Error(signal.aborted ? '下载文件已取消或超时' : '无法连接文件下载地址'))
})
req.end()
})
}
export async function downloadProductPackageRemoteFile(
value: string, destination: string, maxBytes: number, callerSignal?: AbortSignal,
): Promise<number> {
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new Error('下载文件大小限制无效')
const timeout = AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS)
const signal = callerSignal ? AbortSignal.any([callerSignal, timeout]) : timeout
let url = parseProductPackageRemoteUrl(value)
for (let hop = 0; ; hop += 1) {
// Node's HTTP request handles one hop only. Resolve and pin every redirect.
const response = await requestFile(url, signal)
const status = response.statusCode ?? 0
if (redirects.has(status)) {
response.destroy()
if (hop >= MAX_REDIRECTS || !response.headers.location) throw new Error('下载地址重定向无效或次数过多')
const next = parseProductPackageRemoteUrl(response.headers.location, url)
if (next.origin !== url.origin) throw new Error('下载地址不允许跨站重定向')
url = next
continue
}
if (status !== 200 || (response.headers['content-encoding'] && response.headers['content-encoding'] !== 'identity')) {
response.destroy()
throw new Error('下载服务未返回完整的原始文件')
}
if (Number(response.headers['content-length']) > maxBytes) {
response.destroy()
throw new Error('下载文件超过声明大小或单文件上限')
}
let size = 0
const byteLimit = new Transform({
transform(chunk: Buffer, _encoding, callback) {
size += chunk.length
callback(size > maxBytes ? new Error('下载文件超过声明大小或单文件上限') : null, chunk)
},
})
await pipeline(response, byteLimit, createWriteStream(destination, { flags: 'wx' }), { signal })
if (!size) throw new Error('下载文件为空')
return size
}
}