keep-core 0.7.5

Core library for Keep - sovereign key management for Nostr and Bitcoin
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
// SPDX-FileCopyrightText: (C) 2026 PrivKey LLC
// SPDX-License-Identifier: MIT

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

use serde::{Deserialize, Serialize};

use crate::crypto::{self, EncryptedData, SecretKey};
use crate::error::{KeepError, Result as KeepResult};

/// Sentinel key for global (non-group-specific) relay configuration.
pub const GLOBAL_RELAY_KEY: [u8; 32] = [0u8; 32];

/// Maximum number of relays per category per share.
pub const MAX_RELAYS: usize = 10;

/// Maximum size of a decrypted relay-config blob.
pub const MAX_RELAY_CONFIG_SIZE: usize = 1024 * 1024;

/// Maximum number of persisted bunker app permissions per config.
pub const MAX_BUNKER_APPS: usize = 100;

/// Maximum length of a stored bunker app name.
pub const MAX_BUNKER_NAME_LEN: usize = 256;

/// Maximum number of auto-approve kinds per app or globally.
pub const MAX_AUTO_KINDS: usize = 64;

/// Valid bunker permission bitflags mask (matches `keep_nip46::Permission`).
pub const VALID_PERMISSION_MASK: u32 = 0b0011_1111;

/// Maximum length of a relay URL.
pub const MAX_RELAY_URL_LENGTH: usize = 256;

/// Range of seconds to randomly tweak event timestamps for privacy.
pub const TIMESTAMP_TWEAK_RANGE: std::ops::Range<u64> = 0..5;

/// Duration for stored bunker client permissions.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum StoredPermissionDuration {
    /// Lasts only for the current session (not persisted across restarts).
    Session,
    /// Expires after a number of seconds from `connected_at`.
    Seconds(u64),
    /// Never expires.
    Forever,
}

/// A single timed per-kind auto-approve grant persisted for a bunker client.
/// Survives restart; pruned on restore once `expires_at` has passed.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StoredTimedKindGrant {
    /// Event kind this grant auto-approves.
    pub kind: u16,
    /// Unix timestamp (seconds) when the grant expires.
    pub expires_at: u64,
}

/// Persisted permission state for a connected bunker (NIP-46) client.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StoredBunkerPermission {
    /// Client's Nostr public key as hex.
    pub pubkey_hex: String,
    /// Display name of the client app.
    pub name: String,
    /// Permission bitflags (matches `keep_nip46::Permission` bits).
    pub permissions: u32,
    /// Event kinds that skip user approval for `sign_event`.
    pub auto_approve_kinds: Vec<u16>,
    /// How long the permission grant lasts.
    pub duration: StoredPermissionDuration,
    /// Unix timestamp when the client first connected.
    pub connected_at: u64,
    /// Per-kind timed auto-approve grants that survive restart. Expired entries
    /// are pruned when the bunker restores this client.
    #[serde(default)]
    pub timed_kind_grants: Vec<StoredTimedKindGrant>,
    /// Whether the user made an explicit remember-decision for this app (picking
    /// a `Forever` or timed duration on the approval prompt), as opposed to a
    /// bare connection or a client-requested connect-time kind scope. Only
    /// remembered apps are persisted and restored, so a merely-connected client
    /// must re-present the connect secret after a restart. `None` marks a legacy
    /// row written before this field existed; the bunker falls back to inspecting
    /// the row's grants on restore.
    #[serde(default)]
    pub explicitly_remembered: Option<bool>,
}

/// Per-peer send/receive policy entry, stored alongside relay configuration.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PeerPolicyEntry {
    /// Nostr public key as hex string.
    pub pubkey_hex: String,
    /// Whether to allow sending messages to this peer.
    pub allow_send: bool,
    /// Whether to allow receiving messages from this peer.
    pub allow_receive: bool,
}

/// Relay configuration for a FROST share, keyed by group public key.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RelayConfig {
    /// The FROST group public key this config belongs to.
    pub group_pubkey: [u8; 32],
    /// FROST coordination relay URLs.
    pub frost_relays: Vec<String>,
    /// Profile / NIP-46 relay URLs.
    pub profile_relays: Vec<String>,
    /// NIP-46 bunker relay URLs.
    #[serde(default)]
    pub bunker_relays: Vec<String>,
    /// Per-peer send/receive policies.
    #[serde(default)]
    pub peer_policies: Vec<PeerPolicyEntry>,
    /// Persisted bunker client permission grants.
    #[serde(default)]
    pub bunker_permissions: Vec<StoredBunkerPermission>,
    /// Global event kinds auto-approved for every NIP-46 signing request,
    /// independent of any per-app `auto_approve_kinds`. Set via
    /// `keep nip46 auto-approve`.
    #[serde(default)]
    pub auto_approve_kinds: Vec<u16>,
}

