Skip to main content

core_api/
lib.rs

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