kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
//! Sign-in, session persistence and serialized refresh (PROTOCOL.md §2.2–2.7, ADR 0018).
//!
//! - Device code with a device key (CLIs, devices without a browser), PKCE
//!   with a custom-scheme or loopback redirect, a Machine Auth Key, or a
//!   pre-issued token.
//! - End users of a public app (ADR 0021 §2): email codes, OAuth with the
//!   owner's client, ID tokens from an external issuer, server-minted
//!   sign-in codes and guests (`/v1/eu/{space}/…`, see [`crate::EndUsers`]).
//!   Their sessions are bound to the same device key and rotate the same way.
//! - The session lives in the [`SecretStore`] and survives restarts.
//! - Device-bound sessions refresh before they expire and after a 401, one
//!   refresh at a time. A failed refresh signs out; signing in again with the
//!   same device key keeps the machine and its grants. Only
//!   `reason: "device_revoked"` makes a new key.

pub mod key;
pub mod secrets;

use std::collections::BTreeMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use tokio::sync::watch;

use crate::error::{Error, Result};
use crate::transport::{form, Body, HttpRequest, Transport};
use key::{proof, DeviceKey, KeyProvider};
use secrets::SecretStore;

/// Refresh this long before the access token expires.
const REFRESH_EARLY_MS: u64 = 5 * 60 * 1000;

/// What a session grants per slot (PKCE sign-ins).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SlotGrant {
    pub space_id: String,
    #[serde(default)]
    pub role: String,
}

/// A signed-in session, persisted in the SecretStore.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Session {
    pub access_token: String,
    /// Milliseconds since the epoch.
    pub expires_at: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refresh_token: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refresh_expires_at: Option<u64>,
    #[serde(default)]
    pub client_id: String,
    #[serde(default)]
    pub machine_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_id: Option<String>,
    #[serde(default)]
    pub workspace_id: String,
    /// Bound to the device key: every use carries a proof.
    #[serde(default)]
    pub device_bound: bool,
    #[serde(default)]
    pub spaces: BTreeMap<String, SlotGrant>,
    /// Set for an end user's session (`kvu_…`): valid for one space only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_user: Option<EndUserSession>,
}

/// An end user of a public app (ADR 0021 §2): a person without a Kovlet
/// account, in one Data Space's directory.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EndUser {
    pub id: String,
    /// `None` for guests.
    #[serde(default)]
    pub email: Option<String>,
    #[serde(default)]
    pub email_verified: bool,
    #[serde(default)]
    pub is_guest: bool,
    /// RFC 3339.
    #[serde(default)]
    pub created_at: String,
}

/// What an end-user session is for.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EndUserSession {
    pub space_id: String,
    pub app_id: String,
    pub user: EndUser,
}

/// A finished end-user sign-in.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EndUserSignIn {
    pub user: EndUser,
    /// Set when a guest signed in with an identity that already belonged to
    /// another end user: the session switched to that user, and this is the
    /// guest's id, so the app can move the guest's rows itself.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub guest_id: Option<String>,
}

/// A started end-user OAuth sign-in: open `url` (the provider), then pass
/// the redirect it reaches to `EndUsers::oauth_finish`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EndUserOAuthRequest {
    pub url: String,
    pub state: String,
    pub verifier: String,
    pub redirect_uri: String,
    pub provider: String,
}

impl Session {
    fn refreshable(&self, now: u64) -> bool {
        // End-user tokens don't say when their refresh token expires: try it.
        self.refresh_token.is_some() && self.refresh_expires_at.is_none_or(|e| e > now + 60_000)
    }
    fn fresh(&self, now: u64) -> bool {
        self.expires_at > now + 60_000
    }
}

/// A device code to show the user (device flow).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeviceCode {
    pub user_code: String,
    pub verification_uri: String,
    pub verification_uri_complete: String,
    pub expires_in: u64,
}

pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;

/// Opens a consent URL and resolves with the redirect URL it reached (`?code=…&state=…`).
pub type Authorize = Arc<dyn Fn(String) -> BoxFuture<Result<String>> + Send + Sync>;

/// How to sign in.
#[derive(Clone)]
pub enum SignIn {
    /// The device flow with a device key: show `user_code` or open
    /// `verification_uri_complete`, then the core polls.
    Device {
        on_code: Arc<dyn Fn(&DeviceCode) + Send + Sync>,
        machine_name: Option<String>,
        space_name: Option<String>,
        /// A keyless code: a new headless machine, 90-day token, no refresh.
        keyless: bool,
    },
    /// PKCE: `authorize` opens the consent URL (ASWebAuthenticationSession,
    /// Custom Tabs, the system browser) and returns the redirect it reached.
    Pkce { redirect_uri: String, authorize: Authorize, space_name: Option<String> },
    /// A Machine Auth Key (`kvm_…`) for unattended servers.
    MachineKey { machine_key: String, client_id: String },
    /// A token issued elsewhere (e.g. `kovletd dev seed`). Not refreshed.
    Token { access_token: String },
}