impl RelayConfig {
    /// Create a new empty relay config for a group.
    pub fn new(group_pubkey: [u8; 32]) -> Self {
        Self {
            group_pubkey,
            frost_relays: Vec::new(),
            profile_relays: Vec::new(),
            bunker_relays: Vec::new(),
            peer_policies: Vec::new(),
            bunker_permissions: Vec::new(),
            auto_approve_kinds: Vec::new(),
        }
    }

    /// Create a global relay config using the sentinel key with default FROST relays.
    pub fn new_global() -> Self {
        Self::with_defaults(GLOBAL_RELAY_KEY)
    }

    /// Create a relay config with default FROST relays.
    pub fn with_defaults(group_pubkey: [u8; 32]) -> Self {
        Self {
            group_pubkey,
            frost_relays: default_frost_relays(),
            profile_relays: Vec::new(),
            bunker_relays: Vec::new(),
            peer_policies: Vec::new(),
            bunker_permissions: Vec::new(),
            auto_approve_kinds: Vec::new(),
        }
    }

    /// Validate and normalize a relay config before persistence.
    ///
    /// Relay URLs are normalized, deduplicated and validated; bunker
    /// permissions and auto-approve kinds are capped and masked. Used by every
    /// storage backend so all persisted configs share the same integrity rules.
    pub fn normalize(self) -> KeepResult<Self> {
        let normalize_relays = |urls: Vec<String>, label: &str| -> KeepResult<Vec<String>> {
            if urls.len() > MAX_RELAYS {
                return Err(KeepError::InvalidInput(format!(
                    "Too many {label} relays (max {MAX_RELAYS})"
                )));
            }
            let normalized = dedup_stable(urls.iter().map(|u| normalize_relay_url(u)));
            for url in &normalized {
                validate_relay_url(url).map_err(KeepError::InvalidInput)?;
            }
            Ok(normalized)
        };

        let mut peer_policies = Vec::with_capacity(self.peer_policies.len());
        for p in self.peer_policies {
            if p.pubkey_hex.len() != 64 || !p.pubkey_hex.chars().all(|c| c.is_ascii_hexdigit()) {
                return Err(KeepError::InvalidInput(format!(
                    "Invalid peer policy pubkey: {}",
                    p.pubkey_hex
                )));
            }
            peer_policies.push(PeerPolicyEntry {
                pubkey_hex: p.pubkey_hex.to_ascii_lowercase(),
                allow_send: p.allow_send,
                allow_receive: p.allow_receive,
            });
        }

        if self.bunker_permissions.len() > MAX_BUNKER_APPS {
            return Err(KeepError::InvalidInput(format!(
                "Too many bunker permissions: {} (max {MAX_BUNKER_APPS})",
                self.bunker_permissions.len()
            )));
        }
        let mut bunker_permissions = Vec::with_capacity(self.bunker_permissions.len());
        for bp in self.bunker_permissions {
            if bp.pubkey_hex.len() != 64 || !bp.pubkey_hex.chars().all(|c| c.is_ascii_hexdigit()) {
                return Err(KeepError::InvalidInput(format!(
                    "Invalid bunker permission pubkey: {}",
                    bp.pubkey_hex
                )));
            }
            if bp.name.len() > MAX_BUNKER_NAME_LEN {
                return Err(KeepError::InvalidInput(format!(
                    "Bunker app name too long: {} (max {MAX_BUNKER_NAME_LEN})",
                    bp.name.len()
                )));
            }
            if bp.auto_approve_kinds.len() > MAX_AUTO_KINDS {
                return Err(KeepError::InvalidInput(format!(
                    "Too many auto-approve kinds: {} (max {MAX_AUTO_KINDS})",
                    bp.auto_approve_kinds.len()
                )));
            }
            if bp.timed_kind_grants.len() > MAX_AUTO_KINDS {
                return Err(KeepError::InvalidInput(format!(
                    "Too many timed kind grants: {} (max {MAX_AUTO_KINDS})",
                    bp.timed_kind_grants.len()
                )));
            }
            bunker_permissions.push(StoredBunkerPermission {
                pubkey_hex: bp.pubkey_hex.to_ascii_lowercase(),
                name: bp.name,
                permissions: bp.permissions & VALID_PERMISSION_MASK,
                auto_approve_kinds: bp.auto_approve_kinds,
                duration: bp.duration,
                connected_at: bp.connected_at,
                timed_kind_grants: bp.timed_kind_grants,
                explicitly_remembered: bp.explicitly_remembered,
            });
        }

        if self.auto_approve_kinds.len() > MAX_AUTO_KINDS {
            return Err(KeepError::InvalidInput(format!(
                "Too many global auto-approve kinds: {} (max {MAX_AUTO_KINDS})",
                self.auto_approve_kinds.len()
            )));
        }
        let mut auto_approve_kinds = self.auto_approve_kinds;
        auto_approve_kinds.sort_unstable();
        auto_approve_kinds.dedup();

        Ok(Self {
            group_pubkey: self.group_pubkey,
            frost_relays: normalize_relays(self.frost_relays, "FROST")?,
            profile_relays: normalize_relays(self.profile_relays, "profile")?,
            bunker_relays: normalize_relays(self.bunker_relays, "bunker")?,
            peer_policies,
            bunker_permissions,
            auto_approve_kinds,
        })
    }
}

