-
Notifications
You must be signed in to change notification settings - Fork 202
Expand file tree
/
Copy pathfeishu.rs
More file actions
3198 lines (2944 loc) · 119 KB
/
Copy pathfeishu.rs
File metadata and controls
3198 lines (2944 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::schema::*;
use axum::extract::State;
use prost::Message as ProstMessage;
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::RwLock;
use tracing::{info, warn};
/// Timing-safe string comparison to prevent side-channel attacks on tokens.
fn constant_time_eq(a: &str, b: &str) -> bool {
use subtle::ConstantTimeEq;
if a.len() != b.len() {
return false;
}
a.as_bytes().ct_eq(b.as_bytes()).into()
}
// ---------------------------------------------------------------------------
// Feishu WebSocket protobuf frame (pbbp2.Frame)
// ---------------------------------------------------------------------------
#[derive(Clone, PartialEq, ProstMessage)]
pub struct WsFrame {
#[prost(uint64, tag = "1")]
pub seq_id: u64,
#[prost(uint64, tag = "2")]
pub log_id: u64,
#[prost(int32, tag = "3")]
pub service: i32,
#[prost(int32, tag = "4")]
pub method: i32,
#[prost(message, repeated, tag = "5")]
pub headers: Vec<WsHeader>,
#[prost(string, optional, tag = "6")]
pub payload_encoding: Option<String>,
#[prost(string, optional, tag = "7")]
pub payload_type: Option<String>,
#[prost(bytes = "vec", optional, tag = "8")]
pub payload: Option<Vec<u8>>,
#[prost(string, optional, tag = "9")]
pub log_id_new: Option<String>,
}
#[derive(Clone, PartialEq, ProstMessage)]
pub struct WsHeader {
#[prost(string, tag = "1")]
pub key: String,
#[prost(string, tag = "2")]
pub value: String,
}
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq)]
pub enum ConnectionMode {
Websocket,
Webhook,
}
#[derive(Debug, Clone, PartialEq)]
pub enum AllowBots {
Off,
Mentions,
All,
}
/// Controls when the bot responds without @mention in threads.
/// Mirrors Discord's `allow_user_messages` setting.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum AllowUsers {
/// Bot responds in threads it has participated in without @mention.
#[default]
Involved,
/// Always require @mention, even in participated threads.
Mentions,
/// Like Involved, but if another bot has also posted in the thread,
/// require @mention to avoid all bots responding.
MultibotMentions,
}
#[derive(Debug, Clone)]
pub struct FeishuConfig {
pub app_id: String,
pub app_secret: String,
pub domain: String,
pub connection_mode: ConnectionMode,
pub webhook_path: String,
pub verification_token: Option<String>,
pub encrypt_key: Option<String>,
pub allowed_groups: Vec<String>,
pub allowed_users: Vec<String>,
pub require_mention: bool,
pub allow_bots: AllowBots,
pub allow_user_messages: AllowUsers,
pub trusted_bot_ids: Vec<String>,
pub max_bot_turns: u32,
pub dedupe_ttl_secs: u64,
pub message_limit: usize,
/// TTL for participated-thread cache entries (seconds). Threads older than
/// this are forgotten and require a fresh @mention to re-engage.
/// Set to 0 (via FEISHU_SESSION_TTL_HOURS=0) to disable participation
/// tracking entirely — all messages will require @mention.
/// Converted from `FEISHU_SESSION_TTL_HOURS` (user-facing, in hours) to seconds internally.
pub session_ttl_secs: u64,
/// Override the API base URL. Used in tests to point at a mock server.
/// Always None in production (not read from env).
pub api_base_override: Option<String>,
}
impl FeishuConfig {
/// Build config from environment variables. Returns None if FEISHU_APP_ID
/// is not set (adapter disabled).
pub fn from_env() -> Option<Self> {
let app_id = std::env::var("FEISHU_APP_ID").ok()?;
let app_secret = std::env::var("FEISHU_APP_SECRET").ok().unwrap_or_default();
if app_secret.is_empty() {
warn!("FEISHU_APP_ID set but FEISHU_APP_SECRET is empty");
return None;
}
let domain = std::env::var("FEISHU_DOMAIN").unwrap_or_else(|_| "feishu".into());
let connection_mode = match std::env::var("FEISHU_CONNECTION_MODE")
.unwrap_or_else(|_| "websocket".into())
.to_lowercase()
.as_str()
{
"webhook" => ConnectionMode::Webhook,
_ => ConnectionMode::Websocket,
};
let webhook_path = std::env::var("FEISHU_WEBHOOK_PATH")
.unwrap_or_else(|_| "/webhook/feishu".into());
let verification_token = std::env::var("FEISHU_VERIFICATION_TOKEN").ok();
let encrypt_key = std::env::var("FEISHU_ENCRYPT_KEY").ok();
let allowed_groups = parse_csv("FEISHU_ALLOWED_GROUPS");
let allowed_users = parse_csv("FEISHU_ALLOWED_USERS");
let require_mention = std::env::var("FEISHU_REQUIRE_MENTION")
.map(|v| v != "false" && v != "0")
.unwrap_or(true);
let allow_bots = match std::env::var("FEISHU_ALLOW_BOTS")
.unwrap_or_else(|_| "off".into())
.to_lowercase()
.as_str()
{
"mentions" => AllowBots::Mentions,
"all" => AllowBots::All,
_ => AllowBots::Off,
};
let trusted_bot_ids = parse_csv("FEISHU_TRUSTED_BOT_IDS");
let allow_user_messages = match std::env::var("FEISHU_ALLOW_USER_MESSAGES")
.unwrap_or_else(|_| "involved".into())
.to_lowercase()
.replace('-', "_")
.as_str()
{
"mentions" => AllowUsers::Mentions,
"multibot_mentions" => AllowUsers::MultibotMentions,
_ => AllowUsers::Involved,
};
let max_bot_turns = std::env::var("FEISHU_MAX_BOT_TURNS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(20);
let dedupe_ttl_secs = std::env::var("FEISHU_DEDUPE_TTL_SECS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(300);
let message_limit = std::env::var("FEISHU_MESSAGE_LIMIT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(4000);
let session_ttl_secs = std::env::var("FEISHU_SESSION_TTL_HOURS")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(24)
* 3600;
Some(Self {
app_id,
app_secret,
domain,
connection_mode,
webhook_path,
verification_token,
encrypt_key,
allowed_groups,
allowed_users,
require_mention,
allow_bots,
allow_user_messages,
trusted_bot_ids,
max_bot_turns,
dedupe_ttl_secs,
message_limit,
session_ttl_secs,
api_base_override: None,
})
}
/// API base URL for the configured domain.
pub fn api_base(&self) -> String {
if let Some(ref base) = self.api_base_override {
return base.clone();
}
if self.domain == "lark" {
"https://open.larksuite.com".into()
} else {
"https://open.feishu.cn".into()
}
}
}
fn parse_csv(var: &str) -> Vec<String> {
std::env::var(var)
.unwrap_or_default()
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
}
// ---------------------------------------------------------------------------
// Feishu event types (im.message.receive_v1)
// ---------------------------------------------------------------------------
mod event_types {
use super::*;
#[derive(Debug, Deserialize)]
pub struct FeishuEventEnvelope {
pub header: Option<FeishuEventHeader>,
pub event: Option<FeishuEventBody>,
pub challenge: Option<String>,
// Parsed by serde, not consumed in current code paths.
#[allow(dead_code)]
#[serde(rename = "type")]
pub event_type_field: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct FeishuEventHeader {
pub event_id: Option<String>,
// Parsed by serde, not consumed in current code paths.
#[allow(dead_code)]
pub event_type: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct FeishuEventBody {
pub sender: Option<FeishuSender>,
pub message: Option<FeishuMessage>,
}
#[derive(Debug, Deserialize)]
pub struct FeishuSender {
pub sender_id: Option<FeishuSenderId>,
pub sender_type: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct FeishuSenderId {
pub open_id: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct FeishuMessage {
pub message_id: Option<String>,
pub chat_id: Option<String>,
pub chat_type: Option<String>,
pub message_type: Option<String>,
pub content: Option<String>,
pub mentions: Option<Vec<FeishuMention>>,
pub root_id: Option<String>,
pub parent_id: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct FeishuMention {
pub key: Option<String>,
pub id: Option<FeishuMentionId>,
// Parsed by serde, not consumed in current code paths.
#[allow(dead_code)]
pub name: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct FeishuMentionId {
pub open_id: Option<String>,
}
/// Parse a feishu im.message.receive_v1 event into a GatewayEvent.
/// Returns None if the event should be skipped (unsupported type, bot message, etc).
/// The Vec<MediaRef> contains references to media that need async download.
///
/// `bypass_mention_gating`: whether the bot should skip @mention requirement for this message.
/// This is the final computed result from mode-specific logic (detect_and_mark_multibot),
/// already accounting for the configured `allow_user_messages` mode.
/// Do NOT pass raw participation status here.
pub fn parse_message_event(
envelope: &FeishuEventEnvelope,
bot_open_id: Option<&str>,
config: &FeishuConfig,
bypass_mention_gating: bool,
) -> Option<(GatewayEvent, Vec<MediaRef>)> {
let _header = envelope.header.as_ref()?;
let event = envelope.event.as_ref()?;
let msg = event.message.as_ref()?;
let sender = event.sender.as_ref()?;
let msg_type = msg.message_type.as_deref().unwrap_or("text");
if !matches!(msg_type, "text" | "image" | "file" | "post" | "audio") {
return None;
}
// Skip bot messages with explicit sender_type
if matches!(sender.sender_type.as_deref(), Some("bot") | Some("app")) {
return None;
}
let sender_open_id = sender.sender_id.as_ref()?.open_id.as_deref()?;
// Skip messages from self
if let Some(bot_id) = bot_open_id {
if sender_open_id == bot_id {
return None;
}
}
// Check if sender is a known bot:
// Bot identification:
// 1. If trusted_bot_ids is configured, check against it
// 2. If trusted_bot_ids is empty, we cannot reliably identify bots
// (Feishu marks other bots as sender_type="user")
let is_bot_sender = if !config.trusted_bot_ids.is_empty() {
config.trusted_bot_ids.iter().any(|id| id == sender_open_id)
} else {
false
};
// User allowlist: if configured, only allow listed users.
// Trusted bots bypass user allowlist (same as Discord behavior).
if !is_bot_sender
&& !config.allowed_users.is_empty()
&& !config.allowed_users.iter().any(|u| u == sender_open_id)
{
return None;
}
if is_bot_sender {
match config.allow_bots {
AllowBots::Off => return None,
AllowBots::Mentions | AllowBots::All => {
// Allowed — will check mentions below for Mentions mode
}
}
}
let chat_id = msg.chat_id.as_deref()?;
// Group allowlist: if configured, only allow listed groups
let is_group = msg.chat_type.as_deref() != Some("p2p");
if is_group
&& !config.allowed_groups.is_empty()
&& !config.allowed_groups.iter().any(|g| g == chat_id)
{
return None;
}
let content_json: serde_json::Value = msg.content.as_deref()
.and_then(|s| serde_json::from_str(s).ok())?;
let message_id = msg.message_id.as_deref()?;
// Parse content based on message type
let (clean_text, mention_ids, media_refs) = match msg_type {
"image" => {
let image_key = content_json.get("image_key")?.as_str()?;
let mentions = extract_mentions(
"", msg.mentions.as_deref().unwrap_or(&[]), bot_open_id,
);
let refs = vec![MediaRef::Image {
message_id: message_id.to_string(),
image_key: image_key.to_string(),
}];
(String::new(), mentions.1, refs)
}
"file" => {
let file_key = content_json.get("file_key")?.as_str()?;
let file_name = content_json.get("file_name")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
let mentions = extract_mentions(
"", msg.mentions.as_deref().unwrap_or(&[]), bot_open_id,
);
let refs = vec![MediaRef::File {
message_id: message_id.to_string(),
file_key: file_key.to_string(),
file_name: file_name.to_string(),
}];
(String::new(), mentions.1, refs)
}
"audio" => {
let file_key = content_json.get("file_key")?.as_str()?;
let mentions = extract_mentions(
"", msg.mentions.as_deref().unwrap_or(&[]), bot_open_id,
);
let refs = vec![MediaRef::Audio {
message_id: message_id.to_string(),
file_key: file_key.to_string(),
}];
(String::new(), mentions.1, refs)
}
"post" => {
// Rich text: content is {"title":"...","content":[[{tag,text,...},{tag,image_key,...}]]}
let mut texts = Vec::new();
let mut refs = Vec::new();
if let Some(rows) = content_json.get("content").and_then(|v| v.as_array()) {
for row in rows {
if let Some(elements) = row.as_array() {
for el in elements {
match el.get("tag").and_then(|v| v.as_str()) {
Some("text") => {
if let Some(t) = el.get("text").and_then(|v| v.as_str()) {
texts.push(t.to_string());
}
}
Some("img") => {
if let Some(key) = el.get("image_key").and_then(|v| v.as_str()) {
refs.push(MediaRef::Image {
message_id: message_id.to_string(),
image_key: key.to_string(),
});
}
}
Some("a") => {
if let Some(t) = el.get("text").and_then(|v| v.as_str()) {
texts.push(t.to_string());
}
}
Some("at") => {
// Mentions handled via msg.mentions at envelope level
}
_ => {}
}
}
}
}
}
let raw_text = texts.join("");
let (clean, ids) = extract_mentions(
&raw_text,
msg.mentions.as_deref().unwrap_or(&[]),
bot_open_id,
);
(clean, ids, refs)
}
_ => {
// text
let raw_text = content_json.get("text").and_then(|v| v.as_str()).unwrap_or("");
if raw_text.trim().is_empty() {
return None;
}
let (clean, ids) = extract_mentions(
raw_text,
msg.mentions.as_deref().unwrap_or(&[]),
bot_open_id,
);
if clean.trim().is_empty() {
return None;
}
(clean, ids, Vec::new())
}
};
let channel_type = match msg.chat_type.as_deref() {
Some("p2p") => "direct",
_ => "group",
};
let thread_id = msg.root_id.clone().or_else(|| msg.parent_id.clone());
// Gateway-side mention gating: in groups, skip if require_mention
// is true and bot is not mentioned (for human senders).
// Bypass: if bot has previously replied in this thread (participated),
// no @mention needed (like Discord's "involved" mode).
let in_thread = thread_id.is_some();
if channel_type == "group"
&& !is_bot_sender
&& config.require_mention
&& !(in_thread && bypass_mention_gating)
{
if let Some(bot_id) = bot_open_id {
let bot_mentioned = mention_ids.iter().any(|id| id == bot_id);
if !bot_mentioned {
return None;
}
}
}
// Bot-to-bot mention gating: in AllowBots::Mentions mode,
// bot messages must @mention this bot (like Discord "mentions" mode).
// Note: in DMs there is no @mention mechanism, so bot DMs are
// silently dropped in Mentions mode. Use AllowBots::All for DM bots.
if is_bot_sender && config.allow_bots == AllowBots::Mentions {
if let Some(bot_id) = bot_open_id {
let bot_mentioned = mention_ids.iter().any(|id| id == bot_id);
if !bot_mentioned {
return None;
}
}
}
let event = GatewayEvent::new(
"feishu",
ChannelInfo {
id: chat_id.to_string(),
channel_type: channel_type.to_string(),
thread_id,
},
SenderInfo {
id: sender_open_id.to_string(),
name: sender_open_id.to_string(),
display_name: sender_open_id.to_string(),
is_bot: is_bot_sender,
},
clean_text.trim(),
message_id,
mention_ids,
);
Some((event, media_refs))
}
fn extract_mentions(
raw_text: &str,
mentions: &[FeishuMention],
bot_open_id: Option<&str>,
) -> (String, Vec<String>) {
let mut text = raw_text.to_string();
let mut ids = Vec::new();
for m in mentions {
let open_id = m.id.as_ref().and_then(|id| id.open_id.as_deref());
if let Some(oid) = open_id {
ids.push(oid.to_string());
if let Some(key) = m.key.as_deref() {
if bot_open_id == Some(oid) {
text = text.replacen(key, "", 1);
}
}
}
}
(text, ids)
}
}
pub use event_types::*;
// ---------------------------------------------------------------------------
// Deduplication
// ---------------------------------------------------------------------------
pub struct DedupeCache {
seen: std::sync::Mutex<HashMap<String, Instant>>,
ttl_secs: u64,
max_size: usize,
}
impl DedupeCache {
pub fn new(ttl_secs: u64) -> Self {
Self {
seen: std::sync::Mutex::new(HashMap::new()),
ttl_secs,
max_size: 10_000,
}
}
/// Returns true if this id was already seen (duplicate).
pub fn is_duplicate(&self, id: &str) -> bool {
let mut map = self.seen.lock().unwrap_or_else(|e| e.into_inner());
// Lazy sweep
if map.len() >= self.max_size {
map.retain(|_, ts| ts.elapsed().as_secs() < self.ttl_secs);
}
if let Some(ts) = map.get(id) {
if ts.elapsed().as_secs() < self.ttl_secs {
return true;
}
}
map.insert(id.to_string(), Instant::now());
false
}
}
// ---------------------------------------------------------------------------
// Token cache
// ---------------------------------------------------------------------------
pub struct FeishuTokenCache {
/// (token, created_at, ttl_secs)
token: RwLock<Option<(String, Instant, u64)>>,
api_base: String,
app_id: String,
app_secret: String,
}
/// Refresh margin: renew 5 minutes before expiry.
const TOKEN_REFRESH_MARGIN_SECS: u64 = 300;
impl FeishuTokenCache {
pub fn new(config: &FeishuConfig) -> Self {
Self {
token: RwLock::new(None),
api_base: config.api_base(),
app_id: config.app_id.clone(),
app_secret: config.app_secret.clone(),
}
}
/// Construct with explicit api_base (for tests).
pub fn with_base(config: &FeishuConfig, api_base: &str) -> Self {
Self {
token: RwLock::new(None),
api_base: api_base.to_string(),
app_id: config.app_id.clone(),
app_secret: config.app_secret.clone(),
}
}
/// Get a valid tenant_access_token, refreshing if expired or missing.
pub async fn get_token(&self, client: &reqwest::Client) -> anyhow::Result<String> {
// Fast path: read lock
{
let guard = self.token.read().await;
if let Some((ref tok, ref ts, ttl)) = *guard {
if ts.elapsed().as_secs() < ttl.saturating_sub(TOKEN_REFRESH_MARGIN_SECS) {
return Ok(tok.clone());
}
}
}
// Slow path: write lock + refresh
let mut guard = self.token.write().await;
// Double-check after acquiring write lock
if let Some((ref tok, ref ts, ttl)) = *guard {
if ts.elapsed().as_secs() < ttl.saturating_sub(TOKEN_REFRESH_MARGIN_SECS) {
return Ok(tok.clone());
}
}
let (new_token, expire) = self.refresh(client).await?;
*guard = Some((new_token.clone(), Instant::now(), expire));
Ok(new_token)
}
async fn refresh(&self, client: &reqwest::Client) -> anyhow::Result<(String, u64)> {
let url = format!(
"{}/open-apis/auth/v3/tenant_access_token/internal",
self.api_base
);
let resp = client
.post(&url)
.json(&serde_json::json!({
"app_id": self.app_id,
"app_secret": self.app_secret,
}))
.send()
.await
.map_err(|e| anyhow::anyhow!("feishu token refresh request failed: {e}"))?;
let status = resp.status();
let body: serde_json::Value = resp
.json()
.await
.map_err(|e| anyhow::anyhow!("feishu token refresh parse failed: {e}"))?;
let code = body.get("code").and_then(|v| v.as_i64()).unwrap_or(-1);
if code != 0 {
let msg = body
.get("msg")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
anyhow::bail!("feishu token refresh error: code={code} msg={msg} status={status}");
}
let expire = body.get("expire").and_then(|v| v.as_u64()).unwrap_or(7200);
let token = body.get("tenant_access_token")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.ok_or_else(|| anyhow::anyhow!("feishu token refresh: missing tenant_access_token"))?;
Ok((token, expire))
}
}
// ---------------------------------------------------------------------------
// Adapter (aggregated state)
// ---------------------------------------------------------------------------
pub struct FeishuAdapter {
pub config: FeishuConfig,
pub token_cache: Arc<FeishuTokenCache>,
pub bot_open_id: Arc<RwLock<Option<String>>>,
pub dedupe: Arc<DedupeCache>,
pub rate_limiter: Arc<RateLimiter>,
pub name_cache: Arc<std::sync::Mutex<HashMap<String, String>>>,
/// Per-channel bot turn counter. Key = chat_id, Value = (count, last_reset).
/// Human message resets count to 0. Prevents runaway bot-to-bot loops.
pub bot_turns: Arc<std::sync::Mutex<HashMap<String, u32>>>, // eviction: human msg resets; follow-up can add TTL like participated_threads
/// Positive-only cache: thread_id (root_id) → last_replied_at.
/// When bot has replied in a thread, subsequent messages in that thread
/// bypass @mention gating (like Discord's "involved" mode).
pub participated_threads: Arc<std::sync::Mutex<HashMap<String, Instant>>>,
/// Positive-only cache: thread_id → first_seen for threads where other bots
/// have posted. Used by multibot-mentions mode to require @mention.
pub multibot_threads: Arc<std::sync::Mutex<HashMap<String, Instant>>>,
pub client: reqwest::Client,
}
impl FeishuAdapter {
pub fn new(config: FeishuConfig) -> Self {
let token_cache = Arc::new(FeishuTokenCache::new(&config));
let dedupe = Arc::new(DedupeCache::new(config.dedupe_ttl_secs));
let rate_limiter = Arc::new(RateLimiter::new(60, 120));
Self {
config,
token_cache,
dedupe,
rate_limiter,
bot_open_id: Arc::new(RwLock::new(None)),
name_cache: Arc::new(std::sync::Mutex::new(HashMap::new())),
bot_turns: Arc::new(std::sync::Mutex::new(HashMap::new())),
participated_threads: Arc::new(std::sync::Mutex::new(HashMap::new())),
multibot_threads: Arc::new(std::sync::Mutex::new(HashMap::new())),
client: reqwest::Client::new(),
}
}
/// Resolve bot identity (open_id) via API. Called during startup for both
/// WebSocket and webhook modes so mention gating works in either mode.
pub async fn resolve_bot_identity(&self) {
let token = match self.token_cache.get_token(&self.client).await {
Ok(t) => t,
Err(e) => {
warn!(err = %e, "feishu bot identity lookup failed (token error), mention gating may not work");
return;
}
};
match get_bot_info(&self.client, &self.config.api_base(), &token).await {
Ok(bot_id) => {
info!(bot_open_id = %bot_id, "feishu bot identity resolved");
*self.bot_open_id.write().await = Some(bot_id);
}
Err(e) => {
warn!(err = %e, "feishu bot identity lookup failed, mention gating may not work");
}
}
}
}
// ---------------------------------------------------------------------------
// WebSocket long connection
// ---------------------------------------------------------------------------
use futures_util::{SinkExt, StreamExt};
use tokio::sync::{broadcast, watch};
/// Get WebSocket endpoint URL from feishu API.
/// Note: This API uses AppID+AppSecret directly, not Bearer token.
async fn get_ws_endpoint(
client: &reqwest::Client,
api_base: &str,
app_id: &str,
app_secret: &str,
) -> anyhow::Result<String> {
let url = format!("{}/callback/ws/endpoint", api_base);
let resp = client
.post(&url)
.json(&serde_json::json!({
"AppID": app_id,
"AppSecret": app_secret,
}))
.send()
.await?;
let body: serde_json::Value = resp.json().await?;
let code = body.get("code").and_then(|v| v.as_i64()).unwrap_or(-1);
if code != 0 {
let msg = body.get("msg").and_then(|v| v.as_str()).unwrap_or("unknown");
anyhow::bail!("feishu ws endpoint error: code={code} msg={msg}");
}
body.get("data")
.and_then(|d| d.get("URL"))
.and_then(|u| u.as_str())
.map(|s| s.to_string())
.ok_or_else(|| anyhow::anyhow!("feishu ws endpoint: missing URL"))
}
/// Get bot identity (open_id) via bot info API.
async fn get_bot_info(
client: &reqwest::Client,
api_base: &str,
token: &str,
) -> anyhow::Result<String> {
let url = format!("{}/open-apis/bot/v3/info", api_base);
let resp = client.get(&url).bearer_auth(token).send().await?;
let body: serde_json::Value = resp.json().await?;
body.get("bot")
.and_then(|b| b.get("open_id"))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.ok_or_else(|| anyhow::anyhow!("feishu bot info: missing open_id"))
}
/// Spawn the feishu WebSocket long-connection task.
/// Returns a JoinHandle that runs until shutdown_rx fires.
pub async fn start_websocket(
adapter: &FeishuAdapter,
event_tx: broadcast::Sender<String>,
mut shutdown_rx: watch::Receiver<bool>,
) -> anyhow::Result<tokio::task::JoinHandle<()>> {
let token_cache = adapter.token_cache.clone();
let bot_open_id_store = adapter.bot_open_id.clone();
let dedupe = adapter.dedupe.clone();
let config = adapter.config.clone();
let client = adapter.client.clone();
let name_cache = adapter.name_cache.clone();
let bot_turns = adapter.bot_turns.clone();
let participated_threads = adapter.participated_threads.clone();
let multibot_threads = adapter.multibot_threads.clone();
let handle = tokio::spawn(async move {
let mut backoff_secs = 1u64;
loop {
let result = ws_connect_loop(
&token_cache,
&bot_open_id_store,
&dedupe,
&config,
&client,
&event_tx,
&mut shutdown_rx,
&name_cache,
&bot_turns,
&participated_threads,
&multibot_threads,
)
.await;
if *shutdown_rx.borrow() {
info!("feishu websocket shutting down");
break;
}
match result {
Ok(()) => {
info!("feishu websocket disconnected, reconnecting...");
backoff_secs = 1;
}
Err(e) => {
tracing::error!(err = %e, backoff = backoff_secs, "feishu websocket error, reconnecting...");
backoff_secs = (backoff_secs * 2).min(120);
}
}
tokio::select! {
_ = tokio::time::sleep(std::time::Duration::from_secs(backoff_secs)) => {}
_ = shutdown_rx.changed() => { break; }
}
}
});
Ok(handle)
}
/// Single WebSocket connection lifecycle.
#[allow(clippy::too_many_arguments)]
async fn ws_connect_loop(
token_cache: &Arc<FeishuTokenCache>,
bot_open_id_store: &Arc<RwLock<Option<String>>>,
dedupe: &Arc<DedupeCache>,
config: &FeishuConfig,
client: &reqwest::Client,
event_tx: &broadcast::Sender<String>,
shutdown_rx: &mut watch::Receiver<bool>,
name_cache: &Arc<std::sync::Mutex<HashMap<String, String>>>,
bot_turns: &Arc<std::sync::Mutex<HashMap<String, u32>>>,
participated_threads: &Arc<std::sync::Mutex<HashMap<String, Instant>>>,
multibot_threads: &Arc<std::sync::Mutex<HashMap<String, Instant>>>,
) -> anyhow::Result<()> {
let api_base = config.api_base();
// Refresh bot identity on each reconnect in case it was not resolved earlier
if bot_open_id_store.read().await.is_none() {
if let Ok(token) = token_cache.get_token(client).await {
if let Ok(bot_id) = get_bot_info(client, &api_base, &token).await {
info!(bot_open_id = %bot_id, "feishu bot identity resolved on reconnect");
*bot_open_id_store.write().await = Some(bot_id);
}
}
}
let ws_url = get_ws_endpoint(client, &api_base, &config.app_id, &config.app_secret).await?;
info!(url = %ws_url, "feishu websocket connecting");
let (ws_stream, _) = tokio_tungstenite::connect_async(&ws_url).await?;
let (mut ws_tx, mut ws_rx) = ws_stream.split();
info!("feishu websocket connected");
loop {
tokio::select! {
msg = ws_rx.next() => {
match msg {
Some(Ok(tokio_tungstenite::tungstenite::Message::Text(text))) => {
handle_ws_message(
&text, bot_open_id_store, dedupe, config, event_tx,
name_cache, token_cache, client, bot_turns, participated_threads, multibot_threads,
).await;
}
Some(Ok(tokio_tungstenite::tungstenite::Message::Ping(data))) => {
let _ = ws_tx.send(tokio_tungstenite::tungstenite::Message::Pong(data)).await;
}
Some(Ok(tokio_tungstenite::tungstenite::Message::Close(_))) | None => {
return Ok(());
}
Some(Err(e)) => {
return Err(anyhow::anyhow!("websocket error: {e}"));
}
Some(Ok(tokio_tungstenite::tungstenite::Message::Binary(data))) => {
match WsFrame::decode(data.as_ref()) {
Ok(frame) => {
// method=1 is data frame (events), method=0 is control
if frame.method == 1 {
if let Some(ref payload) = frame.payload {
if let Ok(text) = String::from_utf8(payload.clone()) {
handle_ws_message(
&text, bot_open_id_store, dedupe, config, event_tx,
name_cache, token_cache, client, bot_turns, participated_threads, multibot_threads,
).await;
}
}
// Send ACK: echo frame back with {"code":200} payload
let mut ack = frame.clone();
ack.payload = Some(b"{\"code\":200}".to_vec());
let ack_bytes = ack.encode_to_vec();
let _ = ws_tx.send(
tokio_tungstenite::tungstenite::Message::Binary(ack_bytes)
).await;
}
}
Err(e) => {
tracing::debug!(err = %e, len = data.len(), "feishu ws protobuf decode failed");
}
}
}
_ => {}
}
}
_ = shutdown_rx.changed() => {
let _ = ws_tx.send(tokio_tungstenite::tungstenite::Message::Close(None)).await;
return Ok(());
}
}
}
}
/// Process a single WebSocket text message.
#[allow(clippy::too_many_arguments)]
async fn handle_ws_message(
text: &str,
bot_open_id_store: &Arc<RwLock<Option<String>>>,
dedupe: &Arc<DedupeCache>,
config: &FeishuConfig,
event_tx: &broadcast::Sender<String>,
name_cache: &Arc<std::sync::Mutex<HashMap<String, String>>>,
token_cache: &Arc<FeishuTokenCache>,
client: &reqwest::Client,
bot_turns: &Arc<std::sync::Mutex<HashMap<String, u32>>>,
participated_threads: &Arc<std::sync::Mutex<HashMap<String, Instant>>>,
multibot_threads: &Arc<std::sync::Mutex<HashMap<String, Instant>>>,
) {
let envelope: FeishuEventEnvelope = match serde_json::from_str(text) {
Ok(e) => e,
Err(_) => return,
};
// Handle challenge frame (Feishu may send this in WS mode for verification)
if let Some(ref challenge) = envelope.challenge {
tracing::debug!(challenge = %challenge, "feishu ws challenge received (ignored in WS mode)");
return;
}
// Debug: log sender_type for diagnosing bot-to-bot loops
if let Some(ref event) = envelope.event {
if let Some(ref sender) = event.sender {
tracing::debug!(
sender_type = ?sender.sender_type,
sender_id = ?sender.sender_id.as_ref().and_then(|s| s.open_id.as_deref()),
"feishu ws event sender"
);
}
}
// Dedupe by event_id
if let Some(ref header) = envelope.header {