Skip to main content

acosmi/chatbridge/
types.rs

1//! Acosmi 第三方聊天 bridge 控制面 —— SDK 类型契约(Phase 7)。
2//!
3//! 契约源:`docs/audit/sdk-remote-control-contract-2026-05-27.md` §6(Secret zero-knowledge)
4//! + §7 + §12 + ADR-8。
5//!
6//! 设计纪律(安全红线):
7//!   - chatbridge 资源 **响应 data = camelCase**(与 model/chat_bridge.go json tag 逐字一致);
8//!     **请求体 = snake_case**(handler ShouldBindJSON tag),两平面在 [`client`](super::client) 手工映射;
9//!   - 平台 secret(plaintext / token / signing key)**永不出现在 SDK 公共导出**;
10//!     SDK 只见 read-only metadata + [`CredentialRef`] + fingerprint + ChannelEvents;
11//!   - 7 个平台严格枚举(闭 union);
12//!   - 平台原始 thread / sender / workspace / bot ID 一律 **hash 字段**入 SDK,永不持原值。
13
14use serde::{Deserialize, Serialize};
15use std::collections::HashMap;
16
17// =============================================================================
18// Platform / Region / IntegrationStatus(闭 union → enum + serde rename)
19// =============================================================================
20
21/// 平台(闭 union,与 Go `service/chatbridge/types.go` 对齐)。TS `Platform`。
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
23pub enum Platform {
24    #[serde(rename = "feishu")]
25    Feishu,
26    #[serde(rename = "wecom")]
27    Wecom,
28    #[serde(rename = "dingtalk")]
29    Dingtalk,
30    #[serde(rename = "slack")]
31    Slack,
32    #[serde(rename = "teams")]
33    Teams,
34    #[serde(rename = "telegram")]
35    Telegram,
36    #[serde(rename = "whatsapp")]
37    Whatsapp,
38}
39
40impl Platform {
41    /// wire 字符串值。
42    pub fn as_str(self) -> &'static str {
43        match self {
44            Platform::Feishu => "feishu",
45            Platform::Wecom => "wecom",
46            Platform::Dingtalk => "dingtalk",
47            Platform::Slack => "slack",
48            Platform::Teams => "teams",
49            Platform::Telegram => "telegram",
50            Platform::Whatsapp => "whatsapp",
51        }
52    }
53}
54
55/// 区域(闭 union)。TS `Region`。
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
57pub enum Region {
58    #[serde(rename = "cn")]
59    Cn,
60    #[serde(rename = "intl")]
61    Intl,
62}
63
64impl Region {
65    pub fn as_str(self) -> &'static str {
66        match self {
67            Region::Cn => "cn",
68            Region::Intl => "intl",
69        }
70    }
71}
72
73/// 集成状态(闭 union)。TS `IntegrationStatus`。
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
75pub enum IntegrationStatus {
76    #[serde(rename = "pending")]
77    Pending,
78    #[serde(rename = "active")]
79    Active,
80    #[serde(rename = "suspended")]
81    Suspended,
82    #[serde(rename = "revoked")]
83    Revoked,
84}
85
86impl IntegrationStatus {
87    pub fn as_str(self) -> &'static str {
88        match self {
89            IntegrationStatus::Pending => "pending",
90            IntegrationStatus::Active => "active",
91            IntegrationStatus::Suspended => "suspended",
92            IntegrationStatus::Revoked => "revoked",
93        }
94    }
95}
96
97// =============================================================================
98// CredentialRef newtype(branded type → #[serde(transparent)] 透明 String 新类型)
99// =============================================================================
100
101/// CredentialRef —— chat-bridge 凭证公开引用(`cred_<22 char base32>`)。
102///
103/// 透明 newtype 防止 plaintext secret 字符串被误传到需要 CredentialRef 的位置。
104/// SDK 调用方应仅持有 `CredentialRef`,**永不持 plaintext**。
105///
106/// **安全**:本类型只承载公开 ref(非 secret);构造经 [`as_credential_ref`],不做合法性校验
107/// (bug-for-bug,与 TS `asCredentialRef` 一致)。
108#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
109#[serde(transparent)]
110pub struct CredentialRef(String);
111
112impl CredentialRef {
113    /// 借出底层 ref 字符串(公开值,非 secret)。
114    pub fn as_str(&self) -> &str {
115        &self.0
116    }
117}
118
119impl std::fmt::Display for CredentialRef {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        f.write_str(&self.0)
122    }
123}
124
125/// 把任意字符串安全包装成 [`CredentialRef`];不做合法性校验(调用方自判 `cred_` 前缀)。
126/// 对应 TS `asCredentialRef`。
127pub fn as_credential_ref(s: impl Into<String>) -> CredentialRef {
128    CredentialRef(s.into())
129}
130
131// =============================================================================
132// Channel event 公共类型(read-only events;secret 永不出现)
133// =============================================================================
134
135/// 入站附件 / 出站文件附件(ADR-8:`url` 必须是 Acosmi 内部存储 URL,非平台原始签名 URL)。
136/// TS `ChannelAttachment`。
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct ChannelAttachment {
139    pub kind: String,
140    pub url: String,
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub size: Option<i64>,
143    #[serde(
144        rename = "contentType",
145        default,
146        skip_serializing_if = "Option::is_none"
147    )]
148    pub content_type: Option<String>,
149}
150
151/// 出站交互卡片按钮 / 自由输入。TS `ChannelCardAction`。
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct ChannelCardAction {
154    /// 'approve' | 'reject' | 'cancel' | 'free_text' | 其他 bridge 自定义。
155    pub kind: String,
156    /// bridge 侧稳定 action id(映射回原 requestId 幂等键)。
157    pub id: String,
158    pub label: String,
159}
160
161/// 出站交互卡片(permission / tool_status / done / error)。TS `ChannelCard`。
162#[derive(Debug, Clone, Serialize, Deserialize)]
163pub struct ChannelCard {
164    pub kind: String,
165    pub title: String,
166    pub body: String,
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub actions: Option<Vec<ChannelCardAction>>,
169}
170
171/// bridge runtime 视角的入站平台消息。TS `ChannelInboundEvent`。
172///
173/// 安全约束:`thread_hash` / `sender_hash` 是 SHA256(平台原始 ID),不允许直接是平台 ID。
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct ChannelInboundEvent {
176    pub platform: Platform,
177    #[serde(rename = "threadHash")]
178    pub thread_hash: String,
179    #[serde(
180        rename = "senderHash",
181        default,
182        skip_serializing_if = "Option::is_none"
183    )]
184    pub sender_hash: Option<String>,
185    pub content: String,
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub attachments: Option<Vec<ChannelAttachment>>,
188    #[serde(rename = "messageId", default, skip_serializing_if = "Option::is_none")]
189    pub message_id: Option<String>,
190    /// ISO-8601。
191    #[serde(
192        rename = "receivedAt",
193        default,
194        skip_serializing_if = "Option::is_none"
195    )]
196    pub received_at: Option<String>,
197    /// 仅含非敏感字段(locale, message_kind),严禁含 plaintext secret。
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub metadata: Option<HashMap<String, String>>,
200}
201
202/// bridge runtime 出站平台消息 / 卡片。TS `ChannelOutboundEvent`。
203#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct ChannelOutboundEvent {
205    #[serde(rename = "threadHash")]
206    pub thread_hash: String,
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub content: Option<String>,
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub cards: Option<Vec<ChannelCard>>,
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub metadata: Option<HashMap<String, String>>,
213}
214
215/// bridge runtime 内部 thread 引用(Acosmi 三元组)。永不携带 platform secret / 原始平台 ID。
216/// TS `BridgeThreadRef`。
217#[derive(Debug, Clone, Serialize, Deserialize)]
218pub struct BridgeThreadRef {
219    #[serde(rename = "threadId")]
220    pub thread_id: String,
221    #[serde(rename = "runId", default, skip_serializing_if = "Option::is_none")]
222    pub run_id: Option<String>,
223    #[serde(
224        rename = "remoteSessionId",
225        default,
226        skip_serializing_if = "Option::is_none"
227    )]
228    pub remote_session_id: Option<String>,
229    #[serde(rename = "tenantId")]
230    pub tenant_id: String,
231    #[serde(rename = "userId")]
232    pub user_id: String,
233    #[serde(rename = "appId")]
234    pub app_id: String,
235}
236
237// =============================================================================
238// Public 只读视图(admin/管理后台 GET 用;严禁含 Ciphertext / Plaintext)
239// =============================================================================
240
241/// 平台安装记录的 SDK 只读视图(响应 camelCase,契约 §12)。TS `ChatIntegration`。
242#[derive(Debug, Clone, Serialize, Deserialize)]
243pub struct ChatIntegration {
244    pub id: String,
245    #[serde(rename = "tenantId")]
246    pub tenant_id: String,
247    #[serde(rename = "appId")]
248    pub app_id: String,
249    pub platform: Platform,
250    pub region: Region,
251    #[serde(
252        rename = "workspaceIdHash",
253        default,
254        skip_serializing_if = "Option::is_none"
255    )]
256    pub workspace_id_hash: Option<String>,
257    #[serde(rename = "botIdHash", default, skip_serializing_if = "Option::is_none")]
258    pub bot_id_hash: Option<String>,
259    pub status: IntegrationStatus,
260    /// **@deprecated** 服务端从不返回此字段(model ConfigJSON json:"-",防 secret 误入后整体
261    /// 不外发)—— 读取恒为 `None`。写入走 `create_integration({config_json})`。
262    #[serde(
263        rename = "configJson",
264        default,
265        skip_serializing_if = "Option::is_none"
266    )]
267    pub config_json: Option<String>,
268    #[serde(
269        rename = "installedByUserId",
270        default,
271        skip_serializing_if = "Option::is_none"
272    )]
273    pub installed_by_user_id: Option<String>,
274    #[serde(
275        rename = "lastUsedAt",
276        default,
277        skip_serializing_if = "Option::is_none"
278    )]
279    pub last_used_at: Option<String>,
280    #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")]
281    pub created_at: Option<String>,
282    #[serde(rename = "updatedAt", default, skip_serializing_if = "Option::is_none")]
283    pub updated_at: Option<String>,
284}
285
286/// 凭证的 SDK 只读视图(**绝不含 ciphertext / plaintext**)。TS `ChatCredentialPublic`。
287///
288/// 仅暴露公开字段:`credential_ref` / `fingerprint` / `key_id` / `version` / `status`。
289#[derive(Debug, Clone, Serialize, Deserialize)]
290pub struct ChatCredentialPublic {
291    #[serde(rename = "credentialRef")]
292    pub credential_ref: CredentialRef,
293    #[serde(rename = "integrationId")]
294    pub integration_id: String,
295    pub platform: Platform,
296    pub region: Region,
297    #[serde(rename = "secretKind")]
298    pub secret_kind: String,
299    pub fingerprint: String,
300    #[serde(rename = "keyId")]
301    pub key_id: String,
302    pub version: i64,
303    /// 开放 union('active'|'rotating'|'revoked'|任意 string 兜底)。
304    pub status: String,
305    #[serde(
306        rename = "lastUsedAt",
307        default,
308        skip_serializing_if = "Option::is_none"
309    )]
310    pub last_used_at: Option<String>,
311    #[serde(rename = "rotatedAt", default, skip_serializing_if = "Option::is_none")]
312    pub rotated_at: Option<String>,
313    #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")]
314    pub created_at: Option<String>,
315    #[serde(rename = "updatedAt", default, skip_serializing_if = "Option::is_none")]
316    pub updated_at: Option<String>,
317}
318
319/// 平台 thread 到 Acosmi session 的映射(SDK 只读视图)。永不携带原始 thread/sender ID。
320/// TS `ChatThread`。
321#[derive(Debug, Clone, Serialize, Deserialize)]
322pub struct ChatThread {
323    pub id: String,
324    #[serde(rename = "tenantId")]
325    pub tenant_id: String,
326    #[serde(rename = "integrationId")]
327    pub integration_id: String,
328    #[serde(rename = "platformThreadHash")]
329    pub platform_thread_hash: String,
330    pub platform: Platform,
331    #[serde(rename = "userId")]
332    pub user_id: String,
333    #[serde(rename = "appId")]
334    pub app_id: String,
335    #[serde(rename = "sessionId", default, skip_serializing_if = "Option::is_none")]
336    pub session_id: Option<String>,
337    #[serde(rename = "lastRunId", default, skip_serializing_if = "Option::is_none")]
338    pub last_run_id: Option<String>,
339    #[serde(
340        rename = "senderHash",
341        default,
342        skip_serializing_if = "Option::is_none"
343    )]
344    pub sender_hash: Option<String>,
345    #[serde(
346        rename = "lastInboundAt",
347        default,
348        skip_serializing_if = "Option::is_none"
349    )]
350    pub last_inbound_at: Option<String>,
351    #[serde(
352        rename = "lastOutboundAt",
353        default,
354        skip_serializing_if = "Option::is_none"
355    )]
356    pub last_outbound_at: Option<String>,
357}
358
359/// 一次 bridge runtime 会话(SDK 只读视图)。TS `ChatBridgeSession`。
360#[derive(Debug, Clone, Serialize, Deserialize)]
361pub struct ChatBridgeSession {
362    pub id: String,
363    #[serde(rename = "tenantId")]
364    pub tenant_id: String,
365    #[serde(rename = "threadId")]
366    pub thread_id: String,
367    #[serde(rename = "integrationId")]
368    pub integration_id: String,
369    #[serde(rename = "runId", default, skip_serializing_if = "Option::is_none")]
370    pub run_id: Option<String>,
371    #[serde(
372        rename = "remoteSessionId",
373        default,
374        skip_serializing_if = "Option::is_none"
375    )]
376    pub remote_session_id: Option<String>,
377    /// 开放 union('created'|'routing'|'active'|'paused'|'closed'|'errored'|任意 string)。
378    pub status: String,
379    #[serde(default, skip_serializing_if = "Option::is_none")]
380    pub adapter: Option<String>,
381    #[serde(
382        rename = "lastFrameAt",
383        default,
384        skip_serializing_if = "Option::is_none"
385    )]
386    pub last_frame_at: Option<String>,
387    #[serde(rename = "closedAt", default, skip_serializing_if = "Option::is_none")]
388    pub closed_at: Option<String>,
389    #[serde(
390        rename = "disconnectReason",
391        default,
392        skip_serializing_if = "Option::is_none"
393    )]
394    pub disconnect_reason: Option<String>,
395    #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")]
396    pub created_at: Option<String>,
397    #[serde(rename = "updatedAt", default, skip_serializing_if = "Option::is_none")]
398    pub updated_at: Option<String>,
399}
400
401// =============================================================================
402// 平台 / 区域 / 状态 常量集合 + runtime type guards
403// =============================================================================
404
405/// 全部平台(运行时校验用)。对应 TS `ALL_PLATFORMS`。
406pub const ALL_PLATFORMS: &[Platform] = &[
407    Platform::Feishu,
408    Platform::Wecom,
409    Platform::Dingtalk,
410    Platform::Slack,
411    Platform::Teams,
412    Platform::Telegram,
413    Platform::Whatsapp,
414];
415
416/// 全部区域。对应 TS `ALL_REGIONS`。
417pub const ALL_REGIONS: &[Region] = &[Region::Cn, Region::Intl];
418
419/// 全部集成状态。对应 TS `ALL_INTEGRATION_STATUS`。
420pub const ALL_INTEGRATION_STATUS: &[IntegrationStatus] = &[
421    IntegrationStatus::Pending,
422    IntegrationStatus::Active,
423    IntegrationStatus::Suspended,
424    IntegrationStatus::Revoked,
425];
426
427/// runtime type guard:字符串是否合法 [`Platform`]。对应 TS `isPlatform`。
428pub fn is_platform(v: &str) -> bool {
429    ALL_PLATFORMS.iter().any(|p| p.as_str() == v)
430}
431
432/// runtime type guard:字符串是否合法 [`Region`]。对应 TS `isRegion`。
433pub fn is_region(v: &str) -> bool {
434    ALL_REGIONS.iter().any(|r| r.as_str() == v)
435}
436
437/// runtime type guard:字符串是否合法 [`IntegrationStatus`]。对应 TS `isIntegrationStatus`。
438pub fn is_integration_status(v: &str) -> bool {
439    ALL_INTEGRATION_STATUS.iter().any(|s| s.as_str() == v)
440}
441
442/// 极简 type guard:任意 JSON 是否为合法入站事件(仅校验 platform/threadHash/content)。
443/// 对应 TS `isChannelInboundEvent`(失败返 false,不抛)。
444pub fn is_channel_inbound_event(v: &serde_json::Value) -> bool {
445    let obj = match v.as_object() {
446        Some(o) => o,
447        None => return false,
448    };
449    let platform_ok = obj
450        .get("platform")
451        .and_then(|p| p.as_str())
452        .map(is_platform)
453        .unwrap_or(false);
454    let thread_hash_ok = obj
455        .get("threadHash")
456        .and_then(|t| t.as_str())
457        .map(|s| !s.is_empty())
458        .unwrap_or(false);
459    let content_ok = obj.get("content").map(|c| c.is_string()).unwrap_or(false);
460    platform_ok && thread_hash_ok && content_ok
461}
462
463#[cfg(test)]
464mod tests {
465    use super::*;
466
467    #[test]
468    fn credential_ref_is_transparent_newtype() {
469        // #[serde(transparent)]:序列化为裸字符串(非 {"0":"..."} 包装)。
470        let r = as_credential_ref("cred_abc123");
471        let v = serde_json::to_value(&r).unwrap();
472        assert_eq!(v, serde_json::Value::String("cred_abc123".into()));
473        // 反序列化也是裸字符串。
474        let back: CredentialRef = serde_json::from_str("\"cred_xyz\"").unwrap();
475        assert_eq!(back.as_str(), "cred_xyz");
476    }
477
478    #[test]
479    fn chat_credential_public_response_is_camel_case() {
480        // 响应 data = camelCase(contract §12 chatbridge 平面);credentialRef → CredentialRef。
481        let c: ChatCredentialPublic = serde_json::from_str(
482            r#"{"credentialRef":"cred_aaa","integrationId":"int1","platform":"slack",
483                "region":"intl","secretKind":"bot_token","fingerprint":"fp","keyId":"k1",
484                "version":2,"status":"active"}"#,
485        )
486        .unwrap();
487        assert_eq!(c.credential_ref.as_str(), "cred_aaa");
488        assert_eq!(c.platform, Platform::Slack);
489        assert_eq!(c.region, Region::Intl);
490        assert_eq!(c.secret_kind, "bot_token");
491        // 安全:结构体无任何 plaintext/ciphertext 字段(编译期保证;此处只断公开字段)。
492        assert_eq!(c.version, 2);
493    }
494
495    #[test]
496    fn integration_response_no_config_json_when_absent() {
497        // configJson @deprecated 服务端从不返回 → 恒 None。
498        let i: ChatIntegration = serde_json::from_str(
499            r#"{"id":"int1","tenantId":"t1","appId":"a1","platform":"feishu",
500                "region":"cn","status":"active"}"#,
501        )
502        .unwrap();
503        assert!(i.config_json.is_none());
504        assert_eq!(i.platform, Platform::Feishu);
505    }
506
507    #[test]
508    fn type_guards_validate_strings() {
509        assert!(is_platform("slack"));
510        assert!(!is_platform("discord"));
511        assert!(is_region("cn"));
512        assert!(!is_region("us"));
513        assert!(is_integration_status("revoked"));
514        assert!(!is_integration_status("deleted"));
515    }
516
517    #[test]
518    fn is_channel_inbound_event_checks_minimal_fields() {
519        let ok = serde_json::json!({"platform":"slack","threadHash":"h","content":"hi"});
520        assert!(is_channel_inbound_event(&ok));
521        // 缺 content。
522        let bad = serde_json::json!({"platform":"slack","threadHash":"h"});
523        assert!(!is_channel_inbound_event(&bad));
524        // 非法平台。
525        let bad2 = serde_json::json!({"platform":"x","threadHash":"h","content":"hi"});
526        assert!(!is_channel_inbound_event(&bad2));
527        // 空 threadHash。
528        let bad3 = serde_json::json!({"platform":"slack","threadHash":"","content":"hi"});
529        assert!(!is_channel_inbound_event(&bad3));
530    }
531}