fn dedup_stable(iter: impl Iterator<Item = String>) -> Vec<String> {
    let mut seen = std::collections::HashSet::new();
    iter.filter(|s| seen.insert(s.clone())).collect()
}

/// Serialize and encrypt a relay config for at-rest storage.
pub fn encode_relay_config(config: &RelayConfig, key: &SecretKey) -> KeepResult<Vec<u8>> {
    let serialized = serde_json::to_vec(config)
        .map_err(|e| KeepError::Other(format!("json serialization failed: {e}")))?;
    if serialized.len() > MAX_RELAY_CONFIG_SIZE {
        return Err(KeepError::InvalidInput(format!(
            "relay config blob too large: {} (max {MAX_RELAY_CONFIG_SIZE})",
            serialized.len()
        )));
    }
    Ok(crypto::encrypt(&serialized, key)?.to_bytes())
}

/// Decrypt and deserialize a relay config blob produced by [`encode_relay_config`].
pub fn decode_relay_config(bytes: &[u8], key: &SecretKey) -> KeepResult<RelayConfig> {
    let encrypted = EncryptedData::from_bytes(bytes)?;
    let decrypted = crypto::decrypt(&encrypted, key)?;
    let decrypted_bytes = decrypted.as_slice()?;
    if decrypted_bytes.len() > MAX_RELAY_CONFIG_SIZE {
        return Err(KeepError::InvalidInput(format!(
            "relay config blob too large: {} (max {MAX_RELAY_CONFIG_SIZE})",
            decrypted_bytes.len()
        )));
    }
    serde_json::from_slice(&decrypted_bytes)
        .map_err(|e| KeepError::Other(format!("json deserialization failed: {e}")))
}

/// Default FROST coordination relays.
pub fn default_frost_relays() -> Vec<String> {
    // coracle's relay reliably delivers the rapid ephemeral (kind 24242) events
    // FROST coordination depends on; most public relays drop them, which causes
    // missed or prematurely-rejected signing rounds. Operators can add more in
    // settings for redundancy.
    vec!["wss://bucket.coracle.social".into()]
}

/// Normalize a relay URL: trim whitespace, lowercase scheme+host, ensure trailing slash.
pub fn normalize_relay_url(url: &str) -> String {
    let url = url.trim();
    let result = if let Some(idx) = url.find("://") {
        let scheme = url[..idx].to_lowercase();
        let rest = &url[idx + 3..];
        let host_end = rest.find('/').unwrap_or(rest.len());
        let host = rest[..host_end].to_lowercase();
        let path = &rest[host_end..];
        format!("{scheme}://{host}{path}")
    } else {
        url.to_string()
    };
    if result.ends_with('/') {
        result
    } else {
        format!("{result}/")
    }
}

/// Whether the `allow-internal` Cargo feature is active.
pub const ALLOW_INTERNAL_HOSTS: bool = cfg!(feature = "allow-internal");

/// Validate a relay URL is a valid wss:// URL pointing to a public host.
pub fn validate_relay_url(url: &str) -> Result<(), String> {
    validate_relay_url_inner(url, false)
}

/// Like [`validate_relay_url`] but permits internal/private addresses.
pub fn validate_relay_url_allow_internal(url: &str) -> Result<(), String> {
    validate_relay_url_inner(url, true)
}

