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