Skip to main content

core_api/
lib.rs

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