diff --git a/CLAUDE.md b/CLAUDE.md index b831809..da23d91 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -127,7 +127,7 @@ 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`; + - **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) 扫描。 diff --git a/conf/nginx.conf b/conf/nginx.conf index 48d6dd4..a4c1cc0 100644 --- a/conf/nginx.conf +++ b/conf/nginx.conf @@ -202,10 +202,10 @@ http { proxy_read_timeout 600s; } - # ---- API 代理出口:`/apix/?<参数>` → 外部 API 市场 ---- + # ---- API 代理出口:`/apix/?<参数>` → 外部 API 供应商 ---- # # 与 LLM 代理同一把 `sk_` Key、同一份限流与用量统计,差别在上游形态: - # 市场只有一个收口 `POST /api/v1/ai/request`,资产由**请求体里的 asset_id** + # 供应商只有一个收口 `POST /api/v1/ai/request`,资产由**请求体里的 asset_id** # 决定。所以这里不能像 LLM 那样原样透传请求体——网关必须自己拼, # 否则「只暴露免费资产」这条管理策略形同虚设(调用方自己挑最贵的刷)。 # @@ -222,7 +222,7 @@ http { # 与 LLM 同一套出站头策略:默认不放行 + 显式放行。 # 抹掉 x-api-key 尤其重要——那是**调用方的网关 Key**, - # 原样带出去等于把网关的身份送给市场。 + # 原样带出去等于把网关的身份送给供应商。 proxy_pass_request_headers off; proxy_set_header x-api-key ""; proxy_set_header api-key ""; @@ -230,7 +230,7 @@ http { # 变量形式不会推导 Host,必须显式设 proxy_set_header Host $apix_host; - # 换上平台真 Key。下行那把 sk_ 到此为止 + # 换上供应商真 Key。下行那把 sk_ 到此为止 proxy_set_header X-API-Key $apix_key; proxy_set_header Content-Type application/json; proxy_set_header Accept application/json; @@ -247,7 +247,7 @@ http { } location = /apix_error { default_type application/json; - return 502 '{"code":502,"msg":"API 市场不可达,请稍后重试或联系管理员"}'; + return 502 '{"code":502,"msg":"API 供应商不可达,请稍后重试或联系管理员"}'; } # 只改写「连不上上游」这类由 nginx 自己产生的错误。 @@ -307,9 +307,9 @@ http { } # —— API 代理连通性/余额探测(管理台「测试」按钮)—— - # /api/admin/apix/test 校验 slug 后内部重定向到这里。走市场的**免费** - # 预估接口,不执行资产、不扣费,响应里带平台余额 current_balance_usd。 - # internal 挡住外部直连——这是绕过 ukey 鉴权直接花市场钱的口子。 + # /api/admin/apix/test 校验 slug 后内部重定向到这里。走供应商的**免费** + # 预估接口,不执行资产、不扣费,响应里带供应商余额 current_balance_usd。 + # internal 挡住外部直连——这是绕过 ukey 鉴权直接花供应商钱的口子。 location /_apix_probe/ { internal; proxy_pass $apix_probe_target; diff --git a/readme.md b/readme.md index fb86946..65923b3 100755 --- a/readme.md +++ b/readme.md @@ -965,30 +965,30 @@ curl -s -H "X-API-Key: $KEY" "$API/api/v1/usage" --- -## 15.1 API 代理(外部 API 市场) +## 15.1 API 代理(外部 API 供应商) -把外部 API 市场(默认 `搜蚁智选 / AIMALL`,`https://souyi.net.cn`)的资产挂到网关下, +把外部 API 供应商的资产挂到网关下, 与 LLM 代理**共用同一把账号 API Key、同一份限流与用量统计**——差别只在下游形态: -市场只有一个收口 `POST /api/v1/ai/request`,资产靠**请求体里的 `asset_id`** 区分。 +供应商只有一个收口 `POST /api/v1/ai/request`,资产靠**请求体里的 `asset_id`** 区分。 ```text GET /apix/search?q=nginx Authorization: Bearer sk_<本网关签发> → access 阶段 ApiProxyHandler(ipass_apix 开关) ① 取 URL 第一段 → slug = search ② 查 ukey: → 身份 + 配额(与 LLM 同一套) - ③ 查 ax: → base + 平台 Key + asset_id(纯内存) + ③ 查 ax: → base + 供应商 Key + asset_id(纯内存) ④ 放行;GET 被改写成 POST:proxy_method + proxy_set_body $apix_body - $apix_body 由网关**从 query 拼**(见下);$apix_key 换上平台 Key - → 转发到市场(下游 sk_ 到此为止,绝不带出去) + $apix_body 由网关**从 query 拼**(见下);$apix_key 换上供应商 Key + → 转发到供应商(下游 sk_ 到此为止,绝不带出去) ``` -**为什么请求体必须由网关拼**:市场只认一个收口 URL,资产全靠 body 里的 `asset_id` 区分。 +**为什么请求体必须由网关拼**:供应商只认一个收口 URL,资产全靠 body 里的 `asset_id` 区分。 如果让客户端自己带 `asset_id`,管理员就失去「只暴露免费资产」的控制力。所以 **资产选择权留在服务端**:`slug → asset_id` 由管理员在「API 代理」页配置,调用方只能决定 query 参数。 **调用方式**:`/apix/?<参数>=<值>`。参数只能走 query string——转发决策在 access 阶段, -那时请求体还读不到。网关把全部 query 参数原样塞进 `call_data`(`prompt` 提到顶层,市场模型类资产用它当必填), -再 `proxy_method POST` + `proxy_set_body` 转成带体请求。例如 `GET /apix/search?q=nginx` 会向市场发: +那时请求体还读不到。网关把全部 query 参数原样塞进 `call_data`(`prompt` 提到顶层,供应商模型类资产用它当必填), +再 `proxy_method POST` + `proxy_set_body` 转成带体请求。例如 `GET /apix/search?q=nginx` 会向供应商发: ```json {"asset_id":"searxng-search","call_data":{"q":"nginx"}} @@ -996,45 +996,44 @@ GET /apix/search?q=nginx Authorization: Bearer sk_<本网关签 **管理台「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` 带回来。 +- **代理列表**:每个代理自带该供应商的 `基址 / 供应商 Key / asset_id`,由管理员在「新建 / 编辑」 + 弹出卡片里填写。供应商只是被代理方之一,**没有「平台级」凭据面板**。真 Key 只落在 + `data/api-proxies.json`,列表只显示掩码 `ak_***`。 +- 每个代理给复制调用地址 / 测试 / 编辑 / 启停 / 删除。停用立刻对调用方表现为 404 + (共享内存已摘除,无回源兜底)。「测试」走该供应商的**免费**预估接口 `/api/v1/ai/estimate`, + 不执行资产、不扣费,顺带把供应商余额 `current_balance_usd` 带回来。 **接口** | 方法 | 路径 | 说明 | | --- | --- | --- | -| `GET` | `/apix/?<参数>` | 账号态:转发到市场对应资产 | +| `GET` | `/apix/?<参数>` | 账号态:转发到供应商对应资产 | | `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/`,`internal` 挡外部直连) | **硬约束** -- `apix.rs` 与 `llm.rs` 共用下游 `sk_` 鉴权与配额;`data/api-proxies.json` 含平台真 Key, +- `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:`,value = `base\n平台Key\nasset_id`。写操作必须走 `apix::sync_shm` + 再显式放行 `Host` / `X-API-Key`(=供应商 Key)/ `Content-Type`。**抹空三条是堵漏关键**, + 漏 `Content-Type` 会令供应商侧解析失败。 +- shm 键 `ax:`,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/?<参数>` → 市场 `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}`; +- **2026-09-13(续7)新增「API 代理」板块:把外部免费 API 供应商挂到网关下(`ipass-1.0.9`)** + - 新增 `rust/src/apix.rs` + 模块:`/apix/?<参数>` → 供应商 `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/`(`internal`)。 - - 管理台 `apix.html` + `assets/apix.js`:市场凭据配置、目录直拉、代理增删启停、复制地址、免费预估测试。 + - 管理台 `apix.html` + `assets/apix.js`:每条代理自带供应商凭据、增删启停、复制地址、免费预估测试(弹出卡片填写)。 - 计费天然并入既有体系:用量按 `api/` 归组(与 LLM 上游同片键空间),趋势 / 用量页直接出现。 - **2026-09-13(续6)管理台图表(用量/token/趋势/按人/按 API 组)+ 单页拆分多页(`ipass-1.0.8`)** diff --git a/rust/src/api.rs b/rust/src/api.rs index 78ed79c..6bf7f50 100644 --- a/rust/src/api.rs +++ b/rust/src/api.rs @@ -94,8 +94,6 @@ fn route(method: &str, uri: &str) -> Option<(Guard, Handler)> { ("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), @@ -682,14 +680,13 @@ fn h_admin_trend(r: *mut ngx_http_request_t, _actor: Actor) -> Status { // API 代理管理 // =========================================================================== -/// 管理员: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(), }), @@ -727,6 +724,9 @@ fn h_admin_apix_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status { match apix::upsert( &slug, &asset, + p.get("base"), + p.get("key"), + p.get("supplier"), p.get("name"), p.get("desc"), params, @@ -753,45 +753,9 @@ fn h_admin_apix_delete(r: *mut ngx_http_request_t, _actor: Actor) -> Status { } } -/// 管理员:设置市场基址与平台 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::().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 是否可用(管理台「测试」按钮)。 +/// 管理员:探测供应商 Key 是否可用(管理台「测试」按钮)。 /// -/// 走市场的**免费预估**接口(`/api/v1/ai/estimate`):它不执行资产、不扣费, +/// 走供应商的**免费预估**接口(`/api/v1/ai/estimate`):它不执行资产、不扣费, /// 响应里还带 `current_balance_usd` —— 一次调用同时拿到「Key 通不通」和 /// 「还剩多少钱」。实现上内部重定向到管理 server 的 `/_apix_probe/`, /// 复用 `$apix_probe_*` 变量(拼体、换 Key 与真实转发同一套逻辑)。 diff --git a/rust/src/apix.rs b/rust/src/apix.rs index 73d819c..fe8b674 100644 --- a/rust/src/apix.rs +++ b/rust/src/apix.rs @@ -1,17 +1,17 @@ -//! API 代理:把外部 API 市场(aimall / 搜蚁智选)的资产挂到网关下。 +//! API 代理:把外部供应商的 API 资产挂到网关下。 //! //! 与 LLM 代理(`llm.rs`)是**同一套下行契约**——都认 `sk_` 那把 Key、都吃 //! 同一份限流配额、都进同一套用量统计——差别只在上游形态: //! //! | | LLM 代理 | API 代理 | //! | --- | --- | --- | -//! | 上游 | N 家厂商,各有基址与密钥 | 一个市场,共用基址与平台 Key | +//! | 上游 | N 家厂商,各有基址与密钥 | 每条记录自带基址与供应商 Key | //! | URL 第一段 | `slot` → `up:` 里的 `base \n auth` | `slug` → `ax:` 里的 `base \n key \n asset_id` | //! | 请求体 | 客户端原样带过来 | **由网关从 query 拼**(见下) | //! //! ## 为什么请求体必须由网关拼 //! -//! 市场侧只有一个收口 `POST /api/v1/ai/request`,资产靠**请求体里的 +//! 供应商侧只有一个收口 `POST /api/v1/ai/request`,资产靠**请求体里的 //! `asset_id`** 区分。如果让客户端自己带 `asset_id`,管理员就失去了 //! 「只暴露免费资产」的控制力——任何人都能拿网关的 Key 去刷最贵的那个模型。 //! 所以资产选择权留在服务端:`slug → asset_id` 由管理员配置, @@ -22,7 +22,7 @@ //! `proxy_method POST` + `proxy_set_body $apix_body` 把 GET 变成 //! 带体的 POST,网关不需要自己实现 upstream。 //! -//! `data/api-proxies.json` 含平台真 Key,**敏感级别等同 `users.json`**。 +//! `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}; @@ -43,7 +43,7 @@ use crate::util; pub const VAR_TARGET: usize = 1; /// `$apix_host`:上游 Host 头 pub const VAR_HOST: usize = 2; -/// `$apix_key`:平台 API Key(下行那把 `sk_` 到此为止,不往上游传) +/// `$apix_key`:供应商 API Key(下行那把 `sk_` 到此为止,不往上游传) pub const VAR_KEY: usize = 3; /// `$apix_body`:由 query 拼出的调用体 pub const VAR_BODY: usize = 4; @@ -51,7 +51,7 @@ pub const VAR_BODY: usize = 4; pub const VAR_PROBE_TARGET: usize = 5; pub const VAR_PROBE_BODY: usize = 6; -/// shm payload 内部分隔符:base / 平台 Key / asset_id 之间。 +/// shm payload 内部分隔符:base / 供应商 Key / asset_id 之间。 /// /// base 是 URL、key 与 asset_id 都是 token 类字符串,都不可能含换行。 pub const PAYLOAD_SEP: char = '\n'; @@ -85,7 +85,7 @@ pub fn validate_slug(raw: &str) -> Result { Ok(s) } -/// 市场基址:`http(s)://host`,允许尾随路径(市场挂在子路径下的情况)。 +/// 供应商基址:`http(s)://host`,允许尾随路径(供应商挂在子路径下的情况)。 pub fn validate_base(raw: &str) -> Result { let s = util::trim(raw).trim_end_matches('/').to_owned(); if s.is_empty() { @@ -99,7 +99,7 @@ pub fn validate_base(raw: &str) -> Result { } else if let Some(r) = s.strip_prefix("http://") { r } else { - return Err("base 必须以 http:// 或 https:// 开头,例如 https://souyi.net.cn".to_owned()); + return Err("base 必须以 http:// 或 https:// 开头,例如 https://api.example.com".to_owned()); }; if rest.is_empty() || rest.split('/').next().unwrap_or("").is_empty() { return Err("base 缺少主机名".to_owned()); @@ -110,7 +110,7 @@ pub fn validate_base(raw: &str) -> Result { Ok(s) } -/// asset_id:市场那边的资产标识。宽进——各市场的命名规则不同, +/// asset_id:供应商那边的资产标识。宽进——各供应商的命名规则不同, /// 这里只挡空白与控制字符(它要出现在 JSON 与 HTML 里)。 fn validate_asset(raw: &str) -> Result { let s = util::trim(raw).to_owned(); @@ -153,8 +153,8 @@ fn check_params(raw: &[String]) -> Result, String> { // 共享内存同步(写穿 / 装载) // =========================================================================== -fn payload_of(base: &str, key: &str, item: &ApiProxy) -> String { - format!("{base}{PAYLOAD_SEP}{key}{PAYLOAD_SEP}{}", item.asset_id) +fn payload_of(item: &ApiProxy) -> String { + format!("{}{PAYLOAD_SEP}{}{PAYLOAD_SEP}{}", item.base, item.key, item.asset_id) } /// 拆 payload:`base \n key \n asset_id` @@ -179,7 +179,7 @@ pub fn sync_shm(slug: &str, store: &ApiProxyStore) { state::remove(config::KEY_AX_PREFIX, slug.as_bytes()); return; } - let payload = payload_of(&store.base, &store.key, item); + let payload = payload_of(item); if !state::put(config::KEY_AX_PREFIX, slug.as_bytes(), payload.as_bytes(), 0) { util::log_err(&format!( "[apix] 代理配置写共享内存失败 slug={slug} —— 该代理会 404(共享内存可能已满)" @@ -187,7 +187,7 @@ pub fn sync_shm(slug: &str, store: &ApiProxyStore) { } } -/// 全量重载代理表(启动装载 / 平台凭据变更后)。返回装载条数。 +/// 全量重载代理表(启动装载 / 供应商凭据变更后)。返回装载条数。 pub fn reload_shm() -> usize { state::clear_prefix(config::KEY_AX_PREFIX); let data = store::read_api_proxies(); @@ -198,7 +198,7 @@ pub fn reload_shm() -> usize { continue; } expected += 1; - let payload = payload_of(&data.base, &data.key, item); + let payload = payload_of(item); if state::put(config::KEY_AX_PREFIX, slug.as_bytes(), payload.as_bytes(), 0) { loaded += 1; } @@ -211,7 +211,7 @@ pub fn reload_shm() -> usize { loaded } -/// 热路径查表:`slug → (base, 平台Key, asset_id)` +/// 热路径查表:`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); @@ -241,7 +241,7 @@ pub fn slug_of(r: *mut ngx_http_request_t) -> Option { Some(slug.to_ascii_lowercase()) } -/// 从 `https://souyi.net.cn:443` 取出 `souyi.net.cn:443` +/// 从 `https://api.example.com:443` 取出 `api.example.com:443` fn host_of(base: &str) -> &str { let rest = match base.find("://") { Some(i) => &base[i + 3..], @@ -290,14 +290,14 @@ fn clip(v: &str) -> &str { &v[..end] } -/// 由 query 拼出市场的调用体。 +/// 由 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 等)把它当必填字段, +/// `prompt` 单独提到顶层:供应商的 model 类资产(MiniMax-M3 等)把它当必填字段, /// 塞进 `call_data` 会被当成未知参数。其余参数一律进 `call_data`。 pub fn build_body(asset_id: &str, args: &[(String, String)]) -> String { let mut call = String::new(); @@ -386,7 +386,7 @@ pub extern "C" fn var_get( VAR_BODY => build_body_from_request(r, &asset), VAR_PROBE_BODY => { // 预估是**免费**的,且不真正执行资产——用它当连通性探针, - // 响应里的 current_balance_usd 顺带把平台余额带回来 + // 响应里的 current_balance_usd 顺带把供应商余额带回来 format!("{{\"asset_id\":{},\"max_tokens\":1}}", json_quote(&asset)) } _ => return None, @@ -415,26 +415,25 @@ pub fn all() -> Vec<(String, ApiProxy)> { .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 +/// 客户端应当使用的调用地址(base,不带 query)。端口由调用方从请求 Host 头取, +/// **不要写死**(部署在 88 时要带 `:88`,放在 443 反代后面时不能带)。 +/// query 参数由前端按 `params` 拼一次(避免后端与前端各拼一次导致 `?q=?q=`)。 +pub fn call_url(slug: &str, port: &str) -> String { + format!("https://{}{port}{PUB_PREFIX}{slug}", config::LLM_PUBLIC_HOST) } /// 新增或覆盖一个代理条目。 /// /// `params = None` 表示保持原值(只改名字时不必回填参数清单)。 +/// `base` / `key` / `supplier` 同理:`None` 或空串都表示「保留原值」—— +/// 这样编辑时不必把密钥再抄一遍。新建时若填了空串仍为空,则报错 +/// (没有基址与密钥无法转发)。 pub fn upsert( slug_raw: &str, asset_raw: &str, + base_raw: Option<&String>, + key_raw: Option<&String>, + supplier_raw: Option<&String>, name: Option<&String>, desc: Option<&String>, params: Option>, @@ -448,9 +447,45 @@ pub fn upsert( None => None, }; + // base / key:空串视为「保留原值」,交给下方闭包按 existing 决定 + let new_base = match base_raw { + Some(b) => { + let b = util::trim(b); + if b.is_empty() { None } else { Some(validate_base(&b)?) } + } + None => None, + }; + let new_key = match key_raw { + Some(k) => { + let k = util::trim(k).to_owned(); + if k.is_empty() { + None + } else { + if k.chars().count() > config::APIX_KEY_MAX_LEN { + return Err(format!("供应商 Key 超过 {} 个字符", config::APIX_KEY_MAX_LEN)); + } + Some(k) + } + } + None => None, + }; + let key = slug.clone(); let (item, snapshot) = store::update_api_proxies(move |data| { let existing = data.items.get(&key).cloned(); + let base = new_base + .or_else(|| existing.as_ref().map(|e| e.base.clone())) + .unwrap_or_default(); + let key_val = new_key + .or_else(|| existing.as_ref().map(|e| e.key.clone())) + .unwrap_or_default(); + if existing.is_none() && (base.is_empty() || key_val.is_empty()) { + return Err("新建代理必须提供供应商基址与密钥".to_owned()); + } + let supplier = match supplier_raw { + Some(s) => util::trim(s).chars().take(config::APIX_NAME_MAX_LEN).collect(), + None => existing.as_ref().map(|e| e.supplier.clone()).unwrap_or_default(), + }; 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(), @@ -473,7 +508,7 @@ pub fn upsert( .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 }; + let item = ApiProxy { asset_id, supplier, base, key: key_val, name, desc, params, enabled, note, created_at }; data.items.insert(key.clone(), item.clone()); Ok((item, data.clone())) })?; @@ -482,22 +517,6 @@ pub fn upsert( 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 { let slug = validate_slug(slug_raw)?; let key = slug.clone(); @@ -511,88 +530,34 @@ pub fn remove(slug_raw: &str) -> Result { 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 { - 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 里。 +/// **绝不回显完整供应商 Key**——与 `upstreams::view` 同一理由:管理台页面会被 +/// 截图、被浏览器插件读取,回显真 Key 等于把供应商余额摆在一个 HTML 里。 +/// `url` 只给 base 路径,query 参数由前端按 `params` 拼一次。 pub fn view(slug: &str, item: &ApiProxy, port: &str) -> Value { json!({ "slug": slug, "asset_id": item.asset_id, + "supplier": item.supplier, + "base": item.base, "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, + "key_set": !item.key.is_empty(), + "key_mask": if item.key.is_empty() { "-".to_owned() } else { util::mask_key(&item.key) }, "note": item.note, "created_at": item.created_at, "created_at_text": util::fmt_time(item.created_at), - "url": call_url(slug, &item.params, port), + "url": call_url(slug, port), }) } pub fn view_all(list: &[(String, ApiProxy)], port: &str) -> Vec { 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), - }) -} diff --git a/rust/src/config.rs b/rust/src/config.rs index 9b662be..b7c4946 100644 --- a/rust/src/config.rs +++ b/rust/src/config.rs @@ -152,30 +152,29 @@ pub const TREND_DAYS_MAX: i64 = 90; pub const KEY_UH_PREFIX: &[u8] = b"uh:"; // --------------------------------------------------------------------------- -// API 代理(apix):把外部 API 市场(aimall / 搜蚁智选)的资产挂到网关下 +// API 代理(apix):把外部供应商的 API 资产挂到网关下 // --------------------------------------------------------------------------- // // 与 LLM 代理的关系:同一把 `sk_` 下行 Key、同一套限流与统计, -// 但上游是「一个市场 + N 个资产」而不是「N 家厂商」,所以 slug 只映射到 -// `asset_id`,基址与平台 Key 是全局一份(见 `models::ApiProxyStore`)。 +// 但每条 apix 记录自带「基址 + 供应商 Key + 资产 id」——不同供应商互不影响 +// (见 `models::ApiProxyStore`),所以 slug 只映射到 `asset_id`。 -/// shm 键前缀:slug → `base \n 平台Key \n asset_id`。 +/// 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":{..}}`) +/// 供应商「调用资产」路径(`POST {base}{path}`,body = `{"asset_id":..,"call_data":{..}}`)。 +/// 每条 apix 记录都按这个路径转发——它定义了该供应商接口所遵循的协议。 pub const APIX_REQUEST_PATH: &str = "/api/v1/ai/request"; -/// 市场「费用预估」路径。**免费**,且响应里带平台余额——管理台的 -/// 「测试」按钮走它:既能验 Key 通不通,又能看到还剩多少钱,不花一分钱。 +/// 供应商「费用预估」路径。**免费**,且响应里带余额——管理台的 +/// 「测试」按钮走它:既能验 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; @@ -188,7 +187,7 @@ pub const APIX_PARAM_MAX: usize = 16; pub const APIX_ARG_MAX: usize = 32; /// 单个参数值长度上限(bytes) pub const APIX_VAL_MAX: usize = 4096; -/// 平台 Key 长度上限 +/// 供应商 Key 长度上限 pub const APIX_KEY_MAX_LEN: usize = 128; /// 用量统计里 API 代理的 slot 前缀。 /// diff --git a/rust/src/lib.rs b/rust/src/lib.rs index e589022..4d32c17 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -20,7 +20,7 @@ //! | --- | --- | --- | --- | //! | `*.yourdomain.com/*` | access | `ipass_proxy` | 查 `sub:` 决定后端 | //! | `llm.yourdomain.com//*` | access | `ipass_llm` | 查 `ukey:` 鉴权 + `up:` 定上游 | -//! | `llm.yourdomain.com/apix/` | access | `ipass_apix` | 同上鉴权,查 `ax:` 定市场资产 | +//! | `llm.yourdomain.com/apix/` | access | `ipass_apix` | 同上鉴权,查 `ax:` 定供应商资产 | //! | `proxy-api.yourdomain.com/api/*` | content | `ipass_api` | 管理接口,读体后分发 | //! //! ## 关键实现约束(均为实测/查证确认,详见 CLAUDE.md) @@ -360,7 +360,7 @@ impl HttpRequestHandler for ApiProxyHandler { // 代理的**可见性**由管理员的启用/停用决定,不再叠一层账号白名单: // 白名单是给「一家厂商一个 slot」设计的,这里再套一层会让 // 「管理员明明启用了、某账号却 403」变得难以解释。 - let Some((_base, platform_key, _asset)) = apix::lookup(&slug) else { + let Some((_base, supplier_key, _asset)) = apix::lookup(&slug) else { return http::fail( r, HTTPStatus::NOT_FOUND, @@ -368,14 +368,14 @@ impl HttpRequestHandler for ApiProxyHandler { ); }; - if platform_key.is_empty() { + if supplier_key.is_empty() { util::log_err(&format!( - "[apix] 平台 Key 未配置,slug={slug} 无法转发 —— 请到管理台「API 代理」填写" + "[apix] 供应商 Key 未配置,slug={slug} 无法转发 —— 请到管理台「API 代理」填写" )); return http::fail( r, HTTPStatus::SERVICE_UNAVAILABLE, - "平台 API Key 未配置,请联系管理员", + "供应商 API Key 未配置,请联系管理员", ); } @@ -567,7 +567,7 @@ struct ModuleConfig { api: bool, /// 该 location 走 LLM 代理(`//...` → 上游) llm: bool, - /// 该 location 走 API 代理(`/apix/` → 外部市场) + /// 该 location 走 API 代理(`/apix/` → 外部供应商) apix: bool, } diff --git a/rust/src/models.rs b/rust/src/models.rs index c551f1e..712f4a9 100644 --- a/rust/src/models.rs +++ b/rust/src/models.rs @@ -106,42 +106,41 @@ fn default_llm_daily() -> i64 { crate::config::LLM_DAILY_DEFAULT } -/// API 代理表(`api-proxies.json`):**一个文件同时承载平台凭据与代理清单**。 +/// API 代理表(`api-proxies.json`)。 /// -/// 与 `llm-upstreams.json` 的区别:上游表是「一条记录 = 一家厂商(自带基址与 -/// 密钥)」,而 API 代理面对的是**同一个市场**(aimall / 搜蚁智选)—— -/// 所有资产共用一个基址、一把平台 Key,只有 `asset_id` 不同。 -/// 所以凭据放在文件顶层(`base` + `key`),`items` 里只放资产差异。 +/// 与 `llm-upstreams.json` 同构:每条记录 = 一个供应商(自带基址与密钥), +/// 由 `slug` 区分。调用方访问 `/apix/?参数=值`,网关用本记录里的密钥 +/// 转发到供应商、并把响应原样返回。不同供应商彼此独立、互不耦合。 /// -/// `key` 是平台真 Key,**敏感级别等同 `users.json`**(data/ 已 gitignore)。 +/// `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 → 资产映射 + /// slug → 代理映射 #[serde(default)] pub items: BTreeMap, } impl Default for ApiProxyStore { fn default() -> Self { - Self { base: default_apix_base(), key: String::new(), items: BTreeMap::new() } + Self { items: BTreeMap::new() } } } -fn default_apix_base() -> String { - crate::config::APIX_BASE_DEFAULT.to_owned() -} - -/// 单个 API 代理条目。 +/// 单个 API 代理条目:指向某一家供应商的一个可调用的资产。 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ApiProxy { - /// 市场侧的资产 id(如 `searxng-search`),决定钱花在哪个资产上 + /// 供应商侧的资产 id(如 `searxng-search`),决定具体调用哪个资产 pub asset_id: String, + /// 供应商名称(仅展示用,管理员自填,例如 `provider-x` / 客户自定) + #[serde(default)] + pub supplier: String, + /// 供应商基址,如 `https://api.example.com` + #[serde(default)] + pub base: String, + /// 供应商 API Key(`ak_...`)。留空 = 未配置,热路径直接 503。 + /// **敏感**:写盘与回显都按密钥处理,管理台只回显掩码。 + #[serde(default)] + pub key: String, /// 展示名(中文) #[serde(default)] pub name: String, @@ -152,18 +151,11 @@ pub struct ApiProxy { /// /// 只用于给调用方看的文档(管理台把 `?q=关键词` 拼出来、账号态接口回显), /// 转发时**不按它过滤**——过滤要靠读请求体,而 access 阶段读不到。 - /// 市场侧自己会拒绝不认识的参数,拦在网关意义不大。 + /// 供应商侧自己会拒绝不认识的参数,拦在网关意义不大。 #[serde(default)] pub params: Vec, #[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)] diff --git a/rust/src/store.rs b/rust/src/store.rs index 52dcfba..5f079a5 100644 --- a/rust/src/store.rs +++ b/rust/src/store.rs @@ -19,7 +19,7 @@ //! | `users.json` | 账号、口令哈希、API Key | `ukey:` 索引进(热路径要它) | //! | `domains.json` | 子域名 → 后端映射 | `sub:` 进(转发热路径) | //! | `llm-upstreams.json` | LLM 上游基址与密钥 | `up:` 进(LLM 转发热路径) | -//! | `api-proxies.json` | API 市场凭据 + 代理清单 | `ax:` 进(API 代理热路径) | +//! | `api-proxies.json` | API 代理清单(每条含各自供应商凭据) | `ax:` 进(API 代理热路径) | //! //! 四个文件都在 `data/` 下,都已 `.gitignore`。**LLM 上游表含上游真 Key, //! 敏感级别与 `users.json` 相同**,不要再往别处复制。 diff --git a/tests/llm/e2e.sh b/tests/llm/e2e.sh index 036fe57..a18e7ef 100755 --- a/tests/llm/e2e.sh +++ b/tests/llm/e2e.sh @@ -327,8 +327,8 @@ ck "★内部 location 外部直连 → 404(不能绕过 admin 会话触达上 "$(code -b "$JAR" -X POST "$API/_upstream_test/openai/v1/chat/completions" -d '{}')" echo -echo "【11.5】★ API 代理(/apix/ → 外部 API 市场)" -# 与 LLM 代理同一把 sk_ Key,但上游形态不同:市场只有一个收口,资产由 +echo "【11.5】★ API 代理(/apix/ → 外部供应商)" +# 与 LLM 代理同一把 sk_ Key,但上游形态不同:供应商只有一个收口,资产由 # **请求体里的 asset_id** 决定,所以请求体必须由网关拼——判据是看靶机 # 收到的 path / 头 / body 三件事,只看网关自己的 200 什么都证明不了。 ck "无 Key → 401" 401 "$(code "$GW/apix/search?q=hello")" @@ -336,27 +336,37 @@ ck "坏 Key → 401" 401 "$(code -H 'X-API-Key: sk_nope' "$GW/apix/search?q=hell 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 " 靶机 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 " ★换上了供应商真 Key" "ak_test_supplier_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 换来市场凭据,而不是凭据被原样透传。 +# 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 " ★条目 Key 只回显掩码(不回显真值)" no \ + "$(curl -s -b "$JAR" $API/api/admin/apix | has 'ak_test_supplier_key')" +ck " 条目 base 回显" "http://127.0.0.1:18999" \ + "$(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"] == "search"), None) +print(it.get("base") if it else "miss")')" +ck " 供应商名回显" "vendor-a" \ + "$(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"] == "search"), None) +print(it.get("supplier") if it else "miss")')" ck " 已停用条目 enabled=false" "False" "$(curl -s -b "$JAR" $API/api/admin/apix | "$PY" -c ' import sys, json d = json.load(sys.stdin)["data"] @@ -370,7 +380,7 @@ ck "非法 slug → 400" 400 "$(code -b "$JAR" -X POST $API/api/admin/apix/save 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)")" + -H 'Content-Type: application/json' -d "$(jbody slug med asset_id asset_26476ef1-4687-45 name 疾病百科 params kw base http://127.0.0.1:18999 key ak_test_supplier_key supplier vendor-a)")" 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)" @@ -387,11 +397,11 @@ curl -s -b "$JAR" -X POST $API/api/admin/apix/delete -H 'Content-Type: applicati -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 " 探测也换了供应商真 Key" "ak_test_supplier_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 \ diff --git a/tests/llm/fixtures/api-proxies.json b/tests/llm/fixtures/api-proxies.json index 8899367..59c3871 100644 --- a/tests/llm/fixtures/api-proxies.json +++ b/tests/llm/fixtures/api-proxies.json @@ -1,9 +1,10 @@ { - "base": "http://127.0.0.1:18999", - "key": "ak_test_platform_key", "items": { "search": { + "supplier": "vendor-a", "asset_id": "searxng-search", + "base": "http://127.0.0.1:18999", + "key": "ak_test_supplier_key", "name": "SearXNG 免费搜索", "desc": "服务端聚合 Google / Brave / Bing", "params": ["q"], @@ -11,7 +12,10 @@ "created_at": 1750000000 }, "offline": { + "supplier": "vendor-a", "asset_id": "disabled-asset", + "base": "http://127.0.0.1:18999", + "key": "ak_test_supplier_key", "name": "已停用的代理", "desc": "enabled=false,热路径必须查不到", "params": [], diff --git a/www/apix.html b/www/apix.html index 600459b..1a2276a 100644 --- a/www/apix.html +++ b/www/apix.html @@ -12,64 +12,20 @@
-

