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