polyc-web-session 2026.9.0

Browser session establishment (ADR 0007): one-time login challenges, the shared session cookie, and both the persona-passkey and wallet-passkey ceremonies that mint a polyc_crypto::session token. Consumed by polyc-control-plane; carries no ceremony-consumer naming of its own.
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
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
//! The wallet-passkey login ceremony (ADR 0007): stateless proof of wallet
//! ownership.
//!
//! Verified against nothing this control plane has stored — a session
//! minted here is trusted because the presented signature recovers the
//! claimed address, never because a matching credential record was found.
//!
//! # Root keys only, for now
//!
//! [`WalletLoginSessions::login`] accepts a
//! [`tempo_primitives::transaction::TempoSignature::Primitive`] envelope
//! only. A `Keychain` (TIP-1011 delegated-key) envelope is refused
//! ([`WalletLoginError::KeychainNotYetSupported`]) rather than half-verified:
//! `TempoSignature::recover_signer`'s own doc warns that for a `Keychain`
//! envelope it verifies the INNER signature belongs to SOME valid key and
//! returns the envelope's CLAIMED `user_address` — it does **not** confirm
//! that key is an authorized, non-revoked delegate of that address. Trusting
//! that claim without an onchain read (ADR 0007 calls this out, mirroring
//! `polyc_wallet_delegation::provision::key_is_revoked_onchain`) would let
//! anyone claim any address with a key of their own choosing. That read is
//! follow-up work; this slice only trusts a root key, where the recovered
//! address is a direct, self-authenticating commitment to the same key that
//! signed (`keccak256(pubkey)[12..]`) — nothing else to verify.
//!
//! # No stored `rp_id`/`origin` to check, and that is deliberate
//!
//! Unlike [`crate::passkey_login`]'s persona-credential login,
//! [`TempoSignature::recover_signer`] never inspects the `WebAuthn`
//! envelope's `origin`, and never checks `rpIdHash` against any expected
//! value — confirmed by reading the vendored verifier, not assumed. Adding
//! an independent origin check here would not close a real gap (the
//! high-entropy, single-use challenge this module mints is what a forged
//! envelope would actually need to guess) and would break the exact property
//! ADR 0007 designs for: a wallet signs once, for whichever origin's page
//! initiated the ceremony, and that same proof is valid against ANY
//! independent polychrome instance mounting this same verification — zero
//! prior registration, zero per-deployment credential to have pre-registered.
//! That is also why this ceremony does NOT build on
//! [`crate::LoginChallengeRegistry`] (unlike [`crate::passkey_login`]): that
//! type bundles a `WebAuthn` `rp_id`/`origin` config this ceremony has no use
//! for, so it uses the shared durable [`CeremonyAuthority`] directly instead
//! of forcing an unused config through its shape.
//!
//! # Challenge shape
//!
//! [`TempoSignature::recover_signer`] takes a 32-byte `sig_hash` and requires
//! the posted envelope's `clientDataJSON.challenge` to equal
//! `base64url(sig_hash)` exactly — unlike the persona-rooted login ceremony's
//! arbitrary-length token bytes, this MUST be exactly 32 bytes.
//! [`WalletLoginSessions::challenge`] mints an opaque durable one-time token
//! and derives the 32-byte signing
//! hash from it via a domain-separated `keccak256`, so the same one-time-
//! token discipline still governs mint/redeem/replay — only the bytes
//! actually signed differ from the persona-rooted login ceremony's.

use std::sync::Arc;

use alloy_primitives::{B256, keccak256};
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use polyc_ceremony::{
    CeremonyAuthority, CeremonyClassification, CeremonyError, CeremonyKind, CeremonyPayload,
    CeremonyToken, MAX_TTL_MS, MintCeremony,
};
#[cfg(any(test, feature = "test-util"))]
use polyc_crypto::session::RevokedTokens;
use tempo_primitives::transaction::TempoSignature;

use crate::{MintedSession, ScopeRoot};
use polyc_session_family::authority::BrowserSessionAuthority;

/// Domain-separation prefix for the 32-byte hash a wallet signs to log in —
/// keeps this hash's keccak256 preimage disjoint from every other
/// domain-separated hash this workspace computes (the session token's own
/// prefix in `polyc_crypto::session`, `KeychainSignature::signing_hash`'s
/// `0x04` byte, etc.), so a signature minted for one purpose can never be
/// replayed as if it were minted for this one.
const WALLET_LOGIN_DOMAIN_PREFIX: &[u8] = b"polychrome.wallet-login.v1\0";
const WALLET_LOGIN_SCHEMA: &[u8] = b"\x01";

/// Derive the 32-byte hash a wallet must sign to redeem `challenge_token`.
fn wallet_login_sig_hash(challenge_token: &str) -> B256 {
    domain_separated_sig_hash(WALLET_LOGIN_DOMAIN_PREFIX, challenge_token)
}