impl SignIn {
    pub fn device(on_code: impl Fn(&DeviceCode) + Send + Sync + 'static) -> SignIn {
        SignIn::Device { on_code: Arc::new(on_code), machine_name: None, space_name: None, keyless: false }
    }

    pub fn pkce<F, Fut>(redirect_uri: impl Into<String>, authorize: F) -> SignIn
    where
        F: Fn(String) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<String>> + Send + 'static,
    {
        let authorize = Arc::new(authorize);
        SignIn::Pkce {
            redirect_uri: redirect_uri.into(),
            authorize: Arc::new(move |url| {
                let a = authorize.clone();
                Box::pin(async move { a(url).await })
            }),
            space_name: None,
        }
    }

    pub fn machine_key(machine_key: impl Into<String>, client_id: impl Into<String>) -> SignIn {
        SignIn::MachineKey { machine_key: machine_key.into(), client_id: client_id.into() }
    }

    pub fn token(access_token: impl Into<String>) -> SignIn {
        SignIn::Token { access_token: access_token.into() }
    }
}

/// A started PKCE request, for apps that drive the browser themselves
/// (`Client::pkce_begin` / `pkce_finish`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PkceRequest {
    /// Open this URL.
    pub url: String,
    pub state: String,
    pub verifier: String,
    pub redirect_uri: String,
}

/// What a request needs to authenticate.
#[derive(Clone)]
pub struct Credentials {
    pub token: String,
    pub key: Option<Arc<dyn DeviceKey>>,
    /// An end user's session: protocol 2 only.
    pub end_user: bool,
}

impl Credentials {
    /// A fresh device proof over the access token, when the session is device-bound.
    pub fn proof(&self) -> Result<Option<String>> {
        self.key.as_ref().map(|k| proof(k.as_ref(), &self.token)).transpose()
    }
}

pub(crate) struct Auth {
    pub base: String,
    pub console: String,
    pub app_name: String,
    transport: Arc<dyn Transport>,
    secrets: Arc<dyn SecretStore>,
    keys: Arc<dyn KeyProvider>,
    session: Mutex<Option<Session>>,
    signed_in: watch::Sender<bool>,
    /// Whether the server answered the last request: `None` before the first one.
    reachable: watch::Sender<Option<bool>>,
    refresh_lock: tokio::sync::Mutex<()>,
    /// Slot requests for PKCE consent: slot → (role, pinned space id).
    pub slots: Mutex<BTreeMap<String, (String, Option<String>)>>,
}

const SESSION_KEY: &str = "session";
const CLIENT_ID_KEY: &str = "client_id";

fn oauth_error(status: u16, body: &[u8]) -> Error {
    let v: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
    if let Some(code) = v.get("error").and_then(Value::as_str) {
        let msg = v.get("error_description").and_then(Value::as_str).unwrap_or(code).to_string();
        let mut e = Error::new(code, msg);
        if let Some(r) = v.get("reason") {
            e = e.with_details(json!({ "reason": r }));
        }
        e.status = Some(status);
        return e;
    }
    rest_error(status, body)
}

/// Parses a REST error (`{"error": {"code", "message", "hint", …}}`).
pub(crate) fn rest_error(status: u16, body: &[u8]) -> Error {
    let v: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
    let mut e = match v.get("error") {
        Some(Value::Object(o)) => {
            let mut e = Error::new(
                o.get("code").and_then(Value::as_str).unwrap_or("http_error"),
                o.get("message").and_then(Value::as_str).unwrap_or_default(),
            );
            e.hint = o.get("hint").and_then(Value::as_str).map(String::from);
            let mut details = o.get("details").cloned().unwrap_or_else(|| json!({}));
            for k in ["metric", "used", "limit", "soft_limit", "upgrade_url", "reads_open"] {
                if let (Some(v), Some(d)) = (o.get(k), details.as_object_mut()) {
                    d.insert(k.into(), v.clone());
                }
            }
            if details.as_object().is_some_and(|d| !d.is_empty()) {
                e.details = Some(Box::new(details));
            }
            e
        }
        Some(Value::String(code)) => {
            Error::new(code.as_str(), v.get("error_description").and_then(Value::as_str).unwrap_or_default())
        }
        _ => Error::new(if status == 401 { "unauthenticated" } else { "http_error" }, format!("HTTP {status}")),
    };
    e.status = Some(status);
    e
}

fn random_b64(n: usize) -> Result<String> {
    let mut b = vec![0u8; n];
    getrandom::fill(&mut b).map_err(|e| Error::new("crypto", e.to_string()))?;
    Ok(B64.encode(b))
}

