javascript
export default {
async fetch(request, env) {
// 从 cfxhttp 加载配置
const cfg = {
XHTTP_PATH: '/xhttp', // 配置 xhttp 的路径,根据需要更改
XPADDING_RANGE: '100-1000', // X-Padding 长度范围
};
// 解析请求 URL
const url = new URL(request.url);
// 检查是否为 xhttp 请求
if (cfg.XHTTP_PATH && request.method === 'POST' && url.pathname.endsWith(cfg.XHTTP_PATH)) {
try {
// 转发 xhttp 请求
const readable = await handleXhttp(cfg, request.body, url.hostname);
const headers = {
'X-Accel-Buffering': 'no',
'Cache-Control': 'no-store',
Connection: 'Keep-Alive',
'User-Agent': 'Go-http-client/2.0',
'Content-Type': 'application/grpc',
};
// 添加 X-Padding 头
const padding = randomPadding(cfg.XPADDING_RANGE);
if (padding) {
headers['X-Padding'] = padding;
}
return new Response(readable, { headers });
} catch (err) {
console.error(`Error handling xhttp: ${err.message}`);
return new Response('Internal Server Error', { status: 500 });
}
}
// 默认反代逻辑(非 xhttp 请求)
if (url.pathname.startsWith('/')) {
url.hostname = 'sptp.liveagreatlife.tk'; // 目标主机
const newRequest = new Request(url, request);
return fetch(newRequest);
}
return env.ASSETS.fetch(request);
},
};
// 随机生成 X-Padding 长度
function randomPadding(rangeStr) {
if (!rangeStr || typeof rangeStr !== 'string') {
return null;
}
const range = rangeStr
.split('-')
.map((s) => parseInt(s))
.filter((s) => s || s === 0)
.slice(0, 2)
.sort((a, b) => a - b);
if (range.length < 1 || range[0] < 1) {
return null;
}
const last = range[range.length - 1];
if (last < 1) {
return null;
}
const n = range[0] === last ? range[0] : Math.floor(Math.random() * (last - range[0] + 1)) + range[0];
return '0'.repeat(n);
}
// 处理 xhttp 请求的逻辑
async function handleXhttp(cfg, clientBody, hostname) {
// 模拟处理 xhttp 请求(此处实现为简单的转发逻辑,可根据需求扩展)
const remoteUrl = `https://${hostname}${cfg.XHTTP_PATH}`;
// 转发到目标服务器
const response = await fetch(remoteUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/grpc',
},
body: clientBody,
});
if (!response.ok) {
throw new Error(`Upstream responded with status ${response.status}`);
}
return response.body; // 返回响应的可读流
}