1use serde_json::{Value, json};
19
20pub const PATTERN: &str = "Noise_NKpsk0_25519_ChaChaPoly_BLAKE2s";
22pub const DEFAULT_PORT: u16 = 7342;
24const CHUNK: usize = 65_000;
26
27fn params() -> snow::params::NoiseParams {
28 PATTERN.parse().expect("padrão do Noise válido")
29}
30
31pub fn hex(bytes: &[u8]) -> String {
33 bytes.iter().map(|b| format!("{b:02x}")).collect()
34}
35
36pub fn unhex32(text: &str) -> Option<[u8; 32]> {
38 if text.len() != 64 {
39 return None;
40 }
41 let mut out = [0u8; 32];
42 for (i, byte) in out.iter_mut().enumerate() {
43 *byte = u8::from_str_radix(text.get(i * 2..i * 2 + 2)?, 16).ok()?;
44 }
45 Some(out)
46}
47
48pub fn keypair() -> Result<([u8; 32], [u8; 32]), String> {
50 let k = snow::Builder::new(params()).generate_keypair().map_err(|e| e.to_string())?;
51 Ok((k.private.try_into().map_err(|_| "chave privada")?, k.public.try_into().map_err(|_| "chave pública")?))
52}
53
54pub fn secret() -> Result<[u8; 32], String> {
56 Ok(keypair()?.0)
58}
59
60#[derive(Clone, Debug, PartialEq)]
63pub struct Target {
64 pub address: String,
66 pub ide_public: [u8; 32],
67 pub secret: [u8; 32],
68}
69
70impl Target {
71 pub fn to_json(&self) -> Value {
72 json!({ "address": self.address, "ide_public": hex(&self.ide_public), "secret": hex(&self.secret) })
73 }
74
75 pub fn from_json(v: &Value) -> Option<Target> {
76 Some(Target {
77 address: v["address"].as_str()?.to_string(),
78 ide_public: unhex32(v["ide_public"].as_str()?)?,
79 secret: unhex32(v["secret"].as_str()?)?,
80 })
81 }
82
83 pub fn url(&self) -> String {
85 format!("ws://{}", self.address)
86 }
87}
88
89pub struct Session {
91 state: snow::TransportState,
92 pending: Vec<u8>,
93}
94
95impl Session {
96 pub fn seal(&mut self, text: &str) -> Result<Vec<Vec<u8>>, String> {
98 let bytes = text.as_bytes();
99 let pieces: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK).collect() };
100 let last = pieces.len() - 1;
101 pieces
102 .into_iter()
103 .enumerate()
104 .map(|(i, piece)| {
105 let mut plain = Vec::with_capacity(piece.len() + 1);
106 plain.push(u8::from(i == last));
107 plain.extend_from_slice(piece);
108 let mut out = vec![0u8; plain.len() + 16];
109 let n = self.state.write_message(&plain, &mut out).map_err(|e| e.to_string())?;
110 out.truncate(n);
111 Ok(out)
112 })
113 .collect()
114 }
115
116 pub fn open(&mut self, frame: &[u8]) -> Result<Option<String>, String> {
119 let mut plain = vec![0u8; frame.len()];
120 let n = self.state.read_message(frame, &mut plain).map_err(|_| "quadro do canal de desenvolvimento inválido".to_string())?;
121 let (flag, data) = plain[..n].split_first().ok_or("quadro vazio")?;
122 self.pending.extend_from_slice(data);
123 if *flag == 1 {
124 let text = String::from_utf8(std::mem::take(&mut self.pending)).map_err(|_| "mensagem não é UTF-8")?;
125 Ok(Some(text))
126 } else {
127 Ok(None)
128 }
129 }
130}
131
132pub struct Initiator(snow::HandshakeState);
134
135pub fn initiate(target: &Target, hello: &str) -> Result<(Initiator, Vec<u8>), String> {
138 let mut hs = snow::Builder::new(params())
139 .remote_public_key(&target.ide_public)
140 .psk(0, &target.secret)
141 .build_initiator()
142 .map_err(|e| e.to_string())?;
143 let mut out = vec![0u8; hello.len() + 128];
144 let n = hs.write_message(hello.as_bytes(), &mut out).map_err(|e| e.to_string())?;
145 out.truncate(n);
146 Ok((Initiator(hs), out))
147}
148
149impl Initiator {
150 pub fn finish(mut self, reply: &[u8]) -> Result<Session, String> {
152 let mut payload = vec![0u8; reply.len()];
153 self.0.read_message(reply, &mut payload).map_err(|_| "a IDE do outro lado não confere (chave ou segredo errados)".to_string())?;
154 Ok(Session { state: self.0.into_transport_mode().map_err(|e| e.to_string())?, pending: Vec::new() })
155 }
156}
157
158pub fn respond(private: &[u8; 32], secret: &[u8; 32], first: &[u8]) -> Result<(Session, String, Vec<u8>), String> {
161 let mut hs = snow::Builder::new(params()).local_private_key(private).psk(0, secret).build_responder().map_err(|e| e.to_string())?;
162 let mut hello = vec![0u8; first.len()];
163 let n = hs.read_message(first, &mut hello).map_err(|_| "aperto de mão inválido".to_string())?;
164 let hello = String::from_utf8_lossy(&hello[..n]).into_owned();
165 let mut out = vec![0u8; 128];
166 let m = hs.write_message(&[], &mut out).map_err(|e| e.to_string())?;
167 out.truncate(m);
168 Ok((Session { state: hs.into_transport_mode().map_err(|e| e.to_string())?, pending: Vec::new() }, hello, out))
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174
175 fn pair(secret_app: [u8; 32], secret_ide: [u8; 32]) -> Result<(Session, Session), String> {
176 let (private, public) = keypair()?;
177 let target = Target { address: "127.0.0.1:7342".into(), ide_public: public, secret: secret_app };
178 let (init, first) = initiate(&target, r#"{"project":"Loja","pid":1}"#)?;
179 let (ide, hello, reply) = respond(&private, &secret_ide, &first)?;
180 assert!(hello.contains("Loja"));
181 Ok((init.finish(&reply)?, ide))
182 }
183
184 #[test]
185 fn both_sides_talk_and_big_messages_are_split() {
186 let s = secret().unwrap();
187 let (mut app, mut ide) = pair(s, s).unwrap();
188 let big = "x".repeat(200_000);
189 let frames = ide.seal(&big).unwrap();
190 assert!(frames.len() >= 4);
191 let mut got = None;
192 for f in &frames {
193 got = app.open(f).unwrap().or(got);
194 }
195 assert_eq!(got.as_deref(), Some(big.as_str()));
196 let frames = app.seal(r#"{"ok":1}"#).unwrap();
197 assert_eq!(ide.open(&frames[0]).unwrap().as_deref(), Some(r#"{"ok":1}"#));
198 }
199
200 #[test]
201 fn a_wrong_secret_or_impostor_fails() {
202 assert!(pair(secret().unwrap(), secret().unwrap()).is_err());
204 let (_, public) = keypair().unwrap();
206 let (other_private, _) = keypair().unwrap();
207 let s = secret().unwrap();
208 let target = Target { address: "x".into(), ide_public: public, secret: s };
209 let (_, first) = initiate(&target, "{}").unwrap();
210 assert!(respond(&other_private, &s, &first).is_err());
211 let (mut app, mut ide) = pair(s, s).unwrap();
213 let mut frame = ide.seal("oi").unwrap().remove(0);
214 frame[3] ^= 1;
215 assert!(app.open(&frame).is_err());
216 }
217
218 #[test]
219 fn target_round_trips_as_json() {
220 let t = Target { address: "10.0.0.5:7342".into(), ide_public: [7; 32], secret: [9; 32] };
221 assert_eq!(Target::from_json(&t.to_json()), Some(t));
222 }
223}
224
225#[cfg(not(target_arch = "wasm32"))]
227pub mod client {
228 use std::net::TcpStream;
229 use std::sync::mpsc::Receiver;
230 use std::time::Duration;
231
232 use tungstenite::stream::MaybeTlsStream;
233 use tungstenite::{Message, WebSocket};
234
235 use super::{Session, Target, initiate};
236
237 const POLL: Duration = Duration::from_millis(50);
239 const RETRY: Duration = Duration::from_secs(3);
241
242 pub fn run(target: Target, hello: String, mut handle: impl FnMut(&str) -> Option<String> + Send + 'static, outgoing: Receiver<String>) {
247 let _ = std::thread::Builder::new().name("aylis-dev".into()).spawn(move || {
248 let mut announced = false;
249 loop {
250 match connect(&target, &hello) {
251 Ok((mut socket, mut session)) => {
252 if !announced {
253 println!("aylis: conectado na IDE ({})", target.address);
254 announced = true;
255 }
256 serve(&mut socket, &mut session, &mut handle, &outgoing);
257 }
258 Err(_) => std::thread::sleep(RETRY),
259 }
260 std::thread::sleep(Duration::from_millis(200));
261 }
262 });
263 }
264
265 type Socket = WebSocket<MaybeTlsStream<TcpStream>>;
266
267 fn connect(target: &Target, hello: &str) -> Result<(Socket, Session), String> {
268 let (mut socket, _) = tungstenite::connect(target.url()).map_err(|e| e.to_string())?;
269 if let MaybeTlsStream::Plain(s) = socket.get_ref() {
270 s.set_read_timeout(Some(Duration::from_secs(10))).map_err(|e| e.to_string())?;
271 }
272 let (init, first) = initiate(target, hello)?;
273 socket.send(Message::binary(first)).map_err(|e| e.to_string())?;
274 let reply = loop {
275 match socket.read().map_err(|e| e.to_string())? {
276 Message::Binary(b) => break b,
277 Message::Close(_) => return Err("a IDE fechou a conexão".into()),
278 _ => {}
279 }
280 };
281 let session = init.finish(&reply)?;
282 if let MaybeTlsStream::Plain(s) = socket.get_ref() {
283 s.set_read_timeout(Some(POLL)).map_err(|e| e.to_string())?;
284 }
285 Ok((socket, session))
286 }
287
288 fn send(socket: &mut Socket, session: &mut Session, text: &str) -> bool {
289 match session.seal(text) {
290 Ok(frames) => frames.into_iter().all(|f| socket.send(Message::binary(f)).is_ok()),
291 Err(_) => false,
292 }
293 }
294
295 fn serve(socket: &mut Socket, session: &mut Session, handle: &mut impl FnMut(&str) -> Option<String>, outgoing: &Receiver<String>) {
296 loop {
297 while let Ok(text) = outgoing.try_recv() {
298 if !send(socket, session, &text) {
299 return;
300 }
301 }
302 match socket.read() {
303 Ok(Message::Binary(frame)) => match session.open(&frame) {
304 Ok(Some(text)) => {
305 if let Some(reply) = handle(&text) {
306 if !send(socket, session, &reply) {
307 return;
308 }
309 }
310 }
311 Ok(None) => {}
312 Err(_) => return,
314 },
315 Ok(Message::Close(_)) => return,
316 Ok(_) => {}
317 Err(tungstenite::Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {
318 let _ = socket.flush();
319 }
320 Err(_) => return,
321 }
322 }
323 }
324}