fn validate_relay_url_inner(url: &str, allow_internal: bool) -> Result<(), String> {
    if url.len() > MAX_RELAY_URL_LENGTH {
        return Err("URL too long".into());
    }

    // `ws://` is normally rejected in release builds. It can be opted into via
    // the `allow-ws` Cargo feature (for tests) or the `KEEP_ALLOW_WS=1` runtime
    // env (for local development against `nak serve`). Both knobs are intended
    // for non-production use; production deployments should always speak wss://.
    let ws_allowed_at_runtime =
        cfg!(feature = "allow-ws") || std::env::var("KEEP_ALLOW_WS").as_deref() == Ok("1");
    let rest = url
        .strip_prefix("wss://")
        .or_else(|| {
            if ws_allowed_at_runtime {
                url.strip_prefix("ws://")
            } else {
                None
            }
        })
        .ok_or("Must use wss:// protocol (set KEEP_ALLOW_WS=1 for local-only ws:// testing)")?;

    if rest.is_empty() {
        return Err("Missing host".into());
    }

    let host_port = rest.split('/').next().unwrap_or(rest);
    if host_port.contains('@') {
        return Err("Userinfo not allowed in relay URLs".into());
    }

    let (host, port_str) = if host_port.starts_with('[') {
        match host_port.find(']') {
            Some(bracket_end) => {
                let host = &host_port[..=bracket_end];
                let remainder = &host_port[bracket_end + 1..];
                let port = remainder.strip_prefix(':').unwrap_or("");
                (host, port)
            }
            None => return Err("Unclosed IPv6 bracket".into()),
        }
    } else if let Some(colon_pos) = host_port.rfind(':') {
        let host = &host_port[..colon_pos];
        if host.contains(':') {
            return Err("Invalid unbracketed IPv6 address".into());
        }
        (host, &host_port[colon_pos + 1..])
    } else {
        (host_port, "")
    };
    if !port_str.is_empty() {
        let port = port_str.parse::<u16>().map_err(|_| "Invalid port")?;
        if port == 0 {
            return Err("Invalid port".into());
        }
    }

    if host.is_empty() {
        return Err("Missing host".into());
    }

    let valid_host_char = |c: char| {
        c.is_ascii_alphanumeric()
            || c == '.'
            || c == '-'
            || (host.starts_with('[') && (c == '[' || c == ']' || c == ':'))
    };
    if !host.chars().all(valid_host_char) {
        return Err("Invalid host characters".into());
    }

    if !allow_internal && is_internal_host(host) {
        return Err("Internal addresses not allowed".into());
    }

    Ok(())
}

/// Check if a resolved IP address is internal/private/reserved.
///
/// Use this after DNS resolution to prevent DNS rebinding attacks where
/// a hostname passes URL validation but resolves to an internal IP.
pub fn is_internal_ip(ip: &IpAddr) -> bool {
    match ip {
        IpAddr::V4(addr) => is_internal_v4(*addr),
        IpAddr::V6(addr) => is_internal_v6(addr),
    }
}

fn is_internal_v6(addr: &Ipv6Addr) -> bool {
    if let Some(v4) = to_embedded_v4(addr) {
        return is_internal_v4(v4);
    }
    let s = addr.segments();
    (s[0] & 0xfe00) == 0xfc00        // ULA fc00::/7
        || (s[0] & 0xffc0) == 0xfe80 // link-local fe80::/10
        || (s[0] & 0xffc0) == 0xfec0 // site-local fec0::/10 (deprecated)
        || (s[0] == 0x2001 && s[1] == 0x0db8) // documentation 2001:db8::/32
        || addr.is_loopback()
        || addr.is_unspecified()
        || addr.is_multicast()
}

fn to_embedded_v4(addr: &Ipv6Addr) -> Option<Ipv4Addr> {
    if let Some(mapped) = addr.to_ipv4_mapped() {
        return Some(mapped);
    }
    let s = addr.segments();
    let o = addr.octets();
    let tail_v4 = || Ipv4Addr::new(o[12], o[13], o[14], o[15]);
    // IPv4-compatible (::x.x.x.x): deprecated but still exploitable
    if s[..6] == [0, 0, 0, 0, 0, 0] {
        return Some(tail_v4());
    }
    // NAT64 Well-Known Prefix 64:ff9b::/96 (RFC 6052)
    if s[0] == 0x0064 && s[1] == 0xff9b && s[2..6] == [0, 0, 0, 0] {
        return Some(tail_v4());
    }
    // 6to4 (2002::/16): IPv4 embedded in bits 16-47
    if s[0] == 0x2002 {
        return Some(Ipv4Addr::new(o[2], o[3], o[4], o[5]));
    }
    // Teredo (2001:0000::/32): IPv4 XOR'd in last 32 bits
    if s[0] == 0x2001 && s[1] == 0x0000 {
        return Some(Ipv4Addr::new(
            o[12] ^ 0xff,
            o[13] ^ 0xff,
            o[14] ^ 0xff,
            o[15] ^ 0xff,
        ));
    }
    None
}

