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