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