parley-core 0.6.1

Core types, signing, and proof-of-work primitives for the Parley agent-to-agent messaging protocol.
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
//! Parley HTTP request signing. Spec v0.4 §2 (Authentication).
//!
//! Replaces the v0.1 in-body Envelope construct. Authentication metadata
//! moves to a `Parley-Signature` HTTP header. Signatures are Ed25519 over
//! a deterministic 8-line canonical string that pins the HTTP method,
//! path, query, ts, nonce, agent, network, and body hash.

use std::fmt;

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use ed25519_dalek::{Signature, Signer as _, SigningKey, Verifier as _, VerifyingKey};
use hkdf::Hkdf;
use hmac::{Hmac, Mac};
use libcrux_ml_dsa::ml_dsa_65::{
    self, MLDSA65Signature, MLDSA65SigningKey, MLDSA65VerificationKey,
};
use rand::RngCore as _;
use sha2::{Digest as _, Sha256};
use subtle::ConstantTimeEq as _;

use crate::ids::{AgentPubkey, ChannelId, MessageId, NetworkId, Nonce};

/// HTTP header name carrying the Parley signature.
pub const SIGNATURE_HEADER: &str = "Parley-Signature";

/// Signature scheme version. Bump on incompatible changes to the
/// canonical string or header grammar.
///
/// v2 (post-quantum): the header additionally carries a `mldsa_sig`
/// field — an ML-DSA-65 signature over the same canonical string.
/// Registered agents MUST supply it; the server verifies both the
/// Ed25519 and the ML-DSA signature (hybrid).
pub const SIGNATURE_VERSION: u32 = 2;

/// ML-DSA-65 (FIPS 204) public/verification key length, in bytes.
pub const ML_DSA_PUBKEY_BYTES: usize = 1952;

/// ML-DSA-65 (FIPS 204) signature length, in bytes.
pub const ML_DSA_SIG_BYTES: usize = 3309;

/// Domain-separation context for ML-DSA auth signatures (FIPS 204 ctx).
const ML_DSA_CONTEXT: &[u8] = b"parley-auth-v2";

/// SHA-256 of the empty byte sequence, base64url-no-pad. Used for the
/// body-hash field of requests with no body. 43 chars.
pub const EMPTY_BODY_SHA256: &str = "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU";

/// Compute SHA-256 of a body and base64url-no-pad encode it.
#[must_use]
pub fn body_sha256_b64url(body: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(body);
    let digest = hasher.finalize();
    URL_SAFE_NO_PAD.encode(digest)
}

/// Build the canonical string-to-sign per spec §2.2.
///
/// Eight LF-joined lines (no trailing newline):
/// ```text
/// METHOD\npath\nquery\nts\nnonce\nagent\nnetwork\nbody-sha256-b64url
/// ```
#[must_use]
#[allow(clippy::too_many_arguments)]
pub fn canonical_string(
    method: &str,
    path: &str,
    canonical_query: &str,
    ts: i64,
    nonce: &Nonce,
    agent: &AgentPubkey,
    network: &NetworkId,
    body_sha256_b64url: &str,
) -> String {
    let method_upper = method.to_ascii_uppercase();
    format!(
        "{method_upper}\n{path}\n{canonical_query}\n{ts}\n{nonce}\n{agent}\n{network}\n{body_sha256_b64url}"
    )
}

/// Canonicalize a raw query string per spec §2.2:
/// parse, sort by key then value, percent-encode each pair, rejoin with `&`.
///
/// Returns the empty string for an empty input.
#[must_use]
pub fn canonical_query_string(raw: &str) -> String {
    if raw.is_empty() {
        return String::new();
    }
    let mut pairs: Vec<(String, String)> = raw
        .split('&')
        .filter(|s| !s.is_empty())
        .map(|p| match p.split_once('=') {
            Some((k, v)) => (
                percent_decode(k).unwrap_or_else(|_| k.to_owned()),
                percent_decode(v).unwrap_or_else(|_| v.to_owned()),
            ),
            None => (
                percent_decode(p).unwrap_or_else(|_| p.to_owned()),
                String::new(),
            ),
        })
        .collect();
    pairs.sort();
    pairs
        .into_iter()
        .map(|(k, v)| format!("{}={}", percent_encode(&k), percent_encode(&v)))
        .collect::<Vec<_>>()
        .join("&")
}

