pylon-auth 0.3.20

Pylon — realtime backend as a single Rust binary. Schema, policies, server functions, live queries, auth — one process.
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
//! Sign-In With Ethereum (EIP-4361).
//!
//! Wallet-based passwordless auth — the user signs a structured
//! message in their wallet (MetaMask, WalletConnect, Coinbase
//! Wallet, etc.), pylon recovers the signer's Ethereum address,
//! and that address becomes the identity.
//!
//! Spec: <https://eips.ethereum.org/EIPS/eip-4361>
//!
//! Wire flow:
//!   1. Frontend asks `/api/auth/siwe/nonce?address=0x…` →
//!      pylon generates a random nonce, stashes it server-side
//!      keyed by address (5-min expiry, single-use).
//!   2. Frontend builds the EIP-4361 message including the nonce,
//!      `domain`, `uri`, `chain_id`, etc., and asks the wallet
//!      to `personal_sign` it.
//!   3. Frontend POSTs `/api/auth/siwe/verify` with
//!      `{ message, signature }`. Pylon recovers the signer
//!      address from the signature using secp256k1 + keccak256
//!      (the Ethereum signed-message scheme), validates the
//!      message fields (nonce match, domain match, expiry,
//!      not-before, chain_id), and mints a session keyed on
//!      `siwe:<lowercased-address>`.

use std::collections::HashMap;
use std::sync::Mutex;

/// Ethereum-signed-message recovery + EIP-4361 message validation.
///
/// pylon implements the recovery using `ring`'s low-level primitives
/// to avoid pulling in a dedicated secp256k1 crate. If the signature
/// verifier becomes a hot path, swap in `secp256k1` (the libsecp256k1
/// bindings) — currently it'd be O(1 sign-in per minute per user)
/// so the overhead is negligible.

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SiweMessage {
    /// `<scheme>://<host>[:<port>]` — must match the configured
    /// origin allowlist.
    pub domain: String,
    /// Lowercased EVM address (0x-prefixed, 42 chars).
    pub address: String,
    /// Optional human-readable statement — shown in the wallet UI.
    pub statement: Option<String>,
    pub uri: String,
    pub version: String,
    pub chain_id: u64,
    pub nonce: String,
    /// ISO-8601 timestamp.
    pub issued_at: String,
    pub expiration_time: Option<String>,
    pub not_before: Option<String>,
    pub request_id: Option<String>,
    pub resources: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SiweError {
    Malformed,
    NonceMismatch,
    NonceMissing,
    DomainMismatch,
    Expired,
    NotYetValid,
    BadSignature,
    AddressMismatch,
}

impl std::fmt::Display for SiweError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Malformed => "SIWE message malformed",
            Self::NonceMismatch => "nonce doesn't match issued challenge",
            Self::NonceMissing => "no challenge issued for this address",
            Self::DomainMismatch => "domain doesn't match expected origin",
            Self::Expired => "message expiration_time has passed",
            Self::NotYetValid => "not_before is in the future",
            Self::BadSignature => "signature did not recover to message address",
            Self::AddressMismatch => "address claimed in message ≠ recovered signer",
        })
    }
}

/// Per-address pending nonce (issued at /siwe/nonce, consumed at
/// /siwe/verify). Single-use, 5-min TTL.
pub struct NonceStore {
    nonces: Mutex<HashMap<String, (String, u64)>>, // addr → (nonce, expires_at)
}

impl Default for NonceStore {
    fn default() -> Self {
        Self {
            nonces: Mutex::new(HashMap::new()),
        }
    }
}

impl NonceStore {
    pub fn new() -> Self {
        Self::default()
    }

    /// Mint + stash a nonce for `address`. Overwrites any existing
    /// nonce for that address (reissue is fine — only one in-flight
    /// challenge per address).
    pub fn issue(&self, address: &str) -> String {
        use rand::RngCore;
        let mut bytes = [0u8; 16];
        rand::thread_rng().fill_bytes(&mut bytes);
        // EIP-4361 says nonce is `[A-Za-z0-9]{8,}`. Hex-encode our
        // random bytes (32 chars) — well within the allowed alphabet.
        let nonce: String = bytes
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect();
        let key = address.to_ascii_lowercase();
        let expires_at = now_secs() + 5 * 60;
        self.nonces
            .lock()
            .unwrap()
            .insert(key, (nonce.clone(), expires_at));
        nonce
    }

