feat(api-proxy): 新增「API 代理」板块,把外部免费 API 市场挂到网关下

后端(rust/src/apix.rs,新模块)
- /apix/<slug>?<参数> → 市场 POST /api/v1/ai/request;复用 LLM 的 sk_ 鉴权 +
  配额 + 用量统计(slot 带 api/ 前缀,天然归组)
- 请求体由网关从 query 拼:asset_id 服务端决定(调用方只能选参数),堵住
  「客户端自选最贵资产」的口子;GET 经 proxy_method POST + proxy_set_body 转带体
- data/api-proxies.json(含平台真 Key,等同 users.json 敏感度):base+key+items
  shm 写穿 ax:,停用=摘键;平台 Key 不回显(只给掩码)
- 6 个 nginx 变量 + /_apix_probe/<slug>(internal)免费预估探测,复用 $apix_probe_*

前端(www/apix.html + assets/apix.js)
- 市场凭据配置 / 目录直拉(GET /api/v1/assets,跨域已开)/ 代理增删启停 /
  复制地址 / 免费预估测试(带回平台余额)

验证
- 回归 261 条全绿(网关 102 + LLM 159,新增 34 条 apix 断言)
- 涵盖:无/坏 Key→401、不存在/停用 slug→404、GET 改写 POST、换平台 Key、
  体由网关拼、下行 Key 不泄漏、写穿 shm、探测归 api/<slug>

文档
- readme §15.1 API 代理使用 + 变更日志;CLAUDE.md location 表补 ipass_apix
This commit is contained in:
admin committed 2026-09-13 02:46:35 +08:00
1 parent c426789734
commit 1f548ac953
16 files changed
+1666 -7

No files matched your search