/// Derive a 32-byte domain-separated hash for a wallet to sign:
/// `keccak256(domain || token)`.
///
/// The general shape `wallet_login_sig_hash` specializes for the login
/// ceremony's own `WALLET_LOGIN_DOMAIN_PREFIX` — exposed here so any OTHER
/// ceremony that needs "prove you hold this wallet's key over MY OWN
/// one-time token" derives its
/// signing hash the identical way, with its own, disjoint `domain` constant.
/// `domain` MUST be unique per ceremony (never reused across two distinct
/// purposes) — that disjointness is what stops a signature minted for one
/// ceremony from being replayed as if it were minted for another; see
/// `WALLET_LOGIN_DOMAIN_PREFIX`'s own doc for the same discipline.
#[must_use]
pub fn domain_separated_sig_hash(domain: &[u8], token: &str) -> B256 {
    let mut preimage = Vec::with_capacity(domain.len() + token.len());
    preimage.extend_from_slice(domain);
    preimage.extend_from_slice(token.as_bytes());
    keccak256(preimage)
}

/// [`recover_root_wallet_address`] failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecoverRootWalletAddressError {
    /// The posted bytes do not parse as a `TempoSignature` envelope at all.
    MalformedEnvelope,
    /// The envelope is a `Keychain` (delegated-key) presentation — refused,
    /// see the module doc for why trusting it today would be unsound.
    KeychainNotYetSupported,
    /// The envelope parsed but recovery/verification failed (wrong hash,
    /// bad signature, wrong `clientDataJSON` type, ...).
    AssertionRejected,
}

/// Verify a root (non-keychain) `TempoSignature` envelope proves control of
/// a wallet's key over `sig_hash`, and return the recovered `0x`-hex
/// address.
///
/// The shared crypto-verification core of [`WalletLoginSessions::login`] —
/// steps 2-3 of that method's doc — factored out so any OTHER ceremony that
/// needs "prove you hold this wallet's key over MY OWN domain-separated
/// hash", including one with no pending
/// challenge registry of its own, can reuse the exact same parsing and
/// recovery logic rather than re-deriving it. Carries no challenge-registry
/// or session-minting concerns of its own — purely the recover-and-verify
/// primitive.
///
/// # Errors
///
/// See [`RecoverRootWalletAddressError`]'s variants.
pub fn recover_root_wallet_address(
    sig_hash: &B256,
    serialized_envelope: &[u8],
) -> Result<String, RecoverRootWalletAddressError> {
    let sig = TempoSignature::from_bytes(serialized_envelope)
        .map_err(|_| RecoverRootWalletAddressError::MalformedEnvelope)?;
    if sig.is_keychain() {
        return Err(RecoverRootWalletAddressError::KeychainNotYetSupported);
    }
    let address = sig
        .recover_signer(sig_hash)
        .map_err(|_| RecoverRootWalletAddressError::AssertionRejected)?;
    Ok(format!("{address:#x}"))
}

/// A freshly minted wallet-login challenge.
///
/// The opaque one-time `token` the browser posts back to redeem, and the
/// base64url `sig_hash_b64` string the wallet SDK signs (the
/// `navigator.credentials.get` `challenge` parameter).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalletLoginChallenge {
    /// Opaque one-time session token, posted back with the signed envelope.
    pub token: String,
    /// `base64url(no-pad)` of the 32-byte hash the wallet must sign.
    pub sig_hash_b64: String,
}

/// What the browser posts back to [`WalletLoginSessions::login`].
///
/// The raw `TempoSignature`-encoded envelope bytes
/// ([`tempo_primitives::transaction::TempoSignature::to_bytes`]'s wire
/// shape) — the exact bytes `ox`'s `SignatureEnvelope.serialize` produces
/// client-side (conformance-tested end-to-end,
/// `crates/wallet-delegation/src/tempo_envelope_conformance.rs`).
#[derive(Debug, Clone)]
pub struct PostedWalletAssertion {
    /// The serialized `TempoSignature` envelope.
    pub serialized_envelope: Vec<u8>,
}