API 市场凭据

-
- 把外部 API 市场(默认 搜蚁智选 / AIMALL)挂到网关下:调用方用同一把账号 API Key, - 访问 /apix/<代理名>?参数=值,网关换成平台 Key 后转发到市场,并返回市场原样结果。 - 资产由本页面的配置决定(不是调用方在请求里指定),所以管理员能控制"只暴露哪些、不暴露哪些"。 -
-
-
-
-
-
-
-
- -
-

新建 / 更新代理

-
- slug 是对外的名字(/apix/slug),asset_id 是市场内部的资产标识。 - 参数只能走 query string(转发决策在 access 阶段,那时读不到请求体), - 声明的参数名只用于生成示例地址,实际转发会把全部 query 参数原样带过去。 -
-
-
-
-
-
-
-
-
-
- -
-

市场资产目录 (点「接入」自动填表)

-
- 直接从市场拉取公开目录(GET /api/v1/assets,匿名可读、已开放跨域), - 价格是市场侧的实时数字。免费的资产接入后不消耗余额,计费资产请先看自己的余额再开放。 -
-
- - +
+
+

代理列表

+
+ 把外部供应商的 API 挂到网关下:调用方用同一把账号 API Key 访问 + /apix/<slug>?参数=值,网关换成该代理自身登记的供应商 Key后转发,并返回供应商原样结果。 + 每家供应商的基址与 Key 都在每一条代理里单独填写,互不影响。停用的代理对调用方表现为 404(共享内存已摘除,立即生效)。 +
+
+
- - - -
asset_id名称 / 说明类型单价30 天成功率操作
点「刷新目录」拉取
-
- -
-