+2
View File
@@ -127,6 +127,8 @@ Rust 模块在 `rust/src/` —— **一个文件对应旧版一个 `lua/*.lua`
所以本机测试配置可以没有 PCRE。
- **LLM**(access,`ipass_llm on`):查 `ukey:` 鉴权 + `up:` 定上游 → 填 `$llm_target/$llm_host/$llm_auth`。
- **API**(content,`ipass_api on`):**先异步读请求体**再分发(access 阶段拿不到 body,见「两段式读体」)。
- **API 代理**(access,`ipass_apix on`):查 `ukey:` 鉴权 + `ax:` 定市场资产 → 填 `$apix_target/$apix_host/$apix_key/$apix_body`;
**请求体由网关从 query 拼**(`asset_id` 服务端决定),GET 经 `proxy_method POST` + `proxy_set_body` 转带体请求。
2. **共享内存是唯一真源,JSON 文件只是持久化副本**(**与旧版正好相反**)。
旧版是「文件是真源、shm 只是 600s 缓存」,代价是每次 miss 都要同步读文件 + 全表 JSON 解码 + O(n) 扫描。
现在**所有写操作同时写 shm 与文件**(write-through),miss 就等于「不存在」,
+69
View File
@@ -202,6 +202,54 @@ http {
proxy_read_timeout 600s;
}
# ---- API 代理出口:`/apix/<slug>?<参数>` → 外部 API 市场 ----
#
# 与 LLM 代理同一把 `sk_` Key、同一份限流与用量统计,差别在上游形态:
# 市场只有一个收口 `POST /api/v1/ai/request`,资产由**请求体里的 asset_id**
# 决定。所以这里不能像 LLM 那样原样透传请求体——网关必须自己拼,
# 否则「只暴露免费资产」这条管理策略形同虚设(调用方自己挑最贵的刷)。
#
# 参数只能走 query string:转发决策在 access 阶段,请求体那时还读不到。
# 靠 proxy_method + proxy_set_body 把 GET 变成带体的 POST。
location /apix/ {
ipass_apix on;
proxy_pass $apix_target;
proxy_method POST;
proxy_set_body $apix_body;
proxy_http_version 1.1;
# 与 LLM 同一套出站头策略:默认不放行 + 显式放行。
# 抹掉 x-api-key 尤其重要——那是**调用方的网关 Key**,
# 原样带出去等于把网关的身份送给市场。
proxy_pass_request_headers off;
proxy_set_header x-api-key "";
proxy_set_header api-key "";
proxy_set_header Authorization "";
# 变量形式不会推导 Host,必须显式设
proxy_set_header Host $apix_host;
# 换上平台真 Key。下行那把 sk_ 到此为止
proxy_set_header X-API-Key $apix_key;
proxy_set_header Content-Type application/json;
proxy_set_header Accept application/json;
proxy_set_header User-Agent $http_user_agent;
proxy_set_header Connection "";
proxy_ssl_server_name on;
proxy_connect_timeout 10s;
proxy_send_timeout 120s;
proxy_read_timeout 120s;
error_page 502 503 504 = /apix_error;
}
location = /apix_error {
default_type application/json;
return 502 '{"code":502,"msg":"API 市场不可达,请稍后重试或联系管理员"}';
}
# 只改写「连不上上游」这类由 nginx 自己产生的错误。
# 404 等一律透传上游响应——那可能是模型名不存在的正常业务错误,
# 覆盖掉反而让客户端拿不到有用信息。
@@ -258,6 +306,27 @@ http {
ipass_api on;
}
# —— API 代理连通性/余额探测(管理台「测试」按钮)——
# /api/admin/apix/test 校验 slug 后内部重定向到这里。走市场的**免费**
# 预估接口,不执行资产、不扣费,响应里带平台余额 current_balance_usd。
# internal 挡住外部直连——这是绕过 ukey 鉴权直接花市场钱的口子。
location /_apix_probe/ {
internal;
proxy_pass $apix_probe_target;
proxy_method POST;
proxy_set_body $apix_probe_body;
proxy_http_version 1.1;
proxy_pass_request_headers off;
proxy_set_header Host $apix_host;
proxy_set_header X-API-Key $apix_key;
proxy_set_header Content-Type application/json;
proxy_set_header Accept application/json;
proxy_ssl_server_name on;
proxy_connect_timeout 5s;
proxy_send_timeout 15s;
proxy_read_timeout 15s;
}
# —— 上游连通性测试(管理台「测试」按钮)——
# /api/admin/upstreams/test 校验 slot 后由模块内部重定向到这里。
# proxy_pass 复用 LLM 的 $llm_* 变量(getter 从 URI 第一段取 slot,
+70
View File
@@ -965,8 +965,78 @@ curl -s -H "X-API-Key: $KEY" "$API/api/v1/usage"
---
## 15.1 API 代理(外部 API 市场)
把外部 API 市场(默认 `搜蚁智选 / AIMALL`,`https://souyi.net.cn`)的资产挂到网关下,
与 LLM 代理**共用同一把账号 API Key、同一份限流与用量统计**——差别只在下游形态:
市场只有一个收口 `POST /api/v1/ai/request`,资产靠**请求体里的 `asset_id`** 区分。
```text
GET /apix/search?q=nginx Authorization: Bearer sk_<本网关签发>
→ access 阶段 ApiProxyHandler(ipass_apix 开关)
① 取 URL 第一段 → slug = search
② 查 ukey:<key> → 身份 + 配额(与 LLM 同一套)
③ 查 ax:<slug> → base + 平台 Key + asset_id(纯内存)
④ 放行;GET 被改写成 POST:proxy_method + proxy_set_body $apix_body
$apix_body 由网关**从 query 拼**(见下);$apix_key 换上平台 Key
→ 转发到市场(下游 sk_ 到此为止,绝不带出去)
```
**为什么请求体必须由网关拼**:市场只认一个收口 URL,资产全靠 body 里的 `asset_id` 区分。
如果让客户端自己带 `asset_id`,管理员就失去「只暴露免费资产」的控制力。所以
**资产选择权留在服务端**:`slug → asset_id` 由管理员在「API 代理」页配置,调用方只能决定 query 参数。
**调用方式**:`/apix/<slug>?<参数>=<值>`。参数只能走 query string——转发决策在 access 阶段,
那时请求体还读不到。网关把全部 query 参数原样塞进 `call_data`(`prompt` 提到顶层,市场模型类资产用它当必填),
再 `proxy_method POST` + `proxy_set_body` 转成带体请求。例如 `GET /apix/search?q=nginx` 会向市场发:
```json
{"asset_id":"searxng-search","call_data":{"q":"nginx"}}
```
**管理台「API 代理」页**(`/admin/apix.html`):
- **API 市场凭据**:填市场基址(默认 `https://souyi.net.cn`)与**平台 API Key**。
真 Key 只在 `data/api-proxies.json` 里,**不回显**(列表只显示掩码 `ak_***`)。
- **刷新目录**:直连市场公开目录 `GET /api/v1/assets`(匿名可读、已开跨域),点「接入」自动填表。
- **代理列表**:每个代理给复制调用地址 / 测试 / 编辑 / 启停 / 删除。停用立刻对调用方表现为 404
(共享内存已摘除,无回源兜底)。「测试」走市场的**免费**预估接口 `/api/v1/ai/estimate`,
不执行资产、不扣费,顺带把平台余额 `current_balance_usd` 带回来。
**接口**
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| `GET` | `/apix/<slug>?<参数>` | 账号态:转发到市场对应资产 |
| `GET` | `/api/v1/apix` | 账号态:列出已启用的代理与调用地址 |
| `GET` | `/api/admin/apix` | 管理:凭据掩码 + 代理列表 |
| `POST` | `/api/admin/apix/save` | 新建 / 更新代理(`slug` / `asset_id` / `params` / `enabled`) |
| `POST` | `/api/admin/apix/delete` | 删除代理(调用方立即 404) |
| `POST` | `/api/admin/apix/platform` | 设置市场基址 + 平台 Key(留空 = 保持原值) |
| `POST` | `/api/admin/apix/test` | 连通性 / 余额探测(内部重定向到 `/_apix_probe/<slug>`,`internal` 挡外部直连) |
**硬约束**
- `apix.rs` 与 `llm.rs` 共用下游 `sk_` 鉴权与配额;`data/api-proxies.json` 含平台真 Key,
**敏感级别等同 `users.json`**,不要复制到其他地方。
- 出站头默认不放行(`proxy_pass_request_headers off`)+ 抹空 `x-api-key`/`api-key`/`Authorization`,
再显式放行 `Host` / `X-API-Key`(=平台 Key)/ `Content-Type`。**抹空三条是堵漏关键**,
漏 `Content-Type` 会令市场侧解析失败。
- shm 键 `ax:<slug>`,value = `base\n平台Key\nasset_id`。写操作必须走 `apix::sync_shm`
(停用 = 删键),否则「面板显示已保存、调用却 404」。
## 16. 变更记录
- **2026-09-13(续7)新增「API 代理」板块:把外部免费 API 市场挂到网关下(`ipass-1.0.9`)**
- 新增 `rust/src/apix.rs` + 模块:`/apix/<slug>?<参数>` → 市场 `POST /api/v1/ai/request`,
网关**从 query 拼体**(`asset_id` 由服务端决定,调用方只能选参数),`sk_` 下行 Key 换成平台 Key 后转发。
- `data/api-proxies.json`(含平台真 Key,等同 `users.json` 敏感度):`base` + `key` + `items{slug→asset_id/params/enabled}`;
shm 写穿 `ax:`,停用 = 摘键。
- 6 个 nginx 变量(`$apix_target/$apix_host/$apix_key/$apix_body/$apix_probe_target/$apix_probe_body`),
GET 经 `proxy_method POST` + `proxy_set_body` 改写成带体请求;探测走 `/_apix_probe/<slug>`(`internal`)。
- 管理台 `apix.html` + `assets/apix.js`:市场凭据配置、目录直拉、代理增删启停、复制地址、免费预估测试。
- 计费天然并入既有体系:用量按 `api/<slug>` 归组(与 LLM 上游同片键空间),趋势 / 用量页直接出现。
- **2026-09-13(续6)管理台图表(用量/token/趋势/按人/按 API 组)+ 单页拆分多页(`ipass-1.0.8`)**
- **趋势数据源(日桶)**:`ust:`/`utt:` 只有「今日 + 累计」两个数,**画不出历史曲线**(今日跨天归零、
累计不区分日期)。新增一组**键名带日窗 id** 的桶 `ud:`(全局)/ `udu:<user>:<day>` /
+179 -1
View File
@@ -18,6 +18,7 @@ use ngx::ffi::ngx_http_request_t;
use ngx::http::HTTPStatus;
use serde_json::{Value, json};
use crate::apix;
use crate::config;
use crate::domains;
use crate::http;
@@ -90,6 +91,13 @@ fn route(method: &str, uri: &str) -> Option<(Guard, Handler)> {
("POST", "/api/admin/upstreams/delete") => (Guard::Admin, h_admin_upstream_delete),
("GET", "/api/admin/usage") => (Guard::Admin, h_admin_usage),
("GET", "/api/admin/trend") => (Guard::Admin, h_admin_trend),
("GET", "/api/admin/apix") => (Guard::Admin, h_admin_apix),
("POST", "/api/admin/apix/save") => (Guard::Admin, h_admin_apix_save),
("POST", "/api/admin/apix/delete") => (Guard::Admin, h_admin_apix_delete),
("POST", "/api/admin/apix/platform") => (Guard::Admin, h_admin_apix_platform),
("POST", "/api/admin/apix/price") => (Guard::Admin, h_admin_apix_price),
("POST", "/api/admin/apix/test") => (Guard::Admin, h_admin_apix_test),
("GET", "/api/v1/apix") => (Guard::User, h_my_apix),
("GET", "/api/v1/me") => (Guard::User, h_me),
("GET", "/api/v1/models") => (Guard::User, h_my_models),
("GET", "/api/v1/usage") => (Guard::User, h_my_usage),
@@ -659,11 +667,181 @@ fn h_admin_trend(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
.unwrap_or_else(stats::trend_default_days);
let usernames: Vec<String> = users::all().into_iter().map(|u| u.username).collect();
let slots: Vec<String> = upstreams::all().into_iter().map(|(slot, _)| slot).collect();
// API 代理与 LLM 上游共用同一片用量键空间,只是 slot 带 `api/` 前缀
// (见 `config::APIX_STATS_PREFIX`)——这里一起列出,趋势图才会出现它们
let slots: Vec<String> = upstreams::all()
.into_iter()
.map(|(slot, _)| slot)
.chain(apix::all().into_iter().map(|(slug, _)| format!("{}{}", config::APIX_STATS_PREFIX, slug)))
.collect();
http::ok(r, stats::trend(util::now(), days, &usernames, &slots), "ok")
}
// ===========================================================================
// API 代理管理
// ===========================================================================
/// 管理员:API 代理清单 + 平台凭据状态
fn h_admin_apix(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let port = http::host_port(r);
let list = apix::all();
http::ok(
r,
json!({
"platform": apix::platform_view(),
"items": apix::view_all(&list, &port),
"count": list.len(),
}),
"ok",
)
}
/// 管理员:新增/修改一个 API 代理条目
fn h_admin_apix_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let p = http::params(r);
let slug = p.get("slug").cloned().unwrap_or_default();
let asset = p.get("asset_id").cloned().unwrap_or_default();
// 参数清单允许两种写法:逗号分隔(`q,format`)或 JSON 数组(`["q"]`)
let params = p.get("params").and_then(|v| {
let v = util::trim(v);
if v.is_empty() {
return None;
}
Some(if let Ok(Value::Array(arr)) = serde_json::from_str::<Value>(v) {
arr.into_iter()
.filter_map(|x| x.as_str().map(str::to_owned))
.collect::<Vec<String>>()
} else {
v.split(',').map(str::to_owned).collect::<Vec<String>>()
})
});
// 不带 enabled 视为「启用」:新建表单里漏勾是常见手滑,默认值取更安全的一侧
let enabled = match p.get("enabled") {
Some(v) => util::to_bool(Some(v)),
None => true,
};
match apix::upsert(
&slug,
&asset,
p.get("name"),
p.get("desc"),
params,
enabled,
p.get("note"),
) {
Ok(item) => {
util::log_notice(&format!("[api] 保存 API 代理 {slug} → {asset}"));
http::ok(r, json!({ "slug": slug, "asset_id": item.asset_id }), "已保存")
}
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
}
}
/// 管理员:删除一个 API 代理条目
fn h_admin_apix_delete(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let p = http::params(r);
match apix::remove(p.get("slug").map(String::as_str).unwrap_or("")) {
Ok(slug) => {
util::log_notice(&format!("[api] 删除 API 代理 {slug}"));
http::ok(r, json!({ "slug": slug }), "已删除")
}
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
}
}
/// 管理员:设置市场基址与平台 Key
fn h_admin_apix_platform(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let p = http::params(r);
match apix::set_platform(p.get("base"), p.get("key")) {
Ok(data) => {
util::log_notice(&format!(
"[api] 更新 API 代理平台配置 base={} key_set={}",
data.base,
!data.key.is_empty()
));
http::ok(
r,
json!({ "base": data.base, "key_set": !data.key.is_empty() }),
"已保存",
)
}
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
}
}
/// 管理员:回填展示用的单价快照(从市场目录同步下来的数字,不参与计费)
fn h_admin_apix_price(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let p = http::params(r);
let slug = p.get("slug").cloned().unwrap_or_default();
let num = |k: &str| -> f64 {
p.get(k)
.map(|v| util::trim(v).parse::<f64>().unwrap_or(0.0))
.unwrap_or(0.0)
};
if apix::validate_slug(&slug).is_err() {
return http::fail(r, HTTPStatus::BAD_REQUEST, "slug 不合法");
}
apix::set_price(&slug, num("price_per_call"), num("price_in"), num("price_out"));
http::ok(r, json!({ "slug": slug }), "ok")
}
/// 管理员:探测平台 Key 是否可用(管理台「测试」按钮)。
///
/// 走市场的**免费预估**接口(`/api/v1/ai/estimate`):它不执行资产、不扣费,
/// 响应里还带 `current_balance_usd` —— 一次调用同时拿到「Key 通不通」和
/// 「还剩多少钱」。实现上内部重定向到管理 server 的 `/_apix_probe/<slug>`,
/// 复用 `$apix_probe_*` 变量(拼体、换 Key 与真实转发同一套逻辑)。
fn h_admin_apix_test(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let slug_raw = http::params(r).get("slug").cloned().unwrap_or_default();
let slug = match apix::validate_slug(&slug_raw) {
Ok(s) => s,
Err(e) => return http::fail(r, HTTPStatus::BAD_REQUEST, &e),
};
if apix::lookup(&slug).is_none() {
return http::fail(r, HTTPStatus::NOT_FOUND, &format!("代理 {slug} 不存在或已停用"));
}
let uri = format!("{}{}", apix::PROBE_URI_PREFIX, slug);
util::log_notice(&format!("[api] 测试 API 代理 {slug}"));
// ⚠️ 与 h_admin_upstream_test 同一个坑:internal_redirect 只浅拷贝 ngx_str_t,
// 必须把字节拷进请求池,否则函数返回后 r->uri 全是 NUL。
// SAFETY: r 有效;池内存在整个请求生命周期内有效。
unsafe {
let pool = Pool::from_ngx_pool((*r).pool);
let bytes = uri.as_bytes();
let data = pool.alloc(bytes.len()) as *mut u8;
if data.is_null() {
return http::fail(r, HTTPStatus::INTERNAL_SERVER_ERROR, "内存分配失败");
}
core::ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len());
let mut u = nginx_sys::ngx_str_t { len: bytes.len(), data };
let mut args = nginx_sys::ngx_str_t {
len: 0,
data: core::ptr::null_mut(),
};
nginx_sys::ngx_http_internal_redirect(r, &mut u, &mut args);
}
Status::NGX_DONE
}
/// 账号态:列出当前可用的 API 代理及调用地址
fn h_my_apix(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let port = http::host_port(r);
let items: Vec<Value> = apix::all()
.into_iter()
.filter(|(_, it)| it.enabled)
.map(|(slug, it)| apix::view(&slug, &it, &port))
.collect();
http::ok(r, json!({ "items": items, "count": items.len() }), "ok")
}
/// 设置某账号可用的 LLM 上游白名单(`models` 字段 = 上游 slot 列表,传空串 = 解除限制)。
///
/// 注意与**上游登记模型清单**(`Upstream.models`)是两件事:这里管"这个账号能用哪几家
+598
View File
@@ -0,0 +1,598 @@
//! API 代理:把外部 API 市场(aimall / 搜蚁智选)的资产挂到网关下。
//!
//! 与 LLM 代理(`llm.rs`)是**同一套下行契约**——都认 `sk_` 那把 Key、都吃
//! 同一份限流配额、都进同一套用量统计——差别只在上游形态:
//!
//! | | LLM 代理 | API 代理 |
//! | --- | --- | --- |
//! | 上游 | N 家厂商,各有基址与密钥 | 一个市场,共用基址与平台 Key |
//! | URL 第一段 | `slot` → `up:` 里的 `base \n auth` | `slug` → `ax:` 里的 `base \n key \n asset_id` |
//! | 请求体 | 客户端原样带过来 | **由网关从 query 拼**(见下) |
//!
//! ## 为什么请求体必须由网关拼
//!
//! 市场侧只有一个收口 `POST /api/v1/ai/request`,资产靠**请求体里的
//! `asset_id`** 区分。如果让客户端自己带 `asset_id`,管理员就失去了
//! 「只暴露免费资产」的控制力——任何人都能拿网关的 Key 去刷最贵的那个模型。
//! 所以资产选择权留在服务端:`slug → asset_id` 由管理员配置,
//! 调用方只能决定参数。
//!
//! 反过来,参数只能走 **query string**:转发决策在 access 阶段,而请求体
//! 要到 content 阶段才读得到(见 `llm.rs` 模块头注释)。nginx 侧靠
//! `proxy_method POST` + `proxy_set_body $apix_body` 把 GET 变成
//! 带体的 POST,网关不需要自己实现 upstream。
//!
//! `data/api-proxies.json` 含平台真 Key,**敏感级别等同 `users.json`**。
use ngx::core::Status;
use ngx::ffi::{ngx_http_request_t, ngx_http_variable_value_t, ngx_int_t};
use serde_json::{Value, json};
use crate::config;
use crate::http;
use crate::models::{ApiProxy, ApiProxyStore};
use crate::state;
use crate::store;
use crate::util;
// ===========================================================================
// 变量分派标记
// ===========================================================================
/// `$apix_target`:完整上游 URL(`base + /api/v1/ai/request`)
pub const VAR_TARGET: usize = 1;
/// `$apix_host`:上游 Host 头
pub const VAR_HOST: usize = 2;
/// `$apix_key`:平台 API Key(下行那把 `sk_` 到此为止,不往上游传)
pub const VAR_KEY: usize = 3;
/// `$apix_body`:由 query 拼出的调用体
pub const VAR_BODY: usize = 4;
/// `$apix_probe_target` / `$apix_probe_body`:管理台「测试」用的**免费**预估调用
pub const VAR_PROBE_TARGET: usize = 5;
pub const VAR_PROBE_BODY: usize = 6;
/// shm payload 内部分隔符:base / 平台 Key / asset_id 之间。
///
/// base 是 URL、key 与 asset_id 都是 token 类字符串,都不可能含换行。
pub const PAYLOAD_SEP: char = '\n';
/// 内部探测前缀(管理台「测试」按钮经内部重定向落到 `/_apix_probe/<slug>`)
pub const PROBE_URI_PREFIX: &str = "/_apix_probe/";
const PROBE_PREFIX: &str = PROBE_URI_PREFIX;
/// 对外的 API 代理前缀
const PUB_PREFIX: &str = "/apix/";
// ===========================================================================
// 校验
// ===========================================================================
/// slug:小写字母/数字开头,其后可含短横线、下划线。与 `upstreams::validate_slot`
/// 同一套规则(保持一致,管理员不用记两套),只把错误文案换成「slug」。
pub fn validate_slug(raw: &str) -> Result<String, String> {
let s = util::trim(raw).to_ascii_lowercase();
if s.is_empty() {
return Err("缺少 slug 参数".to_owned());
}
if s.len() > config::APIX_SLUG_MAX_LEN {
return Err(format!("slug 长度不能超过 {} 个字符", config::APIX_SLUG_MAX_LEN));
}
let bytes = s.as_bytes();
let head_ok = matches!(bytes[0], b'a'..=b'z' | b'0'..=b'9');
let tail_ok = bytes[1..].iter().all(|&b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_'));
if !head_ok || !tail_ok {
return Err("slug 只能是小写字母、数字、短横线或下划线,且不能以符号开头".to_owned());
}
Ok(s)
}
/// 市场基址:`http(s)://host`,允许尾随路径(市场挂在子路径下的情况)。
pub fn validate_base(raw: &str) -> Result<String, String> {
let s = util::trim(raw).trim_end_matches('/').to_owned();
if s.is_empty() {
return Err("缺少 base 参数".to_owned());
}
if s.len() > config::APIX_URL_MAX_LEN {
return Err(format!("base 长度不能超过 {} 个字符", config::APIX_URL_MAX_LEN));
}
let rest = if let Some(r) = s.strip_prefix("https://") {
r
} else if let Some(r) = s.strip_prefix("http://") {
r
} else {
return Err("base 必须以 http:// 或 https:// 开头,例如 https://souyi.net.cn".to_owned());
};
if rest.is_empty() || rest.split('/').next().unwrap_or("").is_empty() {
return Err("base 缺少主机名".to_owned());
}
if rest.chars().any(char::is_whitespace) || rest.contains('@') {
return Err("base 不允许包含空格或用户信息(user@host)".to_owned());
}
Ok(s)
}
/// asset_id:市场那边的资产标识。宽进——各市场的命名规则不同,
/// 这里只挡空白与控制字符(它要出现在 JSON 与 HTML 里)。
fn validate_asset(raw: &str) -> Result<String, String> {
let s = util::trim(raw).to_owned();
if s.is_empty() {
return Err("缺少 asset_id 参数".to_owned());
}
if s.chars().count() > config::APIX_ASSET_MAX_LEN {
return Err(format!("asset_id 超过 {} 个字符", config::APIX_ASSET_MAX_LEN));
}
if s.chars().any(char::is_whitespace) || s.chars().any(char::is_control) {
return Err("asset_id 不能包含空格或控制字符".to_owned());
}
Ok(s)
}
fn check_params(raw: &[String]) -> Result<Vec<String>, String> {
if raw.len() > config::APIX_PARAM_MAX {
return Err(format!("单个代理最多声明 {} 个参数", config::APIX_PARAM_MAX));
}
let mut out: Vec<String> = Vec::new();
for item in raw {
let p = util::trim(item);
if p.is_empty() {
continue;
}
if p.chars().count() > config::APIX_NAME_MAX_LEN {
return Err(format!("参数名「{p}」超过 {} 个字符", config::APIX_NAME_MAX_LEN));
}
if p.chars().any(char::is_whitespace) || p.chars().any(char::is_control) {
return Err(format!("参数名「{p}」不能包含空格或控制字符"));
}
if !out.iter().any(|x| x == p) {
out.push(p.to_owned());
}
}
Ok(out)
}
// ===========================================================================
// 共享内存同步(写穿 / 装载)
// ===========================================================================
fn payload_of(base: &str, key: &str, item: &ApiProxy) -> String {
format!("{base}{PAYLOAD_SEP}{key}{PAYLOAD_SEP}{}", item.asset_id)
}
/// 拆 payload:`base \n key \n asset_id`
pub fn split_payload(payload: &str) -> (&str, &str, &str) {
let mut it = payload.splitn(3, PAYLOAD_SEP);
let base = it.next().unwrap_or("");
let key = it.next().unwrap_or("");
let asset = it.next().unwrap_or("");
(base, key, asset)
}
/// 把一条代理同步进共享内存。**所有写操作之后必须调用它**。
///
/// 停用 = 删除(与 `upstreams::sync_shm` 同一手法):热路径「查不到 = 不可用」,
/// 这样停用即刻生效且不留残留。
pub fn sync_shm(slug: &str, store: &ApiProxyStore) {
let Some(item) = store.items.get(slug) else {
state::remove(config::KEY_AX_PREFIX, slug.as_bytes());
return;
};
if !item.enabled {
state::remove(config::KEY_AX_PREFIX, slug.as_bytes());
return;
}
let payload = payload_of(&store.base, &store.key, item);
if !state::put(config::KEY_AX_PREFIX, slug.as_bytes(), payload.as_bytes(), 0) {
util::log_err(&format!(
"[apix] 代理配置写共享内存失败 slug={slug} —— 该代理会 404(共享内存可能已满)"
));
}
}
/// 全量重载代理表(启动装载 / 平台凭据变更后)。返回装载条数。
pub fn reload_shm() -> usize {
state::clear_prefix(config::KEY_AX_PREFIX);
let data = store::read_api_proxies();
let mut expected = 0;
let mut loaded = 0;
for (slug, item) in &data.items {
if !item.enabled {
continue;
}
expected += 1;
let payload = payload_of(&data.base, &data.key, item);
if state::put(config::KEY_AX_PREFIX, slug.as_bytes(), payload.as_bytes(), 0) {
loaded += 1;
}
}
if loaded != expected {
util::log_err(&format!(
"[apix] 代理装载不全:{loaded}/{expected} —— 有代理会 404"
));
}
loaded
}
/// 热路径查表:`slug → (base, 平台Key, asset_id)`
pub fn lookup(slug: &str) -> Option<(String, String, String)> {
let payload = state::get(config::KEY_AX_PREFIX, slug.as_bytes())?.0;
let (base, key, asset) = split_payload(&payload);
if asset.is_empty() {
return None;
}
Some((base.to_owned(), key.to_owned(), asset.to_owned()))
}
// ===========================================================================
// 请求解析
// ===========================================================================
/// 取 URL 里的 slug:`/apix/search?q=1` 或 `/_apix_probe/search` → `search`
///
/// 两个前缀都认:对外出口与内部探测共用同一套「取 slug → 拼体 → 换 Key」逻辑,
/// 与 `llm::slot_of` 对 `/_upstream_test` 的处理是同一个手法。
pub fn slug_of(r: *mut ngx_http_request_t) -> Option<String> {
let uri = crate::http::uri(r);
let rest = uri
.strip_prefix(PROBE_PREFIX)
.or_else(|| uri.strip_prefix(PUB_PREFIX))?;
let slug = rest.split('/').next().unwrap_or("");
if slug.is_empty() {
return None;
}
Some(slug.to_ascii_lowercase())
}
/// 从 `https://souyi.net.cn:443` 取出 `souyi.net.cn:443`
fn host_of(base: &str) -> &str {
let rest = match base.find("://") {
Some(i) => &base[i + 3..],
None => base,
};
match rest.find('/') {
Some(i) => &rest[..i],
None => rest,
}
}
/// JSON 字符串字面量(含两侧引号)。
///
/// 自己拼而不走 `serde_json` 是因为输入来自 query string,中文与特殊字符
/// 都会被 percent-encode 过一遍,这里必须按 JSON 规则重新转义——
/// 直接 `format!("\"{v}\"")` 遇到 `"` 或 `\` 就拼出非法 JSON,
/// 上游报 400 而从网关日志完全看不出是拼体的问题。
fn json_quote(v: &str) -> String {
let mut out = String::with_capacity(v.len() + 2);
out.push('"');
for c in v.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
/// 单个参数值截断(bytes 级,避免把几 MB 的垃圾塞进调用体)
fn clip(v: &str) -> &str {
if v.len() <= config::APIX_VAL_MAX {
return v;
}
// 截断到字符边界,否则 `\u{fffd}` 会污染整个 JSON
let mut end = config::APIX_VAL_MAX;
while end > 0 && !v.is_char_boundary(end) {
end -= 1;
}
&v[..end]
}
/// 由 query 拼出市场的调用体。
///
/// ```text
/// ?q=nginx&format=json → {"asset_id":"searxng-search","call_data":{"q":"nginx","format":"json"}}
/// ?prompt=你好 → {"asset_id":"minimax-m3","prompt":"你好","call_data":{}}
/// ```
///
/// `prompt` 单独提到顶层:市场的 model 类资产(MiniMax-M3 等)把它当必填字段,
/// 塞进 `call_data` 会被当成未知参数。其余参数一律进 `call_data`。
pub fn build_body(asset_id: &str, args: &[(String, String)]) -> String {
let mut call = String::new();
let mut prompt: Option<&str> = None;
let mut n = 0;
for (k, v) in args {
if k.is_empty() || n >= config::APIX_ARG_MAX {
continue;
}
if k == "prompt" {
prompt = Some(v);
continue;
}
if !call.is_empty() {
call.push(',');
}
call.push_str(&json_quote(k));
call.push(':');
call.push_str(&json_quote(clip(v)));
n += 1;
}
let mut body = String::with_capacity(128 + call.len());
body.push_str("{\"asset_id\":");
body.push_str(&json_quote(asset_id));
if let Some(p) = prompt {
body.push_str(",\"prompt\":");
body.push_str(&json_quote(clip(p)));
}
body.push_str(",\"call_data\":{");
body.push_str(&call);
body.push_str("}}");
body
}
fn build_body_from_request(r: *mut ngx_http_request_t, asset_id: &str) -> String {
let args = util::parse_kv(&http::args_raw(r));
build_body(asset_id, &args)
}
// ===========================================================================
// 变量 get_handler
// ===========================================================================
/// 在请求内存池里分配字符串并写进变量槽。
///
/// # Safety
/// `r` / `v` 必须由 nginx 传入且在本调用期间有效。
unsafe fn set_value(
r: *mut ngx_http_request_t,
v: *mut ngx_http_variable_value_t,
value: &str,
) -> ngx_int_t {
let pool = ngx::core::Pool::from_ngx_pool((*r).pool);
let bytes = value.as_bytes();
let data = pool.alloc(bytes.len()) as *mut u8;
if data.is_null() {
(*v).set_not_found(1);
return Status::NGX_ERROR.into();
}
core::ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len());
(*v).data = data;
(*v).set_len(bytes.len() as _);
(*v).set_valid(1);
(*v).set_no_cacheable(1);
(*v).set_not_found(0);
Status::NGX_OK.into()
}
/// 六个 API 代理变量共用一个 get_handler,靠 `var.data` 分派。
pub extern "C" fn var_get(
r: *mut ngx_http_request_t,
v: *mut ngx_http_variable_value_t,
data: usize,
) -> ngx_int_t {
// SAFETY: r/v 由 nginx 传入且有效;slug_of 只读请求结构
unsafe {
let resolved = (|| -> Option<String> {
let slug = slug_of(r)?;
let (base, key, asset) = lookup(&slug)?;
Some(match data {
VAR_TARGET => format!("{base}{}", config::APIX_REQUEST_PATH),
VAR_PROBE_TARGET => format!("{base}{}", config::APIX_ESTIMATE_PATH),
VAR_HOST => host_of(&base).to_owned(),
VAR_KEY => key,
VAR_BODY => build_body_from_request(r, &asset),
VAR_PROBE_BODY => {
// 预估是**免费**的,且不真正执行资产——用它当连通性探针,
// 响应里的 current_balance_usd 顺带把平台余额带回来
format!("{{\"asset_id\":{},\"max_tokens\":1}}", json_quote(&asset))
}
_ => return None,
})
})();
match resolved {
Some(value) => set_value(r, v, &value),
None => {
(*v).set_not_found(1);
(*v).set_valid(0);
Status::NGX_ERROR.into()
}
}
}
}
// ===========================================================================
// 查询 / 写入
// ===========================================================================
pub fn all() -> Vec<(String, ApiProxy)> {
store::read_api_proxies()
.items
.into_iter()
.collect()
}
/// 客户端应当使用的调用地址。端口由调用方从请求 Host 头取,**不要写死**
/// (部署在 88 时要带 `:88`,放在 443 反代后面时不能带)。
pub fn call_url(slug: &str, params: &[String], port: &str) -> String {
let mut url = format!("https://{}{port}{PUB_PREFIX}{slug}", config::LLM_PUBLIC_HOST);
let mut first = true;
for p in params {
url.push(if first { '?' } else { '&' });
first = false;
url.push_str(p);
url.push('=');
}
url
}
/// 新增或覆盖一个代理条目。
///
/// `params = None` 表示保持原值(只改名字时不必回填参数清单)。
pub fn upsert(
slug_raw: &str,
asset_raw: &str,
name: Option<&String>,
desc: Option<&String>,
params: Option<Vec<String>>,
enabled: bool,
note: Option<&String>,
) -> Result<ApiProxy, String> {
let slug = validate_slug(slug_raw)?;
let asset_id = validate_asset(asset_raw)?;
let params = match params {
Some(list) => Some(check_params(&list)?),
None => None,
};
let key = slug.clone();
let (item, snapshot) = store::update_api_proxies(move |data| {
let existing = data.items.get(&key).cloned();
let name = match name {
Some(n) => util::trim(n).chars().take(config::APIX_NAME_MAX_LEN).collect(),
None => existing.as_ref().map(|e| e.name.clone()).unwrap_or_default(),
};
let desc = match desc {
Some(d) => util::trim(d).chars().take(config::APIX_DESC_MAX_LEN).collect(),
None => existing.as_ref().map(|e| e.desc.clone()).unwrap_or_default(),
};
let note = match note {
Some(n) => util::trim(n).to_owned(),
None => existing.as_ref().map(|e| e.note.clone()).unwrap_or_default(),
};
let params = match params {
Some(p) => p,
None => existing.as_ref().map(|e| e.params.clone()).unwrap_or_default(),
};
let created_at = existing
.as_ref()
.map(|e| e.created_at)
.filter(|&t| t > 0)
.unwrap_or_else(util::now);
let item = ApiProxy { asset_id, name, desc, params, enabled, price_per_call: 0.0, price_in: 0.0, price_out: 0.0, note, created_at };
data.items.insert(key.clone(), item.clone());
Ok((item, data.clone()))
})?;
sync_shm(&slug, &snapshot);
Ok(item)
}
/// 更新条目上的**价格快照**(从市场目录同步下来的展示用单价)
pub fn set_price(slug: &str, per_call: f64, pin: f64, pout: f64) {
let key = slug.to_owned();
let snapshot = store::update_api_proxies(move |data| {
if let Some(it) = data.items.get_mut(&key) {
it.price_per_call = per_call;
it.price_in = pin;
it.price_out = pout;
}
Ok(data.clone())
});
if let Ok(snap) = snapshot {
sync_shm(slug, &snap);
}
}
pub fn remove(slug_raw: &str) -> Result<String, String> {
let slug = validate_slug(slug_raw)?;
let key = slug.clone();
store::update_api_proxies(move |data| {
if data.items.remove(&key).is_none() {
return Err(format!("代理 {key} 不存在"));
}
Ok(())
})?;
state::remove(config::KEY_AX_PREFIX, slug.as_bytes());
Ok(slug)
}
/// 设置市场基址与平台 Key。
///
/// `base = None` / `key = None` 表示**保持原值**;`Some("")` 表示显式清空
/// (与 `upstreams::upsert` 的语义一致,避免"只想改 Key 却把 base 清了")。
/// 改 Key 必须**重新同步全部条目**——凭据是每个条目 payload 的一部分,
/// 漏同步的表现是「面板显示已保存,调用却还是用旧 Key」。
pub fn set_platform(base_raw: Option<&String>, key_raw: Option<&String>) -> Result<ApiProxyStore, String> {
let new_base = match base_raw {
Some(b) => {
let b = util::trim(b);
// 显式空串 = 恢复默认市场,而不是"清空基址"(没有基址无从转发)
if b.is_empty() {
Some(config::APIX_BASE_DEFAULT.to_owned())
} else {
Some(validate_base(b)?)
}
}
None => None,
};
let new_key = match key_raw {
Some(k) => {
let k = util::trim(k).to_owned();
if k.chars().count() > config::APIX_KEY_MAX_LEN {
return Err(format!("平台 Key 超过 {} 个字符", config::APIX_KEY_MAX_LEN));
}
Some(k)
}
None => None,
};
let data = store::update_api_proxies(move |d| {
if let Some(b) = new_base {
d.base = b;
}
if let Some(k) = new_key {
d.key = k;
}
Ok(d.clone())
})?;
reload_shm();
Ok(data)
}
// ===========================================================================
// 对外投影
// ===========================================================================
/// 转成管理台可见的字段。
///
/// **绝不回显完整平台 Key**——与 `upstreams::view` 同一理由:管理台页面会被
/// 截图、被浏览器插件读取,回显真 Key 等于把市场余额摆在一个 HTML 里。
pub fn view(slug: &str, item: &ApiProxy, port: &str) -> Value {
json!({
"slug": slug,
"asset_id": item.asset_id,
"name": item.name,
"desc": item.desc,
"params": item.params,
"enabled": item.enabled,
"price_per_call": item.price_per_call,
"price_in": item.price_in,
"price_out": item.price_out,
"free": item.price_per_call <= 0.0 && item.price_in <= 0.0 && item.price_out <= 0.0,
"note": item.note,
"created_at": item.created_at,
"created_at_text": util::fmt_time(item.created_at),
"url": call_url(slug, &item.params, port),
})
}
pub fn view_all(list: &[(String, ApiProxy)], port: &str) -> Vec<Value> {
list.iter().map(|(slug, it)| view(slug, it, port)).collect()
}
/// 管理台列表接口的顶层信息:基址 + Key 掩码 + 是否可用
pub fn platform_view() -> Value {
let data = store::read_api_proxies();
json!({
"base": data.base,
"key_set": !data.key.is_empty(),
"key_mask": if data.key.is_empty() { "-".to_owned() } else { util::mask_key(&data.key) },
"catalog_url": format!("{}/api/v1/assets", data.base),
})
}
+46
View File
@@ -151,6 +151,52 @@ pub const TREND_DAYS_MAX: i64 = 90;
/// 最多容忍客户端中途断连导致的误标(下一次真实转发即纠正)。
pub const KEY_UH_PREFIX: &[u8] = b"uh:";
// ---------------------------------------------------------------------------
// API 代理(apix):把外部 API 市场(aimall / 搜蚁智选)的资产挂到网关下
// ---------------------------------------------------------------------------
//
// 与 LLM 代理的关系:同一把 `sk_` 下行 Key、同一套限流与统计,
// 但上游是「一个市场 + N 个资产」而不是「N 家厂商」,所以 slug 只映射到
// `asset_id`,基址与平台 Key 是全局一份(见 `models::ApiProxyStore`)。
/// shm 键前缀:slug → `base \n 平台Key \n asset_id`。
///
/// 三行塞一个键是刻意的:热路径只查一次表就拿到转发所需全部信息。
/// 代价是改平台凭据要重新同步全部条目(条目数是个位数,无所谓)。
pub const KEY_AX_PREFIX: &[u8] = b"ax:";
/// 市场基址默认值
pub const APIX_BASE_DEFAULT: &str = "https://souyi.net.cn";
/// 市场「调用资产」路径(`POST {base}{path}`,body = `{"asset_id":..,"call_data":{..}}`)
pub const APIX_REQUEST_PATH: &str = "/api/v1/ai/request";
/// 市场「费用预估」路径。**免费**,且响应里带平台余额——管理台的
/// 「测试」按钮走它:既能验 Key 通不通,又能看到还剩多少钱,不花一分钱。
pub const APIX_ESTIMATE_PATH: &str = "/api/v1/ai/estimate";
/// slug 长度上限
pub const APIX_SLUG_MAX_LEN: usize = 32;
/// 市场基址长度上限
pub const APIX_URL_MAX_LEN: usize = 200;
/// 展示名 / 说明长度上限
pub const APIX_NAME_MAX_LEN: usize = 64;
pub const APIX_DESC_MAX_LEN: usize = 200;
/// asset_id 长度上限
pub const APIX_ASSET_MAX_LEN: usize = 64;
/// 单条目声明的参数个数上限
pub const APIX_PARAM_MAX: usize = 16;
/// 单次调用允许的 query 参数个数上限(挡住拼超长 URL 刷共享内存)
pub const APIX_ARG_MAX: usize = 32;
/// 单个参数值长度上限(bytes)
pub const APIX_VAL_MAX: usize = 4096;
/// 平台 Key 长度上限
pub const APIX_KEY_MAX_LEN: usize = 128;
/// 用量统计里 API 代理的 slot 前缀。
///
/// 与 LLM 的 slot 刻意区分开:`uds:<slot>:<日窗>` 是**同一片键空间**,
/// 而 LLM slot 的字符集不含 `/`(见 `upstreams::validate_slot`),
/// 所以 `api/<slug>` 绝不会和 LLM 上游撞车,用量页能自然分成两组。
pub const APIX_STATS_PREFIX: &str = "api/";
/// LLM 代理对外域名,用于账号态 API 回显 `base_url`。
/// 改域名只改这里(`conf/nginx.conf` 的 LLM server_name 要同步改)。
pub const LLM_PUBLIC_HOST: &str = "lm.mayishangshu.cn";
+156 -2
View File
@@ -20,6 +20,7 @@
//! | --- | --- | --- | --- |
//! | `*.yourdomain.com/*` | access | `ipass_proxy` | 查 `sub:` 决定后端 |
//! | `llm.yourdomain.com/<slot>/*` | access | `ipass_llm` | 查 `ukey:` 鉴权 + `up:` 定上游 |
//! | `llm.yourdomain.com/apix/<slug>` | access | `ipass_apix` | 同上鉴权,查 `ax:` 定市场资产 |
//! | `proxy-api.yourdomain.com/api/*` | content | `ipass_api` | 管理接口,读体后分发 |
//!
//! ## 关键实现约束(均为实测/查证确认,详见 CLAUDE.md)
@@ -38,6 +39,7 @@
//! 根本拿不到请求体。
mod api;
mod apix;
mod config;
mod domains;
mod http;
@@ -313,6 +315,86 @@ impl HttpRequestHandler for LlmHandler {
}
}
/// API 代理热路径(`/apix/<slug>?<参数>`):鉴权 → 查代理 → 放行。
///
/// 与 `LlmHandler` 是同一套下行契约(同一把 `sk_` Key、同一份限流配额),
/// 差别只在查哪张表、以及**请求体由网关拼**(`apix::build_body`)——
/// 资产选择权必须留在服务端,否则客户端能自己挑最贵的模型刷。
struct ApiProxyHandler;
impl HttpRequestHandler for ApiProxyHandler {
const PHASE: HttpPhase = HttpPhase::Access;
type Output = Status;
fn handler(request: &mut ngx::http::Request) -> Self::Output {
if !Module::location_conf(request).map(|c| c.apix).unwrap_or(false) {
return Status::NGX_DECLINED;
}
let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t;
let Some(slug) = apix::slug_of(r) else {
return http::fail(
r,
HTTPStatus::BAD_REQUEST,
"路径缺少代理名,正确形式:/apix/<代理名>?<参数>",
);
};
let Some(key) = llm::downstream_key(r) else {
return http::fail(
r,
HTTPStatus::UNAUTHORIZED,
"缺少 API Key,请在 Authorization: Bearer 或 x-api-key 中携带",
);
};
let Some((username, _allowed, rpm, daily)) = llm::identity(&key) else {
util::log_warn(&format!(
"[apix] API Key 校验失败 slug={slug} client={}",
http::remote_addr(r)
));
return http::fail(r, HTTPStatus::UNAUTHORIZED, "API Key 无效或已失效");
};
// 代理的**可见性**由管理员的启用/停用决定,不再叠一层账号白名单:
// 白名单是给「一家厂商一个 slot」设计的,这里再套一层会让
// 「管理员明明启用了、某账号却 403」变得难以解释。
let Some((_base, platform_key, _asset)) = apix::lookup(&slug) else {
return http::fail(
r,
HTTPStatus::NOT_FOUND,
&format!("代理 {slug} 不存在或已停用"),
);
};
if platform_key.is_empty() {
util::log_err(&format!(
"[apix] 平台 Key 未配置,slug={slug} 无法转发 —— 请到管理台「API 代理」填写"
));
return http::fail(
r,
HTTPStatus::SERVICE_UNAVAILABLE,
"平台 API Key 未配置,请联系管理员",
);
}
// SAFETY: r 由 nginx 传入且有效
if let Some(resp) = unsafe { llm::check_quota(r, &username, rpm, daily) } {
return resp;
}
// 用量统计。slot 带 `api/` 前缀,与 LLM 上游在同一片键空间里天然分组
stats::record(
&username,
&format!("{}{}", config::APIX_STATS_PREFIX, slug),
util::now(),
);
Status::NGX_DECLINED
}
}
/// `$upstream_status` 的变量索引,postconfiguration 时解析一次(log 阶段复用)。
static UPSTREAM_STATUS_IDX: AtomicIsize = AtomicIsize::new(-1);
@@ -485,6 +567,8 @@ struct ModuleConfig {
api: bool,
/// 该 location 走 LLM 代理(`/<slot>/...` → 上游)
llm: bool,
/// 该 location 走 API 代理(`/apix/<slug>` → 外部市场)
apix: bool,
}
unsafe impl HttpModuleLocationConf for Module {
@@ -502,6 +586,9 @@ impl Merge for ModuleConfig {
if prev.llm {
self.llm = true;
}
if prev.apix {
self.apix = true;
}
Ok(())
}
}
@@ -532,6 +619,28 @@ unsafe fn add_llm_var(cf: *mut ngx_conf_t, name: *mut ngx_str_t, slot: usize) ->
true
}
/// 同 [`add_llm_var`],注册一个由 `apix::var_get` 计算的只读变量
unsafe fn add_apix_var(cf: *mut ngx_conf_t, name: *mut ngx_str_t, slot: usize) -> bool {
// SAFETY: cf 由 nginx 传入;name 指向本函数调用方栈上的 ngx_str_t,注册时被拷贝
let var = unsafe {
ngx_http_add_variable(
cf,
name,
(NGX_HTTP_VAR_CHANGEABLE | NGX_HTTP_VAR_NOCACHEABLE) as ngx_uint_t,
)
};
if var.is_null() {
return false;
}
// SAFETY: var 非空且由本函数独占初始化;data 承载分派标记
unsafe {
(*var).get_handler = Some(apix::var_get);
(*var).set_handler = None;
(*var).data = slot;
}
true
}
impl HttpModule for Module {
fn module() -> &'static ngx_module_t {
// SAFETY: 模块定义是静态的,生命周期贯穿进程
@@ -581,6 +690,26 @@ impl HttpModule for Module {
return Status::NGX_ERROR.into();
}
// API 代理六件套。前缀 `apix_` 与 `llm_` 同理:nginx 变量名全局唯一。
let mut ax_target = ngx_string!("apix_target");
let mut ax_host = ngx_string!("apix_host");
let mut ax_key = ngx_string!("apix_key");
let mut ax_body = ngx_string!("apix_body");
let mut ax_ptarget = ngx_string!("apix_probe_target");
let mut ax_pbody = ngx_string!("apix_probe_body");
let apix_ok = unsafe {
add_apix_var(cf, &raw mut ax_target, apix::VAR_TARGET)
&& add_apix_var(cf, &raw mut ax_host, apix::VAR_HOST)
&& add_apix_var(cf, &raw mut ax_key, apix::VAR_KEY)
&& add_apix_var(cf, &raw mut ax_body, apix::VAR_BODY)
&& add_apix_var(cf, &raw mut ax_ptarget, apix::VAR_PROBE_TARGET)
&& add_apix_var(cf, &raw mut ax_pbody, apix::VAR_PROBE_BODY)
};
if !apix_ok {
ngx_conf_log_error!(NGX_LOG_EMERG, unsafe { &mut *cf }, "注册 API 代理变量失败");
return Status::NGX_ERROR.into();
}
Status::NGX_OK.into()
}
@@ -592,6 +721,9 @@ impl HttpModule for Module {
if ngx::http::add_phase_handler::<LlmHandler>(cf).is_err() {
return Status::NGX_ERROR.into();
}
if ngx::http::add_phase_handler::<ApiProxyHandler>(cf).is_err() {
return Status::NGX_ERROR.into();
}
if ngx::http::add_phase_handler::<LlmHealthHandler>(cf).is_err() {
return Status::NGX_ERROR.into();
}
@@ -617,7 +749,7 @@ impl HttpModule for Module {
}
}
static mut NGX_HTTP_IPASS_COMMANDS: [ngx_command_t; 7] = [
static mut NGX_HTTP_IPASS_COMMANDS: [ngx_command_t; 8] = [
ngx_command_t {
name: ngx_string!("ipass_state"),
type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2) as ngx_uint_t,
@@ -666,6 +798,14 @@ static mut NGX_HTTP_IPASS_COMMANDS: [ngx_command_t; 7] = [
offset: 0,
post: ptr::null_mut(),
},
ngx_command_t {
name: ngx_string!("ipass_apix"),
type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(set_flag_apix),
conf: NGX_HTTP_LOC_CONF_OFFSET,
offset: 0,
post: ptr::null_mut(),
},
ngx_command_t::empty(),
];
@@ -761,6 +901,19 @@ extern "C" fn set_flag_llm(
NGX_CONF_OK
}
extern "C" fn set_flag_apix(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
conf: *mut c_void,
) -> *mut c_char {
let Some(flag) = (unsafe { arg_flag(cf, 1) }) else {
return NGX_CONF_ERROR;
};
// SAFETY: 同上
unsafe { (*(conf as *mut ModuleConfig)).apix = flag };
NGX_CONF_OK
}
extern "C" fn set_state_zone(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
@@ -813,8 +966,9 @@ extern "C" fn state_zone_init(zone: *mut ngx_shm_zone_t, _data: *mut c_void) ->
// 没有任何回源兜底(同 domains 的写穿语义)。
let keys = users::reload_shm();
let ups = upstreams::reload_shm();
let axs = apix::reload_shm();
util::log_notice(&format!(
"[ipass] 已装载 {keys} 个账号 Key、{ups} 个 LLM 上游"
"[ipass] 已装载 {keys} 个账号 Key、{ups} 个 LLM 上游、{axs} 个 API 代理"
));
Status::NGX_OK.into()
+64
View File
@@ -106,6 +106,70 @@ fn default_llm_daily() -> i64 {
crate::config::LLM_DAILY_DEFAULT
}
/// API 代理表(`api-proxies.json`):**一个文件同时承载平台凭据与代理清单**。
///
/// 与 `llm-upstreams.json` 的区别:上游表是「一条记录 = 一家厂商(自带基址与
/// 密钥)」,而 API 代理面对的是**同一个市场**(aimall / 搜蚁智选)——
/// 所有资产共用一个基址、一把平台 Key,只有 `asset_id` 不同。
/// 所以凭据放在文件顶层(`base` + `key`),`items` 里只放资产差异。
///
/// `key` 是平台真 Key,**敏感级别等同 `users.json`**(data/ 已 gitignore)。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiProxyStore {
/// 市场基址,如 `https://souyi.net.cn`
#[serde(default = "default_apix_base")]
pub base: String,
/// 平台 API Key(`ak_...`)。留空 = 未配置,热路径直接 503
#[serde(default)]
pub key: String,
/// slug → 资产映射
#[serde(default)]
pub items: BTreeMap<String, ApiProxy>,
}
impl Default for ApiProxyStore {
fn default() -> Self {
Self { base: default_apix_base(), key: String::new(), items: BTreeMap::new() }
}
}
fn default_apix_base() -> String {
crate::config::APIX_BASE_DEFAULT.to_owned()
}
/// 单个 API 代理条目。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiProxy {
/// 市场侧的资产 id(如 `searxng-search`),决定钱花在哪个资产上
pub asset_id: String,
/// 展示名(中文)
#[serde(default)]
pub name: String,
/// 一句话说明
#[serde(default)]
pub desc: String,
/// **声明式参数清单**(如 `["q"]`)。
///
/// 只用于给调用方看的文档(管理台把 `?q=关键词` 拼出来、账号态接口回显),
/// 转发时**不按它过滤**——过滤要靠读请求体,而 access 阶段读不到。
/// 市场侧自己会拒绝不认识的参数,拦在网关意义不大。
#[serde(default)]
pub params: Vec<String>,
#[serde(default = "default_true")]
pub enabled: bool,
/// 单价(USD),从市场目录同步下来的快照,只用于展示
#[serde(default)]
pub price_per_call: f64,
#[serde(default)]
pub price_in: f64,
#[serde(default)]
pub price_out: f64,
#[serde(default)]
pub note: String,
#[serde(default)]
pub created_at: i64,
}
/// 域名表(`domains.json`):一条记录 = 一个子域名。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DomainEntry {
+27 -2
View File
@@ -19,15 +19,16 @@
//! | `users.json` | 账号、口令哈希、API Key | `ukey:` 索引进(热路径要它) |
//! | `domains.json` | 子域名 → 后端映射 | `sub:` 进(转发热路径) |
//! | `llm-upstreams.json` | LLM 上游基址与密钥 | `up:` 进(LLM 转发热路径) |
//! | `api-proxies.json` | API 市场凭据 + 代理清单 | `ax:` 进(API 代理热路径) |
//!
//! 三个文件都在 `data/` 下,都已 `.gitignore`。**LLM 上游表含上游真 Key,
//! 四个文件都在 `data/` 下,都已 `.gitignore`。**LLM 上游表含上游真 Key,
//! 敏感级别与 `users.json` 相同**,不要再往别处复制。
use std::path::PathBuf;
use std::sync::Mutex;
use crate::config::DEFAULT_DATA_DIR;
use crate::models::{DomainEntry, UpstreamTable, UserTable};
use crate::models::{ApiProxyStore, DomainEntry, UpstreamTable, UserTable};
use crate::state;
/// 状态目录。配置阶段由 `ipass_data_dir` 指令设置一次,之后只读。
@@ -63,6 +64,10 @@ pub fn upstreams_path() -> PathBuf {
path_of("llm-upstreams.json")
}
pub fn api_proxies_path() -> PathBuf {
path_of("api-proxies.json")
}
// ===========================================================================
// 读写
// ===========================================================================
@@ -120,6 +125,10 @@ pub fn read_upstreams() -> UpstreamTable {
read_json(&upstreams_path(), UpstreamTable::new())
}
pub fn read_api_proxies() -> ApiProxyStore {
read_json(&api_proxies_path(), ApiProxyStore::default())
}
pub fn write_users(data: &UserTable) -> Result<(), String> {
write_json(&users_path(), data)
}
@@ -132,6 +141,10 @@ pub fn write_upstreams(data: &UpstreamTable) -> Result<(), String> {
write_json(&upstreams_path(), data)
}
pub fn write_api_proxies(data: &ApiProxyStore) -> Result<(), String> {
write_json(&api_proxies_path(), data)
}
/// 加锁「读-改-写」账号表。
///
/// 闭包返回 `Ok(T)` 表示提交,`Err(msg)` 表示放弃(不写盘)。
@@ -169,3 +182,15 @@ where
write_upstreams(&data)?;
Ok(out)
}
/// 加锁「读-改-写」API 代理表
pub fn update_api_proxies<T, F>(f: F) -> Result<T, String>
where
F: FnOnce(&mut ApiProxyStore) -> Result<T, String>,
{
let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?;
let mut data = read_api_proxies();
let out = f(&mut data)?;
write_api_proxies(&data)?;
Ok(out)
}
+74
View File
@@ -326,6 +326,80 @@ ck "不存在的 slot → 404 信封" 404 \
ck "★内部 location 外部直连 → 404(不能绕过 admin 会话触达上游)" 404 \
"$(code -b "$JAR" -X POST "$API/_upstream_test/openai/v1/chat/completions" -d '{}')"
echo
echo "【11.5】★ API 代理(/apix/<slug> → 外部 API 市场)"
# 与 LLM 代理同一把 sk_ Key,但上游形态不同:市场只有一个收口,资产由
# **请求体里的 asset_id** 决定,所以请求体必须由网关拼——判据是看靶机
# 收到的 path / 头 / body 三件事,只看网关自己的 200 什么都证明不了。
ck "无 Key → 401" 401 "$(code "$GW/apix/search?q=hello")"
ck "坏 Key → 401" 401 "$(code -H 'X-API-Key: sk_nope' "$GW/apix/search?q=hello")"
ck "不存在的 slug → 404" 404 "$(code -H "X-API-Key: $ALICE_KEY" "$GW/apix/ghost?q=1")"
ck "★已停用的 slug → 404(shm 里已摘除)" 404 "$(code -H "X-API-Key: $ALICE_KEY" "$GW/apix/offline?q=1")"
ck "★正常调用 → 透传上游 200" 200 "$(code -H "X-API-Key: $ALICE_KEY" "$GW/apix/search?q=hello")"
ck " 靶机 path = 市场的收口" "/api/v1/ai/request" "$(up_field path)"
ck " ★GET 被改写成 POST(proxy_method + proxy_set_body)" "POST" "$(up_field method)"
ck " ★换上了平台真 Key" "ak_test_platform_key" "$(up_hdr x-api-key)"
ck " ★调用体由网关拼:asset_id 来自配置" yes \
"$(up_field body | grep -q '"asset_id":"searxng-search"' && echo yes || echo no)"
ck " ★query 参数进 call_data" yes \
"$(up_field body | grep -q '"q":"hello"' && echo yes || echo no)"
ck " ★下行 Key 没被带出去" yes "$(up_field body | nhas 'sk_alice')"
ck " 下游 Authorization 未透传" "" "$(up_hdr authorization)"
# x-api-key 头**会**有值——那正是换上的平台真 Key。要证的是它不再以下游的
# sk_ 开头:客户端用自己的 Key 换来市场凭据,而不是凭据被原样透传。
AXH=$(up_hdr x-api-key)
ck " ★下游 x-api-key 已被换掉(不再是 sk_ 开头)" no \
"$(printf '%s' "$AXH" | grep -q '^sk_' && echo yes || echo no)"
# 管理台:清单 / 凭据掩码 / 停启用写穿
ck "管理台列表含 search" yes "$(curl -s -b "$JAR" $API/api/admin/apix | has '"slug": *"search"')"
ck " ★平台 Key 只回显掩码(不回显真值)" no \
"$(curl -s -b "$JAR" $API/api/admin/apix | has 'ak_test_platform_key')"
ck " 平台 base 回显" "http://127.0.0.1:18999" \
"$(curl -s -b "$JAR" $API/api/admin/apix | jqv data.platform.base)"
ck " 已停用条目 enabled=false" "False" "$(curl -s -b "$JAR" $API/api/admin/apix | "$PY" -c '
import sys, json
d = json.load(sys.stdin)["data"]
it = next((x for x in d["items"] if x["slug"] == "offline"), None)
print(str(it.get("enabled")) if it else "miss")')"
ck "账号态接口只列已启用的(offline 不出现)" "1" \
"$(curl -s -H "X-API-Key: $ALICE_KEY" $API/api/v1/apix | jqv data.count)"
ck "非法 slug → 400" 400 "$(code -b "$JAR" -X POST $API/api/admin/apix/save \
-H 'Content-Type: application/json' -d "$(jbody slug 'Bad Slug!' asset_id x)")"
ck "缺 asset_id → 400" 400 "$(code -b "$JAR" -X POST $API/api/admin/apix/save \
-H 'Content-Type: application/json' -d "$(jbody slug med asset_id '')")"
ck "新建代理 med → 200" 200 "$(code -b "$JAR" -X POST $API/api/admin/apix/save \
-H 'Content-Type: application/json' -d "$(jbody slug med asset_id asset_26476ef1-4687-45 name 疾病百科 params kw)")"
ck " ★新代理立即可用(写穿 shm)" 200 "$(code -H "X-API-Key: $ALICE_KEY" "$GW/apix/med?kw=感冒")"
ck " 靶机 body 带新 asset_id 与新参数" yes \
"$(up_field body | grep -q '"asset_id":"asset_26476ef1-4687-45"' && echo yes || echo no)"
ck " 参数名用的是 med 声明的 kw" yes "$(up_field body | grep -q '"kw":"' && echo yes || echo no)"
curl -s -b "$JAR" -X POST $API/api/admin/apix/save -H 'Content-Type: application/json' \
-d "$(jbody slug search asset_id searxng-search enabled false)" >/dev/null
ck "★停用后立即 404(写穿 shm,无回源兜底)" 404 \
"$(code -H "X-API-Key: $ALICE_KEY" "$GW/apix/search?q=1")"
curl -s -b "$JAR" -X POST $API/api/admin/apix/save -H 'Content-Type: application/json' \
-d "$(jbody slug search asset_id searxng-search enabled true)" >/dev/null
ck " 重新启用后又能调通" 200 "$(code -H "X-API-Key: $ALICE_KEY" "$GW/apix/search?q=1")"
curl -s -b "$JAR" -X POST $API/api/admin/apix/delete -H 'Content-Type: application/json' \
-d "$(jbody slug med)" >/dev/null
ck "删除后再调 → 404" 404 "$(code -H "X-API-Key: $ALICE_KEY" "$GW/apix/med?kw=x")"
# 探测:走市场的**免费**预估接口,不执行资产、不扣费
ck "★探测(免费预估)→ 透传 200" 200 "$(code -b "$JAR" -X POST \
"$API/api/admin/apix/test?slug=search" -H 'Content-Type: application/json' -d '{}')"
ck " 探测打的是 /api/v1/ai/estimate" "/api/v1/ai/estimate" "$(up_field path)"
ck " 探测也换了平台真 Key" "ak_test_platform_key" "$(up_hdr x-api-key)"
ck "★内部探测口外部直连 → 404" 404 \
"$(code -b "$JAR" -X POST "$API/_apix_probe/search" -d '{}')"
ck " 不存在的 slug 探测 → 404" 404 "$(code -b "$JAR" -X POST \
"$API/api/admin/apix/test?slug=ghost" -H 'Content-Type: application/json' -d '{}')"
ck "★用量统计按 api/<slug> 归组(与 LLM 上游天然分开)" yes \
"$(curl -s -b "$JAR" $API/api/admin/usage | has '"slot": *"api/search"')"
ck "★趋势含 api/<slug> 维度" yes "$(curl -s -b "$JAR" "$API/api/admin/trend?days=7" | has '"slot": *"api/search"')"
echo
echo "【12】★ 上游健康标记(失效自动缓存 + 模型发现附可用地址/状态)"
# 健康缓存由 log 阶段的**真实转发**写入(uh:<slot>)——「测试」按钮走同一条
+22
View File
@@ -0,0 +1,22 @@
{
"base": "http://127.0.0.1:18999",
"key": "ak_test_platform_key",
"items": {
"search": {
"asset_id": "searxng-search",
"name": "SearXNG 免费搜索",
"desc": "服务端聚合 Google / Brave / Bing",
"params": ["q"],
"enabled": true,
"created_at": 1750000000
},
"offline": {
"asset_id": "disabled-asset",
"name": "已停用的代理",
"desc": "enabled=false,热路径必须查不到",
"params": [],
"enabled": false,
"created_at": 1750000000
}
}
}
+46
View File
@@ -82,6 +82,35 @@ http {
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
# ---- API 代理出口(与生产 conf/nginx.conf 的 /apix/ 逐条对齐)----
# 靶机地址由夹具 api-proxies.json 的 base 指向 127.0.0.1:18999,
# 所以这里不需要为测试改任何 nginx 配置——转发链路与生产完全一致。
location /apix/ {
ipass_apix on;
proxy_pass $apix_target;
proxy_method POST;
proxy_set_body $apix_body;
proxy_http_version 1.1;
proxy_pass_request_headers off;
proxy_set_header x-api-key "";
proxy_set_header api-key "";
proxy_set_header Authorization "";
proxy_set_header Host $apix_host;
proxy_set_header X-API-Key $apix_key;
proxy_set_header Content-Type application/json;
proxy_set_header Accept application/json;
proxy_set_header User-Agent $http_user_agent;
proxy_set_header Connection "";
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
# ---- 管理 server(只为在同一次回归里验账号态用量/模型接口)----
@@ -99,6 +128,23 @@ http {
ipass_api on;
}
# API 代理探测:/api/admin/apix/test 内部重定向到这里
location /_apix_probe/ {
internal;
proxy_pass $apix_probe_target;
proxy_method POST;
proxy_set_body $apix_probe_body;
proxy_http_version 1.1;
proxy_pass_request_headers off;
proxy_set_header Host $apix_host;
proxy_set_header X-API-Key $apix_key;
proxy_set_header Content-Type application/json;
proxy_set_header Accept application/json;
proxy_connect_timeout 5s;
proxy_send_timeout 15s;
proxy_read_timeout 15s;
}
# 上游连通性测试:/api/admin/upstreams/test 内部重定向到这里
# (与生产 conf 同套:proxy_pass 复用 $llm_*,探测体原样转发,状态透传)
location /_upstream_test/ {
+1
View File
@@ -118,6 +118,7 @@ suite_llm() {
# 夹具覆盖式播种,保证每次跑的起点一致(这两个文件是合成数据,不是生产 data)
cp "$HERE/llm/fixtures/users.json" "$RUN/data/users.json"
cp "$HERE/llm/fixtures/llm-upstreams.json" "$RUN/data/llm-upstreams.json"
cp "$HERE/llm/fixtures/api-proxies.json" "$RUN/data/api-proxies.json"
rm -f "$RUN/upstream.log"
render "$HERE/llm/nginx.conf.in" "$RUN/nginx.conf" "$RUN"
+84
View File
@@ -0,0 +1,84 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="/admin/">
<title>API 代理 · 尚数网 山海关</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<div id="shell"></div>
<div class="wrap">
<div class="panel">
<h2>API 市场凭据</h2>
<div class="desc">
把外部 API 市场(默认 <code>搜蚁智选 / AIMALL</code>)挂到网关下:调用方用<b>同一把账号 API Key</b>,
访问 <code>/apix/&lt;代理名&gt;?参数=值</code>,网关换成平台 Key 后转发到市场,并返回市场原样结果。
资产由<b>本页面的配置</b>决定(不是调用方在请求里指定),所以管理员能控制"只暴露哪些、不暴露哪些"。
</div>
<form id="platformForm" class="grid-form up-form">
<div><label for="pfBase">市场基址</label><input id="pfBase" class="field-mono" type="text" placeholder="https://souyi.net.cn"></div>
<div><label for="pfKey">平台 API Key(留空 = 不修改)</label><input id="pfKey" class="field-mono" type="text" placeholder="ak_..." autocomplete="off"></div>
<div><button class="btn-primary btn-block" type="submit">保存凭据</button></div>
<div class="span-all muted" id="pfState" style="font-size:12.5px"></div>
</form>
</div>
<div class="panel">
<h2>新建 / 更新代理</h2>
<div class="desc">
<b>slug</b> 是对外的名字(<code>/apix/slug</code>),<b>asset_id</b> 是市场内部的资产标识。
参数只能走 query string(转发决策在 access 阶段,那时读不到请求体),
声明的参数名只用于生成示例地址,实际转发会把全部 query 参数原样带过去。
</div>
<form id="upsertApixForm" class="grid-form up-form">
<div><label for="axSlug">slug(对外名字)</label><input id="axSlug" type="text" placeholder="search" required></div>
<div><label for="axName">展示名</label><input id="axName" type="text" placeholder="SearXNG 免费搜索"></div>
<div class="span-all"><label for="axAsset">asset_id(市场资产标识)</label><input id="axAsset" class="field-mono" type="text" placeholder="searxng-search" required></div>
<div class="span-all"><label for="axParams">参数名(逗号分隔,仅用于生成示例地址)</label><input id="axParams" class="field-mono" type="text" placeholder="q"></div>
<div class="span-all"><label for="axDesc">说明</label><input id="axDesc" type="text" placeholder="可选"></div>
<div><button class="btn-primary btn-block" type="submit">保存代理</button></div>
</form>
</div>
<div class="panel">
<h2>市场资产目录 <span class="muted" style="font-size:12.5px;font-weight:400">(点「接入」自动填表)</span></h2>
<div class="desc">
直接从市场拉取公开目录(<code>GET /api/v1/assets</code>,匿名可读、已开放跨域),
价格是市场侧的实时数字。<b>免费</b>的资产接入后不消耗余额,计费资产请先看自己的余额再开放。
</div>
<div class="row-actions" style="margin-bottom:8px">
<button class="btn-sm" id="refreshCatalog">刷新目录</button>
<span class="muted" id="catalogState" style="font-size:12.5px"></span>
</div>
<table>
<thead><tr>
<th>asset_id</th><th>名称 / 说明</th><th>类型</th><th>单价</th><th>30 天成功率</th><th>操作</th>
</tr></thead>
<tbody id="catalogBody"><tr><td colspan="6" class="empty">点「刷新目录」拉取</td></tr></tbody>
</table>
</div>
<div class="panel">
<h2>代理列表</h2>
<div class="desc">
停用的代理对调用方表现为 404(共享内存里已摘除,立即生效)。
「测试」走市场的<b>免费</b>预估接口,不执行资产、不扣费,顺带把平台余额带回来。
</div>
<table>
<thead><tr>
<th>slug</th><th>asset_id</th><th>调用地址</th><th>单价</th><th>状态</th><th>创建时间</th><th>操作</th>
</tr></thead>
<tbody id="apixBody"></tbody>
</table>
</div>
</div>
<div id="toast"></div>
<script src="assets/core.js"></script>
<script src="assets/apix.js"></script>
</body>
</html>
+219
View File
@@ -0,0 +1,219 @@
/* API 代理:市场凭据 + 资产目录接入 + 代理列表(复制地址、测试、启停、删除)*/
(function () {
"use strict";
var $ = IP.$;
var catalog = [];
function priceText(it) {
if (it.price_per_call > 0) return "$" + it.price_per_call + " / 次";
if (it.price_in > 0 || it.price_out > 0) {
return "in $" + it.price_in + " · out $" + it.price_out + " / 1M tok";
}
return '<span class="badge b-ok">免费</span>';
}
function render(s) {
var pf = s.apix.platform || {};
var st = $("pfState");
if (st) {
st.innerHTML = "当前基址 <code class='mono'>" + IP.esc(pf.base || "-") + "</code> · 平台 Key " +
(pf.key_set
? "<code class='mono'>" + IP.esc(pf.key_mask) + "</code>"
: "<span class='badge b-err'>未配置</span>(代理会返回 503)");
}
var body = $("apixBody");
if (!s.apix.items.length) {
body.innerHTML = '<tr><td colspan="7" class="empty">还没有配置任何 API 代理 —— 可以先在上方「刷新目录」挑一个免费资产接入</td></tr>';
return;
}
body.innerHTML = s.apix.items.map(function (it) {
var enabled = !!it.enabled;
var toggle = enabled
? "<button class='btn-sm btn-danger' data-act='toggle' data-slug='" + IP.esc(it.slug) + "' data-enabled='0'>停用</button>"
: "<button class='btn-sm btn-ok' data-act='toggle' data-slug='" + IP.esc(it.slug) + "' data-enabled='1'>启用</button>";
var params = IP.arr(it.params);
var url = it.url + (params.length ? "?" + params.map(function (p) { return p + "="; }).join("&") : "");
return "<tr>" +
"<td><b>" + IP.esc(it.slug) + "</b>" +
(it.name ? "<div class='muted' style='font-size:12px;margin-top:4px'>" + IP.esc(it.name) + "</div>" : "") +
(it.desc ? "<div class='muted' style='font-size:11.5px;margin-top:2px'>" + IP.esc(it.desc) + "</div>" : "") +
"</td>" +
"<td class='mono'>" + IP.esc(it.asset_id) + "</td>" +
"<td><code class='mono' style='font-size:12px'>" + IP.esc(url) + "</code>" +
"<div class='row-actions' style='margin-top:6px'>" +
"<button class='btn-sm' data-act='copy' data-url='" + IP.esc(url) + "'>复制地址</button>" +
(params.length ? "<button class='btn-sm' data-act='copy' data-url='" + IP.esc(it.url + "?" + params[0] + "=关键词") + "'>复制示例</button>" : "") +
"</div></td>" +
"<td>" + priceText(it) + "</td>" +
"<td>" + (enabled ? "<span class='badge b-ok'>启用中</span>" : "<span class='badge b-gray'>已停用</span>") + "</td>" +
"<td class='muted nowrap'>" + IP.esc(it.created_at_text) + "</td>" +
"<td><div class='row-actions'>" +
"<button class='btn-sm' data-act='test' data-slug='" + IP.esc(it.slug) + "'>测试</button>" +
"<button class='btn-sm' data-act='edit' data-slug='" + IP.esc(it.slug) + "'>编辑</button>" +
toggle +
"<button class='btn-sm btn-danger' data-act='del' data-slug='" + IP.esc(it.slug) + "'>删除</button>" +
"</div></td>" +
"</tr>";
}).join("");
}
// ---------------- 市场资产目录 ----------------
// 目录是**公开**的(市场侧已开 Access-Control-Allow-Origin: *),所以浏览器
// 直接拉就行,不必绕网关——绕一圈反而要把市场地址写死进后端。
function loadCatalog() {
var base = (IP.state.apix.platform && IP.state.apix.platform.base) || "";
var st = $("catalogState");
if (!base) {
if (st) st.textContent = "未配置市场基址";
return;
}
if (st) st.textContent = "拉取中…";
fetch(base + "/api/v1/assets", { headers: { Accept: "application/json" } })
.then(function (r) { return r.json(); })
.then(function (d) {
catalog = IP.arr(d.data);
renderCatalog();
if (st) st.textContent = "共 " + catalog.length + " 个资产";
})
.catch(function () {
if (st) st.textContent = "目录拉取失败(浏览器直连市场被拦时,可在网关宿主机上放行该域名)";
});
}
function renderCatalog() {
var body = $("catalogBody");
if (!catalog.length) {
body.innerHTML = '<tr><td colspan="6" class="empty">目录为空</td></tr>';
return;
}
body.innerHTML = catalog.map(function (a, i) {
var free = !(a.price_per_call > 0 || a.price_input > 0 || a.price_output > 0);
var price = a.price_per_call > 0
? "$" + a.price_per_call + " / 次"
: (a.price_input > 0 || a.price_output > 0)
? "in $" + a.price_input + " · out $" + a.price_output + " / 1M tok"
: '<span class="badge b-ok">免费</span>';
var rate = a.telemetry && typeof a.telemetry.success_rate_30d === "number"
? Math.round(a.telemetry.success_rate_30d * 100) + "%"
: "-";
return "<tr>" +
"<td class='mono'>" + IP.esc(a.asset_id) + "</td>" +
"<td><b>" + IP.esc(a.name || "-") + "</b>" +
"<div class='muted' style='font-size:11.5px;margin-top:3px'>" + IP.esc(a.description || "") + "</div></td>" +
"<td><span class='badge b-blue'>" + IP.esc(a.api_type || "-") + "</span></td>" +
"<td>" + price + (free ? "" : "") + "</td>" +
"<td class='muted'>" + IP.esc(rate) + "</td>" +
"<td><button class='btn-sm' data-act='pick' data-i='" + i + "'>接入</button></td>" +
"</tr>";
}).join("");
}
$("catalogBody").addEventListener("click", function (e) {
var btn = e.target.closest("button[data-act='pick']");
if (!btn) return;
var a = catalog[parseInt(btn.getAttribute("data-i"), 10)];
if (!a) return;
// 由 asset_id 推一个像样的 slug:取最后一段、只留合法字符
var slug = String(a.asset_id).split(/[-_]/).pop().toLowerCase().replace(/[^a-z0-9_-]/g, "").slice(0, 24);
$("axSlug").value = slug || "asset";
$("axName").value = a.name || "";
$("axAsset").value = a.asset_id;
$("axDesc").value = a.description || "";
$("axSlug").focus();
IP.toast("已填入「" + (a.name || a.asset_id) + "」,确认 slug 后保存");
});
$("refreshCatalog").addEventListener("click", loadCatalog);
// ---------------- 列表操作 ----------------
$("apixBody").addEventListener("click", function (e) {
var btn = e.target.closest("button[data-act]");
if (!btn) return;
var act = btn.getAttribute("data-act");
var slug = btn.getAttribute("data-slug");
if (act === "copy") {
IP.copyText(btn.getAttribute("data-url"), "调用地址");
return;
}
if (act === "test") {
var label = btn.textContent;
var restore = function () { btn.disabled = false; btn.textContent = label; };
btn.disabled = true; btn.textContent = "测试中…";
var t0 = Date.now();
IP.api("POST", "/api/admin/apix/test", { slug: slug })
.then(function (d) {
var data = d.data || {};
var inner = data.data || data;
var bal = (inner && (inner.current_balance_usd !== undefined ? inner.current_balance_usd : inner.balance));
var ms = Date.now() - t0;
IP.toast("✅ " + slug + " 通(" + ms + " ms)" +
(bal !== undefined ? " · 平台余额 $" + bal : ""));
restore();
})
.catch(function (err) { IP.toast("✗ " + slug + ":" + err.message, true); restore(); });
return;
}
if (act === "toggle") {
var it = IP.state.apix.items.filter(function (x) { return x.slug === slug; })[0];
if (!it) return;
btn.disabled = true;
IP.api("POST", "/api/admin/apix/save", {
slug: slug,
asset_id: it.asset_id,
enabled: btn.getAttribute("data-enabled") === "1"
}).then(function (r) { IP.toast(r.msg); return IP.reload(); })
.catch(function (err) { IP.toast(err.message, true); btn.disabled = false; });
} else if (act === "edit") {
var it2 = IP.state.apix.items.filter(function (x) { return x.slug === slug; })[0];
if (!it2) return;
$("axSlug").value = it2.slug;
$("axName").value = it2.name || "";
$("axAsset").value = it2.asset_id;
$("axParams").value = IP.arr(it2.params).join(",");
$("axDesc").value = it2.desc || "";
$("axAsset").focus();
IP.toast("已载入 " + slug + ",改完点「保存代理」");
} else if (act === "del") {
if (!confirm("确认删除代理 " + slug + "?调用方将立即 404。")) return;
btn.disabled = true;
IP.api("POST", "/api/admin/apix/delete", { slug: slug })
.then(function (r) { IP.toast(r.msg); return IP.reload(); })
.catch(function (err) { IP.toast(err.message, true); btn.disabled = false; });
}
});
$("upsertApixForm").addEventListener("submit", function (e) {
e.preventDefault();
IP.api("POST", "/api/admin/apix/save", {
slug: $("axSlug").value.trim(),
asset_id: $("axAsset").value.trim(),
name: $("axName").value.trim(),
desc: $("axDesc").value.trim(),
params: $("axParams").value.trim()
}).then(function (r) { IP.toast(r.msg); return IP.reload(); })
.catch(function (err) { IP.toast(err.message, true); });
});
$("platformForm").addEventListener("submit", function (e) {
e.preventDefault();
var payload = {};
var base = $("pfBase").value.trim();
var key = $("pfKey").value.trim();
// 与上游密钥同一约定:留空 = 保持原值,只有填了才下发
if (base) payload.base = base;
if (key) payload.key = key;
IP.api("POST", "/api/admin/apix/platform", payload)
.then(function (r) { IP.toast(r.msg); $("pfKey").value = ""; return IP.reload(); })
.catch(function (err) { IP.toast(err.message, true); });
});
IP.boot("apix", function (s) { render(s); });
})();
+9 -2
View File
@@ -18,6 +18,7 @@ window.IP = (function () {
{ key: "domains", name: "全部域名", href: "domains.html" },
{ key: "users", name: "账号管理", href: "users.html" },
{ key: "upstreams", name: "LLM 上游", href: "upstreams.html" },
{ key: "apix", name: "API 代理", href: "apix.html" },
{ key: "usage", name: "用量统计", href: "usage.html" }
];
@@ -26,6 +27,7 @@ window.IP = (function () {
users: [],
domains: [],
upstreams: [],
apix: { platform: {}, items: [] },
usage: { total: {}, tokens: {}, users: [], models: [] },
trend: null,
trendDays: 14,
@@ -151,6 +153,10 @@ window.IP = (function () {
api("GET", "/api/admin/domains"),
api("GET", "/api/admin/users"),
api("GET", "/api/admin/upstreams"),
// API 代理是后加的板块,老镜像没有这两个接口——缺了不能让整个面板挂掉
api("GET", "/api/admin/apix").catch(function () {
return { data: { platform: {}, items: [] } };
}),
// 老版本后端没有用量接口时不要让整个面板挂掉
api("GET", "/api/admin/usage").catch(function () {
return { data: { total: {}, tokens: {}, users: [], models: [] } };
@@ -164,8 +170,9 @@ window.IP = (function () {
}
state.users = arr(res[1].data.items);
state.upstreams = arr(res[2].data.items);
state.usage = res[3].data || { total: {}, tokens: {}, users: [], models: [] };
state.trend = res[4].data || null;
state.apix = res[3].data || { platform: {}, items: [] };
state.usage = res[4].data || { total: {}, tokens: {}, users: [], models: [] };
state.trend = res[5].data || null;
syncPendingPill();
if (currentRender) currentRender(state);
autoProbeUpstreams();