/// A wallet login failed; every variant is a hard rejection (fail-closed).
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum WalletLoginError {
    /// The login challenge was missing, already redeemed, or expired.
    #[error("login challenge was missing, already used, or expired")]
    ChallengeExpired,
    /// The posted bytes do not parse as a `TempoSignature` envelope at all.
    #[error("the posted signature envelope is malformed")]
    MalformedEnvelope,
    /// The envelope parsed but recovery/verification failed (wrong
    /// challenge, bad signature, wrong `clientDataJSON` type, ...).
    #[error("the wallet signature did not verify")]
    AssertionRejected,
    /// The envelope is a `Keychain` (delegated-key) presentation — refused,
    /// see this module's doc for why trusting it today would be unsound.
    #[error("delegated (keychain) wallet keys are not yet accepted here")]
    KeychainNotYetSupported,
    /// The recovered address is on this deployment's local denylist (ADR
    /// 0007's operator-facing "stop honoring this wallet's sessions on this
    /// instance specifically" lever — see [`WalletAddressDenylist`]).
    #[error("this wallet is not permitted to sign in to this deployment")]
    AddressDenied,
    /// A persona-store read failed while resolving the wallet's linked
    /// persona — no verification verdict was reached either way.
    #[error("a persona-store read failed during login")]
    Storage,
    /// The session-family store failed while creating this session's
    /// rotation family.
    #[error("a session-store write failed during login")]
    FamilyStore(#[from] polyc_session_family::authority::SessionAuthorityError),
    /// Durable one-time authority could not establish a safe verdict.
    #[error("the one-time ceremony authority is unavailable")]
    CeremonyStore,
}

/// An instance-local denylist of wallet addresses this deployment refuses to
/// mint a session for.
///
/// ADR 0007's "Consequences" section: "the operator-facing mitigation for
/// 'stop honoring this wallet's sessions on this instance specifically' is a
/// new, explicitly instance-local address denylist — a local policy lever,
/// not an identity claim, and not a substitute for onchain revocation where
/// that's available."
///
/// Deliberately NOT a substitute for durable State bearer revocation: that
/// revokes an already-minted token at authorization time, while this policy
/// refuses to mint a new one for the address at all, regardless of whether
/// the wallet's root key is still fully intact and able to sign a fresh,
/// otherwise-valid challenge. A denylisted address's onchain funds and
/// delegated keys are entirely unaffected — this is a local policy refusal
/// on one instance, never a substitute for onchain `revokeKey`.
#[derive(Debug, Default)]
pub struct WalletAddressDenylist {
    denied: std::collections::HashSet<String>,
}

impl WalletAddressDenylist {
    /// Build a denylist from a set of `0x`-hex addresses. Compared
    /// case-insensitively (Tempo addresses are checksum-cased on display,
    /// case-insensitive on the wire), so callers may pass either case.
    #[must_use]
    pub fn new(addresses: impl IntoIterator<Item = String>) -> Self {
        Self {
            denied: addresses.into_iter().map(|a| a.to_lowercase()).collect(),
        }
    }

    /// An empty denylist — every address is permitted.
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }

    /// Whether `address` is denied on this deployment.
    #[must_use]
    pub fn contains(&self, address: &str) -> bool {
        self.denied.contains(&address.to_lowercase())
    }
}

/// The registry of pending wallet-login challenges.
/// See the module doc for why this is NOT built on
/// [`crate::LoginChallengeRegistry`].
pub struct WalletLoginSessions {
    /// Durable one-time authority. The signing hash is deterministically
    /// re-derived from the caller-held token, so State stores only the schema
    /// marker behind its digest identity.
    ceremonies: Arc<dyn CeremonyAuthority>,
    /// Legacy denylist retained only for compatibility fixtures.
    #[cfg(any(test, feature = "test-util"))]
    revoked: Arc<RevokedTokens>,
    /// This deployment's wallet-address denylist — see
    /// [`WalletAddressDenylist`]'s doc.
    address_denylist: Arc<WalletAddressDenylist>,
}

impl WalletLoginSessions {
    /// Build a fresh registry enforcing `address_denylist` (empty ⇒ every
    /// address permitted, see
    /// [`WalletAddressDenylist::empty`]).
    #[must_use]
    pub fn new(
        ceremonies: Arc<dyn CeremonyAuthority>,
        address_denylist: Arc<WalletAddressDenylist>,
    ) -> Self {
        Self {
            ceremonies,
            address_denylist,
            #[cfg(any(test, feature = "test-util"))]
            revoked: Arc::new(RevokedTokens::new()),
        }
    }

    /// Build a fixture sharing the retired process-local denylist.
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub fn new_with_legacy_revocations(
        ceremonies: Arc<dyn CeremonyAuthority>,
        revoked: Arc<RevokedTokens>,
        address_denylist: Arc<WalletAddressDenylist>,
    ) -> Self {
        Self {
            ceremonies,
            revoked,
            address_denylist,
        }
    }

    /// Mint a one-time wallet-login challenge.
    ///
    /// # Errors
    ///
    /// Returns the durable authority failure when no token was safely minted.
    pub async fn challenge(&self, now_ms: u64) -> Result<WalletLoginChallenge, CeremonyError> {
        let token = self
            .ceremonies
            .mint(MintCeremony {
                kind: CeremonyKind::WalletLogin,
                schema_version: 1,
                classification: CeremonyClassification::Internal,
                payload: CeremonyPayload::new(WALLET_LOGIN_SCHEMA.to_vec()),
                now_ms,
                ttl_ms: MAX_TTL_MS,
            })
            .await?;
        let sig_hash = wallet_login_sig_hash(token.expose());
        let sig_hash_b64 = URL_SAFE_NO_PAD.encode(sig_hash.as_slice());
        Ok(WalletLoginChallenge {
            token: token.expose().to_owned(),
            sig_hash_b64,
        })
    }

