feat(apix): 透传模式 passthrough —— 通用内部 REST 出口 (1.0.20)

- 模型加 mode 字段(vendor 默认 / passthrough 新增),shm payload 扩为 4 字段
  base\nkey\nasset_id\nmode;旧数据零迁移(无 mode → vendor)
- 拆 location 而非按 mode 分支:/apixp/ 不施加 vendor 强约束
  (proxy_method POST + 强制 Content-Type + proxy_pass_request_headers off
  是 location 级指令,无法按请求级 shm 的 mode 动态切换)
- handler 校验路径前缀 vs mode 一致(vendor slug 走 /apixp/ → 404,反之亦然),
  避免 vendor 条目继承 passthrough 强制 Content-Type 致 415 之类静默故障
- passthrough:方法/请求体/Content-Type 原样透传(含 multipart),上游路径
  = base + /apixp/<slug> 之后的 URI 尾部(含 query 由模块拼,变量式 proxy_pass
  不自动追加);Key 可空(内部服务免鉴权,下发时 nginx 空串 = 不发该头)
- 探测按 mode 分流:vendor 走 POST 预估 / passthrough 走 GET 打上游根地址
- nginx:lm server 加 /apixp/,mdm server 加 /_apixp_probe/(internal)
- 测试 §11.6 新增 35 条断言(鉴权/路径转发/体透传/Key 下发/路径-mode 一致
  /管理台回显/探测);账号态 count 1→3 同步;回归 225/0 全绿
- 管理台:列表加 mode 标签、表单加 mode 下拉 + 透传说明 + 路径示例复制
- 文档:docs/apix/PASSTHROUGH_MODE.md 真源(决策/兼容/改动一览)

OCR 是第一条 passthrough 配置:/apixp/ocr/ocr、/apixp/ocr/ocr/base64、
/apixp/ocr/ocr/url?src=...
This commit is contained in:
admin committed 2026-09-15 10:51:29 +08:00
1 parent 2cd2ba43b9
commit 4533db8536
12 files changed
+594 -49

No files matched your search

