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