Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:memo: Enhance API documentation for forward proxy features

Yingyi / 颖逸3096f0dec99a
diff --git a/docs/API.ja.md b/docs/API.ja.md
index 5b81f7db70..ff46f12e22 100644
--- a/docs/API.ja.md
+++ b/docs/API.ja.md
@@ -80,6 +80,10 @@
* [エラーメッセージをプッシュ](#エラーメッセージをプッシュ)
* [ネットワーク](#ネットワーク)
* [フォワードプロキシ](#フォワードプロキシ)
+ * [JSONフォワードプロキシ](#JSONフォワードプロキシ)
+ * [HTTPフォワードプロキシ](#HTTPフォワードプロキシ)
+ * [WebSocketフォワードプロキシ](#WebSocketフォワードプロキシ)
+ * [EventSourceフォワードプロキシ](#EventSourceフォワードプロキシ)
* [システム](#システム)
* [起動進捗を取得](#起動進捗を取得)
* [システムバージョンを取得](#システムバージョンを取得)
@@ -92,8 +96,8 @@
### パラメータと戻り値
* エンドポイント: `http://127.0.0.1:6806`
-* すべてPOSTメソッドを使用
-* パラメータを持つインターフェースでは、パラメータはJSON文字列としてbodyに配置し、ヘッダーのContent-Typeは`application/json`とする
+* 個別に明記されていない限り、APIインターフェースはPOSTメソッドを使用します
+* JSONパラメータを受け取るインターフェースでは、パラメータはJSON文字列としてbodyに配置し、ヘッダーのContent-Typeは`application/json`とします
* 戻り値
````json
@@ -1511,6 +1515,8 @@
### フォワードプロキシ
+#### JSONフォワードプロキシ
+
* `/api/network/forwardProxy`
* パラメータ
@@ -1525,8 +1531,9 @@
"Cookie": ""
}
],
+ "redirect": true,
"payload": {},
- "payloadEncoding": "text",
+ "payloadEncoding": "json",
"responseEncoding": "text"
}
```
@@ -1535,11 +1542,12 @@
* `method`: HTTPメソッド、デフォルトは`POST`
* `timeout`: タイムアウト(ミリ秒)、デフォルトは`7000`
* `contentType`: Content-Type、デフォルトは`application/json`
- * `headers`: HTTPヘッダー
+ * `headers`: HTTPリクエストヘッダー配列。各オブジェクトのキーと値がリクエストヘッダーとして設定されます
+ * `redirect`: リダイレクトを追跡するかどうか。デフォルトは`true`で、最大2回まで追跡します。`false`に設定するとリダイレクトを追跡しません
* `payload`: HTTPペイロード、オブジェクトまたは文字列
- * `payloadEncoding`: `payload`で使用されるエンコーディングスキーム、デフォルトは`text`、選択可能な値は以下の通り
+ * `payloadEncoding`: `payload`で使用されるエンコーディングスキーム。デフォルトは`json`です。`json`は`payload`をそのまま送信し、バイナリペイロードには次のエンコード済み文字列を使用できます
- * `text`
+ * `json`
* `base64` | `base64-std`
* `base64-url`
* `base32` | `base32-std`
@@ -1567,12 +1575,13 @@
"headers": {
},
"status": 200,
- "url": "https://b3log.org/siyuan"
+ "url": "https://b3log.org/siyuan/"
}
}
```
- * `bodyEncoding`: `body`で使用されるエンコーディングスキーム、リクエストの`responseEncoding`フィールドと一致、デフォルトは`text`、選択可能な値は以下の通り
+ * `body`: レスポンス本文
+ * `bodyEncoding`: `body`で使用されるエンコーディングスキーム。リクエストの`responseEncoding`フィールドと一致します。デフォルトは`text`で、選択可能な値は以下の通り
* `text`
* `base64` | `base64-std`
@@ -1580,6 +1589,45 @@
* `base32` | `base32-std`
* `base32-hex`
* `hex`
+ * `contentType`: レスポンスヘッダー`Content-Type`
+ * `elapsed`: リクエスト所要時間(ミリ秒)
+ * `headers`: ターゲットサービスが返したレスポンスヘッダー
+ * `status`: ターゲットサービスが返したHTTPステータスコード
+ * `url`: 転送したURL
+
+#### HTTPフォワードプロキシ
+
+* `/api/network/proxy`
+* リクエストメソッド: 任意のHTTPメソッド
+* クエリパラメータ
+
+ * `u`: 必須。ターゲットの`http`または`https` URLをGoの`base64.RawURLEncoding`でエンコードした文字列です。URLセーフで、`=`パディングを含まないBase64です
+ * `h`: 任意。同じ方式でエンコードしたリクエストヘッダーJSONです。JSONの型は`map[string][]string`で、例は`{"Authorization":["Bearer token"]}`です
+ * `t`: 任意。接続タイムアウトです。Goの`time.ParseDuration`形式を使用します。例は`30s`、`1500ms`です
+* リクエスト本文: 現在のリクエスト本文をそのまま転送し、現在のリクエストの完全な`Content-Type`ヘッダーをターゲットリクエストへ転送します
+* 戻り値: ターゲットサービスのHTTPステータスコードとレスポンス本文を直接返し、`code`、`msg`、`data`ではラップしません。ターゲットのレスポンスヘッダーは`Siyuan-Proxy-`プレフィックス付きで返されます。例えば`Content-Type`は`Siyuan-Proxy-Content-Type`として返されます
+
+#### WebSocketフォワードプロキシ
+
+* `/ws/network/proxy`
+* リクエストメソッド: `GET`
+* クエリパラメータ
+
+ * `u`: 必須。ターゲットの`ws`または`wss` URLをGoの`base64.RawURLEncoding`でエンコードした文字列です
+ * `h`: 任意。同じ方式でエンコードしたハンドシェイクリクエストヘッダーJSONです。JSONの型は`map[string][]string`です
+ * `t`: 任意。ハンドシェイクタイムアウトです。Goの`time.ParseDuration`形式を使用します。例は`30s`、`1500ms`です
+* 戻り値: WebSocketへアップグレードした後、メッセージを双方向に転送します。ターゲットのハンドシェイクレスポンスヘッダーは`Siyuan-Proxy-`プレフィックス付きで返されます
+
+#### EventSourceフォワードプロキシ
+
+* `/es/network/proxy`
+* リクエストメソッド: `GET`
+* クエリパラメータ
+
+ * `u`: 必須。ターゲットの`http`または`https` URLをGoの`base64.RawURLEncoding`でエンコードした文字列です
+ * `h`: 任意。同じ方式でエンコードしたリクエストヘッダーJSONです。JSONの型は`map[string][]string`です
+ * `t`: 任意。接続タイムアウトです。Goの`time.ParseDuration`形式を使用します。例は`30s`、`1500ms`です
+* 戻り値: ターゲットサービスのHTTPステータスコードとレスポンス本文を直接ストリーミングし、`code`、`msg`、`data`ではラップしません。リクエストヘッダーに`Accept`がない場合は、`text/event-stream`を自動的に使用します。ターゲットのレスポンスヘッダーは`Siyuan-Proxy-`プレフィックス付きで返されます
## システム
diff --git a/docs/API.md b/docs/API.md
index b69d459495..3fcb7bf5f7 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -80,6 +80,10 @@
* [Push error message](#Push-error-message)
* [Network](#Network)
* [Forward proxy](#Forward-proxy)
+ * [JSON forward proxy](#JSON-forward-proxy)
+ * [HTTP forward proxy](#HTTP-forward-proxy)
+ * [WebSocket forward proxy](#WebSocket-forward-proxy)
+ * [EventSource forward proxy](#EventSource-forward-proxy)
* [System](#System)
* [Get boot progress](#Get-boot-progress)
* [Get system version](#Get-system-version)
@@ -92,9 +96,8 @@
### Parameters and return values
* Endpoint: `http://127.0.0.1:6806`
-* Both are POST methods
-* An interface with parameters is required, the parameter is a JSON string, placed in the body, and the header
- Content-Type is `application/json`
+* Unless otherwise stated, API interfaces use the POST method
+* For interfaces that take JSON parameters, the parameter is a JSON string placed in the body, and the header Content-Type is `application/json`
* Return value
````json
@@ -1520,6 +1523,8 @@ Note: To ensure data security, access to this interface is prohibited in Publish
### Forward proxy
+#### JSON forward proxy
+
* `/api/network/forwardProxy`
* Parameters
@@ -1534,8 +1539,9 @@ Note: To ensure data security, access to this interface is prohibited in Publish
"Cookie": ""
}
],
+ "redirect": true,
"payload": {},
- "payloadEncoding": "text",
+ "payloadEncoding": "json",
"responseEncoding": "text"
}
```
@@ -1544,18 +1550,18 @@ Note: To ensure data security, access to this interface is prohibited in Publish
* `method`: HTTP method, default is `POST`
* `timeout`: timeout in milliseconds, default is `7000`
* `contentType`: Content-Type, default is `application/json`
- * `headers`: HTTP headers
+ * `headers`: HTTP request header array; each key-value pair in the objects is set as a request header
+ * `redirect`: Whether to follow redirects, default is `true`, following up to 2 redirects; set it to `false` to disable redirects
* `payload`: HTTP payload, object or string
- * `payloadEncoding`: The encoding scheme used by `pyaload`, default is `text`, optional values are as follows
+ * `payloadEncoding`: The encoding scheme used by `payload`, default is `json`; `json` sends `payload` directly, and binary payloads can use the following encoded strings
- * `text`
+ * `json`
* `base64` | `base64-std`
* `base64-url`
* `base32` | `base32-std`
* `base32-hex`
* `hex`
- * `responseEncoding`: The encoding scheme used by `body` in response data, default is `text`, optional values are as
- follows
+ * `responseEncoding`: The encoding scheme used by `body` in response data, default is `text`, optional values are as follows
* `text`
* `base64` | `base64-std`
@@ -1577,13 +1583,13 @@ Note: To ensure data security, access to this interface is prohibited in Publish
"headers": {
},
"status": 200,
- "url": "https://b3log.org/siyuan"
+ "url": "https://b3log.org/siyuan/"
}
}
```
- * `bodyEncoding`: The encoding scheme used by `body`, is consistent with field `responseEncoding` in request,
- default is `text`, optional values are as follows
+ * `body`: Response body
+ * `bodyEncoding`: The encoding scheme used by `body`; it is consistent with the `responseEncoding` field in the request, default is `text`, optional values are as follows
* `text`
* `base64` | `base64-std`
@@ -1591,6 +1597,45 @@ Note: To ensure data security, access to this interface is prohibited in Publish
* `base32` | `base32-std`
* `base32-hex`
* `hex`
+ * `contentType`: Response header `Content-Type`
+ * `elapsed`: Request duration in milliseconds
+ * `headers`: Response headers returned by the target service
+ * `status`: HTTP status code returned by the target service
+ * `url`: Forwarded URL
+
+#### HTTP forward proxy
+
+* `/api/network/proxy`
+* Request method: any HTTP method
+* Query parameters
+
+ * `u`: Required, target `http` or `https` URL encoded with Go `base64.RawURLEncoding`, which is URL-safe Base64 without `=` padding
+ * `h`: Optional, request header JSON encoded in the same way; the JSON type is `map[string][]string`, for example `{"Authorization":["Bearer token"]}`
+ * `t`: Optional, connection timeout in Go `time.ParseDuration` format, for example `30s` or `1500ms`
+* Request body: Forwards the current request body as-is, and forwards the current request's full `Content-Type` header to the target request
+* Return value: Directly returns the target service HTTP status code and response body without wrapping them in `code`, `msg`, or `data`; target response headers are returned with the `Siyuan-Proxy-` prefix, for example `Content-Type` is returned as `Siyuan-Proxy-Content-Type`
+
+#### WebSocket forward proxy
+
+* `/ws/network/proxy`
+* Request method: `GET`
+* Query parameters
+
+ * `u`: Required, target `ws` or `wss` URL encoded with Go `base64.RawURLEncoding`
+ * `h`: Optional, handshake request header JSON encoded in the same way; the JSON type is `map[string][]string`
+ * `t`: Optional, handshake timeout in Go `time.ParseDuration` format, for example `30s` or `1500ms`
+* Return value: Upgrades to WebSocket and then forwards messages bidirectionally; target handshake response headers are returned with the `Siyuan-Proxy-` prefix
+
+#### EventSource forward proxy
+
+* `/es/network/proxy`
+* Request method: `GET`
+* Query parameters
+
+ * `u`: Required, target `http` or `https` URL encoded with Go `base64.RawURLEncoding`
+ * `h`: Optional, request header JSON encoded in the same way; the JSON type is `map[string][]string`
+ * `t`: Optional, connection timeout in Go `time.ParseDuration` format, for example `30s` or `1500ms`
+* Return value: Directly streams the target service HTTP status code and response body without wrapping them in `code`, `msg`, or `data`; if the request headers do not include `Accept`, `text/event-stream` is used automatically; target response headers are returned with the `Siyuan-Proxy-` prefix
## System
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index ea8450cece..2f0110ebde 100644
--- a/docs/API.zh-CN.md
+++ b/docs/API.zh-CN.md
@@ -80,6 +80,10 @@
* [推送报错消息](#推送报错消息)
* [网络](#网络)
* [正向代理](#正向代理)
+ * [JSON 正向代理](#JSON-正向代理)
+ * [HTTP 正向代理](#HTTP-正向代理)
+ * [WebSocket 正向代理](#WebSocket-正向代理)
+ * [EventSource 正向代理](#EventSource-正向代理)
* [系统](#系统)
* [获取启动进度](#获取启动进度)
* [获取系统版本](#获取系统版本)
@@ -92,8 +96,8 @@
### 参数和返回值
* 端点:`http://127.0.0.1:6806`
-* 均是 POST 方法
-* 需要带参的接口,参数为 JSON 字符串,放置到 body 里,标头 Content-Type 为 `application/json`
+* 除非接口中另有说明,否则 API 接口均使用 POST 方法
+* 使用 JSON 入参的接口,参数为 JSON 字符串,放置到 body 里,标头 Content-Type 为 `application/json`
* 返回值
```json
@@ -1511,6 +1515,8 @@
### 正向代理
+#### JSON 正向代理
+
* `/api/network/forwardProxy`
* 参数
@@ -1525,21 +1531,23 @@
"Cookie": ""
}
],
+ "redirect": true,
"payload": {},
- "payloadEncoding": "text",
+ "payloadEncoding": "json",
"responseEncoding": "text"
}
```
* `url`:转发的 URL
- * `method`:HTTP 方法,默认为 `GET`
+ * `method`:HTTP 方法,默认为 `POST`
* `timeout`:超时时间,单位为毫秒,默认为 `7000` 毫秒
* `contentType`:HTTP Content-Type,默认为 `application/json`
- * `headers`:HTTP 请求标头
- * `payload`:HTTP 请求体,对象或者是字符串
- * `payloadEncoding`:`pyaload` 所使用的编码方案,默认为 `text`,可选值如下所示
+ * `headers`:HTTP 请求标头数组,每个对象中的键值对都会设置为请求标头
+ * `redirect`:是否跟随重定向,默认为 `true`,最多跟随 2 次;设置为 `false` 时不跟随重定向
+ * `payload`:HTTP 请求体,可以是对象或者字符串
+ * `payloadEncoding`:`payload` 所使用的编码方案,默认为 `json`;`json` 会直接发送 `payload`,二进制请求体可使用以下编码字符串
- * `text`
+ * `json`
* `base64` | `base64-std`
* `base64-url`
* `base32` | `base32-std`
@@ -1567,11 +1575,12 @@
"headers": {
},
"status": 200,
- "url": "https://b3log.org/siyuan"
+ "url": "https://b3log.org/siyuan/"
}
}
```
+ * `body`:响应体
* `bodyEncoding`:`body` 所使用的编码方案,与请求中 `responseEncoding` 字段一致,默认为 `text`,可能的值如下所示
* `text`
@@ -1580,6 +1589,45 @@
* `base32` | `base32-std`
* `base32-hex`
* `hex`
+ * `contentType`:响应标头 `Content-Type`
+ * `elapsed`:请求耗时,单位为毫秒
+ * `headers`:目标服务返回的响应标头
+ * `status`:目标服务返回的 HTTP 状态码
+ * `url`:转发的 URL
+
+#### HTTP 正向代理
+
+* `/api/network/proxy`
+* 请求方法:任意 HTTP 方法
+* 查询参数
+
+ * `u`:必填,目标 `http` 或 `https` URL 使用 Go `base64.RawURLEncoding` 编码后的字符串,也就是 URL 安全且不带 `=` 补位的 Base64
+ * `h`:可选,请求标头 JSON 使用同样方式编码后的字符串,JSON 类型为 `map[string][]string`,例如 `{"Authorization":["Bearer token"]}`
+ * `t`:可选,连接超时时间,使用 Go `time.ParseDuration` 格式,例如 `30s`、`1500ms`
+* 请求体:原样转发当前请求体,当前请求的完整 `Content-Type` 标头会转发到目标请求
+* 返回值:直接返回目标服务的 HTTP 状态码和响应体,不包裹 `code`、`msg`、`data`;目标服务响应标头会添加 `Siyuan-Proxy-` 前缀后返回,例如 `Content-Type` 会返回为 `Siyuan-Proxy-Content-Type`
+
+#### WebSocket 正向代理
+
+* `/ws/network/proxy`
+* 请求方法:`GET`
+* 查询参数
+
+ * `u`:必填,目标 `ws` 或 `wss` URL 使用 Go `base64.RawURLEncoding` 编码后的字符串
+ * `h`:可选,握手请求标头 JSON 使用同样方式编码后的字符串,JSON 类型为 `map[string][]string`
+ * `t`:可选,握手超时时间,使用 Go `time.ParseDuration` 格式,例如 `30s`、`1500ms`
+* 返回值:升级为 WebSocket 后双向转发消息;目标服务握手响应标头会添加 `Siyuan-Proxy-` 前缀后返回
+
+#### EventSource 正向代理
+
+* `/es/network/proxy`
+* 请求方法:`GET`
+* 查询参数
+
+ * `u`:必填,目标 `http` 或 `https` URL 使用 Go `base64.RawURLEncoding` 编码后的字符串
+ * `h`:可选,请求标头 JSON 使用同样方式编码后的字符串,JSON 类型为 `map[string][]string`
+ * `t`:可选,连接超时时间,使用 Go `time.ParseDuration` 格式,例如 `30s`、`1500ms`
+* 返回值:直接流式返回目标服务的 HTTP 状态码和响应体,不包裹 `code`、`msg`、`data`;如果请求标头中没有 `Accept`,会自动使用 `text/event-stream`;目标服务响应标头会添加 `Siyuan-Proxy-` 前缀后返回
## 系统
diff --git a/kernel/api/network.go b/kernel/api/network.go
index 5b8fabd4f8..abc565b10c 100644
--- a/kernel/api/network.go
+++ b/kernel/api/network.go
@@ -365,18 +365,23 @@ func parseForwardProxyParams(c *gin.Context) (parsedURL *url.URL, headers *http.
h := http.Header{}
headers = &h
hParam := c.Query("h")
- if hParam == "" {
- return
- }
- hBytes, decErr := base64.RawURLEncoding.DecodeString(hParam)
- if decErr != nil {
- err = fmt.Errorf("decode [h] failed: %s", decErr.Error())
- return
- }
- var record map[string][]string
- if jsonErr := json.Unmarshal(hBytes, &record); jsonErr != nil {
- err = fmt.Errorf("parse [h] failed: %s", jsonErr.Error())
- return
+ if hParam != "" {
+ hBytes, decErr := base64.RawURLEncoding.DecodeString(hParam)
+ if decErr != nil {
+ err = fmt.Errorf("decode [h] failed: %s", decErr.Error())
+ return
+ }
+ var record map[string][]string
+ if jsonErr := json.Unmarshal(hBytes, &record); jsonErr != nil {
+ err = fmt.Errorf("parse [h] failed: %s", jsonErr.Error())
+ return
+ }
+
+ for k, vs := range record {
+ for _, v := range vs {
+ h.Add(k, v)
+ }
+ }
}
timeout = 30 * time.Second
@@ -390,11 +395,6 @@ func parseForwardProxyParams(c *gin.Context) (parsedURL *url.URL, headers *http.
}
}
- for k, vs := range record {
- for _, v := range vs {
- h.Add(k, v)
- }
- }
return
}
@@ -439,8 +439,10 @@ func httpProxy(c *gin.Context) {
}
proxyReq.ContentLength = c.Request.ContentLength
- if c.ContentType() != "" {
- proxyReq.Header.Set("Content-Type", c.ContentType())
+
+ contentType := c.Request.Header.Get("Content-Type")
+ if contentType != "" {
+ proxyReq.Header.Set("Content-Type", contentType)
}
for k, vs := range *targetHeaders {