Merge pull request #8 from springandme/feat/site-level-proxy
Browse files- .env.example +5 -0
- README.md +19 -0
- server/package.json +7 -2
- server/prisma/schema.prisma +2 -0
- server/scripts/start.js +2 -1
- server/src/checkin.js +2 -2
- server/src/routes.js +100 -85
- server/src/run.js +27 -26
- server/src/server.js +11 -6
- server/src/site-http.js +461 -0
- server/tests/site-proxy.test.js +433 -0
- web/src/pages/Sites.jsx +78 -33
.env.example
CHANGED
|
@@ -19,3 +19,8 @@ PORT=3000
|
|
| 19 |
# 运行环境(production 或 development)
|
| 20 |
NODE_ENV=production
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# 运行环境(production 或 development)
|
| 20 |
NODE_ENV=production
|
| 21 |
|
| 22 |
+
# JWT 签名密钥(生产环境强烈建议设置)
|
| 23 |
+
JWT_SECRET=replace-with-a-random-secret
|
| 24 |
+
|
| 25 |
+
# 敏感数据加密密钥(生产环境强烈建议设置)
|
| 26 |
+
ENCRYPTION_KEY=replace-with-a-random-secret
|
README.md
CHANGED
|
@@ -19,6 +19,7 @@
|
|
| 19 |
|
| 20 |
### 🔍 智能监控
|
| 21 |
- **多站点管理**:统一管理多个 AI 中转站,支持 NewAPI、Veloera、DoneHub、VOAPI 等主流平台
|
|
|
|
| 22 |
- **模型变更检测**:自动追踪模型列表的增删改,精确记录每次变化
|
| 23 |
- **余额监控**:实时显示账户余额、使用量和剩余额度,支持自定义额度配置
|
| 24 |
- **请求详情**:完整记录 API 响应、错误信息和性能数据,便于问题排查
|
|
@@ -121,6 +122,8 @@ services:
|
|
| 121 |
environment:
|
| 122 |
- ADMIN_EMAIL=${ADMIN_EMAIL:-admin@example.com}
|
| 123 |
- ADMIN_PASSWORD=${ADMIN_PASSWORD:-admin123456}
|
|
|
|
|
|
|
| 124 |
volumes:
|
| 125 |
- api-monitor-data:/app/data
|
| 126 |
restart: unless-stopped
|
|
@@ -138,6 +141,8 @@ docker-compose up -d
|
|
| 138 |
# 或自定义管理员账号
|
| 139 |
ADMIN_EMAIL=your-email@example.com \
|
| 140 |
ADMIN_PASSWORD=your-secure-password \
|
|
|
|
|
|
|
| 141 |
docker-compose up -d
|
| 142 |
```
|
| 143 |
|
|
@@ -222,8 +227,22 @@ npm start
|
|
| 222 |
- **定时检测**:设置每日自动检测时间
|
| 223 |
- **分类**:将站点归类到指定分类
|
| 224 |
- **签到配置**:Veloera 类型可启用自动签到
|
|
|
|
| 225 |
- **自定义余额**:配置自定义余额查询接口
|
| 226 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
### 签到功能
|
| 228 |
|
| 229 |
1. 编辑 NewAPI、Veloera 类型的站点
|
|
|
|
| 19 |
|
| 20 |
### 🔍 智能监控
|
| 21 |
- **多站点管理**:统一管理多个 AI 中转站,支持 NewAPI、Veloera、DoneHub、VOAPI 等主流平台
|
| 22 |
+
- **站点级代理**:支持为单个站点单独配置 HTTP / SOCKS5 代理,自动应用到该站点的所有访问操作
|
| 23 |
- **模型变更检测**:自动追踪模型列表的增删改,精确记录每次变化
|
| 24 |
- **余额监控**:实时显示账户余额、使用量和剩余额度,支持自定义额度配置
|
| 25 |
- **请求详情**:完整记录 API 响应、错误信息和性能数据,便于问题排查
|
|
|
|
| 122 |
environment:
|
| 123 |
- ADMIN_EMAIL=${ADMIN_EMAIL:-admin@example.com}
|
| 124 |
- ADMIN_PASSWORD=${ADMIN_PASSWORD:-admin123456}
|
| 125 |
+
- JWT_SECRET=${JWT_SECRET:-replace-with-a-random-secret}
|
| 126 |
+
- ENCRYPTION_KEY=${ENCRYPTION_KEY:-replace-with-a-random-secret}
|
| 127 |
volumes:
|
| 128 |
- api-monitor-data:/app/data
|
| 129 |
restart: unless-stopped
|
|
|
|
| 141 |
# 或自定义管理员账号
|
| 142 |
ADMIN_EMAIL=your-email@example.com \
|
| 143 |
ADMIN_PASSWORD=your-secure-password \
|
| 144 |
+
JWT_SECRET=$(openssl rand -hex 32) \
|
| 145 |
+
ENCRYPTION_KEY=$(openssl rand -hex 32) \
|
| 146 |
docker-compose up -d
|
| 147 |
```
|
| 148 |
|
|
|
|
| 227 |
- **定时检测**:设置每日自动检测时间
|
| 228 |
- **分类**:将站点归类到指定分类
|
| 229 |
- **签到配置**:Veloera 类型可启用自动签到
|
| 230 |
+
- **站点代理**:可选填写 `http(s)://` 或 `socks5://` 代理地址,自动用于该站点全部后端访问
|
| 231 |
- **自定义余额**:配置自定义余额查询接口
|
| 232 |
|
| 233 |
+
### 站点代理配置
|
| 234 |
+
|
| 235 |
+
- 代理字段是可选项,留空时保持直连访问
|
| 236 |
+
- 支持 `http://127.0.0.1:7890`、`http://user:pass@host:port`、`socks5://user:pass@host:port`
|
| 237 |
+
- 代理会统一作用于该站点的模型检测、余额查询、签到、令牌管理、分组读取、兑换码等所有后端请求
|
| 238 |
+
|
| 239 |
+
### GitHub Actions 发布说明
|
| 240 |
+
|
| 241 |
+
- 当前 `.github/workflows/docker-publish.yml` 使用 GitHub 自动提供的 `GITHUB_TOKEN` 推送 GHCR,一般不需要额外自定义 Secrets
|
| 242 |
+
- 在你的 fork 仓库中,需要确认 `Settings -> Actions -> General -> Workflow permissions` 设为 **Read and write permissions**
|
| 243 |
+
- 如果要让镜像推送到 `ghcr.io/<你的用户名>/SimpleHub`,还需要确认该仓库允许 GitHub Actions 写入 GitHub Packages
|
| 244 |
+
- 应用运行本身需要关注的环境变量仍然是:`DATABASE_URL`、`ADMIN_EMAIL`、`ADMIN_PASSWORD`、`PORT`、`NODE_ENV`、`JWT_SECRET`、`ENCRYPTION_KEY`
|
| 245 |
+
|
| 246 |
### 签到功能
|
| 247 |
|
| 248 |
1. 编辑 NewAPI、Veloera 类型的站点
|
server/package.json
CHANGED
|
@@ -8,7 +8,8 @@
|
|
| 8 |
"start": "node scripts/start.js",
|
| 9 |
"dev": "node src/server.js",
|
| 10 |
"db:push": "prisma db push",
|
| 11 |
-
"prisma:generate": "prisma generate"
|
|
|
|
| 12 |
},
|
| 13 |
"dependencies": {
|
| 14 |
"@fastify/cors": "^9.0.1",
|
|
@@ -18,8 +19,12 @@
|
|
| 18 |
"bcryptjs": "^2.4.3",
|
| 19 |
"dotenv": "^17.2.3",
|
| 20 |
"fastify": "^4.27.2",
|
|
|
|
|
|
|
| 21 |
"node-cron": "^3.0.3",
|
| 22 |
-
"
|
|
|
|
|
|
|
| 23 |
},
|
| 24 |
"devDependencies": {
|
| 25 |
"prisma": "^6.17.1"
|
|
|
|
| 8 |
"start": "node scripts/start.js",
|
| 9 |
"dev": "node src/server.js",
|
| 10 |
"db:push": "prisma db push",
|
| 11 |
+
"prisma:generate": "prisma generate",
|
| 12 |
+
"test": "node --test tests/*.test.js"
|
| 13 |
},
|
| 14 |
"dependencies": {
|
| 15 |
"@fastify/cors": "^9.0.1",
|
|
|
|
| 19 |
"bcryptjs": "^2.4.3",
|
| 20 |
"dotenv": "^17.2.3",
|
| 21 |
"fastify": "^4.27.2",
|
| 22 |
+
"http-proxy-agent": "^7.0.2",
|
| 23 |
+
"https-proxy-agent": "^7.0.6",
|
| 24 |
"node-cron": "^3.0.3",
|
| 25 |
+
"node-fetch": "^2.7.0",
|
| 26 |
+
"resend": "^3.0.0",
|
| 27 |
+
"socks-proxy-agent": "^8.0.5"
|
| 28 |
},
|
| 29 |
"devDependencies": {
|
| 30 |
"prisma": "^6.17.1"
|
server/prisma/schema.prisma
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
generator client {
|
| 2 |
provider = "prisma-client-js"
|
|
|
|
| 3 |
}
|
| 4 |
|
| 5 |
datasource db {
|
|
@@ -25,6 +26,7 @@ model Site {
|
|
| 25 |
billingUrl String?
|
| 26 |
billingAuthType String @default("token")
|
| 27 |
billingAuthValue String?
|
|
|
|
| 28 |
billingLimitField String?
|
| 29 |
billingUsageField String?
|
| 30 |
unlimitedQuota Boolean @default(false)
|
|
|
|
| 1 |
generator client {
|
| 2 |
provider = "prisma-client-js"
|
| 3 |
+
binaryTargets = ["native", "debian-openssl-3.0.x", "linux-arm64-openssl-3.0.x"]
|
| 4 |
}
|
| 5 |
|
| 6 |
datasource db {
|
|
|
|
| 26 |
billingUrl String?
|
| 27 |
billingAuthType String @default("token")
|
| 28 |
billingAuthValue String?
|
| 29 |
+
proxyUrlEnc String?
|
| 30 |
billingLimitField String?
|
| 31 |
billingUsageField String?
|
| 32 |
unlimitedQuota Boolean @default(false)
|
server/scripts/start.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
const { spawn } = require('child_process');
|
|
|
|
| 2 |
|
| 3 |
function run(cmd, args) {
|
| 4 |
return new Promise((resolve, reject) => {
|
|
@@ -14,5 +15,5 @@ function run(cmd, args) {
|
|
| 14 |
// eslint-disable-next-line no-console
|
| 15 |
console.error('Prisma db push failed:', e.message);
|
| 16 |
}
|
| 17 |
-
|
| 18 |
})();
|
|
|
|
| 1 |
const { spawn } = require('child_process');
|
| 2 |
+
const { startServer } = require('../src/server');
|
| 3 |
|
| 4 |
function run(cmd, args) {
|
| 5 |
return new Promise((resolve, reject) => {
|
|
|
|
| 15 |
// eslint-disable-next-line no-console
|
| 16 |
console.error('Prisma db push failed:', e.message);
|
| 17 |
}
|
| 18 |
+
await startServer();
|
| 19 |
})();
|
server/src/checkin.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
const { decrypt } = require('./crypto');
|
|
|
|
| 2 |
|
| 3 |
/**
|
| 4 |
* 执行签到(支持 Veloera 和 NewAPI)
|
|
@@ -52,7 +53,7 @@ async function performCheckIn(site) {
|
|
| 52 |
console.log(`[签到] 开始签到: ${site.name} (${checkInUrl})`);
|
| 53 |
|
| 54 |
// 发起签到请求
|
| 55 |
-
const response = await
|
| 56 |
method: 'POST',
|
| 57 |
headers: {
|
| 58 |
'Authorization': `Bearer ${token}`,
|
|
@@ -158,4 +159,3 @@ module.exports = {
|
|
| 158 |
shouldCheckIn,
|
| 159 |
shouldCheckModels
|
| 160 |
};
|
| 161 |
-
|
|
|
|
| 1 |
const { decrypt } = require('./crypto');
|
| 2 |
+
const { siteFetch } = require('./site-http');
|
| 3 |
|
| 4 |
/**
|
| 5 |
* 执行签到(支持 Veloera 和 NewAPI)
|
|
|
|
| 53 |
console.log(`[签到] 开始签到: ${site.name} (${checkInUrl})`);
|
| 54 |
|
| 55 |
// 发起签到请求
|
| 56 |
+
const response = await siteFetch(site, checkInUrl, {
|
| 57 |
method: 'POST',
|
| 58 |
headers: {
|
| 59 |
'Authorization': `Bearer ${token}`,
|
|
|
|
| 159 |
shouldCheckIn,
|
| 160 |
shouldCheckModels
|
| 161 |
};
|
|
|
server/src/routes.js
CHANGED
|
@@ -1,9 +1,44 @@
|
|
| 1 |
const path = require('path');
|
| 2 |
const { authPlugin } = require('./auth');
|
| 3 |
const { prisma } = require('./db');
|
| 4 |
-
const { encrypt } = require('./crypto');
|
| 5 |
const { onSiteUpdated, scheduleGlobalTask } = require('./scheduler');
|
| 6 |
const { checkSiteById } = require('./run');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
async function routes(fastify) {
|
| 9 |
await fastify.register(authPlugin);
|
|
@@ -50,7 +85,7 @@ async function routes(fastify) {
|
|
| 50 |
fastify.log.info({ siteName: site.name }, 'No snapshot found for site');
|
| 51 |
}
|
| 52 |
|
| 53 |
-
const { apiKeyEnc, ...rest } = site;
|
| 54 |
return {
|
| 55 |
...rest,
|
| 56 |
billingLimit: latestSnapshot?.billingLimit ?? null,
|
|
@@ -104,21 +139,21 @@ async function routes(fastify) {
|
|
| 104 |
});
|
| 105 |
|
| 106 |
// 不导出加密的敏感信息,导出原始apiKey和billingAuthValue
|
| 107 |
-
const { decrypt } = require('./crypto');
|
| 108 |
const exportData = sites.map(site => {
|
| 109 |
-
const { apiKeyEnc, billingAuthValue, ...siteData } = site;
|
| 110 |
return {
|
| 111 |
...siteData,
|
| 112 |
apiKey: apiKeyEnc ? decrypt(apiKeyEnc) : null,
|
| 113 |
billingAuthValue: billingAuthValue ? decrypt(billingAuthValue) : null,
|
|
|
|
| 114 |
// 导出分类名称而不是ID
|
| 115 |
categoryName: site.category ? site.category.name : null,
|
| 116 |
category: undefined // 移除category对象
|
| 117 |
};
|
| 118 |
});
|
| 119 |
-
|
| 120 |
return {
|
| 121 |
-
version: '1.
|
| 122 |
exportDate: new Date().toISOString(),
|
| 123 |
sites: exportData
|
| 124 |
};
|
|
@@ -137,20 +172,20 @@ async function routes(fastify) {
|
|
| 137 |
include: { category: true }
|
| 138 |
});
|
| 139 |
|
| 140 |
-
const { decrypt } = require('./crypto');
|
| 141 |
const exportData = sites.map(site => {
|
| 142 |
-
const { apiKeyEnc, billingAuthValue, ...siteData } = site;
|
| 143 |
return {
|
| 144 |
...siteData,
|
| 145 |
apiKey: apiKeyEnc ? decrypt(apiKeyEnc) : null,
|
| 146 |
billingAuthValue: billingAuthValue ? decrypt(billingAuthValue) : null,
|
|
|
|
| 147 |
categoryName: site.category ? site.category.name : null,
|
| 148 |
category: undefined
|
| 149 |
};
|
| 150 |
});
|
| 151 |
|
| 152 |
return {
|
| 153 |
-
version: '1.
|
| 154 |
exportDate: new Date().toISOString(),
|
| 155 |
sites: exportData
|
| 156 |
};
|
|
@@ -197,6 +232,7 @@ async function routes(fastify) {
|
|
| 197 |
name, baseUrl, apiType = 'other', userId = null,
|
| 198 |
scheduleCron = null, timezone = 'UTC', pinned = false, excludeFromBatch = false,
|
| 199 |
billingUrl = null, billingAuthType = 'token', billingAuthValue = null,
|
|
|
|
| 200 |
billingLimitField = null, billingUsageField = null, unlimitedQuota = false,
|
| 201 |
enableCheckIn = false, checkInMode = 'both'
|
| 202 |
} = siteData;
|
|
@@ -218,13 +254,15 @@ async function routes(fastify) {
|
|
| 218 |
if (billingAuthValue) {
|
| 219 |
billingAuthValueEnc = encrypt(billingAuthValue);
|
| 220 |
}
|
| 221 |
-
|
|
|
|
| 222 |
// 创建站点
|
| 223 |
const site = await prisma.site.create({
|
| 224 |
data: {
|
| 225 |
name, baseUrl, apiKeyEnc, apiType, userId, scheduleCron, timezone, pinned, excludeFromBatch,
|
| 226 |
categoryId,
|
| 227 |
billingUrl, billingAuthType, billingAuthValue: billingAuthValueEnc,
|
|
|
|
| 228 |
billingLimitField, billingUsageField, unlimitedQuota,
|
| 229 |
enableCheckIn, checkInMode
|
| 230 |
}
|
|
@@ -272,6 +310,7 @@ async function routes(fastify) {
|
|
| 272 |
billingUrl: { type: 'string' },
|
| 273 |
billingAuthType: { type: 'string', enum: ['token', 'cookie'] },
|
| 274 |
billingAuthValue: { type: 'string' },
|
|
|
|
| 275 |
billingLimitField: { type: 'string' },
|
| 276 |
billingUsageField: { type: 'string' },
|
| 277 |
unlimitedQuota: { type: 'boolean' },
|
|
@@ -283,36 +322,44 @@ async function routes(fastify) {
|
|
| 283 |
},
|
| 284 |
},
|
| 285 |
},
|
| 286 |
-
}, async (request) => {
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
billingAuthValueEnc =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
}
|
| 302 |
-
|
| 303 |
-
const site = await prisma.site.create({
|
| 304 |
-
data: {
|
| 305 |
-
name, baseUrl, apiKeyEnc, apiType, userId, scheduleCron, timezone, pinned, excludeFromBatch,
|
| 306 |
-
categoryId: categoryId || null,
|
| 307 |
-
billingUrl, billingAuthType, billingAuthValue: billingAuthValueEnc,
|
| 308 |
-
billingLimitField, billingUsageField, unlimitedQuota,
|
| 309 |
-
enableCheckIn, checkInMode,
|
| 310 |
-
extralink, remark, sortOrder
|
| 311 |
-
}
|
| 312 |
-
});
|
| 313 |
-
onSiteUpdated(site, fastify);
|
| 314 |
-
const { apiKeyEnc: _, ...rest } = site;
|
| 315 |
-
return rest;
|
| 316 |
});
|
| 317 |
|
| 318 |
fastify.patch('/api/sites/:id', {
|
|
@@ -334,6 +381,7 @@ async function routes(fastify) {
|
|
| 334 |
billingUrl: { type: 'string' },
|
| 335 |
billingAuthType: { type: 'string', enum: ['token', 'cookie'] },
|
| 336 |
billingAuthValue: { type: 'string' },
|
|
|
|
| 337 |
billingLimitField: { type: 'string' },
|
| 338 |
billingUsageField: { type: 'string' },
|
| 339 |
unlimitedQuota: { type: 'boolean' },
|
|
@@ -351,7 +399,7 @@ async function routes(fastify) {
|
|
| 351 |
const {
|
| 352 |
name, baseUrl, apiKey, apiType, userId, scheduleCron, timezone, pinned, excludeFromBatch,
|
| 353 |
categoryId,
|
| 354 |
-
billingUrl, billingAuthType, billingAuthValue, billingLimitField, billingUsageField, unlimitedQuota,
|
| 355 |
enableCheckIn, checkInMode,
|
| 356 |
extralink, remark, sortOrder
|
| 357 |
} = request.body || {};
|
|
@@ -375,6 +423,7 @@ async function routes(fastify) {
|
|
| 375 |
if (billingAuthValue !== undefined) {
|
| 376 |
data.billingAuthValue = billingAuthValue ? encrypt(billingAuthValue) : null;
|
| 377 |
}
|
|
|
|
| 378 |
if (billingLimitField !== undefined) data.billingLimitField = billingLimitField;
|
| 379 |
if (billingUsageField !== undefined) data.billingUsageField = billingUsageField;
|
| 380 |
if (checkInMode) data.checkInMode = checkInMode;
|
|
@@ -396,11 +445,11 @@ async function routes(fastify) {
|
|
| 396 |
onSiteUpdated(site, fastify);
|
| 397 |
}
|
| 398 |
|
| 399 |
-
const { apiKeyEnc: _, ...rest } = site;
|
| 400 |
return rest;
|
| 401 |
} catch (error) {
|
| 402 |
fastify.log.error({ error, id, body: request.body }, 'Failed to update site');
|
| 403 |
-
reply.code(500);
|
| 404 |
return { error: error.message || '更新站点失败' };
|
| 405 |
}
|
| 406 |
});
|
|
@@ -532,7 +581,7 @@ async function routes(fastify) {
|
|
| 532 |
}
|
| 533 |
}
|
| 534 |
|
| 535 |
-
const res = await
|
| 536 |
method: 'GET',
|
| 537 |
headers
|
| 538 |
});
|
|
@@ -556,7 +605,6 @@ async function routes(fastify) {
|
|
| 556 |
}
|
| 557 |
}, async (request, reply) => {
|
| 558 |
const { id } = request.params;
|
| 559 |
-
const { decrypt } = require('./crypto');
|
| 560 |
|
| 561 |
try {
|
| 562 |
const site = await prisma.site.findUnique({
|
|
@@ -569,35 +617,7 @@ async function routes(fastify) {
|
|
| 569 |
return { error: '站点不存在' };
|
| 570 |
}
|
| 571 |
|
| 572 |
-
|
| 573 |
-
let token = null;
|
| 574 |
-
if (site.apiKeyEnc) {
|
| 575 |
-
try {
|
| 576 |
-
token = decrypt(site.apiKeyEnc);
|
| 577 |
-
} catch (e) {
|
| 578 |
-
fastify.log.error({ error: e.message }, 'Failed to decrypt API key');
|
| 579 |
-
}
|
| 580 |
-
}
|
| 581 |
-
|
| 582 |
-
// 解密 billing auth value
|
| 583 |
-
let billingAuthValue = null;
|
| 584 |
-
if (site.billingAuthValue) {
|
| 585 |
-
try {
|
| 586 |
-
billingAuthValue = decrypt(site.billingAuthValue);
|
| 587 |
-
} catch (e) {
|
| 588 |
-
fastify.log.error({ error: e.message }, 'Failed to decrypt billing auth value');
|
| 589 |
-
}
|
| 590 |
-
}
|
| 591 |
-
|
| 592 |
-
// 返回站点信息(包含解密后的token)
|
| 593 |
-
const { apiKeyEnc, ...rest } = site;
|
| 594 |
-
return {
|
| 595 |
-
...rest,
|
| 596 |
-
token,
|
| 597 |
-
url: site.baseUrl,
|
| 598 |
-
type: site.apiType,
|
| 599 |
-
billingAuthValue
|
| 600 |
-
};
|
| 601 |
} catch (e) {
|
| 602 |
fastify.log.error({ error: e.message }, 'Error fetching site');
|
| 603 |
reply.code(500);
|
|
@@ -638,7 +658,7 @@ async function routes(fastify) {
|
|
| 638 |
'Content-Type': 'application/json'
|
| 639 |
};
|
| 640 |
|
| 641 |
-
const res = await
|
| 642 |
const data = await res.json();
|
| 643 |
|
| 644 |
if (!res.ok || data.code !== 0) {
|
|
@@ -688,7 +708,7 @@ async function routes(fastify) {
|
|
| 688 |
}
|
| 689 |
}
|
| 690 |
|
| 691 |
-
const res = await
|
| 692 |
const data = await res.json();
|
| 693 |
|
| 694 |
if (!res.ok) {
|
|
@@ -711,7 +731,6 @@ async function routes(fastify) {
|
|
| 711 |
}
|
| 712 |
}, async (request, reply) => {
|
| 713 |
const { id } = request.params;
|
| 714 |
-
const { decrypt } = require('./crypto');
|
| 715 |
|
| 716 |
try {
|
| 717 |
const site = await prisma.site.findUnique({ where: { id } });
|
|
@@ -748,7 +767,7 @@ async function routes(fastify) {
|
|
| 748 |
// 其他类型不需要用户ID请求头
|
| 749 |
}
|
| 750 |
|
| 751 |
-
const res = await
|
| 752 |
const data = await res.json();
|
| 753 |
|
| 754 |
if (!res.ok) {
|
|
@@ -772,7 +791,6 @@ async function routes(fastify) {
|
|
| 772 |
}, async (request, reply) => {
|
| 773 |
const { id } = request.params;
|
| 774 |
const tokenData = request.body;
|
| 775 |
-
const { decrypt } = require('./crypto');
|
| 776 |
|
| 777 |
try {
|
| 778 |
const site = await prisma.site.findUnique({ where: { id } });
|
|
@@ -864,7 +882,7 @@ async function routes(fastify) {
|
|
| 864 |
};
|
| 865 |
}
|
| 866 |
|
| 867 |
-
const res = await
|
| 868 |
method: 'POST',
|
| 869 |
headers,
|
| 870 |
body: JSON.stringify(payload)
|
|
@@ -901,7 +919,6 @@ async function routes(fastify) {
|
|
| 901 |
}, async (request, reply) => {
|
| 902 |
const { id } = request.params;
|
| 903 |
const tokenData = request.body;
|
| 904 |
-
const { decrypt } = require('./crypto');
|
| 905 |
|
| 906 |
try {
|
| 907 |
const site = await prisma.site.findUnique({ where: { id } });
|
|
@@ -965,7 +982,7 @@ async function routes(fastify) {
|
|
| 965 |
payload = tokenData;
|
| 966 |
}
|
| 967 |
|
| 968 |
-
const res = await
|
| 969 |
method: 'PUT',
|
| 970 |
headers,
|
| 971 |
body: JSON.stringify(payload)
|
|
@@ -1000,7 +1017,6 @@ async function routes(fastify) {
|
|
| 1000 |
}
|
| 1001 |
}, async (request, reply) => {
|
| 1002 |
const { id, tokenId } = request.params;
|
| 1003 |
-
const { decrypt } = require('./crypto');
|
| 1004 |
|
| 1005 |
try {
|
| 1006 |
const site = await prisma.site.findUnique({ where: { id } });
|
|
@@ -1048,7 +1064,7 @@ async function routes(fastify) {
|
|
| 1048 |
}
|
| 1049 |
}
|
| 1050 |
|
| 1051 |
-
const res = await
|
| 1052 |
method: 'DELETE',
|
| 1053 |
headers
|
| 1054 |
});
|
|
@@ -1084,7 +1100,6 @@ async function routes(fastify) {
|
|
| 1084 |
}, async (request, reply) => {
|
| 1085 |
const { id } = request.params;
|
| 1086 |
const { key } = request.body;
|
| 1087 |
-
const { decrypt } = require('./crypto');
|
| 1088 |
|
| 1089 |
try {
|
| 1090 |
const site = await prisma.site.findUnique({ where: { id } });
|
|
@@ -1114,7 +1129,7 @@ async function routes(fastify) {
|
|
| 1114 |
}
|
| 1115 |
}
|
| 1116 |
|
| 1117 |
-
const res = await
|
| 1118 |
method: 'POST',
|
| 1119 |
headers,
|
| 1120 |
body: JSON.stringify({ key })
|
|
|
|
| 1 |
const path = require('path');
|
| 2 |
const { authPlugin } = require('./auth');
|
| 3 |
const { prisma } = require('./db');
|
| 4 |
+
const { encrypt, decrypt } = require('./crypto');
|
| 5 |
const { onSiteUpdated, scheduleGlobalTask } = require('./scheduler');
|
| 6 |
const { checkSiteById } = require('./run');
|
| 7 |
+
const { normalizeProxyUrl, parseProxyUrl, siteFetch } = require('./site-http');
|
| 8 |
+
|
| 9 |
+
function decryptOptional(value, fieldName, fastify) {
|
| 10 |
+
if (!value) return null;
|
| 11 |
+
|
| 12 |
+
try {
|
| 13 |
+
return decrypt(value);
|
| 14 |
+
} catch (error) {
|
| 15 |
+
fastify?.log?.error({ error: error.message }, `Failed to decrypt ${fieldName}`);
|
| 16 |
+
return null;
|
| 17 |
+
}
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
function encryptProxyUrl(proxyUrl) {
|
| 21 |
+
const normalized = normalizeProxyUrl(proxyUrl);
|
| 22 |
+
if (!normalized) return null;
|
| 23 |
+
parseProxyUrl(normalized);
|
| 24 |
+
return encrypt(normalized);
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
function getSiteDetailResponse(site, fastify) {
|
| 28 |
+
const token = decryptOptional(site.apiKeyEnc, 'API key', fastify);
|
| 29 |
+
const billingAuthValue = decryptOptional(site.billingAuthValue, 'billing auth value', fastify);
|
| 30 |
+
const proxyUrl = decryptOptional(site.proxyUrlEnc, 'proxy URL', fastify);
|
| 31 |
+
const { apiKeyEnc, billingAuthValue: _, proxyUrlEnc, ...rest } = site;
|
| 32 |
+
|
| 33 |
+
return {
|
| 34 |
+
...rest,
|
| 35 |
+
token,
|
| 36 |
+
url: site.baseUrl,
|
| 37 |
+
type: site.apiType,
|
| 38 |
+
billingAuthValue,
|
| 39 |
+
proxyUrl
|
| 40 |
+
};
|
| 41 |
+
}
|
| 42 |
|
| 43 |
async function routes(fastify) {
|
| 44 |
await fastify.register(authPlugin);
|
|
|
|
| 85 |
fastify.log.info({ siteName: site.name }, 'No snapshot found for site');
|
| 86 |
}
|
| 87 |
|
| 88 |
+
const { apiKeyEnc, billingAuthValue, proxyUrlEnc, ...rest } = site;
|
| 89 |
return {
|
| 90 |
...rest,
|
| 91 |
billingLimit: latestSnapshot?.billingLimit ?? null,
|
|
|
|
| 139 |
});
|
| 140 |
|
| 141 |
// 不导出加密的敏感信息,导出原始apiKey和billingAuthValue
|
|
|
|
| 142 |
const exportData = sites.map(site => {
|
| 143 |
+
const { apiKeyEnc, billingAuthValue, proxyUrlEnc, ...siteData } = site;
|
| 144 |
return {
|
| 145 |
...siteData,
|
| 146 |
apiKey: apiKeyEnc ? decrypt(apiKeyEnc) : null,
|
| 147 |
billingAuthValue: billingAuthValue ? decrypt(billingAuthValue) : null,
|
| 148 |
+
proxyUrl: proxyUrlEnc ? decrypt(proxyUrlEnc) : null,
|
| 149 |
// 导出分类名称而不是ID
|
| 150 |
categoryName: site.category ? site.category.name : null,
|
| 151 |
category: undefined // 移除category对象
|
| 152 |
};
|
| 153 |
});
|
| 154 |
+
|
| 155 |
return {
|
| 156 |
+
version: '1.1',
|
| 157 |
exportDate: new Date().toISOString(),
|
| 158 |
sites: exportData
|
| 159 |
};
|
|
|
|
| 172 |
include: { category: true }
|
| 173 |
});
|
| 174 |
|
|
|
|
| 175 |
const exportData = sites.map(site => {
|
| 176 |
+
const { apiKeyEnc, billingAuthValue, proxyUrlEnc, ...siteData } = site;
|
| 177 |
return {
|
| 178 |
...siteData,
|
| 179 |
apiKey: apiKeyEnc ? decrypt(apiKeyEnc) : null,
|
| 180 |
billingAuthValue: billingAuthValue ? decrypt(billingAuthValue) : null,
|
| 181 |
+
proxyUrl: proxyUrlEnc ? decrypt(proxyUrlEnc) : null,
|
| 182 |
categoryName: site.category ? site.category.name : null,
|
| 183 |
category: undefined
|
| 184 |
};
|
| 185 |
});
|
| 186 |
|
| 187 |
return {
|
| 188 |
+
version: '1.1',
|
| 189 |
exportDate: new Date().toISOString(),
|
| 190 |
sites: exportData
|
| 191 |
};
|
|
|
|
| 232 |
name, baseUrl, apiType = 'other', userId = null,
|
| 233 |
scheduleCron = null, timezone = 'UTC', pinned = false, excludeFromBatch = false,
|
| 234 |
billingUrl = null, billingAuthType = 'token', billingAuthValue = null,
|
| 235 |
+
proxyUrl = null,
|
| 236 |
billingLimitField = null, billingUsageField = null, unlimitedQuota = false,
|
| 237 |
enableCheckIn = false, checkInMode = 'both'
|
| 238 |
} = siteData;
|
|
|
|
| 254 |
if (billingAuthValue) {
|
| 255 |
billingAuthValueEnc = encrypt(billingAuthValue);
|
| 256 |
}
|
| 257 |
+
const proxyUrlEnc = encryptProxyUrl(proxyUrl);
|
| 258 |
+
|
| 259 |
// 创建站点
|
| 260 |
const site = await prisma.site.create({
|
| 261 |
data: {
|
| 262 |
name, baseUrl, apiKeyEnc, apiType, userId, scheduleCron, timezone, pinned, excludeFromBatch,
|
| 263 |
categoryId,
|
| 264 |
billingUrl, billingAuthType, billingAuthValue: billingAuthValueEnc,
|
| 265 |
+
proxyUrlEnc,
|
| 266 |
billingLimitField, billingUsageField, unlimitedQuota,
|
| 267 |
enableCheckIn, checkInMode
|
| 268 |
}
|
|
|
|
| 310 |
billingUrl: { type: 'string' },
|
| 311 |
billingAuthType: { type: 'string', enum: ['token', 'cookie'] },
|
| 312 |
billingAuthValue: { type: 'string' },
|
| 313 |
+
proxyUrl: { type: 'string' },
|
| 314 |
billingLimitField: { type: 'string' },
|
| 315 |
billingUsageField: { type: 'string' },
|
| 316 |
unlimitedQuota: { type: 'boolean' },
|
|
|
|
| 322 |
},
|
| 323 |
},
|
| 324 |
},
|
| 325 |
+
}, async (request, reply) => {
|
| 326 |
+
try {
|
| 327 |
+
const {
|
| 328 |
+
name, baseUrl, apiKey, apiType = 'other', userId = null,
|
| 329 |
+
scheduleCron = null, timezone = 'UTC', pinned = false, excludeFromBatch = false,
|
| 330 |
+
categoryId = null,
|
| 331 |
+
billingUrl = null, billingAuthType = 'token', billingAuthValue = null,
|
| 332 |
+
proxyUrl = null,
|
| 333 |
+
billingLimitField = null, billingUsageField = null, unlimitedQuota = false,
|
| 334 |
+
enableCheckIn = false, checkInMode = 'both',
|
| 335 |
+
extralink = null, remark = null, sortOrder = 0
|
| 336 |
+
} = request.body;
|
| 337 |
+
|
| 338 |
+
const apiKeyEnc = encrypt(apiKey);
|
| 339 |
+
let billingAuthValueEnc = null;
|
| 340 |
+
if (billingAuthValue) {
|
| 341 |
+
billingAuthValueEnc = encrypt(billingAuthValue);
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
const site = await prisma.site.create({
|
| 345 |
+
data: {
|
| 346 |
+
name, baseUrl, apiKeyEnc, apiType, userId, scheduleCron, timezone, pinned, excludeFromBatch,
|
| 347 |
+
categoryId: categoryId || null,
|
| 348 |
+
billingUrl, billingAuthType, billingAuthValue: billingAuthValueEnc,
|
| 349 |
+
proxyUrlEnc: encryptProxyUrl(proxyUrl),
|
| 350 |
+
billingLimitField, billingUsageField, unlimitedQuota,
|
| 351 |
+
enableCheckIn, checkInMode,
|
| 352 |
+
extralink, remark, sortOrder
|
| 353 |
+
}
|
| 354 |
+
});
|
| 355 |
+
onSiteUpdated(site, fastify);
|
| 356 |
+
const { apiKeyEnc: _, billingAuthValue: __, proxyUrlEnc, ...rest } = site;
|
| 357 |
+
return rest;
|
| 358 |
+
} catch (error) {
|
| 359 |
+
fastify.log.error({ error, body: request.body }, 'Failed to create site');
|
| 360 |
+
reply.code(error.statusCode || 500);
|
| 361 |
+
return { error: error.message || '创建站点失败' };
|
| 362 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
});
|
| 364 |
|
| 365 |
fastify.patch('/api/sites/:id', {
|
|
|
|
| 381 |
billingUrl: { type: 'string' },
|
| 382 |
billingAuthType: { type: 'string', enum: ['token', 'cookie'] },
|
| 383 |
billingAuthValue: { type: 'string' },
|
| 384 |
+
proxyUrl: { type: 'string' },
|
| 385 |
billingLimitField: { type: 'string' },
|
| 386 |
billingUsageField: { type: 'string' },
|
| 387 |
unlimitedQuota: { type: 'boolean' },
|
|
|
|
| 399 |
const {
|
| 400 |
name, baseUrl, apiKey, apiType, userId, scheduleCron, timezone, pinned, excludeFromBatch,
|
| 401 |
categoryId,
|
| 402 |
+
billingUrl, billingAuthType, billingAuthValue, proxyUrl, billingLimitField, billingUsageField, unlimitedQuota,
|
| 403 |
enableCheckIn, checkInMode,
|
| 404 |
extralink, remark, sortOrder
|
| 405 |
} = request.body || {};
|
|
|
|
| 423 |
if (billingAuthValue !== undefined) {
|
| 424 |
data.billingAuthValue = billingAuthValue ? encrypt(billingAuthValue) : null;
|
| 425 |
}
|
| 426 |
+
if (proxyUrl !== undefined) data.proxyUrlEnc = encryptProxyUrl(proxyUrl);
|
| 427 |
if (billingLimitField !== undefined) data.billingLimitField = billingLimitField;
|
| 428 |
if (billingUsageField !== undefined) data.billingUsageField = billingUsageField;
|
| 429 |
if (checkInMode) data.checkInMode = checkInMode;
|
|
|
|
| 445 |
onSiteUpdated(site, fastify);
|
| 446 |
}
|
| 447 |
|
| 448 |
+
const { apiKeyEnc: _, billingAuthValue: __, proxyUrlEnc, ...rest } = site;
|
| 449 |
return rest;
|
| 450 |
} catch (error) {
|
| 451 |
fastify.log.error({ error, id, body: request.body }, 'Failed to update site');
|
| 452 |
+
reply.code(error.statusCode || 500);
|
| 453 |
return { error: error.message || '更新站点失败' };
|
| 454 |
}
|
| 455 |
});
|
|
|
|
| 581 |
}
|
| 582 |
}
|
| 583 |
|
| 584 |
+
const res = await siteFetch(site, url, {
|
| 585 |
method: 'GET',
|
| 586 |
headers
|
| 587 |
});
|
|
|
|
| 605 |
}
|
| 606 |
}, async (request, reply) => {
|
| 607 |
const { id } = request.params;
|
|
|
|
| 608 |
|
| 609 |
try {
|
| 610 |
const site = await prisma.site.findUnique({
|
|
|
|
| 617 |
return { error: '站点不存在' };
|
| 618 |
}
|
| 619 |
|
| 620 |
+
return getSiteDetailResponse(site, fastify);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 621 |
} catch (e) {
|
| 622 |
fastify.log.error({ error: e.message }, 'Error fetching site');
|
| 623 |
reply.code(500);
|
|
|
|
| 658 |
'Content-Type': 'application/json'
|
| 659 |
};
|
| 660 |
|
| 661 |
+
const res = await siteFetch(site, url, { headers });
|
| 662 |
const data = await res.json();
|
| 663 |
|
| 664 |
if (!res.ok || data.code !== 0) {
|
|
|
|
| 708 |
}
|
| 709 |
}
|
| 710 |
|
| 711 |
+
const res = await siteFetch(site, url, { headers });
|
| 712 |
const data = await res.json();
|
| 713 |
|
| 714 |
if (!res.ok) {
|
|
|
|
| 731 |
}
|
| 732 |
}, async (request, reply) => {
|
| 733 |
const { id } = request.params;
|
|
|
|
| 734 |
|
| 735 |
try {
|
| 736 |
const site = await prisma.site.findUnique({ where: { id } });
|
|
|
|
| 767 |
// 其他类型不需要用户ID请求头
|
| 768 |
}
|
| 769 |
|
| 770 |
+
const res = await siteFetch(site, url, { headers });
|
| 771 |
const data = await res.json();
|
| 772 |
|
| 773 |
if (!res.ok) {
|
|
|
|
| 791 |
}, async (request, reply) => {
|
| 792 |
const { id } = request.params;
|
| 793 |
const tokenData = request.body;
|
|
|
|
| 794 |
|
| 795 |
try {
|
| 796 |
const site = await prisma.site.findUnique({ where: { id } });
|
|
|
|
| 882 |
};
|
| 883 |
}
|
| 884 |
|
| 885 |
+
const res = await siteFetch(site, url, {
|
| 886 |
method: 'POST',
|
| 887 |
headers,
|
| 888 |
body: JSON.stringify(payload)
|
|
|
|
| 919 |
}, async (request, reply) => {
|
| 920 |
const { id } = request.params;
|
| 921 |
const tokenData = request.body;
|
|
|
|
| 922 |
|
| 923 |
try {
|
| 924 |
const site = await prisma.site.findUnique({ where: { id } });
|
|
|
|
| 982 |
payload = tokenData;
|
| 983 |
}
|
| 984 |
|
| 985 |
+
const res = await siteFetch(site, url, {
|
| 986 |
method: 'PUT',
|
| 987 |
headers,
|
| 988 |
body: JSON.stringify(payload)
|
|
|
|
| 1017 |
}
|
| 1018 |
}, async (request, reply) => {
|
| 1019 |
const { id, tokenId } = request.params;
|
|
|
|
| 1020 |
|
| 1021 |
try {
|
| 1022 |
const site = await prisma.site.findUnique({ where: { id } });
|
|
|
|
| 1064 |
}
|
| 1065 |
}
|
| 1066 |
|
| 1067 |
+
const res = await siteFetch(site, url, {
|
| 1068 |
method: 'DELETE',
|
| 1069 |
headers
|
| 1070 |
});
|
|
|
|
| 1100 |
}, async (request, reply) => {
|
| 1101 |
const { id } = request.params;
|
| 1102 |
const { key } = request.body;
|
|
|
|
| 1103 |
|
| 1104 |
try {
|
| 1105 |
const site = await prisma.site.findUnique({ where: { id } });
|
|
|
|
| 1129 |
}
|
| 1130 |
}
|
| 1131 |
|
| 1132 |
+
const res = await siteFetch(site, url, {
|
| 1133 |
method: 'POST',
|
| 1134 |
headers,
|
| 1135 |
body: JSON.stringify({ key })
|
server/src/run.js
CHANGED
|
@@ -3,6 +3,7 @@ const { prisma } = require('./db');
|
|
| 3 |
const { decrypt } = require('./crypto');
|
| 4 |
const { sendModelChangeNotification } = require('./notifier');
|
| 5 |
const { performCheckIn, shouldCheckIn, shouldCheckModels } = require('./checkin');
|
|
|
|
| 6 |
|
| 7 |
// 辅助函数:获取嵌套对象的值
|
| 8 |
function getNestedValue(obj, path) {
|
|
@@ -63,7 +64,7 @@ function computeDiff(prevList, nextList) {
|
|
| 63 |
}
|
| 64 |
|
| 65 |
// Newapi/Veloera API:获取模型列表
|
| 66 |
-
async function fetchModelsNewapi(baseUrl, apiKey, userId, apiType, fastify) {
|
| 67 |
const url = new URL('api/user/models', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 68 |
const ac = new AbortController();
|
| 69 |
const timeout = setTimeout(() => ac.abort(), 15000);
|
|
@@ -73,7 +74,7 @@ async function fetchModelsNewapi(baseUrl, apiKey, userId, apiType, fastify) {
|
|
| 73 |
|
| 74 |
try {
|
| 75 |
console.log(`[NEWAPI-REQ] GET ${url}`);
|
| 76 |
-
const res = await
|
| 77 |
method: 'GET',
|
| 78 |
headers: {
|
| 79 |
'Authorization': `Bearer ${apiKey}`,
|
|
@@ -141,7 +142,7 @@ async function fetchModelsNewapi(baseUrl, apiKey, userId, apiType, fastify) {
|
|
| 141 |
}
|
| 142 |
|
| 143 |
// Newapi/Veloera API:获取用户信息(billing)
|
| 144 |
-
async function fetchUserInfoNewapi(baseUrl, apiKey, userId, apiType, fastify) {
|
| 145 |
const url = new URL('api/user/self', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 146 |
const ac = new AbortController();
|
| 147 |
const timeout = setTimeout(() => ac.abort(), 10000);
|
|
@@ -150,7 +151,7 @@ async function fetchUserInfoNewapi(baseUrl, apiKey, userId, apiType, fastify) {
|
|
| 150 |
|
| 151 |
try {
|
| 152 |
console.log(`[NEWAPI-REQ] GET ${url}`);
|
| 153 |
-
const res = await
|
| 154 |
method: 'GET',
|
| 155 |
headers: {
|
| 156 |
'Authorization': `Bearer ${apiKey}`,
|
|
@@ -211,7 +212,7 @@ async function fetchUserInfoNewapi(baseUrl, apiKey, userId, apiType, fastify) {
|
|
| 211 |
}
|
| 212 |
|
| 213 |
// DoneHub API:获取模型列表
|
| 214 |
-
async function fetchModelsDonehub(baseUrl, apiKey, fastify) {
|
| 215 |
const url = new URL('api/available_model', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 216 |
const ac = new AbortController();
|
| 217 |
const timeout = setTimeout(() => ac.abort(), 15000);
|
|
@@ -219,7 +220,7 @@ async function fetchModelsDonehub(baseUrl, apiKey, fastify) {
|
|
| 219 |
|
| 220 |
try {
|
| 221 |
console.log(`[DONEHUB-REQ] GET ${url}`);
|
| 222 |
-
const res = await
|
| 223 |
method: 'GET',
|
| 224 |
headers: {
|
| 225 |
'Authorization': `Bearer ${apiKey}`,
|
|
@@ -275,14 +276,14 @@ async function fetchModelsDonehub(baseUrl, apiKey, fastify) {
|
|
| 275 |
}
|
| 276 |
|
| 277 |
// VOAPI API:获取用户信息(billing)
|
| 278 |
-
async function fetchUserInfoVoapi(baseUrl, jwtToken, fastify) {
|
| 279 |
const url = new URL('api/user/info', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 280 |
const ac = new AbortController();
|
| 281 |
const timeout = setTimeout(() => ac.abort(), 10000);
|
| 282 |
|
| 283 |
try {
|
| 284 |
console.log(`[VOAPI-REQ] GET ${url}`);
|
| 285 |
-
const res = await
|
| 286 |
method: 'GET',
|
| 287 |
headers: {
|
| 288 |
'Authorization': jwtToken, // VOAPI直接使用JWT token
|
|
@@ -327,14 +328,14 @@ async function fetchUserInfoVoapi(baseUrl, jwtToken, fastify) {
|
|
| 327 |
}
|
| 328 |
|
| 329 |
// DoneHub API:获取用户信息(billing)
|
| 330 |
-
async function fetchUserInfoDonehub(baseUrl, apiKey, fastify) {
|
| 331 |
const url = new URL('api/user/self', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 332 |
const ac = new AbortController();
|
| 333 |
const timeout = setTimeout(() => ac.abort(), 10000);
|
| 334 |
|
| 335 |
try {
|
| 336 |
console.log(`[DONEHUB-REQ] GET ${url}`);
|
| 337 |
-
const res = await
|
| 338 |
method: 'GET',
|
| 339 |
headers: {
|
| 340 |
'Authorization': `Bearer ${apiKey}`,
|
|
@@ -383,14 +384,14 @@ async function fetchUserInfoDonehub(baseUrl, apiKey, fastify) {
|
|
| 383 |
}
|
| 384 |
|
| 385 |
// 获取billing订阅额度信息
|
| 386 |
-
async function fetchBillingSubscription(baseUrl, apiKey, fastify) {
|
| 387 |
const url = new URL('v1/dashboard/billing/subscription', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 388 |
const ac = new AbortController();
|
| 389 |
const timeout = setTimeout(() => ac.abort(), 10000);
|
| 390 |
|
| 391 |
try {
|
| 392 |
console.log(`[BILLING-REQ] GET ${url}`);
|
| 393 |
-
const res = await
|
| 394 |
method: 'GET',
|
| 395 |
headers: {
|
| 396 |
'Authorization': `Bearer ${apiKey}`,
|
|
@@ -451,7 +452,7 @@ async function fetchCustomBilling(site, fastify) {
|
|
| 451 |
}
|
| 452 |
}
|
| 453 |
|
| 454 |
-
const res = await
|
| 455 |
method: 'GET',
|
| 456 |
headers,
|
| 457 |
signal: ac.signal
|
|
@@ -511,14 +512,14 @@ async function fetchCustomBilling(site, fastify) {
|
|
| 511 |
}
|
| 512 |
|
| 513 |
// 获取billing使用量信息
|
| 514 |
-
async function fetchBillingUsage(baseUrl, apiKey, fastify) {
|
| 515 |
const url = new URL('v1/dashboard/billing/usage', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 516 |
const ac = new AbortController();
|
| 517 |
const timeout = setTimeout(() => ac.abort(), 10000);
|
| 518 |
|
| 519 |
try {
|
| 520 |
console.log(`[BILLING-REQ] GET ${url}`);
|
| 521 |
-
const res = await
|
| 522 |
method: 'GET',
|
| 523 |
headers: {
|
| 524 |
'Authorization': `Bearer ${apiKey}`,
|
|
@@ -552,7 +553,7 @@ async function fetchBillingUsage(baseUrl, apiKey, fastify) {
|
|
| 552 |
}
|
| 553 |
}
|
| 554 |
|
| 555 |
-
async function fetchModels(baseUrl, apiKey, fastify) {
|
| 556 |
// 使用相对路径(不带前导/)以保留 baseUrl 中的路径部分(如 /api)
|
| 557 |
const url = new URL('v1/models', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 558 |
const ac = new AbortController();
|
|
@@ -563,7 +564,7 @@ async function fetchModels(baseUrl, apiKey, fastify) {
|
|
| 563 |
// VERSION: v2.0-simplified (只用2个头,模仿Python)
|
| 564 |
fastify?.log?.info({ msg: 'Fetching with v2.0-simplified headers', url: url.toString() });
|
| 565 |
|
| 566 |
-
const res = await
|
| 567 |
method: 'GET',
|
| 568 |
headers: {
|
| 569 |
'Authorization': `Bearer ${apiKey}`,
|
|
@@ -738,31 +739,31 @@ async function checkSite(site, fastify, options = {}) {
|
|
| 738 |
}
|
| 739 |
if (!site.unlimitedQuota) {
|
| 740 |
billingPromises = Promise.allSettled([
|
| 741 |
-
fetchUserInfoNewapi(site.baseUrl, apiKey, site.userId || '1', site.apiType, fastify)
|
| 742 |
]);
|
| 743 |
}
|
| 744 |
-
fetchModelsFunc = () => fetchModelsNewapi(site.baseUrl, apiKey, site.userId || '1', site.apiType, fastify);
|
| 745 |
} else if (site.apiType === 'donehub') {
|
| 746 |
// DoneHub:不需要userId
|
| 747 |
if (!site.unlimitedQuota) {
|
| 748 |
billingPromises = Promise.allSettled([
|
| 749 |
-
fetchUserInfoDonehub(site.baseUrl, apiKey, fastify)
|
| 750 |
]);
|
| 751 |
}
|
| 752 |
-
fetchModelsFunc = () => fetchModelsDonehub(site.baseUrl, apiKey, fastify);
|
| 753 |
} else if (site.apiType === 'voapi') {
|
| 754 |
// VOAPI:使用JWT token获取用量,apiKey获取模型
|
| 755 |
if (!site.unlimitedQuota) {
|
| 756 |
const jwtToken = site.billingAuthValue ? decrypt(site.billingAuthValue) : null;
|
| 757 |
if (jwtToken) {
|
| 758 |
billingPromises = Promise.allSettled([
|
| 759 |
-
fetchUserInfoVoapi(site.baseUrl, jwtToken, fastify)
|
| 760 |
]);
|
| 761 |
} else {
|
| 762 |
console.log(`[VOAPI-WARN] No JWT token configured for billing`);
|
| 763 |
}
|
| 764 |
}
|
| 765 |
-
fetchModelsFunc = () => fetchModels(site.baseUrl, apiKey, fastify); // 使用标准OpenAI模式获取模型
|
| 766 |
} else {
|
| 767 |
// Other: 使用原有的OpenAI兼容方式或自定义billing
|
| 768 |
if (!site.unlimitedQuota) {
|
|
@@ -774,12 +775,12 @@ async function checkSite(site, fastify, options = {}) {
|
|
| 774 |
} else {
|
| 775 |
// 使用默认的OpenAI兼容billing
|
| 776 |
billingPromises = Promise.allSettled([
|
| 777 |
-
fetchBillingSubscription(site.baseUrl, apiKey, fastify),
|
| 778 |
-
fetchBillingUsage(site.baseUrl, apiKey, fastify)
|
| 779 |
]);
|
| 780 |
}
|
| 781 |
}
|
| 782 |
-
fetchModelsFunc = () => fetchModels(site.baseUrl, apiKey, fastify);
|
| 783 |
}
|
| 784 |
|
| 785 |
try {
|
|
|
|
| 3 |
const { decrypt } = require('./crypto');
|
| 4 |
const { sendModelChangeNotification } = require('./notifier');
|
| 5 |
const { performCheckIn, shouldCheckIn, shouldCheckModels } = require('./checkin');
|
| 6 |
+
const { siteFetch } = require('./site-http');
|
| 7 |
|
| 8 |
// 辅助函数:获取嵌套对象的值
|
| 9 |
function getNestedValue(obj, path) {
|
|
|
|
| 64 |
}
|
| 65 |
|
| 66 |
// Newapi/Veloera API:获取模型列表
|
| 67 |
+
async function fetchModelsNewapi(baseUrl, apiKey, userId, apiType, fastify, site) {
|
| 68 |
const url = new URL('api/user/models', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 69 |
const ac = new AbortController();
|
| 70 |
const timeout = setTimeout(() => ac.abort(), 15000);
|
|
|
|
| 74 |
|
| 75 |
try {
|
| 76 |
console.log(`[NEWAPI-REQ] GET ${url}`);
|
| 77 |
+
const res = await siteFetch(site, url, {
|
| 78 |
method: 'GET',
|
| 79 |
headers: {
|
| 80 |
'Authorization': `Bearer ${apiKey}`,
|
|
|
|
| 142 |
}
|
| 143 |
|
| 144 |
// Newapi/Veloera API:获取用户信息(billing)
|
| 145 |
+
async function fetchUserInfoNewapi(baseUrl, apiKey, userId, apiType, fastify, site) {
|
| 146 |
const url = new URL('api/user/self', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 147 |
const ac = new AbortController();
|
| 148 |
const timeout = setTimeout(() => ac.abort(), 10000);
|
|
|
|
| 151 |
|
| 152 |
try {
|
| 153 |
console.log(`[NEWAPI-REQ] GET ${url}`);
|
| 154 |
+
const res = await siteFetch(site, url, {
|
| 155 |
method: 'GET',
|
| 156 |
headers: {
|
| 157 |
'Authorization': `Bearer ${apiKey}`,
|
|
|
|
| 212 |
}
|
| 213 |
|
| 214 |
// DoneHub API:获取模型列表
|
| 215 |
+
async function fetchModelsDonehub(baseUrl, apiKey, fastify, site) {
|
| 216 |
const url = new URL('api/available_model', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 217 |
const ac = new AbortController();
|
| 218 |
const timeout = setTimeout(() => ac.abort(), 15000);
|
|
|
|
| 220 |
|
| 221 |
try {
|
| 222 |
console.log(`[DONEHUB-REQ] GET ${url}`);
|
| 223 |
+
const res = await siteFetch(site, url, {
|
| 224 |
method: 'GET',
|
| 225 |
headers: {
|
| 226 |
'Authorization': `Bearer ${apiKey}`,
|
|
|
|
| 276 |
}
|
| 277 |
|
| 278 |
// VOAPI API:获取用户信息(billing)
|
| 279 |
+
async function fetchUserInfoVoapi(baseUrl, jwtToken, fastify, site) {
|
| 280 |
const url = new URL('api/user/info', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 281 |
const ac = new AbortController();
|
| 282 |
const timeout = setTimeout(() => ac.abort(), 10000);
|
| 283 |
|
| 284 |
try {
|
| 285 |
console.log(`[VOAPI-REQ] GET ${url}`);
|
| 286 |
+
const res = await siteFetch(site, url, {
|
| 287 |
method: 'GET',
|
| 288 |
headers: {
|
| 289 |
'Authorization': jwtToken, // VOAPI直接使用JWT token
|
|
|
|
| 328 |
}
|
| 329 |
|
| 330 |
// DoneHub API:获取用户信息(billing)
|
| 331 |
+
async function fetchUserInfoDonehub(baseUrl, apiKey, fastify, site) {
|
| 332 |
const url = new URL('api/user/self', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 333 |
const ac = new AbortController();
|
| 334 |
const timeout = setTimeout(() => ac.abort(), 10000);
|
| 335 |
|
| 336 |
try {
|
| 337 |
console.log(`[DONEHUB-REQ] GET ${url}`);
|
| 338 |
+
const res = await siteFetch(site, url, {
|
| 339 |
method: 'GET',
|
| 340 |
headers: {
|
| 341 |
'Authorization': `Bearer ${apiKey}`,
|
|
|
|
| 384 |
}
|
| 385 |
|
| 386 |
// 获取billing订阅额度信息
|
| 387 |
+
async function fetchBillingSubscription(baseUrl, apiKey, fastify, site) {
|
| 388 |
const url = new URL('v1/dashboard/billing/subscription', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 389 |
const ac = new AbortController();
|
| 390 |
const timeout = setTimeout(() => ac.abort(), 10000);
|
| 391 |
|
| 392 |
try {
|
| 393 |
console.log(`[BILLING-REQ] GET ${url}`);
|
| 394 |
+
const res = await siteFetch(site, url, {
|
| 395 |
method: 'GET',
|
| 396 |
headers: {
|
| 397 |
'Authorization': `Bearer ${apiKey}`,
|
|
|
|
| 452 |
}
|
| 453 |
}
|
| 454 |
|
| 455 |
+
const res = await siteFetch(site, site.billingUrl, {
|
| 456 |
method: 'GET',
|
| 457 |
headers,
|
| 458 |
signal: ac.signal
|
|
|
|
| 512 |
}
|
| 513 |
|
| 514 |
// 获取billing使用量信息
|
| 515 |
+
async function fetchBillingUsage(baseUrl, apiKey, fastify, site) {
|
| 516 |
const url = new URL('v1/dashboard/billing/usage', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 517 |
const ac = new AbortController();
|
| 518 |
const timeout = setTimeout(() => ac.abort(), 10000);
|
| 519 |
|
| 520 |
try {
|
| 521 |
console.log(`[BILLING-REQ] GET ${url}`);
|
| 522 |
+
const res = await siteFetch(site, url, {
|
| 523 |
method: 'GET',
|
| 524 |
headers: {
|
| 525 |
'Authorization': `Bearer ${apiKey}`,
|
|
|
|
| 553 |
}
|
| 554 |
}
|
| 555 |
|
| 556 |
+
async function fetchModels(baseUrl, apiKey, fastify, site) {
|
| 557 |
// 使用相对路径(不带前导/)以保留 baseUrl 中的路径部分(如 /api)
|
| 558 |
const url = new URL('v1/models', baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
| 559 |
const ac = new AbortController();
|
|
|
|
| 564 |
// VERSION: v2.0-simplified (只用2个头,模仿Python)
|
| 565 |
fastify?.log?.info({ msg: 'Fetching with v2.0-simplified headers', url: url.toString() });
|
| 566 |
|
| 567 |
+
const res = await siteFetch(site, url, {
|
| 568 |
method: 'GET',
|
| 569 |
headers: {
|
| 570 |
'Authorization': `Bearer ${apiKey}`,
|
|
|
|
| 739 |
}
|
| 740 |
if (!site.unlimitedQuota) {
|
| 741 |
billingPromises = Promise.allSettled([
|
| 742 |
+
fetchUserInfoNewapi(site.baseUrl, apiKey, site.userId || '1', site.apiType, fastify, site)
|
| 743 |
]);
|
| 744 |
}
|
| 745 |
+
fetchModelsFunc = () => fetchModelsNewapi(site.baseUrl, apiKey, site.userId || '1', site.apiType, fastify, site);
|
| 746 |
} else if (site.apiType === 'donehub') {
|
| 747 |
// DoneHub:不需要userId
|
| 748 |
if (!site.unlimitedQuota) {
|
| 749 |
billingPromises = Promise.allSettled([
|
| 750 |
+
fetchUserInfoDonehub(site.baseUrl, apiKey, fastify, site)
|
| 751 |
]);
|
| 752 |
}
|
| 753 |
+
fetchModelsFunc = () => fetchModelsDonehub(site.baseUrl, apiKey, fastify, site);
|
| 754 |
} else if (site.apiType === 'voapi') {
|
| 755 |
// VOAPI:使用JWT token获取用量,apiKey获取模型
|
| 756 |
if (!site.unlimitedQuota) {
|
| 757 |
const jwtToken = site.billingAuthValue ? decrypt(site.billingAuthValue) : null;
|
| 758 |
if (jwtToken) {
|
| 759 |
billingPromises = Promise.allSettled([
|
| 760 |
+
fetchUserInfoVoapi(site.baseUrl, jwtToken, fastify, site)
|
| 761 |
]);
|
| 762 |
} else {
|
| 763 |
console.log(`[VOAPI-WARN] No JWT token configured for billing`);
|
| 764 |
}
|
| 765 |
}
|
| 766 |
+
fetchModelsFunc = () => fetchModels(site.baseUrl, apiKey, fastify, site); // 使用标准OpenAI模式获取模型
|
| 767 |
} else {
|
| 768 |
// Other: 使用原有的OpenAI兼容方式或自定义billing
|
| 769 |
if (!site.unlimitedQuota) {
|
|
|
|
| 775 |
} else {
|
| 776 |
// 使用默认的OpenAI兼容billing
|
| 777 |
billingPromises = Promise.allSettled([
|
| 778 |
+
fetchBillingSubscription(site.baseUrl, apiKey, fastify, site),
|
| 779 |
+
fetchBillingUsage(site.baseUrl, apiKey, fastify, site)
|
| 780 |
]);
|
| 781 |
}
|
| 782 |
}
|
| 783 |
+
fetchModelsFunc = () => fetchModels(site.baseUrl, apiKey, fastify, site);
|
| 784 |
}
|
| 785 |
|
| 786 |
try {
|
server/src/server.js
CHANGED
|
@@ -42,9 +42,6 @@ async function buildServer() {
|
|
| 42 |
|
| 43 |
await fastify.register(routes);
|
| 44 |
|
| 45 |
-
// 初始化认证模块
|
| 46 |
-
await initAuth(fastify);
|
| 47 |
-
|
| 48 |
if (fs.existsSync(staticRoot)) {
|
| 49 |
fastify.setNotFoundHandler((req, reply) => {
|
| 50 |
// For SPA, serve index.html for non-API routes
|
|
@@ -77,10 +74,18 @@ async function buildServer() {
|
|
| 77 |
return fastify;
|
| 78 |
}
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
// eslint-disable-next-line no-console
|
| 84 |
console.error(err);
|
| 85 |
process.exit(1);
|
| 86 |
});
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
await fastify.register(routes);
|
| 44 |
|
|
|
|
|
|
|
|
|
|
| 45 |
if (fs.existsSync(staticRoot)) {
|
| 46 |
fastify.setNotFoundHandler((req, reply) => {
|
| 47 |
// For SPA, serve index.html for non-API routes
|
|
|
|
| 74 |
return fastify;
|
| 75 |
}
|
| 76 |
|
| 77 |
+
async function startServer() {
|
| 78 |
+
const app = await buildServer();
|
| 79 |
+
await app.listen({ port: CONFIG.PORT, host: '0.0.0.0' });
|
| 80 |
+
return app;
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
if (require.main === module) {
|
| 84 |
+
startServer().catch((err) => {
|
| 85 |
// eslint-disable-next-line no-console
|
| 86 |
console.error(err);
|
| 87 |
process.exit(1);
|
| 88 |
});
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
module.exports = { buildServer, startServer };
|
server/src/site-http.js
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const crypto = require('crypto');
|
| 2 |
+
const fetchModule = require('node-fetch');
|
| 3 |
+
const fetch = fetchModule;
|
| 4 |
+
const { Headers, Response } = fetchModule;
|
| 5 |
+
const { HttpProxyAgent } = require('http-proxy-agent');
|
| 6 |
+
const { HttpsProxyAgent } = require('https-proxy-agent');
|
| 7 |
+
const { SocksProxyAgent } = require('socks-proxy-agent');
|
| 8 |
+
const { decrypt } = require('./crypto');
|
| 9 |
+
|
| 10 |
+
const SUPPORTED_PROXY_PROTOCOLS = new Set(['http:', 'https:', 'socks:', 'socks4:', 'socks5:']);
|
| 11 |
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
| 12 |
+
const BUNKERWEB_MARKERS = [/BunkerWeb/i, /Bot Detection/i, /Please wait while we check if you are a Human/i];
|
| 13 |
+
const DEFAULT_MAX_REDIRECTS = 10;
|
| 14 |
+
const DEFAULT_MAX_CHALLENGE_ATTEMPTS = 2;
|
| 15 |
+
const agentCache = new Map();
|
| 16 |
+
|
| 17 |
+
function createValidationError(message) {
|
| 18 |
+
const error = new Error(message);
|
| 19 |
+
error.statusCode = 400;
|
| 20 |
+
return error;
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
function createFetchError(message, details = {}) {
|
| 24 |
+
const error = new Error(message);
|
| 25 |
+
Object.assign(error, details);
|
| 26 |
+
return error;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
function normalizeProxyUrl(proxyUrl) {
|
| 30 |
+
if (proxyUrl === undefined || proxyUrl === null) return null;
|
| 31 |
+
const value = String(proxyUrl).trim();
|
| 32 |
+
return value || null;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
function parseProxyUrl(proxyUrl) {
|
| 36 |
+
const normalized = normalizeProxyUrl(proxyUrl);
|
| 37 |
+
if (!normalized) return null;
|
| 38 |
+
|
| 39 |
+
let parsed;
|
| 40 |
+
try {
|
| 41 |
+
parsed = new URL(normalized);
|
| 42 |
+
} catch (error) {
|
| 43 |
+
throw createValidationError('代理地址格式无效,请输入完整的代理 URL');
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
if (!SUPPORTED_PROXY_PROTOCOLS.has(parsed.protocol)) {
|
| 47 |
+
throw createValidationError('代理协议仅支持 http、https、socks 和 socks5');
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
return parsed;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
function resolveSiteProxyUrl(site) {
|
| 54 |
+
if (!site) return null;
|
| 55 |
+
|
| 56 |
+
if (typeof site === 'string') {
|
| 57 |
+
const normalized = normalizeProxyUrl(site);
|
| 58 |
+
parseProxyUrl(normalized);
|
| 59 |
+
return normalized;
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
if ('proxyUrl' in site) {
|
| 63 |
+
const normalized = normalizeProxyUrl(site.proxyUrl);
|
| 64 |
+
parseProxyUrl(normalized);
|
| 65 |
+
return normalized;
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
if (!site.proxyUrlEnc) return null;
|
| 69 |
+
|
| 70 |
+
const proxyUrl = normalizeProxyUrl(decrypt(site.proxyUrlEnc));
|
| 71 |
+
parseProxyUrl(proxyUrl);
|
| 72 |
+
return proxyUrl;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
function getAgentFactory(proxyUrl) {
|
| 76 |
+
const parsedProxyUrl = parseProxyUrl(proxyUrl);
|
| 77 |
+
if (!parsedProxyUrl) return undefined;
|
| 78 |
+
|
| 79 |
+
const cacheKey = parsedProxyUrl.toString();
|
| 80 |
+
let agentFactory = agentCache.get(cacheKey);
|
| 81 |
+
|
| 82 |
+
if (!agentFactory) {
|
| 83 |
+
const isSocksProxy = parsedProxyUrl.protocol.startsWith('socks');
|
| 84 |
+
const httpAgent = isSocksProxy ? new SocksProxyAgent(cacheKey) : new HttpProxyAgent(cacheKey);
|
| 85 |
+
const httpsAgent = isSocksProxy ? new SocksProxyAgent(cacheKey) : new HttpsProxyAgent(cacheKey);
|
| 86 |
+
|
| 87 |
+
agentFactory = (parsedRequestUrl) => (parsedRequestUrl.protocol === 'http:' ? httpAgent : httpsAgent);
|
| 88 |
+
agentCache.set(cacheKey, agentFactory);
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
return agentFactory;
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
function buildSiteFetchOptions(site, options = {}) {
|
| 95 |
+
const proxyUrl = resolveSiteProxyUrl(site);
|
| 96 |
+
if (!proxyUrl) return { ...options };
|
| 97 |
+
|
| 98 |
+
return {
|
| 99 |
+
...options,
|
| 100 |
+
agent: getAgentFactory(proxyUrl)
|
| 101 |
+
};
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
function parseCookieHeader(cookieHeader) {
|
| 105 |
+
const cookies = new Map();
|
| 106 |
+
if (!cookieHeader) return cookies;
|
| 107 |
+
|
| 108 |
+
const parts = String(cookieHeader).split(';');
|
| 109 |
+
for (const part of parts) {
|
| 110 |
+
const trimmed = part.trim();
|
| 111 |
+
if (!trimmed) continue;
|
| 112 |
+
const separatorIndex = trimmed.indexOf('=');
|
| 113 |
+
if (separatorIndex <= 0) continue;
|
| 114 |
+
const name = trimmed.slice(0, separatorIndex).trim();
|
| 115 |
+
const value = trimmed.slice(separatorIndex + 1).trim();
|
| 116 |
+
if (!name) continue;
|
| 117 |
+
cookies.set(name, value);
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
return cookies;
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
function serializeCookieJar(cookieJar) {
|
| 124 |
+
return Array.from(cookieJar.entries())
|
| 125 |
+
.map(([name, value]) => `${name}=${value}`)
|
| 126 |
+
.join('; ');
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
function seedCookieJar(headersInit) {
|
| 130 |
+
const headers = new Headers(headersInit || {});
|
| 131 |
+
return parseCookieHeader(headers.get('cookie'));
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
function updateCookieJar(cookieJar, response) {
|
| 135 |
+
const setCookies = response?.headers?.raw?.()['set-cookie'] || [];
|
| 136 |
+
|
| 137 |
+
for (const setCookie of setCookies) {
|
| 138 |
+
const [cookiePart] = String(setCookie).split(';');
|
| 139 |
+
const separatorIndex = cookiePart.indexOf('=');
|
| 140 |
+
if (separatorIndex <= 0) continue;
|
| 141 |
+
const name = cookiePart.slice(0, separatorIndex).trim();
|
| 142 |
+
const value = cookiePart.slice(separatorIndex + 1).trim();
|
| 143 |
+
if (!name) continue;
|
| 144 |
+
|
| 145 |
+
if (!value) {
|
| 146 |
+
cookieJar.delete(name);
|
| 147 |
+
continue;
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
cookieJar.set(name, value);
|
| 151 |
+
}
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
function applyCookieJar(headersInit, cookieJar) {
|
| 155 |
+
const headers = new Headers(headersInit || {});
|
| 156 |
+
if (cookieJar.size > 0) {
|
| 157 |
+
headers.set('cookie', serializeCookieJar(cookieJar));
|
| 158 |
+
}
|
| 159 |
+
return headers;
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
function buildFetchRequestOptions(site, options, cookieJar) {
|
| 163 |
+
return buildSiteFetchOptions(site, {
|
| 164 |
+
...options,
|
| 165 |
+
headers: applyCookieJar(options.headers, cookieJar),
|
| 166 |
+
redirect: 'manual'
|
| 167 |
+
});
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
function isRedirectResponse(response) {
|
| 171 |
+
return response && REDIRECT_STATUSES.has(response.status);
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
function getResponseUrl(response, fallbackUrl) {
|
| 175 |
+
return response?.url || String(fallbackUrl);
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
function getRedirectTarget(response, currentUrl) {
|
| 179 |
+
const location = response?.headers?.get?.('location');
|
| 180 |
+
if (!location) return null;
|
| 181 |
+
return new URL(location, getResponseUrl(response, currentUrl)).toString();
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
function getRedirectedOptions(options, response, currentUrl, nextUrl) {
|
| 185 |
+
const headers = new Headers(options.headers || {});
|
| 186 |
+
const method = (options.method || 'GET').toUpperCase();
|
| 187 |
+
const nextMethod = method;
|
| 188 |
+
let body = options.body;
|
| 189 |
+
let redirectMethod = nextMethod;
|
| 190 |
+
|
| 191 |
+
if (response.status === 303 || ((response.status === 301 || response.status === 302) && method === 'POST')) {
|
| 192 |
+
redirectMethod = 'GET';
|
| 193 |
+
body = undefined;
|
| 194 |
+
headers.delete('content-length');
|
| 195 |
+
headers.delete('content-type');
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
const previousUrl = new URL(String(currentUrl));
|
| 199 |
+
const redirectUrl = new URL(String(nextUrl));
|
| 200 |
+
if (previousUrl.origin !== redirectUrl.origin) {
|
| 201 |
+
headers.delete('authorization');
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
return {
|
| 205 |
+
...options,
|
| 206 |
+
method: redirectMethod,
|
| 207 |
+
body,
|
| 208 |
+
headers
|
| 209 |
+
};
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
function isHtmlResponse(response) {
|
| 213 |
+
const contentType = response?.headers?.get?.('content-type') || '';
|
| 214 |
+
return /text\/html/i.test(contentType);
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
function readAttributeMap(tag) {
|
| 218 |
+
const attributes = {};
|
| 219 |
+
const attributePattern = /([a-zA-Z0-9:_-]+)(?:=("([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
|
| 220 |
+
let match;
|
| 221 |
+
|
| 222 |
+
while ((match = attributePattern.exec(tag)) !== null) {
|
| 223 |
+
const name = match[1].toLowerCase();
|
| 224 |
+
const value = match[3] ?? match[4] ?? match[5] ?? '';
|
| 225 |
+
attributes[name] = value;
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
return attributes;
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
function extractHiddenInputs(html) {
|
| 232 |
+
const hiddenInputs = [];
|
| 233 |
+
const inputPattern = /<input\b[^>]*>/gi;
|
| 234 |
+
let match;
|
| 235 |
+
|
| 236 |
+
while ((match = inputPattern.exec(html)) !== null) {
|
| 237 |
+
const attributes = readAttributeMap(match[0]);
|
| 238 |
+
if ((attributes.type || '').toLowerCase() !== 'hidden') continue;
|
| 239 |
+
if (!attributes.name) continue;
|
| 240 |
+
hiddenInputs.push({
|
| 241 |
+
name: attributes.name,
|
| 242 |
+
value: attributes.value || '',
|
| 243 |
+
id: attributes.id || ''
|
| 244 |
+
});
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
return hiddenInputs;
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
function extractPostFormAction(html, responseUrl) {
|
| 251 |
+
const formPattern = /<form\b[^>]*>/gi;
|
| 252 |
+
let match;
|
| 253 |
+
|
| 254 |
+
while ((match = formPattern.exec(html)) !== null) {
|
| 255 |
+
const attributes = readAttributeMap(match[0]);
|
| 256 |
+
const method = (attributes.method || 'get').toLowerCase();
|
| 257 |
+
if (method !== 'post') continue;
|
| 258 |
+
const action = attributes.action || responseUrl;
|
| 259 |
+
return new URL(action, responseUrl).toString();
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
return new URL('/challenge', responseUrl).toString();
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
function hasBunkerWebMarkers(html) {
|
| 266 |
+
return BUNKERWEB_MARKERS.some((pattern) => pattern.test(html));
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
function extractBunkerWebChallenge(html, responseUrl) {
|
| 270 |
+
const responsePath = responseUrl ? new URL(responseUrl).pathname : '';
|
| 271 |
+
const hiddenInputs = extractHiddenInputs(html);
|
| 272 |
+
const looksLikeChallengePath = /\/challenge\/?$/i.test(responsePath);
|
| 273 |
+
const looksLikeChallengeHtml = hasBunkerWebMarkers(html) || hiddenInputs.some((input) => input.name === 'challenge' || input.id === 'challenge');
|
| 274 |
+
|
| 275 |
+
if (!looksLikeChallengePath && !looksLikeChallengeHtml) {
|
| 276 |
+
return null;
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
const seedMatch = html.match(/digestMessage\(\s*["']([^"']+)["']\s*\+\s*[^)]*?\.toString\(\)\s*\)/i);
|
| 280 |
+
const prefixMatch = html.match(/startsWith\(\s*["']([^"']+)["']\s*\)/i);
|
| 281 |
+
const challengeField = hiddenInputs.find((input) => input.name === 'challenge' || input.id === 'challenge') || hiddenInputs[0];
|
| 282 |
+
|
| 283 |
+
if (!seedMatch || !prefixMatch || !challengeField) {
|
| 284 |
+
return {
|
| 285 |
+
kind: 'blocked',
|
| 286 |
+
responseUrl,
|
| 287 |
+
html
|
| 288 |
+
};
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
return {
|
| 292 |
+
kind: 'challenge',
|
| 293 |
+
responseUrl,
|
| 294 |
+
actionUrl: extractPostFormAction(html, responseUrl),
|
| 295 |
+
seed: seedMatch[1],
|
| 296 |
+
prefix: prefixMatch[1],
|
| 297 |
+
fieldName: challengeField.name,
|
| 298 |
+
hiddenInputs,
|
| 299 |
+
html
|
| 300 |
+
};
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
function assertNotAborted(signal) {
|
| 304 |
+
if (signal?.aborted) {
|
| 305 |
+
throw createFetchError('请求已取消', { name: 'AbortError' });
|
| 306 |
+
}
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
function solveHashPrefixChallenge(seed, prefix, signal) {
|
| 310 |
+
for (let nonce = 0; nonce < 10_000_000; nonce += 1) {
|
| 311 |
+
if (nonce % 2000 === 0) assertNotAborted(signal);
|
| 312 |
+
const digest = crypto.createHash('sha256').update(`${seed}${nonce}`).digest('hex');
|
| 313 |
+
if (digest.startsWith(prefix)) {
|
| 314 |
+
return String(nonce);
|
| 315 |
+
}
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
throw createFetchError('BunkerWeb 人机验证求解失败:未找到有效挑战答案');
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
async function completeBunkerWebChallenge(site, fetchImpl, challengeInfo, cookieJar, options) {
|
| 322 |
+
const challengeValue = solveHashPrefixChallenge(challengeInfo.seed, challengeInfo.prefix, options.signal);
|
| 323 |
+
const formData = new URLSearchParams();
|
| 324 |
+
|
| 325 |
+
for (const input of challengeInfo.hiddenInputs) {
|
| 326 |
+
formData.set(input.name, input.value || '');
|
| 327 |
+
}
|
| 328 |
+
formData.set(challengeInfo.fieldName, challengeValue);
|
| 329 |
+
|
| 330 |
+
const headers = new Headers(options.headers || {});
|
| 331 |
+
headers.set('content-type', 'application/x-www-form-urlencoded');
|
| 332 |
+
headers.set('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
|
| 333 |
+
headers.set('referer', challengeInfo.responseUrl);
|
| 334 |
+
headers.delete('content-length');
|
| 335 |
+
|
| 336 |
+
const response = await fetchImpl(
|
| 337 |
+
challengeInfo.actionUrl,
|
| 338 |
+
buildFetchRequestOptions(site, {
|
| 339 |
+
...options,
|
| 340 |
+
method: 'POST',
|
| 341 |
+
body: formData.toString(),
|
| 342 |
+
headers
|
| 343 |
+
}, cookieJar)
|
| 344 |
+
);
|
| 345 |
+
|
| 346 |
+
updateCookieJar(cookieJar, response);
|
| 347 |
+
|
| 348 |
+
if (isRedirectResponse(response)) {
|
| 349 |
+
return;
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
if (!isHtmlResponse(response) && response.ok) {
|
| 353 |
+
return;
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
const rawResponse = await response.text();
|
| 357 |
+
throw createFetchError('BunkerWeb 人机验证提交失败,代理未能通过验证', {
|
| 358 |
+
statusCode: response.status,
|
| 359 |
+
rawResponse
|
| 360 |
+
});
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
async function inspectHtmlResponse(response, currentUrl) {
|
| 364 |
+
const rawResponse = await response.text();
|
| 365 |
+
const responseUrl = getResponseUrl(response, currentUrl);
|
| 366 |
+
const bunkerWebInfo = extractBunkerWebChallenge(rawResponse, responseUrl);
|
| 367 |
+
|
| 368 |
+
if (!bunkerWebInfo) {
|
| 369 |
+
return {
|
| 370 |
+
kind: 'response',
|
| 371 |
+
response: new Response(rawResponse, {
|
| 372 |
+
status: response.status,
|
| 373 |
+
statusText: response.statusText,
|
| 374 |
+
headers: response.headers
|
| 375 |
+
})
|
| 376 |
+
};
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
if (bunkerWebInfo.kind === 'challenge') {
|
| 380 |
+
return {
|
| 381 |
+
kind: 'challenge',
|
| 382 |
+
challengeInfo: bunkerWebInfo
|
| 383 |
+
};
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
throw createFetchError('站点启用了 BunkerWeb 人机验证,当前代理未通过验证', {
|
| 387 |
+
statusCode: response.status,
|
| 388 |
+
rawResponse
|
| 389 |
+
});
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
async function siteFetch(site, url, options = {}, extra = {}) {
|
| 393 |
+
const fetchImpl = extra.fetchImpl || fetch;
|
| 394 |
+
const maxRedirects = extra.maxRedirects || DEFAULT_MAX_REDIRECTS;
|
| 395 |
+
const maxChallengeAttempts = extra.maxChallengeAttempts || DEFAULT_MAX_CHALLENGE_ATTEMPTS;
|
| 396 |
+
const originalUrl = String(url);
|
| 397 |
+
const originalOptions = { ...options };
|
| 398 |
+
const cookieJar = seedCookieJar(originalOptions.headers);
|
| 399 |
+
|
| 400 |
+
let currentUrl = originalUrl;
|
| 401 |
+
let currentOptions = { ...originalOptions };
|
| 402 |
+
let redirectCount = 0;
|
| 403 |
+
let challengeCount = 0;
|
| 404 |
+
|
| 405 |
+
while (true) {
|
| 406 |
+
assertNotAborted(currentOptions.signal);
|
| 407 |
+
|
| 408 |
+
const response = await fetchImpl(currentUrl, buildFetchRequestOptions(site, currentOptions, cookieJar));
|
| 409 |
+
updateCookieJar(cookieJar, response);
|
| 410 |
+
|
| 411 |
+
if (isRedirectResponse(response)) {
|
| 412 |
+
if (redirectCount >= maxRedirects) {
|
| 413 |
+
throw createFetchError('请求重定向次数过多,已停止访问', { statusCode: response.status });
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
const nextUrl = getRedirectTarget(response, currentUrl);
|
| 417 |
+
if (!nextUrl) {
|
| 418 |
+
return response;
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
redirectCount += 1;
|
| 422 |
+
currentOptions = getRedirectedOptions(currentOptions, response, currentUrl, nextUrl);
|
| 423 |
+
currentUrl = nextUrl;
|
| 424 |
+
continue;
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
if (isHtmlResponse(response) || response.status >= 400) {
|
| 428 |
+
const inspected = await inspectHtmlResponse(response, currentUrl);
|
| 429 |
+
|
| 430 |
+
if (inspected.kind === 'response') {
|
| 431 |
+
return inspected.response;
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
if (challengeCount >= maxChallengeAttempts) {
|
| 435 |
+
throw createFetchError('BunkerWeb 人机验证次数过多,代理未能完成校验', {
|
| 436 |
+
statusCode: response.status,
|
| 437 |
+
rawResponse: inspected.challengeInfo.html
|
| 438 |
+
});
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
challengeCount += 1;
|
| 442 |
+
await completeBunkerWebChallenge(site, fetchImpl, inspected.challengeInfo, cookieJar, currentOptions);
|
| 443 |
+
currentUrl = originalUrl;
|
| 444 |
+
currentOptions = { ...originalOptions };
|
| 445 |
+
redirectCount = 0;
|
| 446 |
+
continue;
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
return response;
|
| 450 |
+
}
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
module.exports = {
|
| 454 |
+
SUPPORTED_PROXY_PROTOCOLS,
|
| 455 |
+
normalizeProxyUrl,
|
| 456 |
+
parseProxyUrl,
|
| 457 |
+
resolveSiteProxyUrl,
|
| 458 |
+
buildSiteFetchOptions,
|
| 459 |
+
siteFetch,
|
| 460 |
+
createValidationError
|
| 461 |
+
};
|
server/tests/site-proxy.test.js
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const test = require('node:test');
|
| 2 |
+
const assert = require('node:assert/strict');
|
| 3 |
+
const crypto = require('crypto');
|
| 4 |
+
const fs = require('fs');
|
| 5 |
+
const os = require('os');
|
| 6 |
+
const path = require('path');
|
| 7 |
+
const http = require('http');
|
| 8 |
+
const { once } = require('events');
|
| 9 |
+
const { execFileSync } = require('child_process');
|
| 10 |
+
|
| 11 |
+
process.env.NODE_ENV = 'test';
|
| 12 |
+
process.env.SKIP_AUTH = 'true';
|
| 13 |
+
process.env.JWT_SECRET = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
|
| 14 |
+
process.env.ENCRYPTION_KEY = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
|
| 15 |
+
process.env.ADMIN_EMAIL = 'admin@example.com';
|
| 16 |
+
process.env.ADMIN_PASSWORD = 'admin123456';
|
| 17 |
+
|
| 18 |
+
const serverRoot = path.resolve(__dirname, '..');
|
| 19 |
+
const CHALLENGE_SEED = 'seed-28';
|
| 20 |
+
const CHALLENGE_PREFIX = '0000';
|
| 21 |
+
let tempDir;
|
| 22 |
+
let buildServer;
|
| 23 |
+
let prisma;
|
| 24 |
+
let app;
|
| 25 |
+
|
| 26 |
+
const { parseProxyUrl, buildSiteFetchOptions, siteFetch } = require('../src/site-http');
|
| 27 |
+
|
| 28 |
+
async function listen(server) {
|
| 29 |
+
server.listen(0, '127.0.0.1');
|
| 30 |
+
await once(server, 'listening');
|
| 31 |
+
return server.address().port;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
function parseCookies(cookieHeader) {
|
| 35 |
+
const cookies = new Map();
|
| 36 |
+
if (!cookieHeader) return cookies;
|
| 37 |
+
|
| 38 |
+
for (const segment of String(cookieHeader).split(';')) {
|
| 39 |
+
const trimmed = segment.trim();
|
| 40 |
+
if (!trimmed) continue;
|
| 41 |
+
const separatorIndex = trimmed.indexOf('=');
|
| 42 |
+
if (separatorIndex <= 0) continue;
|
| 43 |
+
cookies.set(trimmed.slice(0, separatorIndex), trimmed.slice(separatorIndex + 1));
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
return cookies;
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
function createUpstreamServer() {
|
| 50 |
+
const requests = [];
|
| 51 |
+
const server = http.createServer((req, res) => {
|
| 52 |
+
const url = new URL(req.url, `http://${req.headers.host}`);
|
| 53 |
+
const bodyChunks = [];
|
| 54 |
+
|
| 55 |
+
req.on('data', (chunk) => bodyChunks.push(chunk));
|
| 56 |
+
req.on('end', () => {
|
| 57 |
+
requests.push({
|
| 58 |
+
path: url.pathname,
|
| 59 |
+
method: req.method,
|
| 60 |
+
viaProxy: req.headers['x-through-proxy'] === 'yes'
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
res.setHeader('Content-Type', 'application/json');
|
| 64 |
+
|
| 65 |
+
if (url.pathname === '/v1/models') {
|
| 66 |
+
res.end(JSON.stringify({ data: [{ id: 'gpt-4o-mini' }, { id: 'claude-3-5-sonnet' }] }));
|
| 67 |
+
return;
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
if (url.pathname === '/v1/dashboard/billing/subscription') {
|
| 71 |
+
res.end(JSON.stringify({ system_hard_limit_usd: 12.5 }));
|
| 72 |
+
return;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
if (url.pathname === '/v1/dashboard/billing/usage') {
|
| 76 |
+
res.end(JSON.stringify({ total_usage: 250 }));
|
| 77 |
+
return;
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
if (url.pathname === '/api/token/') {
|
| 81 |
+
res.end(JSON.stringify({ success: true, data: [{ id: 1, key: 'tok-1' }] }));
|
| 82 |
+
return;
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
res.statusCode = 404;
|
| 86 |
+
res.end(JSON.stringify({ error: `Unhandled path: ${url.pathname}` }));
|
| 87 |
+
});
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
return { server, requests };
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
function renderBunkerWebChallengeHtml() {
|
| 94 |
+
return `<!doctype html>
|
| 95 |
+
<html>
|
| 96 |
+
<head>
|
| 97 |
+
<title>Bot Detection</title>
|
| 98 |
+
</head>
|
| 99 |
+
<body>
|
| 100 |
+
<h1>Please wait while we check if you are a Human</h1>
|
| 101 |
+
<p>Protected by BunkerWeb</p>
|
| 102 |
+
<form method="post" class="hidden" action="/challenge" id="form">
|
| 103 |
+
<input type="hidden" name="challenge" id="challenge" value="" />
|
| 104 |
+
</form>
|
| 105 |
+
<script>
|
| 106 |
+
async function digestMessage(message) {
|
| 107 |
+
return message;
|
| 108 |
+
}
|
| 109 |
+
async function run() {
|
| 110 |
+
let a = 0;
|
| 111 |
+
while (!(await digestMessage("${CHALLENGE_SEED}" + a.toString())).startsWith("${CHALLENGE_PREFIX}")) {
|
| 112 |
+
a += 1;
|
| 113 |
+
}
|
| 114 |
+
document.getElementById("challenge").value = a.toString();
|
| 115 |
+
document.getElementById("form").submit();
|
| 116 |
+
}
|
| 117 |
+
run();
|
| 118 |
+
</script>
|
| 119 |
+
</body>
|
| 120 |
+
</html>`;
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
function createBunkerWebProtectedServer() {
|
| 124 |
+
const requests = [];
|
| 125 |
+
const server = http.createServer((req, res) => {
|
| 126 |
+
const url = new URL(req.url, `http://${req.headers.host}`);
|
| 127 |
+
const bodyChunks = [];
|
| 128 |
+
|
| 129 |
+
req.on('data', (chunk) => bodyChunks.push(chunk));
|
| 130 |
+
req.on('end', () => {
|
| 131 |
+
const cookies = parseCookies(req.headers.cookie);
|
| 132 |
+
const requestBody = Buffer.concat(bodyChunks).toString('utf8');
|
| 133 |
+
|
| 134 |
+
requests.push({
|
| 135 |
+
path: url.pathname,
|
| 136 |
+
method: req.method,
|
| 137 |
+
viaProxy: req.headers['x-through-proxy'] === 'yes',
|
| 138 |
+
cookie: req.headers.cookie || '',
|
| 139 |
+
body: requestBody
|
| 140 |
+
});
|
| 141 |
+
|
| 142 |
+
if (url.pathname === '/challenge' && req.method === 'GET') {
|
| 143 |
+
res.statusCode = 200;
|
| 144 |
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
| 145 |
+
res.end(renderBunkerWebChallengeHtml());
|
| 146 |
+
return;
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
if (url.pathname === '/challenge' && req.method === 'POST') {
|
| 150 |
+
const params = new URLSearchParams(requestBody);
|
| 151 |
+
const challengeValue = params.get('challenge') || '';
|
| 152 |
+
const expectedHash = crypto.createHash('sha256').update(`${CHALLENGE_SEED}${challengeValue}`).digest('hex');
|
| 153 |
+
const targetPath = decodeURIComponent(cookies.get('bw_target') || '/api/user/models');
|
| 154 |
+
|
| 155 |
+
if (!expectedHash.startsWith(CHALLENGE_PREFIX)) {
|
| 156 |
+
res.statusCode = 403;
|
| 157 |
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
| 158 |
+
res.end('<html><body><h1>Forbidden</h1><p>BunkerWeb</p></body></html>');
|
| 159 |
+
return;
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
res.statusCode = 302;
|
| 163 |
+
res.setHeader('Location', targetPath);
|
| 164 |
+
res.setHeader('Set-Cookie', [
|
| 165 |
+
'bw_verified=1; Path=/',
|
| 166 |
+
'bw_target=; Max-Age=0; Path=/'
|
| 167 |
+
]);
|
| 168 |
+
res.end();
|
| 169 |
+
return;
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
if ((url.pathname === '/api/user/models' || url.pathname === '/api/user/self') && cookies.get('bw_verified') !== '1') {
|
| 173 |
+
res.statusCode = 302;
|
| 174 |
+
res.setHeader('Location', '/challenge');
|
| 175 |
+
res.setHeader('Set-Cookie', `bw_target=${encodeURIComponent(url.pathname)}; Path=/`);
|
| 176 |
+
res.end();
|
| 177 |
+
return;
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
res.setHeader('Content-Type', 'application/json');
|
| 181 |
+
|
| 182 |
+
if (url.pathname === '/api/user/models') {
|
| 183 |
+
res.end(JSON.stringify({ success: true, data: ['gpt-4o-mini', 'claude-3-5-sonnet'] }));
|
| 184 |
+
return;
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
if (url.pathname === '/api/user/self') {
|
| 188 |
+
res.end(JSON.stringify({ success: true, data: { quota: 1250000, used_quota: 250000, status: 1 } }));
|
| 189 |
+
return;
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
res.statusCode = 404;
|
| 193 |
+
res.end(JSON.stringify({ success: false, message: `Unhandled path: ${url.pathname}` }));
|
| 194 |
+
});
|
| 195 |
+
});
|
| 196 |
+
|
| 197 |
+
return { server, requests };
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
function createHttpProxyServer() {
|
| 201 |
+
const requests = [];
|
| 202 |
+
const server = http.createServer((clientReq, clientRes) => {
|
| 203 |
+
const targetUrl = new URL(clientReq.url);
|
| 204 |
+
requests.push({ method: clientReq.method, url: clientReq.url });
|
| 205 |
+
|
| 206 |
+
const proxyReq = http.request({
|
| 207 |
+
hostname: targetUrl.hostname,
|
| 208 |
+
port: targetUrl.port,
|
| 209 |
+
path: `${targetUrl.pathname}${targetUrl.search}`,
|
| 210 |
+
method: clientReq.method,
|
| 211 |
+
headers: {
|
| 212 |
+
...clientReq.headers,
|
| 213 |
+
host: targetUrl.host,
|
| 214 |
+
'x-through-proxy': 'yes'
|
| 215 |
+
}
|
| 216 |
+
}, (proxyRes) => {
|
| 217 |
+
clientRes.writeHead(proxyRes.statusCode || 500, proxyRes.headers);
|
| 218 |
+
proxyRes.pipe(clientRes);
|
| 219 |
+
});
|
| 220 |
+
|
| 221 |
+
proxyReq.on('error', (error) => {
|
| 222 |
+
clientRes.statusCode = 502;
|
| 223 |
+
clientRes.end(JSON.stringify({ error: error.message }));
|
| 224 |
+
});
|
| 225 |
+
|
| 226 |
+
clientReq.pipe(proxyReq);
|
| 227 |
+
});
|
| 228 |
+
|
| 229 |
+
return { server, requests };
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
async function createSite(payload) {
|
| 233 |
+
const response = await app.inject({
|
| 234 |
+
method: 'POST',
|
| 235 |
+
url: '/api/sites',
|
| 236 |
+
payload
|
| 237 |
+
});
|
| 238 |
+
|
| 239 |
+
assert.equal(response.statusCode, 200, response.body);
|
| 240 |
+
return response.json();
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
test.before(async () => {
|
| 244 |
+
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'simplehub-site-proxy-'));
|
| 245 |
+
process.env.DATABASE_URL = `file:${path.join(tempDir, 'db.sqlite')}`;
|
| 246 |
+
|
| 247 |
+
execFileSync('npx', ['prisma', 'db', 'push', '--force-reset', '--skip-generate'], {
|
| 248 |
+
cwd: serverRoot,
|
| 249 |
+
env: process.env,
|
| 250 |
+
stdio: 'inherit'
|
| 251 |
+
});
|
| 252 |
+
|
| 253 |
+
({ buildServer } = require('../src/server'));
|
| 254 |
+
({ prisma } = require('../src/db'));
|
| 255 |
+
app = await buildServer();
|
| 256 |
+
});
|
| 257 |
+
|
| 258 |
+
test.after(async () => {
|
| 259 |
+
if (app) await app.close();
|
| 260 |
+
if (prisma) await prisma.$disconnect();
|
| 261 |
+
if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true });
|
| 262 |
+
});
|
| 263 |
+
|
| 264 |
+
test.afterEach(async () => {
|
| 265 |
+
await prisma.modelDiff.deleteMany();
|
| 266 |
+
await prisma.modelSnapshot.deleteMany();
|
| 267 |
+
await prisma.site.deleteMany();
|
| 268 |
+
});
|
| 269 |
+
|
| 270 |
+
test('site-http validates proxy URLs and attaches proxy agents', async () => {
|
| 271 |
+
assert.equal(parseProxyUrl('socks5://user:pass@127.0.0.1:1080').protocol, 'socks5:');
|
| 272 |
+
assert.throws(() => parseProxyUrl('ftp://127.0.0.1:21'), /代理协议/);
|
| 273 |
+
|
| 274 |
+
const directOptions = buildSiteFetchOptions({ proxyUrl: null }, { method: 'GET' });
|
| 275 |
+
assert.equal(directOptions.agent, undefined);
|
| 276 |
+
|
| 277 |
+
let receivedOptions;
|
| 278 |
+
await siteFetch(
|
| 279 |
+
{ proxyUrl: 'http://127.0.0.1:7890' },
|
| 280 |
+
'http://example.com',
|
| 281 |
+
{ method: 'GET' },
|
| 282 |
+
{
|
| 283 |
+
fetchImpl: async (url, options) => {
|
| 284 |
+
receivedOptions = options;
|
| 285 |
+
return { ok: true };
|
| 286 |
+
}
|
| 287 |
+
}
|
| 288 |
+
);
|
| 289 |
+
|
| 290 |
+
assert.equal(typeof receivedOptions.agent, 'function');
|
| 291 |
+
assert.equal(receivedOptions.method, 'GET');
|
| 292 |
+
});
|
| 293 |
+
|
| 294 |
+
test('site CRUD persists encrypted proxyUrl and allows clearing it', async () => {
|
| 295 |
+
const created = await createSite({
|
| 296 |
+
name: 'proxy-site',
|
| 297 |
+
baseUrl: 'http://127.0.0.1:18080',
|
| 298 |
+
apiKey: 'sk-test',
|
| 299 |
+
apiType: 'other',
|
| 300 |
+
proxyUrl: 'http://user:pass@127.0.0.1:18888'
|
| 301 |
+
});
|
| 302 |
+
|
| 303 |
+
const savedSite = await prisma.site.findUnique({ where: { id: created.id } });
|
| 304 |
+
assert.ok(savedSite.proxyUrlEnc);
|
| 305 |
+
assert.notEqual(savedSite.proxyUrlEnc, 'http://user:pass@127.0.0.1:18888');
|
| 306 |
+
|
| 307 |
+
const detailResponse = await app.inject({
|
| 308 |
+
method: 'GET',
|
| 309 |
+
url: `/api/sites/${created.id}`
|
| 310 |
+
});
|
| 311 |
+
|
| 312 |
+
assert.equal(detailResponse.statusCode, 200, detailResponse.body);
|
| 313 |
+
assert.equal(detailResponse.json().proxyUrl, 'http://user:pass@127.0.0.1:18888');
|
| 314 |
+
|
| 315 |
+
const clearedResponse = await app.inject({
|
| 316 |
+
method: 'PATCH',
|
| 317 |
+
url: `/api/sites/${created.id}`,
|
| 318 |
+
payload: { proxyUrl: '' }
|
| 319 |
+
});
|
| 320 |
+
|
| 321 |
+
assert.equal(clearedResponse.statusCode, 200, clearedResponse.body);
|
| 322 |
+
|
| 323 |
+
const clearedSite = await prisma.site.findUnique({ where: { id: created.id } });
|
| 324 |
+
assert.equal(clearedSite.proxyUrlEnc, null);
|
| 325 |
+
|
| 326 |
+
const invalidResponse = await app.inject({
|
| 327 |
+
method: 'POST',
|
| 328 |
+
url: '/api/sites',
|
| 329 |
+
payload: {
|
| 330 |
+
name: 'invalid-proxy',
|
| 331 |
+
baseUrl: 'http://127.0.0.1:18080',
|
| 332 |
+
apiKey: 'sk-test',
|
| 333 |
+
proxyUrl: 'ftp://127.0.0.1:21'
|
| 334 |
+
}
|
| 335 |
+
});
|
| 336 |
+
|
| 337 |
+
assert.equal(invalidResponse.statusCode, 400, invalidResponse.body);
|
| 338 |
+
assert.match(invalidResponse.body, /代理协议/);
|
| 339 |
+
});
|
| 340 |
+
|
| 341 |
+
test('site checks and token proxy routes honor per-site proxy settings', async () => {
|
| 342 |
+
const upstream = createUpstreamServer();
|
| 343 |
+
const proxy = createHttpProxyServer();
|
| 344 |
+
const upstreamPort = await listen(upstream.server);
|
| 345 |
+
const proxyPort = await listen(proxy.server);
|
| 346 |
+
|
| 347 |
+
try {
|
| 348 |
+
const proxiedSite = await createSite({
|
| 349 |
+
name: 'proxied-site',
|
| 350 |
+
baseUrl: `http://127.0.0.1:${upstreamPort}`,
|
| 351 |
+
apiKey: 'sk-proxy',
|
| 352 |
+
apiType: 'other',
|
| 353 |
+
proxyUrl: `http://127.0.0.1:${proxyPort}`
|
| 354 |
+
});
|
| 355 |
+
|
| 356 |
+
const proxiedCheckResponse = await app.inject({
|
| 357 |
+
method: 'POST',
|
| 358 |
+
url: `/api/sites/${proxiedSite.id}/check?skipNotification=true`
|
| 359 |
+
});
|
| 360 |
+
|
| 361 |
+
assert.equal(proxiedCheckResponse.statusCode, 200, proxiedCheckResponse.body);
|
| 362 |
+
assert.equal(proxiedCheckResponse.json().ok, true);
|
| 363 |
+
assert.ok(proxy.requests.some((request) => request.url.includes('/v1/models')));
|
| 364 |
+
assert.ok(upstream.requests.some((request) => request.path === '/v1/models' && request.viaProxy));
|
| 365 |
+
|
| 366 |
+
const proxiedTokensResponse = await app.inject({
|
| 367 |
+
method: 'GET',
|
| 368 |
+
url: `/api/sites/${proxiedSite.id}/tokens`
|
| 369 |
+
});
|
| 370 |
+
|
| 371 |
+
assert.equal(proxiedTokensResponse.statusCode, 200, proxiedTokensResponse.body);
|
| 372 |
+
assert.ok(upstream.requests.some((request) => request.path === '/api/token/' && request.viaProxy));
|
| 373 |
+
|
| 374 |
+
const proxyRequestCount = proxy.requests.length;
|
| 375 |
+
|
| 376 |
+
const directSite = await createSite({
|
| 377 |
+
name: 'direct-site',
|
| 378 |
+
baseUrl: `http://127.0.0.1:${upstreamPort}`,
|
| 379 |
+
apiKey: 'sk-direct',
|
| 380 |
+
apiType: 'other'
|
| 381 |
+
});
|
| 382 |
+
|
| 383 |
+
const directCheckResponse = await app.inject({
|
| 384 |
+
method: 'POST',
|
| 385 |
+
url: `/api/sites/${directSite.id}/check?skipNotification=true`
|
| 386 |
+
});
|
| 387 |
+
|
| 388 |
+
assert.equal(directCheckResponse.statusCode, 200, directCheckResponse.body);
|
| 389 |
+
assert.equal(proxy.requests.length, proxyRequestCount);
|
| 390 |
+
assert.ok(upstream.requests.some((request) => request.path === '/v1/models' && !request.viaProxy));
|
| 391 |
+
} finally {
|
| 392 |
+
await Promise.all([
|
| 393 |
+
new Promise((resolve) => proxy.server.close(resolve)),
|
| 394 |
+
new Promise((resolve) => upstream.server.close(resolve))
|
| 395 |
+
]);
|
| 396 |
+
}
|
| 397 |
+
});
|
| 398 |
+
|
| 399 |
+
test('newapi site check solves BunkerWeb challenge through per-site proxy', async () => {
|
| 400 |
+
const upstream = createBunkerWebProtectedServer();
|
| 401 |
+
const proxy = createHttpProxyServer();
|
| 402 |
+
const upstreamPort = await listen(upstream.server);
|
| 403 |
+
const proxyPort = await listen(proxy.server);
|
| 404 |
+
|
| 405 |
+
try {
|
| 406 |
+
const protectedSite = await createSite({
|
| 407 |
+
name: 'protected-newapi-site',
|
| 408 |
+
baseUrl: `http://127.0.0.1:${upstreamPort}`,
|
| 409 |
+
apiKey: 'sk-newapi',
|
| 410 |
+
apiType: 'newapi',
|
| 411 |
+
userId: '15875',
|
| 412 |
+
proxyUrl: `http://127.0.0.1:${proxyPort}`
|
| 413 |
+
});
|
| 414 |
+
|
| 415 |
+
const checkResponse = await app.inject({
|
| 416 |
+
method: 'POST',
|
| 417 |
+
url: `/api/sites/${protectedSite.id}/check?skipNotification=true`
|
| 418 |
+
});
|
| 419 |
+
|
| 420 |
+
assert.equal(checkResponse.statusCode, 200, checkResponse.body);
|
| 421 |
+
assert.equal(checkResponse.json().ok, true);
|
| 422 |
+
assert.ok(proxy.requests.some((request) => request.url.includes('/challenge')));
|
| 423 |
+
assert.ok(upstream.requests.filter((request) => request.path === '/challenge' && request.viaProxy).length >= 2);
|
| 424 |
+
assert.ok(upstream.requests.some((request) => request.path === '/api/user/models' && request.viaProxy));
|
| 425 |
+
assert.ok(upstream.requests.some((request) => request.path === '/api/user/self' && request.viaProxy));
|
| 426 |
+
assert.ok(upstream.requests.some((request) => request.path === '/challenge' && request.method === 'POST' && /challenge=688/.test(request.body)));
|
| 427 |
+
} finally {
|
| 428 |
+
await Promise.all([
|
| 429 |
+
new Promise((resolve) => proxy.server.close(resolve)),
|
| 430 |
+
new Promise((resolve) => upstream.server.close(resolve))
|
| 431 |
+
]);
|
| 432 |
+
}
|
| 433 |
+
});
|
web/src/pages/Sites.jsx
CHANGED
|
@@ -46,6 +46,23 @@ function authHeaders(includeJson = false) {
|
|
| 46 |
return h;
|
| 47 |
}
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
export default function Sites() {
|
| 50 |
const [list, setList] = useState([])
|
| 51 |
const [loading, setLoading] = useState(false)
|
|
@@ -533,6 +550,7 @@ export default function Sites() {
|
|
| 533 |
v.excludeFromBatch = v.excludeFromBatch === true;
|
| 534 |
v.unlimitedQuota = v.unlimitedQuota === true;
|
| 535 |
v.enableCheckIn = v.enableCheckIn === true;
|
|
|
|
| 536 |
|
| 537 |
const res = await fetch('/api/sites', { method: 'POST', headers: authHeaders(true), body: JSON.stringify(v) })
|
| 538 |
if (!res.ok) {
|
|
@@ -545,42 +563,56 @@ export default function Sites() {
|
|
| 545 |
}
|
| 546 |
}
|
| 547 |
|
| 548 |
-
const openEditModal = (site) => {
|
| 549 |
-
|
| 550 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 551 |
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
|
|
|
| 558 |
}
|
| 559 |
-
}
|
| 560 |
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 584 |
}
|
| 585 |
|
| 586 |
const onEdit = async () => {
|
|
@@ -601,6 +633,7 @@ export default function Sites() {
|
|
| 601 |
billingUrl: v.billingUrl || null,
|
| 602 |
billingAuthType: v.billingAuthType || 'token',
|
| 603 |
billingAuthValue: v.billingAuthValue || null,
|
|
|
|
| 604 |
billingLimitField: v.billingLimitField || null,
|
| 605 |
billingUsageField: v.billingUsageField || null,
|
| 606 |
enableCheckIn: v.enableCheckIn === true,
|
|
@@ -2007,6 +2040,18 @@ export default function Sites() {
|
|
| 2007 |
style={{ borderRadius: 8, fontSize: 15 }}
|
| 2008 |
/>
|
| 2009 |
</Form.Item>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2010 |
<Form.Item
|
| 2011 |
name="apiType"
|
| 2012 |
label={<span style={{ fontSize: 15, fontWeight: 500 }}>API 类型</span>}
|
|
|
|
| 46 |
return h;
|
| 47 |
}
|
| 48 |
|
| 49 |
+
function validateProxyUrl(_, value) {
|
| 50 |
+
if (!value || !String(value).trim()) {
|
| 51 |
+
return Promise.resolve()
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
try {
|
| 55 |
+
const parsed = new URL(String(value).trim())
|
| 56 |
+
const supportedProtocols = ['http:', 'https:', 'socks:', 'socks5:']
|
| 57 |
+
if (!supportedProtocols.includes(parsed.protocol)) {
|
| 58 |
+
return Promise.reject(new Error('仅支持 http、https、socks 或 socks5 代理'))
|
| 59 |
+
}
|
| 60 |
+
return Promise.resolve()
|
| 61 |
+
} catch (error) {
|
| 62 |
+
return Promise.reject(new Error('请输入有效的代理 URL'))
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
export default function Sites() {
|
| 67 |
const [list, setList] = useState([])
|
| 68 |
const [loading, setLoading] = useState(false)
|
|
|
|
| 550 |
v.excludeFromBatch = v.excludeFromBatch === true;
|
| 551 |
v.unlimitedQuota = v.unlimitedQuota === true;
|
| 552 |
v.enableCheckIn = v.enableCheckIn === true;
|
| 553 |
+
v.proxyUrl = v.proxyUrl?.trim() || null;
|
| 554 |
|
| 555 |
const res = await fetch('/api/sites', { method: 'POST', headers: authHeaders(true), body: JSON.stringify(v) })
|
| 556 |
if (!res.ok) {
|
|
|
|
| 563 |
}
|
| 564 |
}
|
| 565 |
|
| 566 |
+
const openEditModal = async (site) => {
|
| 567 |
+
try {
|
| 568 |
+
const res = await fetch(`/api/sites/${site.id}`, { headers: authHeaders() })
|
| 569 |
+
if (!res.ok) {
|
| 570 |
+
const data = await res.json().catch(() => ({}))
|
| 571 |
+
throw new Error(data.error || '获取站点详情失败')
|
| 572 |
+
}
|
| 573 |
+
|
| 574 |
+
const siteDetail = await res.json()
|
| 575 |
+
const currentSite = { ...site, ...siteDetail }
|
| 576 |
+
|
| 577 |
+
setEditMode(true)
|
| 578 |
+
setEditingSite(currentSite)
|
| 579 |
|
| 580 |
+
let cnHour = undefined, cnMinute = undefined
|
| 581 |
+
if (currentSite.scheduleCron && currentSite.timezone === 'Asia/Shanghai') {
|
| 582 |
+
const parts = String(currentSite.scheduleCron).trim().split(/\s+/)
|
| 583 |
+
if (parts.length >= 2) {
|
| 584 |
+
cnMinute = Number(parts[0])
|
| 585 |
+
cnHour = Number(parts[1])
|
| 586 |
+
}
|
| 587 |
}
|
|
|
|
| 588 |
|
| 589 |
+
form.setFieldsValue({
|
| 590 |
+
name: currentSite.name,
|
| 591 |
+
baseUrl: currentSite.baseUrl,
|
| 592 |
+
apiKey: '',
|
| 593 |
+
apiType: currentSite.apiType || 'other',
|
| 594 |
+
userId: currentSite.userId || '',
|
| 595 |
+
cnHour,
|
| 596 |
+
cnMinute,
|
| 597 |
+
pinned: currentSite.pinned !== undefined ? currentSite.pinned : false,
|
| 598 |
+
excludeFromBatch: currentSite.excludeFromBatch !== undefined ? currentSite.excludeFromBatch : false,
|
| 599 |
+
categoryId: currentSite.categoryId || null,
|
| 600 |
+
unlimitedQuota: currentSite.unlimitedQuota !== undefined ? currentSite.unlimitedQuota : false,
|
| 601 |
+
billingUrl: currentSite.billingUrl || '',
|
| 602 |
+
billingAuthType: currentSite.billingAuthType || 'token',
|
| 603 |
+
billingAuthValue: '',
|
| 604 |
+
proxyUrl: currentSite.proxyUrl || '',
|
| 605 |
+
billingLimitField: currentSite.billingLimitField || '',
|
| 606 |
+
billingUsageField: currentSite.billingUsageField || '',
|
| 607 |
+
enableCheckIn: currentSite.enableCheckIn !== undefined ? currentSite.enableCheckIn : false,
|
| 608 |
+
checkInMode: currentSite.checkInMode || 'both',
|
| 609 |
+
extralink: currentSite.extralink || '',
|
| 610 |
+
remark: currentSite.remark || ''
|
| 611 |
+
})
|
| 612 |
+
setOpen(true)
|
| 613 |
+
} catch (e) {
|
| 614 |
+
message.error(e.message || '获取站点详情失败')
|
| 615 |
+
}
|
| 616 |
}
|
| 617 |
|
| 618 |
const onEdit = async () => {
|
|
|
|
| 633 |
billingUrl: v.billingUrl || null,
|
| 634 |
billingAuthType: v.billingAuthType || 'token',
|
| 635 |
billingAuthValue: v.billingAuthValue || null,
|
| 636 |
+
proxyUrl: v.proxyUrl?.trim() || null,
|
| 637 |
billingLimitField: v.billingLimitField || null,
|
| 638 |
billingUsageField: v.billingUsageField || null,
|
| 639 |
enableCheckIn: v.enableCheckIn === true,
|
|
|
|
| 2040 |
style={{ borderRadius: 8, fontSize: 15 }}
|
| 2041 |
/>
|
| 2042 |
</Form.Item>
|
| 2043 |
+
<Form.Item
|
| 2044 |
+
name="proxyUrl"
|
| 2045 |
+
label={<span style={{ fontSize: 15, fontWeight: 500 }}>站点代理(可选)</span>}
|
| 2046 |
+
rules={[{ validator: validateProxyUrl }]}
|
| 2047 |
+
extra="支持 http(s):// 或 socks5:// 代理;配置后该站点所有后端访问都将走这个代理"
|
| 2048 |
+
>
|
| 2049 |
+
<Input
|
| 2050 |
+
prefix={<GlobalOutlined style={{ color: '#bbb' }} />}
|
| 2051 |
+
placeholder="例如:http://127.0.0.1:7890 或 socks5://user:pass@host:1080"
|
| 2052 |
+
style={{ borderRadius: 8, fontSize: 15 }}
|
| 2053 |
+
/>
|
| 2054 |
+
</Form.Item>
|
| 2055 |
<Form.Item
|
| 2056 |
name="apiType"
|
| 2057 |
label={<span style={{ fontSize: 15, fontWeight: 500 }}>API 类型</span>}
|