    /// Redeem a login challenge against a posted wallet signature and, on
    /// success, mint a wallet-rooted session token.
    ///
    /// Steps:
    ///
    /// 1. Redeem `challenge_token` through the durable authority as the first
    ///    awaited operation, matching
    ///    [`crate::passkey_login::PasskeyLoginSessions::login`]'s fail-closed
    ///    cancellation discipline.
    /// 2. Parse the posted bytes as a [`TempoSignature`]; refuse a `Keychain`
    ///    presentation outright (see the module doc).
    /// 3. Recover the signer address — this call itself verifies the P-256
    ///    signature and the `clientDataJSON` challenge/type, per
    ///    `tempo_primitives`. Refused outright if the address is on this
    ///    deployment's [`WalletAddressDenylist`], before any persona-store
    ///    read.
    /// 4. Resolve the session's subject and scopes via
    ///    [`crate::resolve_subject_and_scopes`] (the ONE shared scope-policy
    ///    helper: scopes are recomputed fresh here, never replayed from a
    ///    stored value): `WalletManage` always; `ExplorerRead` +
    ///    `AgentTurn` and the resolved `persona_id` only when the recovered
    ///    address currently resolves to a `STATUS_LINKED` persona.
    /// 5. Durably create the session's rotation family and bearer through
    ///    [`BrowserSessionAuthority`].
    ///
    /// # Errors
    ///
    /// See [`WalletLoginError`]'s variants.
    pub async fn login(
        &self,
        challenge_token: &str,
        proof: &PostedWalletAssertion,
        persona: &(impl crate::PersonaSessionReader + ?Sized),
        sessions: &dyn BrowserSessionAuthority,
        now_ms: u64,
    ) -> Result<MintedSession, WalletLoginError> {
        // 1. Redeem single-use as the first durable operation.
        let redemption = self
            .ceremonies
            .redeem(
                CeremonyKind::WalletLogin,
                CeremonyToken::new(challenge_token),
                now_ms,
            )
            .await;
        match redemption {
            Ok(payload) if payload.as_bytes() == WALLET_LOGIN_SCHEMA => {}
            Ok(_) | Err(CeremonyError::Invalid | CeremonyError::Unavailable) => {
                return Err(WalletLoginError::CeremonyStore);
            }
            Err(
                CeremonyError::NotRecognized
                | CeremonyError::Expired
                | CeremonyError::Spent
                | CeremonyError::Conflict,
            ) => return Err(WalletLoginError::ChallengeExpired),
        }
        let sig_hash = wallet_login_sig_hash(challenge_token);

        // 2-3. Parse, refuse Keychain, recover — see `recover_root_wallet_address`.
        let wallet_address = recover_root_wallet_address(&sig_hash, &proof.serialized_envelope)
            .map_err(|err| match err {
                RecoverRootWalletAddressError::MalformedEnvelope => {
                    WalletLoginError::MalformedEnvelope
                }
                RecoverRootWalletAddressError::KeychainNotYetSupported => {
                    WalletLoginError::KeychainNotYetSupported
                }
                RecoverRootWalletAddressError::AssertionRejected => {
                    WalletLoginError::AssertionRejected
                }
            })?;

        // 3b. Refuse before any persona-store I/O: a denylisted address
        // never gets a session, regardless of whether it also resolves to
        // a linked persona.
        if self.address_denylist.contains(&wallet_address) {
            return Err(WalletLoginError::AddressDenied);
        }

        // 4. Subject + scopes via the ONE shared policy helper.
        let (subject, scopes) = crate::resolve_subject_and_scopes(
            persona,
            ScopeRoot::Wallet {
                wallet_address: wallet_address.clone(),
            },
        )
        .await
        .map_err(|_| WalletLoginError::Storage)?;

        // 5. Create the rotation family. The persona this wallet resolves to
        // is never persisted on the family record — it is re-resolved from
        // `wallet_address` on every refresh (see `ScopeRoot::Wallet`'s doc).
        let (family, grant) = sessions
            .create_family(ScopeRoot::Wallet { wallet_address }, now_ms)
            .await
            .map_err(WalletLoginError::FamilyStore)?;

        let session_token = sessions
            .mint_bearer(&subject, &scopes, now_ms, crate::SESSION_TTL_MS)
            .await
            .map_err(WalletLoginError::FamilyStore)?;
        Ok(MintedSession {
            session_token,
            grant,
            family_expires_ms: family.absolute_expires_ms,
        })
    }

    /// Legacy fixture logout. Production logout is a durable State command.
    #[cfg(any(test, feature = "test-util"))]
    pub fn logout(&self, session_token: &str) {
        self.revoked.revoke(session_token);
    }

    /// Legacy fixture denylist.
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub const fn revoked(&self) -> &Arc<RevokedTokens> {
        &self.revoked
    }
}

