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