Skip to main content

hns_wallet_provider/
lib.rs

1#![doc = "Hostile-page request, permission, approval, and event policy core."]
2#![forbid(unsafe_code)]
3
4use std::collections::{BTreeMap, BTreeSet};
5
6use hns_wallet_store::{SharedWalletStore, StoreError, WalletStore};
7use hns_wallet_types::{
8    AccountId, ApprovalId, ApprovalKind, BrowserRuntimeSessionId, HostAuthorityHandleId,
9    PROVIDER_METHOD_WIRE_NAMES, PermissionCapability, ProviderAuthorityFingerprint,
10    WalletSessionId,
11};
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14use sha2::{Digest, Sha256};
15use thiserror::Error;
16use url::{Host, Url};
17
18pub const MAX_PROVIDER_REQUEST_BYTES: usize = 64 * 1024;
19pub const MAX_METHOD_BYTES: usize = 96;
20pub const MAX_ORIGIN_BYTES: usize = 512;
21pub const APPROVAL_LIFETIME_SECONDS: u64 = 90;
22pub const RATE_WINDOW_SECONDS: u64 = 60;
23pub const MAX_REGISTERED_AUTHORITIES: usize = 256;
24pub const MAX_PENDING_APPROVALS: usize = 128;
25pub const MAX_REPLAY_NONCES: usize = 4_096;
26pub const MAX_APPROVED_ACCOUNTS: usize = 16;
27pub const MAX_APPROVED_NAMES: usize = 128;
28pub const PROVIDER_API_VERSION: u16 = 1;
29
30#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
31pub struct Origin {
32    serialized: String,
33}
34
35impl Origin {
36    pub fn parse(input: &str) -> Result<Self, ProviderError> {
37        if input.is_empty() || input.len() > MAX_ORIGIN_BYTES || !input.is_ascii() {
38            return Err(ProviderError::InvalidOrigin);
39        }
40        let parsed = Url::parse(input).map_err(|_| ProviderError::InvalidOrigin)?;
41        if parsed.username() != ""
42            || parsed.password().is_some()
43            || parsed.query().is_some()
44            || parsed.fragment().is_some()
45            || parsed.path() != "/"
46        {
47            return Err(ProviderError::InvalidOrigin);
48        }
49        let host = parsed.host().ok_or(ProviderError::InvalidOrigin)?;
50        let loopback = match host {
51            Host::Domain(domain) => domain == "localhost",
52            Host::Ipv4(address) => address.is_loopback(),
53            Host::Ipv6(address) => address.is_loopback(),
54        };
55        let secure = parsed.scheme() == "https" || (parsed.scheme() == "http" && loopback);
56        if !secure {
57            return Err(ProviderError::InsecureContext);
58        }
59        let port = parsed
60            .port_or_known_default()
61            .ok_or(ProviderError::InvalidOrigin)?;
62        let default_port = (parsed.scheme() == "https" && port == 443)
63            || (parsed.scheme() == "http" && port == 80);
64        let serialized_host = parsed.host_str().ok_or(ProviderError::InvalidOrigin)?;
65        let serialized = if default_port {
66            format!("{}://{serialized_host}", parsed.scheme())
67        } else {
68            format!("{}://{serialized_host}:{port}", parsed.scheme())
69        };
70        Ok(Self { serialized })
71    }
72
73    pub fn as_str(&self) -> &str {
74        &self.serialized
75    }
76}
77
78#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
79#[serde(rename_all = "lowercase")]
80pub enum SelectedNamespace {
81    Hns,
82    Icann,
83}
84
85/// Facts copied from an engine-issued authority by the trusted browser host.
86///
87/// The affirmative registration operation is the authorization signal. There
88/// are deliberately no caller-constructible authentication or injection
89/// booleans here, and wallet lock/session/permission state is never supplied
90/// by the host.
91#[derive(Clone, Debug, Eq, PartialEq)]
92pub struct HostAuthorityRegistration {
93    pub origin: Origin,
94    pub namespace: SelectedNamespace,
95    pub runtime_session: BrowserRuntimeSessionId,
96    pub runtime_generation: u64,
97    pub policy_generation: u64,
98    pub navigation_generation: u64,
99    pub decision_fingerprint: ProviderAuthorityFingerprint,
100    pub valid_until_unix_ms: u64,
101}
102
103impl HostAuthorityRegistration {
104    fn validate(&self, now_unix_ms: u64) -> Result<(), ProviderError> {
105        if self.runtime_generation == 0
106            || self.policy_generation == 0
107            || self.navigation_generation == 0
108            || self.valid_until_unix_ms <= now_unix_ms
109        {
110            return Err(ProviderError::StaleContext);
111        }
112        Ok(())
113    }
114}
115
116#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
117#[serde(deny_unknown_fields)]
118pub struct ProviderRequest {
119    pub method: String,
120    #[serde(default)]
121    pub params: Value,
122}
123
124impl ProviderRequest {
125    pub fn decode(input: &[u8]) -> Result<Self, ProviderError> {
126        if input.is_empty() || input.len() > MAX_PROVIDER_REQUEST_BYTES {
127            return Err(ProviderError::RequestTooLarge);
128        }
129        let request: Self =
130            serde_json::from_slice(input).map_err(|_| ProviderError::InvalidParams)?;
131        if request.method.is_empty() || request.method.len() > MAX_METHOD_BYTES {
132            return Err(ProviderError::MethodNotFound);
133        }
134        Ok(request)
135    }
136}
137
138#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
139#[repr(u8)]
140pub enum ProviderMethod {
141    WalletGetCapabilities,
142    WalletGetEnabledModules,
143    WalletEnableModule,
144    WalletDisableModule,
145    WalletRequestPermissions,
146    WalletGetPermissions,
147    WalletRevokePermissions,
148    WalletLock,
149    WalletGetStatus,
150    HnsRequestAccounts,
151    HnsAccounts,
152    HnsGetBalance,
153    HnsGetTransactions,
154    HnsGetReceiveAddress,
155    HnsSend,
156    HnsGetNames,
157    HnsGetName,
158    HnsImportKnownName,
159    HnsTransferName,
160    HnsFinalizeName,
161    HnsSignTypedMessage,
162    AssetGetAccount,
163    AssetGetBalance,
164    AssetGetTransactions,
165    AssetGetReceiveTarget,
166    AssetSend,
167    NameMarketListOffers,
168    NameMarketCreateFixedPriceOffer,
169    NameMarketCancelOffer,
170    NameMarketAcceptOffer,
171    NameMarketGetSession,
172    NameMarketFinalizePurchase,
173    NameMarketRecoverName,
174    SwapGetSupportedPairs,
175    SwapListDirectOffers,
176    SwapPublishDirectOffer,
177    SwapCancelDirectOffer,
178    SwapAcceptDirectOffer,
179    SwapGetSession,
180    SwapRedeem,
181    SwapRefund,
182    /// Set the exact Handshake resource bytes for a currently owned name.
183    /// Appended to preserve every existing stable enum/wire index.
184    HnsUpdateName,
185    /// List seller workflows owned by the selected wallet account.
186    /// Appended to preserve existing enum and wire indices.
187    NameMarketListMyOffers,
188    /// Resolve one exact, currently locked listing for a user-facing review.
189    NameMarketGetOffer,
190}
191
192impl ProviderMethod {
193    pub const ALL: [Self; PROVIDER_METHOD_WIRE_NAMES.len()] = [
194        Self::WalletGetCapabilities,
195        Self::WalletGetEnabledModules,
196        Self::WalletEnableModule,
197        Self::WalletDisableModule,
198        Self::WalletRequestPermissions,
199        Self::WalletGetPermissions,
200        Self::WalletRevokePermissions,
201        Self::WalletLock,
202        Self::WalletGetStatus,
203        Self::HnsRequestAccounts,
204        Self::HnsAccounts,
205        Self::HnsGetBalance,
206        Self::HnsGetTransactions,
207        Self::HnsGetReceiveAddress,
208        Self::HnsSend,
209        Self::HnsGetNames,
210        Self::HnsGetName,
211        Self::HnsImportKnownName,
212        Self::HnsTransferName,
213        Self::HnsFinalizeName,
214        Self::HnsSignTypedMessage,
215        Self::AssetGetAccount,
216        Self::AssetGetBalance,
217        Self::AssetGetTransactions,
218        Self::AssetGetReceiveTarget,
219        Self::AssetSend,
220        Self::NameMarketListOffers,
221        Self::NameMarketCreateFixedPriceOffer,
222        Self::NameMarketCancelOffer,
223        Self::NameMarketAcceptOffer,
224        Self::NameMarketGetSession,
225        Self::NameMarketFinalizePurchase,
226        Self::NameMarketRecoverName,
227        Self::SwapGetSupportedPairs,
228        Self::SwapListDirectOffers,
229        Self::SwapPublishDirectOffer,
230        Self::SwapCancelDirectOffer,
231        Self::SwapAcceptDirectOffer,
232        Self::SwapGetSession,
233        Self::SwapRedeem,
234        Self::SwapRefund,
235        Self::HnsUpdateName,
236        Self::NameMarketListMyOffers,
237        Self::NameMarketGetOffer,
238    ];
239
240    pub const fn wire_name(self) -> &'static str {
241        PROVIDER_METHOD_WIRE_NAMES[self as usize]
242    }
243
244    pub fn parse(method: &str) -> Result<Self, ProviderError> {
245        if let Some(index) = PROVIDER_METHOD_WIRE_NAMES
246            .iter()
247            .position(|candidate| *candidate == method)
248        {
249            return Ok(Self::ALL[index]);
250        }
251        if FORBIDDEN_METHODS.contains(&method) {
252            Err(ProviderError::ForbiddenMethod)
253        } else {
254            Err(ProviderError::MethodNotFound)
255        }
256    }
257
258    pub const fn requires_hns_namespace(self) -> bool {
259        matches!(
260            self,
261            Self::HnsRequestAccounts
262                | Self::HnsAccounts
263                | Self::HnsGetBalance
264                | Self::HnsGetTransactions
265                | Self::HnsGetReceiveAddress
266                | Self::HnsSend
267                | Self::HnsGetNames
268                | Self::HnsGetName
269                | Self::HnsImportKnownName
270                | Self::HnsTransferName
271                | Self::HnsFinalizeName
272                | Self::HnsUpdateName
273                | Self::HnsSignTypedMessage
274                | Self::NameMarketListOffers
275                | Self::NameMarketListMyOffers
276                | Self::NameMarketGetOffer
277                | Self::NameMarketCreateFixedPriceOffer
278                | Self::NameMarketCancelOffer
279                | Self::NameMarketAcceptOffer
280                | Self::NameMarketGetSession
281                | Self::NameMarketFinalizePurchase
282                | Self::NameMarketRecoverName
283        )
284    }
285
286    pub const fn permission(self) -> Option<PermissionCapability> {
287        match self {
288            Self::WalletGetCapabilities
289            | Self::WalletGetEnabledModules
290            | Self::WalletRequestPermissions
291            | Self::WalletGetPermissions
292            | Self::WalletRevokePermissions
293            | Self::WalletLock
294            | Self::WalletGetStatus
295            | Self::HnsRequestAccounts
296            | Self::SwapGetSupportedPairs => None,
297            Self::HnsAccounts | Self::AssetGetAccount => Some(PermissionCapability::Accounts),
298            Self::HnsGetBalance | Self::AssetGetBalance => Some(PermissionCapability::Balance),
299            Self::HnsGetTransactions | Self::AssetGetTransactions => {
300                Some(PermissionCapability::Transactions)
301            }
302            Self::HnsGetReceiveAddress | Self::AssetGetReceiveTarget => {
303                Some(PermissionCapability::ReceiveTarget)
304            }
305            Self::HnsSend | Self::AssetSend => Some(PermissionCapability::Send),
306            Self::HnsGetNames | Self::HnsGetName | Self::HnsImportKnownName => {
307                Some(PermissionCapability::Names)
308            }
309            Self::HnsTransferName => Some(PermissionCapability::NameTransfer),
310            Self::HnsFinalizeName => Some(PermissionCapability::NameFinalize),
311            Self::HnsUpdateName => Some(PermissionCapability::NameUpdate),
312            Self::HnsSignTypedMessage => Some(PermissionCapability::TypedIdentitySignature),
313            Self::NameMarketListOffers
314            | Self::NameMarketListMyOffers
315            | Self::NameMarketGetOffer
316            | Self::NameMarketCreateFixedPriceOffer
317            | Self::NameMarketCancelOffer
318            | Self::NameMarketAcceptOffer
319            | Self::NameMarketGetSession
320            | Self::NameMarketFinalizePurchase
321            | Self::NameMarketRecoverName => Some(PermissionCapability::NameMarket),
322            Self::SwapListDirectOffers
323            | Self::SwapPublishDirectOffer
324            | Self::SwapCancelDirectOffer
325            | Self::SwapAcceptDirectOffer => Some(PermissionCapability::CrossChainMarket),
326            Self::SwapGetSession | Self::SwapRedeem | Self::SwapRefund => {
327                Some(PermissionCapability::SwapSettlement)
328            }
329            Self::WalletEnableModule | Self::WalletDisableModule => None,
330        }
331    }
332
333    pub const fn approval(self) -> Option<ApprovalKind> {
334        match self {
335            Self::WalletEnableModule | Self::WalletDisableModule => {
336                Some(ApprovalKind::ModuleEnablement)
337            }
338            Self::WalletRequestPermissions | Self::HnsRequestAccounts => {
339                Some(ApprovalKind::Permission)
340            }
341            Self::HnsSend | Self::AssetSend => Some(ApprovalKind::Send),
342            Self::HnsTransferName => Some(ApprovalKind::NameTransfer),
343            Self::HnsFinalizeName => Some(ApprovalKind::NameFinalize),
344            Self::HnsUpdateName => Some(ApprovalKind::NameUpdate),
345            Self::HnsSignTypedMessage => Some(ApprovalKind::TypedSignature),
346            Self::NameMarketCreateFixedPriceOffer | Self::NameMarketCancelOffer => {
347                Some(ApprovalKind::NameMarketOffer)
348            }
349            Self::NameMarketAcceptOffer | Self::NameMarketFinalizePurchase => {
350                Some(ApprovalKind::NameMarketPurchase)
351            }
352            Self::NameMarketRecoverName => Some(ApprovalKind::NameMarketOffer),
353            Self::SwapPublishDirectOffer | Self::SwapCancelDirectOffer => {
354                Some(ApprovalKind::DirectOffer)
355            }
356            Self::SwapAcceptDirectOffer => Some(ApprovalKind::DirectOfferAcceptance),
357            Self::SwapRedeem => Some(ApprovalKind::SwapRedeem),
358            Self::SwapRefund => Some(ApprovalKind::SwapRefund),
359            _ => None,
360        }
361    }
362
363    const fn rate_limit(self) -> u32 {
364        if self.approval().is_some() { 10 } else { 120 }
365    }
366}
367
368const FORBIDDEN_METHODS: &[&str] = &[
369    "eth_sendTransaction",
370    "eth_call",
371    "eth_estimateGas",
372    "eth_sign",
373    "personal_sign",
374    "wallet_addEthereumChain",
375    "wallet_switchEthereumChain",
376    "bitcoin_signPsbt",
377    "signRawTransaction",
378    "wallet_getSeed",
379    "wallet_getPrivateKey",
380];
381
382#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
383pub struct PermissionRecord {
384    pub origin: Origin,
385    pub namespace: SelectedNamespace,
386    pub generation: u64,
387    pub capabilities: BTreeSet<PermissionCapability>,
388    /// Exact wallet-local accounts visible to this origin. Legacy records that
389    /// claimed `Accounts` without this binding deserialize but fail closed.
390    #[serde(default)]
391    pub approved_accounts: BTreeSet<AccountId>,
392    pub approved_names: BTreeSet<[u8; 32]>,
393    pub created_at_unix: u64,
394    pub expires_at_unix: Option<u64>,
395}
396
397/// The current authority-scoped permission view. `generation` survives an
398/// absent or expired record so a revocation tombstone can never project as a
399/// fresh generation zero.
400#[derive(Clone, Debug, Eq, PartialEq)]
401pub struct PermissionSnapshot {
402    pub generation: u64,
403    pub record: Option<PermissionRecord>,
404}
405
406impl PermissionRecord {
407    fn permits(&self, capability: PermissionCapability, now_unix: u64) -> bool {
408        self.capabilities.contains(&capability)
409            && self.expires_at_unix.is_none_or(|expiry| expiry > now_unix)
410    }
411}
412
413#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
414pub struct ApprovedCall {
415    pub origin: Origin,
416    pub namespace: SelectedNamespace,
417    pub method: ProviderMethod,
418    pub params: Value,
419    pub request_nonce: u64,
420}
421
422#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
423pub struct PendingApproval {
424    pub id: ApprovalId,
425    pub kind: ApprovalKind,
426    pub call: ApprovedCall,
427    pub authority_handle: HostAuthorityHandleId,
428    pub authority_revision: u64,
429    pub wallet_session: WalletSessionId,
430    pub permission_generation: u64,
431    pub expires_at_unix: u64,
432}
433
434#[derive(Clone, Debug, PartialEq)]
435pub enum ProviderAction {
436    Execute(ApprovedCall),
437    ApprovalRequired(PendingApproval),
438}
439
440pub trait ProviderStateStore {
441    fn permission(&self, scope: &str) -> Result<Option<PermissionRecord>, ProviderError>;
442    fn permission_generation(&self, scope: &str) -> Result<Option<u64>, ProviderError>;
443    fn save_permission(
444        &mut self,
445        scope: &str,
446        record: &PermissionRecord,
447    ) -> Result<(), ProviderError>;
448    fn revoke_permission(
449        &mut self,
450        scope: &str,
451        expected_generation: u64,
452        next_generation: u64,
453        now_unix: u64,
454    ) -> Result<(), ProviderError>;
455}
456
457impl ProviderStateStore for WalletStore {
458    fn permission(&self, scope: &str) -> Result<Option<PermissionRecord>, ProviderError> {
459        self.provider_permission(scope)?
460            .map(|(_, bytes)| serde_json::from_slice(&bytes).map_err(ProviderError::from))
461            .transpose()
462    }
463
464    fn permission_generation(&self, scope: &str) -> Result<Option<u64>, ProviderError> {
465        Ok(self.provider_permission_generation(scope)?)
466    }
467
468    fn save_permission(
469        &mut self,
470        scope: &str,
471        record: &PermissionRecord,
472    ) -> Result<(), ProviderError> {
473        self.put_provider_permission(
474            scope,
475            record.generation,
476            &serde_json::to_vec(record)?,
477            record.created_at_unix,
478        )?;
479        Ok(())
480    }
481
482    fn revoke_permission(
483        &mut self,
484        scope: &str,
485        expected_generation: u64,
486        next_generation: u64,
487        now_unix: u64,
488    ) -> Result<(), ProviderError> {
489        self.revoke_provider_permission(scope, expected_generation, next_generation, now_unix)?;
490        Ok(())
491    }
492}
493
494impl ProviderStateStore for SharedWalletStore {
495    fn permission(&self, scope: &str) -> Result<Option<PermissionRecord>, ProviderError> {
496        self.with_store(|store| store.provider_permission(scope))?
497            .map(|(_, bytes)| serde_json::from_slice(&bytes).map_err(ProviderError::from))
498            .transpose()
499    }
500
501    fn permission_generation(&self, scope: &str) -> Result<Option<u64>, ProviderError> {
502        Ok(self.with_store(|store| store.provider_permission_generation(scope))?)
503    }
504
505    fn save_permission(
506        &mut self,
507        scope: &str,
508        record: &PermissionRecord,
509    ) -> Result<(), ProviderError> {
510        let encoded = serde_json::to_vec(record)?;
511        self.with_store_mut(|store| {
512            store.put_provider_permission(
513                scope,
514                record.generation,
515                &encoded,
516                record.created_at_unix,
517            )
518        })?;
519        Ok(())
520    }
521
522    fn revoke_permission(
523        &mut self,
524        scope: &str,
525        expected_generation: u64,
526        next_generation: u64,
527        now_unix: u64,
528    ) -> Result<(), ProviderError> {
529        self.with_store_mut(|store| {
530            store.revoke_provider_permission(scope, expected_generation, next_generation, now_unix)
531        })?;
532        Ok(())
533    }
534}
535
536#[derive(Default)]
537pub struct MemoryProviderState {
538    permissions: BTreeMap<String, PermissionRecord>,
539    permission_generations: BTreeMap<String, u64>,
540}
541
542impl ProviderStateStore for MemoryProviderState {
543    fn permission(&self, scope: &str) -> Result<Option<PermissionRecord>, ProviderError> {
544        Ok(self.permissions.get(scope).cloned())
545    }
546
547    fn permission_generation(&self, scope: &str) -> Result<Option<u64>, ProviderError> {
548        Ok(self.permission_generations.get(scope).copied())
549    }
550
551    fn save_permission(
552        &mut self,
553        scope: &str,
554        record: &PermissionRecord,
555    ) -> Result<(), ProviderError> {
556        let expected = match self.permission_generations.get(scope).copied() {
557            Some(current) => current.checked_add(1).ok_or(ProviderError::StaleContext)?,
558            None => record.generation,
559        };
560        if record.generation != expected {
561            return Err(ProviderError::StaleContext);
562        }
563        self.permission_generations
564            .insert(scope.to_owned(), record.generation);
565        self.permissions.insert(scope.to_owned(), record.clone());
566        Ok(())
567    }
568
569    fn revoke_permission(
570        &mut self,
571        scope: &str,
572        expected_generation: u64,
573        next_generation: u64,
574        _: u64,
575    ) -> Result<(), ProviderError> {
576        if self.permission_generations.get(scope).copied() != Some(expected_generation)
577            || next_generation
578                != expected_generation
579                    .checked_add(1)
580                    .ok_or(ProviderError::StaleContext)?
581        {
582            return Err(ProviderError::StaleContext);
583        }
584        self.permissions.remove(scope);
585        self.permission_generations
586            .insert(scope.to_owned(), next_generation);
587        Ok(())
588    }
589}
590
591#[derive(Clone, Debug, Eq, PartialEq)]
592struct RegisteredAuthority {
593    facts: HostAuthorityRegistration,
594    revision: u64,
595}
596
597/// Provider policy and persisted state behind a bounded registry of opaque,
598/// host-issued handles. Pages never construct or observe a registered
599/// authority, and no engine policy is duplicated here.
600pub struct ProviderCore<S> {
601    state: S,
602    authorities: BTreeMap<HostAuthorityHandleId, RegisteredAuthority>,
603    wallet_session: WalletSessionId,
604    wallet_locked: bool,
605    last_now_unix_ms: u64,
606    pending: BTreeMap<ApprovalId, PendingApproval>,
607    replay: BTreeMap<(HostAuthorityHandleId, u64), u64>,
608    rate: BTreeMap<(HostAuthorityHandleId, ProviderMethod), RateWindow>,
609}
610
611impl<S: ProviderStateStore> ProviderCore<S> {
612    pub fn new(state: S, wallet_session: WalletSessionId, wallet_locked: bool) -> Self {
613        Self {
614            state,
615            authorities: BTreeMap::new(),
616            wallet_session,
617            wallet_locked,
618            last_now_unix_ms: 0,
619            pending: BTreeMap::new(),
620            replay: BTreeMap::new(),
621            rate: BTreeMap::new(),
622        }
623    }
624
625    pub fn register_authority(
626        &mut self,
627        handle: HostAuthorityHandleId,
628        facts: HostAuthorityRegistration,
629        now_unix_ms: u64,
630    ) -> Result<u64, ProviderError> {
631        self.accept_time(now_unix_ms)?;
632        facts.validate(now_unix_ms)?;
633        self.prune_expired_authorities(now_unix_ms);
634        if self.authorities.contains_key(&handle) {
635            return Err(ProviderError::DuplicateAuthority);
636        }
637        if self.authorities.len() >= MAX_REGISTERED_AUTHORITIES {
638            return Err(ProviderError::AuthorityCapacity);
639        }
640        self.authorities
641            .insert(handle, RegisteredAuthority { facts, revision: 1 });
642        Ok(1)
643    }
644
645    pub fn replace_authority(
646        &mut self,
647        handle: HostAuthorityHandleId,
648        expected_revision: u64,
649        replacement: HostAuthorityRegistration,
650        now_unix_ms: u64,
651    ) -> Result<u64, ProviderError> {
652        self.accept_time(now_unix_ms)?;
653        replacement.validate(now_unix_ms)?;
654        let current = self
655            .authorities
656            .get(&handle)
657            .cloned()
658            .ok_or(ProviderError::AuthorityNotFound)?;
659        if expected_revision == 0
660            || current.revision != expected_revision
661            || current.facts.valid_until_unix_ms <= now_unix_ms
662            || replacement.origin != current.facts.origin
663            || replacement.namespace != current.facts.namespace
664            || replacement.runtime_session != current.facts.runtime_session
665            || replacement.runtime_generation < current.facts.runtime_generation
666            || replacement.policy_generation < current.facts.policy_generation
667            || replacement.navigation_generation < current.facts.navigation_generation
668        {
669            return Err(ProviderError::StaleContext);
670        }
671        let revision = current
672            .revision
673            .checked_add(1)
674            .ok_or(ProviderError::StaleContext)?;
675        self.authorities.insert(
676            handle,
677            RegisteredAuthority {
678                facts: replacement,
679                revision,
680            },
681        );
682        self.pending
683            .retain(|_, approval| approval.authority_handle != handle);
684        self.rate.retain(|(candidate, _), _| *candidate != handle);
685        self.replay.retain(|(candidate, _), _| *candidate != handle);
686        Ok(revision)
687    }
688
689    pub fn revoke_authority(
690        &mut self,
691        handle: HostAuthorityHandleId,
692        expected_revision: u64,
693    ) -> Result<(), ProviderError> {
694        let authority = self
695            .authorities
696            .get(&handle)
697            .ok_or(ProviderError::AuthorityNotFound)?;
698        if expected_revision == 0 || authority.revision != expected_revision {
699            return Err(ProviderError::StaleContext);
700        }
701        self.authorities.remove(&handle);
702        self.pending
703            .retain(|_, approval| approval.authority_handle != handle);
704        self.rate.retain(|(candidate, _), _| *candidate != handle);
705        self.replay.retain(|(candidate, _), _| *candidate != handle);
706        Ok(())
707    }
708
709    pub fn set_wallet_state(&mut self, wallet_session: WalletSessionId, wallet_locked: bool) {
710        if wallet_session != self.wallet_session || wallet_locked != self.wallet_locked {
711            self.pending.clear();
712            self.replay.clear();
713            self.rate.clear();
714        }
715        self.wallet_session = wallet_session;
716        self.wallet_locked = wallet_locked;
717    }
718
719    pub const fn wallet_session_id(&self) -> WalletSessionId {
720        self.wallet_session
721    }
722
723    pub fn request(
724        &mut self,
725        handle: HostAuthorityHandleId,
726        authority_revision: u64,
727        request_nonce: u64,
728        now_unix_ms: u64,
729        request_bytes: &[u8],
730    ) -> Result<ProviderAction, ProviderError> {
731        self.accept_time(now_unix_ms)?;
732        let request = ProviderRequest::decode(request_bytes)?;
733        let authority = self
734            .authority(handle, authority_revision, now_unix_ms)?
735            .clone();
736        if request_nonce == 0 {
737            return Err(ProviderError::Replay);
738        }
739        let method = ProviderMethod::parse(&request.method)?;
740        if method.requires_hns_namespace() && authority.facts.namespace != SelectedNamespace::Hns {
741            return Err(ProviderError::Unauthorized);
742        }
743        validate_module_params(method, &request.params)?;
744        let now_unix = now_unix_ms / 1_000;
745        self.enforce_rate(handle, method, now_unix)?;
746        let expires_at_unix = now_unix_ms
747            .checked_add(APPROVAL_LIFETIME_SECONDS * 1_000)
748            .ok_or(ProviderError::StaleContext)?
749            / 1_000;
750        self.consume_nonce(handle, request_nonce, now_unix, expires_at_unix)?;
751
752        if self.wallet_locked
753            && !matches!(
754                method,
755                ProviderMethod::WalletGetStatus | ProviderMethod::WalletGetCapabilities
756            )
757        {
758            return Err(ProviderError::WalletLocked);
759        }
760        let scope = permission_scope(&authority.facts);
761        let permission_generation = self.state.permission_generation(&scope)?.unwrap_or(0);
762        if let Some(required) = method.permission() {
763            let permission = validate_permission_identity(
764                self.state.permission(&scope)?,
765                &authority.facts,
766                now_unix,
767            )?
768            .ok_or(ProviderError::Unauthorized)?;
769            if permission.generation != permission_generation
770                || !permission.permits(required, now_unix)
771            {
772                return Err(ProviderError::Unauthorized);
773            }
774        }
775
776        let call = ApprovedCall {
777            origin: authority.facts.origin.clone(),
778            namespace: authority.facts.namespace,
779            method,
780            params: request.params,
781            request_nonce,
782        };
783        let Some(kind) = method.approval() else {
784            return Ok(ProviderAction::Execute(call));
785        };
786        self.pending
787            .retain(|_, approval| approval.expires_at_unix > now_unix);
788        if self.pending.len() >= MAX_PENDING_APPROVALS {
789            return Err(ProviderError::RateLimited);
790        }
791        let approval = PendingApproval {
792            id: approval_id(
793                handle,
794                authority_revision,
795                self.wallet_session,
796                request_nonce,
797                method,
798                authority.facts.namespace,
799                &authority.facts.origin,
800            ),
801            kind,
802            call,
803            authority_handle: handle,
804            authority_revision,
805            wallet_session: self.wallet_session,
806            permission_generation,
807            expires_at_unix,
808        };
809        self.pending.insert(approval.id, approval.clone());
810        Ok(ProviderAction::ApprovalRequired(approval))
811    }
812
813    pub fn approve(
814        &mut self,
815        handle: HostAuthorityHandleId,
816        authority_revision: u64,
817        id: ApprovalId,
818        now_unix_ms: u64,
819    ) -> Result<ApprovedCall, ProviderError> {
820        self.accept_time(now_unix_ms)?;
821        let authority = self
822            .authority(handle, authority_revision, now_unix_ms)?
823            .clone();
824        let approval = self
825            .pending
826            .get(&id)
827            .cloned()
828            .ok_or(ProviderError::StaleApproval)?;
829        let now_unix = now_unix_ms / 1_000;
830        let scope = permission_scope(&authority.facts);
831        let permission_generation = self.state.permission_generation(&scope)?.unwrap_or(0);
832        if approval.expires_at_unix <= now_unix_ms / 1_000
833            || approval.call.origin != authority.facts.origin
834            || approval.call.namespace != authority.facts.namespace
835            || approval.authority_handle != handle
836            || approval.authority_revision != authority_revision
837            || approval.wallet_session != self.wallet_session
838            || approval.permission_generation != permission_generation
839        {
840            return Err(ProviderError::StaleApproval);
841        }
842        if let Some(required) = approval.call.method.permission() {
843            let permission = validate_permission_identity(
844                self.state.permission(&scope)?,
845                &authority.facts,
846                now_unix,
847            )?
848            .ok_or(ProviderError::StaleApproval)?;
849            if permission.generation != permission_generation
850                || !permission.permits(required, now_unix)
851            {
852                return Err(ProviderError::StaleApproval);
853            }
854        }
855        self.pending.remove(&id);
856        Ok(approval.call)
857    }
858
859    pub fn reject(
860        &mut self,
861        handle: HostAuthorityHandleId,
862        authority_revision: u64,
863        id: ApprovalId,
864        now_unix_ms: u64,
865    ) -> Result<(), ProviderError> {
866        self.accept_time(now_unix_ms)?;
867        let authority = self
868            .authority(handle, authority_revision, now_unix_ms)?
869            .clone();
870        let approval = self
871            .pending
872            .get(&id)
873            .cloned()
874            .ok_or(ProviderError::StaleApproval)?;
875        let scope = permission_scope(&authority.facts);
876        let permission_generation = self.state.permission_generation(&scope)?.unwrap_or(0);
877        if approval.expires_at_unix <= now_unix_ms / 1_000
878            || approval.call.origin != authority.facts.origin
879            || approval.call.namespace != authority.facts.namespace
880            || approval.authority_handle != handle
881            || approval.authority_revision != authority_revision
882            || approval.wallet_session != self.wallet_session
883            || approval.permission_generation != permission_generation
884        {
885            return Err(ProviderError::StaleApproval);
886        }
887        self.pending.remove(&id);
888        Ok(())
889    }
890
891    pub fn permission_snapshot(
892        &mut self,
893        handle: HostAuthorityHandleId,
894        authority_revision: u64,
895        now_unix_ms: u64,
896    ) -> Result<PermissionSnapshot, ProviderError> {
897        self.accept_time(now_unix_ms)?;
898        let authority = self
899            .authority(handle, authority_revision, now_unix_ms)?
900            .clone();
901        let scope = permission_scope(&authority.facts);
902        let generation = self.state.permission_generation(&scope)?.unwrap_or(0);
903        let stored = self.state.permission(&scope)?;
904        if stored
905            .as_ref()
906            .is_some_and(|permission| permission.generation != generation)
907        {
908            return Err(ProviderError::Persistence);
909        }
910        let permission =
911            validate_permission_identity(stored, &authority.facts, now_unix_ms / 1_000)?;
912        Ok(PermissionSnapshot {
913            generation,
914            record: permission,
915        })
916    }
917
918    pub fn permission(
919        &mut self,
920        handle: HostAuthorityHandleId,
921        authority_revision: u64,
922        now_unix_ms: u64,
923    ) -> Result<Option<PermissionRecord>, ProviderError> {
924        Ok(self
925            .permission_snapshot(handle, authority_revision, now_unix_ms)?
926            .record)
927    }
928
929    pub fn grant_permissions(
930        &mut self,
931        handle: HostAuthorityHandleId,
932        authority_revision: u64,
933        capabilities: BTreeSet<PermissionCapability>,
934        approved_names: BTreeSet<[u8; 32]>,
935        now_unix_ms: u64,
936        expires_at_unix: Option<u64>,
937    ) -> Result<PermissionRecord, ProviderError> {
938        self.grant_scoped_permissions(
939            handle,
940            authority_revision,
941            capabilities,
942            BTreeSet::new(),
943            approved_names,
944            now_unix_ms,
945            expires_at_unix,
946        )
947    }
948
949    /// Persist one generation of origin/namespace permission authority with
950    /// an exact account disclosure set. Account capability without a binding,
951    /// or a binding without account capability, is never accepted.
952    // These fields form the explicit permission-grant boundary; grouping them
953    // would obscure the public API's security-relevant inputs.
954    #[allow(clippy::too_many_arguments)]
955    pub fn grant_scoped_permissions(
956        &mut self,
957        handle: HostAuthorityHandleId,
958        authority_revision: u64,
959        capabilities: BTreeSet<PermissionCapability>,
960        approved_accounts: BTreeSet<AccountId>,
961        approved_names: BTreeSet<[u8; 32]>,
962        now_unix_ms: u64,
963        expires_at_unix: Option<u64>,
964    ) -> Result<PermissionRecord, ProviderError> {
965        self.grant_scoped_permissions_inner(
966            handle,
967            authority_revision,
968            None,
969            capabilities,
970            approved_accounts,
971            approved_names,
972            now_unix_ms,
973            expires_at_unix,
974        )
975    }
976
977    /// Persist a permission grant only if it still targets the exact
978    /// generation authenticated by an approval prompt.
979    #[allow(clippy::too_many_arguments)]
980    pub fn grant_scoped_permissions_at_generation(
981        &mut self,
982        handle: HostAuthorityHandleId,
983        authority_revision: u64,
984        expected_generation: u64,
985        capabilities: BTreeSet<PermissionCapability>,
986        approved_accounts: BTreeSet<AccountId>,
987        approved_names: BTreeSet<[u8; 32]>,
988        now_unix_ms: u64,
989        expires_at_unix: Option<u64>,
990    ) -> Result<PermissionRecord, ProviderError> {
991        self.grant_scoped_permissions_inner(
992            handle,
993            authority_revision,
994            Some(expected_generation),
995            capabilities,
996            approved_accounts,
997            approved_names,
998            now_unix_ms,
999            expires_at_unix,
1000        )
1001    }
1002
1003    #[allow(clippy::too_many_arguments)]
1004    fn grant_scoped_permissions_inner(
1005        &mut self,
1006        handle: HostAuthorityHandleId,
1007        authority_revision: u64,
1008        expected_generation: Option<u64>,
1009        capabilities: BTreeSet<PermissionCapability>,
1010        approved_accounts: BTreeSet<AccountId>,
1011        approved_names: BTreeSet<[u8; 32]>,
1012        now_unix_ms: u64,
1013        expires_at_unix: Option<u64>,
1014    ) -> Result<PermissionRecord, ProviderError> {
1015        self.accept_time(now_unix_ms)?;
1016        let now_unix = now_unix_ms / 1_000;
1017        let authority = self
1018            .authority(handle, authority_revision, now_unix_ms)?
1019            .clone();
1020        let binds_accounts = !approved_accounts.is_empty();
1021        if capabilities.is_empty()
1022            || approved_accounts.len() > MAX_APPROVED_ACCOUNTS
1023            || approved_names.len() > MAX_APPROVED_NAMES
1024            || approved_accounts
1025                .iter()
1026                .any(|account| account.as_bytes().iter().all(|byte| *byte == 0))
1027            || capabilities.contains(&PermissionCapability::Accounts) != binds_accounts
1028            || (binds_accounts && authority.facts.namespace != SelectedNamespace::Hns)
1029            || (!approved_names.is_empty()
1030                && (!capabilities.contains(&PermissionCapability::Names)
1031                    || !capabilities.contains(&PermissionCapability::Accounts)
1032                    || approved_accounts.is_empty()
1033                    || authority.facts.namespace != SelectedNamespace::Hns))
1034            || expires_at_unix.is_some_and(|expiry| expiry <= now_unix)
1035        {
1036            return Err(ProviderError::InvalidPermission);
1037        }
1038        let scope = permission_scope(&authority.facts);
1039        let current_generation = self.state.permission_generation(&scope)?.unwrap_or(0);
1040        if expected_generation.is_some_and(|expected| expected != current_generation) {
1041            return Err(ProviderError::StaleApproval);
1042        }
1043        let next_generation = current_generation
1044            .checked_add(1)
1045            .ok_or(ProviderError::StaleContext)?;
1046        let record = PermissionRecord {
1047            origin: authority.facts.origin.clone(),
1048            namespace: authority.facts.namespace,
1049            generation: next_generation,
1050            capabilities,
1051            approved_accounts,
1052            approved_names,
1053            created_at_unix: now_unix,
1054            expires_at_unix,
1055        };
1056        self.state.save_permission(&scope, &record)?;
1057        self.pending.retain(|_, approval| {
1058            approval.call.origin != authority.facts.origin
1059                || approval.call.namespace != authority.facts.namespace
1060        });
1061        Ok(record)
1062    }
1063
1064    pub fn revoke_permissions(
1065        &mut self,
1066        handle: HostAuthorityHandleId,
1067        authority_revision: u64,
1068        now_unix_ms: u64,
1069    ) -> Result<u64, ProviderError> {
1070        self.accept_time(now_unix_ms)?;
1071        let now_unix = now_unix_ms / 1_000;
1072        let authority = self
1073            .authority(handle, authority_revision, now_unix_ms)?
1074            .clone();
1075        let scope = permission_scope(&authority.facts);
1076        let expected_generation = self
1077            .state
1078            .permission_generation(&scope)?
1079            .ok_or(ProviderError::InvalidPermission)?;
1080        let next_generation = expected_generation
1081            .checked_add(1)
1082            .ok_or(ProviderError::StaleContext)?;
1083        self.state
1084            .revoke_permission(&scope, expected_generation, next_generation, now_unix)?;
1085        self.pending.retain(|_, approval| {
1086            approval.call.origin != authority.facts.origin
1087                || approval.call.namespace != authority.facts.namespace
1088        });
1089        Ok(next_generation)
1090    }
1091
1092    fn accept_time(&mut self, now_unix_ms: u64) -> Result<(), ProviderError> {
1093        if now_unix_ms < self.last_now_unix_ms {
1094            return Err(ProviderError::ClockRollback);
1095        }
1096        self.last_now_unix_ms = now_unix_ms;
1097        Ok(())
1098    }
1099
1100    fn authority(
1101        &self,
1102        handle: HostAuthorityHandleId,
1103        authority_revision: u64,
1104        now_unix_ms: u64,
1105    ) -> Result<&RegisteredAuthority, ProviderError> {
1106        let authority = self
1107            .authorities
1108            .get(&handle)
1109            .ok_or(ProviderError::AuthorityNotFound)?;
1110        if authority_revision == 0
1111            || authority.revision != authority_revision
1112            || authority.facts.valid_until_unix_ms <= now_unix_ms
1113        {
1114            return Err(ProviderError::StaleContext);
1115        }
1116        Ok(authority)
1117    }
1118
1119    fn prune_expired_authorities(&mut self, now_unix_ms: u64) {
1120        let expired: Vec<_> = self
1121            .authorities
1122            .iter()
1123            .filter_map(|(handle, authority)| {
1124                (authority.facts.valid_until_unix_ms <= now_unix_ms).then_some(*handle)
1125            })
1126            .collect();
1127        for handle in expired {
1128            self.authorities.remove(&handle);
1129            self.pending
1130                .retain(|_, approval| approval.authority_handle != handle);
1131            self.rate.retain(|(candidate, _), _| *candidate != handle);
1132            self.replay.retain(|(candidate, _), _| *candidate != handle);
1133        }
1134    }
1135
1136    fn consume_nonce(
1137        &mut self,
1138        handle: HostAuthorityHandleId,
1139        nonce: u64,
1140        now_unix: u64,
1141        expires_at_unix: u64,
1142    ) -> Result<(), ProviderError> {
1143        self.replay.retain(|_, expiry| *expiry > now_unix);
1144        if self.replay.contains_key(&(handle, nonce)) {
1145            return Err(ProviderError::Replay);
1146        }
1147        if self.replay.len() >= MAX_REPLAY_NONCES {
1148            return Err(ProviderError::RateLimited);
1149        }
1150        self.replay.insert((handle, nonce), expires_at_unix);
1151        Ok(())
1152    }
1153
1154    fn enforce_rate(
1155        &mut self,
1156        handle: HostAuthorityHandleId,
1157        method: ProviderMethod,
1158        now_unix: u64,
1159    ) -> Result<(), ProviderError> {
1160        let window = self.rate.entry((handle, method)).or_insert(RateWindow {
1161            starts_at_unix: now_unix,
1162            count: 0,
1163        });
1164        if now_unix.saturating_sub(window.starts_at_unix) >= RATE_WINDOW_SECONDS {
1165            *window = RateWindow {
1166                starts_at_unix: now_unix,
1167                count: 0,
1168            };
1169        }
1170        if window.count >= method.rate_limit() {
1171            return Err(ProviderError::RateLimited);
1172        }
1173        window.count += 1;
1174        Ok(())
1175    }
1176}
1177
1178#[derive(Clone, Copy)]
1179struct RateWindow {
1180    starts_at_unix: u64,
1181    count: u32,
1182}
1183
1184fn permission_scope(facts: &HostAuthorityRegistration) -> String {
1185    const HEX: &[u8; 16] = b"0123456789abcdef";
1186
1187    let namespace = match facts.namespace {
1188        SelectedNamespace::Hns => b"hns".as_slice(),
1189        SelectedNamespace::Icann => b"icann".as_slice(),
1190    };
1191    let mut hasher = Sha256::new();
1192    hasher.update(b"hns-provider-permission-scope/v2");
1193    hasher.update([0_u8]);
1194    hasher.update(namespace);
1195    hasher.update([0_u8]);
1196    hasher.update(facts.origin.as_str().as_bytes());
1197    let digest = hasher.finalize();
1198    let mut scope = String::with_capacity(31 + namespace.len() + digest.len() * 2);
1199    scope.push_str("hns-provider-permission-v2:");
1200    scope.push_str(match facts.namespace {
1201        SelectedNamespace::Hns => "hns:",
1202        SelectedNamespace::Icann => "icann:",
1203    });
1204    for byte in digest {
1205        scope.push(HEX[(byte >> 4) as usize] as char);
1206        scope.push(HEX[(byte & 0x0f) as usize] as char);
1207    }
1208    scope
1209}
1210
1211fn validate_permission_identity(
1212    permission: Option<PermissionRecord>,
1213    facts: &HostAuthorityRegistration,
1214    now_unix: u64,
1215) -> Result<Option<PermissionRecord>, ProviderError> {
1216    let Some(permission) = permission else {
1217        return Ok(None);
1218    };
1219    if permission.origin != facts.origin
1220        || permission.namespace != facts.namespace
1221        || permission.generation == 0
1222        || permission.capabilities.is_empty()
1223        || permission.approved_accounts.len() > MAX_APPROVED_ACCOUNTS
1224        || permission.approved_names.len() > MAX_APPROVED_NAMES
1225        || permission
1226            .approved_accounts
1227            .iter()
1228            .any(|account| account.as_bytes().iter().all(|byte| *byte == 0))
1229        || permission
1230            .capabilities
1231            .contains(&PermissionCapability::Accounts)
1232            == permission.approved_accounts.is_empty()
1233        || (!permission.approved_accounts.is_empty()
1234            && permission.namespace != SelectedNamespace::Hns)
1235        || (!permission.approved_names.is_empty()
1236            && (!permission
1237                .capabilities
1238                .contains(&PermissionCapability::Names)
1239                || !permission
1240                    .capabilities
1241                    .contains(&PermissionCapability::Accounts)
1242                || permission.approved_accounts.is_empty()
1243                || permission.namespace != SelectedNamespace::Hns))
1244        || permission.created_at_unix > now_unix
1245        || permission
1246            .expires_at_unix
1247            .is_some_and(|expiry| expiry <= permission.created_at_unix)
1248    {
1249        return Err(ProviderError::Persistence);
1250    }
1251    if permission
1252        .expires_at_unix
1253        .is_some_and(|expiry| expiry <= now_unix)
1254    {
1255        return Ok(None);
1256    }
1257    Ok(Some(permission))
1258}
1259
1260fn approval_id(
1261    handle: HostAuthorityHandleId,
1262    authority_revision: u64,
1263    wallet_session: WalletSessionId,
1264    request_nonce: u64,
1265    method: ProviderMethod,
1266    namespace: SelectedNamespace,
1267    origin: &Origin,
1268) -> ApprovalId {
1269    let mut hasher = Sha256::new();
1270    hasher.update(b"hns-provider-approval/v2");
1271    hasher.update(handle.as_bytes());
1272    hasher.update(authority_revision.to_be_bytes());
1273    hasher.update(wallet_session.as_bytes());
1274    hasher.update(request_nonce.to_be_bytes());
1275    hasher.update([match namespace {
1276        SelectedNamespace::Hns => 0_u8,
1277        SelectedNamespace::Icann => 1_u8,
1278    }]);
1279    hasher.update((origin.as_str().len() as u64).to_be_bytes());
1280    hasher.update(origin.as_str().as_bytes());
1281    hasher.update(method.wire_name().as_bytes());
1282    let digest: [u8; 32] = hasher.finalize().into();
1283    let mut id = [0_u8; 16];
1284    id.copy_from_slice(&digest[..16]);
1285    ApprovalId::new(id)
1286}
1287
1288fn validate_module_params(method: ProviderMethod, params: &Value) -> Result<(), ProviderError> {
1289    if !matches!(
1290        method,
1291        ProviderMethod::AssetGetAccount
1292            | ProviderMethod::AssetGetBalance
1293            | ProviderMethod::AssetGetTransactions
1294            | ProviderMethod::AssetGetReceiveTarget
1295            | ProviderMethod::AssetSend
1296    ) {
1297        return Ok(());
1298    }
1299    let module = params
1300        .as_object()
1301        .and_then(|object| object.get("module"))
1302        .and_then(Value::as_str)
1303        .ok_or(ProviderError::InvalidParams)?;
1304    if !matches!(module, "bitcoin" | "ethereum") {
1305        return Err(ProviderError::InvalidParams);
1306    }
1307    Ok(())
1308}
1309
1310#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
1311#[serde(rename_all = "camelCase")]
1312pub enum ProviderEvent {
1313    Connect,
1314    Disconnect,
1315    PermissionsChanged,
1316    ModulesChanged,
1317    AccountsChanged,
1318    BalancesChanged,
1319    TransactionsChanged,
1320    NamesChanged,
1321    NameMarketChanged,
1322    DirectOfferChanged,
1323    SwapSessionChanged,
1324    WalletLocked,
1325}
1326
1327#[derive(Debug, Error)]
1328pub enum ProviderError {
1329    #[error("invalid logical origin")]
1330    InvalidOrigin,
1331    #[error("provider requires an authenticated secure context")]
1332    InsecureContext,
1333    #[error("opaque browser authority handle is unknown or revoked")]
1334    AuthorityNotFound,
1335    #[error("opaque browser authority handle is already registered")]
1336    DuplicateAuthority,
1337    #[error("browser authority registry reached its bounded capacity")]
1338    AuthorityCapacity,
1339    #[error("request context is stale or mismatched")]
1340    StaleContext,
1341    #[error("provider wall clock moved backwards within this process")]
1342    ClockRollback,
1343    #[error("provider request exceeds its bounded maximum")]
1344    RequestTooLarge,
1345    #[error("provider method was not found")]
1346    MethodNotFound,
1347    #[error("method is intentionally forbidden")]
1348    ForbiddenMethod,
1349    #[error("provider parameters are invalid")]
1350    InvalidParams,
1351    #[error("origin lacks the required permission")]
1352    Unauthorized,
1353    #[error("wallet is locked")]
1354    WalletLocked,
1355    #[error("request rate limit exceeded")]
1356    RateLimited,
1357    #[error("request replay rejected")]
1358    Replay,
1359    #[error("approval is stale, expired, or belongs to another context")]
1360    StaleApproval,
1361    #[error("permission grant is invalid")]
1362    InvalidPermission,
1363    #[error("persistent provider state failed")]
1364    Persistence,
1365}
1366
1367impl From<StoreError> for ProviderError {
1368    fn from(error: StoreError) -> Self {
1369        match error {
1370            StoreError::Replay => Self::Replay,
1371            StoreError::Locked => Self::WalletLocked,
1372            _ => Self::Persistence,
1373        }
1374    }
1375}
1376
1377impl From<serde_json::Error> for ProviderError {
1378    fn from(_: serde_json::Error) -> Self {
1379        Self::Persistence
1380    }
1381}
1382
1383#[cfg(test)]
1384mod tests {
1385    use super::*;
1386
1387    const NOW_MS: u64 = 100_000;
1388
1389    fn origin() -> Origin {
1390        Origin::parse("https://wallet.example").expect("origin")
1391    }
1392
1393    fn wire_id<const N: usize>(byte: u8) -> [u8; N] {
1394        [byte; N]
1395    }
1396
1397    fn handle() -> HostAuthorityHandleId {
1398        HostAuthorityHandleId::from_bytes(wire_id(1)).expect("handle")
1399    }
1400
1401    fn wallet_session() -> WalletSessionId {
1402        WalletSessionId::from_bytes(wire_id(2)).expect("wallet session")
1403    }
1404
1405    fn registration() -> HostAuthorityRegistration {
1406        HostAuthorityRegistration {
1407            origin: origin(),
1408            namespace: SelectedNamespace::Hns,
1409            runtime_session: BrowserRuntimeSessionId::from_bytes(wire_id(3))
1410                .expect("runtime session"),
1411            runtime_generation: 2,
1412            policy_generation: 3,
1413            navigation_generation: 6,
1414            decision_fingerprint: ProviderAuthorityFingerprint::from_bytes(wire_id(4))
1415                .expect("fingerprint"),
1416            valid_until_unix_ms: NOW_MS + 60_000,
1417        }
1418    }
1419
1420    fn provider() -> ProviderCore<MemoryProviderState> {
1421        let mut provider =
1422            ProviderCore::new(MemoryProviderState::default(), wallet_session(), false);
1423        provider
1424            .register_authority(handle(), registration(), NOW_MS)
1425            .expect("register authority");
1426        provider
1427    }
1428
1429    #[test]
1430    fn canonical_provider_method_set_has_exact_wire_round_trips() {
1431        assert_eq!(ProviderMethod::ALL.len(), 44);
1432        let names: BTreeSet<_> = ProviderMethod::ALL
1433            .into_iter()
1434            .map(ProviderMethod::wire_name)
1435            .collect();
1436        assert_eq!(names.len(), 44);
1437        for (index, method) in ProviderMethod::ALL.into_iter().enumerate() {
1438            assert_eq!(method.wire_name(), PROVIDER_METHOD_WIRE_NAMES[index]);
1439            assert!(matches!(
1440                ProviderMethod::parse(method.wire_name()),
1441                Ok(parsed) if parsed == method
1442            ));
1443        }
1444        assert!(matches!(
1445            ProviderMethod::parse("wallet_unknown"),
1446            Err(ProviderError::MethodNotFound)
1447        ));
1448        assert!(matches!(
1449            ProviderMethod::parse("eth_sendTransaction"),
1450            Err(ProviderError::ForbiddenMethod)
1451        ));
1452    }
1453
1454    #[test]
1455    fn production_next_rejects_every_hns_method_outside_the_hns_namespace() {
1456        let mut icann_registration = registration();
1457        icann_registration.namespace = SelectedNamespace::Icann;
1458        let mut provider =
1459            ProviderCore::new(MemoryProviderState::default(), wallet_session(), false);
1460        provider
1461            .register_authority(handle(), icann_registration, NOW_MS)
1462            .expect("register ICANN authority");
1463
1464        let hns_methods = ProviderMethod::ALL
1465            .into_iter()
1466            .filter(|method| method.requires_hns_namespace())
1467            .collect::<Vec<_>>();
1468        assert_eq!(hns_methods.len(), 22);
1469        for (index, method) in hns_methods.into_iter().enumerate() {
1470            let request = serde_json::to_vec(&serde_json::json!({
1471                "method": method.wire_name(),
1472                "params": null,
1473            }))
1474            .expect("encode provider request");
1475            assert!(matches!(
1476                provider.request(
1477                    handle(),
1478                    1,
1479                    u64::try_from(index).expect("bounded method index") + 1,
1480                    NOW_MS,
1481                    &request,
1482                ),
1483                Err(ProviderError::Unauthorized)
1484            ));
1485        }
1486        assert!(provider.pending.is_empty());
1487        let permission = provider
1488            .permission_snapshot(handle(), 1, NOW_MS)
1489            .expect("ICANN permission snapshot");
1490        assert_eq!(permission.generation, 0);
1491        assert!(permission.record.is_none());
1492    }
1493
1494    #[test]
1495    fn permission_snapshot_preserves_fresh_and_tombstone_generations() {
1496        let mut provider = provider();
1497        let fresh = provider
1498            .permission_snapshot(handle(), 1, NOW_MS)
1499            .expect("fresh snapshot");
1500        assert_eq!(fresh.generation, 0);
1501        assert!(fresh.record.is_none());
1502
1503        let account = AccountId::new([7_u8; 16]);
1504        let granted = provider
1505            .grant_scoped_permissions(
1506                handle(),
1507                1,
1508                BTreeSet::from([PermissionCapability::Accounts]),
1509                BTreeSet::from([account]),
1510                BTreeSet::new(),
1511                NOW_MS,
1512                None,
1513            )
1514            .expect("grant");
1515        assert_eq!(granted.generation, 1);
1516        assert_eq!(granted.approved_accounts, BTreeSet::from([account]));
1517        let revoked_generation = provider
1518            .revoke_permissions(handle(), 1, NOW_MS)
1519            .expect("revoke");
1520        assert_eq!(revoked_generation, 2);
1521
1522        let tombstone = provider
1523            .permission_snapshot(handle(), 1, NOW_MS)
1524            .expect("tombstone snapshot");
1525        assert_eq!(tombstone.generation, 2);
1526        assert!(tombstone.record.is_none());
1527    }
1528
1529    #[test]
1530    fn production_followup_name_scope_requires_bounded_hns_account_authority() {
1531        let account = AccountId::new([7_u8; 16]);
1532        let name = [8_u8; 32];
1533        let mut provider = provider();
1534        assert!(matches!(
1535            provider.grant_permissions(
1536                handle(),
1537                1,
1538                BTreeSet::from([PermissionCapability::Names]),
1539                BTreeSet::from([name]),
1540                NOW_MS,
1541                None,
1542            ),
1543            Err(ProviderError::InvalidPermission)
1544        ));
1545        assert!(matches!(
1546            provider.grant_scoped_permissions(
1547                handle(),
1548                1,
1549                BTreeSet::from([PermissionCapability::Names]),
1550                BTreeSet::from([account]),
1551                BTreeSet::from([name]),
1552                NOW_MS,
1553                None,
1554            ),
1555            Err(ProviderError::InvalidPermission)
1556        ));
1557        let granted = provider
1558            .grant_scoped_permissions(
1559                handle(),
1560                1,
1561                BTreeSet::from([PermissionCapability::Accounts, PermissionCapability::Names]),
1562                BTreeSet::from([account]),
1563                BTreeSet::from([name]),
1564                NOW_MS,
1565                None,
1566            )
1567            .expect("account-bound name scope");
1568        assert_eq!(granted.approved_names, BTreeSet::from([name]));
1569
1570        let oversized = (0_u16..=MAX_APPROVED_NAMES as u16)
1571            .map(|index| {
1572                let mut name_hash = [0_u8; 32];
1573                name_hash[..2].copy_from_slice(&index.to_be_bytes());
1574                name_hash
1575            })
1576            .collect();
1577        assert!(matches!(
1578            provider.grant_scoped_permissions(
1579                handle(),
1580                1,
1581                BTreeSet::from([PermissionCapability::Accounts, PermissionCapability::Names,]),
1582                BTreeSet::from([account]),
1583                oversized,
1584                NOW_MS,
1585                None,
1586            ),
1587            Err(ProviderError::InvalidPermission)
1588        ));
1589
1590        let orphan = PermissionRecord {
1591            origin: origin(),
1592            namespace: SelectedNamespace::Hns,
1593            generation: 1,
1594            capabilities: BTreeSet::from([PermissionCapability::Names]),
1595            approved_accounts: BTreeSet::new(),
1596            approved_names: BTreeSet::from([name]),
1597            created_at_unix: 1,
1598            expires_at_unix: None,
1599        };
1600        assert!(matches!(
1601            validate_permission_identity(Some(orphan), &registration(), NOW_MS / 1_000),
1602            Err(ProviderError::Persistence)
1603        ));
1604    }
1605
1606    #[test]
1607    fn canonical_provider_account_join_rejects_unbound_and_legacy_account_authority() {
1608        let mut scoped_provider = provider();
1609        assert!(matches!(
1610            scoped_provider.grant_permissions(
1611                handle(),
1612                1,
1613                BTreeSet::from([PermissionCapability::Accounts]),
1614                BTreeSet::new(),
1615                NOW_MS,
1616                None,
1617            ),
1618            Err(ProviderError::InvalidPermission)
1619        ));
1620
1621        let account = AccountId::new([8_u8; 16]);
1622        let record = scoped_provider
1623            .grant_scoped_permissions(
1624                handle(),
1625                1,
1626                BTreeSet::from([PermissionCapability::Accounts]),
1627                BTreeSet::from([account]),
1628                BTreeSet::new(),
1629                NOW_MS,
1630                None,
1631            )
1632            .expect("scoped account grant");
1633        let mut legacy = serde_json::to_value(record).expect("record");
1634        legacy
1635            .as_object_mut()
1636            .expect("record object")
1637            .remove("approved_accounts");
1638        let legacy: PermissionRecord = serde_json::from_value(legacy).expect("legacy record");
1639        assert!(legacy.approved_accounts.is_empty());
1640        assert!(matches!(
1641            validate_permission_identity(Some(legacy), &registration(), NOW_MS / 1_000),
1642            Err(ProviderError::Persistence)
1643        ));
1644
1645        let mut provider = provider();
1646        let ProviderAction::ApprovalRequired(approval) = provider
1647            .request(
1648                handle(),
1649                1,
1650                1,
1651                NOW_MS,
1652                br#"{"method":"hns_requestAccounts","params":null}"#,
1653            )
1654            .expect("account approval")
1655        else {
1656            panic!("account approval required")
1657        };
1658        let approved_generation = approval.permission_generation;
1659        let approved_call = provider
1660            .approve(handle(), 1, approval.id, NOW_MS)
1661            .expect("approval validated");
1662        assert_eq!(approved_call.method, ProviderMethod::HnsRequestAccounts);
1663        provider
1664            .grant_permissions(
1665                handle(),
1666                1,
1667                BTreeSet::from([PermissionCapability::Send]),
1668                BTreeSet::new(),
1669                NOW_MS,
1670                None,
1671            )
1672            .expect("concurrent permission generation");
1673        assert!(matches!(
1674            provider.grant_scoped_permissions_at_generation(
1675                handle(),
1676                1,
1677                approved_generation,
1678                BTreeSet::from([PermissionCapability::Accounts]),
1679                BTreeSet::from([account]),
1680                BTreeSet::new(),
1681                NOW_MS,
1682                None,
1683            ),
1684            Err(ProviderError::StaleApproval)
1685        ));
1686        let current = provider
1687            .permission(handle(), 1, NOW_MS)
1688            .expect("permission read")
1689            .expect("concurrent grant retained");
1690        assert_eq!(current.generation, 1);
1691        assert_eq!(
1692            current.capabilities,
1693            BTreeSet::from([PermissionCapability::Send])
1694        );
1695        assert!(current.approved_accounts.is_empty());
1696    }
1697
1698    #[test]
1699    fn pages_have_no_constructible_trust_booleans_or_origin_context() {
1700        assert!(matches!(
1701            Origin::parse("http://wallet.example"),
1702            Err(ProviderError::InsecureContext)
1703        ));
1704        let mut provider = provider();
1705        assert!(matches!(
1706            provider.request(
1707                HostAuthorityHandleId::from_bytes(wire_id(9)).expect("other handle"),
1708                1,
1709                1,
1710                NOW_MS,
1711                br#"{"method":"wallet_getStatus"}"#
1712            ),
1713            Err(ProviderError::AuthorityNotFound)
1714        ));
1715        assert!(matches!(
1716            provider.request(
1717                handle(),
1718                1,
1719                2,
1720                NOW_MS,
1721                br#"{"method":"eth_sendTransaction","params":{}}"#
1722            ),
1723            Err(ProviderError::ForbiddenMethod)
1724        ));
1725    }
1726
1727    #[test]
1728    fn permissions_are_origin_scoped_and_value_movement_always_prompts() {
1729        let mut provider = provider();
1730        let scope = permission_scope(&registration());
1731        provider
1732            .state
1733            .save_permission(
1734                &scope,
1735                &PermissionRecord {
1736                    origin: origin(),
1737                    namespace: SelectedNamespace::Hns,
1738                    generation: 1,
1739                    capabilities: BTreeSet::from([PermissionCapability::Send]),
1740                    approved_accounts: BTreeSet::new(),
1741                    approved_names: BTreeSet::new(),
1742                    created_at_unix: 1,
1743                    expires_at_unix: None,
1744                },
1745            )
1746            .expect("permission");
1747        let action = provider
1748            .request(
1749                handle(),
1750                1,
1751                9,
1752                NOW_MS,
1753                br#"{"method":"hns_send","params":{"amount":"1","recipient":"hs1q"}}"#,
1754            )
1755            .expect("authorized request");
1756        let ProviderAction::ApprovalRequired(approval) = action else {
1757            panic!("send must require approval")
1758        };
1759        let mut replacement = registration();
1760        replacement.navigation_generation += 1;
1761        let revision = provider
1762            .replace_authority(handle(), 1, replacement, NOW_MS)
1763            .expect("replace");
1764        assert!(matches!(
1765            provider.approve(handle(), revision, approval.id, NOW_MS),
1766            Err(ProviderError::StaleApproval)
1767        ));
1768    }
1769
1770    #[test]
1771    fn duplicate_request_nonce_is_rejected() {
1772        let mut provider = provider();
1773        let bytes = br#"{"method":"wallet_getStatus"}"#;
1774        provider
1775            .request(handle(), 1, 11, NOW_MS, bytes)
1776            .expect("first");
1777        assert!(matches!(
1778            provider.request(handle(), 1, 11, NOW_MS, bytes),
1779            Err(ProviderError::Replay)
1780        ));
1781    }
1782
1783    #[test]
1784    fn external_asset_methods_are_generic_and_module_bounded() {
1785        let mut provider = provider();
1786        assert!(matches!(
1787            provider.request(
1788                handle(),
1789                1,
1790                12,
1791                NOW_MS,
1792                br#"{"method":"asset_getBalance","params":{"module":"litecoin"}}"#
1793            ),
1794            Err(ProviderError::InvalidParams)
1795        ));
1796    }
1797
1798    #[test]
1799    fn handle_replacement_is_exact_and_cannot_regress() {
1800        let mut provider = provider();
1801        let mut regressed = registration();
1802        regressed.navigation_generation -= 1;
1803        assert!(matches!(
1804            provider.replace_authority(handle(), 1, regressed, NOW_MS),
1805            Err(ProviderError::StaleContext)
1806        ));
1807        let mut replacement = registration();
1808        replacement.policy_generation += 1;
1809        assert_eq!(
1810            provider
1811                .replace_authority(handle(), 1, replacement, NOW_MS)
1812                .expect("fresh replacement"),
1813            2
1814        );
1815        assert!(matches!(
1816            provider.revoke_authority(handle(), 1),
1817            Err(ProviderError::StaleContext)
1818        ));
1819        provider
1820            .revoke_authority(handle(), 2)
1821            .expect("exact revision revoke");
1822    }
1823
1824    #[test]
1825    fn permission_tombstone_prevents_generation_reset() {
1826        let mut state = MemoryProviderState::default();
1827        let scope = permission_scope(&registration());
1828        let record = PermissionRecord {
1829            origin: origin(),
1830            namespace: SelectedNamespace::Hns,
1831            generation: 5,
1832            capabilities: BTreeSet::from([PermissionCapability::Send]),
1833            approved_accounts: BTreeSet::new(),
1834            approved_names: BTreeSet::new(),
1835            created_at_unix: 1,
1836            expires_at_unix: None,
1837        };
1838        state
1839            .save_permission(&scope, &record)
1840            .expect("trusted bootstrap");
1841        state.revoke_permission(&scope, 5, 6, 2).expect("revoke");
1842        let mut reset = record.clone();
1843        reset.generation = 6;
1844        assert!(matches!(
1845            state.save_permission(&scope, &reset),
1846            Err(ProviderError::StaleContext)
1847        ));
1848        reset.generation = 7;
1849        state
1850            .save_permission(&scope, &reset)
1851            .expect("next monotonic generation");
1852    }
1853}