fn device_name() -> String {
    let os = match crate::protocol::platform() {
        "ios" => "iOS",
        "android" => "Android",
        "macos" => "macOS",
        "windows" => "Windows",
        "linux" => "Linux",
        _ => "device",
    };
    match std::env::var("HOSTNAME").or_else(|_| std::env::var("COMPUTERNAME")) {
        Ok(h) if !h.is_empty() => format!("{h} ({os})"),
        _ => format!("{os} device"),
    }
}

impl Auth {
    pub fn new(
        base: String,
        console: String,
        app_name: String,
        transport: Arc<dyn Transport>,
        secrets: Arc<dyn SecretStore>,
        keys: Arc<dyn KeyProvider>,
    ) -> Auth {
        let stored: Option<Session> =
            secrets.get(SESSION_KEY).ok().flatten().and_then(|s| serde_json::from_str(&s).ok());
        let now = crate::hlc::now_ms();
        let stored = stored.filter(|s| s.fresh(now) || s.refreshable(now));
        let (tx, _) = watch::channel(stored.is_some());
        Auth {
            base,
            console,
            app_name,
            transport,
            secrets,
            keys,
            session: Mutex::new(stored),
            signed_in: tx,
            reachable: watch::channel(None).0,
            refresh_lock: tokio::sync::Mutex::new(()),
            slots: Mutex::new(BTreeMap::new()),
        }
    }

    pub fn session(&self) -> Option<Session> {
        self.session.lock().unwrap().clone()
    }

    pub fn signed_in(&self) -> bool {
        self.session.lock().unwrap().is_some()
    }

    /// Records whether the server answered (any HTTP status) or the request failed in transit.
    pub fn mark_reachable(&self, ok: bool) {
        self.reachable.send_if_modified(|v| {
            let changed = *v != Some(ok);
            *v = Some(ok);
            changed
        });
    }

    pub fn watch_reachable(&self) -> watch::Receiver<Option<bool>> {
        self.reachable.subscribe()
    }

    pub fn watch_signed_in(&self) -> watch::Receiver<bool> {
        self.signed_in.subscribe()
    }

    fn save(&self, s: Option<Session>) -> Result<()> {
        match &s {
            Some(s) => {
                self.secrets.set(SESSION_KEY, &serde_json::to_string(s)?)?;
                if !s.client_id.is_empty() {
                    self.secrets.set(CLIENT_ID_KEY, &s.client_id)?;
                }
            }
            None => self.secrets.delete(SESSION_KEY)?,
        }
        let signed_in = s.is_some();
        *self.session.lock().unwrap() = s;
        self.signed_in.send_replace(signed_in);
        Ok(())
    }

    fn client_id(&self) -> Option<String> {
        self.secrets.get(CLIENT_ID_KEY).ok().flatten().filter(|s| !s.is_empty())
    }

    async fn token_request(&self, fields: &[(&str, &str)], proof: Option<String>) -> Result<Value> {
        let mut headers = vec![("content-type".to_string(), "application/x-www-form-urlencoded".to_string())];
        if let Some(p) = proof {
            headers.push(("kovlet-device-proof".into(), p));
        }
        self.oauth_post("/v1/oauth/token", fields, headers).await
    }

    async fn oauth_post(
        &self,
        path: &str,
        fields: &[(&str, &str)],
        mut headers: Vec<(String, String)>,
    ) -> Result<Value> {
        if !headers.iter().any(|(k, _)| k == "content-type") {
            headers.push(("content-type".into(), "application/x-www-form-urlencoded".into()));
        }
        headers.push(("accept".into(), "application/json".into()));
        let res = self
            .transport
            .http(HttpRequest {
                method: "POST".into(),
                url: format!("{}{}", self.base, path),
                headers,
                body: Body::Bytes(form(fields)),
                save_to: None,
            })
            .await
            .inspect_err(|_| self.mark_reachable(false))?;
        self.mark_reachable(true);
        if !(200..300).contains(&res.status) {
            return Err(oauth_error(res.status, &res.body));
        }
        Ok(serde_json::from_slice(&res.body)?)
    }

    fn session_from(&self, t: &Value, device_bound: bool, spaces: BTreeMap<String, SlotGrant>) -> Session {
        let now = crate::hlc::now_ms();
        let s = |k: &str| t.get(k).and_then(Value::as_str).map(String::from);
        let n = |k: &str| t.get(k).and_then(Value::as_u64);
        let mut spaces = spaces;
        if let Some(sp) =
            t.get("spaces").and_then(|v| serde_json::from_value::<BTreeMap<String, SlotGrant>>(v.clone()).ok())
        {
            spaces.extend(sp);
        }
        Session {
            access_token: s("access_token").unwrap_or_default(),
            expires_at: now + n("expires_in").unwrap_or(90 * 86400) * 1000,
            refresh_token: s("refresh_token"),
            refresh_expires_at: n("refresh_token_expires_in").map(|e| now + e * 1000),
            client_id: s("client_id").unwrap_or_default(),
            machine_id: s("machine_id").unwrap_or_default(),
            user_id: s("user_id"),
            workspace_id: s("workspace_id").unwrap_or_default(),
            device_bound,
            spaces,
            end_user: None,
        }
    }

