s2_kit/connect/proto/lan.rs
1//! The operations only LAN endpoints implement, as wire types.
2//!
3//! `S2C §LAN-LAN only interactions`: "WAN endpoints **cannot** implement these operations.
4//! It is **recommended** that WAN endpoints respond with status code 404." They exist
5//! because a node discovered over DNS-SD is a host and a port and nothing else — these are
6//! what turn it into a brand, a model name and a list a person can choose from.
7//!
8//! # None of this is authenticated
9//!
10//! There is no bearer and no challenge here; the only protection is that the server
11//! "**must** check if the request originated from the same subnet" and answer `401`
12//! otherwise. A client cannot verify that a server did so. So everything learned here is
13//! material for a user interface — "pair with *Acme Charger 9000*?" — and never a basis
14//! for a decision. The pairing HMAC is what decides.
15//!
16//! # Long-polling, and why it exists
17//!
18//! A Resource Manager on constrained hardware may be "purely an HTTPS client" with no
19//! server at all, which makes it unreachable — and pairing has to start somewhere. So it
20//! calls `waitForPairing` on the other endpoint and holds the request open until the
21//! server tells it what to do. That inverts who dials without inverting who is the pairing
22//! server, which is the point.
23
24use alloc::string::String;
25use alloc::vec::Vec;
26
27use serde::{Deserialize, Serialize};
28
29use super::{EndpointDescription, NodeDescription, NodeId, PairingErrorMessage};
30
31/// The body of `POST /v1/preparePairing`.
32///
33/// A hint, not a request: "It is up to the server implementation to decide what to do with
34/// this signal, but it can be used to display a pop-up with the pairing token in its UI."
35/// The device shows the code at the moment the user is looking for it.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "camelCase")]
38pub struct PreparePairing {
39 /// Who is about to try.
40 pub client_node_description: NodeDescription,
41 /// From where.
42 pub client_endpoint_description: EndpointDescription,
43 /// Which of the server's nodes.
44 pub server_node_id: NodeId,
45}
46
47/// The body of `POST /v1/cancelPreparePairing`.
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(rename_all = "camelCase")]
50pub struct CancelPreparePairing {
51 /// Who has stopped.
52 pub client_node_id: NodeId,
53 /// Which of the server's nodes they were going to pair with.
54 pub server_node_id: NodeId,
55}
56
57/// One entry of the `waitForPairing` request array.
58///
59/// "Note that the client can represent multiple nodes so the request body and the response
60/// contains a list."
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(rename_all = "camelCase")]
63pub struct WaitForPairing {
64 /// Which of the client's nodes is available.
65 pub client_node_id: NodeId,
66 /// Sent only in the request that follows a `sendNodeDescription` action.
67 #[serde(skip_serializing_if = "Option::is_none")]
68 pub client_node_description: Option<NodeDescription>,
69 /// Likewise.
70 #[serde(skip_serializing_if = "Option::is_none")]
71 pub client_endpoint_description: Option<EndpointDescription>,
72 /// Why the client cannot proceed, when it cannot.
73 #[serde(skip_serializing_if = "Option::is_none")]
74 pub error_message: Option<WaitErrorMessage>,
75}
76
77/// Why a long-polling client cannot act.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
79#[non_exhaustive]
80pub enum WaitErrorMessage {
81 /// The client has no pairing token, so there is nothing for it to prove.
82 NoValidTokenOnPairingClient,
83}
84
85/// What the server tells a long-polling client to do next.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[non_exhaustive]
88pub enum WaitAction {
89 /// Send your description on the next poll.
90 #[serde(rename = "sendNodeDescription")]
91 SendNodeDescription,
92 /// The user has started pairing on my side.
93 #[serde(rename = "preparePairing")]
94 PreparePairing,
95 /// The user has stopped.
96 #[serde(rename = "cancelPreparePairing")]
97 CancelPreparePairing,
98 /// Begin the pairing exchange now.
99 #[serde(rename = "requestPairing")]
100 RequestPairing,
101}
102
103/// One entry of the `waitForPairing` response array.
104///
105/// "The server may only provide at most one item for each clientNodeId."
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(rename_all = "camelCase")]
108pub struct WaitInstruction {
109 /// Which of the client's nodes this is for.
110 pub client_node_id: NodeId,
111 /// What to do.
112 pub action: WaitAction,
113}
114
115/// The `400` body of `preparePairing`.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase")]
118pub struct PrepareRefused {
119 /// Which of the enumerated reasons.
120 pub error_message: PairingErrorMessage,
121 /// Free text, for a log.
122 #[serde(skip_serializing_if = "Option::is_none")]
123 pub additional_info: Option<String>,
124}
125
126/// How long a long-polling server may hold a request open.
127///
128/// `S2C §Long-polling`: "The server **must** always respond within 25 seconds." Twenty,
129/// so that the hold plus the time to build and send the answer stays inside the deadline
130/// rather than on it. The client's own timeout must be longer than this, or it will
131/// abandon requests the server was about to answer.
132pub const LONG_POLL_HOLD: crate::types::Duration = crate::types::Duration::from_secs(20);
133
134/// How long a long-polling client should wait before giving up on one request.
135pub const LONG_POLL_TIMEOUT: crate::types::Duration = crate::types::Duration::from_secs(30);
136
137/// What `GET /v1/nodes` answers: the descriptions, and nothing else.
138pub type NodeListing = Vec<NodeDescription>;
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143 use alloc::string::ToString;
144
145 #[test]
146 fn a_clients_timeout_outlasts_the_servers_hold() {
147 // Otherwise the client abandons requests the server was about to answer, and the
148 // pairing never starts.
149 assert!(LONG_POLL_TIMEOUT > LONG_POLL_HOLD);
150 }
151
152 #[test]
153 fn the_actions_are_spelled_as_the_schema_spells_them() {
154 for (action, expected) in [
155 (WaitAction::SendNodeDescription, "\"sendNodeDescription\""),
156 (WaitAction::PreparePairing, "\"preparePairing\""),
157 (WaitAction::CancelPreparePairing, "\"cancelPreparePairing\""),
158 (WaitAction::RequestPairing, "\"requestPairing\""),
159 ] {
160 assert_eq!(serde_json::to_string(&action).unwrap(), expected);
161 }
162 assert_eq!(
163 serde_json::to_string(&WaitErrorMessage::NoValidTokenOnPairingClient).unwrap(),
164 "\"NoValidTokenOnPairingClient\""
165 );
166 }
167
168 #[test]
169 fn a_wait_entry_carries_only_what_the_server_asked_for() {
170 let entry = WaitForPairing {
171 client_node_id: NodeId::parse("rm-1").unwrap(),
172 client_node_description: None,
173 client_endpoint_description: None,
174 error_message: None,
175 };
176 let json = serde_json::to_value(&entry).unwrap();
177 assert_eq!(json.as_object().unwrap().len(), 1, "{json}");
178 assert_eq!(json["clientNodeId"], "rm-1".to_string());
179 }
180}