    /// Consume the stored nonce for `address` (single-use). Returns
    /// `None` for unknown OR expired entries — but DOESN'T remove an
    /// expired entry early (an attacker repeatedly posting expired
    /// nonces would otherwise burn the slot and DoS legitimate
    /// retries).
    pub fn take(&self, address: &str) -> Option<String> {
        let key = address.to_ascii_lowercase();
        let mut map = self.nonces.lock().unwrap();
        let (nonce, exp) = map.get(&key)?.clone();
        if exp <= now_secs() {
            return None;
        }
        map.remove(&key);
        Some(nonce)
    }
}

/// Parse the EIP-4361 plaintext message format. Apps that need the
/// full structured form should use this + `verify_signature` separately.
pub fn parse_message(text: &str) -> Result<SiweMessage, SiweError> {
    // Spec format:
    // <domain> wants you to sign in with your Ethereum account:
    // <address>
    //
    // [<statement>]
    //
    // URI: <uri>
    // Version: <version>
    // Chain ID: <chain_id>
    // Nonce: <nonce>
    // Issued At: <iso-8601>
    // [Expiration Time: <iso-8601>]
    // [Not Before: <iso-8601>]
    // [Request ID: <id>]
    // [Resources:
    // - <uri>
    // - <uri>]
    let mut lines = text.lines();
    let header = lines.next().ok_or(SiweError::Malformed)?;
    let domain = header
        .strip_suffix(" wants you to sign in with your Ethereum account:")
        .ok_or(SiweError::Malformed)?
        .to_string();
    let address = lines
        .next()
        .ok_or(SiweError::Malformed)?
        .trim()
        .to_string();
    if !address.starts_with("0x") || address.len() != 42 {
        return Err(SiweError::Malformed);
    }

    // Skip the blank line after the address; collect the statement
    // (which CAN span multiple lines per spec) until we hit URI:.
    let mut statement_parts: Vec<String> = Vec::new();
    let mut peeked: Option<&str> = None;
    let mut seen_blank = false;
    for l in lines.by_ref() {
        if l.is_empty() {
            seen_blank = true;
            continue;
        }
        if l.starts_with("URI:") {
            peeked = Some(l);
            break;
        }
        // Pre-URI non-blank lines are statement content. Re-introduce
        // the inter-line newlines so re-serialization matches the
        // wallet-signed bytes exactly.
        if !statement_parts.is_empty() {
            statement_parts.push("\n".into());
        }
        statement_parts.push(l.to_string());
    }
    let _ = seen_blank;
    let statement = if statement_parts.is_empty() {
        None
    } else {
        Some(statement_parts.concat())
    };
    // We may have already consumed the URI line into `peeked`.
    let mut uri: Option<String> = None;
    let mut version: Option<String> = None;
    let mut chain_id: Option<u64> = None;
    let mut nonce: Option<String> = None;
    let mut issued_at: Option<String> = None;
    let mut expiration_time: Option<String> = None;
    let mut not_before: Option<String> = None;
    let mut request_id: Option<String> = None;
    let mut resources = Vec::new();
    let mut in_resources = false;

    let process = |line: &str,
                       uri: &mut Option<String>,
                       version: &mut Option<String>,
                       chain_id: &mut Option<u64>,
                       nonce: &mut Option<String>,
                       issued_at: &mut Option<String>,
                       expiration_time: &mut Option<String>,
                       not_before: &mut Option<String>,
                       request_id: &mut Option<String>,
                       resources: &mut Vec<String>,
                       in_resources: &mut bool| {
        if let Some(v) = line.strip_prefix("URI:") {
            *uri = Some(v.trim().to_string());
            *in_resources = false;
        } else if let Some(v) = line.strip_prefix("Version:") {
            *version = Some(v.trim().to_string());
            *in_resources = false;
        } else if let Some(v) = line.strip_prefix("Chain ID:") {
            *chain_id = v.trim().parse().ok();
            *in_resources = false;
        } else if let Some(v) = line.strip_prefix("Nonce:") {
            *nonce = Some(v.trim().to_string());
            *in_resources = false;
        } else if let Some(v) = line.strip_prefix("Issued At:") {
            *issued_at = Some(v.trim().to_string());
            *in_resources = false;
        } else if let Some(v) = line.strip_prefix("Expiration Time:") {
            *expiration_time = Some(v.trim().to_string());
            *in_resources = false;
        } else if let Some(v) = line.strip_prefix("Not Before:") {
            *not_before = Some(v.trim().to_string());
            *in_resources = false;
        } else if let Some(v) = line.strip_prefix("Request ID:") {
            *request_id = Some(v.trim().to_string());
            *in_resources = false;
        } else if line.starts_with("Resources:") {
            *in_resources = true;
        } else if *in_resources {
            if let Some(v) = line.strip_prefix("- ") {
                resources.push(v.trim().to_string());
            }
        }
    };
    if let Some(line) = peeked {
        process(
            line,
            &mut uri,
            &mut version,
            &mut chain_id,
            &mut nonce,
            &mut issued_at,
            &mut expiration_time,
            &mut not_before,
            &mut request_id,
            &mut resources,
            &mut in_resources,
        );
    }
    for line in lines {
        process(
            line,
            &mut uri,
            &mut version,
            &mut chain_id,
            &mut nonce,
            &mut issued_at,
            &mut expiration_time,
            &mut not_before,
            &mut request_id,
            &mut resources,
            &mut in_resources,
        );
    }

    Ok(SiweMessage {
        domain,
        address,
        statement,
        uri: uri.ok_or(SiweError::Malformed)?,
        version: version.ok_or(SiweError::Malformed)?,
        chain_id: chain_id.ok_or(SiweError::Malformed)?,
        nonce: nonce.ok_or(SiweError::Malformed)?,
        issued_at: issued_at.ok_or(SiweError::Malformed)?,
        expiration_time,
        not_before,
        request_id,
        resources,
    })
}