    /// Signs in and stores the session.
    pub async fn sign_in(&self, how: &SignIn) -> Result<Session> {
        let s = match how {
            SignIn::Device { on_code, machine_name, space_name, keyless } => {
                let mut attempt = 0;
                loop {
                    match self
                        .device_once(on_code.as_ref(), machine_name.as_deref(), space_name.as_deref(), *keyless)
                        .await
                    {
                        Err(e) if attempt == 0 && !keyless && e.reason() == Some("device_revoked") => {
                            self.keys.rotate()?;
                            attempt += 1;
                        }
                        r => break r?,
                    }
                }
            }
            SignIn::Pkce { redirect_uri, authorize, space_name } => {
                let req = self.pkce_begin(redirect_uri, space_name.as_deref())?;
                let callback = authorize(req.url.clone()).await?;
                return self.pkce_finish(&callback, &req).await;
            }
            SignIn::MachineKey { machine_key, client_id } => {
                let t = self
                    .token_request(
                        &[
                            ("grant_type", "urn:kovlet:params:oauth:grant-type:machine_key"),
                            ("machine_key", machine_key),
                            ("client_id", client_id),
                        ],
                        None,
                    )
                    .await?;
                self.session_from(&t, false, BTreeMap::new())
            }
            SignIn::Token { access_token } => Session {
                access_token: access_token.clone(),
                expires_at: crate::hlc::now_ms() + 30 * 86400 * 1000,
                refresh_token: None,
                refresh_expires_at: None,
                client_id: String::new(),
                machine_id: String::new(),
                user_id: None,
                workspace_id: String::new(),
                device_bound: false,
                spaces: BTreeMap::new(),
                end_user: None,
            },
        };
        self.save(Some(s.clone()))?;
        Ok(s)
    }

    async fn device_once(
        &self,
        on_code: &(dyn Fn(&DeviceCode) + Send + Sync),
        machine_name: Option<&str>,
        space_name: Option<&str>,
        keyless: bool,
    ) -> Result<Session> {
        let key = if keyless { None } else { Some(self.keys.key()?) };
        let jwk = key.as_ref().map(|k| k.public_jwk().to_string());
        let client_id = self.client_id();
        let machine = machine_name.map(String::from).unwrap_or_else(device_name);
        let mut f: Vec<(&str, &str)> =
            vec![("client_name", self.app_name.as_str()), ("machine_name", machine.as_str())];
        if let Some(c) = &client_id {
            f.push(("client_id", c));
        }
        if let Some(j) = &jwk {
            f.push(("device_public_key", j));
        }
        if let Some(n) = space_name {
            f.push(("space_name", n));
        }
        // The pinned spaces, so /activate preselects them (ADR 0023 §5).
        let pinned = self.pinned_space_ids();
        if !pinned.is_empty() {
            f.push(("space_ids", pinned.as_str()));
        }
        let da = self.oauth_post("/v1/oauth/device_authorization", &f, vec![]).await?;
        let get = |k: &str| da.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
        let device_code = get("device_code");
        let code = DeviceCode {
            user_code: get("user_code"),
            verification_uri: get("verification_uri"),
            verification_uri_complete: get("verification_uri_complete"),
            expires_in: da.get("expires_in").and_then(Value::as_u64).unwrap_or(600),
        };
        on_code(&code);
        let mut interval = Duration::from_secs(da.get("interval").and_then(Value::as_u64).unwrap_or(5).max(1));
        let deadline = tokio::time::Instant::now() + Duration::from_secs(code.expires_in);
        while tokio::time::Instant::now() < deadline {
            tokio::time::sleep(interval).await;
            // A keyed code is redeemed only with a proof over the device code; sign every poll.
            let p = key.as_ref().map(|k| proof(k.as_ref(), &device_code)).transpose()?;
            let mut fields = vec![
                ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
                ("device_code", device_code.as_str()),
            ];
            if let Some(c) = &client_id {
                fields.push(("client_id", c));
            }
            match self.token_request(&fields, p).await {
                Ok(t) => return Ok(self.session_from(&t, key.is_some(), BTreeMap::new())),
                Err(e) if e.code == "authorization_pending" => continue,
                Err(e) if e.code == "slow_down" => {
                    interval += Duration::from_secs(5);
                    continue;
                }
                Err(e) if e.code == "network" => continue,
                Err(e) => return Err(e),
            }
        }
        Err(Error::new("expired_token", "the device code expired before it was approved")
            .with_hint("Start the sign-in again to get a new code, and approve it before it expires."))
    }

    /// The slots' pinned space ids, space-separated and without duplicates:
    /// the `space_ids` hint of a device authorization (ADR 0023 §5).
    pub fn pinned_space_ids(&self) -> String {
        let mut ids: Vec<String> = Vec::new();
        for (_, space) in self.slots.lock().unwrap().values() {
            if let Some(s) = space {
                if !ids.contains(s) {
                    ids.push(s.clone());
                }
            }
        }
        ids.join(" ")
    }

