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