OpenAI Codex commited on
Commit
3d1bdb6
·
1 Parent(s): 14a9596

feat: add site-level proxy support

Browse files
.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
- "resend": "^3.0.0"
 
 
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
- require('../src/server');
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 fetch(checkInUrl, {
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.0',
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.0',
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
- const {
288
- name, baseUrl, apiKey, apiType = 'other', userId = null,
289
- scheduleCron = null, timezone = 'UTC', pinned = false, excludeFromBatch = false,
290
- categoryId = null,
291
- billingUrl = null, billingAuthType = 'token', billingAuthValue = null,
292
- billingLimitField = null, billingUsageField = null, unlimitedQuota = false,
293
- enableCheckIn = false, checkInMode = 'both',
294
- extralink = null, remark = null, sortOrder = 0
295
- } = request.body;
296
-
297
- const apiKeyEnc = encrypt(apiKey);
298
- let billingAuthValueEnc = null;
299
- if (billingAuthValue) {
300
- billingAuthValueEnc = encrypt(billingAuthValue);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 fetch(url, {
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
- // 解密 API 密钥
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 fetch(url, { headers });
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 fetch(url, { headers });
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 fetch(url, { headers });
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 fetch(url, {
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 fetch(url, {
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 fetch(url, {
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 fetch(url, {
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 fetch(url, {
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 fetch(url, {
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 fetch(url, {
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 fetch(url, {
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 fetch(url, {
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 fetch(url, {
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 fetch(site.billingUrl, {
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 fetch(url, {
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 fetch(url, {
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
- buildServer()
81
- .then((app) => app.listen({ port: CONFIG.PORT, host: '0.0.0.0' }))
82
- .catch((err) => {
 
 
 
 
 
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,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const fetch = require('node-fetch');
2
+ const { HttpProxyAgent } = require('http-proxy-agent');
3
+ const { HttpsProxyAgent } = require('https-proxy-agent');
4
+ const { SocksProxyAgent } = require('socks-proxy-agent');
5
+ const { decrypt } = require('./crypto');
6
+
7
+ const SUPPORTED_PROXY_PROTOCOLS = new Set(['http:', 'https:', 'socks:', 'socks4:', 'socks5:']);
8
+ const agentCache = new Map();
9
+
10
+ function createValidationError(message) {
11
+ const error = new Error(message);
12
+ error.statusCode = 400;
13
+ return error;
14
+ }
15
+
16
+ function normalizeProxyUrl(proxyUrl) {
17
+ if (proxyUrl === undefined || proxyUrl === null) return null;
18
+ const value = String(proxyUrl).trim();
19
+ return value || null;
20
+ }
21
+
22
+ function parseProxyUrl(proxyUrl) {
23
+ const normalized = normalizeProxyUrl(proxyUrl);
24
+ if (!normalized) return null;
25
+
26
+ let parsed;
27
+ try {
28
+ parsed = new URL(normalized);
29
+ } catch (error) {
30
+ throw createValidationError('代理地址格式无效,请输入完整的代理 URL');
31
+ }
32
+
33
+ if (!SUPPORTED_PROXY_PROTOCOLS.has(parsed.protocol)) {
34
+ throw createValidationError('代理协议仅支持 http、https、socks 和 socks5');
35
+ }
36
+
37
+ return parsed;
38
+ }
39
+
40
+ function resolveSiteProxyUrl(site) {
41
+ if (!site) return null;
42
+
43
+ if (typeof site === 'string') {
44
+ const normalized = normalizeProxyUrl(site);
45
+ parseProxyUrl(normalized);
46
+ return normalized;
47
+ }
48
+
49
+ if ('proxyUrl' in site) {
50
+ const normalized = normalizeProxyUrl(site.proxyUrl);
51
+ parseProxyUrl(normalized);
52
+ return normalized;
53
+ }
54
+
55
+ if (!site.proxyUrlEnc) return null;
56
+
57
+ const proxyUrl = normalizeProxyUrl(decrypt(site.proxyUrlEnc));
58
+ parseProxyUrl(proxyUrl);
59
+ return proxyUrl;
60
+ }
61
+
62
+ function getAgentFactory(proxyUrl) {
63
+ const parsedProxyUrl = parseProxyUrl(proxyUrl);
64
+ if (!parsedProxyUrl) return undefined;
65
+
66
+ const cacheKey = parsedProxyUrl.toString();
67
+ let agentFactory = agentCache.get(cacheKey);
68
+
69
+ if (!agentFactory) {
70
+ const isSocksProxy = parsedProxyUrl.protocol.startsWith('socks');
71
+ const httpAgent = isSocksProxy ? new SocksProxyAgent(cacheKey) : new HttpProxyAgent(cacheKey);
72
+ const httpsAgent = isSocksProxy ? new SocksProxyAgent(cacheKey) : new HttpsProxyAgent(cacheKey);
73
+
74
+ agentFactory = (parsedRequestUrl) => (parsedRequestUrl.protocol === 'http:' ? httpAgent : httpsAgent);
75
+ agentCache.set(cacheKey, agentFactory);
76
+ }
77
+
78
+ return agentFactory;
79
+ }
80
+
81
+ function buildSiteFetchOptions(site, options = {}) {
82
+ const proxyUrl = resolveSiteProxyUrl(site);
83
+ if (!proxyUrl) return { ...options };
84
+
85
+ return {
86
+ ...options,
87
+ agent: getAgentFactory(proxyUrl)
88
+ };
89
+ }
90
+
91
+ async function siteFetch(site, url, options = {}, extra = {}) {
92
+ const fetchImpl = extra.fetchImpl || fetch;
93
+ return fetchImpl(url, buildSiteFetchOptions(site, options));
94
+ }
95
+
96
+ module.exports = {
97
+ SUPPORTED_PROXY_PROTOCOLS,
98
+ normalizeProxyUrl,
99
+ parseProxyUrl,
100
+ resolveSiteProxyUrl,
101
+ buildSiteFetchOptions,
102
+ siteFetch,
103
+ createValidationError
104
+ };
server/tests/site-proxy.test.js ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const test = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const http = require('http');
7
+ const { once } = require('events');
8
+ const { execFileSync } = require('child_process');
9
+
10
+ process.env.NODE_ENV = 'test';
11
+ process.env.SKIP_AUTH = 'true';
12
+ process.env.JWT_SECRET = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
13
+ process.env.ENCRYPTION_KEY = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
14
+ process.env.ADMIN_EMAIL = 'admin@example.com';
15
+ process.env.ADMIN_PASSWORD = 'admin123456';
16
+
17
+ const serverRoot = path.resolve(__dirname, '..');
18
+ let tempDir;
19
+ let buildServer;
20
+ let prisma;
21
+ let app;
22
+
23
+ const { parseProxyUrl, buildSiteFetchOptions, siteFetch } = require('../src/site-http');
24
+
25
+ async function listen(server) {
26
+ server.listen(0, '127.0.0.1');
27
+ await once(server, 'listening');
28
+ return server.address().port;
29
+ }
30
+
31
+ function createUpstreamServer() {
32
+ const requests = [];
33
+ const server = http.createServer((req, res) => {
34
+ const url = new URL(req.url, `http://${req.headers.host}`);
35
+ const bodyChunks = [];
36
+
37
+ req.on('data', (chunk) => bodyChunks.push(chunk));
38
+ req.on('end', () => {
39
+ requests.push({
40
+ path: url.pathname,
41
+ method: req.method,
42
+ viaProxy: req.headers['x-through-proxy'] === 'yes'
43
+ });
44
+
45
+ res.setHeader('Content-Type', 'application/json');
46
+
47
+ if (url.pathname === '/v1/models') {
48
+ res.end(JSON.stringify({ data: [{ id: 'gpt-4o-mini' }, { id: 'claude-3-5-sonnet' }] }));
49
+ return;
50
+ }
51
+
52
+ if (url.pathname === '/v1/dashboard/billing/subscription') {
53
+ res.end(JSON.stringify({ system_hard_limit_usd: 12.5 }));
54
+ return;
55
+ }
56
+
57
+ if (url.pathname === '/v1/dashboard/billing/usage') {
58
+ res.end(JSON.stringify({ total_usage: 250 }));
59
+ return;
60
+ }
61
+
62
+ if (url.pathname === '/api/token/') {
63
+ res.end(JSON.stringify({ success: true, data: [{ id: 1, key: 'tok-1' }] }));
64
+ return;
65
+ }
66
+
67
+ res.statusCode = 404;
68
+ res.end(JSON.stringify({ error: `Unhandled path: ${url.pathname}` }));
69
+ });
70
+ });
71
+
72
+ return { server, requests };
73
+ }
74
+
75
+ function createHttpProxyServer() {
76
+ const requests = [];
77
+ const server = http.createServer((clientReq, clientRes) => {
78
+ const targetUrl = new URL(clientReq.url);
79
+ requests.push({ method: clientReq.method, url: clientReq.url });
80
+
81
+ const proxyReq = http.request({
82
+ hostname: targetUrl.hostname,
83
+ port: targetUrl.port,
84
+ path: `${targetUrl.pathname}${targetUrl.search}`,
85
+ method: clientReq.method,
86
+ headers: {
87
+ ...clientReq.headers,
88
+ host: targetUrl.host,
89
+ 'x-through-proxy': 'yes'
90
+ }
91
+ }, (proxyRes) => {
92
+ clientRes.writeHead(proxyRes.statusCode || 500, proxyRes.headers);
93
+ proxyRes.pipe(clientRes);
94
+ });
95
+
96
+ proxyReq.on('error', (error) => {
97
+ clientRes.statusCode = 502;
98
+ clientRes.end(JSON.stringify({ error: error.message }));
99
+ });
100
+
101
+ clientReq.pipe(proxyReq);
102
+ });
103
+
104
+ return { server, requests };
105
+ }
106
+
107
+ async function createSite(payload) {
108
+ const response = await app.inject({
109
+ method: 'POST',
110
+ url: '/api/sites',
111
+ payload
112
+ });
113
+
114
+ assert.equal(response.statusCode, 200, response.body);
115
+ return response.json();
116
+ }
117
+
118
+ test.before(async () => {
119
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'simplehub-site-proxy-'));
120
+ process.env.DATABASE_URL = `file:${path.join(tempDir, 'db.sqlite')}`;
121
+
122
+ execFileSync('npx', ['prisma', 'db', 'push', '--force-reset', '--skip-generate'], {
123
+ cwd: serverRoot,
124
+ env: process.env,
125
+ stdio: 'inherit'
126
+ });
127
+
128
+ ({ buildServer } = require('../src/server'));
129
+ ({ prisma } = require('../src/db'));
130
+ app = await buildServer();
131
+ });
132
+
133
+ test.after(async () => {
134
+ if (app) await app.close();
135
+ if (prisma) await prisma.$disconnect();
136
+ if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true });
137
+ });
138
+
139
+ test.afterEach(async () => {
140
+ await prisma.modelDiff.deleteMany();
141
+ await prisma.modelSnapshot.deleteMany();
142
+ await prisma.site.deleteMany();
143
+ });
144
+
145
+ test('site-http validates proxy URLs and attaches proxy agents', async () => {
146
+ assert.equal(parseProxyUrl('socks5://user:pass@127.0.0.1:1080').protocol, 'socks5:');
147
+ assert.throws(() => parseProxyUrl('ftp://127.0.0.1:21'), /代理协议/);
148
+
149
+ const directOptions = buildSiteFetchOptions({ proxyUrl: null }, { method: 'GET' });
150
+ assert.equal(directOptions.agent, undefined);
151
+
152
+ let receivedOptions;
153
+ await siteFetch(
154
+ { proxyUrl: 'http://127.0.0.1:7890' },
155
+ 'http://example.com',
156
+ { method: 'GET' },
157
+ {
158
+ fetchImpl: async (url, options) => {
159
+ receivedOptions = options;
160
+ return { ok: true };
161
+ }
162
+ }
163
+ );
164
+
165
+ assert.equal(typeof receivedOptions.agent, 'function');
166
+ assert.equal(receivedOptions.method, 'GET');
167
+ });
168
+
169
+ test('site CRUD persists encrypted proxyUrl and allows clearing it', async () => {
170
+ const created = await createSite({
171
+ name: 'proxy-site',
172
+ baseUrl: 'http://127.0.0.1:18080',
173
+ apiKey: 'sk-test',
174
+ apiType: 'other',
175
+ proxyUrl: 'http://user:pass@127.0.0.1:18888'
176
+ });
177
+
178
+ const savedSite = await prisma.site.findUnique({ where: { id: created.id } });
179
+ assert.ok(savedSite.proxyUrlEnc);
180
+ assert.notEqual(savedSite.proxyUrlEnc, 'http://user:pass@127.0.0.1:18888');
181
+
182
+ const detailResponse = await app.inject({
183
+ method: 'GET',
184
+ url: `/api/sites/${created.id}`
185
+ });
186
+
187
+ assert.equal(detailResponse.statusCode, 200, detailResponse.body);
188
+ assert.equal(detailResponse.json().proxyUrl, 'http://user:pass@127.0.0.1:18888');
189
+
190
+ const clearedResponse = await app.inject({
191
+ method: 'PATCH',
192
+ url: `/api/sites/${created.id}`,
193
+ payload: { proxyUrl: '' }
194
+ });
195
+
196
+ assert.equal(clearedResponse.statusCode, 200, clearedResponse.body);
197
+
198
+ const clearedSite = await prisma.site.findUnique({ where: { id: created.id } });
199
+ assert.equal(clearedSite.proxyUrlEnc, null);
200
+
201
+ const invalidResponse = await app.inject({
202
+ method: 'POST',
203
+ url: '/api/sites',
204
+ payload: {
205
+ name: 'invalid-proxy',
206
+ baseUrl: 'http://127.0.0.1:18080',
207
+ apiKey: 'sk-test',
208
+ proxyUrl: 'ftp://127.0.0.1:21'
209
+ }
210
+ });
211
+
212
+ assert.equal(invalidResponse.statusCode, 400, invalidResponse.body);
213
+ assert.match(invalidResponse.body, /代理协议/);
214
+ });
215
+
216
+ test('site checks and token proxy routes honor per-site proxy settings', async () => {
217
+ const upstream = createUpstreamServer();
218
+ const proxy = createHttpProxyServer();
219
+ const upstreamPort = await listen(upstream.server);
220
+ const proxyPort = await listen(proxy.server);
221
+
222
+ try {
223
+ const proxiedSite = await createSite({
224
+ name: 'proxied-site',
225
+ baseUrl: `http://127.0.0.1:${upstreamPort}`,
226
+ apiKey: 'sk-proxy',
227
+ apiType: 'other',
228
+ proxyUrl: `http://127.0.0.1:${proxyPort}`
229
+ });
230
+
231
+ const proxiedCheckResponse = await app.inject({
232
+ method: 'POST',
233
+ url: `/api/sites/${proxiedSite.id}/check?skipNotification=true`
234
+ });
235
+
236
+ assert.equal(proxiedCheckResponse.statusCode, 200, proxiedCheckResponse.body);
237
+ assert.equal(proxiedCheckResponse.json().ok, true);
238
+ assert.ok(proxy.requests.some((request) => request.url.includes('/v1/models')));
239
+ assert.ok(upstream.requests.some((request) => request.path === '/v1/models' && request.viaProxy));
240
+
241
+ const proxiedTokensResponse = await app.inject({
242
+ method: 'GET',
243
+ url: `/api/sites/${proxiedSite.id}/tokens`
244
+ });
245
+
246
+ assert.equal(proxiedTokensResponse.statusCode, 200, proxiedTokensResponse.body);
247
+ assert.ok(upstream.requests.some((request) => request.path === '/api/token/' && request.viaProxy));
248
+
249
+ const proxyRequestCount = proxy.requests.length;
250
+
251
+ const directSite = await createSite({
252
+ name: 'direct-site',
253
+ baseUrl: `http://127.0.0.1:${upstreamPort}`,
254
+ apiKey: 'sk-direct',
255
+ apiType: 'other'
256
+ });
257
+
258
+ const directCheckResponse = await app.inject({
259
+ method: 'POST',
260
+ url: `/api/sites/${directSite.id}/check?skipNotification=true`
261
+ });
262
+
263
+ assert.equal(directCheckResponse.statusCode, 200, directCheckResponse.body);
264
+ assert.equal(proxy.requests.length, proxyRequestCount);
265
+ assert.ok(upstream.requests.some((request) => request.path === '/v1/models' && !request.viaProxy));
266
+ } finally {
267
+ await Promise.all([
268
+ new Promise((resolve) => proxy.server.close(resolve)),
269
+ new Promise((resolve) => upstream.server.close(resolve))
270
+ ]);
271
+ }
272
+ });
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
- setEditMode(true)
550
- setEditingSite(site)
 
 
 
 
 
 
 
 
 
 
551
 
552
- let cnHour = undefined, cnMinute = undefined
553
- if (site.scheduleCron && site.timezone === 'Asia/Shanghai') {
554
- const parts = String(site.scheduleCron).trim().split(/\s+/)
555
- if (parts.length >= 2) {
556
- cnMinute = Number(parts[0])
557
- cnHour = Number(parts[1])
 
558
  }
559
- }
560
 
561
- form.setFieldsValue({
562
- name: site.name,
563
- baseUrl: site.baseUrl,
564
- apiKey: '',
565
- apiType: site.apiType || 'other',
566
- userId: site.userId || '',
567
- cnHour,
568
- cnMinute,
569
- pinned: site.pinned !== undefined ? site.pinned : false,
570
- excludeFromBatch: site.excludeFromBatch !== undefined ? site.excludeFromBatch : false,
571
- categoryId: site.categoryId || null,
572
- unlimitedQuota: site.unlimitedQuota !== undefined ? site.unlimitedQuota : false,
573
- billingUrl: site.billingUrl || '',
574
- billingAuthType: site.billingAuthType || 'token',
575
- billingAuthValue: '',
576
- billingLimitField: site.billingLimitField || '',
577
- billingUsageField: site.billingUsageField || '',
578
- enableCheckIn: site.enableCheckIn !== undefined ? site.enableCheckIn : false,
579
- checkInMode: site.checkInMode || 'both',
580
- extralink: site.extralink || '',
581
- remark: site.remark || ''
582
- })
583
- setOpen(true)
 
 
 
 
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>}