    /// Starts a PKCE request: open `url`, then pass the redirect to [`Auth::pkce_finish`].
    pub fn pkce_begin(&self, redirect_uri: &str, space_name: Option<&str>) -> Result<PkceRequest> {
        let verifier = random_b64(32)?;
        let challenge = B64.encode(Sha256::digest(verifier.as_bytes()));
        let state = format!("kv_{}", random_b64(16)?);
        let mut slots = serde_json::Map::new();
        for (name, (role, space)) in self.slots.lock().unwrap().iter() {
            let mut o = serde_json::Map::new();
            o.insert("role".into(), json!(role));
            if let Some(s) = space {
                o.insert("space_id".into(), json!(s));
            }
            slots.insert(name.clone(), Value::Object(o));
        }
        if slots.is_empty() {
            slots.insert("main".into(), json!({"role": "editor"}));
        }
        let mut q = form_urlencoded::Serializer::new(String::new());
        q.append_pair("response_type", "code");
        q.append_pair("client_name", &self.app_name);
        if let Some(c) = self.client_id() {
            q.append_pair("client_id", &c);
        }
        q.append_pair("redirect_uri", redirect_uri);
        q.append_pair("code_challenge", &challenge);
        q.append_pair("code_challenge_method", "S256");
        q.append_pair("state", &state);
        q.append_pair("slots", &Value::Object(slots).to_string());
        if let Some(n) = space_name {
            q.append_pair("space_name", n);
        }
        Ok(PkceRequest {
            url: format!("{}/oauth/consent?{}", self.console, q.finish()),
            state,
            verifier,
            redirect_uri: redirect_uri.to_string(),
        })
    }

