Skip to main content

lenso_process_protocol/
lib.rs

1//! Language-neutral source types for `lenso-process-jsonrpc-http-v1`.
2
3use std::cmp::Ordering;
4
5use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8
9mod proof;
10mod strict_json;
11
12/// Runtime-neutral values shared by Authoring V2 execution profiles.
13///
14/// This module does not define a transport envelope. Process and Bun adapters
15/// wrap these values in their own versioned protocols.
16pub mod authoring;
17
18pub use proof::{
19    AuthoringHandshakeProofInput, authoring_callback_proof_message, authoring_child_proof_message,
20    authoring_handshake_proof_payload, authoring_host_proof_message, canonicalize_proof_value,
21    child_proof_message, handshake_params_digest, host_proof_message,
22};
23pub use strict_json::{MAX_STRICT_JSON_NESTING, decode_strict, encode_compact};
24
25/// Exact Process Protocol profile selected by an Adapter.
26pub const PROCESS_PROFILE: &str = "lenso-process-jsonrpc-http-v1";
27/// Portable JSON value profile used by request payloads.
28pub const VALUE_PROFILE: &str = "lenso-json-value-v1";
29/// Mandatory child-provides-request interaction profile.
30pub const PROVIDE_REQUEST_PROFILE: &str = "provide-request-v1";
31/// Control method used once during process startup.
32pub const HANDSHAKE_METHOD: &str = "lenso.process.v1.handshake";
33/// Data method used for one request interaction.
34pub const REQUEST_METHOD: &str = "lenso.process.v1.request";
35/// Control method used for idempotent cancellation.
36pub const CANCEL_METHOD: &str = "lenso.process.v1.cancel";
37/// Control method used for graceful child shutdown.
38pub const SHUTDOWN_METHOD: &str = "lenso.process.v1.shutdown";
39
40/// One bounded readiness record written on the dedicated inherited handle.
41#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
42#[serde(deny_unknown_fields)]
43pub struct ReadinessRecord {
44    /// Exact Process Protocol profile implemented by both listeners.
45    pub protocol: String,
46    /// Ephemeral loopback data-listener port.
47    pub data_port: u16,
48    /// Distinct ephemeral loopback control-listener port.
49    pub control_port: u16,
50}
51
52impl ReadinessRecord {
53    /// Validates the exact profile and two non-zero, distinct ports.
54    pub fn validate(&self) -> Result<(), ProtocolError> {
55        if self.protocol != PROCESS_PROFILE {
56            return Err(ProtocolError::new("unsupported Process Protocol profile"));
57        }
58        if self.data_port == 0 || self.control_port == 0 || self.data_port == self.control_port {
59            return Err(ProtocolError::new(
60                "readiness requires distinct non-zero data and control ports",
61            ));
62        }
63        Ok(())
64    }
65}
66
67/// Error returned when a Process Protocol document is malformed or inconsistent.
68#[derive(Clone, Debug, Eq, PartialEq)]
69pub struct ProtocolError {
70    detail: String,
71}
72
73impl ProtocolError {
74    fn new(detail: impl Into<String>) -> Self {
75        Self {
76            detail: detail.into(),
77        }
78    }
79
80    /// Returns the stable human-readable validation detail.
81    #[must_use]
82    pub fn detail(&self) -> &str {
83        &self.detail
84    }
85}
86
87impl std::fmt::Display for ProtocolError {
88    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        formatter.write_str(&self.detail)
90    }
91}
92
93impl std::error::Error for ProtocolError {}
94
95/// Peer-confirmed limits that must match exactly during handshake.
96#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
97#[serde(deny_unknown_fields)]
98pub struct PeerLimits {
99    /// Maximum encoded data request or response body.
100    pub max_http_body_bytes: u64,
101    /// Maximum encoded control request or response body.
102    pub max_control_http_body_bytes: u64,
103    /// Maximum concurrently active request handlers.
104    pub max_concurrent_requests: u32,
105    /// Maximum queued child data requests.
106    pub child_request_queue_capacity: u32,
107    /// Maximum completed correlation IDs retained in one process session.
108    pub max_retired_correlation_ids: u32,
109    /// Maximum queued control requests, with at least one reserved handler.
110    pub control_queue_capacity: u32,
111}
112
113impl PeerLimits {
114    /// Returns the V1 defaults.
115    #[must_use]
116    pub const fn v1_defaults() -> Self {
117        Self {
118            max_http_body_bytes: 65_536,
119            max_control_http_body_bytes: 16_384,
120            max_concurrent_requests: 32,
121            child_request_queue_capacity: 32,
122            max_retired_correlation_ids: 65_536,
123            control_queue_capacity: 32,
124        }
125    }
126
127    /// Enforces non-zero V1 hard maxima.
128    pub fn validate(&self) -> Result<(), ProtocolError> {
129        validate_limit("max_http_body_bytes", self.max_http_body_bytes, 1_048_576)?;
130        validate_limit(
131            "max_control_http_body_bytes",
132            self.max_control_http_body_bytes,
133            65_536,
134        )?;
135        validate_limit(
136            "max_concurrent_requests",
137            u64::from(self.max_concurrent_requests),
138            256,
139        )?;
140        validate_limit(
141            "child_request_queue_capacity",
142            u64::from(self.child_request_queue_capacity),
143            1_024,
144        )?;
145        validate_limit(
146            "max_retired_correlation_ids",
147            u64::from(self.max_retired_correlation_ids),
148            1_048_576,
149        )?;
150        validate_limit(
151            "control_queue_capacity",
152            u64::from(self.control_queue_capacity),
153            256,
154        )
155    }
156}
157
158/// One exact provided operation in handshake identity.
159#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
160#[serde(deny_unknown_fields)]
161pub struct OperationDescriptor {
162    /// Stable operation name.
163    pub operation: String,
164    /// Exact interaction kind. V1 supports request provision only.
165    pub interaction: InteractionKind,
166}
167
168/// Interaction kinds admitted by the base V1 profile.
169#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
170#[serde(rename_all = "snake_case")]
171pub enum InteractionKind {
172    /// One request with one terminal outcome.
173    Request,
174}
175
176/// One exact provided Capability Descriptor.
177#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
178#[serde(deny_unknown_fields)]
179pub struct CapabilityDescriptor {
180    /// Stable `namespace.name@major` identity.
181    pub capability_id: String,
182    /// Exact Descriptor semantic version.
183    pub descriptor_version: String,
184    /// Canonical Descriptor SHA-256 digest.
185    pub descriptor_digest: String,
186    /// Canonical-sorted operation table.
187    pub operations: Vec<OperationDescriptor>,
188}
189
190/// One exact outbound binding exposed only by a selected consume profile.
191#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
192#[serde(deny_unknown_fields)]
193pub struct OutboundBindingDescriptor {
194    /// Stable binding identity within the Plugin Instance.
195    pub binding_id: String,
196    /// Required Capability identity.
197    pub capability_id: String,
198    /// Exact Descriptor version.
199    pub descriptor_version: String,
200    /// Canonical Descriptor digest.
201    pub descriptor_digest: String,
202    /// Explicit provider Plugin Instance key.
203    pub provider_instance: String,
204}
205
206/// Immutable identity the child must echo exactly during handshake.
207#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
208#[serde(deny_unknown_fields)]
209pub struct HandshakeIdentity {
210    /// Exact transport profile.
211    pub protocol_profile: String,
212    /// Exact portable value profile.
213    pub value_profile: String,
214    /// App-local Plugin Instance key.
215    pub plugin_instance: String,
216    /// Canonical decimal Plugin generation.
217    pub plugin_generation: String,
218    /// Exact App Generation Spec digest.
219    pub generation_spec_digest: String,
220    /// Exact executable Artifact digest.
221    pub artifact_digest: String,
222    /// Exact Effective Host Grant Set digest.
223    pub effective_host_grant_set_digest: String,
224    /// Canonical-sorted exact interaction profiles.
225    pub interaction_profiles: Vec<String>,
226    /// Canonical-sorted provided Capability Descriptors.
227    pub provided_capabilities: Vec<CapabilityDescriptor>,
228    /// Canonical-sorted explicit outbound bindings.
229    pub outbound_bindings: Vec<OutboundBindingDescriptor>,
230    /// Limits both peers must confirm exactly.
231    pub peer_limits: PeerLimits,
232}
233
234/// Host-to-child handshake params.
235#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
236#[serde(deny_unknown_fields)]
237pub struct HandshakeParams {
238    /// Exact identity to admit.
239    pub identity: HandshakeIdentity,
240    /// Canonical base64url encoding of 32 random bytes.
241    pub host_nonce: String,
242    /// Canonical base64url HMAC output.
243    pub host_proof: String,
244}
245
246/// Child-to-host accepted handshake result.
247#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
248#[serde(deny_unknown_fields)]
249pub struct HandshakeResult {
250    /// Exact admitted identity echoed from the request.
251    pub identity: HandshakeIdentity,
252    /// Canonical base64url encoding of 32 random bytes.
253    pub session: String,
254    /// Canonical base64url HMAC output.
255    pub child_proof: String,
256}
257
258/// Portable invocation extension transported without domain interpretation.
259#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
260#[serde(deny_unknown_fields)]
261pub struct InvocationExtension {
262    /// Stable unique extension key.
263    pub key: String,
264    /// Canonical padded Base64 bytes.
265    pub value: String,
266    /// Optional issuing authority.
267    #[serde(skip_serializing_if = "Option::is_none")]
268    pub issuer: Option<String>,
269    /// Canonical-sorted declared audiences.
270    #[serde(default, skip_serializing_if = "Vec::is_empty")]
271    pub audience: Vec<String>,
272    /// Optional opaque proof.
273    #[serde(skip_serializing_if = "Option::is_none")]
274    pub proof: Option<String>,
275    /// Whether the extension value is sealed for its audience.
276    #[serde(default, skip_serializing_if = "is_false")]
277    pub sealed: bool,
278}
279
280/// Host-to-child request params for `provide-request-v1`.
281#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
282#[serde(deny_unknown_fields)]
283pub struct RequestParams {
284    /// Authenticated process session.
285    pub session: String,
286    /// Opaque canonical decimal-string correlation ID.
287    pub correlation_id: String,
288    /// Selected Capability identity.
289    pub capability_id: String,
290    /// Exact selected Descriptor version.
291    pub descriptor_version: String,
292    /// Exact selected Descriptor digest.
293    pub descriptor_digest: String,
294    /// Selected operation.
295    pub operation: String,
296    /// Exact request interaction marker.
297    pub interaction: InteractionKind,
298    /// Host-established caller Plugin Instance, or `null` for host ingress.
299    pub caller_instance: Option<String>,
300    /// Relative remaining budget as decimal nanoseconds, or `null` for none.
301    pub remaining_timeout_nanos: Option<String>,
302    /// Structurally validated portable invocation extensions.
303    #[serde(default)]
304    pub extensions: Vec<InvocationExtension>,
305    /// Capability-defined portable JSON payload.
306    pub payload: Value,
307}
308
309/// Child-to-host request result.
310#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
311#[serde(deny_unknown_fields)]
312pub struct RequestResult {
313    /// Authenticated process session.
314    pub session: String,
315    /// Correlation ID echoed from the request.
316    pub correlation_id: String,
317    /// Exactly one terminal application outcome.
318    pub outcome: ProcessOutcome,
319}
320
321/// Child-originated request outcomes allowed by V1.
322#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
323#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
324pub enum ProcessOutcome {
325    /// Capability success payload.
326    Success { value: Value },
327    /// Capability-defined Domain Error payload.
328    Domain { error: Value },
329    /// Narrow child-originated Runtime Failure.
330    Runtime { failure: ChildRuntimeFailure },
331}
332
333/// Runtime Failures the child is permitted to originate.
334#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
335#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
336pub enum ChildRuntimeFailure {
337    /// The child cannot admit this operation within its declared bound.
338    ResourceExhausted { operation: String },
339    /// The Plugin generation is no longer trustworthy and must be retired.
340    PluginFailure { detail: String },
341}
342
343/// Idempotent cancel params.
344#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
345#[serde(deny_unknown_fields)]
346pub struct CancelParams {
347    /// Authenticated process session.
348    pub session: String,
349    /// Active, retired, or unknown correlation ID.
350    pub correlation_id: String,
351}
352
353/// Graceful shutdown params.
354#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
355#[serde(deny_unknown_fields)]
356pub struct ShutdownParams {
357    /// Authenticated process session.
358    pub session: String,
359}
360
361/// Successful cancel or shutdown acknowledgement.
362#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
363#[serde(deny_unknown_fields)]
364pub struct ControlAck {
365    /// Authenticated process session.
366    pub session: String,
367    /// Always true; cancel does not reveal correlation existence.
368    pub accepted: bool,
369}
370
371/// Strict JSON-RPC request envelope.
372#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
373#[serde(deny_unknown_fields)]
374pub struct JsonRpcRequest<T> {
375    /// Must equal `2.0`.
376    pub jsonrpc: String,
377    /// Canonical decimal-string JSON-RPC ID.
378    pub id: String,
379    /// Exact versioned method.
380    pub method: String,
381    /// Strict method params object.
382    pub params: T,
383}
384
385/// Strict successful JSON-RPC response envelope.
386#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
387#[serde(deny_unknown_fields)]
388pub struct JsonRpcSuccess<T> {
389    /// Must equal `2.0`.
390    pub jsonrpc: String,
391    /// Exact request ID.
392    pub id: String,
393    /// Strict method result object.
394    pub result: T,
395}
396
397/// Strict JSON-RPC 2.0 error object used before a method result exists.
398#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
399#[serde(deny_unknown_fields)]
400pub struct JsonRpcErrorObject {
401    /// Standard JSON-RPC error code.
402    pub code: i32,
403    /// Stable public error message without host or child internals.
404    pub message: String,
405}
406
407/// Strict JSON-RPC 2.0 error response. Parse/invalid-request errors use a null ID.
408#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
409#[serde(deny_unknown_fields)]
410pub struct JsonRpcError {
411    /// Must equal `2.0`.
412    pub jsonrpc: String,
413    /// Exact request ID, or null when the request ID could not be authenticated.
414    pub id: Option<String>,
415    /// Standard error object.
416    pub error: JsonRpcErrorObject,
417}
418
419impl HandshakeIdentity {
420    /// Validates exact profiles, digests, canonical ordering, and V1 limits.
421    pub fn validate(&self) -> Result<(), ProtocolError> {
422        if self.protocol_profile != PROCESS_PROFILE {
423            return Err(ProtocolError::new("unsupported Process Protocol profile"));
424        }
425        if self.value_profile != VALUE_PROFILE {
426            return Err(ProtocolError::new("unsupported portable value profile"));
427        }
428        validate_token("plugin_instance", &self.plugin_instance)?;
429        validate_decimal("plugin_generation", &self.plugin_generation)?;
430        validate_digest("generation_spec_digest", &self.generation_spec_digest)?;
431        validate_digest("artifact_digest", &self.artifact_digest)?;
432        validate_digest(
433            "effective_host_grant_set_digest",
434            &self.effective_host_grant_set_digest,
435        )?;
436        validate_sorted_unique("interaction_profiles", &self.interaction_profiles, Ord::cmp)?;
437        if self.interaction_profiles.as_slice() != [PROVIDE_REQUEST_PROFILE] {
438            return Err(ProtocolError::new(
439                "V1 requires exactly the provide-request-v1 interaction profile",
440            ));
441        }
442        validate_sorted_unique(
443            "provided_capabilities",
444            &self.provided_capabilities,
445            |left, right| left.capability_id.cmp(&right.capability_id),
446        )?;
447        if self.provided_capabilities.is_empty() {
448            return Err(ProtocolError::new(
449                "at least one provided Capability is required",
450            ));
451        }
452        for descriptor in &self.provided_capabilities {
453            descriptor.validate()?;
454        }
455        if !self.outbound_bindings.is_empty() {
456            return Err(ProtocolError::new(
457                "outbound bindings require a selected consume profile",
458            ));
459        }
460        self.peer_limits.validate()
461    }
462}
463
464impl CapabilityDescriptor {
465    fn validate(&self) -> Result<(), ProtocolError> {
466        validate_token("capability_id", &self.capability_id)?;
467        validate_token("descriptor_version", &self.descriptor_version)?;
468        validate_digest("descriptor_digest", &self.descriptor_digest)?;
469        validate_sorted_unique("operations", &self.operations, |left, right| {
470            left.operation.cmp(&right.operation)
471        })?;
472        if self.operations.is_empty() {
473            return Err(ProtocolError::new(
474                "provided Capability operations cannot be empty",
475            ));
476        }
477        for operation in &self.operations {
478            validate_token("operation", &operation.operation)?;
479        }
480        Ok(())
481    }
482}
483
484impl HandshakeParams {
485    /// Validates identity, nonce, and proof encoding.
486    pub fn validate(&self) -> Result<(), ProtocolError> {
487        self.identity.validate()?;
488        decode_base64url_32("host_nonce", &self.host_nonce)?;
489        decode_base64url_32("host_proof", &self.host_proof)?;
490        Ok(())
491    }
492}
493
494impl HandshakeResult {
495    /// Validates the child echo and proof encoding against the expected identity.
496    pub fn validate_against(&self, expected: &HandshakeIdentity) -> Result<(), ProtocolError> {
497        self.identity.validate()?;
498        if &self.identity != expected {
499            return Err(ProtocolError::new("child handshake identity mismatch"));
500        }
501        decode_base64url_32("session", &self.session)?;
502        decode_base64url_32("child_proof", &self.child_proof)?;
503        Ok(())
504    }
505}
506
507impl RequestParams {
508    /// Validates host-owned request envelope fields before payload Schema decoding.
509    pub fn validate(&self) -> Result<(), ProtocolError> {
510        decode_base64url_32("session", &self.session)?;
511        validate_decimal("correlation_id", &self.correlation_id)?;
512        validate_token("capability_id", &self.capability_id)?;
513        validate_token("descriptor_version", &self.descriptor_version)?;
514        validate_digest("descriptor_digest", &self.descriptor_digest)?;
515        validate_token("operation", &self.operation)?;
516        if let Some(caller) = &self.caller_instance {
517            validate_token("caller_instance", caller)?;
518        }
519        if let Some(timeout) = &self.remaining_timeout_nanos {
520            validate_decimal("remaining_timeout_nanos", timeout)?;
521        }
522        validate_sorted_unique("extensions", &self.extensions, |left, right| {
523            left.key.cmp(&right.key)
524        })?;
525        for extension in &self.extensions {
526            extension.validate()?;
527        }
528        Ok(())
529    }
530}
531
532impl InvocationExtension {
533    fn validate(&self) -> Result<(), ProtocolError> {
534        validate_token("extension key", &self.key)?;
535        let decoded = base64::engine::general_purpose::STANDARD
536            .decode(&self.value)
537            .map_err(|_| ProtocolError::new("extension value must be padded Base64"))?;
538        if base64::engine::general_purpose::STANDARD.encode(decoded) != self.value {
539            return Err(ProtocolError::new(
540                "extension value must use canonical padded Base64",
541            ));
542        }
543        validate_sorted_unique("extension audience", &self.audience, |left, right| {
544            left.cmp(right)
545        })?;
546        Ok(())
547    }
548}
549
550impl RequestResult {
551    /// Validates session, correlation, and bounded child Runtime Failure fields.
552    pub fn validate(&self) -> Result<(), ProtocolError> {
553        decode_base64url_32("session", &self.session)?;
554        validate_decimal("correlation_id", &self.correlation_id)?;
555        if let ProcessOutcome::Runtime { failure } = &self.outcome {
556            match failure {
557                ChildRuntimeFailure::ResourceExhausted { operation } => {
558                    validate_token("operation", operation)?;
559                }
560                ChildRuntimeFailure::PluginFailure { detail } => {
561                    if detail.is_empty() || detail.len() > 1_024 {
562                        return Err(ProtocolError::new(
563                            "Plugin Failure detail must contain 1..=1024 bytes",
564                        ));
565                    }
566                }
567            }
568        }
569        Ok(())
570    }
571}
572
573impl CancelParams {
574    /// Validates the authenticated cancel identity.
575    pub fn validate(&self) -> Result<(), ProtocolError> {
576        decode_base64url_32("session", &self.session)?;
577        validate_decimal("correlation_id", &self.correlation_id).map(|_| ())
578    }
579}
580
581impl ShutdownParams {
582    /// Validates the authenticated shutdown identity.
583    pub fn validate(&self) -> Result<(), ProtocolError> {
584        decode_base64url_32("session", &self.session)?;
585        Ok(())
586    }
587}
588
589impl ControlAck {
590    /// Validates an authenticated, affirmative control acknowledgement.
591    pub fn validate(&self) -> Result<(), ProtocolError> {
592        decode_base64url_32("session", &self.session)?;
593        if !self.accepted {
594            return Err(ProtocolError::new(
595                "control acknowledgement must be accepted",
596            ));
597        }
598        Ok(())
599    }
600}
601
602impl<T> JsonRpcRequest<T> {
603    /// Validates the base JSON-RPC envelope and exact expected method.
604    pub fn validate_envelope(&self, expected_method: &str) -> Result<(), ProtocolError> {
605        if self.jsonrpc != "2.0" {
606            return Err(ProtocolError::new("jsonrpc must equal 2.0"));
607        }
608        validate_decimal("JSON-RPC id", &self.id)?;
609        if self.method != expected_method {
610            return Err(ProtocolError::new("unexpected JSON-RPC method"));
611        }
612        Ok(())
613    }
614}
615
616impl<T> JsonRpcSuccess<T> {
617    /// Validates the base JSON-RPC success envelope and expected request ID.
618    pub fn validate_envelope(&self, expected_id: &str) -> Result<(), ProtocolError> {
619        if self.jsonrpc != "2.0" {
620            return Err(ProtocolError::new("jsonrpc must equal 2.0"));
621        }
622        validate_decimal("JSON-RPC id", &self.id)?;
623        if self.id != expected_id {
624            return Err(ProtocolError::new("JSON-RPC response id mismatch"));
625        }
626        Ok(())
627    }
628}
629
630impl JsonRpcError {
631    /// Validates the closed V1 JSON-RPC error surface and optional request ID.
632    pub fn validate(&self) -> Result<(), ProtocolError> {
633        if self.jsonrpc != "2.0" {
634            return Err(ProtocolError::new("jsonrpc must equal 2.0"));
635        }
636        if let Some(id) = &self.id {
637            validate_decimal("JSON-RPC id", id)?;
638        }
639        if !matches!(self.error.code, -32700 | -32600 | -32601 | -32602 | -32603) {
640            return Err(ProtocolError::new("unsupported JSON-RPC error code"));
641        }
642        if self.error.message.is_empty() || self.error.message.len() > 256 {
643            return Err(ProtocolError::new(
644                "JSON-RPC error message must contain 1..=256 bytes",
645            ));
646        }
647        Ok(())
648    }
649}
650
651fn validate_limit(name: &str, value: u64, maximum: u64) -> Result<(), ProtocolError> {
652    if value == 0 || value > maximum {
653        return Err(ProtocolError::new(format!(
654            "{name} must be within 1..={maximum}"
655        )));
656    }
657    Ok(())
658}
659
660fn validate_token(name: &str, value: &str) -> Result<(), ProtocolError> {
661    if value.is_empty()
662        || value.len() > 256
663        || !value.bytes().all(|byte| {
664            byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'@' | b'/' | b':')
665        })
666    {
667        return Err(ProtocolError::new(format!(
668            "{name} must be a 1..=256 byte portable token"
669        )));
670    }
671    Ok(())
672}
673
674fn validate_decimal(name: &str, value: &str) -> Result<u64, ProtocolError> {
675    if value.is_empty()
676        || (value.len() > 1 && value.starts_with('0'))
677        || !value.bytes().all(|byte| byte.is_ascii_digit())
678    {
679        return Err(ProtocolError::new(format!(
680            "{name} must be a canonical non-negative decimal string"
681        )));
682    }
683    value.parse::<u64>().map_err(|_| {
684        ProtocolError::new(format!(
685            "{name} exceeds the unsigned 64-bit decimal profile"
686        ))
687    })
688}
689
690fn validate_digest(name: &str, value: &str) -> Result<(), ProtocolError> {
691    let Some(hex) = value.strip_prefix("sha256:") else {
692        return Err(ProtocolError::new(format!(
693            "{name} must use a sha256: prefix"
694        )));
695    };
696    if hex.len() != 64
697        || !hex
698            .bytes()
699            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
700    {
701        return Err(ProtocolError::new(format!(
702            "{name} must contain 64 lowercase hexadecimal characters"
703        )));
704    }
705    Ok(())
706}
707
708fn decode_base64url_32(name: &str, value: &str) -> Result<[u8; 32], ProtocolError> {
709    let decoded = URL_SAFE_NO_PAD
710        .decode(value)
711        .map_err(|_| ProtocolError::new(format!("{name} must be canonical base64url")))?;
712    let decoded: [u8; 32] = decoded
713        .try_into()
714        .map_err(|_| ProtocolError::new(format!("{name} must encode exactly 32 bytes")))?;
715    if URL_SAFE_NO_PAD.encode(decoded) != value {
716        return Err(ProtocolError::new(format!(
717            "{name} must be canonical unpadded base64url"
718        )));
719    }
720    Ok(decoded)
721}
722
723fn validate_sorted_unique<T>(
724    name: &str,
725    values: &[T],
726    compare: impl Fn(&T, &T) -> Ordering,
727) -> Result<(), ProtocolError> {
728    if values
729        .windows(2)
730        .any(|pair| compare(&pair[0], &pair[1]) != Ordering::Less)
731    {
732        return Err(ProtocolError::new(format!(
733            "{name} must be strictly canonical-sorted and unique"
734        )));
735    }
736    Ok(())
737}
738
739#[allow(clippy::trivially_copy_pass_by_ref)]
740const fn is_false(value: &bool) -> bool {
741    !*value
742}