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