/// Validate the non-cryptographic parts of a SIWE message: domain,
/// nonce, expiration, not-before. Use [`verify`] to also check the
/// signature.
pub fn validate_message(
    nonces: &NonceStore,
    message: &SiweMessage,
    expected_domain: &str,
) -> Result<(), SiweError> {
    if message.domain != expected_domain {
        return Err(SiweError::DomainMismatch);
    }
    let issued = nonces
        .take(&message.address)
        .ok_or(SiweError::NonceMissing)?;
    if issued != message.nonce {
        return Err(SiweError::NonceMismatch);
    }
    if let Some(exp) = &message.expiration_time {
        if iso_to_unix(exp).map(|t| t <= now_secs()).unwrap_or(false) {
            return Err(SiweError::Expired);
        }
    }
    if let Some(nb) = &message.not_before {
        if iso_to_unix(nb).map(|t| t > now_secs()).unwrap_or(false) {
            return Err(SiweError::NotYetValid);
        }
    }
    Ok(())
}

/// Validate the message + verify the signature, returning the
/// recovered lowercased Ethereum address on success.
///
/// Signature is the standard 65-byte (r||s||v) hex form wallets
/// produce, with `v ∈ {0, 1, 27, 28}` (both pre- and post-EIP-155
/// recovery ids). Recovery uses k256 ECDSA + Keccak-256 (Ethereum's
/// variant, not SHA-3) over the EIP-191 personal_sign envelope.
pub fn verify(
    nonces: &NonceStore,
    message: &SiweMessage,
    signature_hex: &str,
    expected_domain: &str,
) -> Result<String, SiweError> {
    validate_message(nonces, message, expected_domain)?;
    let recovered = recover_address(message, signature_hex)?;
    if !recovered.eq_ignore_ascii_case(&message.address) {
        return Err(SiweError::AddressMismatch);
    }
    Ok(recovered)
}

