Skip to main content

agentmux_common/
jekt_sign.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Jekt sender signing/verification: five schemes, each over its own material:
5//!   - Host-tier: HMAC-SHA256, one shared key per agent (`sign_jekt`/
6//!     `verify_jekt`). A 1:1 sender-to-local-srv relationship, so a
7//!     symmetric key is fine — the srv instance is the sole verifier.
8//!   - WAN, reagent only: Ed25519 against one pinned service keypair
9//!     (`verify_reagent_jekt`, `verify_trusted_reagent_jekt`). Multi-party
10//!     (receivers verify but can't forge), hence asymmetric.
11//!   - LAN, any agent: Ed25519, one keypair per agent
12//!     (`sign_lan_jekt`/`verify_lan_jekt`, and the UID-bound `_v2`). Same
13//!     multi-party reasoning as WAN, but per-sender instead of one pinned
14//!     key — see docs/specs/SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md.
15//!   - Cross-channel (same machine, other instance): the LAN keypair over a
16//!     domain-separated payload (`sign_channel_jekt`, and `_v2`).
17//!   - WAN, same account: Ed25519 per agent, certified by the sending
18//!     install (`sign_wan_jekt`/`verify_wan_jekt`).
19//!
20//! Shared between `agentmux-mcp` (the `Message` tool signs host, LAN and
21//! cross-channel jekts with the calling agent's own keys, fetched from srv's
22//! `GET /agentmux/agents/self/keys` with its env vars as a fallback; srv
23//! signs WAN jekts itself, at the origin) and `agentmux-srv` (the reactive
24//! handler verifies an incoming jekt's claimed signature against the
25//! claimed sender's key, looked up server-side by agent_id — see
26//! `crates/srv-core/src/backend/storage/agent_jekt_keys.rs` and
27//! `agent_lan_keys.rs`). Living here, not in either binary, is what
28//! guarantees the two can never independently drift on the signed-material
29//! format.
30//!
31//! See docs/specs/SPEC_JEKT_TRUST_LAYER_COMPLETION_2026_08_13.md §2.2,
32//! `docs/specs/SPEC_JEKT_SECURITY_AND_VISIBILITY_2026_07_01.md` §5.3 (the
33//! original spec's never-built "Phase 5" this module implements), and
34//! `docs/specs/SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md`.
35//!
36//! The signed material binds sender, target, message id, and timestamp
37//! together (not just msgid+payload) so a valid signature can't be replayed
38//! against a different target or reattributed to a different claimed sender.
39
40use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
41use ed25519_dalek::{Signature, Verifier, VerifyingKey};
42use hmac::{Hmac, Mac};
43use sha2::Sha256;
44
45type HmacSha256 = Hmac<Sha256>;
46
47/// Field separator inside the signed material — a control character, not a
48/// character any of the individual fields can plausibly contain, so
49/// concatenation can't be ambiguated by a field that happens to contain the
50/// separator (msgid/agent ids are validated elsewhere to be alnum/_/-; the
51/// message body is free text, but shifting the separator's *position* within
52/// the body can't produce a colliding signature for a different logical
53/// (source, target, msgid, ts) tuple, which is what actually matters here).
54pub const FIELD_SEP: char = '\u{1}';
55
56fn signed_material(msgid: &str, source_agent: &str, target_agent: &str, ts_secs: i64, message: &str) -> String {
57    format!("{msgid}{FIELD_SEP}{source_agent}{FIELD_SEP}{target_agent}{FIELD_SEP}{ts_secs}{FIELD_SEP}{message}")
58}
59
60/// Decode a base64-encoded signing key (e.g. from the `AGENTMUX_JEKT_KEY`
61/// process env var). Returns `None` on malformed input rather than erroring
62/// — callers should treat that the same as "no key available" (sign
63/// nothing, deliver unsigned rather than fail the send). Exposed here so
64/// `agentmux-mcp` doesn't need its own `base64` dependency just for this.
65pub fn decode_key(b64: &str) -> Option<Vec<u8>> {
66    BASE64.decode(b64).ok()
67}
68
69/// Sign a jekt with the sender's key. Returns a base64-encoded HMAC-SHA256
70/// tag. `key` of any length is accepted (HMAC's own key-hashing handles
71/// that) but `agent_jekt_keys::agent_jekt_key_ensure` always mints 32 bytes.
72pub fn sign_jekt(key: &[u8], msgid: &str, source_agent: &str, target_agent: &str, ts_secs: i64, message: &str) -> String {
73    let material = signed_material(msgid, source_agent, target_agent, ts_secs, message);
74    let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts a key of any length");
75    mac.update(material.as_bytes());
76    BASE64.encode(mac.finalize().into_bytes())
77}
78
79/// Verify a claimed signature against the sender's stored key. Constant-time
80/// comparison via `Mac::verify_slice` (not a manual `==`), so this can't leak
81/// timing information about how much of the tag matched.
82pub fn verify_jekt(
83    key: &[u8],
84    msgid: &str,
85    source_agent: &str,
86    target_agent: &str,
87    ts_secs: i64,
88    message: &str,
89    sig_b64: &str,
90) -> bool {
91    let Ok(sig) = BASE64.decode(sig_b64) else { return false };
92    let material = signed_material(msgid, source_agent, target_agent, ts_secs, message);
93    let Ok(mut mac) = HmacSha256::new_from_slice(key) else { return false };
94    mac.update(material.as_bytes());
95    mac.verify_slice(&sig).is_ok()
96}
97
98// ---- WAN-tier sender signing (Ed25519) ----
99//
100// Distinct signing scheme from host-tier's HMAC above, and deliberately so:
101// host-tier's key is minted per-instance and never leaves the srv process
102// that owns it, so a symmetric secret shared only between "sign" and
103// "verify" on the very same machine is the right tool. A WAN-tier service
104// sender (e.g. the GitHub review-notification consumer, "reagent") is
105// verified by *every* AgentMux instance on the network, not just its own
106// account — an HMAC key distributed that widely is no longer meaningfully
107// secret. Asymmetric signing lets the private key stay in exactly one
108// place (the signing key held in AgentMux's private secret store) while
109// every client ships only the public key, openly.
110//
111// Reuses the exact same `signed_material` construction as host-tier HMAC —
112// same replay/reattribution-resistance properties (msgid+source+target+ts
113// bound into what's signed), just a different signature algorithm over it.
114
115// The WAN-tier service senders' pinned keys and their two verifiers are their own module.
116mod reagent;
117pub use reagent::{is_reagent_trusted_signing_key, verify_reagent_jekt, verify_trusted_reagent_jekt};
118
119// ── LAN-tier per-agent Ed25519 signing (SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md) ──
120//
121// Asymmetric, not HMAC like host-tier: LAN is multi-party (any receiving
122// instance must be able to verify without being able to forge — the same
123// reason reagent's WAN signing above is asymmetric, just per-agent instead
124// of one pinned service key). Signed material is the exact same
125// `signed_material` host-tier and reagent both already use — one format,
126// three signature schemes layered on top depending on tier.
127
128/// Generate a fresh Ed25519 keypair for a newly-registered agent's LAN
129/// signing key. Returns `(public_key_bytes, private_key_seed_bytes)`, both
130/// 32 bytes raw — callers base64-encode for storage/transport (mirrors
131/// the `random_seed_bytes` + `BASE64.encode` split in the srv crate's
132/// `agent_lan_keys.rs`).
133///
134/// No RNG dependency needed beyond what's already used for HMAC key
135/// generation: `SigningKey::from_bytes` accepts any 32 bytes of randomness
136/// as a valid seed (deterministic key derivation from the seed, not a
137/// call into an RNG itself) — reusing the two-v4-UUIDs CSPRNG source
138/// `agent_lan_keys.rs::random_seed_bytes` already established avoids
139/// adding a `rand`/`getrandom` dependency here too.
140pub fn generate_lan_keypair(seed: [u8; 32]) -> ([u8; 32], [u8; 32]) {
141    let signing_key = ed25519_dalek::SigningKey::from_bytes(&seed);
142    (signing_key.verifying_key().to_bytes(), seed)
143}
144
145/// Sign a jekt with the sending agent's own LAN private key (read from its
146/// `AGENTMUX_LAN_KEY` process env var, mirroring `sign_jekt`'s
147/// `AGENTMUX_JEKT_KEY` — called client-side, inside `agentmux-mcp`, never
148/// server-side). `private_key` must be exactly 32 bytes (the seed
149/// `generate_lan_keypair` produced) — returns `None` on any other length
150/// rather than panicking, same "missing/malformed key must never block
151/// sending" policy `sign_jekt`'s callers already rely on.
152pub fn sign_lan_jekt(
153    private_key: &[u8],
154    msgid: &str,
155    source_agent: &str,
156    target_agent: &str,
157    ts_secs: i64,
158    message: &str,
159) -> Option<String> {
160    let seed: [u8; 32] = private_key.try_into().ok()?;
161    let signing_key = ed25519_dalek::SigningKey::from_bytes(&seed);
162    let material = signed_material(msgid, source_agent, target_agent, ts_secs, message);
163    let signature = ed25519_dalek::Signer::sign(&signing_key, material.as_bytes());
164    Some(BASE64.encode(signature.to_bytes()))
165}
166
167/// Verify a claimed LAN signature against the claimed sender's public key
168/// (looked up server-side by `source_agent`, over the LAN peer-lookup RPC —
169/// see `LanDiscovery::find_agent_lan_pubkey`). Returns `false` (never
170/// panics) for a malformed public key, malformed base64, a
171/// malformed/wrong-length signature, or a signature that simply doesn't
172/// verify — same "treat all of these identically as not verified" policy
173/// `verify_reagent_jekt` already documents.
174pub fn verify_lan_jekt(
175    public_key: &[u8],
176    msgid: &str,
177    source_agent: &str,
178    target_agent: &str,
179    ts_secs: i64,
180    message: &str,
181    sig_b64: &str,
182) -> bool {
183    let Ok(pubkey_arr) = <[u8; 32]>::try_from(public_key) else { return false };
184    let Ok(verifying_key) = VerifyingKey::from_bytes(&pubkey_arr) else { return false };
185    let Ok(sig_bytes) = BASE64.decode(sig_b64) else { return false };
186    let Ok(sig_arr) = <[u8; 64]>::try_from(sig_bytes.as_slice()) else { return false };
187    let signature = Signature::from_bytes(&sig_arr);
188    let material = signed_material(msgid, source_agent, target_agent, ts_secs, message);
189    verifying_key.verify(material.as_bytes(), &signature).is_ok()
190}
191
192// ── Cross-channel per-agent Ed25519 signing (SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md §D5) ──
193//
194// Same machine, different AgentMux instance. Asymmetric for the same reason
195// LAN is: the receiving instance must be able to verify without being able to
196// forge — and unlike host-tier's HMAC, the key can therefore be published in
197// the host-global shared registry, which is what makes cross-channel
198// verification possible at all (§5 of the spec explains why globalizing the
199// symmetric host key instead would be strictly worse).
200//
201// Reuses the agent's EXISTING LAN keypair — no new key material, no new
202// provisioning step. What it does NOT reuse is the signed material.
203
204/// Domain separator for cross-channel signatures.
205///
206/// Without this, a cross-channel signature and a LAN signature over the same
207/// (msgid, source, target, ts, message) tuple would be byte-identical, signed
208/// by the byte-identical key — so either could be replayed as the other. The
209/// tiers make different trust claims (`TRUST=lan-verified` vs
210/// `TRUST=channel-verified`) and are verified against different key sources, so
211/// they must not be interchangeable. Cheap now; a flag day later.
212const CHANNEL_DOMAIN: &str = "amx-jekt-channel-v1";
213
214/// Signed material for a cross-channel jekt.
215///
216/// Differs from [`signed_material`] in two ways, both load-bearing:
217///  - the [`CHANNEL_DOMAIN`] prefix (see above), and
218///  - `source_channel`, which binds the signature to the channel that minted
219///    it. Without it, a signature legitimately produced by an agent running in
220///    channel A could be replayed as that same agent speaking from channel B —
221///    and since one agent name can legitimately be live in several channels at
222///    once (`AgentEntry::channel` exists precisely because of that), the
223///    receiver has no other way to tell those apart.
224fn channel_signed_material(
225    msgid: &str,
226    source_agent: &str,
227    source_channel: &str,
228    target_agent: &str,
229    ts_secs: i64,
230    message: &str,
231) -> String {
232    format!(
233        "{CHANNEL_DOMAIN}{FIELD_SEP}{msgid}{FIELD_SEP}{source_agent}{FIELD_SEP}\
234         {source_channel}{FIELD_SEP}{target_agent}{FIELD_SEP}{ts_secs}{FIELD_SEP}{message}"
235    )
236}
237
238/// Sign a cross-channel jekt with the sending agent's own LAN private key
239/// (`AGENTMUX_LAN_KEY`) — called client-side in `agentmux-mcp`, never
240/// server-side, exactly like [`sign_lan_jekt`].
241///
242/// `private_key` must be exactly 32 bytes (the seed [`generate_lan_keypair`]
243/// produced); returns `None` on any other length rather than panicking — same
244/// "a missing or malformed key must never block sending" policy the other
245/// signers use. A message that can't be signed is delivered unsigned, and the
246/// receiver decides what that means.
247pub fn sign_channel_jekt(
248    private_key: &[u8],
249    msgid: &str,
250    source_agent: &str,
251    source_channel: &str,
252    target_agent: &str,
253    ts_secs: i64,
254    message: &str,
255) -> Option<String> {
256    let seed: [u8; 32] = private_key.try_into().ok()?;
257    let signing_key = ed25519_dalek::SigningKey::from_bytes(&seed);
258    let material =
259        channel_signed_material(msgid, source_agent, source_channel, target_agent, ts_secs, message);
260    let signature = ed25519_dalek::Signer::sign(&signing_key, material.as_bytes());
261    Some(BASE64.encode(signature.to_bytes()))
262}
263
264/// Verify a claimed cross-channel signature against the claimed sender's
265/// published public key (read server-side from the host-global shared registry
266/// entry — `AgentEntry::jekt_public_key`).
267///
268/// Returns `false`, never panics, for a malformed public key, malformed
269/// base64, a wrong-length signature, or a signature that simply doesn't verify
270/// — the same "all of these are identically 'not verified'" policy
271/// [`verify_lan_jekt`] and [`verify_reagent_jekt`] already document. The
272/// caller distinguishes "couldn't check" from "checked and failed"; this
273/// function only answers the second question.
274#[allow(clippy::too_many_arguments)]
275pub fn verify_channel_jekt(
276    public_key: &[u8],
277    msgid: &str,
278    source_agent: &str,
279    source_channel: &str,
280    target_agent: &str,
281    ts_secs: i64,
282    message: &str,
283    sig_b64: &str,
284) -> bool {
285    let Ok(pubkey_arr) = <[u8; 32]>::try_from(public_key) else { return false };
286    let Ok(verifying_key) = VerifyingKey::from_bytes(&pubkey_arr) else { return false };
287    let Ok(sig_bytes) = BASE64.decode(sig_b64) else { return false };
288    let Ok(sig_arr) = <[u8; 64]>::try_from(sig_bytes.as_slice()) else { return false };
289    let signature = Signature::from_bytes(&sig_arr);
290    let material =
291        channel_signed_material(msgid, source_agent, source_channel, target_agent, ts_secs, message);
292    verifying_key.verify(material.as_bytes(), &signature).is_ok()
293}
294
295// ── Cross-channel v2: bound to the sender's UID (identity M4d-6) ──
296mod channel_v2;
297pub use channel_v2::{sign_channel_jekt_v2, verify_channel_jekt_v2};
298mod lan_v2;
299pub use lan_v2::{sign_lan_jekt_v2, verify_lan_jekt_v2};
300#[cfg(test)]
301mod newer_domain_tests;
302
303// ── General agent-to-agent WAN signing ──
304//
305// Issue #2586's second half. Asymmetric for the same reason LAN and
306// cross-channel are — the receiving instance must verify without being able to
307// forge — but with a different key-distribution story: the public half is
308// published to muxbus's agent-ownership registry rather than fetched from a
309// peer, because a WAN counterpart is by definition unreachable directly.
310//
311// Only the primitives live here. srv signs at the origin
312// (`muxbus::relay::wan_sign_at_origin`), publishes keys
313// (`muxbus::wan_publish`) and verifies on delivery (`muxbus::wan_verify`)
314// (see https://docs.agentmux.ai/internals/jekt-protocol/).
315
316/// Domain separator for general agent-to-agent WAN signatures.
317///
318/// Exactly the same reasoning as [`CHANNEL_DOMAIN`], and load-bearing for the
319/// same reason: `db_agent_wan_keys` is a *separate* keypair from
320/// `db_agent_lan_keys`, but nothing structurally prevents a future change from
321/// reusing one key across tiers, and an undomained signature over the shared
322/// (msgid, source, target, ts, message) tuple would then be replayable from
323/// one tier to the other. The tiers make different trust claims
324/// (`TRUST=lan-verified` vs `TRUST=wan-verified`) against different key
325/// sources — a LAN peer's own answer vs. the cloud registry — so they must
326/// never be interchangeable.
327const WAN_DOMAIN: &str = "amx-jekt-wan-v1";
328
329/// Signed material for a general agent-to-agent WAN jekt.
330///
331/// Binds the sending **instance** (`source_host` + `source_channel`) as well
332/// as the agent, for the same reason [`channel_signed_material`] binds
333/// `source_channel`: one agent name can
334/// legitimately be live on several instances under one account — a different
335/// machine, or a different build channel on the same machine — and **each
336/// mints its own keypair**, because each srv instance has its own database.
337/// The instance therefore selects which key a signature is checked against,
338/// so it has to be part of what the signature covers; otherwise a mislabelled
339/// instance would silently select a different key rather than fail.
340///
341/// Deliberately does NOT bind the sender's muxbus account, even though
342/// verification resolves the key by `(account, host, channel, agent)`: the
343/// account is a cloud-side fact the signing process has no trustworthy view
344/// of at sign time, and binding a client-asserted account into the signature
345/// would let a sender pick which account's key it is checked against. The
346/// account is resolved server-side from the authenticated caller instead
347/// (§3.4.1) and selects the key; the signature then proves the agent and its
348/// instance. Host and channel are different: the signer is the sending
349/// srv itself, which knows both (its `wan.db` instance id and its channel),
350/// and a wrong value selects a key the signature cannot verify under — it
351/// grants nothing.
352fn wan_signed_material(
353    msgid: &str,
354    source_agent: &str,
355    source_host: &str,
356    source_channel: &str,
357    target_agent: &str,
358    ts_secs: i64,
359    message: &str,
360) -> String {
361    format!(
362        "{WAN_DOMAIN}{FIELD_SEP}{msgid}{FIELD_SEP}{source_agent}{FIELD_SEP}\
363         {source_host}{FIELD_SEP}{source_channel}{FIELD_SEP}\
364         {target_agent}{FIELD_SEP}{ts_secs}{FIELD_SEP}{message}"
365    )
366}
367
368/// Generate an agent's WAN keypair from 32 bytes of seed entropy, returning
369/// `(public_key, private_key)`.
370///
371/// Identical construction to [`generate_lan_keypair`] — same curve, same seed
372/// handling — but kept as its own entry point because the two keys are
373/// independent by design and must be minted separately: LAN public keys are
374/// permanently trust-on-first-use pinned by peers
375/// (`db_lan_peer_pubkey_pins`), which is exactly why
376/// `SPEC_JEKT_HOST_KEY_TTL_ROTATION_2026_09_14.md` §4 declined to rotate them,
377/// whereas WAN keys are served from an authoritative registry and are intended
378/// to rotate. One key cannot have both lifecycles.
379pub fn generate_wan_keypair(seed: [u8; 32]) -> ([u8; 32], [u8; 32]) {
380    let signing_key = ed25519_dalek::SigningKey::from_bytes(&seed);
381    (signing_key.verifying_key().to_bytes(), seed)
382}
383
384/// Sign a jekt with the sending agent's WAN private key, by the sending srv
385/// for the agent its token names (`muxbus::relay::wan_sign_at_origin`,
386/// SPEC_WAN_JEKT_SIGNED_BY_SRV_2026_10_14.md); no agent holds the key.
387///
388/// `private_key` must be exactly 32 bytes (the seed [`generate_wan_keypair`]
389/// produced); any other length returns `None` rather than panicking, matching
390/// the "a missing or malformed key must never block sending" policy every
391/// other signer here follows.
392pub fn sign_wan_jekt(
393    private_key: &[u8],
394    msgid: &str,
395    source_agent: &str,
396    source_host: &str,
397    source_channel: &str,
398    target_agent: &str,
399    ts_secs: i64,
400    message: &str,
401) -> Option<String> {
402    let seed: [u8; 32] = private_key.try_into().ok()?;
403    let signing_key = ed25519_dalek::SigningKey::from_bytes(&seed);
404    let material = wan_signed_material(
405        msgid,
406        source_agent,
407        source_host,
408        source_channel,
409        target_agent,
410        ts_secs,
411        message,
412    );
413    let signature = ed25519_dalek::Signer::sign(&signing_key, material.as_bytes());
414    Some(BASE64.encode(signature.to_bytes()))
415}
416
417/// Verify a claimed WAN signature against the claimed sender's published
418/// public key.
419///
420/// Returns `false` (never panics) for a malformed key, malformed base64, a
421/// wrong-length signature, or a signature that simply doesn't verify — the
422/// same "treat all of these identically as not verified" policy
423/// [`verify_lan_jekt`] and [`verify_reagent_jekt`] document. Note that the
424/// *caller* is responsible for the distinction that actually matters to tier
425/// escalation: "no key could be resolved" (nothing to check against) is not
426/// the same as "a key was resolved and this failed" (active forgery).
427pub fn verify_wan_jekt(
428    public_key: &[u8],
429    msgid: &str,
430    source_agent: &str,
431    source_host: &str,
432    source_channel: &str,
433    target_agent: &str,
434    ts_secs: i64,
435    message: &str,
436    sig_b64: &str,
437) -> bool {
438    let Ok(pubkey_arr) = <[u8; 32]>::try_from(public_key) else { return false };
439    let Ok(verifying_key) = VerifyingKey::from_bytes(&pubkey_arr) else { return false };
440    let Ok(sig_bytes) = BASE64.decode(sig_b64) else { return false };
441    let Ok(sig_arr) = <[u8; 64]>::try_from(sig_bytes.as_slice()) else { return false };
442    let signature = Signature::from_bytes(&sig_arr);
443    let material = wan_signed_material(
444        msgid,
445        source_agent,
446        source_host,
447        source_channel,
448        target_agent,
449        ts_secs,
450        message,
451    );
452    verifying_key.verify(material.as_bytes(), &signature).is_ok()
453}
454
455// ── W3-S: same-account WAN verification (SPEC_WAN_JEKT_VERIFICATION_2026_09_24.md) ──
456//
457// The pure half of W3-S: identifiers, the instance-signed agent-key
458// certificate, the revocation record, and the checks a receiver runs on the
459// fields the cloud relay carried. Storage, publishing, directory lookup and
460// replay tracking live in agentmux-srv; the cloud re-implements the chain
461// check in TypeScript and must match the
462// byte formats here exactly — the fixed vectors in the tests below are the
463// contract between the two.
464
465/// Domain separator for an instance's certificate over one agent key (§2.2).
466const WAN_CERT_DOMAIN: &str = "amx-wan-agent-cert-v1";
467
468/// Domain separator for an instance revocation record (§2.2).
469const WAN_REVOKE_DOMAIN: &str = "amx-wan-instance-revoke-v1";
470
471/// How old a carried `wan_ts_secs` may be: the relay's own 1800 s delivery
472/// TTL plus 300 s of slack (§2.4). A shorter window would reject messages
473/// the relay is still legitimately holding.
474pub const WAN_SIG_MAX_AGE_SECS: i64 = 1800 + 300;
475
476/// How far in the future a carried `wan_ts_secs` may be — desktop clock skew
477/// between sender and receiver (§2.4).
478pub const WAN_SIG_MAX_FUTURE_SKEW_SECS: i64 = 300;
479
480/// Length of an instance id: 128 bits as unpadded base32.
481pub const WAN_INSTANCE_ID_LEN: usize = 26;
482
483/// Length of a key fingerprint: 256 bits as unpadded base64url.
484pub const WAN_KEY_FP_LEN: usize = 43;
485
486const BASE32_ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
487
488/// RFC 4648 base32, lowercase, no padding.
489fn base32_lower_nopad(bytes: &[u8]) -> String {
490    let mut out = String::with_capacity((bytes.len() * 8).div_ceil(5));
491    let mut buffer: u32 = 0;
492    let mut bits = 0;
493    for &byte in bytes {
494        buffer = (buffer << 8) | u32::from(byte);
495        bits += 8;
496        while bits >= 5 {
497            bits -= 5;
498            out.push(BASE32_ALPHABET[((buffer >> bits) & 0x1f) as usize] as char);
499        }
500    }
501    if bits > 0 {
502        out.push(BASE32_ALPHABET[((buffer << (5 - bits)) & 0x1f) as usize] as char);
503    }
504    out
505}
506
507/// An instance's id: the first 128 bits of `SHA-256(instance public key)`,
508/// lowercase unpadded base32 — 26 chars of `[a-z2-7]` (§2.2).
509///
510/// Not secret. It names the key, so anything signed by the instance key can
511/// be checked against the id without trusting whoever supplied the key.
512pub fn wan_instance_id(instance_public_key: &[u8; 32]) -> String {
513    use sha2::Digest;
514    let digest = Sha256::digest(instance_public_key);
515    base32_lower_nopad(&digest[..16])
516}
517
518/// An agent key's fingerprint: `SHA-256(agent public key)`, unpadded
519/// base64url — 43 chars. Carried as `wan_key_fp`, an unsigned lookup hint
520/// (§2.1): a wrong value finds a key the signature won't verify under.
521pub fn wan_key_fingerprint(agent_public_key: &[u8; 32]) -> String {
522    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
523    use sha2::Digest;
524    URL_SAFE_NO_PAD.encode(Sha256::digest(agent_public_key))
525}
526
527/// Whether `host_hint` is safe to render: `[a-z0-9.-]{1,48}` (§2.6). The
528/// hint is sender-chosen; anything else renders as `?`.
529pub fn is_valid_wan_host_hint(host_hint: &str) -> bool {
530    (1..=48).contains(&host_hint.len())
531        && host_hint.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-')
532}
533
534/// The label a human sees for a verified instance: `<host_hint>~<id8>`
535/// (§2.6). The suffix comes from the id the chain proved, never from the
536/// sender's own label, so two instances claiming the same hostname still
537/// render differently.
538pub fn wan_instance_display_label(host_hint: &str, verified_instance_id: &str) -> String {
539    let hint = if is_valid_wan_host_hint(host_hint) { host_hint } else { "?" };
540    let id8: String = verified_instance_id.chars().take(8).collect();
541    format!("{hint}~{id8}")
542}
543
544/// Whether a carried `wan_ts_secs` is inside the freshness window (§2.4).
545/// Both bounds inclusive. Outside it the verdict is `None` (stale), not
546/// `Some(false)`: a stale signature grants nothing that dropping it wouldn't.
547pub fn wan_sig_is_fresh(wan_ts_secs: i64, now_secs: i64) -> bool {
548    now_secs.saturating_sub(wan_ts_secs) <= WAN_SIG_MAX_AGE_SECS
549        && wan_ts_secs.saturating_sub(now_secs) <= WAN_SIG_MAX_FUTURE_SKEW_SECS
550}
551
552/// ASCII case-insensitive equality after trimming — the one comparison every
553/// W3-S identifier check uses (§2.1). Agent ids are ASCII-only, and the cloud
554/// lowercases most of them but stores `github*` sources raw.
555fn wan_id_eq(a: &str, b: &str) -> bool {
556    a.trim().eq_ignore_ascii_case(b.trim())
557}
558
559fn wan_cert_material(
560    instance_id: &str,
561    agent_id: &str,
562    channel: &str,
563    agent_public_key_b64: &str,
564    host_hint: &str,
565    issued_at: i64,
566) -> String {
567    let agent_id = agent_id.to_ascii_lowercase();
568    format!(
569        "{WAN_CERT_DOMAIN}{FIELD_SEP}{instance_id}{FIELD_SEP}{agent_id}{FIELD_SEP}\
570         {channel}{FIELD_SEP}{agent_public_key_b64}{FIELD_SEP}{host_hint}{FIELD_SEP}{issued_at}"
571    )
572}
573
574fn wan_revoke_material(old_instance_id: &str, new_instance_id: &str, revoked_at: i64) -> String {
575    format!("{WAN_REVOKE_DOMAIN}{FIELD_SEP}{old_instance_id}{FIELD_SEP}{new_instance_id}{FIELD_SEP}{revoked_at}")
576}
577
578pub fn ed25519_sign_b64(private_key: &[u8], material: &str) -> Option<String> {
579    let seed: [u8; 32] = private_key.try_into().ok()?;
580    let signing_key = ed25519_dalek::SigningKey::from_bytes(&seed);
581    let signature = ed25519_dalek::Signer::sign(&signing_key, material.as_bytes());
582    Some(BASE64.encode(signature.to_bytes()))
583}
584
585pub fn ed25519_verify_b64(public_key: &[u8; 32], material: &str, sig_b64: &str) -> bool {
586    let Ok(verifying_key) = VerifyingKey::from_bytes(public_key) else { return false };
587    let Ok(sig_bytes) = BASE64.decode(sig_b64) else { return false };
588    let Ok(sig_arr) = <[u8; 64]>::try_from(sig_bytes.as_slice()) else { return false };
589    verifying_key.verify(material.as_bytes(), &Signature::from_bytes(&sig_arr)).is_ok()
590}
591
592pub fn decode_public_key_b64(b64: &str) -> Option<[u8; 32]> {
593    BASE64.decode(b64).ok()?.try_into().ok()
594}
595
596/// One entry in the per-account key directory (§2.2): an agent key,
597/// certified by the instance that minted it. Public keys are standard
598/// base64 of the raw 32 bytes; `cert_sig` is standard base64 Ed25519.
599///
600/// Every field is untrusted until [`WanKeyRecord::check_chain`] passes —
601/// the record arrives from the cloud, which may be tampering.
602#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
603pub struct WanKeyRecord {
604    pub instance_id: String,
605    pub agent_id: String,
606    pub channel: String,
607    pub key_fp: String,
608    pub instance_pubkey: String,
609    pub agent_pubkey: String,
610    pub host_hint: String,
611    pub issued_at: i64,
612    pub cert_sig: String,
613}
614
615impl WanKeyRecord {
616    /// Certify `agent_public_key` with the instance key. Called by the srv
617    /// that owns the instance; returns `None` for a malformed instance
618    /// private key, never panics.
619    pub fn certify(
620        instance_private_key: &[u8],
621        agent_id: &str,
622        channel: &str,
623        agent_public_key: &[u8; 32],
624        host_hint: &str,
625        issued_at: i64,
626    ) -> Option<Self> {
627        let seed: [u8; 32] = instance_private_key.try_into().ok()?;
628        let instance_public_key = ed25519_dalek::SigningKey::from_bytes(&seed).verifying_key().to_bytes();
629        let instance_id = wan_instance_id(&instance_public_key);
630        let agent_pubkey = BASE64.encode(agent_public_key);
631        let material = wan_cert_material(&instance_id, agent_id, channel, &agent_pubkey, host_hint, issued_at);
632        Some(Self {
633            instance_id,
634            agent_id: agent_id.to_ascii_lowercase(),
635            channel: channel.to_string(),
636            key_fp: wan_key_fingerprint(agent_public_key),
637            instance_pubkey: BASE64.encode(instance_public_key),
638            agent_pubkey,
639            host_hint: host_hint.to_string(),
640            issued_at,
641            cert_sig: ed25519_sign_b64(&seed, &material)?,
642        })
643    }
644
645    /// The chain every holder of a record checks — the cloud on `PUT`
646    /// (hygiene) and the receiver before trusting it (the real anchor):
647    /// the instance id is the hash of the instance key, the fingerprint is
648    /// the hash of the agent key, and the instance key signed the
649    /// certificate. Returns the decoded agent public key on success.
650    pub fn check_chain(&self) -> Option<[u8; 32]> {
651        let instance_public_key = decode_public_key_b64(&self.instance_pubkey)?;
652        let agent_public_key = decode_public_key_b64(&self.agent_pubkey)?;
653        if wan_instance_id(&instance_public_key) != self.instance_id
654            || wan_key_fingerprint(&agent_public_key) != self.key_fp
655            || self.agent_id != self.agent_id.to_ascii_lowercase()
656        {
657            return None;
658        }
659        let material = wan_cert_material(
660            &self.instance_id,
661            &self.agent_id,
662            &self.channel,
663            &self.agent_pubkey,
664            &self.host_hint,
665            self.issued_at,
666        );
667        ed25519_verify_b64(&instance_public_key, &material, &self.cert_sig).then_some(agent_public_key)
668    }
669}
670
671/// An instance revocation (§2.2), signed by the **old** instance key so only
672/// the owner of that key can retire it. Sticky: nothing un-revokes an id.
673#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
674pub struct WanRevocation {
675    pub old_instance_id: String,
676    pub old_instance_pubkey: String,
677    pub new_instance_id: String,
678    pub revoked_at: i64,
679    pub sig: String,
680}
681
682impl WanRevocation {
683    /// Sign a revocation of the instance whose private key is `old_private_key`.
684    pub fn sign(old_private_key: &[u8], new_instance_id: &str, revoked_at: i64) -> Option<Self> {
685        let seed: [u8; 32] = old_private_key.try_into().ok()?;
686        let old_public_key = ed25519_dalek::SigningKey::from_bytes(&seed).verifying_key().to_bytes();
687        let old_instance_id = wan_instance_id(&old_public_key);
688        let material = wan_revoke_material(&old_instance_id, new_instance_id, revoked_at);
689        Some(Self {
690            old_instance_id,
691            old_instance_pubkey: BASE64.encode(old_public_key),
692            new_instance_id: new_instance_id.to_string(),
693            revoked_at,
694            sig: ed25519_sign_b64(&seed, &material)?,
695        })
696    }
697
698    /// The old id is the hash of the old key, and the old key signed it.
699    pub fn verify(&self) -> bool {
700        let Some(old_public_key) = decode_public_key_b64(&self.old_instance_pubkey) else { return false };
701        wan_instance_id(&old_public_key) == self.old_instance_id
702            && ed25519_verify_b64(
703                &old_public_key,
704                &wan_revoke_material(&self.old_instance_id, &self.new_instance_id, self.revoked_at),
705                &self.sig,
706            )
707    }
708}
709
710/// The signed tuple as carried through the relay (§2.1). All of it is
711/// sender-supplied; `key_fp` is a lookup hint and is not signed.
712#[derive(Debug, Clone, PartialEq, Eq)]
713pub struct WanCarried<'a> {
714    pub sig: &'a str,
715    pub msg_id: &'a str,
716    pub ts_secs: i64,
717    pub source_agent: &'a str,
718    pub target_agent: &'a str,
719    pub source_host: &'a str,
720    pub source_channel: &'a str,
721    pub key_fp: &'a str,
722}
723
724/// Why a carried signature did not verify. Each maps to the §2.3 verdict the
725/// caller records; the ones that are `None` there are "couldn't check",
726/// never a forgery signal.
727#[derive(Debug, Clone, Copy, PartialEq, Eq)]
728pub enum WanCheckFailure {
729    /// The carried source or target isn't the one actually delivered →
730    /// `Some(false)`.
731    EnvelopeMismatch,
732    /// Outside the freshness window → `None`, audit `wan_sig_stale`.
733    Stale,
734    /// The directory record's chain is broken → `Some(false)`, audit
735    /// `wan_cert_invalid`. Only a tampering cloud or a bug produces this.
736    CertInvalid,
737    /// The record is for a different instance, channel, agent or key than
738    /// the carried one → `Some(false)`.
739    RecordMismatch,
740    /// The message signature doesn't verify under the certified key →
741    /// `Some(false)`.
742    BadSignature,
743}
744
745impl WanCheckFailure {
746    /// The `wan_verified` value this failure records: `None` for "couldn't
747    /// check", `Some(false)` for an active verification failure.
748    pub fn verdict(self) -> Option<bool> {
749        match self {
750            Self::Stale => None,
751            Self::EnvelopeMismatch | Self::CertInvalid | Self::RecordMismatch | Self::BadSignature => Some(false),
752        }
753    }
754}
755
756/// The checks that need no directory record, in the §2.3 order: the
757/// envelope binding, then freshness. `row_source_agent` is the cloud row's
758/// `source_agent`; `polled_agent_id` is the agent the subscriber is
759/// delivering to — **not** a row field, so a cloud can't move a message
760/// signed for one agent into another's queue.
761pub fn check_wan_envelope(
762    carried: &WanCarried<'_>,
763    row_source_agent: &str,
764    polled_agent_id: &str,
765    now_secs: i64,
766) -> Result<(), WanCheckFailure> {
767    if !wan_id_eq(carried.source_agent, row_source_agent) || !wan_id_eq(carried.target_agent, polled_agent_id) {
768        return Err(WanCheckFailure::EnvelopeMismatch);
769    }
770    if !wan_sig_is_fresh(carried.ts_secs, now_secs) {
771        return Err(WanCheckFailure::Stale);
772    }
773    Ok(())
774}
775
776/// The checks against a directory record, in the §2.3 order: the chain, the
777/// record matching what was carried, then the message signature. Run after
778/// [`check_wan_envelope`] passes and a record was found. Replay is the
779/// caller's (it needs state).
780pub fn verify_wan_against_record(
781    carried: &WanCarried<'_>,
782    record: &WanKeyRecord,
783    message: &str,
784) -> Result<(), WanCheckFailure> {
785    let agent_public_key = record.check_chain().ok_or(WanCheckFailure::CertInvalid)?;
786    // ASCII case-insensitive for instance, channel and agent, as §2.3
787    // specifies (Codex P2 on #3727). Safe: the signature still covers the
788    // carried values exactly, the certificate the record's, and a channel that
789    // differs only in case is a different data dir, hence a different
790    // instance id.
791    if !wan_id_eq(&record.instance_id, carried.source_host)
792        || !wan_id_eq(&record.channel, carried.source_channel)
793        || !wan_id_eq(&record.agent_id, carried.source_agent)
794        || record.key_fp != carried.key_fp
795    {
796        return Err(WanCheckFailure::RecordMismatch);
797    }
798    if !verify_wan_jekt(
799        &agent_public_key,
800        carried.msg_id,
801        carried.source_agent,
802        carried.source_host,
803        carried.source_channel,
804        carried.target_agent,
805        carried.ts_secs,
806        message,
807        carried.sig,
808    ) {
809        return Err(WanCheckFailure::BadSignature);
810    }
811    Ok(())
812}
813
814#[cfg(test)]
815mod tests {
816    use super::*;
817
818    fn key() -> Vec<u8> {
819        vec![7u8; 32]
820    }
821
822    #[test]
823    fn a_correctly_signed_message_verifies() {
824        let k = key();
825        let sig = sign_jekt(&k, "msg-1", "agentx", "agenty", 1_000, "hello");
826        assert!(verify_jekt(&k, "msg-1", "agentx", "agenty", 1_000, "hello", &sig));
827    }
828
829    #[test]
830    fn wrong_key_fails_verification() {
831        let sig = sign_jekt(&key(), "msg-1", "agentx", "agenty", 1_000, "hello");
832        let other_key = vec![9u8; 32];
833        assert!(!verify_jekt(&other_key, "msg-1", "agentx", "agenty", 1_000, "hello", &sig));
834    }
835
836    #[test]
837    fn tampered_message_fails_verification() {
838        let k = key();
839        let sig = sign_jekt(&k, "msg-1", "agentx", "agenty", 1_000, "hello");
840        assert!(!verify_jekt(&k, "msg-1", "agentx", "agenty", 1_000, "goodbye", &sig));
841    }
842
843    #[test]
844    fn signature_cannot_be_replayed_against_a_different_target() {
845        // The whole point of binding target_agent into the signed material:
846        // a signature legitimately produced for agenty must not verify when
847        // replayed claiming a different target.
848        let k = key();
849        let sig = sign_jekt(&k, "msg-1", "agentx", "agenty", 1_000, "hello");
850        assert!(!verify_jekt(&k, "msg-1", "agentx", "agentz", 1_000, "hello", &sig));
851    }
852
853    #[test]
854    fn signature_cannot_be_reattributed_to_a_different_claimed_sender() {
855        let k = key();
856        let sig = sign_jekt(&k, "msg-1", "agentx", "agenty", 1_000, "hello");
857        assert!(!verify_jekt(&k, "msg-1", "agentz", "agenty", 1_000, "hello", &sig));
858    }
859
860    #[test]
861    fn different_msgid_fails_verification() {
862        let k = key();
863        let sig = sign_jekt(&k, "msg-1", "agentx", "agenty", 1_000, "hello");
864        assert!(!verify_jekt(&k, "msg-2", "agentx", "agenty", 1_000, "hello", &sig));
865    }
866
867    #[test]
868    fn different_timestamp_fails_verification() {
869        let k = key();
870        let sig = sign_jekt(&k, "msg-1", "agentx", "agenty", 1_000, "hello");
871        assert!(!verify_jekt(&k, "msg-1", "agentx", "agenty", 1_001, "hello", &sig));
872    }
873
874    #[test]
875    fn malformed_base64_signature_fails_verification_not_panics() {
876        assert!(!verify_jekt(&key(), "msg-1", "agentx", "agenty", 1_000, "hello", "not-valid-base64!!"));
877    }
878
879    #[test]
880    fn empty_signature_fails_verification() {
881        assert!(!verify_jekt(&key(), "msg-1", "agentx", "agenty", 1_000, "hello", ""));
882    }
883
884    // ---- LAN-tier Ed25519 signing ----
885
886    fn lan_seed(byte: u8) -> [u8; 32] {
887        [byte; 32]
888    }
889
890    #[test]
891    fn lan_keypair_is_deterministic_from_seed_and_public_differs_from_private() {
892        let (pub1, priv1) = generate_lan_keypair(lan_seed(3));
893        let (pub2, priv2) = generate_lan_keypair(lan_seed(3));
894        assert_eq!(pub1, pub2, "same seed must derive the same keypair");
895        assert_eq!(priv1, priv2);
896        assert_ne!(pub1, priv1, "public and private halves must differ");
897    }
898
899    #[test]
900    fn different_seeds_give_different_keypairs() {
901        let (pub_a, _) = generate_lan_keypair(lan_seed(1));
902        let (pub_b, _) = generate_lan_keypair(lan_seed(2));
903        assert_ne!(pub_a, pub_b);
904    }
905
906    #[test]
907    fn a_correctly_signed_lan_message_verifies() {
908        let (public_key, private_key) = generate_lan_keypair(lan_seed(5));
909        let sig = sign_lan_jekt(&private_key, "msg-1", "agentx", "agenty", 1_000, "hello").unwrap();
910        assert!(verify_lan_jekt(&public_key, "msg-1", "agentx", "agenty", 1_000, "hello", &sig));
911    }
912
913    #[test]
914    fn lan_wrong_key_fails_verification() {
915        let (_, private_key) = generate_lan_keypair(lan_seed(5));
916        let sig = sign_lan_jekt(&private_key, "msg-1", "agentx", "agenty", 1_000, "hello").unwrap();
917        let (other_public, _) = generate_lan_keypair(lan_seed(9));
918        assert!(!verify_lan_jekt(&other_public, "msg-1", "agentx", "agenty", 1_000, "hello", &sig));
919    }
920
921    #[test]
922    fn lan_tampered_message_fails_verification() {
923        let (public_key, private_key) = generate_lan_keypair(lan_seed(5));
924        let sig = sign_lan_jekt(&private_key, "msg-1", "agentx", "agenty", 1_000, "hello").unwrap();
925        assert!(!verify_lan_jekt(&public_key, "msg-1", "agentx", "agenty", 1_000, "goodbye", &sig));
926    }
927
928    #[test]
929    fn lan_tampered_claimed_sender_fails_verification() {
930        // Same signature, different claimed source_agent — binding sender
931        // into the signed material means a captured signature can't be
932        // reattributed to a different identity.
933        let (public_key, private_key) = generate_lan_keypair(lan_seed(5));
934        let sig = sign_lan_jekt(&private_key, "msg-1", "agentx", "agenty", 1_000, "hello").unwrap();
935        assert!(!verify_lan_jekt(&public_key, "msg-1", "someoneelse", "agenty", 1_000, "hello", &sig));
936    }
937
938    #[test]
939    fn lan_signing_with_wrong_length_key_returns_none_not_panics() {
940        assert!(sign_lan_jekt(&[1u8; 16], "msg-1", "agentx", "agenty", 1_000, "hello").is_none());
941        assert!(sign_lan_jekt(&[], "msg-1", "agentx", "agenty", 1_000, "hello").is_none());
942    }
943
944    #[test]
945    fn lan_verify_with_wrong_length_public_key_fails_not_panics() {
946        let (_, private_key) = generate_lan_keypair(lan_seed(5));
947        let sig = sign_lan_jekt(&private_key, "msg-1", "agentx", "agenty", 1_000, "hello").unwrap();
948        assert!(!verify_lan_jekt(&[1u8; 16], "msg-1", "agentx", "agenty", 1_000, "hello", &sig));
949    }
950
951    #[test]
952    fn lan_verify_with_malformed_base64_signature_fails_not_panics() {
953        let (public_key, _) = generate_lan_keypair(lan_seed(5));
954        assert!(!verify_lan_jekt(
955            &public_key,
956            "msg-1",
957            "agentx",
958            "agenty",
959            1_000,
960            "hello",
961            "not-valid-base64!!",
962        ));
963    }
964
965    #[test]
966    fn lan_verify_with_wrong_length_signature_fails_not_panics() {
967        let (public_key, _) = generate_lan_keypair(lan_seed(5));
968        assert!(!verify_lan_jekt(
969            &public_key,
970            "msg-1",
971            "agentx",
972            "agenty",
973            1_000,
974            "hello",
975            "dG9vc2hvcnQ=", // "tooshort" base64 — decodes fine, wrong length
976        ));
977    }
978
979    #[test]
980    fn lan_verify_with_empty_signature_fails_not_panics() {
981        let (public_key, _) = generate_lan_keypair(lan_seed(5));
982        assert!(!verify_lan_jekt(&public_key, "msg-1", "agentx", "agenty", 1_000, "hello", ""));
983    }
984
985    #[test]
986    fn a_lan_signature_does_not_verify_against_reagent_or_host_schemes() {
987        // Cross-scheme confusion check: a LAN Ed25519 signature must not be
988        // mistakable for anything the HMAC verifier would accept (different
989        // algorithm entirely, so this is really just documenting the type
990        // boundary — verify_jekt takes a raw HMAC key, not an Ed25519 one).
991        let (_, private_key) = generate_lan_keypair(lan_seed(5));
992        let sig = sign_lan_jekt(&private_key, "msg-1", "agentx", "agenty", 1_000, "hello").unwrap();
993        assert!(!verify_jekt(&private_key, "msg-1", "agentx", "agenty", 1_000, "hello", &sig));
994    }
995
996    // ---- Cross-channel Ed25519 signing (SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md §D5) ----
997
998    #[test]
999    fn a_correctly_signed_channel_message_verifies() {
1000        let (public_key, private_key) = generate_lan_keypair(lan_seed(9));
1001        let sig =
1002            sign_channel_jekt(&private_key, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello")
1003                .unwrap();
1004        assert!(verify_channel_jekt(
1005            &public_key, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello", &sig
1006        ));
1007    }
1008
1009    #[test]
1010    fn channel_wrong_key_fails_verification() {
1011        let (_, private_key) = generate_lan_keypair(lan_seed(9));
1012        let (other_public, _) = generate_lan_keypair(lan_seed(10));
1013        let sig =
1014            sign_channel_jekt(&private_key, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello")
1015                .unwrap();
1016        assert!(!verify_channel_jekt(
1017            &other_public, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello", &sig
1018        ));
1019    }
1020
1021    #[test]
1022    fn channel_tampered_fields_fail_verification() {
1023        let (public_key, private_key) = generate_lan_keypair(lan_seed(9));
1024        let sig =
1025            sign_channel_jekt(&private_key, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello")
1026                .unwrap();
1027        // Every signed field must actually be covered.
1028        for (msgid, src, chan, tgt, ts, msg) in [
1029            ("msg-2", "agentx", "chan-a", "agenty", 1_000, "hello"),
1030            ("msg-1", "agentz", "chan-a", "agenty", 1_000, "hello"),
1031            ("msg-1", "agentx", "chan-a", "agentz", 1_000, "hello"),
1032            ("msg-1", "agentx", "chan-a", "agenty", 1_001, "hello"),
1033            ("msg-1", "agentx", "chan-a", "agenty", 1_000, "goodbye"),
1034        ] {
1035            assert!(
1036                !verify_channel_jekt(&public_key, msgid, src, chan, tgt, ts, msg, &sig),
1037                "tampering with a signed field must fail: {msgid}/{src}/{chan}/{tgt}/{ts}/{msg}"
1038            );
1039        }
1040    }
1041
1042    #[test]
1043    fn a_signature_minted_for_one_channel_does_not_verify_as_another() {
1044        // §D5 channel binding. One agent name can be live in several channels
1045        // at once; without `source_channel` in the signed material, a signature
1046        // legitimately produced in chan-a could be replayed as that same agent
1047        // speaking from chan-b, and the receiver would have no way to tell.
1048        let (public_key, private_key) = generate_lan_keypair(lan_seed(9));
1049        let sig =
1050            sign_channel_jekt(&private_key, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello")
1051                .unwrap();
1052        assert!(!verify_channel_jekt(
1053            &public_key, "msg-1", "agentx", "chan-b", "agenty", 1_000, "hello", &sig
1054        ));
1055    }
1056
1057    #[test]
1058    fn lan_and_channel_signatures_are_not_interchangeable_in_either_direction() {
1059        // §D5 domain separation — the test the separator exists for. Same key,
1060        // same (msgid, source, target, ts, message) tuple: without
1061        // CHANNEL_DOMAIN these two signatures would be byte-identical and each
1062        // would verify as the other, collapsing two different trust claims
1063        // (TRUST=lan-verified vs TRUST=channel-verified) into one.
1064        let (public_key, private_key) = generate_lan_keypair(lan_seed(9));
1065        let lan_sig = sign_lan_jekt(&private_key, "msg-1", "agentx", "agenty", 1_000, "hello").unwrap();
1066        let channel_sig =
1067            sign_channel_jekt(&private_key, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello")
1068                .unwrap();
1069
1070        assert_ne!(lan_sig, channel_sig, "the two schemes must not produce identical bytes");
1071
1072        // A LAN signature replayed as a cross-channel one.
1073        assert!(!verify_channel_jekt(
1074            &public_key, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello", &lan_sig
1075        ));
1076        // A cross-channel signature replayed as a LAN one.
1077        assert!(!verify_lan_jekt(
1078            &public_key, "msg-1", "agentx", "agenty", 1_000, "hello", &channel_sig
1079        ));
1080    }
1081
1082    #[test]
1083    fn channel_malformed_inputs_fail_rather_than_panic() {
1084        let (public_key, private_key) = generate_lan_keypair(lan_seed(9));
1085        let sig =
1086            sign_channel_jekt(&private_key, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello")
1087                .unwrap();
1088        // Wrong-length private key → None, never a panic.
1089        assert!(sign_channel_jekt(&[1u8; 16], "m", "a", "c", "b", 1, "x").is_none());
1090        // Malformed public key / base64 / signature length → false, never a panic.
1091        assert!(!verify_channel_jekt(&[0u8; 16], "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello", &sig));
1092        assert!(!verify_channel_jekt(&public_key, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello", "!!not base64!!"));
1093        assert!(!verify_channel_jekt(&public_key, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello", ""));
1094    }
1095
1096    #[test]
1097    fn an_empty_source_channel_is_still_bound_not_ignored() {
1098        // A pre-upgrade or unknown channel id must not act as a wildcard that
1099        // matches any channel — it is just another distinct value.
1100        let (public_key, private_key) = generate_lan_keypair(lan_seed(9));
1101        let sig = sign_channel_jekt(&private_key, "msg-1", "agentx", "", "agenty", 1_000, "hello").unwrap();
1102        assert!(verify_channel_jekt(&public_key, "msg-1", "agentx", "", "agenty", 1_000, "hello", &sig));
1103        assert!(!verify_channel_jekt(&public_key, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello", &sig));
1104    }
1105
1106    // ── WAN tier ──
1107
1108    #[test]
1109    fn a_correctly_signed_wan_message_verifies() {
1110        let (public_key, private_key) = generate_wan_keypair(lan_seed(11));
1111        let sig = sign_wan_jekt(&private_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello").unwrap();
1112        assert!(verify_wan_jekt(&public_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello", &sig));
1113    }
1114
1115    #[test]
1116    fn a_wan_signature_does_not_verify_under_another_agents_key() {
1117        let (_, private_key) = generate_wan_keypair(lan_seed(11));
1118        let (other_public, _) = generate_wan_keypair(lan_seed(12));
1119        let sig = sign_wan_jekt(&private_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello").unwrap();
1120        assert!(!verify_wan_jekt(&other_public, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello", &sig));
1121    }
1122
1123    #[test]
1124    fn tampering_with_any_wan_field_breaks_verification() {
1125        let (public_key, private_key) = generate_wan_keypair(lan_seed(11));
1126        let sig = sign_wan_jekt(&private_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello").unwrap();
1127        assert!(!verify_wan_jekt(&public_key, "msg-2", "agentx", "narko", "stable", "agenty", 1_000, "hello", &sig));
1128        assert!(!verify_wan_jekt(&public_key, "msg-1", "someoneelse", "narko", "stable", "agenty", 1_000, "hello", &sig));
1129        assert!(!verify_wan_jekt(&public_key, "msg-1", "agentx", "narko", "stable", "agentz", 1_000, "hello", &sig));
1130        assert!(!verify_wan_jekt(&public_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_001, "hello", &sig));
1131        assert!(!verify_wan_jekt(&public_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "goodbye", &sig));
1132    }
1133
1134    #[test]
1135    fn wan_malformed_inputs_fail_rather_than_panic() {
1136        let (public_key, private_key) = generate_wan_keypair(lan_seed(11));
1137        let sig = sign_wan_jekt(&private_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello").unwrap();
1138        assert!(sign_wan_jekt(&[1u8; 16], "m", "a", "h", "c", "b", 1, "x").is_none());
1139        assert!(!verify_wan_jekt(&[0u8; 16], "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello", &sig));
1140        assert!(!verify_wan_jekt(&public_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello", "!!not base64!!"));
1141        assert!(!verify_wan_jekt(&public_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello", ""));
1142    }
1143
1144    #[test]
1145    fn a_wan_signature_is_bound_to_the_sending_instance() {
1146        // One account can run
1147        // the same agent name on several instances — another machine, or
1148        // another build channel on the same machine — and each mints its own
1149        // keypair. The instance selects which key a signature is checked
1150        // against, so it must be part of what the signature covers: otherwise
1151        // a mislabelled instance would silently select a different key instead
1152        // of failing.
1153        let (public_key, private_key) = generate_wan_keypair(lan_seed(14));
1154        let sig =
1155            sign_wan_jekt(&private_key, "msg-1", "lark", "narko", "stable", "agenty", 1_000, "hello")
1156                .unwrap();
1157
1158        assert!(verify_wan_jekt(
1159            &public_key, "msg-1", "lark", "narko", "stable", "agenty", 1_000, "hello", &sig
1160        ));
1161        // Same agent, same account, different machine → not the same claim.
1162        assert!(!verify_wan_jekt(
1163            &public_key, "msg-1", "lark", "area54", "stable", "agenty", 1_000, "hello", &sig
1164        ));
1165        // Same agent, same machine, different build channel → also distinct,
1166        // because that is a different data dir, database, and keypair.
1167        assert!(!verify_wan_jekt(
1168            &public_key, "msg-1", "lark", "narko", "local-dev", "agenty", 1_000, "hello", &sig
1169        ));
1170    }
1171
1172    #[test]
1173    fn a_wan_signature_is_not_interchangeable_with_lan_or_channel() {
1174        // The whole point of WAN_DOMAIN. Even with the SAME key bytes and the
1175        // SAME (msgid, source, target, ts, message) tuple, a signature minted
1176        // for one tier must not verify as another — otherwise a signature
1177        // captured off the LAN could be replayed to claim `TRUST=wan-verified`,
1178        // which is a materially stronger claim verified against a different
1179        // key source.
1180        let seed = lan_seed(13);
1181        let (public_key, private_key) = generate_wan_keypair(seed);
1182
1183        let wan_sig = sign_wan_jekt(&private_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello").unwrap();
1184        let lan_sig = sign_lan_jekt(&private_key, "msg-1", "agentx", "agenty", 1_000, "hello").unwrap();
1185        let channel_sig =
1186            sign_channel_jekt(&private_key, "msg-1", "agentx", "chan-a", "agenty", 1_000, "hello")
1187                .unwrap();
1188
1189        // Each verifies only under its own tier's verifier.
1190        assert!(verify_wan_jekt(&public_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello", &wan_sig));
1191        assert!(!verify_lan_jekt(&public_key, "msg-1", "agentx", "agenty", 1_000, "hello", &wan_sig));
1192        assert!(!verify_wan_jekt(&public_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello", &lan_sig));
1193        assert!(!verify_wan_jekt(&public_key, "msg-1", "agentx", "narko", "stable", "agenty", 1_000, "hello", &channel_sig
1194        ));
1195        assert_ne!(wan_sig, lan_sig);
1196    }
1197
1198    // ── W3-S ──
1199    //
1200    // The vectors below were computed by an independent implementation
1201    // (Node's `crypto`: raw Ed25519 from a PKCS#8-wrapped seed, SHA-256,
1202    // hand-rolled base32) and pasted in. The cloud's TypeScript chain check
1203    // asserts the same values, so a byte
1204    // drift on either side fails a test instead of every verification.
1205    // Instance seed [1; 32], agent seed [2; 32], successor instance [3; 32].
1206
1207    const V_INSTANCE_PUBKEY: &str = "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=";
1208    const V_INSTANCE_ID: &str = "gr2q7gf5lh6pzfdnurnkvputhm";
1209    const V_AGENT_PUBKEY: &str = "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=";
1210    const V_KEY_FP: &str = "ajgD1fBZkCocba-8m6RykhL3yqwIY0zDrnaydSnwOCc";
1211    const V_CERT_SIG: &str =
1212        "ighbn1y/kyisIolSHwNyRtBqC2u95zQEBtGc3wxwksBUBHrDoUvXmz8yEXY20TFzOBC6IDEsG51WzTNJCrgNAA==";
1213    const V_NEW_INSTANCE_ID: &str = "wyxim75c6m5p4ywv22ywilqwee";
1214    const V_REVOKE_SIG: &str =
1215        "DOQzFIVNGItL3mkN7IPlEk5lBrmM96Dgub7jbL5JmTR5oDnCwWlfKzuYsyvZcUJJMRs56glIBhrDVHIeclqEDg==";
1216    const V_MSG_SIG: &str =
1217        "49VODE2M7pORgWgcQPl2p+M8W2ccaXJ1O8Zu1XeR4qRiJDsshawzq8eMpSkKTz+CJE0CXz2oTlXsNDobpgsRBw==";
1218    const V_ISSUED_AT: i64 = 1_790_000_000;
1219    const V_MSG_TS: i64 = 1_790_000_100;
1220
1221    fn vector_record() -> WanKeyRecord {
1222        let (agent_public_key, _) = generate_wan_keypair([2; 32]);
1223        WanKeyRecord::certify(&[1; 32], "camper", "stable", &agent_public_key, "narko", V_ISSUED_AT).unwrap()
1224    }
1225
1226    fn vector_carried() -> WanCarried<'static> {
1227        WanCarried {
1228            sig: V_MSG_SIG,
1229            msg_id: "msg-1",
1230            ts_secs: V_MSG_TS,
1231            source_agent: "camper",
1232            target_agent: "agent2",
1233            source_host: V_INSTANCE_ID,
1234            source_channel: "stable",
1235            key_fp: V_KEY_FP,
1236        }
1237    }
1238
1239    #[test]
1240    fn w3s_identifiers_and_certificate_match_the_cross_language_vectors() {
1241        let record = vector_record();
1242        assert_eq!(record.instance_pubkey, V_INSTANCE_PUBKEY);
1243        assert_eq!(record.instance_id, V_INSTANCE_ID);
1244        assert_eq!(record.instance_id.len(), WAN_INSTANCE_ID_LEN);
1245        assert_eq!(record.agent_pubkey, V_AGENT_PUBKEY);
1246        assert_eq!(record.key_fp, V_KEY_FP);
1247        assert_eq!(record.key_fp.len(), WAN_KEY_FP_LEN);
1248        assert_eq!(record.cert_sig, V_CERT_SIG);
1249        assert!(record.check_chain().is_some());
1250
1251        let (new_instance_public_key, _) = generate_wan_keypair([3; 32]);
1252        assert_eq!(wan_instance_id(&new_instance_public_key), V_NEW_INSTANCE_ID);
1253        let revocation = WanRevocation::sign(&[1; 32], V_NEW_INSTANCE_ID, 1_790_000_500).unwrap();
1254        assert_eq!(revocation.sig, V_REVOKE_SIG);
1255        assert!(revocation.verify());
1256
1257        let (_, agent_private_key) = generate_wan_keypair([2; 32]);
1258        let msg_sig = sign_wan_jekt(&agent_private_key, "msg-1", "camper", V_INSTANCE_ID, "stable", "agent2", V_MSG_TS, "hello");
1259        assert_eq!(msg_sig.as_deref(), Some(V_MSG_SIG));
1260    }
1261
1262    #[test]
1263    fn base32_matches_rfc4648_lowercased() {
1264        // RFC 4648 §10 test vectors, lowercased and unpadded.
1265        for (input, expected) in
1266            [("", ""), ("f", "my"), ("fo", "mzxq"), ("foo", "mzxw6"), ("foob", "mzxw6yq"), ("fooba", "mzxw6ytb"), ("foobar", "mzxw6ytboi")]
1267        {
1268            assert_eq!(base32_lower_nopad(input.as_bytes()), expected, "input {input:?}");
1269        }
1270    }
1271
1272    #[test]
1273    fn a_certificate_chain_breaks_on_any_substituted_field() {
1274        let good = vector_record();
1275        let (other_public_key, _) = generate_wan_keypair([9; 32]);
1276        let other_b64 = BASE64.encode(other_public_key);
1277        type Mutation<'a> = (&'a str, Box<dyn Fn(&mut WanKeyRecord) + 'a>);
1278        let mutations: Vec<Mutation> = vec![
1279            // A cloud swapping in its own agent key, with a matching fingerprint.
1280            ("agent key", Box::new(|r| {
1281                r.agent_pubkey = other_b64.clone();
1282                r.key_fp = wan_key_fingerprint(&other_public_key);
1283            })),
1284            // A cloud swapping the instance key: the id no longer matches.
1285            ("instance key", Box::new(|r| r.instance_pubkey = other_b64.clone())),
1286            // ...or relabelling the id to match its own key: the cert no longer verifies.
1287            ("instance id + key", Box::new(|r| {
1288                r.instance_pubkey = other_b64.clone();
1289                r.instance_id = wan_instance_id(&other_public_key);
1290            })),
1291            ("fingerprint", Box::new(|r| r.key_fp = wan_key_fingerprint(&other_public_key))),
1292            ("agent id", Box::new(|r| r.agent_id = "lark".into())),
1293            ("uppercased agent id", Box::new(|r| r.agent_id = "Camper".into())),
1294            ("channel", Box::new(|r| r.channel = "beta".into())),
1295            ("host hint", Box::new(|r| r.host_hint = "area54".into())),
1296            ("issued_at", Box::new(|r| r.issued_at += 1)),
1297            ("cert sig", Box::new(|r| r.cert_sig = V_REVOKE_SIG.into())),
1298            ("garbage key", Box::new(|r| r.agent_pubkey = "not base64".into())),
1299        ];
1300        for (name, mutate) in mutations {
1301            let mut record = good.clone();
1302            mutate(&mut record);
1303            assert!(record.check_chain().is_none(), "{name} substitution passed the chain");
1304        }
1305    }
1306
1307    #[test]
1308    fn certify_lowercases_the_agent_id_and_rejects_a_bad_seed() {
1309        let (agent_public_key, _) = generate_wan_keypair([2; 32]);
1310        let record = WanKeyRecord::certify(&[1; 32], "Camper", "stable", &agent_public_key, "narko", V_ISSUED_AT).unwrap();
1311        assert_eq!(record, vector_record());
1312        assert!(WanKeyRecord::certify(&[1; 31], "camper", "stable", &agent_public_key, "narko", 0).is_none());
1313    }
1314
1315    #[test]
1316    fn a_revocation_verifies_only_as_signed_by_the_old_key() {
1317        let good = WanRevocation::sign(&[1; 32], V_NEW_INSTANCE_ID, 1_790_000_500).unwrap();
1318        let mut retargeted = good.clone();
1319        retargeted.new_instance_id = V_INSTANCE_ID.into();
1320        assert!(!retargeted.verify());
1321        let mut redated = good.clone();
1322        redated.revoked_at += 1;
1323        assert!(!redated.verify());
1324        // Someone else's key revoking this instance: the id doesn't match the key.
1325        let mut foreign = WanRevocation::sign(&[9; 32], V_NEW_INSTANCE_ID, 1_790_000_500).unwrap();
1326        foreign.old_instance_id = V_INSTANCE_ID.into();
1327        assert!(!foreign.verify());
1328    }
1329
1330    #[test]
1331    fn freshness_window_boundaries() {
1332        let now = 1_790_000_000;
1333        assert!(wan_sig_is_fresh(now, now));
1334        assert!(wan_sig_is_fresh(now - WAN_SIG_MAX_AGE_SECS, now));
1335        assert!(!wan_sig_is_fresh(now - WAN_SIG_MAX_AGE_SECS - 1, now));
1336        assert!(wan_sig_is_fresh(now + WAN_SIG_MAX_FUTURE_SKEW_SECS, now));
1337        assert!(!wan_sig_is_fresh(now + WAN_SIG_MAX_FUTURE_SKEW_SECS + 1, now));
1338        assert_eq!(WAN_SIG_MAX_AGE_SECS, 2100);
1339        // Extremes saturate instead of overflowing into "fresh".
1340        assert!(!wan_sig_is_fresh(i64::MIN, now));
1341        assert!(!wan_sig_is_fresh(i64::MAX, now));
1342    }
1343
1344    #[test]
1345    fn the_envelope_binds_source_to_the_row_and_target_to_the_polled_agent() {
1346        let carried = vector_carried();
1347        assert_eq!(check_wan_envelope(&carried, "camper", "agent2", V_MSG_TS), Ok(()));
1348        // Trimmed and case-folded, as the cloud normalises (or, for github*, doesn't).
1349        assert_eq!(check_wan_envelope(&carried, " Camper ", "AGENT2", V_MSG_TS), Ok(()));
1350        // A cloud moving a message signed for agent2 into lark's queue.
1351        assert_eq!(check_wan_envelope(&carried, "camper", "lark", V_MSG_TS), Err(WanCheckFailure::EnvelopeMismatch));
1352        assert_eq!(check_wan_envelope(&carried, "clamk", "agent2", V_MSG_TS), Err(WanCheckFailure::EnvelopeMismatch));
1353        // The binding is checked before freshness: a moved stale message is still a mismatch.
1354        assert_eq!(
1355            check_wan_envelope(&carried, "camper", "lark", V_MSG_TS + 10_000),
1356            Err(WanCheckFailure::EnvelopeMismatch)
1357        );
1358        assert_eq!(check_wan_envelope(&carried, "camper", "agent2", V_MSG_TS + 2_101), Err(WanCheckFailure::Stale));
1359        assert_eq!(WanCheckFailure::Stale.verdict(), None);
1360        assert_eq!(WanCheckFailure::EnvelopeMismatch.verdict(), Some(false));
1361    }
1362
1363    #[test]
1364    fn a_carried_message_verifies_against_its_certified_record() {
1365        assert_eq!(verify_wan_against_record(&vector_carried(), &vector_record(), "hello"), Ok(()));
1366    }
1367
1368    #[test]
1369    fn each_carried_field_altered_in_turn_fails() {
1370        let record = vector_record();
1371        let cases: Vec<(&str, WanCarried<'static>, WanCheckFailure)> = vec![
1372            ("msg_id", WanCarried { msg_id: "msg-2", ..vector_carried() }, WanCheckFailure::BadSignature),
1373            ("ts", WanCarried { ts_secs: V_MSG_TS + 1, ..vector_carried() }, WanCheckFailure::BadSignature),
1374            ("target", WanCarried { target_agent: "lark", ..vector_carried() }, WanCheckFailure::BadSignature),
1375            ("sig", WanCarried { sig: V_CERT_SIG, ..vector_carried() }, WanCheckFailure::BadSignature),
1376            ("source", WanCarried { source_agent: "lark", ..vector_carried() }, WanCheckFailure::RecordMismatch),
1377            ("host", WanCarried { source_host: V_NEW_INSTANCE_ID, ..vector_carried() }, WanCheckFailure::RecordMismatch),
1378            ("channel", WanCarried { source_channel: "beta", ..vector_carried() }, WanCheckFailure::RecordMismatch),
1379            ("key_fp", WanCarried { key_fp: "x", ..vector_carried() }, WanCheckFailure::RecordMismatch),
1380        ];
1381        for (name, carried, expected) in cases {
1382            assert_eq!(verify_wan_against_record(&carried, &record, "hello"), Err(expected), "altered {name}");
1383        }
1384        assert_eq!(
1385            verify_wan_against_record(&vector_carried(), &record, "hello!"),
1386            Err(WanCheckFailure::BadSignature)
1387        );
1388    }
1389
1390    #[test]
1391    fn the_record_match_is_ascii_case_insensitive_for_instance_channel_and_agent() {
1392        // A record certified for channel `Stable` and a message signed under
1393        // `stable`: both halves are individually valid, so the only question is
1394        // the §2.3 match, which is case-insensitive.
1395        let (agent_public_key, agent_private_key) = generate_wan_keypair([2; 32]);
1396        let record = WanKeyRecord::certify(&[1; 32], "camper", "Stable", &agent_public_key, "narko", V_ISSUED_AT).unwrap();
1397        let sig = sign_wan_jekt(&agent_private_key, "msg-1", "Camper", V_INSTANCE_ID, "stable", "agent2", V_MSG_TS, "hello").unwrap();
1398        let carried = WanCarried {
1399            sig: &sig,
1400            source_agent: "Camper",
1401            source_channel: "stable",
1402            ..vector_carried()
1403        };
1404        assert_eq!(verify_wan_against_record(&carried, &record, "hello"), Ok(()));
1405    }
1406
1407    #[test]
1408    fn a_tampered_record_is_cert_invalid_before_anything_else() {
1409        let mut record = vector_record();
1410        record.host_hint = "evil".into();
1411        assert_eq!(
1412            verify_wan_against_record(&vector_carried(), &record, "hello"),
1413            Err(WanCheckFailure::CertInvalid)
1414        );
1415    }
1416
1417    #[test]
1418    fn host_hints_and_display_labels() {
1419        assert!(is_valid_wan_host_hint("narko"));
1420        assert!(is_valid_wan_host_hint("host-1.lan"));
1421        for bad in ["", "Narko", "narko~x", "has space", "ümlaut", &"a".repeat(49)] {
1422            assert!(!is_valid_wan_host_hint(bad), "{bad:?}");
1423        }
1424        assert_eq!(wan_instance_display_label("narko", V_INSTANCE_ID), "narko~gr2q7gf5");
1425        // A sender-chosen label that tries to smuggle its own suffix renders as `?`.
1426        assert_eq!(wan_instance_display_label("narko~abcdefgh", V_INSTANCE_ID), "?~gr2q7gf5");
1427    }
1428}
1429
1430/// Cross-version wire compatibility for jekt signatures. The fleet never
1431/// upgrades all at once, so a signature made by one ed25519-dalek major must
1432/// verify on another. Ed25519 signing is deterministic (RFC 8032), so the
1433/// strongest check is byte equality: these goldens were produced by
1434/// ed25519-dalek 2.2.0 (2026-10-01) and must stay identical across upgrades.
1435/// If one changes, older peers would reject the new signatures — that is a
1436/// fleet-breaking change, not a test to update.
1437#[cfg(test)]
1438mod cross_version_goldens {
1439    use super::*;
1440
1441    const SEED: [u8; 32] = [42u8; 32];
1442    const TS: i64 = 1_790_000_000;
1443    const PK: &str = "GX9rI+FshTLGq8g4+s1ep4m+DHaykgM0A5v6iz02jWE=";
1444    const LAN: &str = "EXTYmZi7R4FlXQU5olRQng9i3JvoyPaNk+5hsgz/pwLVYBoIP5/fKSlN8YCAViv/j18Gr9fCp0W9fS2NYrFrAQ==";
1445    const CHAN: &str = "lSTM+FmFR/QsqzmTiVvO8KLa5jmFrnQhpuQ7i543/ezCoeOMaAll+N2NEs2wfL727/vwzOYFDt3Exkk6h7yKCw==";
1446    const WAN: &str = "IeNtT8Ivh6k84poizAS0a1oBzBQsDRteO72vlsviWieBDHu/ET8XZNwjLNlZGFyjMWA4GnbZbOn9S02pvbYjCw==";
1447
1448    fn hex(s: &str) -> Vec<u8> {
1449        (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect()
1450    }
1451
1452    #[test]
1453    fn rfc8032_test_1_matches() {
1454        let seed: [u8; 32] = hex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
1455            .try_into()
1456            .unwrap();
1457        let key = ed25519_dalek::SigningKey::from_bytes(&seed);
1458        assert_eq!(
1459            key.verifying_key().to_bytes().to_vec(),
1460            hex("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a")
1461        );
1462        let sig = ed25519_dalek::Signer::sign(&key, b"");
1463        assert_eq!(
1464            sig.to_bytes().to_vec(),
1465            hex("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b")
1466        );
1467    }
1468
1469    #[test]
1470    fn public_key_matches_golden() {
1471        assert_eq!(BASE64.encode(generate_lan_keypair(SEED).0), PK);
1472    }
1473
1474    #[test]
1475    fn lan_signature_is_byte_identical_and_verifies() {
1476        let sig = sign_lan_jekt(&SEED, "msg-golden", "agentx", "manoz", TS, "hello fleet").unwrap();
1477        assert_eq!(sig, LAN);
1478        let pk = BASE64.decode(PK).unwrap();
1479        assert!(verify_lan_jekt(&pk, "msg-golden", "agentx", "manoz", TS, "hello fleet", LAN));
1480        assert!(!verify_lan_jekt(&pk, "msg-golden", "agentx", "manoz", TS, "hello fleet!", LAN));
1481    }
1482
1483    #[test]
1484    fn channel_signature_is_byte_identical_and_verifies() {
1485        let sig = sign_channel_jekt(&SEED, "msg-golden", "agentx", "local-main", "manoz", TS, "hello fleet").unwrap();
1486        assert_eq!(sig, CHAN);
1487        let pk = BASE64.decode(PK).unwrap();
1488        assert!(verify_channel_jekt(&pk, "msg-golden", "agentx", "local-main", "manoz", TS, "hello fleet", CHAN));
1489    }
1490
1491    #[test]
1492    fn wan_signature_is_byte_identical_and_verifies() {
1493        let sig =
1494            sign_wan_jekt(&SEED, "msg-golden", "agentx", "narko", "stable", "manoz", TS, "hello fleet").unwrap();
1495        assert_eq!(sig, WAN);
1496        let pk = BASE64.decode(PK).unwrap();
1497        assert!(verify_wan_jekt(&pk, "msg-golden", "agentx", "narko", "stable", "manoz", TS, "hello fleet", WAN));
1498    }
1499}