fn is_internal_v4(addr: Ipv4Addr) -> bool {
    addr.is_loopback()
        || addr.is_private()
        || addr.is_link_local()
        || addr.is_unspecified()
        || addr.is_multicast()
        || addr.octets()[0] == 0
        || is_cgn(addr)
        || is_special_purpose_v4(addr)
}

fn is_internal_host(host: &str) -> bool {
    let host = host.to_lowercase();

    // Strip brackets for IPv6
    let bare = host
        .strip_prefix('[')
        .and_then(|h| h.strip_suffix(']'))
        .unwrap_or(&host);

    // Strip trailing dot (FQDN bypass)
    let bare = bare.strip_suffix('.').unwrap_or(bare);

    if let Ok(addr) = bare.parse::<Ipv6Addr>() {
        return is_internal_v6(&addr);
    }

    if let Ok(addr) = bare.parse::<Ipv4Addr>() {
        return is_internal_v4(addr);
    }

    const FORBIDDEN: &[&str] = &["localhost"];

    if FORBIDDEN.contains(&bare)
        || bare.ends_with(".local")
        || bare.ends_with(".localhost")
        || bare.ends_with(".arpa")
        || bare.ends_with(".onion")
    {
        return true;
    }

    // Reject single-label hostnames (no dots) to prevent SSRF to internal names
    !bare.contains('.')
}

fn is_cgn(addr: Ipv4Addr) -> bool {
    let octets = addr.octets();
    octets[0] == 100 && (64..=127).contains(&octets[1])
}

