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