/// Recover the Ethereum address that signed `message`. Returns the
/// lowercase 0x-prefixed form. Standalone for callers that want to
/// compose their own validation pipeline.
pub fn recover_address(message: &SiweMessage, signature_hex: &str) -> Result<String, SiweError> {
    let signed_text = serialize_for_signing(message);
    // EIP-191 personal_sign envelope: "\x19Ethereum Signed Message:\n<len><msg>".
    let prefix = format!("\x19Ethereum Signed Message:\n{}", signed_text.len());
    let mut to_hash = Vec::with_capacity(prefix.len() + signed_text.len());
    to_hash.extend_from_slice(prefix.as_bytes());
    to_hash.extend_from_slice(signed_text.as_bytes());
    let digest = keccak256(&to_hash);

    let sig_bytes = decode_hex(signature_hex.trim_start_matches("0x"))
        .map_err(|_| SiweError::BadSignature)?;
    if sig_bytes.len() != 65 {
        return Err(SiweError::BadSignature);
    }
    // v: pre-EIP-155 = {27, 28}, post-EIP-155 = {0, 1}. Map to {0, 1}.
    let v = sig_bytes[64];
    let recovery_id = match v {
        0 | 27 => 0u8,
        1 | 28 => 1u8,
        _ => return Err(SiweError::BadSignature),
    };

    use k256::ecdsa::{RecoveryId, Signature, VerifyingKey};
    let sig = Signature::from_slice(&sig_bytes[..64]).map_err(|_| SiweError::BadSignature)?;
    let rec_id = RecoveryId::from_byte(recovery_id).ok_or(SiweError::BadSignature)?;
    let vk = VerifyingKey::recover_from_prehash(&digest, &sig, rec_id)
        .map_err(|_| SiweError::BadSignature)?;
    // Public key in uncompressed SEC1 (65 bytes: 0x04 || X || Y).
    // Ethereum address = last 20 bytes of keccak256(X||Y).
    let pubkey_point = vk.to_encoded_point(false);
    let pubkey_xy = &pubkey_point.as_bytes()[1..]; // strip 0x04 prefix
    let h = keccak256(pubkey_xy);
    let mut addr = [0u8; 20];
    addr.copy_from_slice(&h[12..]);
    Ok(format!("0x{}", bytes_to_hex(&addr)))
}

/// Keccak-256 (Ethereum's variant — NOT NIST SHA-3). The two have
/// different padding bytes (0x01 vs 0x06).
fn keccak256(input: &[u8]) -> [u8; 32] {
    use sha3::{Digest, Keccak256};
    let mut hasher = Keccak256::new();
    hasher.update(input);
    let out = hasher.finalize();
    let mut buf = [0u8; 32];
    buf.copy_from_slice(&out);
    buf
}

fn decode_hex(s: &str) -> Result<Vec<u8>, ()> {
    if s.len() % 2 != 0 {
        return Err(());
    }
    let mut out = Vec::with_capacity(s.len() / 2);
    for chunk in s.as_bytes().chunks(2) {
        let hi = hex_digit(chunk[0])?;
        let lo = hex_digit(chunk[1])?;
        out.push((hi << 4) | lo);
    }
    Ok(out)
}

fn hex_digit(b: u8) -> Result<u8, ()> {
    match b {
        b'0'..=b'9' => Ok(b - b'0'),
        b'a'..=b'f' => Ok(b - b'a' + 10),
        b'A'..=b'F' => Ok(b - b'A' + 10),
        _ => Err(()),
    }
}

fn bytes_to_hex(bytes: &[u8]) -> String {
    use std::fmt::Write;
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        let _ = write!(s, "{b:02x}");
    }
    s
}

/// Serialize a SIWE message back into its canonical wire form for
/// signing. MUST be byte-identical to what the wallet hashed.
pub fn serialize_for_signing(m: &SiweMessage) -> String {
    let mut out = String::new();
    out.push_str(&m.domain);
    out.push_str(" wants you to sign in with your Ethereum account:\n");
    out.push_str(&m.address);
    out.push('\n');
    if let Some(s) = &m.statement {
        out.push('\n');
        out.push_str(s);
        out.push('\n');
    }
    out.push('\n');
    out.push_str(&format!("URI: {}\n", m.uri));
    out.push_str(&format!("Version: {}\n", m.version));
    out.push_str(&format!("Chain ID: {}\n", m.chain_id));
    out.push_str(&format!("Nonce: {}\n", m.nonce));
    out.push_str(&format!("Issued At: {}", m.issued_at));
    if let Some(v) = &m.expiration_time {
        out.push_str(&format!("\nExpiration Time: {v}"));
    }
    if let Some(v) = &m.not_before {
        out.push_str(&format!("\nNot Before: {v}"));
    }
    if let Some(v) = &m.request_id {
        out.push_str(&format!("\nRequest ID: {v}"));
    }
    if !m.resources.is_empty() {
        out.push_str("\nResources:");
        for r in &m.resources {
            out.push_str("\n- ");
            out.push_str(r);
        }
    }
    out
}

