Skip to main content

core_api/
lib.rs

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