Skip to main content

acosmi/chatbridge/
client.rs

1//! 第三方聊天 bridge 控制面客户端(Phase 7B)。端口自 `chatbridge/client.ts`
2//! (getter 子客户端:TS `Object.defineProperty` + WeakMap → `fn chat_bridge(&self)`)。
3//!
4//! 端点:`/api/v4/chat-bridge/*`(nexus-v4 registerChatBridgeRoutes)。
5//!
6//! **双平面 wire(契约 §12)**:
7//!   - **请求体字段 = snake_case**(app_id / workspace_id / config_json / secret_kind / new_plaintext ...);
8//!   - **响应 data = model 直接序列化的 camelCase**(appId / credentialRef / secretKind ...,
9//!     与本域 [`types`](super::types) 逐字一致)。
10//!     出站请求体经本模块手工映射 camelCase 入参 → snake_case wire。
11//!
12//! **安全红线(契约 §6 Secret zero-knowledge)**:
13//!   - 任何端点不回 plaintext / ciphertext(model Ciphertext/ConfigJSON json:"-");
14//!   - 创建/轮换的明文只在请求体出现一次,SDK 不缓存不打印(plaintext 入参只进 [`serde_json::json!`]
15//!     请求体,永不存字段、永不 Display);
16//!   - 跨租户引用服务端一律 404(不暴露存在性)。
17
18use super::types::{
19    as_credential_ref, ChatCredentialPublic, ChatIntegration, IntegrationStatus, Platform, Region,
20};
21use crate::billing::entitlements::urlencoding;
22use crate::core::client::Client;
23use crate::shared::{ApiResponse, Result};
24use serde::Deserialize;
25use serde_json::json;
26use tokio_util::sync::CancellationToken;
27
28/// `create_integration()` 请求(wire snake_case 由 SDK 转换)。对应 TS `CreateIntegrationRequest`。
29#[derive(Debug, Clone)]
30pub struct CreateIntegrationRequest {
31    /// 绑定的 Acosmi app。
32    pub app_id: String,
33    pub platform: Platform,
34    pub region: Region,
35    /// 平台 workspace/企业 原始 ID;服务端只存 SHA256 hash。
36    pub workspace_id: Option<String>,
37    /// 平台 bot 原始 ID;服务端只存 SHA256 hash。
38    pub bot_id: Option<String>,
39    /// 仅非敏感配置(rate limit / feature toggles);**严禁含 secret**。
40    pub config_json: Option<String>,
41}
42
43/// `store_credential()` 请求 —— 明文一次性提交。对应 TS `StoreCredentialRequest`。
44///
45/// **安全**:`plaintext` 仅在出站请求体出现一次,加密落库后即弃;本结构体不被任何响应/缓存持有。
46#[derive(Debug, Clone)]
47pub struct StoreCredentialRequest {
48    /// 凭证种类(平台相关,例:app_secret / signing_secret / bot_token)。
49    pub secret_kind: String,
50    /// 凭证明文;加密落库后即弃,响应只回 masked 视图。
51    pub plaintext: String,
52    pub region: Option<Region>,
53    pub platform: Option<Platform>,
54}
55
56/// 列表端点包装(`{items?: [...]}`)。chatbridge GET 列表用。
57#[derive(Debug, Deserialize)]
58struct ItemsWrapper<T> {
59    #[serde(default = "Vec::new")]
60    items: Vec<T>,
61}
62
63/// SDK-facing 第三方聊天 bridge 控制面子客户端。对应 TS `ChatBridgeClient`。
64///
65/// 经 [`Client::chat_bridge`] getter 获取(无状态,持 [`Client`] clone)。
66pub struct ChatBridgeClient {
67    client: Client,
68}
69
70impl Client {
71    /// 第三方聊天 bridge 控制面(Phase 7B;契约 §6/§12/ADR-8)。对应 TS `client.chatBridge` getter。
72    ///
73    /// 守卫(最小授权三档,chat_bridge 不进 all_scopes):
74    ///   - chat_bridge:read   → list_integrations / get_integration / list_credentials
75    ///   - chat_bridge:write  → create_integration / update_integration_status / store_credential
76    ///   - chat_bridge:rotate → rotate_credential / revoke_credential(高风险)
77    pub fn chat_bridge(&self) -> ChatBridgeClient {
78        ChatBridgeClient {
79            client: self.clone(),
80        }
81    }
82}
83
84impl ChatBridgeClient {
85    // ---------------------------------------------------------------------------
86    // Integration 管理面
87    // ---------------------------------------------------------------------------
88
89    /// 创建平台集成(chat_bridge:write)。对应 TS `createIntegration`。
90    ///
91    /// 出站请求体手工映射 camelCase 入参 → **snake_case wire**(app_id / workspace_id / bot_id /
92    /// config_json)。
93    pub async fn create_integration(
94        &self,
95        req: &CreateIntegrationRequest,
96        signal: Option<CancellationToken>,
97    ) -> Result<ChatIntegration> {
98        // 请求体 = snake_case(契约 §12 chatbridge 平面)。Option 为 None 时省略字段。
99        let body_str = create_integration_wire_body(req).to_string();
100        self.client
101            .commerce_post::<ChatIntegration>("/chat-bridge/integrations", Some(&body_str), signal)
102            .await
103    }
104
105    /// 列出本租户集成(chat_bridge:read;masked 视图)。可按 app_id 过滤。对应 TS `listIntegrations`。
106    pub async fn list_integrations(
107        &self,
108        app_id: Option<&str>,
109        signal: Option<CancellationToken>,
110    ) -> Result<Vec<ChatIntegration>> {
111        let path = match app_id {
112            Some(a) => format!("/chat-bridge/integrations?app_id={}", urlencoding(a)),
113            None => "/chat-bridge/integrations".to_string(),
114        };
115        // data = `{items?: [...]}`(响应 camelCase)。
116        let w: ItemsWrapper<ChatIntegration> = self.client.commerce_get(&path, signal).await?;
117        Ok(w.items)
118    }
119
120    /// 取单个集成(chat_bridge:read)。不存在/跨租户一律 404。对应 TS `getIntegration`。
121    pub async fn get_integration(
122        &self,
123        id: &str,
124        signal: Option<CancellationToken>,
125    ) -> Result<ChatIntegration> {
126        self.client
127            .commerce_get(
128                &format!("/chat-bridge/integrations/{}", urlencoding(id)),
129                signal,
130            )
131            .await
132    }
133
134    /// 更新集成状态(chat_bridge:write):pending | active | suspended | revoked。
135    /// 对应 TS `updateIntegrationStatus`(PATCH,返回 void)。
136    pub async fn update_integration_status(
137        &self,
138        id: &str,
139        status: IntegrationStatus,
140        signal: Option<CancellationToken>,
141    ) -> Result<()> {
142        let body = json!({ "status": status.as_str() }).to_string();
143        // PATCH —— commerce helper 默认 POST/GET,这里直接走 do_json_full(PATCH)。
144        let (env, _) = self
145            .client
146            .do_json_full::<ApiResponse<serde_json::Value>>(
147                http::Method::PATCH,
148                &format!("/chat-bridge/integrations/{}/status", urlencoding(id)),
149                Some(&body),
150                signal,
151            )
152            .await?;
153        if let Some(env) = env {
154            if let Some(err) = env.business_error() {
155                return Err(err);
156            }
157        }
158        Ok(())
159    }
160
161    // ---------------------------------------------------------------------------
162    // Credential 管理面(vault)
163    // ---------------------------------------------------------------------------
164
165    /// 存凭证(chat_bridge:write)—— 明文一次性提交,返回 masked 记录(ref+fingerprint)。
166    /// 对应 TS `storeCredential`。
167    ///
168    /// 出站请求体 = **snake_case**(secret_kind / plaintext / region / platform)。
169    /// **plaintext 仅进此处请求体一次**;响应恒为 masked 视图(无 plaintext/ciphertext)。
170    pub async fn store_credential(
171        &self,
172        integration_id: &str,
173        req: &StoreCredentialRequest,
174        signal: Option<CancellationToken>,
175    ) -> Result<ChatCredentialPublic> {
176        let body_str = store_credential_wire_body(req).to_string();
177        let cred: ChatCredentialPublic = self
178            .client
179            .commerce_post(
180                &format!(
181                    "/chat-bridge/integrations/{}/credentials",
182                    urlencoding(integration_id)
183                ),
184                Some(&body_str),
185                signal,
186            )
187            .await?;
188        Ok(brand_credential(cred))
189    }
190
191    /// 列出集成的凭证(chat_bridge:read;masked,永不含明文/密文)。对应 TS `listCredentials`。
192    pub async fn list_credentials(
193        &self,
194        integration_id: &str,
195        signal: Option<CancellationToken>,
196    ) -> Result<Vec<ChatCredentialPublic>> {
197        let w: ItemsWrapper<ChatCredentialPublic> = self
198            .client
199            .commerce_get(
200                &format!(
201                    "/chat-bridge/integrations/{}/credentials",
202                    urlencoding(integration_id)
203                ),
204                signal,
205            )
206            .await?;
207        Ok(w.items.into_iter().map(brand_credential).collect())
208    }
209
210    /// 轮换凭证(chat_bridge:rotate,高风险)—— ref 不变,fingerprint 更新。对应 TS `rotateCredential`。
211    ///
212    /// 出站请求体 = **snake_case**(secret_kind / new_plaintext)。new_plaintext 仅出现一次。
213    pub async fn rotate_credential(
214        &self,
215        integration_id: &str,
216        secret_kind: &str,
217        new_plaintext: &str,
218        signal: Option<CancellationToken>,
219    ) -> Result<ChatCredentialPublic> {
220        let body = json!({
221            "secret_kind": secret_kind,
222            "new_plaintext": new_plaintext,
223        })
224        .to_string();
225        let cred: ChatCredentialPublic = self
226            .client
227            .commerce_post(
228                &format!(
229                    "/chat-bridge/integrations/{}/credentials/rotate",
230                    urlencoding(integration_id)
231                ),
232                Some(&body),
233                signal,
234            )
235            .await?;
236        Ok(brand_credential(cred))
237    }
238
239    /// 吊销凭证(chat_bridge:rotate)—— 软吊销 + 服务端抹密文。对应 TS `revokeCredential`(返回 void)。
240    pub async fn revoke_credential(
241        &self,
242        credential_ref: &str,
243        signal: Option<CancellationToken>,
244    ) -> Result<()> {
245        self.client
246            .commerce_post_discard(
247                &format!(
248                    "/chat-bridge/credentials/{}/revoke",
249                    urlencoding(credential_ref)
250                ),
251                Some("{}"),
252                signal,
253            )
254            .await
255    }
256}
257
258/// 服务端返回的 credentialRef 是裸 string;出 SDK 边界前统一 brand 成 [`CredentialRef`]
259/// (运行时恒等,只改类型识别),防止与 plaintext 字符串互窜。对应 TS `brandCredential`。
260fn brand_credential(mut c: ChatCredentialPublic) -> ChatCredentialPublic {
261    c.credential_ref = as_credential_ref(c.credential_ref.as_str());
262    c
263}
264
265/// 构建 create_integration 出站请求体(camelCase 入参 → **snake_case wire**)。
266fn create_integration_wire_body(req: &CreateIntegrationRequest) -> serde_json::Value {
267    let mut body = serde_json::Map::new();
268    body.insert("app_id".into(), json!(req.app_id));
269    body.insert("platform".into(), json!(req.platform.as_str()));
270    body.insert("region".into(), json!(req.region.as_str()));
271    if let Some(w) = &req.workspace_id {
272        body.insert("workspace_id".into(), json!(w));
273    }
274    if let Some(b) = &req.bot_id {
275        body.insert("bot_id".into(), json!(b));
276    }
277    if let Some(c) = &req.config_json {
278        body.insert("config_json".into(), json!(c));
279    }
280    serde_json::Value::Object(body)
281}
282
283/// 构建 store_credential 出站请求体(camelCase 入参 → **snake_case wire**)。
284/// plaintext 仅在此处进入请求体一次。
285fn store_credential_wire_body(req: &StoreCredentialRequest) -> serde_json::Value {
286    let mut body = serde_json::Map::new();
287    body.insert("secret_kind".into(), json!(req.secret_kind));
288    body.insert("plaintext".into(), json!(req.plaintext));
289    if let Some(r) = req.region {
290        body.insert("region".into(), json!(r.as_str()));
291    }
292    if let Some(p) = req.platform {
293        body.insert("platform".into(), json!(p.as_str()));
294    }
295    serde_json::Value::Object(body)
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301    use crate::chatbridge::types::{Platform, Region};
302
303    #[test]
304    fn create_integration_request_is_snake_case_wire() {
305        // 入参 camelCase → 请求体 snake_case(双平面,契约 §12)。
306        let req = CreateIntegrationRequest {
307            app_id: "app-1".into(),
308            platform: Platform::Feishu,
309            region: Region::Cn,
310            workspace_id: Some("ws-raw".into()),
311            bot_id: Some("bot-raw".into()),
312            config_json: Some("{\"rate\":1}".into()),
313        };
314        let body = create_integration_wire_body(&req);
315        assert_eq!(body["app_id"], "app-1");
316        assert_eq!(body["workspace_id"], "ws-raw");
317        assert_eq!(body["bot_id"], "bot-raw");
318        assert_eq!(body["config_json"], "{\"rate\":1}");
319        assert_eq!(body["platform"], "feishu");
320        assert_eq!(body["region"], "cn");
321        // 绝不出现 camelCase wire 键。
322        assert!(body.get("appId").is_none());
323        assert!(body.get("workspaceId").is_none());
324        assert!(body.get("configJson").is_none());
325    }
326
327    #[test]
328    fn store_credential_request_snake_case_plaintext_once() {
329        let req = StoreCredentialRequest {
330            secret_kind: "bot_token".into(),
331            plaintext: "super-secret".into(),
332            region: Some(Region::Intl),
333            platform: Some(Platform::Slack),
334        };
335        let body = store_credential_wire_body(&req);
336        assert_eq!(body["secret_kind"], "bot_token");
337        // plaintext 出现且仅一次(snake_case 键)。
338        assert_eq!(body["plaintext"], "super-secret");
339        assert_eq!(body["region"], "intl");
340        assert_eq!(body["platform"], "slack");
341        assert!(body.get("secretKind").is_none());
342        // 计数 plaintext 仅 1 个键。
343        let count = body
344            .as_object()
345            .unwrap()
346            .keys()
347            .filter(|k| k.contains("plaintext"))
348            .count();
349        assert_eq!(count, 1);
350    }
351
352    #[test]
353    fn optional_fields_omitted_when_none() {
354        let req = CreateIntegrationRequest {
355            app_id: "a".into(),
356            platform: Platform::Wecom,
357            region: Region::Cn,
358            workspace_id: None,
359            bot_id: None,
360            config_json: None,
361        };
362        let body = create_integration_wire_body(&req);
363        let obj = body.as_object().unwrap();
364        assert!(!obj.contains_key("workspace_id"));
365        assert!(!obj.contains_key("bot_id"));
366        assert!(!obj.contains_key("config_json"));
367    }
368}