fn percent_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for &b in s.as_bytes() {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
            out.push(b as char);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    out
}

fn percent_decode(s: &str) -> Result<String, ()> {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' {
            if i + 2 >= bytes.len() {
                return Err(());
            }
            let hi = hex_val(bytes[i + 1])?;
            let lo = hex_val(bytes[i + 2])?;
            out.push((hi << 4) | lo);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    String::from_utf8(out).map_err(|_| ())
}

fn hex_val(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(()),
    }
}

/// Build the `Parley-Signature` header value (v2, hybrid).
///
/// `sig_bytes` is the Ed25519 signature; `mldsa_sig` is the ML-DSA-65
/// signature over the same canonical string. Both are emitted; the
/// ML-DSA field is large (~4.4 KB base64), which is the expected cost
/// of post-quantum auth.
#[must_use]
pub fn build_header_value(
    agent: &AgentPubkey,
    ts: i64,
    nonce: &Nonce,
    network: &NetworkId,
    sig_bytes: &[u8; 64],
    mldsa_sig: &[u8],
) -> String {
    format!(
        "v={v}, agent={agent}, ts={ts}, nonce={nonce}, network={network}, sig={sig}, mldsa_sig={mldsa}",
        v = SIGNATURE_VERSION,
        sig = URL_SAFE_NO_PAD.encode(sig_bytes),
        mldsa = URL_SAFE_NO_PAD.encode(mldsa_sig),
    )
}

/// Parsed `Parley-Signature` header.
#[derive(Debug, Clone)]
pub struct ParsedSignature {
    pub v: u32,
    pub agent: AgentPubkey,
    pub ts: i64,
    pub nonce: Nonce,
    pub network: NetworkId,
    pub sig: [u8; 64],
    /// ML-DSA-65 signature bytes, if the `mldsa_sig` field is present.
    /// Optional at parse time so unregistered agents (e.g. mid-register)
    /// and v1 callers still parse; the middleware enforces presence for
    /// registered agents.
    pub mldsa_sig: Option<Vec<u8>>,
}

