109 lines
5.7 KiB
JavaScript
109 lines
5.7 KiB
JavaScript
// Cloudflare Pages Function:**第一方**图片代理(同源 /api/img)。
|
||
// 目的:豆包(火山 TOS)等图床**不返回 CORS 头**,浏览器无法 fetch ⇒ 下载、缩略图归档、
|
||
// 本地原图备份全部拿不到字节。经本站代理转发后由本站给出 CORS 头,前端即可正常读取。
|
||
// 用法:GET /api/img?url=<encodeURIComponent(https 图片地址)>
|
||
//
|
||
// 安全边界(H2 加固):
|
||
// - 仅接受**同源**调用:若请求带 Origin 头,其 host 必须与本站一致。
|
||
// - 仅 https、仅允许常见图片/对象存储域名(避免成为开放代理/SSRF),仅透传 image/* 响应。
|
||
// - **手动跟随重定向**:每一跳都对目标 host 重新做白名单校验(原实现 redirect:'follow' 只校验初始
|
||
// host,可被 302 逃逸到任意主机),并限制跳数。
|
||
// - **响应大小上限**:先看 content-length,超限即拒;无 content-length 时按流裁剪(防超大响应耗尽配额)。
|
||
// - 不再返回 Access-Control-Allow-Origin: *(同源调用本就不需要 CORS)。
|
||
export function onRequest(context) {
|
||
return handle(context.request)
|
||
}
|
||
|
||
const ALLOW_HOSTS = [
|
||
/(^|\.)volces\.com$/i, // 火山引擎 / TOS(豆包 Seedream 图床)
|
||
/(^|\.)aliyuncs\.com$/i, // 阿里云 OSS(tuzi 文档示例图床)
|
||
/(^|\.)myqcloud\.com$/i, // 腾讯云 COS
|
||
/(^|\.)qiniucdn\.com$/i,
|
||
/(^|\.)cloudfront\.net$/i,
|
||
/(^|\.)googleusercontent\.com$/i,
|
||
/(^|\.)openai\.org$/i,
|
||
/(^|\.)oaistatic\.com$/i,
|
||
/(^|\.)blob\.core\.windows\.net$/i,
|
||
]
|
||
const MAX_BYTES = 25 * 1024 * 1024 // 单张图片上限 25MB(生成图远小于此;防超大响应)
|
||
const MAX_REDIRECTS = 3
|
||
|
||
// 安全头(2026-10-20 加,H1):Cloudflare Pages 的 `_headers` **不作用于 Functions 响应**
|
||
// (https://developers.cloudflare.com/pages/configuration/headers/)⇒ 静态资源有 CSP/nosniff,
|
||
// 而本函数(及 plugins 函数)原本**一个安全头都没有**。这不是可利用漏洞(每个响应都显式
|
||
// 设了 Content-Type),但属于纵深防御缺口:将来若有端点返回用户影响的内容且漏设 Content-Type,
|
||
// 浏览器会自行嗅探类型 ⇒ 可能演变成 XSS。故在**每个** Response 显式补齐 nosniff + Referrer-Policy。
|
||
const SECURITY_HEADERS = {
|
||
'X-Content-Type-Options': 'nosniff',
|
||
'Referrer-Policy': 'no-referrer',
|
||
}
|
||
|
||
function hdr() {
|
||
return Object.assign({ 'Content-Type': 'text/plain; charset=utf-8' }, SECURITY_HEADERS)
|
||
}
|
||
function plain(msg, status) {
|
||
return new Response(msg, { status, headers: hdr() })
|
||
}
|
||
function sameOrigin(request) {
|
||
const origin = request.headers.get('Origin')
|
||
if (!origin || origin === 'null') return true
|
||
try { return new URL(origin).host === new URL(request.url).host } catch (e) { return false }
|
||
}
|
||
function hostAllowed(u) {
|
||
return ALLOW_HOSTS.some((re) => re.test(u.hostname))
|
||
}
|
||
function capStream(stream, max) {
|
||
let seen = 0
|
||
return stream.pipeThrough(new TransformStream({
|
||
transform(chunk, controller) {
|
||
seen += chunk && chunk.byteLength ? chunk.byteLength : 0
|
||
if (seen > max) { controller.error(new Error('response too large')); return }
|
||
controller.enqueue(chunk)
|
||
},
|
||
}))
|
||
}
|
||
|
||
async function handle(request) {
|
||
if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: hdr() })
|
||
if (request.method !== 'GET') return plain('仅支持 GET', 405)
|
||
if (!sameOrigin(request)) return plain('仅允许同源调用', 403)
|
||
let target
|
||
try {
|
||
const raw = String(new URL(request.url).searchParams.get('url') || '')
|
||
target = new URL(raw)
|
||
} catch (e) { return plain('缺少或非法的 url 参数', 400) }
|
||
if (target.protocol !== 'https:') return plain('仅支持 https 图片地址', 400)
|
||
if (!hostAllowed(target)) return plain('该图床未在允许列表中:' + target.hostname, 403)
|
||
try {
|
||
// 手动跟随重定向:每一跳都对 host 重新校验,逃逸即拒。
|
||
let upstream = null
|
||
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
||
upstream = await fetch(target.toString(), { headers: { Accept: 'image/*' }, redirect: 'manual' })
|
||
const status = upstream.status
|
||
const isRedirect = status >= 300 && status < 400
|
||
if (!isRedirect) break
|
||
const location = upstream.headers.get('Location')
|
||
if (!location) return plain('上游重定向缺少 Location', 502)
|
||
if (hop === MAX_REDIRECTS) return plain('重定向次数过多', 508)
|
||
let next
|
||
try { next = new URL(location, target) } catch (e) { return plain('上游重定向地址非法', 502) }
|
||
if (next.protocol !== 'https:') return plain('重定向目标非 https', 403)
|
||
if (!hostAllowed(next)) return plain('重定向目标未在允许列表中:' + next.hostname, 403)
|
||
target = next
|
||
}
|
||
if (!upstream || !upstream.ok) return plain('上游返回 ' + (upstream ? upstream.status : '0'), 502)
|
||
const ct = String(upstream.headers.get('content-type') || '')
|
||
if (ct && ct.toLowerCase().indexOf('image/') !== 0) return plain('上游不是图片(' + ct + ')', 415)
|
||
const len = Number(upstream.headers.get('content-length'))
|
||
if (Number.isFinite(len) && len > MAX_BYTES) return plain('图片过大(超过 ' + MAX_BYTES + ' 字节)', 413)
|
||
const headers = new Headers()
|
||
headers.set('Content-Type', ct || 'image/png')
|
||
headers.set('Cache-Control', 'private, max-age=600')
|
||
for (const [k, v] of Object.entries(SECURITY_HEADERS)) headers.set(k, v)
|
||
const body = upstream.body && !(Number.isFinite(len) && len <= MAX_BYTES) ? capStream(upstream.body, MAX_BYTES) : upstream.body
|
||
return new Response(body, { status: 200, headers })
|
||
} catch (e) {
|
||
return plain('代理失败:' + ((e && e.message) || 'unknown'), 502)
|
||
}
|
||
}
|