-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathrest.rs
More file actions
1232 lines (1143 loc) · 49.2 KB
/
Copy pathrest.rs
File metadata and controls
1232 lines (1143 loc) · 49.2 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
//! HTTP client for TinyHumans / AlphaHuman API routes (`/auth/...`, etc.).
use anyhow::{Context, Result};
use base64::Engine;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue, AUTHORIZATION};
use reqwest::{Client, Method, Url};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::time::Duration;
use super::jwt::bearer_authorization_value;
/// Typed errors surfaced by `authed_json` for expected backend states that
/// callers should recover from in-flow rather than funnel into Sentry.
#[derive(Debug, thiserror::Error)]
pub enum BackendApiError {
/// Edit / delete of a channel message returned 404. Happens when the
/// user deletes the message on the provider side (Telegram, Discord,
/// Slack, …) but our local `StreamingState` still has the id, or when
/// the backend GC'd the relay row before we got around to editing it.
/// Callers should clear stale state and skip the retry. Targets
/// `OPENHUMAN-TAURI-2Y` (~454 events on `/channels/telegram/messages/<id>`).
#[error("message not found on {provider}: {message_id}")]
MessageNotFound {
/// Channel provider segment (e.g. `"telegram"`, `"discord"`).
provider: String,
/// Provider-specific message id from the URL.
message_id: String,
},
/// Backend rejected the bearer JWT with `401 Unauthorized`. This is an
/// expected user-session state (token expired, revoked, rotated
/// server-side) — not a code bug. Callers can route to a re-sign-in
/// flow; the auth domain owns recovery. Targets `OPENHUMAN-TAURI-4K8`
/// (12 events on `/openai/v1/audio/speech` mascot TTS, but the same
/// shape fires on every authed endpoint once the session lapses).
#[error("backend rejected session token on {method} {path}")]
Unauthorized {
/// HTTP method as a static string (`"GET"`, `"POST"`, …).
method: String,
/// Request path the 401 came back from (no query string).
path: String,
},
/// `GET /announcements/latest` returned 404. The announcements feature is
/// a best-effort, cosmetic fetch (`app/src/services/announcementService.ts`:
/// "a missing announcement is never worth surfacing an error for") — a 404
/// here means "no announcement", not a code bug. Callers should degrade to
/// `null` and skip the retry-as-error path. Targets `TAURI-RUST-HW0`
/// (`backend_api`/`authed_json`) and `TAURI-RUST-KHX` (`rpc`/`invoke_method`
/// re-wrap) — one failure reported at two layers, ~452 events / 19 users.
#[error("no announcement available (404 on /announcements/latest)")]
AnnouncementNotFound,
}
/// Flatten an `authed_json` error onto the JSON-RPC `String` channel.
///
/// `BackendApiError::Unauthorized` is an expected backend session-lapse 401
/// (token expired / revoked / rotated server-side), not a code bug — see the
/// variant docs above. Callers used to flatten it with `format!("{e:#}")` /
/// `e.to_string()`, producing `"backend rejected session token on {method}
/// {path}"`, which matches none of the JSON-RPC session-expiry classifiers
/// (`is_session_expired_error`, `is_session_expired_message`, the `before_send`
/// net), so every lapsed-session 401 leaked to Sentry — TAURI-RUST-8WY
/// (`/teams/me/usage`), TAURI-RUST-8WZ (`/payments/stripe/currentPlan`), and the
/// rest of the authed-endpoint family (#3297).
///
/// Mapping `Unauthorized` onto the existing `SESSION_EXPIRED` sentinel makes the
/// dispatcher (`core/jsonrpc.rs`) classify it as session expiry: it skips the
/// Sentry report AND publishes `DomainEvent::SessionExpired` so the auth domain
/// drives re-sign-in. This keys off the typed downcast — not the Display
/// wording — so it stays correct if the `#[error(...)]` text changes, consistent
/// with #2959's removal of brittle string-based suppression. Every other error
/// (including `MessageNotFound`) keeps its full `{e:#}` chain so genuine
/// failures still reach Sentry.
pub fn flatten_authed_error(err: anyhow::Error) -> String {
match err.downcast_ref::<BackendApiError>() {
Some(BackendApiError::Unauthorized { method, path }) => {
format!("SESSION_EXPIRED: backend rejected session token on {method} {path}")
}
_ => format!("{err:#}"),
}
}
/// Extract `(provider, message_id)` from a backend channel path of the
/// shape `…/channels/<provider>/messages/<id>`. Returns `None` for paths
/// that do not contain this four-segment subsequence.
///
/// Handles both the canonical four-segment form and paths with an arbitrary
/// base-path prefix (e.g. `/api/v1/channels/telegram/messages/1103`) via a
/// sliding window so that `BACKEND_URL` variants with path prefixes do not
/// silently fall through to `report_error` (OPENHUMAN-TAURI-R7).
fn parse_message_path(path: &str) -> Option<(&str, &str)> {
let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
// Fast path: exact four-segment canonical form /channels/<p>/messages/<id>
if segments.len() == 4 && segments[0] == "channels" && segments[2] == "messages" {
return Some((segments[1], segments[3]));
}
// Sliding window: handles base-path prefixes like /api/v1/channels/<p>/messages/<id>
for window in segments.windows(4) {
if window[0] == "channels" && window[2] == "messages" {
return Some((window[1], window[3]));
}
}
None
}
/// `true` when `path` is `/announcements/latest`, tolerant of an arbitrary
/// base-path prefix (e.g. `/api/v1/announcements/latest`) — same
/// prefix-tolerant reasoning as [`parse_message_path`] (OPENHUMAN-TAURI-R7):
/// a `BACKEND_URL` override with a path prefix must not cause this route's
/// 404 to silently fall through to the generic `report_error` path.
fn is_announcements_latest_path(path: &str) -> bool {
let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
matches!(segments.as_slice(), [.., "announcements", "latest"])
}
const CLIENT_VERSION_HEADER_MAX_LEN: usize = 64;
/// Max bytes of the `body_shape` key-name list echoed into the `authed_json`
/// report. Bounded so a body with pathologically many keys can't bloat the
/// event; truncation is UTF-8-safe.
const BACKEND_API_BODY_SHAPE_MAX_BYTES: usize = 120;
/// PII-safe classification of a non-2xx response body for telemetry.
///
/// `report_error`'s message is written to the core/Tauri daily logs BEFORE any
/// Sentry `before_send` scrubbing, and that scrubber only catches a few
/// secret-shaped patterns — so the raw body must never be echoed (a non-2xx body
/// can carry emails / profile JSON / OAuth errors / nonstandard token fields).
/// We emit only the SHAPE: for a JSON object, the count of top-level keys plus
/// the sorted subset that look like schema field names; otherwise a coarse
/// label. Even key NAMES are response-controlled (a foreign backend could return
/// `{"jo@example.com": 1}`), so only keys matching a conservative ASCII-identifier
/// shape are echoed — everything else is counted as `redacted` and never logged.
/// The surviving names are enough to identify which backend/gateway produced a
/// response — the `TAURI-RUST-8C` case (a 91-byte body matching no route this
/// backend emits), where our canonical envelope is `{success,error,errorCode}`
/// and a foreign gateway/proxy is not.
fn backend_api_body_shape(body: &str) -> String {
let trimmed = body.trim();
if trimmed.is_empty() {
return "empty".to_string();
}
match serde_json::from_str::<Value>(trimmed) {
Ok(Value::Object(map)) => {
let total = map.len();
let mut safe: Vec<&str> = map
.keys()
.map(String::as_str)
.filter(|k| is_schema_like_key(k))
.collect();
safe.sort_unstable();
let redacted = total - safe.len();
// `safe` keys are ASCII identifiers, so the join is ASCII and the
// truncation can only ever land on a byte boundary — but route it
// through the UTF-8-safe truncator regardless (defence-in-depth).
let keys = crate::openhuman::util::truncate_at_byte_boundary(
&safe.join(","),
BACKEND_API_BODY_SHAPE_MAX_BYTES,
);
format!("object(keys={total},safe=[{keys}],redacted={redacted})")
}
Ok(Value::Array(_)) => "array".to_string(),
Ok(_) => "scalar".to_string(),
Err(_) => "non_json".to_string(),
}
}
/// A JSON key safe to echo into telemetry: a short ASCII identifier (the shape
/// of a schema field name). Anything else — non-ASCII, punctuation like `@`,
/// whitespace, or overlong — is treated as response-controlled data and excluded
/// so `body_shape` can never leak an email/UUID/free-text used as a key.
fn is_schema_like_key(key: &str) -> bool {
const MAX_KEY_LEN: usize = 40;
!key.is_empty()
&& key.len() <= MAX_KEY_LEN
&& key
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
}
fn sanitize_client_version(raw: &str) -> Option<String> {
let sanitized: String = raw
.trim()
.chars()
.filter(|c| matches!(c, '0'..='9' | 'A'..='Z' | 'a'..='z' | '.' | '_' | '+' | '-'))
.take(CLIENT_VERSION_HEADER_MAX_LEN)
.collect();
if sanitized.is_empty() {
None
} else {
Some(sanitized)
}
}
fn build_backend_reqwest_client() -> Result<Client> {
let mut default_headers = HeaderMap::new();
if let Some(version) = sanitize_client_version(env!("CARGO_PKG_VERSION")) {
default_headers.insert(
HeaderName::from_static("x-core-version"),
HeaderValue::from_str(&version).context("invalid x-core-version header value")?,
);
}
// The Tauri shell sets `OPENHUMAN_TAURI_VERSION` to its own package version
// before spawning the in-process core, so backend analytics can attribute
// core-originated requests to the desktop shell build that hosts them.
if let Ok(raw) = std::env::var("OPENHUMAN_TAURI_VERSION") {
if let Some(version) = sanitize_client_version(&raw) {
default_headers.insert(
HeaderName::from_static("x-tauri-version"),
HeaderValue::from_str(&version).context("invalid x-tauri-version header value")?,
);
}
}
// Platform-appropriate TLS backend: Windows → schannel (honors the OS
// cert store, required for corporate TLS-inspection proxies); macOS /
// Linux → rustls. See [`crate::openhuman::tls::tls_client_builder`].
crate::openhuman::tls::tls_client_builder()
.default_headers(default_headers)
.http1_only()
.timeout(Duration::from_secs(120))
.connect_timeout(Duration::from_secs(15))
.build()
.map_err(|e| anyhow::anyhow!("failed to build HTTP client: {e}"))
}
fn parse_api_response_json(text: &str) -> Result<Value> {
let v: Value = serde_json::from_str(text).with_context(|| format!("parse API JSON: {text}"))?;
let Some(obj) = v.as_object() else {
return Ok(v);
};
if let Some(success) = obj.get("success").and_then(|x| x.as_bool()) {
if !success {
let msg = obj
.get("message")
.or_else(|| obj.get("error"))
.and_then(|x| x.as_str())
.unwrap_or("request unsuccessful");
anyhow::bail!("API request failed: {msg}");
}
if let Some(data) = obj.get("data") {
if !data.is_null() {
return Ok(data.clone());
}
}
if let Some(user) = obj.get("user") {
if !user.is_null() {
return Ok(user.clone());
}
}
let mut m = obj.clone();
m.remove("success");
return Ok(Value::Object(m));
}
Ok(v)
}
fn user_id_from_object(obj: &serde_json::Map<String, Value>) -> Option<String> {
for key in ["id", "_id", "userId"] {
if let Some(s) = obj.get(key).and_then(|x| x.as_str()) {
let t = s.trim();
if !t.is_empty() {
return Some(t.to_string());
}
}
}
None
}
/// Best-effort extraction of a user ID from an authenticated profile payload.
///
/// This function handles various envelope formats, including raw user objects
/// or those nested under `data` or `user` keys.
pub fn user_id_from_profile_payload(payload: &Value) -> Option<String> {
let obj = payload.as_object()?;
if let Some(data) = obj.get("data").and_then(|v| v.as_object()) {
return user_id_from_object(data).or_else(|| {
data.get("user")
.and_then(|u| u.as_object())
.and_then(user_id_from_object)
});
}
user_id_from_object(obj).or_else(|| {
obj.get("user")
.and_then(|u| u.as_object())
.and_then(user_id_from_object)
})
}
/// Alias for [`user_id_from_profile_payload`] for semantic clarity in auth flows.
pub fn user_id_from_auth_me_payload(payload: &Value) -> Option<String> {
user_id_from_profile_payload(payload)
}
/// JSON body returned by the backend when an OAuth connection process is initiated.
#[derive(Debug, Clone, Deserialize)]
pub struct ConnectResponse {
/// The URL to redirect the user to for OAuth authorization.
pub oauth_url: String,
/// The state parameter used to prevent CSRF and correlate the callback.
pub state: String,
}
#[derive(Debug, Clone, Deserialize)]
struct ConnectEnvelope {
success: bool,
#[serde(default, alias = "oauthUrl")]
oauth_url: Option<String>,
#[serde(default)]
state: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
struct IntegrationsEnvelope {
success: bool,
data: IntegrationsData,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct IntegrationsData {
integrations: Vec<IntegrationSummary>,
}
/// A summary of an active integration, as returned by the backend.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IntegrationSummary {
/// Unique identifier for the integration.
pub id: String,
/// The name of the integration provider (e.g., "google", "slack").
pub provider: String,
/// RFC3339 timestamp of when the integration was created.
pub created_at: String,
}
#[derive(Debug, Clone, Deserialize)]
struct TokensEnvelope {
success: bool,
data: TokensData,
}
#[derive(Debug, Clone, Deserialize)]
struct TokensData {
encrypted: String,
}
#[derive(Debug, Clone, Deserialize)]
struct LoginTokenConsumeEnvelope {
success: bool,
data: LoginTokenConsumeData,
}
#[derive(Debug, Clone, Deserialize)]
struct LoginTokenConsumeData {
jwt: String,
}
/// Decrypted OAuth token payload for handing off tokens to a local service or skill.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IntegrationTokensHandoff {
/// The OAuth access token.
pub access_token: String,
/// The optional OAuth refresh token.
#[serde(default)]
pub refresh_token: Option<String>,
/// RFC3339 timestamp of when the access token expires.
pub expires_at: String,
}
/// A client for interacting with the TinyHumans / AlphaHuman backend API.
#[derive(Clone)]
pub struct BackendOAuthClient {
client: Client,
base: Url,
}
impl BackendOAuthClient {
/// Creates a new `BackendOAuthClient` with the given API base URL.
///
/// Any path, query, or fragment in `api_base` is stripped so that
/// `Url::join` always resolves root-relative REST paths correctly.
/// This guards against callers who pass a full LLM completions URL
/// (e.g. `https://host/v1/chat/completions`) instead of just the origin:
/// without stripping, `join("teams/me/usage")` would produce the wrong
/// path `/v1/chat/teams/me/usage` via RFC 3986 relative resolution.
pub fn new(api_base: &str) -> Result<Self> {
let mut base = Url::parse(api_base.trim()).context("Invalid API base URL")?;
anyhow::ensure!(
matches!(base.scheme(), "http" | "https") && base.host_str().is_some(),
"API base URL must be an absolute http(s) URL with host"
);
base.set_path("");
base.set_query(None);
base.set_fragment(None);
let client = build_backend_reqwest_client()?;
Ok(Self { client, base })
}
/// Borrow the underlying `reqwest::Client` for callers that need to
/// drive a non-JSON request shape (e.g. `multipart/form-data` uploads
/// for cloud STT) without re-implementing TLS/proxy plumbing.
pub fn raw_client(&self) -> &Client {
&self.client
}
/// Resolve a backend-relative path against the configured base URL.
/// Mirrors what `authed_json` does internally so callers using
/// `raw_client()` don't have to assemble URLs by hand.
pub fn url_for(&self, path: &str) -> Result<Url> {
self.base
.join(path.trim_start_matches('/'))
.with_context(|| format!("build URL for {path}"))
}
/// Returns the URL for initiating a login flow for a specific provider.
pub fn login_url(&self, provider: &str) -> Result<Url> {
let p = provider.trim().trim_matches('/');
anyhow::ensure!(!p.is_empty(), "provider is required");
self.base
.join(&format!("auth/{p}/login"))
.context("build login URL")
}
/// Initiates an OAuth connection flow for the current user and a specific provider.
pub async fn connect(
&self,
provider: &str,
bearer_jwt: &str,
skill_id: Option<&str>,
response_type: Option<&str>,
encryption_mode: Option<&str>,
) -> Result<ConnectResponse> {
let p = provider.trim().trim_matches('/');
anyhow::ensure!(!p.is_empty(), "provider is required");
let mut url = self
.base
.join(&format!("auth/{p}/connect"))
.context("build connect URL")?;
if let Some(s) = skill_id.filter(|s| !s.is_empty()) {
url.query_pairs_mut().append_pair("skillId", s);
}
if let Some(r) = response_type.filter(|r| !r.is_empty()) {
url.query_pairs_mut().append_pair("responseType", r);
}
if let Some(e) = encryption_mode.filter(|e| !e.is_empty()) {
url.query_pairs_mut().append_pair("encryptionMode", e);
}
let resp = self
.client
.get(url)
.header(AUTHORIZATION, bearer_authorization_value(bearer_jwt))
.send()
.await
.context("auth connect request")?;
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
anyhow::bail!("auth connect failed ({status}): {text}");
}
let env: ConnectEnvelope =
serde_json::from_str(&text).with_context(|| format!("parse connect JSON: {text}"))?;
if !env.success {
anyhow::bail!("auth connect unsuccessful: {text}");
}
let oauth_url = env
.oauth_url
.filter(|u| !u.is_empty())
.context("missing oauthUrl in response")?;
let state = env
.state
.filter(|s| !s.is_empty())
.context("missing state")?;
Ok(ConnectResponse { oauth_url, state })
}
/// Fetches the current authenticated user profile using the provided JWT.
pub async fn fetch_current_user(&self, bearer_jwt: &str) -> Result<Value> {
let url = self.base.join("auth/me").context("build /auth/me URL")?;
let resp = self
.client
.get(url)
.header(AUTHORIZATION, bearer_authorization_value(bearer_jwt))
.send()
.await
.context("GET /auth/me")?;
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
anyhow::bail!("GET /auth/me failed ({status}): {text}");
}
parse_api_response_json(&text)
}
/// Exchanges a one-time login token (e.g. from Telegram) for a long-lived JWT.
pub async fn consume_login_token(&self, login_token: &str) -> Result<String> {
let token = login_token.trim();
anyhow::ensure!(!token.is_empty(), "login token is required");
// Backend serves `POST /auth/login-token/consume` with the token in a JSON
// body `{ token, audience? }` and returns `{ success, data: { jwt } }`
// (see backend `routes/auth.ts`). The legacy
// `telegram/login-tokens/{token}/consume` path-param route was removed, so
// the old call 404'd and Telegram/OAuth-token login could never complete
// (WIRING_GAPS_AUDIT C1/C2).
let url = self
.base
.join("auth/login-token/consume")
.context("build login-token consume URL")?;
let resp = self
.client
.post(url)
.json(&serde_json::json!({ "token": token }))
.send()
.await
.context("consume login token")?;
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
anyhow::bail!("consume login token failed ({status}): {text}");
}
let env: LoginTokenConsumeEnvelope = serde_json::from_str(&text)
.with_context(|| format!("parse consume-login-token JSON: {text}"))?;
if !env.success {
anyhow::bail!("consume login token unsuccessful: {text}");
}
let jwt = env.data.jwt.trim().to_string();
anyhow::ensure!(!jwt.is_empty(), "consume login token response missing jwt");
Ok(jwt)
}
/// Validates that the provided session token is still active and accepted.
pub async fn validate_session_token(&self, bearer_jwt: &str) -> Result<()> {
let _ = self.fetch_current_user(bearer_jwt).await?;
Ok(())
}
/// Creates a short-lived link token for connecting a specific communication channel.
pub async fn create_channel_link_token(
&self,
channel: &str,
bearer_jwt: &str,
) -> Result<Value> {
let channel = channel.trim().trim_matches('/');
anyhow::ensure!(!channel.is_empty(), "channel is required");
let encoded_channel = urlencoding::encode(channel);
let url = self
.base
.join(&format!("auth/channels/{encoded_channel}/link-token"))
.context("build channel link-token URL")?;
let resp = self
.client
.post(url)
.header(AUTHORIZATION, bearer_authorization_value(bearer_jwt))
.send()
.await
.context("create channel link token")?;
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
anyhow::bail!("create channel link token failed ({status}): {text}");
}
parse_api_response_json(&text)
}
/// Generic authenticated JSON request helper for backend API routes.
pub async fn authed_json(
&self,
bearer_jwt: &str,
method: Method,
path: &str,
body: Option<Value>,
) -> Result<Value> {
let url = self
.base
.join(path.trim_start_matches('/'))
.with_context(|| format!("build URL for {path}"))?;
let mut request = self
.client
.request(method.clone(), url.clone())
.header(AUTHORIZATION, bearer_authorization_value(bearer_jwt));
if let Some(body) = body {
request = request.json(&body);
}
let response = request.send().await.map_err(|e| {
// Walk the error source chain so transient markers hidden in nested
// causes (reqwest -> hyper -> rustls TLS EOF, etc.) still classify
// correctly. The top-level `e.to_string()` often only carries the
// outermost wrapper, e.g. "error sending request for url (...)".
let mut error_message = e.to_string();
let mut src: Option<&(dyn std::error::Error + 'static)> = std::error::Error::source(&e);
while let Some(s) = src {
error_message.push_str(" → ");
error_message.push_str(&s.to_string());
src = s.source();
}
if crate::core::observability::contains_transient_transport_phrase(&error_message) {
tracing::warn!(
domain = "backend_api",
operation = "authed_json",
method = method.as_str(),
path = url.path(),
failure = "transport",
error = %error_message,
"[backend_api] transient transport failure on {} {}: {}",
method.as_str(),
url.path(),
error_message,
);
} else {
crate::core::observability::report_error(
error_message.as_str(),
"backend_api",
"authed_json",
&[
("method", method.as_str()),
("path", url.path()),
("failure", "transport"),
],
);
}
anyhow::Error::new(e).context(format!(
"backend request {} {}",
method.as_str(),
url.path()
))
})?;
let status = response.status();
let text = response.text().await.unwrap_or_default();
if !status.is_success() {
let status_code = status.as_u16();
let status_str = status_code.to_string();
// 401 on any authed backend endpoint is an expected user-session
// state (token expired / revoked / rotated server-side), not a
// code bug — every authed endpoint will see this once the session
// lapses. Surface a typed `BackendApiError::Unauthorized` so the
// auth domain can drive recovery, and skip `report_error` to
// avoid Sentry noise. Targets `OPENHUMAN-TAURI-4K8` (mascot TTS
// surfaced it first on `/openai/v1/audio/speech`, but the same
// shape applies to every `authed_json` path).
if status_code == 401 {
tracing::info!(
domain = "backend_api",
operation = "authed_json",
method = method.as_str(),
path = url.path(),
status = status_code,
failure = "non_2xx",
"[backend_api] 401 on {} {} — session token rejected, surfacing typed error",
method.as_str(),
url.path(),
);
return Err(anyhow::Error::new(BackendApiError::Unauthorized {
method: method.as_str().to_string(),
path: url.path().to_string(),
}));
}
// 404 on `/channels/<provider>/messages/<id>` is an expected
// state (user deleted the message provider-side, or backend
// GC'd the relay row) — not a code bug. Surface a typed
// `BackendApiError::MessageNotFound` so callers (`bus.rs`
// streaming/thinking/delete/final paths) can clear stale
// ids and skip retry, without funneling the 404 into
// `report_error`. Targets `OPENHUMAN-TAURI-2Y` (~454 events).
if status_code == 404 {
if let Some((provider, message_id)) = parse_message_path(url.path()) {
tracing::info!(
domain = "backend_api",
operation = "authed_json",
provider = provider,
message_id = message_id,
"[backend_api] message-not-found 404 on {} {} — surfacing typed error",
method.as_str(),
url.path(),
);
return Err(anyhow::Error::new(BackendApiError::MessageNotFound {
provider: provider.to_string(),
message_id: message_id.to_string(),
}));
}
// Defense-in-depth: PATCH/DELETE 404s on any channel-message path that
// parse_message_path could not parse (e.g. exotic URL variant with extra
// segments). Still an expected backend state — suppress the Sentry event
// without propagating a typed error. Targets OPENHUMAN-TAURI-R7.
if (method == Method::PATCH || method == Method::DELETE)
&& url.path().contains("/channels/")
&& url.path().contains("/messages/")
{
tracing::debug!(
domain = "backend_api",
operation = "authed_json",
"[backend_api] channel-message 404 on {} {} — path not matched by \
parse_message_path, suppressing Sentry (TAURI-R7 defense-in-depth)",
method.as_str(),
url.path(),
);
anyhow::bail!(
"channel message not found (404) on {} {}",
method.as_str(),
url.path(),
);
}
// 404 on `/announcements/latest` means "no announcement" for
// this best-effort, cosmetic feature — not a code bug. Surface
// a typed `BackendApiError::AnnouncementNotFound` so the caller
// (`announcements::ops::get_latest_announcement`) can degrade to
// `null` instead of propagating an error, without funneling the
// 404 into `report_error`. Targets `TAURI-RUST-HW0` / `TAURI-RUST-KHX`.
if method == Method::GET && is_announcements_latest_path(url.path()) {
tracing::info!(
domain = "backend_api",
operation = "authed_json",
"[backend_api] announcement-not-found 404 on {} {} — surfacing typed error",
method.as_str(),
url.path(),
);
return Err(anyhow::Error::new(BackendApiError::AnnouncementNotFound));
}
}
// These are transient infrastructure errors (proxy/CDN/backend
// temporarily unavailable). They are not code bugs and callers already
// implement retry/disable logic, so skip Sentry to avoid noise.
let is_transient_infra =
crate::core::observability::is_transient_http_status_code(status_code);
let is_budget_exhausted = status_code == 400
&& crate::openhuman::inference::provider::is_budget_exhausted_message(&text);
if is_budget_exhausted {
tracing::info!(
method = method.as_str(),
path = url.path(),
status = status_code,
failure = "non_2xx",
kind = "budget",
"[backend_api] budget-exhausted 400 on {} {} — not reporting to Sentry",
method.as_str(),
url.path(),
);
} else if is_transient_infra {
tracing::warn!(
domain = "backend_api",
operation = "authed_json",
method = method.as_str(),
path = url.path(),
status = status_code,
failure = "non_2xx",
"[backend_api] transient {status} on {} {} — not reporting to Sentry",
method.as_str(),
url.path(),
);
} else {
// Enrich the report with the two fields triage needs to pin a
// non-2xx's origin: the outbound `host` and a PII-safe `body_shape`
// (top-level JSON key names only — never values; see
// `backend_api_body_shape`). `report_error` previously logged only
// `response_body_len`, leaving us blind when a client hits a
// non-canonical backend (custom BACKEND_URL / proxy / foreign
// host) — TAURI-RUST-8C: 12k `GET /teams/me/usage` 404s from one
// user whose 91-byte body matched no route this backend emits,
// un-diagnosable because neither host nor shape was captured.
// `host_str()` carries no scheme/path/query/token. Telemetry only
// — the error still propagates below (no suppression).
let host = url.host_str().unwrap_or("");
let body_shape = backend_api_body_shape(&text);
crate::core::observability::report_error(
format!(
"{} {} failed ({status}); response_body_len={}; body_shape={}",
method.as_str(),
url.path(),
text.len(),
body_shape,
)
.as_str(),
"backend_api",
"authed_json",
&[
("method", method.as_str()),
("path", url.path()),
("host", host),
("status", status_str.as_str()),
("failure", "non_2xx"),
],
);
}
anyhow::bail!(
"{} {} failed ({status}): {text}",
method.as_str(),
url.path()
);
}
parse_api_response_json(&text)
}
/// Lists all active integrations for the current user.
pub async fn list_integrations(&self, bearer_jwt: &str) -> Result<Vec<IntegrationSummary>> {
let url = self
.base
.join("auth/integrations")
.context("build integrations URL")?;
let resp = self
.client
.get(url)
.header(AUTHORIZATION, bearer_authorization_value(bearer_jwt))
.send()
.await
.context("list integrations")?;
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
anyhow::bail!("list integrations failed ({status}): {text}");
}
let env: IntegrationsEnvelope = serde_json::from_str(&text)
.with_context(|| format!("parse integrations JSON: {text}"))?;
if !env.success {
anyhow::bail!("list integrations unsuccessful: {text}");
}
Ok(env.data.integrations)
}
/// Fetches the decrypted OAuth tokens for a specific integration.
///
/// This is a one-time handoff process. The encryption key must match the
/// one used by the backend to encrypt the tokens.
pub async fn fetch_integration_tokens_handoff(
&self,
integration_id: &str,
bearer_jwt: &str,
encryption_key: &str,
) -> Result<IntegrationTokensHandoff> {
let id = integration_id.trim();
anyhow::ensure!(
!id.is_empty() && id.len() == 24,
"integrationId must be a 24-char hex id"
);
let url = self
.base
.join(&format!("auth/integrations/{id}/tokens"))
.context("build tokens URL")?;
let body = serde_json::json!({ "key": encryption_key.trim() });
let resp = self
.client
.post(url)
.header(AUTHORIZATION, bearer_authorization_value(bearer_jwt))
.json(&body)
.send()
.await
.context("integration tokens handoff")?;
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
anyhow::bail!("integration tokens failed ({status}): {text}");
}
let env: TokensEnvelope =
serde_json::from_str(&text).with_context(|| format!("parse tokens JSON: {text}"))?;
if !env.success {
anyhow::bail!("integration tokens unsuccessful: {text}");
}
let plaintext = decrypt_handoff_blob(&env.data.encrypted, encryption_key.trim())?;
serde_json::from_str(&plaintext).context("parse decrypted token JSON")
}
/// Fetches the client key share for a specific integration.
///
/// This is a one-time handoff; the key is deleted from the backend's
/// temporary storage (Redis) after retrieval.
pub async fn fetch_client_key(&self, integration_id: &str, bearer_jwt: &str) -> Result<String> {
let id = integration_id.trim();
anyhow::ensure!(
!id.is_empty() && id.len() == 24,
"integrationId must be a 24-char hex id"
);
let url = self
.base
.join(&format!("auth/integrations/{id}/client-key"))
.context("build client-key URL")?;
let resp = self
.client
.post(url)
.header(AUTHORIZATION, bearer_authorization_value(bearer_jwt))
.send()
.await
.context("fetch client key")?;
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
anyhow::bail!("fetch client key failed ({status}): {text}");
}
let v: Value = serde_json::from_str(&text)
.with_context(|| format!("parse client-key JSON: {text}"))?;
let obj = v.as_object().context("expected JSON object")?;
let success = obj
.get("success")
.and_then(|s| s.as_bool())
.unwrap_or(false);
if !success {
let msg = obj
.get("error")
.and_then(|e| e.as_str())
.unwrap_or("client key retrieval unsuccessful");
anyhow::bail!("fetch client key failed: {msg}");
}
let client_key = obj
.get("data")
.and_then(|d| d.get("clientKey"))
.and_then(|k| k.as_str())
.context("missing data.clientKey in response")?;
Ok(client_key.to_string())
}
/// Sends a message to a communication channel.
pub async fn send_channel_message(
&self,
channel: &str,
bearer_jwt: &str,
message_body: Value,
) -> Result<Value> {
let channel = channel.trim().trim_matches('/');
anyhow::ensure!(!channel.is_empty(), "channel is required");
let encoded = urlencoding::encode(channel);
self.authed_json(
bearer_jwt,
Method::POST,
&format!("channels/{encoded}/messages"),
Some(message_body),
)
.await
}
/// Signals "the agent is typing…" on a channel that supports it
/// (Telegram's `sendChatAction`, Slack's typing event, …). The backend
/// resolves the target chat from the channel integration metadata and
/// is responsible for hitting the provider-native API.
///
/// Telegram keeps the typing indicator alive for ~5 seconds per call,
/// so callers should re-invoke every ~4 s for as long as the turn is
/// in flight. Returns `Err` if the backend doesn't support typing for
/// this channel — caller should swallow the error silently.
pub async fn send_channel_typing(&self, channel: &str, bearer_jwt: &str) -> Result<Value> {
let channel = channel.trim().trim_matches('/');
anyhow::ensure!(!channel.is_empty(), "channel is required");
let encoded = urlencoding::encode(channel);
self.authed_json(
bearer_jwt,
Method::POST,
&format!("channels/{encoded}/typing"),
Some(json!({})),
)
.await
}
/// Edits an existing channel message. Used by the progressive-edit
/// streaming path (Telegram / Slack) to coalesce live deltas into a
/// single evolving outbound message rather than spamming the chat
/// with one bubble per token.
///
/// `message_id` is the backend-returned id of the message that was
/// first sent via [`Self::send_channel_message`]. Returns the
/// updated message record, or an `Err` if the backend does not
/// support editing for this channel (caller should fall back to
/// atomic-final delivery).
pub async fn send_channel_edit(
&self,
channel: &str,
message_id: &str,
bearer_jwt: &str,
edit_body: Value,
) -> Result<Value> {
let channel = channel.trim().trim_matches('/');
anyhow::ensure!(!channel.is_empty(), "channel is required");
anyhow::ensure!(!message_id.is_empty(), "message_id is required");
let encoded_channel = urlencoding::encode(channel);
let encoded_id = urlencoding::encode(message_id);
self.authed_json(
bearer_jwt,