代理列表

-
- 停用的代理对调用方表现为 404(共享内存里已摘除,立即生效)。 - 「测试」走市场的免费预估接口,不执行资产、不扣费,顺带把平台余额带回来。 -
- - - +
slugasset_id调用地址单价状态创建时间操作slugasset_id调用地址供应商状态创建时间操作
diff --git a/www/assets/admin.css b/www/assets/admin.css index 44bfa18..9b82e90 100644 --- a/www/assets/admin.css +++ b/www/assets/admin.css @@ -165,3 +165,21 @@ button.host-copy:hover{text-decoration:underline solid} #toast.show{opacity:1;transform:translateX(-50%) translateY(0)} #toast.err{background:#b91c1c} .err-msg{color:var(--err-fg);font-size:12.5px;margin-top:10px;min-height:18px} + +/* ---------- 弹窗(modal)---------- */ +/* 编辑内容较多的表单用弹窗:遮罩 + 居中卡片。层级高于顶栏(z-index:10), + 故取 80;内容高时遮罩自身可滚动(padding 顶 8vh 让卡片不贴顶)。 */ +.modal-overlay{position:fixed;inset:0;background:rgba(15,23,42,.45);z-index:80; + display:flex;align-items:flex-start;justify-content:center;padding:8vh 16px 16px;overflow:auto} +.modal-card{background:var(--panel);border:1px solid var(--border);border-radius:12px; + width:100%;max-width:660px;box-shadow:0 18px 50px rgba(15,23,42,.22)} +.modal-head{display:flex;align-items:center;justify-content:space-between; + padding:15px 20px;border-bottom:1px solid var(--border)} +.modal-head h3{margin:0;font-size:15px} +.modal-close{border:0;background:none;font-size:22px;line-height:1;color:var(--muted);cursor:pointer;padding:0 4px} +.modal-close:hover{color:var(--text)} +.modal-body{padding:18px 20px} +.modal-foot{display:flex;justify-content:flex-end;gap:10px;padding:14px 20px;border-top:1px solid var(--border)} +/* 弹窗内表单同样限宽两列,窄屏单列;spa-all 跨整行由通用 .grid-form 规则保证 */ +.modal-body .grid-form.up-form{grid-template-columns:repeat(2,1fr)} +@media (max-width:600px){.modal-body .grid-form.up-form{grid-template-columns:1fr}} diff --git a/www/assets/apix.js b/www/assets/apix.js index 68fad59..83830f7 100644 --- a/www/assets/apix.js +++ b/www/assets/apix.js @@ -1,31 +1,65 @@ -/* API 代理:市场凭据 + 资产目录接入 + 代理列表(复制地址、测试、启停、删除)*/ +/* 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 '免费'; + // 弹窗里的表单:it 存在 = 编辑(slug 只读、Key 留空表示不改),否则 = 新建 + function formHtml(it) { + var edit = !!(it && it.slug); + return '' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
'; + } + + function openForm(it) { + IP.modal({ + title: it && it.slug ? "编辑 API 代理" : "新建 API 代理", + submitText: "保存代理", + html: formHtml(it), + onMount: function (card, close) { + var form = card.querySelector("#apixForm"); + form.addEventListener("submit", function (e) { + e.preventDefault(); + IP.api("POST", "/api/admin/apix/save", { + slug: card.querySelector("#axSlug").value.trim(), + asset_id: card.querySelector("#axAsset").value.trim(), + name: card.querySelector("#axName").value.trim(), + supplier: card.querySelector("#axSupplier").value.trim(), + base: card.querySelector("#axBase").value.trim(), + key: card.querySelector("#axKey").value.trim(), + desc: card.querySelector("#axDesc").value.trim(), + params: card.querySelector("#axParams").value.trim(), + enabled: card.querySelector("#axEnabled").checked + }).then(function (r) { IP.toast(r.msg); close(); return IP.reload(); }) + .catch(function (err) { IP.toast(err.message, true); }); + }); + } + }); } function render(s) { - var pf = s.apix.platform || {}; - var st = $("pfState"); - if (st) { - st.innerHTML = "当前基址 " + IP.esc(pf.base || "-") + " · 平台 Key " + - (pf.key_set - ? "" + IP.esc(pf.key_mask) + "" - : "未配置(代理会返回 503)"); - } - var body = $("apixBody"); if (!s.apix.items.length) { - body.innerHTML = '还没有配置任何 API 代理 —— 可以先在上方「刷新目录」挑一个免费资产接入'; + body.innerHTML = '还没有配置任何 API 代理 —— 点右上角「+ 新建代理」添加一条'; return; } @@ -36,7 +70,14 @@ : ""; var params = IP.arr(it.params); + // 后端 it.url 现在是纯基址(不再带 ?q=);参数只拼一次,避免 ?q=?q= 的重复 var url = it.url + (params.length ? "?" + params.map(function (p) { return p + "="; }).join("&") : ""); + var example = params.length ? it.url + "?" + params[0] + "=关键词" : it.url; + + var supplier = (it.supplier || "-") + " · " + + (it.key_set + ? "" + IP.esc(it.key_mask) + "" + : "未配置 Key"); return "" + "" + IP.esc(it.slug) + "" + @@ -47,9 +88,9 @@ "" + IP.esc(url) + "" + "
" + "" + - (params.length ? "" : "") + + "" + "
" + - "" + priceText(it) + "" + + "" + supplier + "" + "" + (enabled ? "启用中" : "已停用") + "" + "" + IP.esc(it.created_at_text) + "" + "
" + @@ -62,74 +103,6 @@ }).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 = '目录为空'; - 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" - : '免费'; - var rate = a.telemetry && typeof a.telemetry.success_rate_30d === "number" - ? Math.round(a.telemetry.success_rate_30d * 100) + "%" - : "-"; - return "" + - "" + IP.esc(a.asset_id) + "" + - "" + IP.esc(a.name || "-") + "" + - "
" + IP.esc(a.description || "") + "
" + - "" + IP.esc(a.api_type || "-") + "" + - "" + price + (free ? "" : "") + "" + - "" + IP.esc(rate) + "" + - "" + - ""; - }).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]"); @@ -154,7 +127,7 @@ 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 : "")); + (bal !== undefined ? " · 余额 $" + bal : "")); restore(); }) .catch(function (err) { IP.toast("✗ " + slug + ":" + err.message, true); restore(); }); @@ -174,13 +147,7 @@ } 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 + ",改完点「保存代理」"); + openForm(it2); } else if (act === "del") { if (!confirm("确认删除代理 " + slug + "?调用方将立即 404。")) return; btn.disabled = true; @@ -190,30 +157,7 @@ } }); - $("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); }); - }); + $("newApixBtn").addEventListener("click", function () { openForm(null); }); IP.boot("apix", function (s) { render(s); }); })(); diff --git a/www/assets/core.js b/www/assets/core.js index 95790af..a698025 100644 --- a/www/assets/core.js +++ b/www/assets/core.js @@ -27,7 +27,7 @@ window.IP = (function () { users: [], domains: [], upstreams: [], - apix: { platform: {}, items: [] }, + apix: { items: [] }, usage: { total: {}, tokens: {}, users: [], models: [] }, trend: null, trendDays: 14, @@ -157,7 +157,7 @@ window.IP = (function () { api("GET", "/api/admin/upstreams"), // API 代理是后加的板块,老镜像没有这两个接口——缺了不能让整个面板挂掉 api("GET", "/api/admin/apix").catch(function () { - return { data: { platform: {}, items: [] } }; + return { data: { items: [] } }; }), // 老版本后端没有用量接口时不要让整个面板挂掉 api("GET", "/api/admin/usage").catch(function () { @@ -172,7 +172,7 @@ window.IP = (function () { } state.users = arr(res[1].data.items); state.upstreams = arr(res[2].data.items); - state.apix = res[3].data || { platform: {}, items: [] }; + state.apix = res[3].data || { items: [] }; state.usage = res[4].data || { total: {}, tokens: {}, users: [], models: [] }; state.trend = res[5].data || null; syncPendingPill(); @@ -237,6 +237,58 @@ window.IP = (function () { /// 优先展示名(中文姓名),空则回落账号名 function displayName(u) { return (u && (u.name || u.display_name)) || (u && u.username) || "-"; } + // ---------------- 弹窗(modal) ---------------- + // 编辑内容较多的表单(API 代理 / LLM 上游)用弹窗操作,避免长表单把列表顶下去。 + // 用法:IP.modal({ title, submitText, html, onMount(card, close) }); + // html 里放一个
,弹窗「保存」按钮会触发该 form 的 submit(带原生 required 校验)。 + function modal(opts) { + opts = opts || {}; + var overlay = document.createElement("div"); + overlay.className = "modal-overlay"; + overlay.innerHTML = + ''; + document.body.appendChild(overlay); + + var closed = false; + function close() { + if (closed) return; + closed = true; + if (overlay.parentNode) overlay.parentNode.removeChild(overlay); + } + overlay.addEventListener("click", function (e) { if (e.target === overlay) close(); }); + overlay.querySelector(".modal-close").addEventListener("click", close); + overlay.querySelector(".modal-cancel").addEventListener("click", close); + var onKey = function (e) { + if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKey); } + }; + document.addEventListener("keydown", onKey); + + var card = overlay.querySelector(".modal-card"); + var form = card.querySelector("form"); + var okBtn = overlay.querySelector(".modal-ok"); + if (form) { + okBtn.addEventListener("click", function () { + if (form.requestSubmit) form.requestSubmit(); + else form.dispatchEvent(new Event("submit", { cancelable: true })); + }); + } else if (opts.onOk) { + okBtn.addEventListener("click", function () { opts.onOk(close); }); + } + if (opts.onMount) opts.onMount(card, close); + + var first = card.querySelector("input,textarea,select"); + if (first) first.focus(); + return close; + } + // ---------------- 启动 ---------------- /// 每页入口:先确认会话 → 装外壳 → 拉数据 → 交给页面自己的 render function boot(page, render) { @@ -255,6 +307,7 @@ window.IP = (function () { $: $, esc: esc, arr: arr, toast: toast, api: api, copyText: copyText, randDigits: randDigits, portSuffix: portSuffix, fullHost: fullHost, typeBadge: typeBadge, statusBadge: statusBadge, displayName: displayName, + modal: modal, boot: boot, loadAll: loadAll, reload: reload }; })(); diff --git a/www/assets/upstreams.js b/www/assets/upstreams.js index b0b7466..51d8397 100644 --- a/www/assets/upstreams.js +++ b/www/assets/upstreams.js @@ -1,4 +1,4 @@ -/* LLM 上游(API 组):新建/更新 + 列表(复制地址、连通性测试、启停、删除)*/ +/* LLM 上游(API 组):列表(新建/编辑弹窗、复制地址、连通性测试、启停、删除)*/ (function () { "use strict"; @@ -14,6 +14,50 @@ }; } + // 弹窗表单:up 存在 = 编辑(slot 只读、auth 留空表示不改),否则 = 新建 + function formHtml(up) { + var edit = !!(up && up.slot); + return '' + + '' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
'; + } + + function openForm(up) { + IP.modal({ + title: up && up.slot ? "编辑 LLM 上游" : "新建 LLM 上游", + submitText: "保存上游", + html: formHtml(up), + onMount: function (card, close) { + var form = card.querySelector("#upForm"); + form.addEventListener("submit", function (e) { + e.preventDefault(); + var payload = { + slot: card.querySelector("#upSlot").value.trim(), + base: card.querySelector("#upBase").value.trim(), + note: card.querySelector("#upNote").value.trim(), + // 模型清单总是显式提交:编辑框里就是"当前值",清空即清空(可预期) + models: card.querySelector("#upModels").value + }; + // 密钥留空时不传该字段:后端对「缺省」保留旧值,对「空串」是清空 + var auth = card.querySelector("#upAuth").value.trim(); + if (auth) payload.auth = auth; + IP.api("POST", "/api/admin/upstreams/save", payload) + .then(function (r) { IP.toast(r.msg); close(); return IP.reload(); }) + .catch(function (err) { IP.toast(err.message, true); }); + }); + } + }); + } + function render(s) { var body = $("upstreamsBody"); if (!s.upstreams.length) { @@ -24,8 +68,8 @@ body.innerHTML = s.upstreams.map(function (u) { var enabled = !!u.enabled; var toggle = enabled - ? "" - : ""; + ? "" + : ""; var key = u.auth_set ? "" + IP.esc(u.auth_mask) + "" : "未设置"; @@ -127,20 +171,13 @@ btn.disabled = true; IP.api("POST", "/api/admin/upstreams/save", { slot: slot, - base: btn.getAttribute("data-base"), 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-up") { var up2 = IP.state.upstreams.filter(function (x) { return x.slot === slot; })[0]; if (!up2) return; - $("upSlot").value = up2.slot; - $("upBase").value = up2.base; - $("upModels").value = IP.arr(up2.models).join(", "); - $("upNote").value = up2.note || ""; - $("upAuth").value = ""; - $("upAuth").focus(); - IP.toast("已载入 " + slot + ",改完点「保存上游」;密钥留空表示不改"); + openForm(up2); } else if (act === "del-up") { if (!confirm("确认删除上游 " + slot + "?删除后指向它的调用将立即 404。")) return; btn.disabled = true; @@ -150,28 +187,7 @@ } }); - $("upsertUpstreamForm").addEventListener("submit", function (e) { - e.preventDefault(); - var payload = { - slot: $("upSlot").value.trim(), - base: $("upBase").value.trim(), - // 模型清单总是显式提交:编辑框里就是"当前值",清空即清空(可预期) - models: $("upModels").value, - note: $("upNote").value.trim() - }; - // 密钥留空时不传该字段:后端对「缺省」保留旧值,对「空串」是清空 - var auth = $("upAuth").value.trim(); - if (auth) payload.auth = auth; - IP.api("POST", "/api/admin/upstreams/save", payload).then(function (r) { - IP.toast(r.msg); - $("upSlot").value = ""; - $("upBase").value = ""; - $("upAuth").value = ""; - $("upModels").value = ""; - $("upNote").value = ""; - return IP.reload(); - }).catch(function (err) { IP.toast(err.message, true); }); - }); + $("newUpBtn").addEventListener("click", function () { openForm(null); }); IP.boot("upstreams", render); })(); diff --git a/www/upstreams.html b/www/upstreams.html index 7f302f3..8fe6658 100644 --- a/www/upstreams.html +++ b/www/upstreams.html @@ -12,25 +12,13 @@
-

新建 / 更新 LLM 上游

-
slot 即 URL 前缀:客户端把 base_url 指向 https://lm.mayishangshu.cn/<slot>/v1 并携带其账号 API Key,网关把 Key 换成本处配置的上游密钥后转发。一家厂商通常挂很多模型,把模型名登记在这里,客户端就能通过 GET /v1/models 或 GET /api/v1/models 先列出可用模型再调用。保存后立即生效,无需重启。密钥/模型列表留空表示不修改已有值。
-
-
-
-
-
-
- - +
+
+

上游列表

+
slot 即 URL 前缀:客户端把 base_url 指向 https://lm.mayishangshu.cn/<slot>/v1 并携带其账号 API Key,网关把 Key 换成本处配置的上游密钥后转发。一家厂商通常挂很多模型,把模型名登记在这里,客户端就能通过 GET /v1/models 或 GET /api/v1/models 先列出可用模型再调用。停用的上游对客户端表现为 404;删除不可恢复,指向它的调用会立即失败。
-
- -
- -
-

上游列表

-
停用的上游对客户端表现为 404;删除不可恢复,指向它的调用会立即失败。
+ +
slot上游地址密钥模型备注状态创建时间操作