/// Test-only envelope construction, exported behind `test-util`.
///
/// Mirrors `polyc_passkey`'s own `softkey` module gate, so
/// `polyc-control-plane`'s HTTP-level integration tests can post a REAL,
/// byte-correct `TempoSignature::WebAuthn` envelope without duplicating this
/// crate's own wire-format knowledge in a second, independently-maintained
/// copy.
#[cfg(any(test, feature = "test-util"))]
pub mod test_util {
    use alloy_primitives::{Address, B256, keccak256};
    use base64::Engine as _;
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use p256::ecdsa::Signature as P256Signature;
    use polyc_passkey::softkey::SoftPasskey;

    /// Re-derive the 32-byte hash a wallet must sign to redeem `challenge_token`.
    ///
    /// The same domain-separated `keccak256` this module's production code
    /// computes internally; exposed here so a caller minting a real
    /// challenge (via HTTP) can independently derive what to sign without
    /// reaching into this module's private items.
    #[must_use]
    pub fn sig_hash(challenge_token: &str) -> B256 {
        super::wallet_login_sig_hash(challenge_token)
    }

    /// Assemble a ROOT (non-keychain) `TempoSignature::WebAuthn` envelope
    /// signing `hash` with `soft`'s key.
    ///
    /// The exact wire shape
    /// [`tempo_primitives::transaction::TempoSignature::to_bytes`] produces,
    /// built by hand from [`SoftPasskey`]'s primitives (no real browser/ox
    /// involved) rather than a hand-transcribed literal.
    ///
    /// `rp_id`/`origin` are irrelevant to verification (see this module's
    /// doc — `recover_signer` never inspects them) so any fixed value works.
    ///
    /// # Panics
    ///
    /// If `soft`'s signature fails to DER-decode — never happens in
    /// practice, since [`SoftPasskey::sign_assertion`] always produces a
    /// valid DER-encoded ECDSA signature.
    #[must_use]
    pub fn build_root_webauthn_envelope(soft: &SoftPasskey, hash: &B256) -> Vec<u8> {
        let challenge_b64 = URL_SAFE_NO_PAD.encode(hash.as_slice());
        let signed = soft.sign_assertion(&challenge_b64, "unused.rp", "https://unused.origin");

        let mut webauthn_data = signed.authenticator_data.clone();
        webauthn_data.extend_from_slice(&signed.client_data_json);

        // DER -> raw (r, s), normalized to low-s (tempo-primitives enforces
        // low-s; see `normalize_p256_s` in the vendored verifier).
        let der_sig = P256Signature::from_der(&signed.signature).expect("valid DER signature");
        // `normalize_s` returns the low-s form directly as of ecdsa 0.17; it
        // returned `Option`, `Some` only when it changed the signature, in
        // 0.16. Calling it plain is what `.unwrap_or(der_sig)` used to mean.
        let normalized = der_sig.normalize_s();
        let rs = normalized.to_bytes();

        // SEC1 uncompressed: 0x04 || X(32) || Y(32).
        let pubkey = soft.public_key_sec1();
        assert_eq!(pubkey.len(), 65, "uncompressed SEC1 point");

        let mut envelope = Vec::with_capacity(1 + webauthn_data.len() + 128);
        envelope.push(0x02u8); // SIGNATURE_TYPE_WEBAUTHN
        envelope.extend_from_slice(&webauthn_data);
        envelope.extend_from_slice(&rs[0..32]); // r
        envelope.extend_from_slice(&rs[32..64]); // s
        envelope.extend_from_slice(&pubkey[1..33]); // pub_key_x
        envelope.extend_from_slice(&pubkey[33..65]); // pub_key_y
        envelope
    }