fn is_special_purpose_v4(addr: Ipv4Addr) -> bool {
    let o = addr.octets();
    // TEST-NET-1 192.0.2.0/24 (RFC 5737)
    (o[0] == 192 && o[1] == 0 && o[2] == 2)
    // TEST-NET-2 198.51.100.0/24 (RFC 5737)
    || (o[0] == 198 && o[1] == 51 && o[2] == 100)
    // TEST-NET-3 203.0.113.0/24 (RFC 5737)
    || (o[0] == 203 && o[1] == 0 && o[2] == 113)
    // Benchmarking 198.18.0.0/15 (RFC 2544)
    || (o[0] == 198 && (o[1] == 18 || o[1] == 19))
    // Reserved 240.0.0.0/4
    || o[0] >= 240
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn valid_relay_urls() {
        assert!(validate_relay_url("wss://relay.example.com/").is_ok());
        assert!(validate_relay_url("wss://relay.example.com").is_ok());
        assert!(validate_relay_url("wss://relay.example.com:443/").is_ok());
        assert!(validate_relay_url("wss://relay.example.com:8080").is_ok());
        assert!(validate_relay_url("wss://bucket.coracle.social/").is_ok());
    }

    #[test]
    fn rejects_non_wss() {
        if cfg!(feature = "allow-ws") {
            assert!(validate_relay_url("ws://relay.example.com").is_ok());
        } else {
            assert!(validate_relay_url("ws://relay.example.com").is_err());
        }
        assert!(validate_relay_url("http://relay.example.com").is_err());
        assert!(validate_relay_url("relay.example.com").is_err());
    }

    #[test]
    fn rejects_empty_and_too_long() {
        assert!(validate_relay_url("wss://").is_err());
        let long_url = format!("wss://{}.example.com", "a".repeat(300));
        assert!(validate_relay_url(&long_url).is_err());
    }

    #[test]
    fn rejects_invalid_ports() {
        assert!(validate_relay_url("wss://relay.example.com:0").is_err());
        assert!(validate_relay_url("wss://relay.example.com:abc").is_err());
        assert!(validate_relay_url("wss://relay.example.com:99999").is_err());
    }

    #[test]
    fn rejects_internal_ipv4() {
        assert!(validate_relay_url("wss://127.0.0.1/").is_err());
        assert!(validate_relay_url("wss://127.0.0.2/").is_err());
        assert!(validate_relay_url("wss://10.0.0.1/").is_err());
        assert!(validate_relay_url("wss://192.168.1.1/").is_err());
        assert!(validate_relay_url("wss://172.16.0.1/").is_err());
        assert!(validate_relay_url("wss://172.31.255.255/").is_err());
        assert!(validate_relay_url("wss://169.254.169.254/").is_err());
        assert!(validate_relay_url("wss://0.0.0.0/").is_err());
    }

    #[test]
    fn rejects_localhost_variants() {
        assert!(validate_relay_url("wss://localhost/").is_err());
        assert!(validate_relay_url("wss://LOCALHOST/").is_err());
        assert!(validate_relay_url("wss://something.localhost/").is_err());
        assert!(validate_relay_url("wss://host.local/").is_err());
    }

    #[test]
    fn rejects_trailing_dot_bypass() {
        assert!(validate_relay_url("wss://localhost./").is_err());
    }

    #[test]
    fn rejects_ipv6_internal() {
        assert!(validate_relay_url("wss://[::1]/").is_err());
        assert!(validate_relay_url("wss://[::ffff:127.0.0.1]/").is_err());
        assert!(validate_relay_url("wss://[::ffff:10.0.0.1]/").is_err());
        assert!(validate_relay_url("wss://[fc00::1]/").is_err());
        assert!(validate_relay_url("wss://[fd00::1]/").is_err());
        assert!(validate_relay_url("wss://[fe80::1]/").is_err());
        assert!(validate_relay_url("wss://[ff02::1]/").is_err());
        // IPv4-compatible (::x.x.x.x), exercises to_embedded_v4 deprecated-compat path
        assert!(validate_relay_url("wss://[::7f00:1]/").is_err()); // ::127.0.0.1
        assert!(validate_relay_url("wss://[::a00:1]/").is_err()); // ::10.0.0.1
                                                                  // NAT64 Well-Known Prefix 64:ff9b::/96, exercises to_embedded_v4 NAT64 path
        assert!(validate_relay_url("wss://[64:ff9b::7f00:1]/").is_err()); // embeds 127.0.0.1
        assert!(validate_relay_url("wss://[64:ff9b::a00:1]/").is_err()); // embeds 10.0.0.1
    }

    #[test]
    fn allows_public_172() {
        assert!(validate_relay_url("wss://172.15.0.1/").is_ok());
        assert!(validate_relay_url("wss://172.32.0.1/").is_ok());
    }

    #[test]
    fn rejects_cgn_range() {
        assert!(validate_relay_url("wss://100.64.0.1/").is_err());
        assert!(validate_relay_url("wss://100.127.255.255/").is_err());
        // Outside CGN range - should be allowed
        assert!(validate_relay_url("wss://100.63.0.1/").is_ok());
        assert!(validate_relay_url("wss://100.128.0.1/").is_ok());
    }

    #[test]
    fn rejects_ipv6_mapped_cgn() {
        assert!(validate_relay_url("wss://[::ffff:100.64.0.1]/").is_err());
        assert!(validate_relay_url("wss://[::ffff:100.127.255.255]/").is_err());
    }

    #[test]
    fn ipv6_with_port() {
        assert!(validate_relay_url("wss://[::1]:443/").is_err());
    }

    #[test]
    fn no_false_positives_on_hostnames() {
        assert!(validate_relay_url("wss://fflogs.example.com/").is_ok());
        assert!(validate_relay_url("wss://fdsecurity.com/").is_ok());
        assert!(validate_relay_url("wss://fe80x.example.com/").is_ok());
    }

    #[test]
    fn unclosed_ipv6_bracket() {
        assert!(validate_relay_url("wss://[::1/").is_err());
    }

    #[test]
    fn rejects_unbracketed_ipv6() {
        assert!(validate_relay_url("wss://::1/").is_err());
        assert!(validate_relay_url("wss://fc00::1/").is_err());
        assert!(validate_relay_url("wss://fe80::1/").is_err());
    }

    #[test]
    fn normalize_adds_trailing_slash() {
        assert_eq!(
            normalize_relay_url("wss://relay.example.com"),
            "wss://relay.example.com/"
        );
        assert_eq!(
            normalize_relay_url("wss://relay.example.com/"),
            "wss://relay.example.com/"
        );
    }

    #[test]
    fn normalize_lowercases_host() {
        assert_eq!(
            normalize_relay_url("wss://RELAY.Example.COM/"),
            "wss://relay.example.com/"
        );
        assert_eq!(
            normalize_relay_url("wss://RELAY.Example.COM:8080/"),
            "wss://relay.example.com:8080/"
        );
    }

    #[test]
    fn normalize_deduplicates_urls() {
        assert_eq!(
            normalize_relay_url("wss://relay.example.com"),
            normalize_relay_url("wss://relay.example.com/")
        );
        assert_eq!(
            normalize_relay_url("wss://Relay.Example.COM/"),
            normalize_relay_url("wss://relay.example.com/")
        );
    }

    #[test]
    fn normalize_trims_whitespace() {
        assert_eq!(
            normalize_relay_url("  wss://relay.example.com/  "),
            "wss://relay.example.com/"
        );
    }

    #[test]
    fn rejects_single_label_hostnames() {
        assert!(validate_relay_url("wss://intranet/").is_err());
        assert!(validate_relay_url("wss://fileserver/").is_err());
        assert!(validate_relay_url("wss://router/").is_err());
    }

    #[test]
    fn rejects_special_purpose_ipv4() {
        // TEST-NET-1
        assert!(validate_relay_url("wss://192.0.2.1/").is_err());
        // TEST-NET-2
        assert!(validate_relay_url("wss://198.51.100.1/").is_err());
        // TEST-NET-3
        assert!(validate_relay_url("wss://203.0.113.1/").is_err());
        // Benchmarking
        assert!(validate_relay_url("wss://198.18.0.1/").is_err());
        assert!(validate_relay_url("wss://198.19.255.255/").is_err());
        // Reserved
        assert!(validate_relay_url("wss://240.0.0.1/").is_err());
        assert!(validate_relay_url("wss://255.255.255.255/").is_err());
    }

    #[test]
    fn rejects_ipv6_mapped_special_purpose() {
        assert!(validate_relay_url("wss://[::ffff:192.0.2.1]/").is_err());
        assert!(validate_relay_url("wss://[::ffff:198.51.100.1]/").is_err());
        assert!(validate_relay_url("wss://[::ffff:240.0.0.1]/").is_err());
    }

    #[test]
    fn is_internal_ip_blocks_private() {
        use std::net::IpAddr;
        assert!(is_internal_ip(&"127.0.0.1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"10.0.0.1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"192.168.1.1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"172.16.0.1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"169.254.1.1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"0.0.0.0".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"100.64.0.1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"240.0.0.1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"::1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"fc00::1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"fe80::1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"fec0::1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(
            &"::ffff:127.0.0.1".parse::<IpAddr>().unwrap()
        ));
    }

    #[test]
    fn is_internal_ip_allows_public() {
        use std::net::IpAddr;
        assert!(!is_internal_ip(&"8.8.8.8".parse::<IpAddr>().unwrap()));
        assert!(!is_internal_ip(&"1.1.1.1".parse::<IpAddr>().unwrap()));
        assert!(!is_internal_ip(&"2607:f8b0::1".parse::<IpAddr>().unwrap()));
    }

    #[test]
    fn allows_nearby_public_ranges() {
        assert!(validate_relay_url("wss://192.0.3.1/").is_ok());
        assert!(validate_relay_url("wss://198.51.101.1/").is_ok());
        assert!(validate_relay_url("wss://203.0.114.1/").is_ok());
        assert!(validate_relay_url("wss://198.17.0.1/").is_ok());
        assert!(validate_relay_url("wss://198.20.0.1/").is_ok());
    }

    #[test]
    fn rejects_ipv4_multicast() {
        assert!(validate_relay_url("wss://224.0.0.1/").is_err());
        assert!(validate_relay_url("wss://239.255.255.255/").is_err());
    }

    #[test]
    fn rejects_this_network_range() {
        assert!(validate_relay_url("wss://0.1.2.3/").is_err());
        assert!(validate_relay_url("wss://0.255.255.255/").is_err());
    }

    #[test]
    fn is_internal_ip_blocks_ipv4_compatible_v6() {
        use std::net::IpAddr;
        assert!(is_internal_ip(&"::7f00:1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"::a00:1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(&"::c0a8:101".parse::<IpAddr>().unwrap()));
    }

    #[test]
    fn is_internal_ip_blocks_multicast_v4() {
        use std::net::IpAddr;
        assert!(is_internal_ip(&"224.0.0.1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(
            &"239.255.255.255".parse::<IpAddr>().unwrap()
        ));
    }

    #[test]
    fn is_internal_ip_blocks_this_network() {
        use std::net::IpAddr;
        assert!(is_internal_ip(&"0.1.2.3".parse::<IpAddr>().unwrap()));
    }

    #[test]
    fn is_internal_ip_blocks_nat64_wkp() {
        use std::net::IpAddr;
        // 64:ff9b::a00:1 embeds 10.0.0.1 (private)
        assert!(is_internal_ip(&"64:ff9b::a00:1".parse::<IpAddr>().unwrap()));
        // 64:ff9b::7f00:1 embeds 127.0.0.1 (loopback)
        assert!(is_internal_ip(
            &"64:ff9b::7f00:1".parse::<IpAddr>().unwrap()
        ));
    }

    #[test]
    fn is_internal_ip_blocks_6to4() {
        use std::net::IpAddr;
        // 2002:7f00:0001::1 embeds 127.0.0.1
        assert!(is_internal_ip(
            &"2002:7f00:0001::1".parse::<IpAddr>().unwrap()
        ));
        // 2002:0a00:0001::1 embeds 10.0.0.1
        assert!(is_internal_ip(&"2002:a00:1::1".parse::<IpAddr>().unwrap()));
        // 2002:c0a8:0101::1 embeds 192.168.1.1
        assert!(is_internal_ip(
            &"2002:c0a8:101::1".parse::<IpAddr>().unwrap()
        ));
        // Public 6to4: 2002:0808:0808::1 embeds 8.8.8.8
        assert!(!is_internal_ip(
            &"2002:808:808::1".parse::<IpAddr>().unwrap()
        ));
    }

    #[test]
    fn is_internal_ip_blocks_teredo() {
        use std::net::IpAddr;
        // Teredo: 2001:0000:x:x:x:x:XXXX:XXXX where last 32 bits are XOR'd IPv4
        // XOR'd 127.0.0.1 = 0x80ff:fffe
        assert!(is_internal_ip(
            &"2001:0000:0000:0000:0000:0000:80ff:fffe"
                .parse::<IpAddr>()
                .unwrap()
        ));
        // XOR'd 10.0.0.1 = 0xf5ff:fffe
        assert!(is_internal_ip(
            &"2001:0000:0000:0000:0000:0000:f5ff:fffe"
                .parse::<IpAddr>()
                .unwrap()
        ));
        // XOR'd 8.8.8.8 = 0xf7f7:f7f7 (public, should NOT be internal)
        assert!(!is_internal_ip(
            &"2001:0000:0000:0000:0000:0000:f7f7:f7f7"
                .parse::<IpAddr>()
                .unwrap()
        ));
    }

    #[test]
    fn rejects_6to4_embedded_internal() {
        assert!(validate_relay_url("wss://[2002:7f00:1::1]/").is_err());
        assert!(validate_relay_url("wss://[2002:a00:1::1]/").is_err());
        assert!(validate_relay_url("wss://[2002:c0a8:101::1]/").is_err());
    }

    #[test]
    fn rejects_teredo_embedded_internal() {
        // Teredo embedding 127.0.0.1 (XOR'd)
        assert!(validate_relay_url("wss://[2001:0000::80ff:fffe]/").is_err());
        // Teredo embedding 10.0.0.1 (XOR'd)
        assert!(validate_relay_url("wss://[2001:0000::f5ff:fffe]/").is_err());
    }

    #[test]
    fn is_internal_ip_blocks_documentation_prefix() {
        use std::net::IpAddr;
        assert!(is_internal_ip(&"2001:db8::1".parse::<IpAddr>().unwrap()));
        assert!(is_internal_ip(
            &"2001:db8:ffff::1".parse::<IpAddr>().unwrap()
        ));
    }

    #[test]
    fn rejects_userinfo_in_url() {
        assert!(validate_relay_url("wss://user@relay.example.com/").is_err());
        assert!(validate_relay_url("wss://user:pass@relay.example.com/").is_err());
        assert!(validate_relay_url("wss://evil.com@relay.example.com/").is_err());
    }

    #[test]
    fn rejects_arpa_and_onion_tlds() {
        assert!(validate_relay_url("wss://host.arpa/").is_err());
        assert!(validate_relay_url("wss://10.in-addr.arpa/").is_err());
        assert!(validate_relay_url("wss://hidden.onion/").is_err());
    }

    #[test]
    fn rejects_mixed_case_trailing_dot() {
        assert!(validate_relay_url("wss://LocalHost./").is_err());
        assert!(validate_relay_url("wss://LOCALHOST./").is_err());
    }

    #[test]
    fn stored_bunker_permission_legacy_json_defaults_remember_flag_to_none() {
        // A row persisted before the flag existed omits `explicitly_remembered`;
        // it must deserialize to None so the restore path treats it as legacy and
        // falls back to inspecting the row's grants.
        let legacy = r#"{
            "pubkey_hex": "aa",
            "name": "app",
            "permissions": 3,
            "auto_approve_kinds": [1],
            "duration": "Forever",
            "connected_at": 100
        }"#;
        let bp: StoredBunkerPermission = serde_json::from_str(legacy).unwrap();
        assert_eq!(bp.explicitly_remembered, None);
        assert!(bp.timed_kind_grants.is_empty());

        // A current row round-trips the flag.
        let current = StoredBunkerPermission {
            explicitly_remembered: Some(true),
            ..bp
        };
        let json = serde_json::to_string(&current).unwrap();
        let back: StoredBunkerPermission = serde_json::from_str(&json).unwrap();
        assert_eq!(back.explicitly_remembered, Some(true));
    }
}