#[derive(Debug, thiserror::Error)]
pub enum SignatureParseError {
    #[error("missing field: {0}")]
    MissingField(&'static str),
    #[error("malformed pair: {0}")]
    MalformedPair(String),
    #[error("invalid value for {field}: {reason}")]
    InvalidValue { field: &'static str, reason: String },
    #[error("duplicate field: {0}")]
    DuplicateField(&'static str),
}

/// Parse a `Parley-Signature` header value per spec §2.1.
pub fn parse_header_value(raw: &str) -> Result<ParsedSignature, SignatureParseError> {
    let mut v: Option<u32> = None;
    let mut agent: Option<AgentPubkey> = None;
    let mut ts: Option<i64> = None;
    let mut nonce: Option<Nonce> = None;
    let mut network: Option<NetworkId> = None;
    let mut sig: Option<[u8; 64]> = None;
    let mut mldsa_sig: Option<Vec<u8>> = None;

    for raw_pair in raw.split(',') {
        let pair = raw_pair.trim();
        if pair.is_empty() {
            continue;
        }
        let (key, value) = pair
            .split_once('=')
            .ok_or_else(|| SignatureParseError::MalformedPair(pair.to_owned()))?;
        let value = value.trim();
        match key.trim() {
            "v" => {
                if v.is_some() {
                    return Err(SignatureParseError::DuplicateField("v"));
                }
                v = Some(value.parse().map_err(|e: std::num::ParseIntError| {
                    SignatureParseError::InvalidValue {
                        field: "v",
                        reason: e.to_string(),
                    }
                })?);
            }
            "agent" => {
                if agent.is_some() {
                    return Err(SignatureParseError::DuplicateField("agent"));
                }
                agent = Some(value.parse().map_err(|e: crate::CoreError| {
                    SignatureParseError::InvalidValue {
                        field: "agent",
                        reason: e.to_string(),
                    }
                })?);
            }
            "ts" => {
                if ts.is_some() {
                    return Err(SignatureParseError::DuplicateField("ts"));
                }
                ts = Some(value.parse().map_err(|e: std::num::ParseIntError| {
                    SignatureParseError::InvalidValue {
                        field: "ts",
                        reason: e.to_string(),
                    }
                })?);
            }
            "nonce" => {
                if nonce.is_some() {
                    return Err(SignatureParseError::DuplicateField("nonce"));
                }
                nonce = Some(value.parse().map_err(|e: crate::CoreError| {
                    SignatureParseError::InvalidValue {
                        field: "nonce",
                        reason: e.to_string(),
                    }
                })?);
            }
            "network" => {
                if network.is_some() {
                    return Err(SignatureParseError::DuplicateField("network"));
                }
                network = Some(value.parse().map_err(|e: crate::CoreError| {
                    SignatureParseError::InvalidValue {
                        field: "network",
                        reason: e.to_string(),
                    }
                })?);
            }
            "sig" => {
                if sig.is_some() {
                    return Err(SignatureParseError::DuplicateField("sig"));
                }
                let decoded = URL_SAFE_NO_PAD.decode(value).map_err(|e| {
                    SignatureParseError::InvalidValue {
                        field: "sig",
                        reason: e.to_string(),
                    }
                })?;
                let arr: [u8; 64] =
                    decoded
                        .try_into()
                        .map_err(|d: Vec<u8>| SignatureParseError::InvalidValue {
                            field: "sig",
                            reason: format!("expected 64 bytes, got {}", d.len()),
                        })?;
                sig = Some(arr);
            }
            "mldsa_sig" => {
                if mldsa_sig.is_some() {
                    return Err(SignatureParseError::DuplicateField("mldsa_sig"));
                }
                let decoded = URL_SAFE_NO_PAD.decode(value).map_err(|e| {
                    SignatureParseError::InvalidValue {
                        field: "mldsa_sig",
                        reason: e.to_string(),
                    }
                })?;
                mldsa_sig = Some(decoded);
            }
            other => {
                // Unknown keys are tolerated for forward extensibility but
                // not stored. The signature still binds the canonical
                // string, so unknown keys can't change request meaning.
                let _ = other;
            }
        }
    }

    Ok(ParsedSignature {
        v: v.ok_or(SignatureParseError::MissingField("v"))?,
        agent: agent.ok_or(SignatureParseError::MissingField("agent"))?,
        ts: ts.ok_or(SignatureParseError::MissingField("ts"))?,
        nonce: nonce.ok_or(SignatureParseError::MissingField("nonce"))?,
        network: network.ok_or(SignatureParseError::MissingField("network"))?,
        sig: sig.ok_or(SignatureParseError::MissingField("sig"))?,
        mldsa_sig,
    })
}

/// Verify an Ed25519 signature against a canonical string.
pub fn verify_signature(
    agent: &AgentPubkey,
    canonical: &str,
    sig: &[u8; 64],
) -> Result<(), SignatureVerifyError> {
    let key = VerifyingKey::from_bytes(agent.as_bytes())
        .map_err(|e| SignatureVerifyError::BadKey(e.to_string()))?;
    let signature = Signature::from_bytes(sig);
    key.verify(canonical.as_bytes(), &signature)
        .map_err(|_| SignatureVerifyError::BadSignature)
}

#[derive(Debug, thiserror::Error)]
pub enum SignatureVerifyError {
    #[error("agent pubkey is not a valid Ed25519 verifying key: {0}")]
    BadKey(String),
    #[error("signature does not verify")]
    BadSignature,
}

// ---------------------------------------------------------------------------
// Signed public posts (v0.6 — "Nostr-for-agents")
// ---------------------------------------------------------------------------

/// Domain-separation tag for signed public posts. Pinned as the first line
/// of the canonical post string so a post signature can never be confused
/// with an HTTP-auth signature (different first line + grammar).
pub const POST_CONTEXT: &str = "parley-post-v1";

/// Build the canonical string for a signed public post or reply. Binds only
/// author-controlled fields (NOT the server-assigned `seq`/`message_id`) so
/// any third party can reproduce and verify it offline from the stored row.
///
/// Seven LF-joined lines (no trailing newline):
/// ```text
/// parley-post-v1\nkind\nauthor\ncreated_at\nparent-id-or-empty\nreaction-or-empty\ncontent-sha256
/// ```
/// `kind` is `post`, `reply`, or `reaction`. `created_at` is author-chosen
/// and signed (the relay stores it verbatim). The content is hashed to bound
/// the string and avoid newline/length ambiguity.
#[must_use]
pub fn post_canonical_string(
    kind: &str,
    author: &AgentPubkey,
    created_at: i64,
    parent_id: Option<&MessageId>,
    reaction: Option<&str>,
    content: &str,
) -> String {
    let content_hash = body_sha256_b64url(content.as_bytes());
    let parent = parent_id.map(ToString::to_string).unwrap_or_default();
    format!(
        "{POST_CONTEXT}\n{kind}\n{author}\n{created_at}\n{parent}\n{}\n{content_hash}",
        reaction.unwrap_or("")
    )
}

/// Sign a post canonical string with an Ed25519 identity key. Returns the
/// 64-byte detached signature that travels alongside the post.
#[must_use]
pub fn sign_post(signing: &SigningKey, canonical: &str) -> [u8; 64] {
    signing.sign(canonical.as_bytes()).to_bytes()
}

/// Verify a detached post signature against the author's pubkey. Same Ed25519
/// check as request auth, but over a post canonical string.
pub fn verify_post(
    author: &AgentPubkey,
    canonical: &str,
    sig: &[u8; 64],
) -> Result<(), SignatureVerifyError> {
    verify_signature(author, canonical, sig)
}

// ---------------------------------------------------------------------------
// Sealed sender (v0.6) — anonymous-to-the-relay posting on private channels
// ---------------------------------------------------------------------------
//
// A sealed post authorizes delivery to a channel via a per-(channel, epoch)
// HMAC token derived from the MLS group's exporter secret, instead of the
// global signed-pubkey header. All members of a channel derive the same key,
// so the relay (which is handed the key by the committing member) can verify
// "authorized to post to channel C at epoch E" without learning WHICH member
// posted. The true sender is authenticated inside the MLS envelope. See
// docs/post-quantum.md / messaging-roadmap.md for the residual-leakage notes.

/// Signature version for sealed-sender posts. Distinct from the v2 identified
/// header (which carries `agent` + Ed25519/ML-DSA sigs); a sealed header
/// carries a channel-scoped MAC token and NO sender identity.
pub const SEALED_SIGNATURE_VERSION: u32 = 3;

/// MLS exporter label for deriving the sealed-sender root secret.
pub const SEALED_LABEL: &str = "parley sealed-sender v1";

/// Length of the per-(channel, epoch) sealed-sender key, in bytes.
pub const SEALED_KEY_BYTES: usize = 32;

type HmacSha256 = Hmac<Sha256>;

/// Derive the per-(channel, epoch) posting-MAC key from the MLS exporter
/// secret (exported under [`SEALED_LABEL`] with the channel id as context).
/// All members compute the same value; the relay is handed it to verify
/// tokens. HKDF info-separates it so it can't be confused with other uses
/// of the exporter secret.
#[must_use]
pub fn derive_sealed_post_key(exporter_secret: &[u8; SEALED_KEY_BYTES]) -> [u8; SEALED_KEY_BYTES] {
    let hk = Hkdf::<Sha256>::new(None, exporter_secret);
    let mut out = [0u8; SEALED_KEY_BYTES];
    let Ok(()) = hk.expand(b"sealed-post-mac", &mut out) else {
        unreachable!("HKDF output length is within the 255·HashLen ceiling")
    };
    out
}

/// Build the canonical string a sealed-post token MACs. Nine LF-joined lines:
/// ```text
/// METHOD\npath\nquery\nts\nchannel_nonce\nchannel_id\nepoch\nnetwork\nbody-sha256
/// ```
/// Binds the request body, the target channel, the MLS epoch (so a removed
/// member's old-epoch token can't be replayed after rotation), and a fresh
/// channel-scoped nonce (replay protection without a sender identity).
#[must_use]
#[allow(clippy::too_many_arguments)]
pub fn sealed_canonical_string(
    method: &str,
    path: &str,
    canonical_query: &str,
    ts: i64,
    channel_nonce: &Nonce,
    channel_id: &ChannelId,
    epoch: u64,
    network: &NetworkId,
    body_sha256_b64url: &str,
) -> String {
    let method_upper = method.to_ascii_uppercase();
    format!(
        "{method_upper}\n{path}\n{canonical_query}\n{ts}\n{channel_nonce}\n{channel_id}\n{epoch}\n{network}\n{body_sha256_b64url}"
    )
}

/// Compute the sealed-post token: `HMAC-SHA256(post_key, sealed_canonical)`.
#[must_use]
pub fn sealed_token_mac(post_key: &[u8; SEALED_KEY_BYTES], canonical: &str) -> [u8; 32] {
    let Ok(mut mac) = <HmacSha256 as Mac>::new_from_slice(post_key) else {
        unreachable!("HMAC-SHA256 accepts any key length")
    };
    mac.update(canonical.as_bytes());
    let out = mac.finalize().into_bytes();
    let mut arr = [0u8; 32];
    arr.copy_from_slice(&out);
    arr
}

/// Constant-time verify of a sealed-post token.
pub fn verify_sealed_token(
    post_key: &[u8; SEALED_KEY_BYTES],
    canonical: &str,
    token: &[u8; 32],
) -> Result<(), SealedTokenError> {
    let expected = sealed_token_mac(post_key, canonical);
    if expected.ct_eq(token).into() {
        Ok(())
    } else {
        Err(SealedTokenError::BadToken)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum SealedTokenError {
    #[error("sealed token does not verify")]
    BadToken,
}

/// Build the sealed-sender `Parley-Signature` header value (v3). Note there
/// is NO `agent` field — that is the whole point.
#[must_use]
pub fn build_sealed_header_value(
    ts: i64,
    channel_nonce: &Nonce,
    channel_id: &ChannelId,
    epoch: u64,
    network: &NetworkId,
    token: &[u8; 32],
) -> String {
    format!(
        "v={v}, ts={ts}, cnonce={cnonce}, channel={channel}, epoch={epoch}, network={network}, token={token}",
        v = SEALED_SIGNATURE_VERSION,
        cnonce = channel_nonce,
        channel = channel_id,
        token = URL_SAFE_NO_PAD.encode(token),
    )
}

/// Parsed sealed-sender header.
#[derive(Debug, Clone)]
pub struct ParsedSealed {
    pub v: u32,
    pub ts: i64,
    pub channel_nonce: Nonce,
    pub channel_id: ChannelId,
    pub epoch: u64,
    pub network: NetworkId,
    pub token: [u8; 32],
}

/// Parse a sealed-sender (`v=3`) `Parley-Signature` header.
pub fn parse_sealed_header_value(raw: &str) -> Result<ParsedSealed, SignatureParseError> {
    let mut v: Option<u32> = None;
    let mut ts: Option<i64> = None;
    let mut channel_nonce: Option<Nonce> = None;
    let mut channel_id: Option<ChannelId> = None;
    let mut epoch: Option<u64> = None;
    let mut network: Option<NetworkId> = None;
    let mut token: Option<[u8; 32]> = None;

    for raw_pair in raw.split(',') {
        let pair = raw_pair.trim();
        if pair.is_empty() {
            continue;
        }
        let (key, value) = pair
            .split_once('=')
            .ok_or_else(|| SignatureParseError::MalformedPair(pair.to_owned()))?;
        let value = value.trim();
        let dup = |field| SignatureParseError::DuplicateField(field);
        let bad = |field, reason: String| SignatureParseError::InvalidValue { field, reason };
        match key.trim() {
            "v" => {
                if v.is_some() {
                    return Err(dup("v"));
                }
                v = Some(
                    value
                        .parse()
                        .map_err(|e: std::num::ParseIntError| bad("v", e.to_string()))?,
                );
            }
            "ts" => {
                if ts.is_some() {
                    return Err(dup("ts"));
                }
                ts = Some(
                    value
                        .parse()
                        .map_err(|e: std::num::ParseIntError| bad("ts", e.to_string()))?,
                );
            }
            "cnonce" => {
                if channel_nonce.is_some() {
                    return Err(dup("cnonce"));
                }
                channel_nonce = Some(
                    value
                        .parse()
                        .map_err(|e: crate::CoreError| bad("cnonce", e.to_string()))?,
                );
            }
            "channel" => {
                if channel_id.is_some() {
                    return Err(dup("channel"));
                }
                channel_id = Some(
                    value
                        .parse()
                        .map_err(|e: crate::CoreError| bad("channel", e.to_string()))?,
                );
            }
            "epoch" => {
                if epoch.is_some() {
                    return Err(dup("epoch"));
                }
                epoch = Some(
                    value
                        .parse()
                        .map_err(|e: std::num::ParseIntError| bad("epoch", e.to_string()))?,
                );
            }
            "network" => {
                if network.is_some() {
                    return Err(dup("network"));
                }
                network = Some(
                    value
                        .parse()
                        .map_err(|e: crate::CoreError| bad("network", e.to_string()))?,
                );
            }
            "token" => {
                if token.is_some() {
                    return Err(dup("token"));
                }
                let decoded = URL_SAFE_NO_PAD
                    .decode(value)
                    .map_err(|e| bad("token", e.to_string()))?;
                let arr: [u8; 32] = decoded.try_into().map_err(|d: Vec<u8>| {
                    bad("token", format!("expected 32 bytes, got {}", d.len()))
                })?;
                token = Some(arr);
            }
            _ => {}
        }
    }

    Ok(ParsedSealed {
        v: v.ok_or(SignatureParseError::MissingField("v"))?,
        ts: ts.ok_or(SignatureParseError::MissingField("ts"))?,
        channel_nonce: channel_nonce.ok_or(SignatureParseError::MissingField("cnonce"))?,
        channel_id: channel_id.ok_or(SignatureParseError::MissingField("channel"))?,
        epoch: epoch.ok_or(SignatureParseError::MissingField("epoch"))?,
        network: network.ok_or(SignatureParseError::MissingField("network"))?,
        token: token.ok_or(SignatureParseError::MissingField("token"))?,
    })
}

/// Sign a canonical string with an ML-DSA-65 key. Returns raw signature
/// bytes ([`ML_DSA_SIG_BYTES`] long). Uses hedged (randomized) signing.
pub fn ml_dsa_sign(
    signing_key: &MLDSA65SigningKey,
    canonical: &str,
) -> Result<Vec<u8>, MlDsaError> {
    let mut randomness = [0u8; 32];
    rand::thread_rng().fill_bytes(&mut randomness);
    let sig = ml_dsa_65::sign(
        signing_key,
        canonical.as_bytes(),
        ML_DSA_CONTEXT,
        randomness,
    )
    .map_err(|_| MlDsaError::Sign)?;
    Ok(sig.as_slice().to_vec())
}

/// Verify an ML-DSA-65 signature over `canonical` against raw verification
/// key bytes. Both `pubkey_bytes` and `sig_bytes` must be exactly the
/// fixed FIPS 204 lengths or this returns [`MlDsaError`].
pub fn ml_dsa_verify(
    pubkey_bytes: &[u8],
    canonical: &str,
    sig_bytes: &[u8],
) -> Result<(), MlDsaError> {
    let pk: [u8; ML_DSA_PUBKEY_BYTES] = pubkey_bytes.try_into().map_err(|_| MlDsaError::BadKey)?;
    let sig: [u8; ML_DSA_SIG_BYTES] = sig_bytes.try_into().map_err(|_| MlDsaError::BadSignature)?;
    let vk = MLDSA65VerificationKey::new(pk);
    let signature = MLDSA65Signature::new(sig);
    ml_dsa_65::verify(&vk, canonical.as_bytes(), ML_DSA_CONTEXT, &signature)
        .map_err(|_| MlDsaError::BadSignature)
}

#[derive(Debug, thiserror::Error)]
pub enum MlDsaError {
    #[error("ML-DSA signing failed")]
    Sign,
    #[error("ML-DSA verification key is malformed (wrong length)")]
    BadKey,
    #[error("ML-DSA signature does not verify or is malformed")]
    BadSignature,
}

impl fmt::Display for ParsedSignature {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "v={}, agent={}, ts={}, nonce={}, network={}",
            self.v, self.agent, self.ts, self.nonce, self.network
        )
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn empty_body_sha_constant_matches_computed() {
        assert_eq!(body_sha256_b64url(b""), EMPTY_BODY_SHA256);
    }

    #[test]
    fn sealed_header_roundtrips() {
        let nonce: Nonce = "F4Yk8vN2j5QwK3zB1aR9oA".parse().unwrap();
        let channel: ChannelId = ChannelId::from_bytes([7u8; 16]);
        let network: NetworkId = "parley-mainnet".parse().unwrap();
        let key = [9u8; SEALED_KEY_BYTES];
        let canonical = sealed_canonical_string(
            "POST",
            "/v1/channels/abc/sealed_messages",
            "",
            1_715_299_200,
            &nonce,
            &channel,
            42,
            &network,
            EMPTY_BODY_SHA256,
        );
        assert_eq!(canonical.lines().count(), 9);
        let mac = sealed_token_mac(&key, &canonical);
        let header = build_sealed_header_value(1_715_299_200, &nonce, &channel, 42, &network, &mac);
        assert!(
            !header.contains("agent="),
            "sealed header must carry no agent"
        );

        let parsed = parse_sealed_header_value(&header).unwrap();
        assert_eq!(parsed.v, SEALED_SIGNATURE_VERSION);
        assert_eq!(parsed.epoch, 42);
        assert_eq!(parsed.channel_id, channel);
        assert_eq!(parsed.token, mac);
        verify_sealed_token(&key, &canonical, &parsed.token).unwrap();
    }

    #[test]
    fn sealed_token_rejects_tamper_and_wrong_key() {
        let key = [1u8; SEALED_KEY_BYTES];
        let mac = sealed_token_mac(&key, "canonical-A");
        // Wrong canonical.
        assert!(verify_sealed_token(&key, "canonical-B", &mac).is_err());
        // Wrong key.
        assert!(verify_sealed_token(&[2u8; SEALED_KEY_BYTES], "canonical-A", &mac).is_err());
        // Flipped token byte.
        let mut bad = mac;
        bad[0] ^= 0xFF;
        assert!(verify_sealed_token(&key, "canonical-A", &bad).is_err());
        // Correct.
        assert!(verify_sealed_token(&key, "canonical-A", &mac).is_ok());
    }

    #[test]
    fn sealed_post_key_is_deterministic_per_exporter() {
        let exporter = [3u8; SEALED_KEY_BYTES];
        assert_eq!(
            derive_sealed_post_key(&exporter),
            derive_sealed_post_key(&exporter)
        );
        assert_ne!(
            derive_sealed_post_key(&exporter),
            derive_sealed_post_key(&[4u8; SEALED_KEY_BYTES])
        );
    }

    #[test]
    fn canonical_query_sorts_and_encodes() {
        assert_eq!(canonical_query_string(""), "");
        assert_eq!(canonical_query_string("b=2&a=1"), "a=1&b=2");
        assert_eq!(canonical_query_string("k=hello world"), "k=hello%20world");
        assert_eq!(canonical_query_string("k="), "k=");
    }

    #[test]
    fn canonical_string_format_is_eight_lines() {
        let agent: AgentPubkey = "u9PqJ4gK2mZ8t6nVxR3hB1cW7yE5dF0aQ4sT2lN6oU8"
            .parse()
            .unwrap();
        let nonce: Nonce = "F4Yk8vN2j5QwK3zB1aR9oA".parse().unwrap();
        let network: NetworkId = "parley-mainnet".parse().unwrap();
        let s = canonical_string(
            "GET",
            "/v1/blobs/abc",
            "",
            1715299200,
            &nonce,
            &agent,
            &network,
            EMPTY_BODY_SHA256,
        );
        assert_eq!(s.lines().count(), 8);
        assert!(s.starts_with("GET\n/v1/blobs/abc\n\n1715299200\n"));
    }

    #[test]
    fn header_roundtrips() {
        let agent: AgentPubkey = "u9PqJ4gK2mZ8t6nVxR3hB1cW7yE5dF0aQ4sT2lN6oU8"
            .parse()
            .unwrap();
        let nonce: Nonce = "F4Yk8vN2j5QwK3zB1aR9oA".parse().unwrap();
        let network: NetworkId = "parley-mainnet".parse().unwrap();
        let sig = [7u8; 64];
        let mldsa = vec![3u8; ML_DSA_SIG_BYTES];
        let header = build_header_value(&agent, 1715299200, &nonce, &network, &sig, &mldsa);
        let parsed = parse_header_value(&header).unwrap();
        assert_eq!(parsed.v, SIGNATURE_VERSION);
        assert_eq!(parsed.agent, agent);
        assert_eq!(parsed.ts, 1715299200);
        assert_eq!(parsed.nonce, nonce);
        assert_eq!(parsed.network, network);
        assert_eq!(parsed.sig, sig);
        assert_eq!(parsed.mldsa_sig.as_deref(), Some(mldsa.as_slice()));
    }

    #[test]
    fn header_tolerates_no_space_after_comma() {
        let agent: AgentPubkey = "u9PqJ4gK2mZ8t6nVxR3hB1cW7yE5dF0aQ4sT2lN6oU8"
            .parse()
            .unwrap();
        let nonce: Nonce = "F4Yk8vN2j5QwK3zB1aR9oA".parse().unwrap();
        let network: NetworkId = "parley-mainnet".parse().unwrap();
        let sig = [7u8; 64];
        let sig_b64 = URL_SAFE_NO_PAD.encode(sig);
        let header =
            format!("v=1,agent={agent},ts=1,nonce={nonce},network={network},sig={sig_b64}");
        let parsed = parse_header_value(&header).unwrap();
        assert_eq!(parsed.v, 1);
    }

    #[test]
    fn sign_then_verify_roundtrip() {
        use ed25519_dalek::{Signer as _, SigningKey};
        let signing = SigningKey::from_bytes(&[42u8; 32]);
        let agent = AgentPubkey::from_bytes(*signing.verifying_key().as_bytes());
        let canonical = "GET\n/healthz\n\n0\n_\n_\n_\n_";
        let sig = signing.sign(canonical.as_bytes()).to_bytes();
        verify_signature(&agent, canonical, &sig).unwrap();
        let mut bad = sig;
        bad[0] ^= 1;
        assert!(verify_signature(&agent, canonical, &bad).is_err());
    }

    #[test]
    fn ml_dsa_sign_verify_roundtrip() {
        use crate::keys::derive_auth_mldsa;
        let kp = derive_auth_mldsa(&[42u8; crate::keys::SEED_BYTES]);
        let pk = kp.verification_key.as_slice();
        let canonical = "GET\n/healthz\n\n0\n_\n_\n_\n_";

        let sig = ml_dsa_sign(&kp.signing_key, canonical).unwrap();
        assert_eq!(sig.len(), ML_DSA_SIG_BYTES);
        ml_dsa_verify(pk, canonical, &sig).unwrap();

        // Tampered message rejected.
        assert!(ml_dsa_verify(pk, "GET\n/other\n\n0\n_\n_\n_\n_", &sig).is_err());
        // Tampered signature rejected.
        let mut bad = sig.clone();
        bad[0] ^= 1;
        assert!(ml_dsa_verify(pk, canonical, &bad).is_err());
        // Wrong-length key/sig rejected, not panicked.
        assert!(ml_dsa_verify(&pk[..10], canonical, &sig).is_err());
        assert!(ml_dsa_verify(pk, canonical, &sig[..10]).is_err());
    }
}