    /// The address a root `SoftPasskey`'s key recovers to.
    ///
    /// `keccak256(pub_key_x || pub_key_y)[12..]`, the same formula
    /// `tempo_primitives::transaction::derive_p256_address` (private to that
    /// crate) computes internally; re-derived here so a caller can assert a
    /// minted session carries the expected address.
    #[must_use]
    pub fn expected_address(soft: &SoftPasskey) -> String {
        let pubkey = soft.public_key_sec1();
        let hash = keccak256(&pubkey[1..65]);
        let address = Address::from_slice(&hash[12..]);
        format!("{address:#x}")
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use polyc_ceremony::test_util::MemoryCeremonies;
    use polyc_crypto::session::{
        SessionScope, SessionSubject, mint_session, verify_authorized_session, verify_session,
    };
    use polyc_crypto::signing_role::WebSessionGrantSigner;
    use polyc_passkey::softkey::SoftPasskey;
    use polyc_persona::PersonaHost;

    use super::test_util::{build_root_webauthn_envelope, expected_address, sig_hash};
    use super::*;
    use polyc_session_family::family_host::test_util::spawn_families;

    const NOW: u64 = 1_700_000_000_000;

    fn test_signer() -> WebSessionGrantSigner {
        WebSessionGrantSigner::from_key_bytes(&[7u8; 32])
            .expect("valid 32-byte ed25519 key material")
    }

    fn test_sessions() -> WalletLoginSessions {
        WalletLoginSessions::new_with_legacy_revocations(
            Arc::new(MemoryCeremonies::new()),
            Arc::new(RevokedTokens::new()),
            Arc::new(WalletAddressDenylist::empty()),
        )
    }

    /// A spawned `PersonaHost` on a temp dir, cleaned up on drop.
    struct TestPersona {
        host: PersonaHost,
        shutdown: tokio_util::sync::CancellationToken,
        dir: std::path::PathBuf,
    }
    impl std::ops::Deref for TestPersona {
        type Target = PersonaHost;
        fn deref(&self) -> &Self::Target {
            &self.host
        }
    }
    impl Drop for TestPersona {
        fn drop(&mut self) {
            self.shutdown.cancel();
            let _ = std::fs::remove_dir_all(&self.dir);
        }
    }
    fn spawn_persona() -> TestPersona {
        let dir = std::env::temp_dir().join(format!(
            "polychrome-wallet-login-{}-{}",
            std::process::id(),
            uuid::Uuid::new_v4()
        ));
        let shutdown = tokio_util::sync::CancellationToken::new();
        let host = PersonaHost::spawn(dir.clone(), shutdown.clone()).expect("spawn persona host");
        TestPersona {
            host,
            shutdown,
            dir,
        }
    }

    // ---- round-trip: no linked persona ---------------------------------

    #[tokio::test]
    async fn valid_root_signature_mints_a_wallet_manage_only_session_when_unlinked() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let signer = test_signer();
        let soft = SoftPasskey::from_seed(1);

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let hash = sig_hash(&challenge.token);
        let envelope = build_root_webauthn_envelope(&soft, &hash);
        let proof = PostedWalletAssertion {
            serialized_envelope: envelope,
        };

        let minted = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect("a valid root-key signature over the minted challenge logs in");

        let resolved =
            verify_authorized_session(&signer.public_key_bytes(), &minted.session_token, NOW)
                .expect("a freshly minted session verifies");
        assert_eq!(
            resolved.subject.wallet_address().map(str::to_owned),
            Some(expected_address(&soft))
        );
        assert_eq!(resolved.subject.persona_id(), None);
        assert!(resolved.has_scope(SessionScope::WalletManage));
        assert!(
            !resolved.has_scope(SessionScope::ExplorerRead),
            "no persona is linked yet, so no ExplorerRead"
        );
        assert!(
            !resolved.has_scope(SessionScope::AgentTurn),
            "a wallet with no linked persona has nobody to dispatch a turn as, so the mint side \
             must withhold AgentTurn — not leave the route's own refusal as the only guard"
        );

        // No linked persona -> registered ONLY in the by-wallet index, not
        // the by-persona one.
        let claims =
            polyc_crypto::session_grant::verify_grant(&signer.public_key_bytes(), &minted.grant)
                .expect("a freshly minted grant verifies");
        let family = families
            .get(claims.family_id)
            .await
            .expect("get")
            .expect("the family login created is present");
        assert_eq!(family.wallet_address, expected_address(&soft));
        assert!(family.persona_id.is_empty());
        assert_eq!(minted.family_expires_ms, family.absolute_expires_ms);
    }

    // ---- round-trip: linked, STATUS_LINKED persona ----------------------

    #[tokio::test]
    async fn valid_root_signature_also_grants_explorer_read_for_a_linked_persona() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let signer = test_signer();
        let soft = SoftPasskey::from_seed(2);
        let address = expected_address(&soft);

        let actor = polyc_proto::proto::polychrome::persona::v1::ExternalIdentity {
            provider: "test".to_owned(),
            external_id: "actor".to_owned(),
            ..Default::default()
        };
        persona
            .attribute(
                actor.clone(),
                "conv-bootstrap".to_owned(),
                polyc_persona::ROLE_INITIATOR.to_owned(),
                NOW,
            )
            .await
            .expect("bootstrap actor persona");
        let target = polyc_proto::proto::polychrome::persona::v1::ExternalIdentity {
            provider: "test".to_owned(),
            external_id: uuid::Uuid::new_v4().to_string(),
            ..Default::default()
        };
        let code = uuid::Uuid::new_v4().to_string();
        persona
            .start_link(actor, code.clone(), 3_600_000, NOW)
            .await
            .expect("start_link");
        let persona_id = match persona
            .complete_link(code, target, NOW)
            .await
            .expect("complete_link")
        {
            polyc_persona::CompleteLinkOutcome::Linked { persona_id } => persona_id,
            other => panic!("a fresh target must link cleanly: {other:?}"),
        };
        persona
            .set_wallet_link(
                &persona_id,
                address.clone(),
                "USD".to_owned(),
                "unused-key-ref".to_owned(),
                0,
                NOW,
                String::new(),
                String::new(),
                None,
            )
            .await
            .expect("set_wallet_link");

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let hash = sig_hash(&challenge.token);
        let envelope = build_root_webauthn_envelope(&soft, &hash);
        let proof = PostedWalletAssertion {
            serialized_envelope: envelope,
        };

