Skip to main content

core_api/
lib.rs

1#![allow(clippy::derivable_impls, clippy::should_implement_trait)]
2
3pub mod client_identity;
4mod delivery;
5pub mod execution_budget;
6pub mod extension_preview;
7pub mod extension_sources;
8mod external_rpc;
9pub mod host;
10pub mod ingress;
11pub mod interaction_flow;
12pub mod local_client;
13pub mod messaging;
14pub mod node;
15mod node_commissioning;
16mod node_metadata;
17mod node_service;
18pub mod plugin_preview;
19pub mod resource_transfer;
20pub mod runtime_space;
21pub mod space_access;
22pub mod timeouts;
23pub mod webhook;
24pub use node_commissioning::*;
25mod recipient;
26mod storage;
27mod storage_backend;
28
29pub use delivery::*;
30pub use external_rpc::*;
31pub use node_metadata::*;
32pub use node_service::*;
33pub use recipient::*;
34pub use storage::*;
35pub use storage_backend::*;
36
37pub use runtime_paths::RuntimeEnv;
38use serde::{Deserialize, Serialize};
39use std::str::FromStr;
40
41/// Shared MWS transport limits. Both websocket peers must apply these values so
42/// an envelope accepted by one side is never rejected solely due to asymmetric
43/// transport configuration.
44pub const MWS_MAX_MESSAGE_SIZE: usize = 2 * 1024 * 1024;
45pub const MWS_MAX_FRAME_SIZE: usize = 2 * 1024 * 1024;
46pub const MWS_MAX_WRITE_BUFFER_SIZE: usize = 32 * 1024 * 1024;
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
49pub enum ExceptionCode {
50    Unsupported,
51    NullData,
52    ErrorSubscribe,
53    ErrorUnsubscribe,
54    ErrorProcessDataReport,
55    ErrorProcessDataPoll,
56    ErrorLock,
57    ErrorUnlock,
58    FunctionNoImpl,
59    Unreachable,
60    Unauthenticated,
61    Unauthorized,
62    PreconditionFail,
63    SessionExpired,
64    Internal,
65    Unknown,
66    NotFound,
67    AlreadyExists,
68    BadRequest,
69    InvalidWidgetDefinition,
70    DeadlineExceeded,
71    TemporaryUnavailable,
72    ResourceLocked,
73    WsConnectionLost,
74    BillAutomationExceed,
75    BillTokenExceed,
76    MissingContext,
77}
78
79impl ExceptionCode {
80    pub fn from_str(s: &str) -> Self {
81        match s {
82            "UNSUPPORTED" => Self::Unsupported,
83            "NULL_DATA" => Self::NullData,
84            "ERROR_SUBSCRIBE" => Self::ErrorSubscribe,
85            "ERROR_UNSUBSCRIBE" => Self::ErrorUnsubscribe,
86            "ERROR_PROCESS_DATA_REPORT" => Self::ErrorProcessDataReport,
87            "ERROR_PROCESS_DATA_POLL" => Self::ErrorProcessDataPoll,
88            "ERROR_LOCK" => Self::ErrorLock,
89            "ERROR_UNLOCK" => Self::ErrorUnlock,
90            "FUNCTION_NO_IMPL" => Self::FunctionNoImpl,
91            "UNREACHABLE" => Self::Unreachable,
92            "UNAUTHENTICATED" => Self::Unauthenticated,
93            "UNAUTHORIZED" => Self::Unauthorized,
94            "PRECONDITION_FAIL" => Self::PreconditionFail,
95            "SESSION_EXPIRED" => Self::SessionExpired,
96            "INTERNAL" => Self::Internal,
97            "NOT_FOUND" => Self::NotFound,
98            "ALREADY_EXISTS" => Self::AlreadyExists,
99            "BAD_REQUEST" => Self::BadRequest,
100            "INVALID_WIDGET_DEFINITION" => Self::InvalidWidgetDefinition,
101            "DEADLINE_EXCEEDED" => Self::DeadlineExceeded,
102            "TEMPORARY_UNAVAILABLE" => Self::TemporaryUnavailable,
103            "RESOURCE_LOCKED" => Self::ResourceLocked,
104            "WS_CONNECTION_LOST" => Self::WsConnectionLost,
105            "BILL_AUTOMATION_EXCEED" => Self::BillAutomationExceed,
106            "BILL_TOKEN_EXCEED" => Self::BillTokenExceed,
107            "MISSING_CONTEXT" => Self::MissingContext,
108            _ => Self::Unknown,
109        }
110    }
111
112    pub fn as_str(&self) -> &'static str {
113        match self {
114            Self::Unsupported => "UNSUPPORTED",
115            Self::NullData => "NULL_DATA",
116            Self::ErrorSubscribe => "ERROR_SUBSCRIBE",
117            Self::ErrorUnsubscribe => "ERROR_UNSUBSCRIBE",
118            Self::ErrorProcessDataReport => "ERROR_PROCESS_DATA_REPORT",
119            Self::ErrorProcessDataPoll => "ERROR_PROCESS_DATA_POLL",
120            Self::ErrorLock => "ERROR_LOCK",
121            Self::ErrorUnlock => "ERROR_UNLOCK",
122            Self::FunctionNoImpl => "FUNCTION_NO_IMPL",
123            Self::Unreachable => "UNREACHABLE",
124            Self::Unauthenticated => "UNAUTHENTICATED",
125            Self::Unauthorized => "UNAUTHORIZED",
126            Self::PreconditionFail => "PRECONDITION_FAIL",
127            Self::SessionExpired => "SESSION_EXPIRED",
128            Self::Internal => "INTERNAL",
129            Self::Unknown => "UNKNOWN",
130            Self::NotFound => "NOT_FOUND",
131            Self::AlreadyExists => "ALREADY_EXISTS",
132            Self::BadRequest => "BAD_REQUEST",
133            Self::InvalidWidgetDefinition => "INVALID_WIDGET_DEFINITION",
134            Self::DeadlineExceeded => "DEADLINE_EXCEEDED",
135            Self::TemporaryUnavailable => "TEMPORARY_UNAVAILABLE",
136            Self::ResourceLocked => "RESOURCE_LOCKED",
137            Self::WsConnectionLost => "WS_CONNECTION_LOST",
138            Self::BillAutomationExceed => "BILL_AUTOMATION_EXCEED",
139            Self::BillTokenExceed => "BILL_TOKEN_EXCEED",
140            Self::MissingContext => "MISSING_CONTEXT",
141        }
142    }
143}
144
145impl From<ExceptionCode> for String {
146    fn from(value: ExceptionCode) -> Self {
147        value.as_str().to_string()
148    }
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
152pub struct ErrorResponse {
153    pub error: String,
154    pub message: String,
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub details: Option<serde_json::Value>,
157}
158
159impl ErrorResponse {
160    pub fn new(error_code: impl Into<String>, message: impl Into<String>) -> Self {
161        Self {
162            error: error_code.into(),
163            message: message.into(),
164            details: None,
165        }
166    }
167
168    pub fn with_details(mut self, details: serde_json::Value) -> Self {
169        self.details = Some(details);
170        self
171    }
172}
173
174pub struct ClientIds;
175
176impl ClientIds {
177    pub fn from_cloud(peer_id: &str, ws_id: &str) -> String {
178        format!("C:{}:{}", peer_id, ws_id)
179    }
180
181    pub fn from_local(ws_id: &str) -> String {
182        format!("L:{}", ws_id)
183    }
184
185    pub fn from_telegram(bot_id: &str, chat_id: i64) -> String {
186        format!("M:telegram:{}:{}", bot_id, chat_id)
187    }
188
189    pub fn is_cloud(client_id: &str) -> bool {
190        client_id.starts_with("C:")
191    }
192
193    pub fn is_local(client_id: &str) -> bool {
194        client_id.starts_with("L:")
195    }
196
197    pub fn is_telegram(client_id: &str) -> bool {
198        client_id.starts_with("M:telegram:")
199    }
200
201    pub fn is_messaging(client_id: &str) -> bool {
202        client_id.starts_with("M:")
203    }
204
205    pub fn to_telegram_bot_id(client_id: &str) -> Option<i64> {
206        let parts: Vec<&str> = client_id.splitn(6, ':').collect();
207        parts.get(2)?.parse::<i64>().ok()
208    }
209
210    pub fn to_telegram_chat_id(client_id: &str) -> Option<i64> {
211        let parts: Vec<&str> = client_id.splitn(6, ':').collect();
212        parts.get(3)?.parse::<i64>().ok()
213    }
214
215    pub fn to_peer_id(client_id: &str) -> Option<String> {
216        let parts: Vec<&str> = client_id.splitn(3, ':').collect();
217        parts.get(1).map(|s| s.to_string())
218    }
219
220    pub fn to_device_id(client_id: &str) -> Option<String> {
221        let parts: Vec<&str> = client_id.splitn(3, ':').collect();
222        parts.get(1).map(|s| s.to_string())
223    }
224}
225
226pub struct MwsMessageType;
227
228impl MwsMessageType {
229    pub const HUB_REQ: &'static str = "hrq";
230    pub const HUB_RESP: &'static str = "hrp";
231    pub const HUB_DATA: &'static str = "hd";
232    pub const NODE_REQ: &'static str = "nrq";
233    pub const NODE_RESP: &'static str = "nrp";
234    pub const NODE_DATA: &'static str = "nd";
235    pub const AGENT_REQ: &'static str = "grq";
236    pub const AGENT_RESP: &'static str = "grp";
237    pub const AGENT_DATA: &'static str = "gd";
238    pub const CLOUD_REQ: &'static str = "crq";
239    pub const CLOUD_RESP: &'static str = "crp";
240    pub const CLOUD_DATA: &'static str = "cd";
241    pub const APP_REQ: &'static str = "arq";
242    pub const APP_RESP: &'static str = "arp";
243    pub const SERVER_REQ: &'static str = "srq";
244    pub const SERVER_RESP: &'static str = "srp";
245    pub const APP_DATA: &'static str = "ad";
246    pub const SERVER_DATA: &'static str = "sd";
247}
248
249pub struct MwsSource;
250
251impl MwsSource {
252    pub const IOS: &'static str = "ios";
253    pub const ANDROID: &'static str = "android";
254    pub const WINDOWS: &'static str = "windows";
255    pub const MAC: &'static str = "macos";
256    pub const LINUX: &'static str = "linux";
257    pub const WEB: &'static str = "web";
258    pub const MESSAGING: &'static str = "messaging";
259
260    pub fn is_desktop(source: &str) -> bool {
261        matches!(source, Self::MAC | Self::WINDOWS | Self::LINUX)
262    }
263}
264
265#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
266#[serde(rename_all = "camelCase")]
267pub struct MwsClientInfo {
268    #[serde(skip_serializing_if = "Option::is_none")]
269    pub client_id: Option<String>,
270    #[serde(skip_serializing_if = "Option::is_none")]
271    pub user_id: Option<String>,
272}
273
274impl MwsClientInfo {
275    pub fn new(client_id: String, user_id: String) -> Self {
276        Self {
277            client_id: Some(client_id),
278            user_id: Some(user_id),
279        }
280    }
281
282    pub fn from_ws_id(ws_id: String) -> Self {
283        Self {
284            client_id: Some(ClientIds::from_local(&ws_id)),
285            user_id: None,
286        }
287    }
288
289    pub fn from_client_id(client_id: String) -> Self {
290        Self {
291            client_id: Some(client_id),
292            user_id: None,
293        }
294    }
295
296    pub fn to_client_id(&self) -> String {
297        self.client_id
298            .clone()
299            .unwrap_or_else(|| ClientIds::from_local("unknown"))
300    }
301}
302
303#[derive(Debug, Clone, Serialize, Deserialize)]
304#[serde(rename_all = "camelCase")]
305pub struct MwsMessage {
306    #[serde(skip_serializing_if = "Option::is_none")]
307    pub scope_id: Option<String>,
308    #[serde(skip_serializing_if = "Option::is_none")]
309    pub from: Option<String>,
310    #[serde(skip_serializing_if = "Option::is_none")]
311    pub target: Option<String>,
312    #[serde(skip_serializing_if = "Option::is_none")]
313    pub sig: Option<String>,
314    #[serde(skip_serializing_if = "Option::is_none")]
315    pub r#type: Option<String>,
316    #[serde(skip_serializing_if = "Option::is_none")]
317    pub payload: Option<String>,
318    /// Transport-owned lifecycle data.  It is deliberately separate from the
319    /// application payload so schema request bodies never become a framework
320    /// envelope.
321    #[serde(skip_serializing_if = "Option::is_none")]
322    pub control: Option<String>,
323    #[serde(skip_serializing_if = "Option::is_none")]
324    pub error: Option<ErrorResponse>,
325    #[serde(skip_serializing_if = "Option::is_none")]
326    pub client_info: Option<MwsClientInfo>,
327}
328
329impl MwsMessage {
330    pub fn create(
331        scope_id: Option<String>,
332        target: String,
333        sig: String,
334        payload: String,
335        msg_type: String,
336    ) -> Self {
337        Self {
338            scope_id,
339            target: Some(target),
340            sig: Some(sig),
341            payload: Some(payload),
342            control: None,
343            r#type: Some(msg_type),
344            from: None,
345            error: None,
346            client_info: None,
347        }
348    }
349
350    pub fn dummy() -> Self {
351        Self {
352            scope_id: None,
353            from: None,
354            target: None,
355            sig: None,
356            r#type: None,
357            payload: None,
358            control: None,
359            error: None,
360            client_info: None,
361        }
362    }
363
364    pub fn server_response(
365        target: String,
366        sig: String,
367        payload: String,
368        client_info: MwsClientInfo,
369    ) -> Self {
370        Self {
371            scope_id: None,
372            from: None,
373            target: Some(target),
374            sig: Some(sig),
375            r#type: Some(MwsMessageType::SERVER_RESP.to_string()),
376            payload: Some(payload),
377            control: None,
378            error: None,
379            client_info: Some(client_info),
380        }
381    }
382
383    pub fn server_response_error(
384        target: String,
385        sig: String,
386        error: ErrorResponse,
387        client_info: MwsClientInfo,
388    ) -> Self {
389        Self {
390            scope_id: None,
391            from: None,
392            target: Some(target),
393            sig: Some(sig),
394            r#type: Some(MwsMessageType::SERVER_RESP.to_string()),
395            payload: None,
396            control: None,
397            error: Some(error),
398            client_info: Some(client_info),
399        }
400    }
401
402    pub fn unscoped_server_data(
403        target: String,
404        payload: String,
405        client_info: MwsClientInfo,
406    ) -> Self {
407        Self {
408            scope_id: None,
409            from: None,
410            target: Some(target),
411            sig: None,
412            r#type: Some(MwsMessageType::SERVER_DATA.to_string()),
413            payload: Some(payload),
414            control: None,
415            error: None,
416            client_info: Some(client_info),
417        }
418    }
419
420    pub fn scoped_server_data(
421        scope_id: String,
422        target: String,
423        payload: String,
424        client_info: Option<MwsClientInfo>,
425    ) -> Self {
426        Self {
427            scope_id: Some(scope_id),
428            from: None,
429            target: Some(target),
430            sig: None,
431            r#type: Some(MwsMessageType::SERVER_DATA.to_string()),
432            payload: Some(payload),
433            control: None,
434            error: None,
435            client_info,
436        }
437    }
438
439    pub fn hub_response(
440        target: String,
441        sig: String,
442        payload: String,
443        client_info: MwsClientInfo,
444    ) -> Self {
445        Self {
446            scope_id: None,
447            from: None,
448            target: Some(target),
449            sig: Some(sig),
450            r#type: Some(MwsMessageType::HUB_RESP.to_string()),
451            payload: Some(payload),
452            control: None,
453            error: None,
454            client_info: Some(client_info),
455        }
456    }
457
458    pub fn hub_response_error(
459        target: String,
460        sig: String,
461        error: ErrorResponse,
462        client_info: MwsClientInfo,
463    ) -> Self {
464        Self {
465            scope_id: None,
466            from: None,
467            target: Some(target),
468            sig: Some(sig),
469            r#type: Some(MwsMessageType::HUB_RESP.to_string()),
470            payload: None,
471            control: None,
472            error: Some(error),
473            client_info: Some(client_info),
474        }
475    }
476
477    pub fn hub_request(
478        scope_id: Option<String>,
479        target: String,
480        sig: String,
481        payload: String,
482    ) -> Self {
483        Self::hub_request_with_control(scope_id, target, sig, payload, None)
484    }
485
486    pub fn hub_request_with_control(
487        scope_id: Option<String>,
488        target: String,
489        sig: String,
490        payload: String,
491        control: Option<String>,
492    ) -> Self {
493        Self {
494            scope_id,
495            from: None,
496            target: Some(target),
497            sig: Some(sig),
498            r#type: Some(MwsMessageType::HUB_REQ.to_string()),
499            payload: Some(payload),
500            control,
501            error: None,
502            client_info: None,
503        }
504    }
505
506    pub fn hub_data(
507        scope_id: Option<String>,
508        target: String,
509        sig: String,
510        payload: String,
511    ) -> Self {
512        Self {
513            scope_id,
514            from: None,
515            target: Some(target),
516            sig: Some(sig),
517            r#type: Some(MwsMessageType::HUB_DATA.to_string()),
518            payload: Some(payload),
519            control: None,
520            error: None,
521            client_info: None,
522        }
523    }
524
525    pub fn set_from(&mut self, from: String) {
526        self.from = Some(from);
527    }
528
529    pub fn set_target(&mut self, target: String) {
530        self.target = Some(target);
531    }
532
533    pub fn set_sig(&mut self, sig: String) {
534        self.sig = Some(sig);
535    }
536
537    pub fn set_payload(&mut self, payload: String) {
538        self.payload = Some(payload);
539    }
540
541    pub fn set_type(&mut self, msg_type: String) {
542        self.r#type = Some(msg_type);
543    }
544
545    pub fn set_client_info(&mut self, client_info: MwsClientInfo) {
546        self.client_info = Some(client_info);
547    }
548}
549
550impl Default for MwsMessage {
551    fn default() -> Self {
552        Self::dummy()
553    }
554}
555
556#[derive(Debug, Clone, Serialize, Deserialize)]
557#[serde(rename_all = "camelCase")]
558pub struct NodeAuthRequest {
559    /// Publisher-signed evidence for this running release, checked before auth succeeds.
560    pub metadata: NodeMetadata,
561    /// Revision of this Node type's Core-facing contract, independent of package versions.
562    #[serde(default, skip_serializing_if = "Option::is_none")]
563    pub core_protocol_version: Option<u32>,
564    pub hub_id: String,
565    pub token: String,
566    pub node_type: String,
567    #[serde(default)]
568    pub node_id: String,
569    #[serde(default, skip_serializing_if = "Option::is_none")]
570    pub scope_id: Option<String>,
571    pub host_id: String,
572    #[serde(default, skip_serializing_if = "Option::is_none")]
573    pub host_name: Option<String>,
574    pub fingerprint: String,
575}
576
577#[derive(Debug, Clone, Serialize, Deserialize)]
578#[serde(rename_all = "camelCase")]
579pub struct NodeAuthResponse {
580    /// Exact release admitted by this authentication. Required when `ok` is true.
581    /// Transports carry this snapshot into connection registration unchanged.
582    #[serde(default, skip_serializing_if = "Option::is_none")]
583    pub binding_metadata: Option<NodeBindingMetadata>,
584    /// Echoed only after the actual Core accepts the Node contract revision.
585    #[serde(default, skip_serializing_if = "Option::is_none")]
586    pub core_protocol_version: Option<u32>,
587    pub ok: bool,
588    #[serde(skip_serializing_if = "Option::is_none")]
589    pub session_id: Option<String>,
590    #[serde(skip_serializing_if = "Option::is_none")]
591    pub hub_id: Option<String>,
592    #[serde(skip_serializing_if = "Option::is_none")]
593    pub tenant_id: Option<String>,
594    #[serde(skip_serializing_if = "Option::is_none")]
595    pub scope_id: Option<String>,
596    #[serde(skip_serializing_if = "Option::is_none")]
597    pub error: Option<String>,
598    #[serde(skip_serializing_if = "Option::is_none")]
599    pub error_code: Option<String>,
600    #[serde(skip_serializing_if = "Option::is_none")]
601    pub recovery_action: Option<String>,
602    #[serde(skip_serializing_if = "Option::is_none")]
603    pub node_id: Option<String>,
604}
605
606impl NodeAuthResponse {
607    /// Check the Core's acknowledgement before opening business traffic or registering
608    /// a connection. Publisher trust is verified by Core, not by this transport helper.
609    pub fn admitted_metadata(
610        &self,
611        request: &NodeAuthRequest,
612    ) -> Result<&NodeBindingMetadata, String> {
613        let metadata = self
614            .binding_metadata
615            .as_ref()
616            .ok_or("Core did not acknowledge the Node release")?;
617        if !self.ok
618            || self.core_protocol_version != request.core_protocol_version
619            || metadata.core_protocol != request.core_protocol_version
620            || metadata.definition.node_type != request.node_type
621            || metadata.definition.service_id != request.metadata.service_id
622            || metadata.delivery != request.metadata.delivery
623            || metadata.version != request.metadata.service_version
624            || metadata.source != request.metadata.source.kind()
625            || metadata.manifest_sha256 != request.metadata.source.manifest_sha256()
626        {
627            return Err("Core did not acknowledge this Node release and contract revision".into());
628        }
629        Ok(metadata)
630    }
631}
632
633#[derive(Debug, Clone, Serialize, Deserialize)]
634#[serde(rename_all = "camelCase")]
635pub struct NodeTokenIssueRequest {
636    pub transaction_id: String,
637    pub node_type: String,
638    pub candidate_host_id: String,
639    pub candidate_fingerprint: String,
640    pub challenge: NodeChallengeEvidence,
641    pub metadata: NodeMetadata,
642}
643
644#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
645#[serde(rename_all = "camelCase")]
646pub enum NodeInstancePolicy {
647    Multiple,
648    Singleton,
649    Shared,
650}
651
652impl NodeInstancePolicy {
653    pub fn as_str(self) -> &'static str {
654        match self {
655            Self::Multiple => "multiple",
656            Self::Singleton => "singleton",
657            Self::Shared => "shared",
658        }
659    }
660}
661
662impl Default for NodeInstancePolicy {
663    fn default() -> Self {
664        Self::Multiple
665    }
666}
667
668impl std::fmt::Display for NodeInstancePolicy {
669    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
670        f.write_str(self.as_str())
671    }
672}
673
674impl FromStr for NodeInstancePolicy {
675    type Err = String;
676
677    fn from_str(value: &str) -> Result<Self, Self::Err> {
678        match value.trim() {
679            "multiple" | "Multiple" => Ok(Self::Multiple),
680            "singleton" | "Singleton" => Ok(Self::Singleton),
681            "shared" | "Shared" => Ok(Self::Shared),
682            other => Err(format!("unsupported node instance policy: {other}")),
683        }
684    }
685}
686
687#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
688#[serde(rename_all = "camelCase")]
689pub enum NodeBindingStatus {
690    Pending,
691    Active,
692    Revoked,
693    Expired,
694    Failed,
695}
696
697impl NodeBindingStatus {
698    pub fn as_str(self) -> &'static str {
699        match self {
700            Self::Pending => "pending",
701            Self::Active => "active",
702            Self::Revoked => "revoked",
703            Self::Expired => "expired",
704            Self::Failed => "failed",
705        }
706    }
707}
708
709impl Default for NodeBindingStatus {
710    fn default() -> Self {
711        Self::Active
712    }
713}
714
715impl std::fmt::Display for NodeBindingStatus {
716    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
717        f.write_str(self.as_str())
718    }
719}
720
721impl FromStr for NodeBindingStatus {
722    type Err = String;
723
724    fn from_str(value: &str) -> Result<Self, Self::Err> {
725        match value.trim() {
726            "pending" | "Pending" => Ok(Self::Pending),
727            "active" | "Active" => Ok(Self::Active),
728            "revoked" | "Revoked" => Ok(Self::Revoked),
729            "expired" | "Expired" => Ok(Self::Expired),
730            "failed" | "Failed" => Ok(Self::Failed),
731            other => Err(format!("unsupported node binding status: {other}")),
732        }
733    }
734}
735
736pub const NODE_ONBOARDING_CHALLENGE_PROTOCOL: &str = "meow.node.onboarding.challenge";
737pub const NODE_ONBOARDING_CHALLENGE_AUDIENCE: &str = "meow-core:node-onboarding";
738pub const NODE_ONBOARDING_CHALLENGE_ALGORITHM: &str = "Ed25519";
739pub const NODE_ONBOARDING_TOKEN_ISSUER_PREFIX: &str = "meow-core:hub:";
740pub const NODE_ONBOARDING_TOKEN_AUDIENCE: &str = "meow-node:onboarding";
741pub const NODE_ONBOARDING_ES256_ALGORITHM: &str = "ES256";
742pub const NODE_ONBOARDING_TRANSACTION_TTL_SECONDS: u64 = 5 * 60;
743pub const NODE_ONBOARDING_START_TARGET: &str = "/identity/node/onboarding/start";
744pub const NODE_TOKEN_ISSUE_TARGET: &str = "/identity/node/issue";
745pub const NODE_TOKEN_REVOKE_TARGET: &str = "/identity/node/revoke";
746pub const NODE_TOKEN_LIST_TARGET: &str = "/identity/node/list";
747pub const HUB_CONNECTION_PROOF_TARGET: &str = "/identity/hub/prove";
748pub const HUB_CONNECTION_PROOF_PROTOCOL: &str = "meow.hub.connection.proof.v1";
749
750#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
751#[serde(rename_all = "camelCase", deny_unknown_fields)]
752pub struct NodeOnboardingStartRequest {
753    pub node_type: String,
754    pub candidate_host_id: String,
755    pub candidate_fingerprint: String,
756    pub idempotency_key: String,
757}
758
759#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
760#[serde(rename_all = "camelCase", deny_unknown_fields)]
761pub struct NodeOnboardingStartResponse {
762    pub transaction_id: String,
763    pub nonce: String,
764    pub expires_at: i64,
765}
766
767#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
768#[serde(rename_all = "camelCase")]
769pub struct HubConnectionProofRequest {
770    #[serde(default, skip_serializing_if = "RuntimeEnv::is_prod")]
771    pub env: RuntimeEnv,
772    pub protocol: String,
773    pub hub_id: String,
774    pub tenant_id: String,
775    pub scope_id: String,
776    pub nonce: String,
777}
778
779#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
780#[serde(rename_all = "camelCase")]
781pub struct HubConnectionProofResponse {
782    #[serde(default, skip_serializing_if = "RuntimeEnv::is_prod")]
783    pub env: RuntimeEnv,
784    pub protocol: String,
785    pub hub_id: String,
786    pub tenant_id: String,
787    pub scope_id: String,
788    pub nonce: String,
789    pub key_id: String,
790    pub signature: String,
791}
792
793/// Canonical, domain-separated bytes signed by the Hub for one physical WS connection.
794/// Length prefixes keep the encoding unambiguous without relying on JSON object ordering.
795pub fn hub_connection_proof_signing_payload(request: &HubConnectionProofRequest) -> Vec<u8> {
796    let fields = [
797        request.protocol.as_str(),
798        request.hub_id.as_str(),
799        request.tenant_id.as_str(),
800        request.scope_id.as_str(),
801        request.nonce.as_str(),
802    ];
803    let mut payload = Vec::new();
804    for field in fields {
805        payload.extend_from_slice(&(field.len() as u64).to_be_bytes());
806        payload.extend_from_slice(field.as_bytes());
807    }
808    if !request.env.is_prod() {
809        let field = request.env.as_str();
810        payload.extend_from_slice(&(field.len() as u64).to_be_bytes());
811        payload.extend_from_slice(field.as_bytes());
812    }
813    payload
814}
815
816#[derive(Debug, Clone, Serialize, Deserialize)]
817#[serde(rename_all = "camelCase")]
818pub struct NodeChallengeEvidence {
819    pub protocol: String,
820    pub algorithm: String,
821    pub payload: String,
822    pub signature: String,
823    pub public_key: String,
824    pub fingerprint: String,
825}
826
827#[derive(Debug, Clone, Serialize, Deserialize)]
828#[serde(rename_all = "camelCase")]
829pub struct NodeChallengePayload {
830    pub runtime_space_policy: runtime_space::RuntimeSpacePolicy,
831    #[serde(default, skip_serializing_if = "RuntimeEnv::is_prod")]
832    pub env: RuntimeEnv,
833    /// TLS key of the Host running this Node, covered by the Node signature.
834    #[serde(default, skip_serializing_if = "Option::is_none")]
835    pub host_public_key: Option<host::auth::PublicKey>,
836    pub protocol: String,
837    pub aud: String,
838    pub nonce: String,
839    pub scope_id: String,
840    pub node_type: String,
841    pub host_id: String,
842    pub fingerprint: String,
843    pub service_instance_id: String,
844    /// Actual running version and exact publisher manifest, bound to this nonce.
845    pub service_version: String,
846    pub manifest_sha256: String,
847    pub instance_policy: NodeInstancePolicy,
848    pub instance_slot: String,
849}
850
851#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
852#[serde(rename_all = "camelCase")]
853pub struct NodeTokenIssueResponse {
854    pub token: String,
855    pub node_id: String,
856    pub expires_in: i64,
857    pub hub_id: String,
858}
859
860#[derive(Debug, Clone, Serialize, Deserialize)]
861#[serde(rename_all = "camelCase")]
862pub struct NodeTokenRevokeRequest {
863    pub node_type: String,
864    #[serde(default, skip_serializing_if = "Option::is_none")]
865    pub node_id: Option<String>,
866}
867
868#[derive(Debug, Clone, Serialize, Deserialize)]
869#[serde(rename_all = "camelCase")]
870pub struct NodeTokenRevokeResponse {
871    pub success: bool,
872}
873
874#[derive(Debug, Clone, Serialize, Deserialize)]
875#[serde(rename_all = "camelCase")]
876pub struct NodeTokenListItem {
877    pub node_id: String,
878    pub node_type: String,
879    pub hub_id: String,
880    pub host_id: String,
881    pub fingerprint: String,
882    pub service_instance_id: String,
883    pub instance_policy: NodeInstancePolicy,
884    pub instance_slot: String,
885    pub status: NodeBindingStatus,
886    pub issued_at: i64,
887    pub expires_at: i64,
888}
889
890#[derive(Debug, Clone, Serialize, Deserialize)]
891#[serde(rename_all = "camelCase")]
892pub struct NodeTokenListResponse {
893    #[serde(default)]
894    pub nodes: Vec<NodeTokenListItem>,
895}
896
897#[derive(Debug, Clone, Serialize, Deserialize)]
898#[serde(rename_all = "camelCase")]
899pub struct NodeInstanceListItem {
900    pub metadata: NodeBindingMetadata,
901    pub node_id: String,
902    pub node_type: String,
903    pub hub_id: String,
904    pub host_id: String,
905    #[serde(default, skip_serializing_if = "Option::is_none")]
906    pub host_name: Option<String>,
907    pub fingerprint: String,
908    pub service_instance_id: String,
909    pub instance_policy: NodeInstancePolicy,
910    pub instance_slot: String,
911    pub binding_status: NodeBindingStatus,
912    pub issued_at: i64,
913    pub expires_at: i64,
914    pub connected: bool,
915    pub runtime_status: String,
916}
917
918#[derive(Debug, Clone, Serialize, Deserialize)]
919#[serde(rename_all = "camelCase")]
920pub struct NodeInstanceListResponse {
921    #[serde(default)]
922    pub instances: Vec<NodeInstanceListItem>,
923}
924
925#[derive(Debug, Clone, Serialize, Deserialize)]
926#[serde(rename_all = "camelCase")]
927pub struct AuthenticatedSession {
928    pub tenant_id: String,
929    pub scope_id: String,
930    pub client: client_identity::AuthenticatedClient,
931    pub is_test: bool,
932}
933
934#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
935#[serde(rename_all = "snake_case")]
936pub enum ScopeAccessRequirement {
937    Member,
938    Owner,
939}
940
941#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
942#[serde(rename_all = "camelCase", deny_unknown_fields)]
943pub struct ScopeAuthorizationRequest {
944    pub tenant_id: String,
945    pub scope_id: String,
946    pub user_id: String,
947    pub requirement: ScopeAccessRequirement,
948}
949
950#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
951#[serde(rename_all = "camelCase", deny_unknown_fields)]
952pub struct ScopeMembershipListRequest {
953    pub tenant_id: String,
954    pub user_id: String,
955}
956
957#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
958#[serde(rename_all = "camelCase", deny_unknown_fields)]
959pub struct ScopeMembership {
960    pub tenant_id: String,
961    pub scope_id: String,
962    pub user_id: String,
963}
964
965/// A service-owned AppClient materialized from an authoritative external model.
966/// This boundary intentionally carries no acting user: authorization belongs to
967/// the service that owns the source model, while Core validates the projection.
968#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
969#[serde(rename_all = "camelCase", deny_unknown_fields)]
970pub struct ServiceAppClientProjection {
971    pub tenant_id: String,
972    pub scope_id: String,
973    pub app_client_id: String,
974    #[serde(default, skip_serializing_if = "Option::is_none")]
975    pub user_id: Option<String>,
976    pub source: String,
977    pub device_type: String,
978    #[serde(default)]
979    pub scope_owned: bool,
980}
981
982#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
983#[serde(rename_all = "camelCase", deny_unknown_fields)]
984pub struct ServiceAppClientProjectionKey {
985    pub tenant_id: String,
986    pub scope_id: String,
987    pub app_client_id: String,
988}
989
990#[derive(Debug, Clone, Serialize, Deserialize)]
991pub enum ServiceCoreInput {
992    MessagingCloudRequest {
993        request: messaging::MessagingCloudRequest,
994    },
995    ClientAuth {
996        message: MwsMessage,
997        ws_id: String,
998        scope_id: String,
999    },
1000    ClientRequest {
1001        target: String,
1002        payload: String,
1003        ws_id: String,
1004        tenant_id: String,
1005        scope_id: String,
1006        client: client_identity::AuthenticatedClient,
1007        is_test: bool,
1008        #[serde(default, skip_serializing_if = "Option::is_none")]
1009        surface_id: Option<String>,
1010    },
1011    /// Invokes the canonical Conversation application boundary without a
1012    /// websocket/client transport identity.
1013    ConversationRequest {
1014        target: String,
1015        payload: String,
1016        tenant_id: String,
1017        scope_id: String,
1018        actor_user_id: String,
1019        surface_id: String,
1020        is_test: bool,
1021    },
1022    /// Authorizes a trusted headless actor before a non-Conversation operation
1023    /// such as binding a shared messaging surface.
1024    ScopeAuthorization {
1025        request: ScopeAuthorizationRequest,
1026    },
1027    /// Lists authoritative scope memberships for a trusted headless principal.
1028    ScopeMembershipList {
1029        request: ScopeMembershipListRequest,
1030    },
1031    /// Idempotently materializes a trusted service-owned AppClient.
1032    AppClientProjectionPut {
1033        projection: ServiceAppClientProjection,
1034    },
1035    /// Idempotently removes a trusted service-owned AppClient.
1036    AppClientProjectionDelete {
1037        key: ServiceAppClientProjectionKey,
1038    },
1039    NodeAuth {
1040        request: NodeAuthRequest,
1041    },
1042    HubConnectionProof {
1043        request: HubConnectionProofRequest,
1044    },
1045    NodeRequest {
1046        target: String,
1047        payload: String,
1048        /// Transport-owned metadata for a Node-to-Core request. It is not part
1049        /// of the integration payload and is validated by the Core target.
1050        #[serde(default, skip_serializing_if = "Option::is_none")]
1051        control: Option<String>,
1052        tenant_id: String,
1053        scope_id: String,
1054        node_type: String,
1055        node_id: String,
1056    },
1057    /// Reports status from an already authenticated Node transport. Core uses
1058    /// `connection_key` to bind the untrusted payload to the authoritative
1059    /// Node session before accepting it into the Hub-owned status projection.
1060    NodeStatusObserved {
1061        connection_key: String,
1062        status: Box<node::status::StatusPayload>,
1063    },
1064    ClientResponse {
1065        message: MwsMessage,
1066    },
1067    NodeResponse {
1068        message: MwsMessage,
1069    },
1070    IssueLocalSessionToken {
1071        tenant_id: String,
1072        scope_id: String,
1073        user_id: String,
1074        app_client_id: String,
1075    },
1076    SetLocalAppClientFocus {
1077        ws_id: String,
1078        focused: bool,
1079    },
1080    RefreshLocalAppClient {
1081        ws_id: String,
1082    },
1083}
1084
1085#[derive(Debug, Clone, Serialize, Deserialize)]
1086#[allow(
1087    clippy::large_enum_variant,
1088    reason = "Keep the public wire fields inline; boxing changes Rust callers for a bounded auth response"
1089)]
1090pub enum ServiceCoreResponse {
1091    MessagingCloudResponse {
1092        value: serde_json::Value,
1093    },
1094    ClientAuth {
1095        session: Option<AuthenticatedSession>,
1096        response: MwsMessage,
1097    },
1098    ClientRequest {
1099        response_payload: Option<String>,
1100        client_info: MwsClientInfo,
1101    },
1102    ConversationRequest {
1103        response_payload: Option<String>,
1104    },
1105    ScopeAuthorization {
1106        authorized: bool,
1107    },
1108    ScopeMembershipList {
1109        memberships: Vec<ScopeMembership>,
1110    },
1111    AppClientProjection {
1112        applied: bool,
1113    },
1114    NodeAuth(NodeAuthResponse),
1115    HubConnectionProof(HubConnectionProofResponse),
1116    NodeRequest {
1117        response_payload: Option<String>,
1118    },
1119    LocalSessionToken(String),
1120    Ack {
1121        handled: bool,
1122    },
1123}
1124
1125#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1126#[serde(deny_unknown_fields)]
1127pub struct ServiceCoreOutput {
1128    #[serde(skip_serializing_if = "Option::is_none")]
1129    pub response: Option<ServiceCoreResponse>,
1130}
1131
1132#[derive(Debug, Clone, Serialize, Deserialize)]
1133#[serde(rename_all = "camelCase")]
1134pub struct UserInfo {
1135    #[serde(skip_serializing_if = "Option::is_none")]
1136    pub id: Option<String>,
1137    #[serde(skip_serializing_if = "Option::is_none")]
1138    pub name: Option<String>,
1139    #[serde(skip_serializing_if = "Option::is_none")]
1140    pub email: Option<String>,
1141}
1142
1143impl UserInfo {
1144    pub fn new(id: String) -> Self {
1145        Self {
1146            id: Some(id),
1147            name: None,
1148            email: None,
1149        }
1150    }
1151}
1152
1153#[derive(Debug, Clone, Serialize, Deserialize)]
1154#[serde(rename_all = "camelCase")]
1155pub struct ScopeMember {
1156    pub id: Option<String>,
1157    pub email: Option<String>,
1158    pub name: Option<String>,
1159    pub pending: bool,
1160    pub role: Option<String>,
1161}
1162
1163impl Default for ScopeMember {
1164    fn default() -> Self {
1165        Self {
1166            id: None,
1167            email: None,
1168            name: None,
1169            pending: false,
1170            role: None,
1171        }
1172    }
1173}
1174
1175#[derive(Debug, Clone, Serialize, Deserialize)]
1176#[serde(rename_all = "camelCase")]
1177pub struct ScopeInfo {
1178    pub name: Option<String>,
1179    pub id: Option<String>,
1180    pub pending: bool,
1181    pub members: Option<Vec<ScopeMember>>,
1182    pub execution_env: Option<String>,
1183    pub mode: Option<String>,
1184    pub connection_mode: Option<String>,
1185    pub agent_mode: Option<String>,
1186    pub default_active: bool,
1187    #[serde(default)]
1188    pub is_test: bool,
1189}
1190
1191impl Default for ScopeInfo {
1192    fn default() -> Self {
1193        Self {
1194            name: None,
1195            id: None,
1196            pending: false,
1197            members: None,
1198            execution_env: None,
1199            mode: None,
1200            connection_mode: None,
1201            agent_mode: None,
1202            default_active: false,
1203            is_test: false,
1204        }
1205    }
1206}
1207
1208#[derive(Debug, Clone, Serialize, Deserialize)]
1209#[serde(rename_all = "camelCase")]
1210pub struct AuthConfig {
1211    pub tenant_id: String,
1212    pub command_timeout: i32,
1213    #[serde(skip_serializing_if = "Option::is_none")]
1214    pub user_info: Option<UserInfo>,
1215    #[serde(skip_serializing_if = "Option::is_none")]
1216    pub client: Option<client_identity::AuthenticatedClient>,
1217    pub scope: ScopeInfo,
1218    #[serde(skip_serializing_if = "Option::is_none")]
1219    pub hub_id: Option<String>,
1220    #[serde(skip_serializing_if = "Option::is_none")]
1221    pub jwt_token: Option<String>,
1222}
1223
1224impl AuthConfig {
1225    pub fn new(
1226        tenant_id: String,
1227        command_timeout: i32,
1228        user_info: UserInfo,
1229        scope: ScopeInfo,
1230    ) -> Self {
1231        Self {
1232            tenant_id,
1233            command_timeout,
1234            user_info: Some(user_info),
1235            client: None,
1236            scope,
1237            hub_id: None,
1238            jwt_token: None,
1239        }
1240    }
1241}
1242
1243impl Default for AuthConfig {
1244    fn default() -> Self {
1245        Self {
1246            tenant_id: String::new(),
1247            command_timeout: 10,
1248            user_info: None,
1249            client: None,
1250            scope: ScopeInfo::default(),
1251            hub_id: None,
1252            jwt_token: None,
1253        }
1254    }
1255}
1256
1257#[derive(Debug, Clone, Serialize, Deserialize)]
1258#[serde(rename_all = "camelCase")]
1259pub struct AuthRequest {
1260    pub token: String,
1261    pub source: String,
1262    pub scope_id: String,
1263    pub device_id: String,
1264    pub client_source: String,
1265    #[serde(default)]
1266    pub tenant_id: Option<String>,
1267    #[serde(default)]
1268    pub hub_id: Option<String>,
1269}
1270
1271#[derive(Debug, Clone, Serialize, Deserialize)]
1272#[serde(rename_all = "camelCase")]
1273pub struct HubMdnsInstanceRecord {
1274    pub tenant_id: String,
1275    pub scope_id: String,
1276    pub hub_id: String,
1277    pub scope_name: String,
1278}
1279
1280/// Binds commissioning to the Host TLS identity, environment and immutable
1281/// runtime policy. The non-UTF8 domain cannot be requested as a plain nonce.
1282pub fn hub_commission_tls_payload(
1283    nonce: &str,
1284    host_id: &str,
1285    key: &host::auth::PublicKey,
1286    env: RuntimeEnv,
1287    policy: &runtime_space::RuntimeSpacePolicy,
1288) -> Vec<u8> {
1289    let mut out = b"\xffmeow-hub-tls-v2\0".to_vec();
1290    let (mode, tenant, scope) = match policy {
1291        runtime_space::RuntimeSpacePolicy::Multi {} => ("multi", "", ""),
1292        runtime_space::RuntimeSpacePolicy::Single { space } => {
1293            ("single", space.tenant_id.as_str(), space.scope_id.as_str())
1294        }
1295    };
1296    for field in [
1297        nonce,
1298        host_id,
1299        key.x.as_str(),
1300        key.y.as_str(),
1301        env.as_str(),
1302        mode,
1303        tenant,
1304        scope,
1305    ] {
1306        out.extend_from_slice(&(field.len() as u64).to_be_bytes());
1307        out.extend_from_slice(field.as_bytes());
1308    }
1309    out
1310}
1311
1312#[cfg(test)]
1313mod tests {
1314    use super::{
1315        hub_connection_proof_signing_payload, HubConnectionProofRequest, MwsMessage,
1316        MwsMessageType, NodeOnboardingStartRequest, HUB_CONNECTION_PROOF_PROTOCOL,
1317    };
1318
1319    #[test]
1320    fn hub_connection_proof_payload_is_unambiguous_and_nonce_bound() {
1321        let request = HubConnectionProofRequest {
1322            env: Default::default(),
1323            protocol: HUB_CONNECTION_PROOF_PROTOCOL.to_string(),
1324            hub_id: "hub-1".to_string(),
1325            tenant_id: "tenant-1".to_string(),
1326            scope_id: "scope-1".to_string(),
1327            nonce: "nonce-1".to_string(),
1328        };
1329        let payload = hub_connection_proof_signing_payload(&request);
1330        let mut changed = request.clone();
1331        changed.nonce = "nonce-2".to_string();
1332
1333        assert_ne!(payload, hub_connection_proof_signing_payload(&changed));
1334        assert!(payload.starts_with(&(HUB_CONNECTION_PROOF_PROTOCOL.len() as u64).to_be_bytes()));
1335    }
1336
1337    #[test]
1338    fn scoped_server_data_builds_scope_envelope() {
1339        let message = MwsMessage::scoped_server_data(
1340            "scope-1".to_string(),
1341            "/dialog".to_string(),
1342            "{}".to_string(),
1343            None,
1344        );
1345
1346        assert_eq!(message.scope_id.as_deref(), Some("scope-1"));
1347        assert_eq!(message.target.as_deref(), Some("/dialog"));
1348        assert_eq!(message.r#type.as_deref(), Some(MwsMessageType::SERVER_DATA));
1349        assert_eq!(message.payload.as_deref(), Some("{}"));
1350        assert!(message.client_info.is_none());
1351    }
1352
1353    #[test]
1354    fn node_onboarding_start_contract_uses_camel_case_and_rejects_unknown_fields() {
1355        let request = NodeOnboardingStartRequest {
1356            node_type: "matter".to_string(),
1357            candidate_host_id: "host-1".to_string(),
1358            candidate_fingerprint: "sha256:abc".to_string(),
1359            idempotency_key: "attempt-1".to_string(),
1360        };
1361
1362        let json = serde_json::to_value(&request).expect("serialize start request");
1363        assert_eq!(json["candidateHostId"], "host-1");
1364        assert_eq!(json["idempotencyKey"], "attempt-1");
1365
1366        let invalid = serde_json::json!({
1367            "nodeType": "matter",
1368            "candidateHostId": "host-1",
1369            "candidateFingerprint": "sha256:abc",
1370            "idempotencyKey": "attempt-1",
1371            "nonce": "caller-must-not-supply-this"
1372        });
1373        assert!(serde_json::from_value::<NodeOnboardingStartRequest>(invalid).is_err());
1374    }
1375}
1376pub mod device_binding;