fn iso_to_unix(iso: &str) -> Option<u64> {
    // Minimal RFC 3339 parser: YYYY-MM-DDTHH:MM:SSZ. Anything fancier
    // (timezone offsets, fractional seconds) we punt to chrono — but
    // pylon's auth crate already pulls in chrono via the workspace.
    chrono::DateTime::parse_from_rfc3339(iso)
        .ok()
        .map(|dt| dt.timestamp() as u64)
}

fn now_secs() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

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

    #[test]
    fn nonce_round_trip() {
        let store = NonceStore::new();
        let n = store.issue("0xABC");
        assert_eq!(store.take("0xabc").as_deref(), Some(n.as_str()));
        // Single-use.
        assert!(store.take("0xabc").is_none());
    }

    #[test]
    fn parse_full_message() {
        let raw = "example.com wants you to sign in with your Ethereum account:\n\
                   0x1111222233334444555566667777888899990000\n\
                   \n\
                   I accept the ToS\n\
                   \n\
                   URI: https://example.com\n\
                   Version: 1\n\
                   Chain ID: 1\n\
                   Nonce: abc123\n\
                   Issued At: 2026-01-01T00:00:00Z";
        let m = parse_message(raw).expect("parse");
        assert_eq!(m.domain, "example.com");
        assert_eq!(m.address, "0x1111222233334444555566667777888899990000");
        assert_eq!(m.statement.as_deref(), Some("I accept the ToS"));
        assert_eq!(m.uri, "https://example.com");
        assert_eq!(m.chain_id, 1);
        assert_eq!(m.nonce, "abc123");
    }

    #[test]
    fn parse_message_without_statement() {
        let raw = "x.com wants you to sign in with your Ethereum account:\n\
                   0x1111222233334444555566667777888899990000\n\
                   \n\
                   URI: https://x.com\n\
                   Version: 1\n\
                   Chain ID: 1\n\
                   Nonce: deadbeef\n\
                   Issued At: 2026-01-01T00:00:00Z";
        let m = parse_message(raw).expect("parse");
        assert!(m.statement.is_none());
        assert_eq!(m.nonce, "deadbeef");
    }

    #[test]
    fn parse_rejects_bad_address_length() {
        let raw = "x.com wants you to sign in with your Ethereum account:\n\
                   0xABC\n\
                   \n\
                   URI: x\nVersion: 1\nChain ID: 1\nNonce: n\nIssued At: t";
        assert!(matches!(parse_message(raw), Err(SiweError::Malformed)));
    }

    #[test]
    fn validate_rejects_domain_mismatch() {
        let store = NonceStore::new();
        store.issue("0x1111222233334444555566667777888899990000");
        let m = SiweMessage {
            domain: "evil.com".into(),
            address: "0x1111222233334444555566667777888899990000".into(),
            statement: None,
            uri: "https://evil.com".into(),
            version: "1".into(),
            chain_id: 1,
            nonce: "x".into(),
            issued_at: "2026-01-01T00:00:00Z".into(),
            expiration_time: None,
            not_before: None,
            request_id: None,
            resources: vec![],
        };
        let err = validate_message(&store, &m, "good.com").unwrap_err();
        assert_eq!(err, SiweError::DomainMismatch);
    }

    #[test]
    fn validate_rejects_nonce_mismatch() {
        let store = NonceStore::new();
        store.issue("0x1111222233334444555566667777888899990000");
        let m = SiweMessage {
            domain: "good.com".into(),
            address: "0x1111222233334444555566667777888899990000".into(),
            statement: None,
            uri: "https://good.com".into(),
            version: "1".into(),
            chain_id: 1,
            nonce: "wrong".into(),
            issued_at: "2026-01-01T00:00:00Z".into(),
            expiration_time: None,
            not_before: None,
            request_id: None,
            resources: vec![],
        };
        let err = validate_message(&store, &m, "good.com").unwrap_err();
        assert_eq!(err, SiweError::NonceMismatch);
    }

    /// Codex-flagged P0-7: nonce-bombing. Posting an EXPIRED nonce
    /// must NOT consume the slot. Otherwise an attacker who can
    /// observe the (address, nonce) handshake could repeatedly
    /// invalidate a target's pending nonce by posting any expired
    /// version of it.
    #[test]
    fn expired_take_does_not_remove_slot() {
        let store = NonceStore::new();
        // Inject an expired entry directly.
        store
            .nonces
            .lock()
            .unwrap()
            .insert("0xabc".into(), ("nonce-x".into(), 1));
        // First take — sees expired, returns None, MUST keep the slot.
        assert!(store.take("0xabc").is_none());
        // Slot still present (the test would also trip if we did remove it).
        assert!(store.nonces.lock().unwrap().contains_key("0xabc"));
    }

    /// End-to-end with REAL crypto: mint a key, sign a SIWE
    /// message, recover the address, verify it matches the
    /// signing key's address. Locks in the EIP-191 envelope +
    /// keccak256 + ECDSA-recover wiring.
    #[test]
    fn verify_real_signature_round_trip() {
        use k256::ecdsa::{signature::hazmat::PrehashSigner, RecoveryId, Signature, SigningKey};
        use sha3::{Digest, Keccak256};

        // 1. Random signing key + derived Ethereum address.
        let mut rng_bytes = [0u8; 32];
        use rand::RngCore;
        rand::thread_rng().fill_bytes(&mut rng_bytes);
        let signing_key = SigningKey::from_slice(&rng_bytes).expect("valid scalar");
        let verifying = signing_key.verifying_key();
        let pk_point = verifying.to_encoded_point(false);
        let pk_xy = &pk_point.as_bytes()[1..];
        let mut h = Keccak256::new();
        h.update(pk_xy);
        let pk_hash = h.finalize();
        let address = format!("0x{}", bytes_to_hex(&pk_hash[12..]));

        // 2. Build + issue a SIWE message for that address.
        let store = NonceStore::new();
        let nonce = store.issue(&address);
        let m = SiweMessage {
            domain: "example.com".into(),
            address: address.clone(),
            statement: Some("Sign in to Example".into()),
            uri: "https://example.com".into(),
            version: "1".into(),
            chain_id: 1,
            nonce,
            issued_at: "2026-01-01T00:00:00Z".into(),
            expiration_time: None,
            not_before: None,
            request_id: None,
            resources: vec![],
        };

        // 3. Sign the EIP-191 personal_sign envelope.
        let signed_text = serialize_for_signing(&m);
        let envelope = format!("\x19Ethereum Signed Message:\n{}{}", signed_text.len(), signed_text);
        let mut h = Keccak256::new();
        h.update(envelope.as_bytes());
        let digest = h.finalize();
        let (sig, rec_id): (Signature, RecoveryId) =
            signing_key.sign_prehash(&digest).expect("sign");
        let mut sig_bytes = sig.to_bytes().to_vec();
        sig_bytes.push(rec_id.to_byte() + 27); // pre-EIP-155 v
        let sig_hex = format!("0x{}", bytes_to_hex(&sig_bytes));

        // 4. Verify recovers the same address.
        let recovered =
            verify(&store, &m, &sig_hex, "example.com").expect("real-sig verify");
        assert_eq!(recovered, address.to_ascii_lowercase());
    }

    /// Multi-line statements per spec are real (any printable
    /// character + LF). The serializer must round-trip them.
    #[test]
    fn parse_handles_multiline_statement() {
        let raw = "x.com wants you to sign in with your Ethereum account:\n\
                   0x1111222233334444555566667777888899990000\n\
                   \n\
                   line one\n\
                   line two\n\
                   \n\
                   URI: https://x.com\n\
                   Version: 1\n\
                   Chain ID: 1\n\
                   Nonce: n\n\
                   Issued At: 2026-01-01T00:00:00Z";
        let m = parse_message(raw).expect("parse");
        assert_eq!(m.statement.as_deref(), Some("line one\nline two"));
    }
}