        let minted = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect("a linked wallet logs in");

        let resolved =
            verify_authorized_session(&signer.public_key_bytes(), &minted.session_token, NOW)
                .expect("a freshly minted session verifies");
        assert_eq!(resolved.subject.wallet_address(), Some(address.as_str()));
        assert_eq!(resolved.subject.persona_id(), Some(persona_id.as_str()));
        assert!(resolved.has_scope(SessionScope::WalletManage));
        assert!(
            resolved.has_scope(SessionScope::ExplorerRead),
            "a STATUS_LINKED persona resolves -> ExplorerRead too"
        );
        assert!(
            resolved.has_scope(SessionScope::AgentTurn),
            "a STATUS_LINKED persona resolves -> AgentTurn too, so the chat surface is reachable \
             from a wallet-rooted login and not only a persona-credential one"
        );

        let claims =
            polyc_crypto::session_grant::verify_grant(&signer.public_key_bytes(), &minted.grant)
                .expect("a freshly minted grant verifies");
        let family = families
            .get(claims.family_id.clone())
            .await
            .expect("get")
            .expect("the family login created is present");
        assert_eq!(family.wallet_address, address);
    }

    // ---- challenge expiry / replay ---------------------------------------

    #[tokio::test]
    async fn expired_challenge_is_rejected() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(3);

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let hash = sig_hash(&challenge.token);
        let envelope = build_root_webauthn_envelope(&soft, &hash);
        let proof = PostedWalletAssertion {
            serialized_envelope: envelope,
        };

        let err = sessions
            .login(
                &challenge.token,
                &proof,
                &*persona,
                &*families,
                NOW + polyc_ceremony::MAX_TTL_MS + 1,
            )
            .await
            .expect_err("a challenge older than the shared TTL must be rejected");
        assert_eq!(err, WalletLoginError::ChallengeExpired);
    }

    #[tokio::test]
    async fn replayed_challenge_token_is_rejected_proving_single_use() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(4);

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let hash = sig_hash(&challenge.token);
        let envelope = build_root_webauthn_envelope(&soft, &hash);
        let proof = PostedWalletAssertion {
            serialized_envelope: envelope,
        };

        sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect("first redemption succeeds");

        let replay = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await;
        assert_eq!(
            replay.unwrap_err(),
            WalletLoginError::ChallengeExpired,
            "a spent challenge token must never redeem twice"
        );
    }

    // ---- recover_root_wallet_address (standalone primitive) --------------

    #[test]
    fn recover_root_wallet_address_returns_the_signers_address() {
        let soft = SoftPasskey::from_seed(42);
        let hash = sig_hash("some-domain-separated-token");
        let envelope = build_root_webauthn_envelope(&soft, &hash);

        let recovered =
            recover_root_wallet_address(&hash, &envelope).expect("a valid envelope recovers");
        assert_eq!(recovered, expected_address(&soft));
    }

    #[test]
    fn recover_root_wallet_address_rejects_a_mismatched_hash() {
        let soft = SoftPasskey::from_seed(43);
        let signed_hash = sig_hash("token-a");
        let checked_hash = sig_hash("token-b");
        let envelope = build_root_webauthn_envelope(&soft, &signed_hash);

        let err = recover_root_wallet_address(&checked_hash, &envelope)
            .expect_err("a mismatched hash must be rejected");
        assert_eq!(err, RecoverRootWalletAddressError::AssertionRejected);
    }

    #[test]
    fn recover_root_wallet_address_rejects_malformed_bytes() {
        let hash = sig_hash("whatever");
        let err = recover_root_wallet_address(&hash, &[0x02, 0x00])
            .expect_err("garbage bytes must be rejected");
        assert_eq!(err, RecoverRootWalletAddressError::MalformedEnvelope);
    }

    #[test]
    fn recover_root_wallet_address_refuses_a_keychain_envelope() {
        let soft = SoftPasskey::from_seed(44);
        let hash = sig_hash("token");
        let inner = build_root_webauthn_envelope(&soft, &hash);
        let victim = alloy_primitives::Address::from([0xEEu8; 20]);
        let mut keychain_envelope = vec![0x04u8];
        keychain_envelope.extend_from_slice(victim.as_slice());
        keychain_envelope.extend_from_slice(&inner);

        let err = recover_root_wallet_address(&hash, &keychain_envelope)
            .expect_err("a keychain envelope must be refused");
        assert_eq!(err, RecoverRootWalletAddressError::KeychainNotYetSupported);
    }

    // ---- wrong challenge / malformed / keychain --------------------------

    #[tokio::test]
    async fn signature_over_the_wrong_challenge_is_rejected() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(5);

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let wrong_hash = sig_hash("some-other-token-entirely");
        let envelope = build_root_webauthn_envelope(&soft, &wrong_hash);
        let proof = PostedWalletAssertion {
            serialized_envelope: envelope,
        };

        let err = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect_err("a mismatched challenge must be rejected");
        assert_eq!(err, WalletLoginError::AssertionRejected);
    }

    #[tokio::test]
    async fn malformed_envelope_bytes_are_rejected() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let proof = PostedWalletAssertion {
            serialized_envelope: vec![0x02, 0x00, 0x01],
        };

        let err = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect_err("garbage bytes must be rejected");
        assert_eq!(err, WalletLoginError::MalformedEnvelope);
    }

    #[tokio::test]
    async fn keychain_envelope_is_refused_not_half_verified() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(6);

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let hash = sig_hash(&challenge.token);
        let inner = build_root_webauthn_envelope(&soft, &hash);

        let victim = alloy_primitives::Address::from([0xEEu8; 20]);
        let mut keychain_envelope = Vec::new();
        keychain_envelope.push(0x04u8); // SIGNATURE_TYPE_KEYCHAIN_V2
        keychain_envelope.extend_from_slice(victim.as_slice());
        // The inner signature keeps its OWN type-id prefix (0x02, WebAuthn):
        // Keychain's wire format is [keychain_type] || user_address(20) ||
        // inner_signature, and `PrimitiveSignature::from_bytes` (which parses
        // the inner slice) itself expects a leading type byte.
        keychain_envelope.extend_from_slice(&inner);
        let proof = PostedWalletAssertion {
            serialized_envelope: keychain_envelope,
        };

        let err = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect_err("a keychain envelope must be refused, not trusted");
        assert_eq!(err, WalletLoginError::KeychainNotYetSupported);
    }

    // ---- address denylist ---------------------------------------------

    #[tokio::test]
    async fn a_denylisted_address_is_refused_even_with_a_valid_signature() {
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(7);
        let address = expected_address(&soft);
        let sessions = WalletLoginSessions::new_with_legacy_revocations(
            Arc::new(MemoryCeremonies::new()),
            Arc::new(RevokedTokens::new()),
            Arc::new(WalletAddressDenylist::new([address.clone()])),
        );

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let hash = sig_hash(&challenge.token);
        let envelope = build_root_webauthn_envelope(&soft, &hash);
        let proof = PostedWalletAssertion {
            serialized_envelope: envelope,
        };

        let err = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect_err("a denylisted address must be refused");
        assert_eq!(err, WalletLoginError::AddressDenied);
    }

    #[tokio::test]
    async fn denylist_comparison_is_case_insensitive() {
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(8);
        let address = expected_address(&soft);
        let sessions = WalletLoginSessions::new_with_legacy_revocations(
            Arc::new(MemoryCeremonies::new()),
            Arc::new(RevokedTokens::new()),
            // Deployment config carries the address in a different case
            // than `expected_address`'s own checksum casing — comparison
            // must still catch it.
            Arc::new(WalletAddressDenylist::new([address.to_uppercase()])),
        );

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let hash = sig_hash(&challenge.token);
        let envelope = build_root_webauthn_envelope(&soft, &hash);
        let proof = PostedWalletAssertion {
            serialized_envelope: envelope,
        };

        let err = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect_err("case must not matter for the denylist comparison");
        assert_eq!(err, WalletLoginError::AddressDenied);
    }

    #[tokio::test]
    async fn a_non_denylisted_address_signs_in_normally() {
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(9);
        let other = alloy_primitives::Address::from([0xAAu8; 20]);
        let sessions = WalletLoginSessions::new_with_legacy_revocations(
            Arc::new(MemoryCeremonies::new()),
            Arc::new(RevokedTokens::new()),
            Arc::new(WalletAddressDenylist::new([format!("{other:#x}")])),
        );

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let hash = sig_hash(&challenge.token);
        let envelope = build_root_webauthn_envelope(&soft, &hash);
        let proof = PostedWalletAssertion {
            serialized_envelope: envelope,
        };

        sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect("an address absent from the denylist signs in normally");
    }

    // ---- logout -----------------------------------------------------------

    #[test]
    fn logout_revokes_a_previously_accepted_session() {
        let sessions = test_sessions();
        let signer = test_signer();
        let session_signer = signer.relabel_for_test();
        let token = mint_session(
            &session_signer,
            &SessionSubject::Wallet {
                wallet_address: "0xabc".to_owned(),
                persona_id: None,
            },
            &[SessionScope::WalletManage],
            NOW,
            crate::SESSION_TTL_MS,
        );

        assert!(
            verify_session(
                &session_signer.public_key_bytes(),
                &token,
                NOW,
                &sessions.revoked
            )
            .is_some(),
            "a freshly minted session verifies before logout"
        );

        sessions.logout(&token);

        assert!(
            verify_session(
                &session_signer.public_key_bytes(),
                &token,
                NOW,
                &sessions.revoked
            )
            .is_none(),
            "the same session must be rejected once revoked"
        );
    }
}