forked from tinyhumansai/openhuman
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
4450 lines (4199 loc) · 171 KB
/
mod.rs
File metadata and controls
4450 lines (4199 loc) · 171 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
//! Franz-style embedded webview accounts.
//!
//! Hosts third-party web apps (WhatsApp Web, Slack, …) as a child Tauri
//! `Webview` positioned inside the main React window at a rect chosen by the
//! UI. A small per-provider "recipe" JS file is injected via
//! `initialization_script` to scrape the DOM and pipe state back to Rust as
//! `webview_recipe_event` invocations. Rust forwards each event up to the
//! React UI as a `webview:event` Tauri event; React is responsible for
//! persisting interesting payloads to memory via the existing core RPC.
//!
//! Architecture:
//! React → invoke('webview_account_open', …) → spawn child Webview
//! React → invoke('webview_account_bounds', …) → reposition / resize
//! recipe → invoke('webview_recipe_event', …) → emit('webview:event', …)
//!
//! Per-account session isolation: each account gets its own
//! `data_directory` under `{app_local_data_dir}/webview_accounts/{id}` so
//! cookies and storage don't bleed between accounts (best-effort on
//! WKWebView — see Tauri docs on `data_store_identifier` for the macOS path).
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Mutex;
#[cfg(target_os = "linux")]
use std::sync::{mpsc::sync_channel, OnceLock};
use std::time::{Duration, Instant};
use chrono::{TimeZone, Utc};
use serde::{Deserialize, Serialize};
use serde_json::json;
use tauri::{
webview::NewWindowResponse, AppHandle, Emitter, LogicalPosition, LogicalSize, Manager, Runtime,
Url, WebviewBuilder, WebviewUrl,
};
#[cfg(windows)]
use tauri_plugin_notification::NotificationExt;
// `ImplBrowser` exposes `Browser::identifier()` — bring the trait into scope
// so the `with_webview` callback can read the CEF browser id.
use cef::ImplBrowser;
use crate::cdp;
const RUNTIME_JS: &str = include_str!("runtime.js");
const LINKEDIN_RECIPE_JS: &str = include_str!("../../recipes/linkedin/recipe.js");
const GOOGLE_MEET_RECIPE_JS: &str = include_str!("../../recipes/google-meet/recipe.js");
/// Registered providers and their service URLs. Add a new arm here plus a
/// recipe.js file under `recipes/<id>/` to support another provider.
fn provider_url(provider: &str) -> Option<&'static str> {
match provider {
"whatsapp" => Some("https://web.whatsapp.com/"),
"wechat" => Some("https://web.wechat.com/"),
"telegram" => Some("https://web.telegram.org/k/"),
"linkedin" => Some("https://www.linkedin.com/messaging/"),
"slack" => Some("https://app.slack.com/client/"),
"discord" => Some("https://discord.com/channels/@me"),
"google-meet" => Some("https://meet.google.com/"),
"zoom" => Some("https://zoom.us/"),
"browserscan" => Some("https://www.browserscan.net/bot-detection"),
_ => None,
}
}
/// Returns the injected recipe.js for providers that still rely on the
/// JS-bridge ingest path. Migrated providers (whatsapp, telegram, slack,
/// discord, browserscan) return `None` — their scraping runs natively via
/// CDP in the per-provider scanner modules.
fn provider_recipe_js(provider: &str) -> Option<&'static str> {
match provider {
"linkedin" => Some(LINKEDIN_RECIPE_JS),
"google-meet" => Some(GOOGLE_MEET_RECIPE_JS),
_ => None,
}
}
/// Whether this provider is supported at all. Derived from
/// `provider_url` so there's one canonical list — new providers added
/// to the `provider_url` match automatically become "supported" here.
fn provider_is_supported(provider: &str) -> bool {
provider_url(provider).is_some()
}
/// Host suffixes the embedded webview is allowed to navigate within. Any
/// navigation to a host outside this set is cancelled and opened in the
/// user's default browser instead. Meet includes Google's auth and
/// static asset hosts so the OAuth redirect loop works; Discord includes
/// its CDN subdomains for the same reason.
fn provider_allowed_hosts(provider: &str) -> &'static [&'static str] {
match provider {
"whatsapp" => &["whatsapp.com", "whatsapp.net", "wa.me"],
"wechat" => &[
"wechat.com",
"wx.qq.com",
"weixin.qq.com",
"login.weixin.qq.com",
],
"telegram" => &["telegram.org", "t.me"],
"linkedin" => &[
"linkedin.com",
"licdn.com",
"accounts.google.com",
"accounts.googleusercontent.com",
"ssl.gstatic.com",
"fonts.gstatic.com",
"lh3.googleusercontent.com",
"oauth2.googleapis.com",
"www.googleapis.com",
],
"slack" => &[
"slack.com",
"slack-edge.com",
"slackb.com",
"accounts.google.com",
"accounts.googleusercontent.com",
"ssl.gstatic.com",
"fonts.gstatic.com",
"lh3.googleusercontent.com",
"oauth2.googleapis.com",
"www.googleapis.com",
],
"discord" => &[
"discord.com",
"discord.gg",
"discordapp.com",
"discordapp.net",
],
"google-meet" => &[
"google.com",
"googleusercontent.com",
"gstatic.com",
"googleapis.com",
],
"zoom" => &[
"zoom.us",
"zoom.com",
"zoomgov.com",
"zdassets.com",
"accounts.google.com",
"accounts.googleusercontent.com",
"ssl.gstatic.com",
"fonts.gstatic.com",
"lh3.googleusercontent.com",
"oauth2.googleapis.com",
"www.googleapis.com",
],
"browserscan" => &["browserscan.net"],
_ => &[],
}
}
/// Rewrite a provider-specific native-app deep link (e.g. Zoom's
/// `zoomus://zoom.us/join?...`) into a web-client URL so the meeting stays
/// inside the embedded webview instead of failing with
/// ERR_UNKNOWN_URL_SCHEME (CEF has no handler for these schemes).
///
/// Returns `Some(rewritten)` when the provider claims the scheme and a
/// valid web-client URL can be built; `None` otherwise (caller should
/// leave the navigation alone).
fn rewrite_provider_deep_link(provider: &str, url: &Url) -> Option<Url> {
if provider != "zoom" {
return None;
}
if !matches!(url.scheme(), "zoomus" | "zoommtg") {
return None;
}
// Pull the meeting id out of the query string. Zoom uses `confno` on
// both `action=join` (joining) and `action=start` (hosting) flows.
let confno = url
.query_pairs()
.find(|(k, _)| k == "confno")
.map(|(_, v)| v.into_owned());
let pwd = url
.query_pairs()
.find(|(k, _)| k == "pwd" || k == "tk")
.map(|(_, v)| v.into_owned());
// Build the rewritten URL via `Url` so `confno` and `pwd` are
// percent-encoded — inbound Zoom tokens can contain reserved chars
// (`&`, `#`, `%`, `+`, …) that would corrupt a hand-rolled
// `format!(…)` string and silently break the join/host flow.
match confno {
Some(id) if !id.is_empty() => {
// Base without trailing slash; `path_segments_mut().push(id)`
// appends `/id` cleanly. A trailing `/` on the base would yield
// `/wc/join//id` (empty segment preserved by the Url spec).
let mut rewritten = Url::parse("https://app.zoom.us/wc/join").ok()?;
rewritten.path_segments_mut().ok()?.push(&id);
if let Some(p) = pwd.filter(|p| !p.is_empty()) {
rewritten.query_pairs_mut().append_pair("pwd", &p);
}
Some(rewritten)
}
_ => Url::parse("https://app.zoom.us/wc/home").ok(),
}
}
/// `true` if `url` is considered in-app for `provider`. Non-HTTP(S)
/// schemes (`about:blank`, `data:`, `blob:`) have no host and are always
/// allowed so the webview's own internal navigations keep working.
/// Unknown providers are also permissive — better to accidentally keep a
/// link in-app than to leak it to the system browser.
fn url_is_internal(provider: &str, url: &Url) -> bool {
let Some(host) = url.host_str() else {
return true;
};
// Google services route the post-2FA `SetSID` cookie-setting hop
// through `accounts.youtube.com` and ccTLD `accounts.google.<rest>`
// hosts that aren't covered by the suffix-based allowlist. Without
// this, the auth chain breaks mid-flight and leaks to the system
// browser (#1053 sign-in leak surfaced in dev:app log line:
// "external navigation https://accounts.youtube.com/accounts/SetSID?...
// → system browser"). Whitelist the full Google SSO host family for
// any provider that uses Google identity.
if (provider == "gmail" || provider_supports_google_sso(provider)) && is_google_sso_host(host) {
return true;
}
let allowed = provider_allowed_hosts(provider);
if allowed.is_empty() {
return true;
}
allowed
.iter()
.any(|suffix| host == *suffix || host.ends_with(&format!(".{}", suffix)))
}
/// `true` if the provider needs `window.open(url)` to return a live
/// window-handle (i.e. the calling site reads the return value and aborts
/// on falsey). Slack Huddles go through `openManagedChildWindow` which
/// calls `window.open("about:blank", …)` and then programmatically
/// navigates the returned popup to the huddle UI. Denying the popup
/// makes the huddle call fail silently with a `beacon/error`. For these
/// cases we allow the default popup so CEF spawns an in-app child window
/// and returns a real handle to the caller.
///
/// Match is intentionally narrow — only the popup URLs the provider
/// actually needs in-app pass. Cmd/Ctrl-click and `target="_blank"`
/// on ordinary links (which carry a concrete URL) still route out to
/// the user's default browser.
fn popup_should_stay_in_app(provider: &str, url: &Url) -> bool {
match provider {
"slack" => {
// Slack's huddle flow opens `about:blank` first, then navigates
// the popup to the huddle URL — at popup-creation time there is
// no host yet. Also accept same-origin slack.com hosts so direct
// `window.open("https://app.slack.com/...")` calls stay in-app.
if url.scheme() == "about" {
return true;
}
match url.host_str() {
Some(host) => host == "app.slack.com" || host.ends_with(".slack.com"),
None => false,
}
}
"zoom" => {
// Zoom's "Join from browser" / WebClient launch can go through a
// `window.open("https://app.zoom.us/wc/...")` popup instead of an
// in-page navigation. Keep those (and any deep-link-rewritten
// popup targeting the same path) inside the embedded webview so
// the meeting doesn't pop out to the system browser.
match url.host_str() {
Some(host) => {
(host == "app.zoom.us" || host == "zoom.us") && url.path().starts_with("/wc/")
}
None => false,
}
}
"linkedin" => {
// LinkedIn's "Sign in with Google" button is rendered as a Google
// Identity Services (GSI) iframe loaded from
// `accounts.google.com/gsi/button`. When the user clicks it, GSI
// calls `window.open("https://accounts.google.com/gsi/select?...",
// "gsig", "width=500,height=600,...")` to show the account chooser.
//
// This popup MUST stay as a real in-app child window — NOT routed
// to the system browser (blank screen) and NOT a parent navigation
// (the parent page would be replaced, so the postMessage credential
// callback from the popup can never reach LinkedIn's JS handler).
//
// After the user selects an account the popup postMessages the
// signed credential back to the opener; LinkedIn's GSI callback
// receives it and completes sign-in (#1021).
match url.host_str() {
Some(host) => {
is_google_sso_host(host) && url.path().to_ascii_lowercase().contains("gsi")
}
None => false,
}
}
_ => false,
}
}
/// `true` if `scheme` is a known provider native-desktop-app deep-link
/// scheme. We suppress these instead of routing them to the system
/// browser because macOS hands them to the native provider app
/// (e.g. `slack://magic-login/<token>` signs the native Slack app into
/// the workspace, breaking embedded-webview isolation: the workspace's
/// session ends up inside the native client even though the user only
/// signed in via OpenHuman's embedded webview).
///
/// The HTTPS fallback in each provider's web flow handles sign-in
/// without the deep link, so suppression is safe — the page just
/// continues on the next link in the sequence.
///
/// Caller contract: only suppress when [`rewrite_provider_deep_link`]
/// has already returned `None` for the URL. Schemes we DO know how to
/// rewrite into a web-client URL (e.g. `zoomus://`) must take the
/// rewrite path first; those flows expect to stay in-app, not be
/// silently dropped.
fn is_provider_native_deep_link_scheme(scheme: &str) -> bool {
matches!(
scheme,
"slack" | "discord" | "tg" | "msteams" | "zoomus" | "zoommtg"
)
}
/// `true` if this provider lets users sign in with their Google
/// account from inside the embedded webview.
///
/// Slack workspaces commonly enable "Sign in with Google" SSO, so the
/// Google OAuth popup flow (`window.open("https://accounts.google.com/...")`)
/// must stay in the per-account CEF session — exactly the same way it
/// has to for Google Meet. Routing it to the system browser leaks the
/// auth cookie into the wrong jar and breaks sign-in (#1036).
///
/// Keep this list narrow: only providers that actually need to issue
/// `accounts.google.com` popups should be listed. Other providers
/// continue to fall through to the default popup-handling path.
fn provider_supports_google_sso(provider: &str) -> bool {
matches!(provider, "google-meet" | "slack" | "zoom" | "linkedin")
}
/// `true` if a popup request should be denied AND the parent webview
/// should be navigated to the popup URL instead.
///
/// Used for Google's "Sign in" / "Use another account" flow on embedded
/// providers that support Google SSO: clicking the link issues
/// `window.open("https://accounts.google.com/...")`. We can't route
/// that to the system browser (the auth cookie would land in the
/// wrong jar) and we don't want to let CEF spawn an unmanaged child
/// window (it has no host rect, so it renders blank/black). The safe
/// option is to deny the popup and replace the parent's URL so the
/// in-app webview finishes the auth flow inside the embedded session.
fn popup_should_navigate_parent(provider: &str, url: &Url) -> Option<Url> {
if !provider_supports_google_sso(provider) {
return None;
}
if url.scheme() == "about" {
return None;
}
if is_google_auth_popup(url) {
return Some(url.clone());
}
// Gmeet: "Start an instant meeting" / "New meeting" / clicking
// a meeting code link calls `window.open(meet.google.com/<roomid>)`
// to launch the room. Default popup handling would route the
// URL to the user's system browser, leaking the Meet session
// out of OpenHuman entirely. Deny the popup and navigate the
// embedded parent into the room URL instead — matches the
// user's expectation that the meeting stays in-app.
if provider == "google-meet" {
if let Some(host) = url.host_str() {
if host == "meet.google.com" {
return Some(url.clone());
}
}
}
None
}
/// `true` if `host` is a Google SSO / account-handoff host that may
/// participate in the OAuth flow for any Google service (Meet, Gmail,
/// Drive, etc.). Google rotates the post-2FA `SetSID` cookie-setting hop
/// across `accounts.google.<cctld>` and `accounts.youtube.com` (sic — the
/// YouTube subdomain is part of the Google identity infra), so a literal
/// `accounts.google.com` match misses real auth popups and leaks them to
/// the system browser.
///
/// Match family:
/// - `accounts.google.com`
/// - `accounts.google.<cctld>` — e.g. `accounts.google.co.in`, `accounts.google.co.uk`,
/// `accounts.google.de`
/// - `accounts.googleusercontent.com`
/// - `accounts.youtube.com` (post-2FA `SetSID` hop)
/// - `myaccount.google.com`
fn is_google_sso_host(host: &str) -> bool {
let host = host.to_ascii_lowercase();
if host == "accounts.google.com"
|| host == "accounts.googleusercontent.com"
|| host == "accounts.youtube.com"
|| host == "myaccount.google.com"
{
return true;
}
// ccTLD variants: `accounts.google.<cctld>`. We must reject phishing
// shapes like `accounts.google.com.evil` and `accounts.google.co.attacker`
// — the dots-only check we used previously accepted both because
// `com.evil` and `co.attacker` each have one dot. Anchor the suffix
// against a real ccTLD shape: either a single 2-letter cc tld
// (`accounts.google.de`, `accounts.google.fr`) OR a 2-label form
// `<sld>.<cc>` where sld ∈ {co, com, net, org} (`accounts.google.co.in`,
// `accounts.google.com.au`).
if let Some(rest) = host.strip_prefix("accounts.google.") {
let labels: Vec<&str> = rest.split('.').collect();
let is_cc = |s: &str| s.len() == 2 && s.chars().all(|c| c.is_ascii_alphabetic());
return match labels.as_slice() {
[tld] => is_cc(tld),
[sld, tld] => matches!(*sld, "co" | "com" | "net" | "org") && is_cc(tld),
_ => false,
};
}
false
}
fn is_google_auth_popup(url: &Url) -> bool {
let Some(host) = url.host_str() else {
return false;
};
if !is_google_sso_host(host) {
return false;
}
let path = url.path().to_ascii_lowercase();
if path.contains("signin")
|| path.contains("servicelogin")
|| path.contains("accountchooser")
|| path.contains("chooseaccount")
|| path.contains("setsid")
|| path.contains("oauth2")
{
return true;
}
url.query_pairs().any(|(key, value)| {
let k = key.to_ascii_lowercase();
let v = value.to_ascii_lowercase();
matches!(k.as_str(), "flowname" | "service" | "continue")
&& (v.contains("signin")
|| v.contains("servicelogin")
|| v.contains("accountchooser")
|| v.contains("chooseaccount")
|| v.contains("meet.google.com")
|| v.contains("mail.google.com")
|| v.contains("linkedin.com"))
})
}
/// `true` if a gmeet navigation lands on Google's Workspace marketing page
/// for Meet — the host bounce that fires when an unauthenticated webview hits
/// `meet.google.com`.
///
/// The `on_navigation` rewrite is scoped to this exact path family so we
/// don't hijack legitimate `workspace.google.com` pages a user might reach
/// from inside Meet (admin console links, Workspace Status, support pages,
/// etc.). Matches `workspace.google.com` (and any subdomain) AND a path
/// starting with `/products/meet` — empirically the only path Google's
/// edge bounces unauthenticated Meet GETs to (`/products/meet/` or
/// `/products/meet/<sub>`).
fn is_gmeet_marketing_redirect(host: &str, path: &str) -> bool {
let host = host.to_ascii_lowercase();
let host_matches = host == "workspace.google.com" || host.ends_with(".workspace.google.com");
if !host_matches {
return false;
}
let p = path.to_ascii_lowercase();
p == "/products/meet" || p == "/products/meet/" || p.starts_with("/products/meet/")
}
fn redact_navigation_url(url: &Url) -> String {
let mut safe = url.clone();
safe.set_query(None);
safe.set_fragment(None);
safe.to_string()
}
fn redact_native_deep_link_url(url: &Url) -> String {
format!("{}://<redacted>", url.scheme())
}
/// Unwrap provider-side "link safety" redirects so the system browser
/// lands on the real destination.
///
/// These wrappers (LinkedIn's `/safety/go/?url=…`, etc.) require the
/// user to be logged into the provider in the destination browser. In
/// our setup the session lives inside the embedded CEF webview's cookie
/// jar, not the user's default browser — opening the wrapper URL there
/// shows a broken safety page instead of completing the redirect.
/// Extract the `url` query param and return the resolved destination.
fn unwrap_provider_redirect(url: &Url) -> Option<Url> {
let host = url.host_str()?;
let path = url.path();
let matches_linkedin = (host == "www.linkedin.com" || host == "linkedin.com")
&& (path == "/safety/go/" || path == "/safety/go" || path == "/redir/redirect");
if !matches_linkedin {
return None;
}
let (_, raw) = url.query_pairs().find(|(k, _)| k == "url")?;
Url::parse(&raw).ok()
}
/// Fire-and-forget handoff to the OS default URL handler. Any error is
/// logged but not propagated — we've already cancelled the in-app
/// navigation so there's nowhere to surface a failure to.
///
/// On macOS we shell out to `/usr/bin/open` directly rather than via
/// `tauri_plugin_opener::open_url`: the plugin returned Ok but no browser
/// actually launched in the CEF runtime (suspected sandbox/launch-service
/// interaction with the `open` crate's detached spawn). The direct
/// Command call is equivalent to what a user would type in Terminal and
/// works reliably.
fn open_in_system_browser(url: &str) {
#[cfg(target_os = "macos")]
{
match std::process::Command::new("/usr/bin/open").arg(url).spawn() {
Ok(_) => log::info!("[webview-accounts] opened externally (macos open): {}", url),
Err(e) => log::warn!(
"[webview-accounts] /usr/bin/open {} failed: {} — falling back to opener plugin",
url,
e
),
}
}
#[cfg(not(target_os = "macos"))]
{
match tauri_plugin_opener::open_url(url, None::<&str>) {
Ok(()) => log::info!("[webview-accounts] opened externally: {}", url),
Err(e) => log::warn!("[webview-accounts] open_url({}) failed: {}", url, e),
}
}
}
fn payload_string(payload: &serde_json::Value, key: &str) -> Option<String> {
payload
.get(key)
.and_then(|v| v.as_str())
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
}
fn payload_bool(payload: &serde_json::Value, key: &str) -> Option<bool> {
payload.get(key).and_then(|v| v.as_bool())
}
fn payload_i64(payload: &serde_json::Value, key: &str) -> Option<i64> {
payload.get(key).and_then(|v| v.as_i64())
}
fn first_message_field(payload: &serde_json::Value, key: &str) -> Option<String> {
payload
.get("messages")
.and_then(|v| v.as_array())
.and_then(|messages| messages.first())
.and_then(|message| message.get(key))
.and_then(|v| v.as_str())
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
}
fn event_timestamp_rfc3339(ts_ms: Option<i64>) -> String {
ts_ms
.and_then(|ts| Utc.timestamp_millis_opt(ts).single())
.unwrap_or_else(Utc::now)
.to_rfc3339()
}
fn normalize_provider_surfaces_event(args: &RecipeEventArgs) -> Option<serde_json::Value> {
if args.kind != "ingest" {
return None;
}
let entity_id = payload_string(&args.payload, "entity_id")
.or_else(|| payload_string(&args.payload, "threadId"))
.or_else(|| payload_string(&args.payload, "chatId"))
.or_else(|| payload_string(&args.payload, "snapshotKey"))
.unwrap_or_else(|| {
format!(
"{}:{}:{}",
args.provider,
args.account_id,
args.ts.unwrap_or_else(|| Utc::now().timestamp_millis())
)
});
let thread_id = payload_string(&args.payload, "threadId")
.or_else(|| payload_string(&args.payload, "chatId"))
.or_else(|| payload_string(&args.payload, "conversationId"));
let title = payload_string(&args.payload, "title")
.or_else(|| payload_string(&args.payload, "chatName"))
.or_else(|| payload_string(&args.payload, "channelName"));
let snippet = payload_string(&args.payload, "snippet")
.or_else(|| first_message_field(&args.payload, "body"));
let sender_name = payload_string(&args.payload, "senderName")
.or_else(|| first_message_field(&args.payload, "from"));
let sender_handle = payload_string(&args.payload, "senderHandle");
let deep_link = payload_string(&args.payload, "deepLink");
let unread = payload_i64(&args.payload, "unread").unwrap_or(0);
let requires_attention = payload_bool(&args.payload, "requires_attention")
.unwrap_or(unread > 0 || sender_name.is_some() || snippet.is_some());
Some(json!({
"provider": args.provider,
"account_id": args.account_id,
"event_kind": args.kind,
"entity_id": entity_id,
"thread_id": thread_id,
"title": title,
"snippet": snippet,
"sender_name": sender_name,
"sender_handle": sender_handle,
"timestamp": event_timestamp_rfc3339(args.ts),
"deep_link": deep_link,
"requires_attention": requires_attention,
"raw_payload": args.payload,
}))
}
async fn post_provider_surfaces_event(args: &RecipeEventArgs) -> Result<(), String> {
let Some(params) = normalize_provider_surfaces_event(args) else {
return Ok(());
};
let body = json!({
"jsonrpc": "2.0",
"id": 1,
"method": "openhuman.provider_surfaces_ingest_event",
"params": params,
});
let url = std::env::var("OPENHUMAN_CORE_RPC_URL")
.unwrap_or_else(|_| "http://127.0.0.1:7788/rpc".to_string());
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(10))
.build()
.map_err(|e| format!("http client: {e}"))?;
let resp = client
.post(&url)
.json(&body)
.send()
.await
.map_err(|e| format!("POST {url}: {e}"))?;
let status = resp.status();
if !status.is_success() {
let body = resp.text().await.unwrap_or_default();
return Err(format!("{status}: {body}"));
}
let v: serde_json::Value = resp.json().await.map_err(|e| format!("decode: {e}"))?;
if let Some(err) = v.get("error") {
return Err(format!("rpc error: {err}"));
}
Ok(())
}
/// Human-readable label used as the title prefix on native notifications
/// so users can tell which provider fired the ping. Matches the labels
/// in the frontend `PROVIDERS` registry.
pub fn provider_display_name(provider: &str) -> &'static str {
match provider {
"whatsapp" => "WhatsApp",
"wechat" => "WeChat",
"telegram" => "Telegram",
"linkedin" => "LinkedIn",
"slack" => "Slack",
"discord" => "Discord",
"google-meet" => "Google Meet",
"zoom" => "Zoom",
"browserscan" => "BrowserScan",
_ => "OpenHuman",
}
}
#[derive(Default)]
pub struct WebviewAccountsState {
/// account_id -> webview label (we use `acct_<id>` as the label).
inner: Mutex<HashMap<String, String>>,
/// account_id -> provider id. Kept so late reveal/close paths can log
/// provider-scoped diagnostics without trusting frontend echo fields.
account_providers: Mutex<HashMap<String, String>>,
/// account_id -> CEF `Browser::identifier()`. Populated asynchronously
/// inside the `with_webview` callback once the renderer hands us the
/// browser handle, and consumed at close/purge time so we can call
/// `tauri_runtime_cef::notification::unregister` without leaking
/// per-browser handler entries across account churn.
browser_ids: Mutex<HashMap<String, i32>>,
/// account_id -> CDP session task. One long-lived task per account
/// keeps the UA override resident (see `cdp::session`); aborted on
/// close/purge so reopen cycles don't stack multiple live loops.
cdp_sessions: Mutex<HashMap<String, tokio::task::JoinHandle<()>>>,
/// account_id -> 15s `webview-account:load{state:"timeout"}` watchdog.
/// Aborted in close/purge so a watchdog spawned for a now-closed
/// account can't fire a stale timeout against a freshly-reused id.
load_watchdogs: Mutex<HashMap<String, tokio::task::JoinHandle<()>>>,
/// account_id of webviews that have already emitted their first
/// `webview-account:load{state:"finished"}` event. Used to dedup
/// triple-signal fires (native on_page_load, CDP `Page.loadEventFired`,
/// 15 s watchdog) so the frontend only reveals once per cold open.
loaded_accounts: Mutex<HashSet<String>>,
/// Last bounds requested by the frontend for a given account, captured at
/// `webview_account_open` time so the off-screen-spawned webview can be
/// revealed at the right rect without the frontend having to round-trip
/// them again.
requested_bounds: Mutex<HashMap<String, Bounds>>,
/// account_id -> `Instant` captured at the moment the cold spawn returns
/// from `add_child`. Consumed by `webview_account_reveal` to compute
/// `elapsed_ms` (spawn -> frontend reveal call) for the diagnostic log
/// instrumented for the Slack first-load investigation (#1036). Cleared
/// alongside `loaded_accounts` on close/purge so a subsequent reopen
/// starts fresh.
spawn_started_at: Mutex<HashMap<String, Instant>>,
/// Runtime notification-bypass controls used by the settings UI.
notification_bypass: Mutex<NotificationBypassPrefs>,
/// Per-label rewrite counter for the gmeet `workspace.google.com`
/// marketing intercept. Google's edge SSR-redirects unauthenticated
/// `meet.google.com` GETs back to `workspace.google.com/products/meet/`,
/// so an unguarded rewrite (see `:1534-1559`) ping-pongs forever and
/// the page never lands. We track `(last_attempt, attempts_in_window)`
/// per webview label and bail to the Google sign-in flow after a
/// threshold so the user breaks out of the loop.
gmeet_marketing_rewrites: Mutex<HashMap<String, (Instant, u32)>>,
/// Per-label "awaiting post-auth handoff" flag. Set when the gmeet
/// rewrite-loop bail navigates to `accounts.google.com/ServiceLogin`,
/// consumed (single-shot) by the `myaccount.google.com` intercept so
/// only the immediate post-auth bounce gets rewritten back to Meet —
/// legitimate user-initiated `myaccount.google.com` navigations (e.g.
/// "Manage your Google Account" from the avatar menu) are passed
/// through unchanged.
gmeet_awaiting_handoff: Mutex<HashSet<String>>,
/// account_ids spawned via `webview_account_prewarm` that have not yet
/// been opened by the user. Issue #1233 — emit_load_finished suppresses
/// `webview-account:load` events for these so the React UI never sees
/// load/timeout signals for an account it didn't ask to open. The flag
/// is cleared on the first user-initiated `webview_account_open`
/// (warm-reopen branch) and on close/purge so subsequent reopens flow
/// through the normal cold-load lifecycle.
prewarm_accounts: Mutex<HashSet<String>>,
}
/// Threshold and window for the gmeet workspace-marketing rewrite loop
/// breaker. After `GMEET_REWRITE_MAX_ATTEMPTS` rewrites within
/// `GMEET_REWRITE_WINDOW`, we bail to the Google sign-in URL instead of
/// rewriting again.
pub(crate) const GMEET_REWRITE_MAX_ATTEMPTS: u32 = 3;
pub(crate) const GMEET_REWRITE_WINDOW: Duration = Duration::from_secs(5);
/// Result of consulting the gmeet marketing-redirect counter.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum GmeetRewriteAction {
/// Allow the rewrite — fewer than `GMEET_REWRITE_MAX_ATTEMPTS` attempts in
/// the current window.
Rewrite,
/// Loop detected — caller should navigate to the Google sign-in URL
/// instead of rewriting back to `meet.google.com`.
Bail,
}
impl WebviewAccountsState {
/// Drop the gmeet marketing-rewrite counter for `label`. Called after
/// the post-auth handoff so a future workspace-marketing bounce (which
/// shouldn't occur post-auth, but could on session expiry) gets a fresh
/// counter window instead of inheriting half-saturated state from the
/// pre-auth loop.
pub(crate) fn clear_gmeet_marketing_rewrite(&self, label: &str) {
if let Ok(mut g) = self.gmeet_marketing_rewrites.lock() {
g.remove(label);
}
}
/// Mark `label` as awaiting the post-auth `myaccount.google.com` →
/// `meet.google.com` handoff. Set by the rewrite-loop bail right
/// before navigating to `accounts.google.com/ServiceLogin?continue=`,
/// so the next `myaccount.google.com` commit on this label is treated
/// as the auth chain's terminal hop (the `?utm_source=sign_in_no_continue`
/// dump-page) and gets force-redirected to Meet.
pub(crate) fn mark_awaiting_gmeet_handoff(&self, label: &str) {
if let Ok(mut g) = self.gmeet_awaiting_handoff.lock() {
g.insert(label.to_string());
}
}
/// Single-shot consume of the post-auth handoff flag for `label`.
/// Returns `true` exactly once after `mark_awaiting_gmeet_handoff`,
/// then resets so subsequent `myaccount.google.com` navigations
/// (e.g. user-initiated profile/settings visits) pass through as
/// normal and aren't hijacked back to Meet.
pub(crate) fn take_awaiting_gmeet_handoff(&self, label: &str) -> bool {
match self.gmeet_awaiting_handoff.lock() {
Ok(mut g) => g.remove(label),
Err(_) => false,
}
}
/// Increment the per-label gmeet marketing-rewrite counter for `now` and
/// decide whether to rewrite or bail. Resets the counter when the last
/// attempt was outside `GMEET_REWRITE_WINDOW` so a future genuine
/// `workspace.google.com` navigation (e.g. user clicks a link inside Meet
/// after sign-in) gets intercepted normally.
pub(crate) fn track_gmeet_marketing_rewrite(
&self,
label: &str,
now: Instant,
) -> GmeetRewriteAction {
let mut map = match self.gmeet_marketing_rewrites.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
let entry = map.entry(label.to_string()).or_insert((now, 0));
if now.duration_since(entry.0) > GMEET_REWRITE_WINDOW {
*entry = (now, 0);
}
entry.1 += 1;
entry.0 = now;
if entry.1 > GMEET_REWRITE_MAX_ATTEMPTS {
GmeetRewriteAction::Bail
} else {
GmeetRewriteAction::Rewrite
}
}
/// Drain every per-account resource owned by this state and abort the
/// associated background tasks. Returns the `(account_id, label)`
/// pairs of webviews that still need closing — the caller does the
/// actual `wv.close()` because that needs an `AppHandle`. Splitting
/// it out keeps the rest of the teardown unit-testable without
/// constructing a Tauri runtime.
///
/// Aborts CDP session tasks and load watchdogs, unregisters CEF
/// notification handlers, and clears the loaded-accounts /
/// requested-bounds bookkeeping. All collections are drained — a
/// repeat call returns an empty `Vec` and is a safe no-op.
fn drain_for_shutdown(&self) -> Vec<(String, String)> {
let cdp_tasks: Vec<_> = self
.cdp_sessions
.lock()
.ok()
.map(|mut g| g.drain().collect())
.unwrap_or_default();
for (acct, task) in cdp_tasks {
task.abort();
log::debug!("[webview-accounts] shutdown abort cdp account={}", acct);
}
let watchdogs: Vec<_> = self
.load_watchdogs
.lock()
.ok()
.map(|mut g| g.drain().collect())
.unwrap_or_default();
for (acct, task) in watchdogs {
task.abort();
log::debug!(
"[webview-accounts] shutdown abort watchdog account={}",
acct
);
}
let browser_ids: Vec<_> = self
.browser_ids
.lock()
.ok()
.map(|mut g| g.drain().collect())
.unwrap_or_default();
for (acct, browser_id) in browser_ids {
tauri_runtime_cef::notification::unregister(browser_id);
log::debug!(
"[notify-cef] shutdown unregistered handler account={} browser_id={}",
acct,
browser_id
);
}
if let Ok(mut g) = self.loaded_accounts.lock() {
g.clear();
}
if let Ok(mut g) = self.requested_bounds.lock() {
g.clear();
}
if let Ok(mut g) = self.spawn_started_at.lock() {
g.clear();
}
if let Ok(mut g) = self.account_providers.lock() {
g.clear();
}
// Per-label gmeet rewrite counter must clear too — `label_for()`
// reuses the same label on reopen, so a stale saturated entry
// would jump a fresh open straight to the bail URL.
if let Ok(mut g) = self.gmeet_marketing_rewrites.lock() {
g.clear();
}
// Drop the post-auth handoff flag too — a stale flag would
// hijack the first user-initiated `myaccount.google.com` visit
// after a relaunch back to Meet.
if let Ok(mut g) = self.gmeet_awaiting_handoff.lock() {
g.clear();
}
// Issue #1233 — clear prewarm flags so a relaunch can't suppress
// load events for accounts that were prewarmed in the previous
// session.
if let Ok(mut g) = self.prewarm_accounts.lock() {
g.clear();
}
self.inner
.lock()
.ok()
.map(|mut g| g.drain().collect())
.unwrap_or_default()
}
/// Tear down every per-account resource owned by this state — used by
/// the app's `RunEvent::ExitRequested` path so nothing outlives the
/// tokio runtime / `AppHandle` (issue #920).
///
/// On top of [`drain_for_shutdown`], this closes every `acct_*` child
/// webview so CEF browsers tear down before `cef::shutdown()` runs,
/// and tells the per-account scanner registries to forget the
/// account so a future open of the same id starts from a clean slate.
/// All collections are drained — repeat calls are cheap no-ops.
pub fn shutdown_all<R: Runtime>(&self, app: &AppHandle<R>) -> Vec<String> {
teardown_all_account_scanners(app);
let labels = self.drain_for_shutdown();
let mut closed_labels = Vec::with_capacity(labels.len());
for (acct, label) in labels {
teardown_account_scanners(app, &acct);
if let Some(wv) = app.get_webview(&label) {
// Track the label as soon as the webview exists so a failed
// `close()` still participates in the post-close drain poll
// (issue #1120 / CodeRabbit).
closed_labels.push(label.clone());
if let Err(e) = wv.close() {
log::warn!(
"[webview-accounts] shutdown close({label}) failed account={acct}: {e}"
);
}
} else {
log::debug!(
"[webview-accounts] shutdown label already gone account={} label={}",
acct,
label
);
}
}
log::info!(
"[webview-accounts] shutdown_all complete closed_labels={:?}",
closed_labels
);
closed_labels
}
}
/// Abort every provider scanner task tracked by the per-provider
/// registries. Used by full-app shutdown before the per-account state is
/// drained so CDP loops stop even if an account label was already removed
/// from `WebviewAccountsState`.
fn teardown_all_account_scanners<R: Runtime>(app: &AppHandle<R>) {
let mut total = 0usize;
if let Some(registry) =
app.try_state::<std::sync::Arc<crate::whatsapp_scanner::ScannerRegistry>>()
{
total += registry.inner().forget_all();
}
if let Some(registry) = app.try_state::<std::sync::Arc<crate::slack_scanner::ScannerRegistry>>()
{
total += registry.inner().forget_all();
}
if let Some(registry) =
app.try_state::<std::sync::Arc<crate::discord_scanner::ScannerRegistry>>()
{
total += registry.inner().forget_all();
}
if let Some(registry) =
app.try_state::<std::sync::Arc<crate::telegram_scanner::ScannerRegistry>>()
{
total += registry.inner().forget_all();
}
if total > 0 {
log::info!(
"[webview-accounts] aborted {} provider scanner task(s) for shutdown",
total
);
}
}
/// Tell the per-account scanner registries (whatsapp / slack / discord /
/// telegram) to forget `account_id`. Shared by `webview_account_close`,
/// `webview_account_purge`, and `WebviewAccountsState::shutdown_all` so
/// every exit path goes through the same teardown.
fn teardown_account_scanners<R: Runtime>(app: &AppHandle<R>, account_id: &str) {
if let Some(registry) =
app.try_state::<std::sync::Arc<crate::whatsapp_scanner::ScannerRegistry>>()
{
registry.inner().forget(account_id);
}
if let Some(registry) = app.try_state::<std::sync::Arc<crate::slack_scanner::ScannerRegistry>>()
{
registry.inner().forget(account_id);
}
if let Some(registry) =
app.try_state::<std::sync::Arc<crate::discord_scanner::ScannerRegistry>>()
{
registry.inner().forget(account_id);
}
if let Some(registry) =
app.try_state::<std::sync::Arc<crate::telegram_scanner::ScannerRegistry>>()
{
registry.inner().forget(account_id);