+74
View File
@@ -249,6 +249,62 @@ http {
return 502 '{"code":502,"msg":"API 供应商不可达,请稍后重试或联系管理员"}';
}
# ---- API 代理透传出口:`/apixp/<slug>/<尾部>` → 内部 REST 服务 ----
#
# 与 `/apix/`(vendor 收口)分离成独立 location,是 passthrough 模式成立的
# 前提:vendor 的 `/apix/` 在 nginx 层强制了 `proxy_method POST` +
# `proxy_set_body` + `Content-Type: application/json`,这些 location 级指令
# 无法按请求级的 shm mode 动态切换。OCR / 文生图 / TTS 这类「多端点、多 body、
# 无 asset 市场」的内部服务必须原样转发方法/请求体/Content-Type,所以另起
# 这个不施加上述约束的 location。
#
# 鉴权仍走网关同一把 `sk_` Key + 配额 + 用量统计(过 iPass 的意义),
# 只是**不再由网关拼体**——客户端带什么方法/body 原样给上游。上游路径 =
# `base + /apixp/<slug> 之后的 URI 尾部`(由模块 `$apixp_target` 算出)。
location /apixp/ {
ipass_apix on;
# 变量形式的上游(已含 path + query)。不强制 proxy_method / proxy_set_body,
# 让 OCR 的 multipart/form-data 或任意 JSON 原样出去。
proxy_pass $apixp_target;
proxy_http_version 1.1;
# 与 /apix/ 同一套出站头策略:默认不放行 + 显式放行。
# 抹掉 x-api-key / Authorization 尤其重要——那是**调用方的网关 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 $apixp_host;
# 内部服务需要 Key 才下发(X-API-Key);空则不下发(nginx 空串 = 不发该头)。
# 下行那把 sk_ 到此为止,绝不外传。
proxy_set_header X-API-Key $apixp_key;
# ★ 原样透传客户端 Content-Type(OCR 的 multipart 必须带 boundary)
proxy_set_header Content-Type $http_content_type;
proxy_set_header Accept $http_accept;
proxy_set_header User-Agent $http_user_agent;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
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 = /apixp_error;
}
location = /apixp_error {
default_type application/json;
return 502 '{"code":502,"msg":"内部服务不可达,请稍后重试或联系管理员"}';
}
# 只改写「连不上上游」这类由 nginx 自己产生的错误。
# 404 等一律透传上游响应——那可能是模型名不存在的正常业务错误,
# 覆盖掉反而让客户端拿不到有用信息。
@@ -326,6 +382,24 @@ http {
proxy_read_timeout 15s;
}
# —— API 代理透传连通性探针(管理台「测试」按钮)——
# /api/admin/apix/test 对 passthrough 模式条目内部重定向到这里。走 GET 打
# 上游根地址验连通性(不执行任何资产),复用 $apixp_probe_target 变量。
# internal 挡住外部直连——这是绕过 ukey 鉴权直接触达内部服务的口子。
location /_apixp_probe/ {
internal;
proxy_pass $apixp_probe_target;
proxy_method GET;
proxy_http_version 1.1;
proxy_pass_request_headers off;
proxy_set_header Host $apixp_host;
proxy_set_header X-API-Key $apixp_key;
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,
+120
View File
@@ -0,0 +1,120 @@
# apix 透传模式(passthrough)
## 为什么需要
vendor 模式假设「单一供应商收口 `POST /api/v1/ai/request`,资产由 body 里的
`asset_id` 决定」,网关负责拼体(堵客户端挑最贵的资产刷)——对 LLM 资产市场型
服务很合理。但公司内部一些 REST 服务(OCR / 文生图 / TTS)有完全不同的形态:
| 维度 | vendor 模式 | passthrough 模式 |
| --- | --- | --- |
| 上游 | 单一收口 | 多端点(`/ocr` `/ocr/base64` `/ocr/url` 等) |
| 请求体 | 网关从 query 拼 | 客户端原样带(含 multipart) |
| Content-Type | 强制 `application/json` | 原样透传(含 `multipart/form-data`) |
| 方法 | GET 被强制改成 POST | 原样透传 |
| 鉴权 | 必填供应商 Key | 可空(内部服务免鉴权) |
| 资产选择权 | 服务端(asset_id 在网关侧) | 客户端(URL 路径即端点) |
强行套 vendor 会 4 处冲突(路径写死 / 体来源 / Content-Type / 方法),所以新加
passthrough 模式作为「通用内部 REST 出口」——OCR 只是第一条配置。
## 设计要点
### 拆 location 而不是按请求级切模式
vendor `/apix/` 在 nginx 层强制了 `proxy_method POST` + `proxy_set_body` +
`Content-Type: application/json` + `proxy_pass_request_headers off`,这些
location 级指令**无法按请求级 shm 的 mode 动态切换**。
所以 passthrough 走独立 `/apixp/` location,不施加上述约束,零风险保留 `/apix/`
的 vendor 行为。nginx 端按 URL 前缀选 location 是**单一判定点**,模块侧不再做
「同前缀按 mode 分支」的二选一。
### Mode 必须与路径前缀一致
- vendor 条目:只能走 `/apix/<slug>`,访问 `/apixp/<slug>` → 404
- passthrough 条目:只能走 `/apixp/<slug>/<tail>`,访问 `/apix/<slug>` → 404
handler 在 access 阶段校验,避免「vendor 条目继承 passthrough 的强制
`Content-Type` 导致 415」之类静默故障。
### 路径尾部 + query 透传
- `$apixp_target = base + tail + (?args if any)`
- 变量式 `proxy_pass` 不自动追加 query,由模块在 `var_get` 里把 `args_raw` 拼上
(与 LLM 同约束)
- 内部探测走 `$apixp_probe_target = base/`(GET 打上游根地址验连通性)
### 鉴权语义
- vendor:供应商 Key 必填,空 → 503「供应商 API Key 未配置」
- passthrough:Key 可空,空时不下发 `X-API-Key`(nginx 空串 = 不发该头)
- 两模式**都**走 `sk_` 下行 Key + 配额 + 用量统计(slot 前缀 `api/<slug>`)
—— 这是 passthrough 仍过 iPass 的意义,不是「直连上游」
## 配置示例(OCR)
```json
{
"ocr": {
"supplier": "internal-ocr",
"asset_id": "",
"base": "http://192.168.1.11:9003",
"key": "",
"mode": "passthrough",
"name": "内部 OCR 服务",
"desc": "多端点透传:/ocr、/ocr/base64、/ocr/url",
"params": [],
"enabled": true
}
}
```
调用方走网关同一把 `sk_` Key:
```
POST /apixp/ocr/ocr multipart/form-data(上传图片)
POST /apixp/ocr/ocr/base64 {"image_base64":"..."}
POST /apixp/ocr/ocr/url?url=... {"url":"..."}
```
## shm payload 兼容
shm `ax:<slug>` 从 3 字段 `base\nkey\nasset_id` 扩成 4 字段 `base\nkey\nasset_id\nmode`。
- 旧数据(无 mode)→ 解析时 mode = "",lookup 视为 vendor(向后兼容)
- 旧代码读 3 元组版本未在线,会被新版本解析时 None 化(重启即统一)
## 回归覆盖
`tests/llm/e2e.sh` §11.6(35 条断言)覆盖:
- 鉴权(无 Key / 坏 Key / 不存在 / 停用 → 401/404)
- 空 Key 透传放行(内部服务免鉴权)
- 路径尾部单级 + 多级(`/ocr` `/ocr/base64` `/ocr/url`)
- query 透传(`/apixp/ocr/ocr/url?src=...`)
- 方法透传(POST 没被改)
- 请求体透传(multipart / JSON 原样)
- `X-API-Key` 按需下发(空 → 不发)
- 下行 `sk_` Key 绝不外传
- 路径/模式一致性(vendor 走 `/apixp/` → 404,反之亦然)
- 管理台:mode 字段回显、调用地址用 `/apixp/` 前缀
- 探测:passthrough 走 GET 打上游根地址
- 内部探测口 `/_apixp_probe/` 外部直连 → 404
- 用量统计按 `api/<slug>` 归组(passthrough 同样计)
## 文件改动一览
| 文件 | 改动 |
| --- | --- |
| `rust/crates/plugin-apix/src/models.rs` | `ApiProxy` 加 `mode` 字段(默认 vendor) |
| `rust/crates/plugin-apix/src/config.rs` | `APIX_MODE_VENDOR` / `APIX_MODE_PASSTHRU` 常量 |
| `rust/crates/plugin-apix/src/apix.rs` | `PUB_PT_PREFIX` / `PROBE_PT_PREFIX`;shm payload 4 元;`slug_of` 返回 `(slug, tail, is_passthru_path)`;`lookup` 返 4 元;`var_get` 增 `$apixp_*` 透传分支;`call_url` 按 mode 选前缀;`view` 回显 mode |
| `rust/crates/plugin-apix/src/handlers.rs` | access 阶段校验「路径前缀 vs mode」一致;passthrough 放行空 Key |
| `rust/crates/plugin-apix/src/api.rs` | `upsert` 收 mode(passthrough 下 asset_id 可空);`view` 含 mode;`h_admin_apix_test` 按 mode 选探针前缀 |
| `conf/nginx.conf` | lm server 加 `/apixp/`;mdm server 加 `/_apixp_probe/`(GET) |
| `tests/llm/nginx.conf.in` | 同步 `/apixp/` 与 `/_apixp_probe/` |
| `tests/llm/fixtures/api-proxies.json` | 新增 `ocr`(空 Key)+ `ocrk`(带 Key)两个 passthrough 夹具 |
| `tests/llm/e2e.sh` | §11.6 加 35 条透传断言;§11.5 账号态计数 1→3 |
| `www/apix.html` | 列表说明加 vendor/passthrough 两模式解释 |
| `www/assets/apix.js` | 列表 mode 标签;表单 mode 下拉 + 透传提示 |
+24 -11
View File
@@ -11,6 +11,7 @@ use ipass_core::api::{Actor, Guard, run_guarded};
use ipass_core::{http, util};
use crate::apix;
use crate::config;
// ===========================================================================
// 路由
@@ -67,6 +68,7 @@ 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();
let mode = p.get("mode").cloned().unwrap_or_default();
// 参数清单允许两种写法:逗号分隔(`q,format`)或 JSON 数组(`["q"]`)
let params = p.get("params").and_then(|v| {
@@ -92,6 +94,7 @@ fn h_admin_apix_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
match apix::upsert(
&slug,
&asset,
Some(&mode),
p.get("base"),
p.get("key"),
p.get("supplier"),
@@ -102,8 +105,12 @@ fn h_admin_apix_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
p.get("note"),
) {
Ok(item) => {
util::log_notice(&format!("[api] 保存 API 代理 {slug} → {asset}"));
http::ok(r, json!({ "slug": slug, "asset_id": item.asset_id }), "已保存")
util::log_notice(&format!("[api] 保存 API 代理 {slug} → {asset} (mode={})", item.mode));
http::ok(
r,
json!({ "slug": slug, "asset_id": item.asset_id, "mode": item.mode }),
"已保存",
)
}
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
}
@@ -121,24 +128,30 @@ fn h_admin_apix_delete(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
}
}
/// 管理员:探测供应商 Key 是否可用(管理台「测试」按钮)。
/// 管理员:探测代理是否可用(管理台「测试」按钮)。
///
/// 走供应商的**免费预估**接口(`/api/v1/ai/estimate`):它不执行资产、不扣费,
/// 响应里还带 `current_balance_usd` —— 一次调用同时拿到「Key 通不通」和
/// 「还剩多少钱」。实现上内部重定向到管理 server 的 `/_apix_probe/<slug>`,
/// 复用 `$apix_probe_*` 变量(拼体、换 Key 与真实转发同一套逻辑)。
/// - vendor 模式:走供应商的**免费预估**接口(`/api/v1/ai/estimate`)——
/// 不执行资产、不扣费,响应里还带 `current_balance_usd`。内部重定向到
/// `/_apix_probe/<slug>`,复用 `$apix_probe_*` 变量(拼体、换 Key 与真实转发同一套逻辑)。
/// - passthrough 模式:没有「预估」概念,探针改为 GET 打上游根地址验连通性,
/// 内部重定向到 `/_apixp_probe/<slug>`,复用 `$apixp_probe_target` 变量。
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() {
let Some((_b, _k, _a, mode)) = apix::lookup(&slug) else {
return http::fail(r, HTTPStatus::NOT_FOUND, &format!("代理 {slug} 不存在或已停用"));
}
};
let uri = format!("{}{}", apix::PROBE_URI_PREFIX, slug);
util::log_notice(&format!("[api] 测试 API 代理 {slug}"));
let prefix = if mode == config::APIX_MODE_PASSTHRU {
apix::PROBE_PT_PREFIX
} else {
apix::PROBE_URI_PREFIX
};
let uri = format!("{prefix}{slug}");
util::log_notice(&format!("[api] 测试 API 代理 {slug} (mode={mode})"));
// ⚠️ 与 LLM 上游测试同一个坑:internal_redirect 只浅拷贝 ngx_str_t,
// 必须把字节拷进请求池,否则函数返回后 r->uri 全是 NUL(实测踩过)。
+157 -25
View File
@@ -56,6 +56,10 @@ pub unsafe fn preconfig(cf: *mut ngx_conf_t) -> bool {
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 mut axp_target = ngx_string!("apixp_target");
let mut axp_host = ngx_string!("apixp_host");
let mut axp_key = ngx_string!("apixp_key");
let mut axp_probe = ngx_string!("apixp_probe_target");
unsafe {
add_var(cf, &raw mut ax_target, VAR_TARGET)
&& add_var(cf, &raw mut ax_host, VAR_HOST)
@@ -63,6 +67,10 @@ pub unsafe fn preconfig(cf: *mut ngx_conf_t) -> bool {
&& add_var(cf, &raw mut ax_body, VAR_BODY)
&& add_var(cf, &raw mut ax_ptarget, VAR_PROBE_TARGET)
&& add_var(cf, &raw mut ax_pbody, VAR_PROBE_BODY)
&& add_var(cf, &raw mut axp_target, VAR_PT_TARGET)
&& add_var(cf, &raw mut axp_host, VAR_PT_HOST)
&& add_var(cf, &raw mut axp_key, VAR_PT_KEY)
&& add_var(cf, &raw mut axp_probe, VAR_PT_PROBE)
}
}
@@ -106,6 +114,14 @@ 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;
/// `$apixp_target`:透传模式完整上游 URL(`base + /apixp/<slug> 之后的 URI 尾部`)
pub const VAR_PT_TARGET: usize = 7;
/// `$apixp_host`:透传模式上游 Host 头
pub const VAR_PT_HOST: usize = 8;
/// `$apixp_key`:透传模式供应商 Key(内部服务无 Key 时下发空,nginx 侧不下发鉴权头)
pub const VAR_PT_KEY: usize = 9;
/// `$apixp_probe_target`:透传模式「测试」用的连通性探针(GET 打上游根地址)
pub const VAR_PT_PROBE: usize = 10;
/// shm payload 内部分隔符:base / 供应商 Key / asset_id 之间。
///
@@ -117,6 +133,17 @@ pub const PROBE_URI_PREFIX: &str = "/_apix_probe/";
const PROBE_PREFIX: &str = PROBE_URI_PREFIX;
/// 对外的 API 代理前缀
const PUB_PREFIX: &str = "/apix/";
/// 透传模式(passthrough)对外的 API 代理前缀:`/apixp/<slug>/<tail>`。
///
/// 与 vendor 的 `/apix/` 拆成**两个独立 location**,根本原因是 vendor 的
/// `/apix/` location 在 nginx 层强制了 `proxy_method POST` + `proxy_set_body`
/// + `Content-Type: application/json` + `proxy_pass_request_headers off`——
/// 这些 location 级指令无法按请求级 shm 的 mode 动态切换。透传必须原样转发
/// 客户端的方法/请求体/Content-Type(OCR 的 `/ocr` 就是 `multipart/form-data`),
/// 所以只能另起一个不施加上述约束的 `/apixp/` location,零风险保留 `/apix/` 行为。
pub const PUB_PT_PREFIX: &str = "/apixp/";
/// 透传模式内部探测前缀(管理台「测试」走 GET 打上游根地址验连通性)。
pub const PROBE_PT_PREFIX: &str = "/_apixp_probe/";
// ===========================================================================
// 校验
@@ -211,16 +238,20 @@ fn check_params(raw: &[String]) -> Result<Vec<String>, String> {
// ===========================================================================
fn payload_of(item: &ApiProxy) -> String {
format!("{}{PAYLOAD_SEP}{}{PAYLOAD_SEP}{}", item.base, item.key, item.asset_id)
format!(
"{}{PAYLOAD_SEP}{}{PAYLOAD_SEP}{}{PAYLOAD_SEP}{}",
item.base, item.key, item.asset_id, item.mode
)
}
/// 拆 payload:`base \n key \n asset_id`
pub fn split_payload(payload: &str) -> (&str, &str, &str) {
let mut it = payload.splitn(3, PAYLOAD_SEP);
/// 拆 payload:`base \n key \n asset_id \n mode`
pub fn split_payload(payload: &str) -> (&str, &str, &str, &str) {
let mut it = payload.splitn(4, PAYLOAD_SEP);
let base = it.next().unwrap_or("");
let key = it.next().unwrap_or("");
let asset = it.next().unwrap_or("");
(base, key, asset)
let mode = it.next().unwrap_or("");
(base, key, asset, mode)
}
/// 把一条代理同步进共享内存。**所有写操作之后必须调用它**。
@@ -268,34 +299,62 @@ pub fn reload_shm() -> usize {
loaded
}
/// 热路径查表:`slug → (base, 供应商Key, asset_id)`
pub fn lookup(slug: &str) -> Option<(String, String, String)> {
/// 热路径查表:`slug → (base, 供应商Key, asset_id, mode)`
///
/// vendor 模式要求 `asset_id` 非空——它是拼调用体的依据;passthrough 模式
/// `asset_id` 留空也合法,上游路径由 URL 尾部(见 [`slug_of`] 的 `tail`)决定。
pub fn lookup(slug: &str) -> Option<(String, 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() {
let (base, key, asset, mode) = split_payload(&payload);
if mode != config::APIX_MODE_PASSTHRU && asset.is_empty() {
return None;
}
Some((base.to_owned(), key.to_owned(), asset.to_owned()))
Some((
base.to_owned(),
key.to_owned(),
asset.to_owned(),
mode.to_owned(),
))
}
// ===========================================================================
// 请求解析
// ===========================================================================
/// 取 URL 里的 slug:`/apix/search?q=1` 或 `/_apix_probe/search` → `search`
/// 取 URL 里的 slug,并返回 URI 尾部与「是否落在透传前缀下」。
///
/// 两个前缀都认:对外出口与内部探测共用同一套「取 slug → 拼体 → 换 Key」逻辑,
/// 与 `llm::slot_of` 对 `/_upstream_test` 的处理是同一个手法。
pub fn slug_of(r: *mut ngx_http_request_t) -> Option<String> {
/// 四个前缀都认:vendor 对外 `/apix/` 与内部探针 `/_apix_probe/`、
/// passthrough 对外 `/apixp/` 与内部探针 `/_apixp_probe/`。
/// 返回三元组 `(slug, tail, is_passthru_path)`:
/// - `tail`:slug 之后的 URI 片段(含前导 `/`,可能为空)。vendor 模式恒为空
/// (路径写死 `/api/v1/ai/request`);passthrough 模式 = 真正转发到上游的
/// 路径尾部(如 `/ocr`、`/ocr/url`、`/ocr/base64`)。
/// - `is_passthru_path`:当前请求是否落在透传前缀下,供 handler 校验
/// 「路径前缀」与「条目 mode」一致(vendor slug 不能走 `/apixp/`,反之亦然)。
///
/// 与 `llm::slot_of` 对 `/_upstream_test` 的处理是同一个手法:对外出口与内部
/// 探测共用同一套「取 slug → 拼目标 → 换 Key」逻辑。
pub fn slug_of(r: *mut ngx_http_request_t) -> Option<(String, String, bool)> {
let uri = http::uri(r);
let rest = uri
.strip_prefix(PROBE_PREFIX)
.or_else(|| uri.strip_prefix(PUB_PREFIX))?;
let (rest, is_pt) = if let Some(rest) = uri.strip_prefix(PUB_PT_PREFIX) {
(rest, true)
} else if let Some(rest) = uri.strip_prefix(PROBE_PT_PREFIX) {
(rest, true)
} else if let Some(rest) = uri.strip_prefix(PUB_PREFIX) {
(rest, false)
} else if let Some(rest) = uri.strip_prefix(PROBE_PREFIX) {
(rest, false)
} else {
return None;
};
let slug = rest.split('/').next().unwrap_or("");
if slug.is_empty() {
return None;
}
Some(slug.to_ascii_lowercase())
let slug = slug.to_ascii_lowercase();
// tail = slug 之后的全部内容(含前导 '/',可能为空)
let tail = rest[slug.len()..].to_owned();
Some((slug, tail, is_pt))
}
/// 从 `https://api.example.com:443` 取出 `api.example.com:443`
@@ -433,8 +492,8 @@ pub extern "C" fn var_get(
// SAFETY: r/v 由 nginx 传入且有效;slug_of 只读请求结构
unsafe {
let resolved = (|| -> Option<String> {
let slug = slug_of(r)?;
let (base, key, asset) = lookup(&slug)?;
let (slug, tail, _is_pt) = slug_of(r)?;
let (base, key, asset, mode) = lookup(&slug)?;
Some(match data {
VAR_TARGET => format!("{base}{}", config::APIX_REQUEST_PATH),
VAR_PROBE_TARGET => format!("{base}{}", config::APIX_ESTIMATE_PATH),
@@ -446,6 +505,25 @@ pub extern "C" fn var_get(
// 响应里的 current_balance_usd 顺带把供应商余额带回来
format!("{{\"asset_id\":{},\"max_tokens\":1}}", json_quote(&asset))
}
// —— 透传模式变量:仅当条目本身是 passthrough 才有效 ——
VAR_PT_TARGET if mode == config::APIX_MODE_PASSTHRU => {
// 原样转发:上游 URL = base + URL 尾部(如 base + /ocr)。
// 变量形式 proxy_pass 不自动追加 query(与 LLM 同约束),
// 所以通用 REST 出口必须把 query 也拼进去。
let args = http::args_raw(r);
let args = std::str::from_utf8(&args).unwrap_or("");
if args.is_empty() {
format!("{base}{tail}")
} else {
format!("{base}{tail}?{args}")
}
}
VAR_PT_HOST if mode == config::APIX_MODE_PASSTHRU => host_of(&base).to_owned(),
VAR_PT_KEY if mode == config::APIX_MODE_PASSTHRU => key,
VAR_PT_PROBE if mode == config::APIX_MODE_PASSTHRU => {
// 透传探针:GET 打上游根地址,验证连通性(不真正执行任何资产)
format!("{base}/")
}
_ => return None,
})
})();
@@ -484,8 +562,16 @@ pub fn enabled() -> Vec<(String, ApiProxy)> {
/// 客户端应当使用的调用地址(base,不带 query)。端口由调用方从请求 Host 头取,
/// **不要写死**(部署在 88 时要带 `:88`,放在 443 反代后面时不能带)。
/// query 参数由前端按 `params` 拼一次(避免后端与前端各拼一次导致 `?q=?q=`)。
pub fn call_url(slug: &str, port: &str) -> String {
format!("https://{LLM_PUBLIC_HOST}{port}{PUB_PREFIX}{slug}")
///
/// `mode` 决定前缀:vendor → `/apix/<slug>`,passthrough → `/apixp/<slug>`
/// (passthrough 后续还能再追路径尾部,如 `/apixp/ocr/ocr`)。
pub fn call_url(slug: &str, port: &str, mode: &str) -> String {
let prefix = if mode == config::APIX_MODE_PASSTHRU {
PUB_PT_PREFIX
} else {
PUB_PREFIX
};
format!("https://{LLM_PUBLIC_HOST}{port}{prefix}{slug}")
}
/// 新增或覆盖一个代理条目。
@@ -497,6 +583,7 @@ pub fn call_url(slug: &str, port: &str) -> String {
pub fn upsert(
slug_raw: &str,
asset_raw: &str,
mode_raw: Option<&String>,
base_raw: Option<&String>,
key_raw: Option<&String>,
supplier_raw: Option<&String>,
@@ -507,7 +594,39 @@ pub fn upsert(
note: Option<&String>,
) -> Result<ApiProxy, String> {
let slug = validate_slug(slug_raw)?;
let asset_id = validate_asset(asset_raw)?;
// 代理模式:vendor(默认)/ passthrough,其余值一律拒绝
let mode = match mode_raw {
Some(m) => {
let m = util::trim(m).to_ascii_lowercase();
if m.is_empty() {
config::APIX_MODE_VENDOR.to_owned()
} else if m == config::APIX_MODE_VENDOR || m == config::APIX_MODE_PASSTHRU {
m
} else {
return Err(format!(
"不支持的代理模式:{m}(仅支持 vendor / passthrough)"
));
}
}
None => config::APIX_MODE_VENDOR.to_owned(),
};
// vendor 模式 asset_id 必填(拼体依据);passthrough 模式可留空
// (上游路径由 URL 尾部决定),仅做与 vendor 同样的卫生检查。
let asset_id = if mode == config::APIX_MODE_PASSTHRU {
let s = util::trim(asset_raw);
if s.chars().any(char::is_whitespace) || s.chars().any(char::is_control) {
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));
}
s.to_owned()
} else {
validate_asset(asset_raw)?
};
let params = match params {
Some(list) => Some(check_params(&list)?),
None => None,
@@ -574,7 +693,19 @@ pub fn upsert(
.filter(|&t| t > 0)
.unwrap_or_else(util::now);
let item = ApiProxy { asset_id, supplier, base, key: key_val, name, desc, params, enabled, note, created_at };
let item = ApiProxy {
asset_id,
supplier,
base,
key: key_val,
mode,
name,
desc,
params,
enabled,
note,
created_at,
};
data.items.insert(key.clone(), item.clone());
Ok((item, data.clone()))
})?;
@@ -609,6 +740,7 @@ pub fn view(slug: &str, item: &ApiProxy, port: &str) -> Value {
json!({
"slug": slug,
"asset_id": item.asset_id,
"mode": item.mode,
"supplier": item.supplier,
"base": item.base,
"name": item.name,
@@ -620,7 +752,7 @@ pub fn view(slug: &str, item: &ApiProxy, port: &str) -> Value {
"note": item.note,
"created_at": item.created_at,
"created_at_text": util::fmt_time(item.created_at),
"url": call_url(slug, port),
"url": call_url(slug, port, &item.mode),
})
}
+4
View File
@@ -42,3 +42,7 @@ pub const APIX_KEY_MAX_LEN: usize = 128;
/// 而 LLM slot 的字符集不含 `/`(见 `plugin_llm::upstreams::validate_slot`),
/// 所以 `api/<slug>` 绝不会和 LLM 上游撞车,用量页能自然分成两组。
pub const APIX_STATS_PREFIX: &str = "api/";
/// 代理模式:vendor(默认)= 单一供应商收口;passthrough = 透传内部 REST 服务。
pub const APIX_MODE_VENDOR: &str = "vendor";
pub const APIX_MODE_PASSTHRU: &str = "passthrough";
+18 -4
View File
@@ -27,11 +27,11 @@ impl HttpRequestHandler for ApiProxyHandler {
return Status::NGX_DECLINED;
}
let Some(slug) = apix::slug_of(r) else {
let Some((slug, _tail, is_pt_path)) = apix::slug_of(r) else {
return http::fail(
r,
HTTPStatus::BAD_REQUEST,
"路径缺少代理名,正确形式:/apix/<代理名>?<参数>",
"路径缺少代理名,正确形式:/apix/<代理名>?<参数> 或 /apixp/<代理名>/<尾部>",
);
};
@@ -54,7 +54,7 @@ impl HttpRequestHandler for ApiProxyHandler {
// 代理的**可见性**由管理员的启用/停用决定,不再叠一层账号白名单:
// 白名单是给「一家厂商一个 slot」设计的,这里再套一层会让
// 「管理员明明启用了、某账号却 403」变得难以解释。
let Some((_base, supplier_key, _asset)) = apix::lookup(&slug) else {
let Some((_base, supplier_key, _asset, mode)) = apix::lookup(&slug) else {
return http::fail(
r,
HTTPStatus::NOT_FOUND,
@@ -62,7 +62,21 @@ impl HttpRequestHandler for ApiProxyHandler {
);
};
if supplier_key.is_empty() {
// 路径前缀必须与条目 mode 一致:vendor slug 不能走 `/apixp/`,
// passthrough slug 也不能走 `/apix/`。两者 nginx location 的强约束不同,
// 混用会继承错误的 proxy_method / Content-Type 导致转发失败。
let is_pt_entry = mode == config::APIX_MODE_PASSTHRU;
if is_pt_path != is_pt_entry {
return http::fail(
r,
HTTPStatus::NOT_FOUND,
&format!("代理 {slug} 的访问路径与代理模式不匹配"),
);
}
// passthrough 模式:内部服务可能不需要供应商 Key,放行空 Key(不下发鉴权头)。
// vendor 模式:供应商 Key 必填,空则无法转发(保持原行为)。
if !is_pt_entry && supplier_key.is_empty() {
util::log_err(&format!(
"[apix] 供应商 Key 未配置,slug={slug} 无法转发 —— 请到管理台「API 代理」填写"
));
+16 -1
View File
@@ -28,7 +28,8 @@ impl Default for ApiProxyStore {
/// 单个 API 代理条目:指向某一家供应商的一个可调用的资产。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiProxy {
/// 供应商侧的资产 id(如 `searxng-search`),决定具体调用哪个资产
/// 供应商侧的资产 id(如 `searxng-search`),决定具体调用哪个资产。
/// **vendor 模式必填**;passthrough 模式用不到(上游路径由 URL 尾部决定),可留空。
pub asset_id: String,
/// 供应商名称(仅展示用,管理员自填,例如 `provider-x` / 客户自定)
#[serde(default)]
@@ -38,8 +39,17 @@ pub struct ApiProxy {
pub base: String,
/// 供应商 API Key(`ak_...`)。留空 = 未配置,热路径直接 503。
/// **敏感**:写盘与回显都按密钥处理,管理台只回显掩码。
/// passthrough 模式下若上游不需要鉴权可留空(不下发任何鉴权头)。
#[serde(default)]
pub key: String,
/// 代理模式:
/// - `vendor`(默认):单一供应商收口 `POST {base}/api/v1/ai/request`,
/// 请求体由网关按 `asset_id` 拼装(见 `apix.rs`)。
/// - `passthrough`:透传模式,原样转发客户端的方法/请求体/Content-Type,
/// 上游路径 = `{base} + /apixp/<slug> 之后的 URI 尾部`,用于 OCR / 文生图 /
/// TTS 这类「多端点、多 body、无 asset 市场」的内部 REST 服务。
#[serde(default = "default_mode")]
pub mode: String,
/// 展示名(中文)
#[serde(default)]
pub name: String,
@@ -64,3 +74,8 @@ pub struct ApiProxy {
fn default_true() -> bool {
true
}
/// 默认代理模式 = vendor(向后兼容旧数据:没有 `mode` 字段的条目就是 vendor)。
fn default_mode() -> String {
"vendor".to_owned()
}
+59 -1
View File
@@ -374,7 +374,7 @@ 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" \
ck "账号态接口只列已启用的(offline 不出现)" "3" \
"$(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 \
@@ -412,6 +412,64 @@ 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 "【11.6】★ API 代理透传模式(/apixp/<slug>/<尾部> → 内部 REST 服务)"
# 与 vendor 模式同一把 sk_ Key + 配额 + 用量统计,但**不再由网关拼体**——
# 客户端带什么方法/body/Content-Type 原样给上游。判据同样是看靶机实际收到的
# path / method / 头 / body,只看网关 200 证明不了「原样透传」。
ck "无 Key → 401" 401 "$(code "$GW/apixp/ocr/ocr")"
ck "坏 Key → 401" 401 "$(code -H 'X-API-Key: sk_nope' "$GW/apixp/ocr/ocr")"
ck "不存在的 slug → 404" 404 "$(code -H "X-API-Key: $ALICE_KEY" "$GW/apixp/ghost/foo")"
ck "★已停用的 slug → 404" 404 "$(code -H "X-API-Key: $ALICE_KEY" "$GW/apixp/offline/foo")"
ck "★passthrough 空 Key 也放行(内部服务免鉴权)" 200 \
"$(code -H "X-API-Key: $ALICE_KEY" -X POST "$GW/apixp/ocr/ocr" -H 'Content-Type: application/json' -d '{"image_base64":"AAAA"}')"
ck " 靶机 path = 路径尾部 /ocr(base + 尾部)" "/ocr" "$(up_field path)"
ck " ★方法原样透传(POST 没被改)" "POST" "$(up_field method)"
ck " ★请求体原样透传" yes "$(up_field body | grep -q 'image_base64' && echo yes || echo no)"
ck " ★空 Key 不下发 X-API-Key(上游收不到该头)" "" "$(up_hdr x-api-key)"
ck " ★下行 sk_ Key 没被带出去" "" "$(up_hdr authorization)"
# 路径尾部可多级:/apixp/ocr/ocr/base64 → 上游 /ocr/base64
ck "★多级尾部透传 → 200" 200 \
"$(code -H "X-API-Key: $ALICE_KEY" -X POST "$GW/apixp/ocr/ocr/base64" -H 'Content-Type: application/json' -d '{"image_base64":"BBBB"}')"
ck " 靶机 path = /ocr/base64" "/ocr/base64" "$(up_field path)"
# query 也随尾部一起透传(变量式 proxy_pass 不自动追加,由模块拼进 $apixp_target)
ck "★query 随尾部透传 → 200" 200 \
"$(code -H "X-API-Key: $ALICE_KEY" -X POST "$GW/apixp/ocr/ocr/url?src=http://example.com/x" -H 'Content-Type: application/json' -d '{"x":1}')"
ck " 靶机 path 含 query" yes "$(up_field path | grep -q '/ocr/url?src=' && echo yes || echo no)"
# 带 Key 的 passthrough:X-API-Key 必须被下发
ck "★带 Key 的 passthrough → 200" 200 \
"$(code -H "X-API-Key: $ALICE_KEY" -X POST "$GW/apixp/ocrk/health" -H 'Content-Type: application/json' -d '{}')"
ck " ★X-API-Key 被下发到上游" "ak_internal_ocr_key" "$(up_hdr x-api-key)"
ck " ★path 尾部 = /health" "/health" "$(up_field path)"
# mode 与路径前缀必须一致:vendor slug 不能走 /apixp/,passthrough slug 不能走 /apix/
ck "★vendor slug 走 /apixp/ → 404(路径与模式不匹配)" 404 \
"$(code -H "X-API-Key: $ALICE_KEY" "$GW/apixp/search?q=1")"
ck "★passthrough slug 走 /apix/ → 404(路径与模式不匹配)" 404 \
"$(code -H "X-API-Key: $ALICE_KEY" "$GW/apix/ocr")"
# 管理台:mode 字段回显 + 调用地址用 /apixp/ 前缀
ck "管理台列表含 ocr 且 mode=passthrough" yes "$(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"] == "ocr"), None)
print("yes" if it and it.get("mode") == "passthrough" else "no")')"
ck " ★ocr 调用地址用 /apixp/ 前缀" yes "$(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"] == "ocr"), None)
print("yes" if it and "/apixp/ocr" in it.get("url","") else "no")')"
# 探测:passthrough 走 GET 打上游根地址验连通性
ck "★探测(passthrough)→ 透传 200" 200 "$(code -b "$JAR" -X POST \
"$API/api/admin/apix/test?slug=ocr" -H 'Content-Type: application/json' -d '{}')"
ck " 探测是 GET(非 POST 预估)" "GET" "$(up_field method)"
ck " 探测打上游根 /" "/" "$(up_field path)"
ck " 探测也空 Key(不下发 X-API-Key)" "" "$(up_hdr x-api-key)"
ck "★内部透传探测口外部直连 → 404" 404 \
"$(code -b "$JAR" -X POST "$API/_apixp_probe/ocr" -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> 归组(passthrough 同样计)" yes \
"$(curl -s -b "$JAR" $API/api/admin/usage | has '"slot": *"api/ocr"')"
echo
echo "【12】★ 上游健康标记(失效自动缓存 + 模型发现附可用地址/状态)"
# 健康缓存由 log 阶段的**真实转发**写入(uh:<slot>)——「测试」按钮走同一条
+24
View File
@@ -21,6 +21,30 @@
"params": [],
"enabled": false,
"created_at": 1750000000
},
"ocr": {
"supplier": "internal-ocr",
"asset_id": "",
"base": "http://127.0.0.1:18999",
"key": "",
"mode": "passthrough",
"name": "内部 OCR 服务(空 Key 透传)",
"desc": "多端点透传:/ocr、/ocr/base64、/ocr/url,内部服务免鉴权",
"params": [],
"enabled": true,
"created_at": 1750000000
},
"ocrk": {
"supplier": "internal-ocr",
"asset_id": "",
"base": "http://127.0.0.1:18999",
"key": "ak_internal_ocr_key",
"mode": "passthrough",
"name": "内部 OCR 服务(带 Key 透传)",
"desc": "同上,但上游需要 X-API-Key,验证透传模式下 Key 会被下发",
"params": [],
"enabled": true,
"created_at": 1750000000
}
}
}
+41
View File
@@ -121,6 +121,33 @@ http {
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
# ---- API 代理透传出口(与生产 conf/nginx.conf 的 /apixp/ 逐条对齐)----
# 靶机地址由夹具 api-proxies.json 的 base 指向 127.0.0.1:18999,
# 转发链路与生产完全一致(只是这里不强制 proxy_method / Content-Type)。
location /apixp/ {
ipass_apix on;
proxy_pass $apixp_target;
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 $apixp_host;
proxy_set_header X-API-Key $apixp_key;
proxy_set_header Content-Type $http_content_type;
proxy_set_header Accept $http_accept;
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(只为在同一次回归里验账号态用量/模型接口)----
@@ -155,6 +182,20 @@ http {
proxy_read_timeout 15s;
}
# API 代理透传探测:/api/admin/apix/test 对 passthrough 条目内部重定向到这里
location /_apixp_probe/ {
internal;
proxy_pass $apixp_probe_target;
proxy_method GET;
proxy_http_version 1.1;
proxy_pass_request_headers off;
proxy_set_header Host $apixp_host;
proxy_set_header X-API-Key $apixp_key;
proxy_connect_timeout 5s;
proxy_send_timeout 15s;
proxy_read_timeout 15s;
}
# 上游连通性测试:/api/admin/upstreams/test 内部重定向到这里
# (与生产 conf 同套:proxy_pass 复用 $llm_*,探测体原样转发,状态透传)
location /_upstream_test/ {
+7
View File
@@ -19,6 +19,13 @@
把外部供应商的 API 挂到网关下:调用方用<b>同一把账号 API Key</b> 访问
<code>/apix/&lt;slug&gt;?参数=值</code>,网关换成<b>该代理自身登记的供应商 Key</b>后转发,并返回供应商原样结果。
每家供应商的基址与 Key 都在每一条代理里单独填写,互不影响。停用的代理对调用方表现为 404(共享内存已摘除,立即生效)。
<br><br>
<b>代理模式</b>:
<span class="badge" style="background:#eee;color:#666">vendor</span>
单一供应商收口 <code>POST /api/v1/ai/request</code>,网关按 <code>asset_id</code> 拼体(防止客户端挑最贵的资产刷);
<span class="badge" style="background:#eef6ee;color:#3a7">passthrough</span>
透传内部 REST 服务(OCR / 文生图 / TTS),访问 <code>/apixp/&lt;slug&gt;/&lt;路径尾部&gt;</code>,
方法/请求体/Content-Type 原样转发,上游路径 = base + 尾部。
</div>
</div>
<button class="btn-primary btn-sm" id="newApixBtn">+ 新建代理</button>
+50 -7
View File
@@ -5,8 +5,12 @@
var $ = IP.$;
// 弹窗里的表单:it 存在 = 编辑(slug 只读、Key 留空表示不改),否则 = 新建
// mode: vendor = 单一供应商收口(POST /api/v1/ai/request,网关拼体);passthrough =
// 透传内部 REST(OCR / 文生图 / TTS 这种多端点多 body 的服务),方法/请求体原样转发。
function formHtml(it) {
var edit = !!(it && it.slug);
var mode = (it && it.mode) || "vendor";
var pt = mode === "passthrough";
return '' +
'<form id="apixForm" class="grid-form up-form">' +
'<div><label>slug(对外名字)</label>' +
@@ -14,19 +18,31 @@
(edit ? 'value="' + IP.esc(it.slug) + '" readonly' : 'required') + '></div>' +
'<div><label>展示名</label>' +
'<input id="axName" type="text" placeholder="SearXNG 免费搜索" value="' + IP.esc(it ? it.name : "") + '"></div>' +
'<div class="span-all"><label>asset_id(资产标识)</label>' +
'<input id="axAsset" class="field-mono" type="text" placeholder="searxng-search" value="' + IP.esc(it ? it.asset_id : "") + '" required></div>' +
'<div class="span-all"><label>代理模式</label>' +
'<select id="axMode" class="field-mono">' +
'<option value="vendor"' + (mode === "vendor" ? " selected" : "") + '>vendor · 单一供应商收口(POST /api/v1/ai/request,网关拼体)</option>' +
'<option value="passthrough"' + (pt ? " selected" : "") + '>passthrough · 透传内部 REST(多端点多 body,方法/请求体原样转发)</option>' +
'</select></div>' +
'<div class="span-all"><label>asset_id(资产标识,passthrough 模式可留空)</label>' +
'<input id="axAsset" class="field-mono" type="text" placeholder="searxng-search" value="' + IP.esc(it ? it.asset_id : "") + '"' + (pt ? '' : ' required') + '></div>' +
'<div class="span-all"><label>供应商名称</label>' +
'<input id="axSupplier" type="text" placeholder="如 provider-x / 自建服务" value="' + IP.esc(it ? it.supplier : "") + '"></div>' +
'<div class="span-all"><label>供应商基址(如 https://supplier.example.com)</label>' +
'<input id="axBase" class="field-mono" type="text" placeholder="https://supplier.example.com" value="' + IP.esc(it ? it.base : "") + '" ' + (edit ? '' : 'required') + '></div>' +
'<div class="span-all"><label>供应商 API Key(' + (edit ? '留空 = 不修改' : '新建必填') + ')</label>' +
'<input id="axKey" class="field-mono" type="text" placeholder="ak_..." autocomplete="off" ' + (edit ? '' : 'required') + '></div>' +
'<div class="span-all"><label>供应商 API Key(' + (pt ? 'passthrough 模式下若上游不需要可留空' : (edit ? '留空 = 不修改' : '新建必填')) + ')</label>' +
'<input id="axKey" class="field-mono" type="text" placeholder="ak_..." autocomplete="off" ' + ((edit || pt) ? '' : 'required') + '></div>' +
'<div class="span-all"><label>参数名(逗号分隔,仅用于生成示例地址)</label>' +
'<input id="axParams" class="field-mono" type="text" placeholder="q" value="' + IP.esc(it ? IP.arr(it.params).join(",") : "") + '"></div>' +
'<div class="span-all"><label>说明</label>' +
'<input id="axDesc" type="text" placeholder="可选" value="' + IP.esc(it ? it.desc : "") + '"></div>' +
'<div class="span-all checkbox"><label style="margin:0"><input type="checkbox" id="axEnabled" ' + ((!edit || it.enabled) ? "checked" : "") + '> 启用</label></div>' +
(pt
? '<div class="span-all muted" style="font-size:11.5px;border-left:3px solid #6a8;padding:6px 10px;background:rgba(0,128,0,0.04)">' +
'💡 <b>passthrough</b>:调用方走 <code>/apixp/' + IP.esc(it ? it.slug : "&lt;slug&gt;") + '/&lt;尾部&gt;</code>,上游路径 = base + 尾部,' +
'方法/请求体/Content-Type 原样转发。OCR 类的 multipart/form-data 也能透传。' +
'「测试」按钮会 GET 打上游根地址验连通性。' +
'</div>'
: '') +
'</form>';
}
@@ -36,12 +52,31 @@
submitText: "保存代理",
html: formHtml(it),
onMount: function (card, close) {
// mode 切换时给个轻提示(asset_id 与 Key 的 required 会跟着变),
// 不强制挡回——保存时由后端校验,最稳的是「前端展示、后端兜底」。
var modeSel = card.querySelector("#axMode");
if (modeSel) {
modeSel.addEventListener("change", function () {
var pt = modeSel.value === "passthrough";
var hint = card.querySelector("#axModeHint");
if (hint) hint.remove();
if (pt) {
hint = document.createElement("div");
hint.id = "axModeHint";
hint.className = "muted";
hint.style.cssText = "font-size:11.5px;border-left:3px solid #6a8;padding:6px 10px;background:rgba(0,128,0,0.04);margin-top:8px";
hint.innerHTML = "💡 passthrough 模式下 asset_id 可留空,Key 可留空(内部服务免鉴权)。";
modeSel.parentNode.appendChild(hint);
}
});
}
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(),
mode: card.querySelector("#axMode").value,
name: card.querySelector("#axName").value.trim(),
supplier: card.querySelector("#axSupplier").value.trim(),
base: card.querySelector("#axBase").value.trim(),
@@ -72,6 +107,7 @@
var params = IP.arr(it.params);
// 后端 it.url 现在是纯基址(不再带 ?q=);参数只拼一次,避免 ?q=?q= 的重复
var url = it.url + (params.length ? "?" + params.map(function (p) { return p + "="; }).join("&") : "");
// passthrough 没有「参数示例」概念(路径 + 任意尾部 + query),改成「路径示例」
var example = params.length ? it.url + "?" + params[0] + "=关键词" : it.url;
var supplier = (it.supplier || "-") + " · " +
@@ -79,16 +115,23 @@
? "<code class='mono'>" + IP.esc(it.key_mask) + "</code>"
: "<span class='badge b-err'>未配置 Key</span>");
var isPt = it.mode === "passthrough";
var modeTag = isPt
? "<span class='badge' style='background:#eef6ee;color:#3a7;margin-left:6px'>passthrough</span>"
: "<span class='badge' style='background:#eee;color:#666;margin-left:6px'>vendor</span>";
return "<tr>" +
"<td><b>" + IP.esc(it.slug) + "</b>" +
"<td><b>" + IP.esc(it.slug) + "</b>" + modeTag +
(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 class='mono'>" + (it.asset_id ? IP.esc(it.asset_id) : "<span class='muted'>—</span>") + "</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>" +
"<button class='btn-sm' data-act='copy' data-url='" + IP.esc(example) + "'>复制示例</button>" +
(isPt
? "<button class='btn-sm' data-act='copy' data-url='" + IP.esc(url + "/&lt;路径尾部&gt;") + "'>复制路径示例</button>"
: "<button class='btn-sm' data-act='copy' data-url='" + IP.esc(example) + "'>复制示例</button>") +
"</div></td>" +
"<td>" + supplier + "</td>" +
"<td>" + (enabled ? "<span class='badge b-ok'>启用中</span>" : "<span class='badge b-gray'>已停用</span>") + "</td>" +