    /// Exchanges the consent redirect (`?code=&state=&client_id=`) for a session.
    pub async fn pkce_finish(&self, callback: &str, req: &PkceRequest) -> Result<Session> {
        // Custom schemes (`com.example.app:/cb?…`) and loopback URLs alike: the query is what matters.
        let query = callback.split_once('?').map(|(_, q)| q.split('#').next().unwrap_or_default()).unwrap_or_default();
        let q: BTreeMap<String, String> = form_urlencoded::parse(query.as_bytes()).into_owned().collect();
        if q.get("state") != Some(&req.state) {
            return Err(Error::new("invalid_state", "consent answered a different request"));
        }
        if let Some(e) = q.get("error") {
            let msg = if e == "access_denied" {
                "the user denied access".to_string()
            } else {
                q.get("error_description").cloned().unwrap_or(e.clone())
            };
            return Err(Error::new(e.as_str(), msg));
        }
        let code = q.get("code").cloned().unwrap_or_default();
        let client_id = q.get("client_id").cloned().or_else(|| self.client_id()).unwrap_or_default();
        if code.is_empty() || client_id.is_empty() {
            return Err(Error::new("invalid_callback", "the consent redirect has no code or client_id"));
        }
        let mut attempt = 0;
        loop {
            let key = self.keys.key()?;
            let jwk = key.public_jwk().to_string();
            let name = device_name();
            let r = self
                .token_request(
                    &[
                        ("grant_type", "authorization_code"),
                        ("code", &code),
                        ("code_verifier", &req.verifier),
                        ("redirect_uri", &req.redirect_uri),
                        ("client_id", &client_id),
                        ("device_public_key", &jwk),
                        ("device_name", &name),
                    ],
                    None,
                )
                .await;
            match r {
                Ok(t) => {
                    let s = self.session_from(&t, true, BTreeMap::new());
                    self.save(Some(s.clone()))?;
                    return Ok(s);
                }
                Err(e) if attempt == 0 && e.reason() == Some("device_revoked") => {
                    self.keys.rotate()?;
                    attempt += 1;
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// The credentials for the next request: waits until signed in, and
    /// refreshes first when the access token is about to expire.
    pub async fn credentials(&self) -> Result<Credentials> {
        let mut rx = self.signed_in.subscribe();
        loop {
            if *rx.borrow_and_update() {
                break;
            }
            if rx.changed().await.is_err() {
                return Err(Error::new("signed_out", "the client was closed"));
            }
        }
        self.try_credentials().await
    }

    /// Like [`Auth::credentials`], but fails with `signed_out` straight away
    /// instead of waiting for a sign-in.
    pub async fn try_credentials(&self) -> Result<Credentials> {
        let s = self.session().ok_or_else(|| Error::new("signed_out", "not signed in"))?;
        let now = crate::hlc::now_ms();
        let s = if s.refreshable(now) && s.expires_at < now + REFRESH_EARLY_MS {
            match self.refresh().await? {
                Some(s) => s,
                None => return Err(Error::new("unauthenticated", "the session could not be refreshed; sign in again")),
            }
        } else {
            s
        };
        let key = if s.device_bound { Some(self.keys.key()?) } else { None };
        Ok(Credentials { token: s.access_token, key, end_user: s.end_user.is_some() })
    }

    /// Rotates the refresh token. Callers share one refresh at a time; a
    /// rotation that another caller already made is reused.
    pub async fn refresh(&self) -> Result<Option<Session>> {
        let before = self.session().map(|s| s.access_token);
        let _g = self.refresh_lock.lock().await;
        // Another caller (or process) may have rotated while we waited.
        let stored: Option<Session> = self.secrets.get(SESSION_KEY)?.and_then(|s| serde_json::from_str(&s).ok());
        let cur = self.session();
        if let (Some(c), Some(b)) = (&cur, &before) {
            if &c.access_token != b {
                return Ok(cur);
            }
        }
        let s = match (stored, cur) {
            (Some(st), Some(c)) if st.refresh_token.is_some() && st.refresh_token != c.refresh_token => {
                *self.session.lock().unwrap() = Some(st.clone());
                return Ok(Some(st));
            }
            (_, Some(c)) => c,
            (Some(st), None) => st,
            (None, None) => return Ok(None),
        };
        let now = crate::hlc::now_ms();
        let Some(rt) = s.refresh_token.clone().filter(|_| s.refreshable(now)) else {
            return Ok(None);
        };
        let key = self.keys.key()?;
        let p = proof(key.as_ref(), &rt)?;
        let res = match &s.end_user {
            Some(eu) => {
                let body = json!({ "grant_type": "refresh_token", "refresh_token": rt });
                let path = format!("/v1/eu/{}/token", crate::api::seg(&eu.space_id));
                self.eu_json("POST", &path, Some(&body), vec![("kovlet-device-proof".into(), p)]).await
            }
            None => self.token_request(&[("grant_type", "refresh_token"), ("refresh_token", &rt)], Some(p)).await,
        };
        match res {
            Ok(t) if s.end_user.is_some() => {
                let eu = s.end_user.clone().expect("end user");
                let ns = self.end_user_session(&t, &eu.space_id, &eu.app_id, Some(eu.user));
                self.save(Some(ns.clone()))?;
                Ok(Some(ns))
            }
            Ok(t) => {
                let ns = self.session_from(&t, true, s.spaces.clone());
                self.save(Some(ns.clone()))?;
                Ok(Some(ns))
            }
            Err(e) if e.is_transient() || e.code == "network" => Err(e),
            Err(e) => {
                if e.reason() == Some("device_revoked") {
                    let _ = self.keys.rotate();
                }
                tracing::warn!("kovlet: refresh failed ({e}); signing out");
                self.save(None)?;
                Ok(None)
            }
        }
    }

    /// After the server answered 401 / 4401: refresh if possible (true), else sign out (false).
    pub async fn unauthorized(&self, token: &str) -> bool {
        let s = self.session();
        if let Some(cur) = &s {
            if cur.access_token != token {
                return true; // already rotated
            }
            if cur.refreshable(crate::hlc::now_ms()) {
                for _ in 0..3 {
                    match self.refresh().await {
                        Ok(Some(_)) => return true,
                        Ok(None) => return false,
                        Err(_) => tokio::time::sleep(Duration::from_secs(1)).await,
                    }
                }
                return false;
            }
        }
        let _ = self.save(None);
        false
    }

    /// Ends the session family on the server (best effort) and forgets it.
    /// The device key stays, so the next sign-in reuses the machine.
    pub async fn sign_out(&self) -> Result<()> {
        if let Some(s) = self.session() {
            let mut headers = vec![("authorization".to_string(), format!("Bearer {}", s.access_token))];
            if s.device_bound {
                headers.push(("kovlet-device-proof".into(), proof(self.keys.key()?.as_ref(), &s.access_token)?));
            }
            let path = match &s.end_user {
                Some(eu) => format!("/v1/eu/{}/sign-out", crate::api::seg(&eu.space_id)),
                None => "/v1/auth/logout".to_string(),
            };
            let _ = self
                .transport
                .http(HttpRequest {
                    method: "POST".into(),
                    url: format!("{}{path}", self.base),
                    headers,
                    body: Body::Empty,
                    save_to: None,
                })
                .await;
        }
        self.save(None)
    }

    // ------------------------------------------------------------ end users

    /// A JSON request to the end-user API (`/v1/eu/…`), unauthenticated
    /// unless `headers` say otherwise. Non-2xx answers become errors.
    pub(crate) async fn eu_json(
        &self,
        method: &str,
        path: &str,
        body: Option<&Value>,
        mut headers: Vec<(String, String)>,
    ) -> Result<Value> {
        headers.push(("accept".into(), "application/json".into()));
        let body = match body {
            Some(b) => {
                headers.push(("content-type".into(), "application/json".into()));
                Body::Bytes(serde_json::to_vec(b)?)
            }
            None => Body::Empty,
        };
        let res = self
            .transport
            .http(HttpRequest {
                method: method.into(),
                url: format!("{}{path}", self.base),
                headers,
                body,
                save_to: None,
            })
            .await
            .inspect_err(|_| self.mark_reachable(false))?;
        self.mark_reachable(true);
        if !(200..300).contains(&res.status) {
            return Err(end_user_hint(rest_error(res.status, &res.body)));
        }
        if res.body.is_empty() {
            return Ok(Value::Null);
        }
        Ok(serde_json::from_slice(&res.body)?)
    }

    fn end_user_session(&self, t: &Value, space_id: &str, app_id: &str, prev: Option<EndUser>) -> Session {
        let mut s = self.session_from(t, true, BTreeMap::new());
        let user =
            t.get("user").and_then(|u| serde_json::from_value::<EndUser>(u.clone()).ok()).or(prev).unwrap_or(EndUser {
                id: String::new(),
                email: None,
                email_verified: false,
                is_guest: false,
                created_at: String::new(),
            });
        s.end_user = Some(EndUserSession { space_id: space_id.into(), app_id: app_id.into(), user });
        s
    }

    /// Redeems an end-user grant at `POST /v1/eu/{space}/token` (or signs in
    /// as a guest with `path` = `guest`) with this device's key, and stores
    /// the session. A guest session of the same space goes along as the
    /// bearer, so the server upgrades the guest in place.
    pub(crate) async fn end_user_grant(
        &self,
        space_id: &str,
        app_id: &str,
        path: &str,
        mut fields: serde_json::Map<String, Value>,
    ) -> Result<EndUserSignIn> {
        let key = self.keys.key()?;
        fields.insert("app_id".into(), json!(app_id));
        fields.insert("device_key".into(), key.public_jwk());
        let mut headers = Vec::new();
        if let Some(cur) = self.session() {
            let guest_here = cur.end_user.as_ref().is_some_and(|eu| eu.user.is_guest && eu.space_id == space_id);
            if guest_here && path == "token" && cur.fresh(crate::hlc::now_ms()) {
                headers.push(("authorization".to_string(), format!("Bearer {}", cur.access_token)));
                headers.push(("kovlet-device-proof".into(), proof(key.as_ref(), &cur.access_token)?));
            }
        }
        let url = format!("/v1/eu/{}/{path}", crate::api::seg(space_id));
        let t = self.eu_json("POST", &url, Some(&Value::Object(fields)), headers).await?;
        let s = self.end_user_session(&t, space_id, app_id, None);
        let user = s.end_user.as_ref().map(|e| e.user.clone()).expect("end user");
        self.save(Some(s))?;
        Ok(EndUserSignIn { user, guest_id: t.get("guest_id").and_then(Value::as_str).map(String::from) })
    }

    /// Starts an end-user OAuth sign-in with the space owner's provider client.
    pub(crate) fn end_user_oauth_begin(
        &self,
        space_id: &str,
        app_id: &str,
        provider: &str,
        redirect_uri: &str,
    ) -> Result<EndUserOAuthRequest> {
        let verifier = random_b64(32)?;
        let challenge = B64.encode(Sha256::digest(verifier.as_bytes()));
        // Distinct from the member consent's states, so neither flow takes the other's callback.
        let state = format!("kveu_{}", random_b64(18)?);
        let mut q = form_urlencoded::Serializer::new(String::new());
        q.append_pair("app_id", app_id);
        q.append_pair("redirect_uri", redirect_uri);
        q.append_pair("state", &state);
        q.append_pair("code_challenge", &challenge);
        q.append_pair("code_challenge_method", "S256");
        let url = format!(
            "{}/v1/eu/{}/oauth/{}/start?{}",
            self.base,
            crate::api::seg(space_id),
            crate::api::seg(provider),
            q.finish()
        );
        Ok(EndUserOAuthRequest {
            url,
            state,
            verifier,
            redirect_uri: redirect_uri.to_string(),
            provider: provider.to_string(),
        })
    }

    /// Finishes an end-user OAuth sign-in from the redirect it reached.
    pub(crate) async fn end_user_oauth_finish(
        &self,
        space_id: &str,
        app_id: &str,
        callback: &str,
        req: &EndUserOAuthRequest,
    ) -> Result<EndUserSignIn> {
        let query = callback.split_once('?').map(|(_, q)| q.split('#').next().unwrap_or_default()).unwrap_or_default();
        let q: BTreeMap<String, String> = form_urlencoded::parse(query.as_bytes()).into_owned().collect();
        if q.get("state") != Some(&req.state) {
            return Err(Error::new("state_mismatch", "the OAuth return does not match this sign-in").with_hint(
                "Start the sign-in again with oauth_begin(), and pass the redirect it reaches to oauth_finish() once.",
            ));
        }
        if let Some(e) = q.get("error") {
            let msg =
                q.get("error_description").cloned().unwrap_or_else(|| format!("the sign-in was not completed ({e})"));
            let mut err = Error::new(e.as_str(), msg);
            if e == "access_denied" {
                err = err.with_hint("The user cancelled at the provider. Offer the sign-in buttons again.");
            }
            return Err(err);
        }
        let code = q.get("code").cloned().unwrap_or_default();
        if code.is_empty() {
            return Err(Error::new("invalid_callback", "the OAuth redirect has no code"));
        }
        let mut f = serde_json::Map::new();
        f.insert("grant_type".into(), json!("authorization_code"));
        f.insert("code".into(), json!(code));
        f.insert("code_verifier".into(), json!(req.verifier));
        f.insert("redirect_uri".into(), json!(req.redirect_uri));
        self.end_user_grant(space_id, app_id, "token", f).await
    }

    /// Replaces the stored end user's profile (after `GET /me`).
    pub(crate) fn set_end_user(&self, user: EndUser) -> Result<()> {
        if let Some(mut s) = self.session() {
            if let Some(eu) = s.end_user.as_mut() {
                if eu.user != user {
                    eu.user = user;
                    self.save(Some(s))?;
                }
            }
        }
        Ok(())
    }

    /// Merges slots into the stored session (grant requests).
    pub fn merge_slots(&self, add: BTreeMap<String, SlotGrant>) -> Result<()> {
        if let Some(mut s) = self.session() {
            s.spaces.extend(add);
            self.save(Some(s))?;
        }
        Ok(())
    }

    pub fn transport(&self) -> &Arc<dyn Transport> {
        &self.transport
    }
}

/// Gives an end-user API error the next step when the server sent none.
fn end_user_hint(e: Error) -> Error {
    if e.hint.is_some() {
        return e;
    }
    let hint = match e.code.as_str() {
        "end_users_disabled" => "End-user sign-in is off for this app. A space owner turns it on in the Kovlet console (Data Space → End users → Apps); the app must be approved and have a pinned origin or redirect URI.",
        "invalid_grant" => "The code is wrong, expired or already used. Ask for a new one (send_magic_code(), or start the sign-in again).",
        "rate_limited" => "Too many sign-in attempts. Wait details.retry_after seconds, then try again; don't retry in a loop.",
        "quota_exceeded" => "The workspace reached its quota of monthly active end users, so new sign-ups are paused; existing end users keep working.",
        "invalid_redirect_uri" => "Register this redirect URI for the app in the Kovlet console (Apps → redirect URIs); native apps use a reverse-DNS scheme such as com.example.app:/oauth.",
        _ => return e,
    };
    e.with_hint(hint)
}

#[cfg(test)]
mod pinned_tests {
    use super::*;
    use crate::auth::key::SoftwareKeyProvider;
    use crate::auth::secrets::MemorySecretStore;
    use crate::transport::{Body, HttpRequest, HttpResponse, Socket};
    use async_trait::async_trait;

    /// Records the device authorization form and refuses it.
    struct Recorder(Mutex<Vec<String>>);

    #[async_trait]
    impl Transport for Recorder {
        async fn http(&self, req: HttpRequest) -> Result<HttpResponse> {
            if let Body::Bytes(b) = &req.body {
                self.0.lock().unwrap().push(String::from_utf8_lossy(b).into_owned());
            }
            Ok(HttpResponse { status: 400, headers: vec![], body: br#"{"error":"invalid_request"}"#.to_vec() })
        }
        async fn connect(&self, _: &str) -> Result<Box<dyn Socket>> {
            Err(Error::config("no sockets"))
        }
    }

    // ADR 0023 §5: the device flow sends the pinned spaces as a hint.
    #[tokio::test]
    async fn device_flow_sends_pinned_space_ids() {
        let rec = Arc::new(Recorder(Mutex::new(vec![])));
        let secrets: Arc<dyn SecretStore> = Arc::new(MemorySecretStore::new());
        let keys = Arc::new(SoftwareKeyProvider::new(secrets.clone(), "k"));
        let auth = Auth::new("http://k.test".into(), "http://c.test".into(), "App".into(), rec.clone(), secrets, keys);
        {
            let mut slots = auth.slots.lock().unwrap();
            slots.insert("main".into(), ("editor".into(), Some("sp1".into())));
            slots.insert("notes".into(), ("viewer".into(), Some("sp2".into())));
            slots.insert("same".into(), ("viewer".into(), Some("sp1".into())));
            slots.insert("open".into(), ("editor".into(), None));
        }
        assert_eq!(auth.pinned_space_ids(), "sp1 sp2");
        let _ = auth.sign_in(&SignIn::device(|_| {})).await;
        let sent = rec.0.lock().unwrap().join("&");
        assert!(sent.contains("space_ids=sp1+sp2") || sent.contains("space_ids=sp1%20sp2"), "{sent}");
    }
}