Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(im): support reverse proxy for feishu websocket long connection (#2550)

Greenplumwine755243d61cbd
diff --git "a/docs/IM\351\233\206\346\210\220\345\274\200\345\217\221\346\226\207\346\241\243.md" "b/docs/IM\351\233\206\346\210\220\345\274\200\345\217\221\346\226\207\346\241\243.md"
index 0f328e1ca..f961be0a5 100644
--- "a/docs/IM\351\233\206\346\210\220\345\274\200\345\217\221\346\226\207\346\241\243.md"
+++ "b/docs/IM\351\233\206\346\210\220\345\274\200\345\217\221\346\226\207\346\241\243.md"
@@ -240,6 +240,147 @@ IM 渠道绑定到 Agent,一个 Agent 可接入多个 IM 渠道,所有配置
---
+#### API Base URL(可选,内网代理)
+
+渠道配置里的 **API Base URL** 是可选字段,用于让 WeKnora 通过反向代理访问飞书开放平台:
+
+- **服务器能直连外网** → **留空**即可,默认访问 `https://open.feishu.cn`
+- **服务器需要代理才能访问外网**(如内网部署)→ 填写反向代理地址(如 nginx,`http://10.0.0.1:8080/feishu`)
+
+该地址同时覆盖飞书 IM 的所有出站调用,一个字段统一管控:
+
+| 出站 | 说明 |
+|---|---|
+| WebSocket bootstrap | SDK 拿 wss 地址的请求 |
+| wss 长连接 | 收消息的 WebSocket(经改写后的地址) |
+| HTTP API | token、发消息、下载文件、CardKit 流式卡片 |
+
+**nginx 反向代理要点**(WebSocket 模式,已生产验证):
+
+飞书 bootstrap 返回的 ws 地址 host 是 **`msg-frontier.feishu.cn`**(长连接专用域名,**不是 `open.feishu.cn`**),path 是 `/ws/v2`。因此 nginx 需要**三个 location**,upstream 不同不能混:
+
+| location | 匹配 | upstream | 作用 |
+|---|---|---|---|
+| `= /<前缀>/callback/ws/endpoint` | bootstrap POST | `open.feishu.cn` | 拿 ws 地址 + `sub_filter` 改写 |
+| `/<前缀>/ws/` | ws dial(GET+Upgrade) | **`msg-frontier.feishu.cn`** | WebSocket 长连接反代 |
+| `/<前缀>/` | OpenAPI HTTP | `open.feishu.cn` | token/发消息/下载文件/卡片 |
+
+- `sub_filter` 替换的是 `wss://msg-frontier.feishu.cn`(不是 `open.feishu.cn`),改成 `ws://<nginx>/<前缀>`,WeKnora 才会明文回连 nginx
+- ws dial 的 upstream 必须是 `msg-frontier.feishu.cn`,若误指 `open.feishu.cn` 会 404(open.feishu.cn 不处理 `/ws/v2`)
+- `rewrite` 模式要与 location 前缀一致(如 `location /weknora/feishu/ws/` 配 `rewrite ^/weknora/feishu/(.*)$ /$1 break`),否则前缀不剥离 -> 飞书 404 -> ws 握手失败
+- `map $http_upgrade $connection_upgrade` 区分 POST(Connection=close)与 ws(Connection=upgrade),三者共存
+- 不需要 nginx 支持 CONNECT
+
+以下为生产验证通过的完整配置(按实际调整地址与前缀):
+
+```nginx
+map $http_upgrade $connection_upgrade {
+ default upgrade;
+ '' close;
+}
+
+server {
+ listen 80;
+ server_name <能访问外网的Nginx 主机IP>;
+
+ # ① bootstrap:POST /callback/ws/endpoint -> open.feishu.cn + sub_filter 改写 wss URL
+ location = /weknora/feishu/callback/ws/endpoint {
+ resolver 114.114.114.114 8.8.8.8 valid=300s ipv6=off;
+ set $feishu_host "open.feishu.cn";
+ rewrite ^/weknora/feishu/(.*)$ /$1 break;
+ proxy_pass https://$feishu_host;
+
+ proxy_ssl_server_name on;
+ proxy_ssl_name open.feishu.cn;
+ proxy_ssl_protocols TLSv1.2 TLSv1.3;
+ proxy_ssl_verify off;
+ proxy_set_header Host open.feishu.cn;
+ 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_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection $connection_upgrade;
+
+ # 禁 gzip,sub_filter 才能改写 JSON
+ proxy_set_header Accept-Encoding "";
+ # 飞书下发的 wss host 是 msg-frontier.feishu.cn(长连接专用域名,非 open.feishu.cn)
+ sub_filter 'wss://msg-frontier.feishu.cn' 'ws://<能访问外网的Nginx 主机IP>/weknora/feishu';
+ sub_filter_once off;
+ sub_filter_types application/json;
+ }
+
+ # ② ws dial:WebSocket 长连接 -> msg-frontier.feishu.cn(upstream 不是 open.feishu.cn!)
+ location /weknora/feishu/ws/ {
+ resolver 114.114.114.114 8.8.8.8 valid=300s ipv6=off;
+ set $feishu_host "msg-frontier.feishu.cn";
+ rewrite ^/weknora/feishu/(.*)$ /$1 break;
+ proxy_pass https://$feishu_host;
+
+ proxy_ssl_server_name on;
+ proxy_ssl_name msg-frontier.feishu.cn;
+ proxy_ssl_protocols TLSv1.2 TLSv1.3;
+ proxy_ssl_verify off;
+ proxy_set_header Host msg-frontier.feishu.cn;
+ 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_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection $connection_upgrade;
+
+ proxy_buffering off;
+ proxy_cache off;
+ proxy_request_buffering off;
+ chunked_transfer_encoding on;
+
+ proxy_connect_timeout 60s;
+ proxy_send_timeout 3600s;
+ proxy_read_timeout 3600s;
+ send_timeout 3600s;
+
+ client_max_body_size 0;
+ proxy_max_temp_file_size 0;
+ }
+
+ # ③ OpenAPI HTTP:token/发消息/下载文件/CardKit -> open.feishu.cn
+ location /weknora/feishu/ {
+ resolver 114.114.114.114 8.8.8.8 valid=300s ipv6=off;
+ set $feishu_host "open.feishu.cn";
+ rewrite ^/weknora/feishu/(.*)$ /$1 break;
+ proxy_pass https://$feishu_host;
+
+ proxy_ssl_server_name on;
+ proxy_ssl_name open.feishu.cn;
+ proxy_ssl_protocols TLSv1.2 TLSv1.3;
+ proxy_ssl_verify off;
+ proxy_set_header Host open.feishu.cn;
+ 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_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection $connection_upgrade;
+
+ proxy_buffering off;
+ proxy_read_timeout 3600s;
+ proxy_send_timeout 3600s;
+ client_max_body_size 0;
+ }
+}
+```
+
+> 验证 sub_filter 生效:`curl -s http://127.0.0.1/weknora/feishu/callback/ws/endpoint -X POST -H 'Content-Type: application/json' -d '{"AppID":"xxx","AppSecret":"xxx"}'`,返回的 `data.URL` 应为 `ws://<能访问外网的Nginx 主机IP>/weknora/feishu/ws/v2?...`(不再是 `wss://msg-frontier.feishu.cn/...`)。WeKnora 日志出现 `[IM] Feishu WebSocket connected successfully` 即长连接建立。
+
+**SSRF 白名单**:若 `api_base_url` 是内网地址,需把主机名加入 `SSRF_WHITELIST` 环境变量,否则 SSRF 防护会拦截。
+
+> Webhook 模式下,`api_base_url` 只影响出站 HTTP API;飞书回调 WeKnora 的入站路径不受影响(回调地址在渠道卡片上单独配置)。
+> Lark 国际版同理,只是默认域名换成 `https://open.larksuite.com`。
+
+---
+
### Lark 接入
Lark 是飞书的国际版。两者是同一产品部署在两朵相互隔离的云上,**IM 的 API 接口、事件结构、
diff --git a/frontend/src/components/IMChannelPanel.vue b/frontend/src/components/IMChannelPanel.vue
index f4ac1475b..67fb6dcd4 100644
--- a/frontend/src/components/IMChannelPanel.vue
+++ b/frontend/src/components/IMChannelPanel.vue
@@ -314,6 +314,11 @@
<label class="form-label">App Secret</label>
<t-input v-model="formData.credentials.app_secret" type="password" placeholder="App Secret" />
</div>
+ <div class="form-item">
+ <label class="form-label">Base URL</label>
+ <t-input v-model="formData.credentials.api_base_url" placeholder="https://open.feishu.cn" />
+ <p class="form-desc">{{ $t('agentEditor.im.feishuAPIBaseURLHint') }}</p>
+ </div>
<template v-if="formData.mode === 'webhook'">
<div class="form-item">
<label class="form-label">Verification Token</label>
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 4a586d0b3..18ab05d6a 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -5209,6 +5209,7 @@ export default {
consoleTip: 'to get credentials',
wecomWSEndpointHint: 'Optional. For private WeCom deployments, enter a custom WebSocket address. Leave empty to use the default public cloud endpoint. For internal network addresses, add the hostname to the SSRF_WHITELIST env var.',
wecomAPIBaseURLHint: 'Optional. For private WeCom deployments, enter a custom API base URL. Leave empty to use the default public cloud endpoint. For internal network addresses, add the hostname to the SSRF_WHITELIST env var.',
+ feishuAPIBaseURLHint: 'Optional. Leave empty if the server can reach the internet directly; if a proxy is required to access Feishu, enter the reverse proxy URL (e.g. nginx, http://host:port). For internal network addresses, add the hostname to the SSRF_WHITELIST env var.',
fileKnowledgeBase: 'File Storage Knowledge Base',
fileKnowledgeBasePlaceholder: 'Select a knowledge base (optional)',
fileKnowledgeBaseHint: 'When configured, files sent by users will be automatically saved to this knowledge base',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 5ade38b47..14418020c 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -990,6 +990,7 @@ export default {
consoleTip: '자격 증명 정보를 가져오세요',
wecomWSEndpointHint: '선택 사항. 프라이빗 WeCom 배포 시 사용자 정의 WebSocket 주소를 입력하세요. 비워두면 기본 퍼블릭 클라우드 주소를 사용합니다. 내부 네트워크 주소의 경우 SSRF_WHITELIST 환경 변수에 호스트명을 추가하세요.',
wecomAPIBaseURLHint: '선택 사항. 프라이빗 WeCom 배포 시 사용자 정의 API 기본 URL을 입력하세요. 비워두면 기본 퍼블릭 클라우드 주소를 사용합니다. 내부 네트워크 주소의 경우 SSRF_WHITELIST 환경 변수에 호스트명을 추가하세요.',
+ feishuAPIBaseURLHint: '선택 사항. 서버가 외부 인터넷에 직접 연결 가능하면 비워두세요. 프록시를 통해서만 접근 가능한 경우 역방향 프록시 URL(예: nginx, http://host:port)을 입력하세요. 내부 네트워크 주소는 SSRF_WHITELIST 환경 변수에 호스트명을 추가하세요.',
fileKnowledgeBase: '파일 저장 지식 베이스',
fileKnowledgeBasePlaceholder: '지식 베이스 선택 (선택 사항)',
fileKnowledgeBaseHint: '설정 시 사용자가 보낸 파일이 자동으로 해당 지식 베이스에 저장됩니다',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 8255f2179..c10b317fb 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -990,6 +990,7 @@ export default {
consoleTip: 'для получения учётных данных',
wecomWSEndpointHint: 'Необязательно. Для приватного развёртывания WeCom укажите пользовательский адрес WebSocket. Оставьте пустым для публичного облака. Для адресов внутренней сети добавьте имя хоста в переменную SSRF_WHITELIST.',
wecomAPIBaseURLHint: 'Необязательно. Для приватного развёртывания WeCom укажите пользовательский базовый URL API. Оставьте пустым для публичного облака. Для адресов внутренней сети добавьте имя хоста в переменную SSRF_WHITELIST.',
+ feishuAPIBaseURLHint: 'Необязательно. Оставьте пустым, если сервер имеет прямой доступ в интернет; если для доступа к Feishu требуется прокси, укажите URL обратного прокси (например, nginx, http://host:port). Для адресов внутренней сети добавьте имя хоста в переменную SSRF_WHITELIST.',
fileKnowledgeBase: 'База знаний для файлов',
fileKnowledgeBasePlaceholder: 'Выберите базу знаний (необязательно)',
fileKnowledgeBaseHint: 'При настройке файлы, отправленные пользователями, автоматически сохраняются в эту базу знаний',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index d8fa881b2..130d26d30 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -992,6 +992,7 @@ export default {
consoleTip: '前往获取凭证信息',
wecomWSEndpointHint: '可选,私有化部署时填写自定义 WebSocket 地址,留空则使用默认公有云地址。内网地址需将域名加入 SSRF_WHITELIST 环境变量',
wecomAPIBaseURLHint: '可选,私有化部署时填写自定义 API 地址,留空则使用默认公有云地址。内网地址需将域名加入 SSRF_WHITELIST 环境变量',
+ feishuAPIBaseURLHint: '可选。若服务器能直连外网则留空;若需通过代理才能访问飞书,填写反向代理地址(如 nginx,http://host:port)。内网地址需将域名加入 SSRF_WHITELIST 环境变量',
fileKnowledgeBase: '文件保存知识库',
fileKnowledgeBasePlaceholder: '选择知识库(可选)',
fileKnowledgeBaseHint: '配置后,用户发送的文件将自动保存到该知识库中',
diff --git a/internal/im/feishu/adapter.go b/internal/im/feishu/adapter.go
index bc5902fb1..6b6d124cc 100644
--- a/internal/im/feishu/adapter.go
+++ b/internal/im/feishu/adapter.go
@@ -24,6 +24,7 @@ import (
"io"
"mime/multipart"
"net/http"
+ "net/url"
"regexp"
"strings"
"sync"
@@ -52,6 +53,11 @@ type Adapter struct {
verificationToken string
encryptKey string
+ // apiBaseURL overrides the region's Open Platform API origin. Empty defaults
+ // to region.OpenBaseURL; set to a reverse-proxy origin for private/internal
+ // deployments that cannot reach open.feishu.cn directly.
+ apiBaseURL string
+
// Token cache
tokenMu sync.Mutex
tokenCache string
@@ -59,7 +65,16 @@ type Adapter struct {
}
// NewAdapter creates a new adapter for the given region (RegionFeishu or RegionLark).
-func NewAdapter(region Region, appID, appSecret, verificationToken, encryptKey string) *Adapter {
+// apiBaseURL overrides the Open Platform API origin (empty uses the region
+// default); it is validated for scheme and SSRF safety before use.
+func NewAdapter(region Region, appID, appSecret, verificationToken, encryptKey, apiBaseURL string) (*Adapter, error) {
+ apiBaseURL = strings.TrimRight(strings.TrimSpace(apiBaseURL), "/")
+ if err := validateAPIBaseURL(apiBaseURL, region.OpenBaseURL); err != nil {
+ return nil, err
+ }
+ if apiBaseURL == "" {
+ apiBaseURL = region.OpenBaseURL
+ }
startStreamReaper()
return &Adapter{
region: region,
@@ -67,13 +82,35 @@ func NewAdapter(region Region, appID, appSecret, verificationToken, encryptKey s
appSecret: appSecret,
verificationToken: verificationToken,
encryptKey: encryptKey,
+ apiBaseURL: apiBaseURL,
+ }, nil
+}
+
+// validateAPIBaseURL checks that a custom Feishu/Lark API base URL uses an
+// http(s) scheme and passes SSRF validation. Empty or the region default is
+// allowed without further checks. Mirrors wecom.validateEndpointURL but allows
+// plain http for internal-network reverse proxies that terminate TLS at nginx.
+func validateAPIBaseURL(endpoint, defaultEndpoint string) error {
+ if endpoint == "" || endpoint == defaultEndpoint {
+ return nil
}
+ u, err := url.Parse(endpoint)
+ if err != nil {
+ return fmt.Errorf("invalid api_base_url: %w", err)
+ }
+ if u.Scheme != "http" && u.Scheme != "https" {
+ return fmt.Errorf("api_base_url must use http(s):// scheme, got %s://", u.Scheme)
+ }
+ if err := utils.ValidateURLForSSRF(endpoint); err != nil {
+ return fmt.Errorf("%w (for private deployments on internal networks, add the hostname to SSRF_WHITELIST)", err)
+ }
+ return nil
}
// api builds an Open Platform API URL on this adapter's cloud. path is a format
// string beginning with "/open-apis/"; args fill its verbs.
func (a *Adapter) api(path string, args ...any) string {
- return a.region.OpenBaseURL + fmt.Sprintf(path, args...)
+ return a.apiBaseURL + fmt.Sprintf(path, args...)
}
// startStreamReaper starts a background goroutine (once) that periodically
diff --git a/internal/im/feishu/factory.go b/internal/im/feishu/factory.go
index b40501cec..c9ef1c4a7 100644
--- a/internal/im/feishu/factory.go
+++ b/internal/im/feishu/factory.go
@@ -25,9 +25,14 @@ func NewFactory(region Region) im.AdapterFactory {
appSecret := im.GetString(creds, "app_secret")
verificationToken := im.GetString(creds, "verification_token")
encryptKey := im.GetString(creds, "encrypt_key")
+ apiBaseURL := im.GetString(creds, "api_base_url")
- // Always create the HTTP adapter (needed for SendReply in both modes)
- adapter := NewAdapter(region, appID, appSecret, verificationToken, encryptKey)
+ // Always create the HTTP adapter (needed for SendReply in both modes).
+ // apiBaseURL is validated here; an invalid value fails the channel.
+ adapter, err := NewAdapter(region, appID, appSecret, verificationToken, encryptKey, apiBaseURL)
+ if err != nil {
+ return nil, nil, fmt.Errorf("create %s adapter: %w", region.Platform, err)
+ }
mode := im.ResolveMode(channel, "websocket")
@@ -36,7 +41,7 @@ func NewFactory(region Region) im.AdapterFactory {
return adapter, nil, nil
case "websocket":
- client := NewLongConnClient(region, appID, appSecret, msgHandler)
+ client := NewLongConnClient(region, appID, appSecret, apiBaseURL, msgHandler)
wsCtx, wsCancel := context.WithCancel(context.Background())
go func() {
diff --git a/internal/im/feishu/longconn.go b/internal/im/feishu/longconn.go
index 342f42b1d..408733983 100644
--- a/internal/im/feishu/longconn.go
+++ b/internal/im/feishu/longconn.go
@@ -24,8 +24,10 @@ type LongConnClient struct {
}
// NewLongConnClient creates a long connection client on the given region's cloud.
+// apiBaseURL overrides the SDK's bootstrap domain (empty uses the region
+// default); set it to a reverse-proxy origin for private/internal deployments.
// When a message arrives, it converts it to IncomingMessage and calls handler.
-func NewLongConnClient(region Region, appID, appSecret string, handler MessageHandler) *LongConnClient {
+func NewLongConnClient(region Region, appID, appSecret, apiBaseURL string, handler MessageHandler) *LongConnClient {
// Long connection mode does not require verificationToken or encryptKey;
// those are only used for webhook signature verification and decryption.
eventHandler := dispatcher.NewEventDispatcher("", "").
@@ -39,13 +41,19 @@ func NewLongConnClient(region Region, appID, appSecret string, handler MessageHa
sdkLogger := &feishuLoggerAdapter{region: region, appID: appID}
- // WithDomain points the SDK at the region's cloud. It defaults to
- // open.feishu.cn, so Lark apps would otherwise fail to authenticate.
+ apiBaseURL = strings.TrimRight(strings.TrimSpace(apiBaseURL), "/")
+ if apiBaseURL == "" {
+ apiBaseURL = region.OpenBaseURL
+ }
+
+ // WithDomain points the SDK at the region's cloud (open.feishu.cn by
+ // default). apiBaseURL overrides it for deployments that reach Feishu
+ // through a reverse proxy.
wsClient := larkws.NewClient(appID, appSecret,
larkws.WithEventHandler(eventHandler),
larkws.WithAutoReconnect(true),
larkws.WithLogger(sdkLogger),
- larkws.WithDomain(region.OpenBaseURL),
+ larkws.WithDomain(apiBaseURL),
)
return &LongConnClient{region: region, appID: appID, wsClient: wsClient}
diff --git a/internal/im/feishu/region_test.go b/internal/im/feishu/region_test.go
index 8671927e6..53f1dc9f8 100644
--- a/internal/im/feishu/region_test.go
+++ b/internal/im/feishu/region_test.go
@@ -55,7 +55,7 @@ func TestAdapterAPI_UsesRegionHost(t *testing.T) {
{RegionLark, "https://open.larksuite.com/open-apis/"},
}
for _, c := range cases {
- a := NewAdapter(c.region, "cli_app", "secret", "", "")
+ a, _ := NewAdapter(c.region, "cli_app", "secret", "", "", "")
got := a.api("/open-apis/im/v1/messages/%s/reply", "om_1")
want := c.wantPrefix + "im/v1/messages/om_1/reply"
@@ -71,14 +71,65 @@ func TestAdapterAPI_UsesRegionHost(t *testing.T) {
}
func TestAdapterPlatform_FollowsRegion(t *testing.T) {
- if got := NewAdapter(RegionFeishu, "a", "b", "", "").Platform(); got != im.PlatformFeishu {
+ aFeishu, _ := NewAdapter(RegionFeishu, "a", "b", "", "", "")
+ if got := aFeishu.Platform(); got != im.PlatformFeishu {
t.Errorf("Feishu adapter Platform() = %q, want %q", got, im.PlatformFeishu)
}
- if got := NewAdapter(RegionLark, "a", "b", "", "").Platform(); got != im.PlatformLark {
+ aLark, _ := NewAdapter(RegionLark, "a", "b", "", "", "")
+ if got := aLark.Platform(); got != im.PlatformLark {
t.Errorf("Lark adapter Platform() = %q, want %q", got, im.PlatformLark)
}
}
+// A custom api_base_url overrides the region's Open Platform host, so internal
+// deployments can route Feishu API calls through a reverse proxy.
+func TestAdapterAPI_BaseURLOverride(t *testing.T) {
+ a := &Adapter{apiBaseURL: "https://feishu-proxy.example.internal"}
+ got := a.api("/open-apis/im/v1/messages/%s/reply", "om_1")
+ want := "https://feishu-proxy.example.internal/open-apis/im/v1/messages/om_1/reply"
+ if got != want {
+ t.Errorf("override api() = %q, want %q", got, want)
+ }
+}
+
+// NewAdapter falls back to the region default when api_base_url is empty, and
+// the region default itself passes validation (no SSRF check on the default).
+func TestNewAdapter_FallbackAndTrim(t *testing.T) {
+ a, err := NewAdapter(RegionFeishu, "a", "b", "", "", "")
+ if err != nil {
+ t.Fatalf("NewAdapter empty api_base_url: %v", err)
+ }
+ if a.apiBaseURL != RegionFeishu.OpenBaseURL {
+ t.Errorf("fallback apiBaseURL = %q, want %q", a.apiBaseURL, RegionFeishu.OpenBaseURL)
+ }
+ // The region default value also passes (treated as "no override").
+ a2, err := NewAdapter(RegionFeishu, "a", "b", "", "", RegionFeishu.OpenBaseURL)
+ if err != nil {
+ t.Fatalf("NewAdapter default api_base_url: %v", err)
+ }
+ if a2.apiBaseURL != RegionFeishu.OpenBaseURL {
+ t.Errorf("default apiBaseURL = %q", a2.apiBaseURL)
+ }
+}
+
+// validateAPIBaseURL rejects non-http(s) schemes; empty and the region default
+// are allowed without further checks.
+func TestValidateAPIBaseURL(t *testing.T) {
+ defaults := RegionFeishu.OpenBaseURL
+ if err := validateAPIBaseURL("", defaults); err != nil {
+ t.Errorf("empty should be allowed: %v", err)
+ }
+ if err := validateAPIBaseURL(defaults, defaults); err != nil {
+ t.Errorf("default should be allowed: %v", err)
+ }
+ if err := validateAPIBaseURL("ftp://example.com", defaults); err == nil {
+ t.Error("ftp scheme should be rejected")
+ }
+ if err := validateAPIBaseURL("gopher://example.com", defaults); err == nil {
+ t.Error("gopher scheme should be rejected")
+ }
+}
+
// The streaming card placeholder follows the region so Lark users are not shown
// Chinese copy.
func TestBuildStreamingCardJSON_PlaceholderFollowsRegion(t *testing.T) {
diff --git a/internal/im/feishu/send_e2e_test.go b/internal/im/feishu/send_e2e_test.go
index 03aab7144..762e2262c 100644
--- a/internal/im/feishu/send_e2e_test.go
+++ b/internal/im/feishu/send_e2e_test.go
@@ -99,7 +99,7 @@ func TestSendReply_EndToEnd_UsesRegionCloud(t *testing.T) {
srv := httptest.NewServer(fake.handler())
defer srv.Close()
- a := NewAdapter(testRegion(srv.URL), "cli_app", "secret", "", "")
+ a, _ := NewAdapter(testRegion(srv.URL), "cli_app", "secret", "", "", "")
incoming := &im.IncomingMessage{
Platform: im.PlatformLark,
UserID: "ou_user1",
@@ -144,7 +144,7 @@ func TestSendReply_EndToEnd_FallsBackToSendAPI(t *testing.T) {
srv := httptest.NewServer(fake.handler())
defer srv.Close()
- a := NewAdapter(testRegion(srv.URL), "cli_app", "secret", "", "")
+ a, _ := NewAdapter(testRegion(srv.URL), "cli_app", "secret", "", "", "")
incoming := &im.IncomingMessage{
Platform: im.PlatformLark,
UserID: "ou_user1",
@@ -175,7 +175,7 @@ func TestSendReply_EndToEnd_HardErrorSurfaces(t *testing.T) {
srv := httptest.NewServer(fake.handler())
defer srv.Close()
- a := NewAdapter(testRegion(srv.URL), "cli_app", "secret", "", "")
+ a, _ := NewAdapter(testRegion(srv.URL), "cli_app", "secret", "", "", "")
incoming := &im.IncomingMessage{
Platform: im.PlatformLark, UserID: "ou_user1",
ChatType: im.ChatTypeDirect, MessageID: "om_msg1",