commit d2c06680f7a61f632ff573e540a8c365055fd6e0 Author: Fredrik Johansson Date: Sun Jun 21 16:32:36 2026 +0200 Initial commit: waste-rs mesh daemon, relay, and proto crates Full Rust implementation with Ed25519 identity, X25519 ECDH handshake, ChaCha20-Poly1305 encrypted peer connections, IPC server, and relay server. Builds on Windows (MSVC), Linux, and macOS. Co-Authored-By: Claude Sonnet 4.6 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2d761e1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/target +**/*.rs.bk +.env +*.identity.json +.local-dev/ diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..214af93 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,9 @@ +{ + "recommendations": [ + "rust-lang.rust-analyzer", + "vadimcn.vscode-lldb", + "serayuzgur.crates", + "tamasfe.even-better-toml", + "usernamehw.errorlens" + ] +} diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..127ff15 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,50 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "type": "lldb", + "request": "launch", + "name": "Debug daemon", + "cargo": { + "args": ["build", "--bin=waste-daemon", "--package=waste-daemon"], + "filter": { "name": "waste-daemon", "kind": "bin" } + }, + "args": [ + "--alias", "local-dev", + "--peer-port", "17338", + "--ipc-port", "17337" + ], + "env": { "RUST_LOG": "debug" }, + "cwd": "${workspaceFolder}" + }, + { + "type": "lldb", + "request": "launch", + "name": "Debug daemon (with relay)", + "cargo": { + "args": ["build", "--bin=waste-daemon", "--package=waste-daemon"], + "filter": { "name": "waste-daemon", "kind": "bin" } + }, + "args": [ + "--alias", "local-dev", + "--peer-port", "17338", + "--ipc-port", "17337", + "--relay", "127.0.0.1:17339" + ], + "env": { "RUST_LOG": "debug" }, + "cwd": "${workspaceFolder}" + }, + { + "type": "lldb", + "request": "launch", + "name": "Debug relay", + "cargo": { + "args": ["build", "--bin=waste-relay", "--package=waste-relay"], + "filter": { "name": "waste-relay", "kind": "bin" } + }, + "args": ["--bind", "127.0.0.1:17339"], + "env": { "RUST_LOG": "debug" }, + "cwd": "${workspaceFolder}" + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..d60858a --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,15 @@ +{ + "rust-analyzer.linkedProjects": ["./Cargo.toml"], + "rust-analyzer.checkOnSave.command": "clippy", + "rust-analyzer.cargo.features": "all", + "editor.formatOnSave": true, + "[rust]": { + "editor.defaultFormatter": "rust-lang.rust-analyzer" + }, + "files.watcherExclude": { + "**/target/**": true + }, + "search.exclude": { + "**/target": true + } +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..1ae259a --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,38 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "cargo build (all)", + "type": "shell", + "command": "cargo build --workspace", + "group": { "kind": "build", "isDefault": true }, + "problemMatcher": ["$rustc"], + "presentation": { "reveal": "always", "panel": "shared" } + }, + { + "label": "cargo clippy", + "type": "shell", + "command": "cargo clippy --workspace -- -D warnings", + "group": "test", + "problemMatcher": ["$rustc"] + }, + { + "label": "run relay (local)", + "type": "shell", + "command": "RUST_LOG=debug cargo run --bin waste-relay -- --bind 127.0.0.1:17339", + "presentation": { "reveal": "always", "panel": "dedicated", "group": "runtime" } + }, + { + "label": "run daemon (peer A)", + "type": "shell", + "command": "RUST_LOG=debug cargo run --bin waste-daemon -- --alias peer-a --peer-port 17338 --ipc-port 17337 --data-dir /tmp/waste-a", + "presentation": { "reveal": "always", "panel": "dedicated", "group": "runtime" } + }, + { + "label": "run daemon (peer B)", + "type": "shell", + "command": "RUST_LOG=debug cargo run --bin waste-daemon -- --alias peer-b --peer-port 17340 --ipc-port 17341 --data-dir /tmp/waste-b", + "presentation": { "reveal": "always", "panel": "dedicated", "group": "runtime" } + } + ] +} diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..660f0d7 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1055 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" + +[[package]] +name = "cc" +version = "1.2.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03d04c30968dffe80775bd4d7fb676131cd04a1fb46d2686dbffbaec2d9dfd31" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" + +[[package]] +name = "mio" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proto" +version = "0.1.0" +dependencies = [ + "chrono", + "serde", + "serde_json", + "uuid", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "socket2" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tokio" +version = "1.52.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.23.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144d6b123cef80b301b8f72a9e2ca4370ddec21950d0a103dd22c437006d2db7" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ddb3f79143bced6de84270411622a2699cee572fc0875aeaf1e7867cf9fca1a" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e21a184b13fb19e157296e2c46056aec9092264fab83e4ba59e68c61b323c3d" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fecefd9c35bd935a20fc3fc344b5f29138961e4f47fb03297d88f2587afb5ebd" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23939e44bb9a5d7576fa2b563dc2e136628f1224e88a8deed09e04858b77871f" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "waste-daemon" +version = "0.1.0" +dependencies = [ + "anyhow", + "base64", + "bytes", + "chrono", + "clap", + "proto", + "rand", + "ring", + "serde", + "serde_json", + "tokio", + "tokio-util", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "waste-relay" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "clap", + "proto", + "serde", + "serde_json", + "tokio", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "zerocopy" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..725ec71 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,23 @@ +[workspace] +resolver = "2" +members = [ + "daemon", + "relay", + "proto", +] + +[workspace.dependencies] +tokio = { version = "1", features = ["full"] } +tokio-util = { version = "0.7", features = ["codec"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +anyhow = "1" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +ring = "0.17" +base64 = "0.22" +rand = "0.8" +bytes = "1" +clap = { version = "4", features = ["derive"] } +uuid = { version = "1", features = ["v4", "serde"] } +chrono = { version = "0.4", features = ["serde"] } diff --git a/FUTURE.md b/FUTURE.md new file mode 100644 index 0000000..061d153 --- /dev/null +++ b/FUTURE.md @@ -0,0 +1,123 @@ +# waste-rs — Project Roadmap + +A modern reimplementation of [WASTE](https://en.wikipedia.org/wiki/WASTE): +decentralized, friend-to-friend encrypted mesh networking with chat and file sharing. + +--- + +## Design Philosophy + +WASTE's core idea is still sound: small trusted groups, no central server, encrypted +everything, equal nodes. This project preserves that philosophy while replacing the +aging crypto and adding proper NAT traversal. + +--- + +## Architecture + +### Core Daemon — Rust + +The networking core (mesh routing, encryption, peer management, file transfer) is +implemented in Rust because: + +- **Memory safety without GC** — critical for a long-running daemon handling untrusted peer data +- **tokio** — excellent async I/O for managing many concurrent peer connections +- **ring** — modern, audited cryptography (ChaCha20-Poly1305, Ed25519, X25519) +- **Native cross-compilation** — Windows, Linux, macOS, and eventually Android/iOS + +### UI Layer — TUI first, Tauri later + +**Step 1: Terminal UI (`ratatui` + `crossterm`)** + +The daemon exposes everything over the IPC socket, so a TUI is purely a client — +it connects to port 17337, renders `IpcEvent` lines, and sends `IpcCommand` lines +back. No mesh or crypto knowledge required. + +- ~400–600 lines of Rust, two crate dependencies +- Works on Windows, Linux, macOS, and over SSH +- Validates the IPC API design before it gets frozen +- Fast to iterate: restart the TUI, daemon keeps running + +This is the right first UI milestone. It gives you a real working chat interface +without any build toolchain beyond `cargo`. + +**Step 2: Tauri GUI** + +Once the IPC contract is stable, wrap it in a proper desktop app: + +- Rust backend shares code directly with the daemon +- Web frontend (React/TypeScript) for a modern chat UI +- Ships as a native binary using the OS webview — not Electron +- Works on Windows, Linux, macOS; Tauri 2.x adds Android/iOS + +This avoids the wxWidgets ugliness of the original WASTE and the Qt licensing +headaches of the VIA fork. + +--- + +## Crypto Modernization + +Replaces WASTE's original Blowfish/PCBC (broken cipher mode) + RSA with: + +| Purpose | Algorithm | Replaces | +|---|---|---| +| Identity | Ed25519 | Unregistered nicknames | +| Key exchange | X25519 ECDH | RSA | +| Symmetric encryption | ChaCha20-Poly1305 | Blowfish/PCBC | +| File integrity | SHA-256 | CRC | + +--- + +## Protocol Modernization + +### NAT Traversal +WASTE's longstanding problem: one party needs an open port. The fix: + +1. **ICE-style UDP hole punching** (STUN) — try direct connection first +2. **Relay fallback** — a lightweight relay server (already implemented) forwards + encrypted blobs when hole punching fails; the relay never sees plaintext + +### Transport (future consideration) +Consider migrating from raw TCP to **QUIC** (via `quinn`) for: +- Connection multiplexing — multiple streams per peer without head-of-line blocking +- Better NAT behavior out of the box +- Built-in TLS 1.3 + +### Identity & Bootstrapping +- Each peer generates an Ed25519 keypair on first run — the public key *is* their identity +- Invite via a signed `.waste-invite` file shared out-of-band (email, Signal, etc.) +- The invite carries: current IP:port hint + public key + short-lived signature +- Once two peers connect, they gossip each other's addresses to mutual friends +- At small group sizes (10–50 nodes) a local known-peers list is sufficient — no DHT needed + +--- + +## Roadmap + +### Near-term +- [ ] Invite file format (`.waste-invite`) for easy peer onboarding +- [ ] Relay-assisted message delivery (daemon → relay → peer when no direct path) +- [ ] Gossip-driven auto-connect (friends-of-friends) +- [ ] Ping/pong keepalive with peer timeout and reconnect + +### Medium-term +- [ ] **TUI client** (`ratatui` + `crossterm`) — chat pane, peer list, text input +- [ ] UDP hole-punching (STUN) in `nat.rs` +- [ ] File transfer implementation (FileOffer/FileChunk protocol already defined in proto) +- [ ] Message persistence (SQLite via `rusqlite`) +- [ ] Tauri GUI wrapping the daemon (sidebar: peers, rooms, chat history) + +### Long-term +- [ ] QUIC transport via `quinn` +- [ ] Mobile daemon (Android/iOS via Rust cross-compilation) +- [ ] Kademlia DHT for larger-scale peer discovery (if the group outgrows static bootstrap) + +--- + +## What We Keep from WASTE + +- Small, trusted friend groups — not a public network +- No central authority — the relay is dumb and optional +- Encrypted everything — the relay forwards opaque blobs +- Equal nodes — no privileged "servers" among peers +- Simple onboarding — one file or one URL to join a group diff --git a/README.md b/README.md new file mode 100644 index 0000000..0f66085 --- /dev/null +++ b/README.md @@ -0,0 +1,215 @@ +# waste-rs + +A modern reimagining of [WASTE](https://en.wikipedia.org/wiki/WASTE) - decentralized, +friend-to-friend encrypted mesh networking with chat and file sharing. + +## Architecture + +``` +waste-rs/ +|-- proto/ Shared types (wire protocol, IPC messages) +|-- daemon/ Main peer process - runs locally on each friend's machine +| |-- crypto.rs Ed25519 identity, X25519 ECDH, ChaCha20-Poly1305 AEAD +| |-- mesh/ Connected peer state, gossip, broadcast +| |-- nat.rs Relay client + future hole-punching +| `-- ipc.rs Local JSON API for UIs (port 17337) +`-- relay/ Bootstrap/relay server - runs on your VPS +``` + +### How it works + +1. Each peer generates an Ed25519 keypair on first run -> their identity. +2. Two peers exchange invite info out-of-band (public key + IP:port). +3. On connect: Ed25519-authenticated X25519 handshake -> per-session ChaCha20 key. +4. All traffic is encrypted; the relay only forwards opaque blobs. +5. Connected peers gossip each other's addresses to strengthen the mesh. + +## Prerequisites + +- Rust 1.78+ (via rustup) +- VS Code with the extensions in `.vscode/extensions.json` +- `cargo-lldb` for debugging (installed by the LLDB extension) + +### Install toolchain (Windows, Linux, macOS) + +Use rustup on all platforms. + +Windows (PowerShell): + +```powershell +winget install Rustlang.Rustup +``` + +Linux/macOS (bash/zsh): + +```bash +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh +``` + +Then install required components: + +```bash +rustup toolchain install stable +rustup default stable +rustup component add rustfmt clippy +``` + +Verify your setup: + +```bash +rustup --version +rustc --version +cargo --version +cargo clippy --version +``` + +## Getting started + +### 1) Build workspace + +```bash +cargo build --workspace +cargo clippy --workspace -- -D warnings +``` + +### 2) Run local relay + +Linux/macOS (bash/zsh): + +```bash +RUST_LOG=debug cargo run --bin waste-relay -- --bind 127.0.0.1:17339 +``` + +Windows PowerShell: + +```powershell +$env:RUST_LOG = "debug" +cargo run --bin waste-relay -- --bind 127.0.0.1:17339 +``` + +Windows cmd.exe: + +```cmd +set RUST_LOG=debug && cargo run --bin waste-relay -- --bind 127.0.0.1:17339 +``` + +### 3) Run two peers + +Use a local folder for data so paths are portable across platforms. + +Peer A (terminal 2) + +Linux/macOS (bash/zsh): + +```bash +RUST_LOG=debug cargo run --bin waste-daemon -- \ + --alias alice --data-dir ./.local-dev/waste-alice \ + --peer-port 17338 --ipc-port 17337 +``` + +Windows PowerShell: + +```powershell +$env:RUST_LOG = "debug" +cargo run --bin waste-daemon -- --alias alice --data-dir ./.local-dev/waste-alice --peer-port 17338 --ipc-port 17337 +``` + +Windows cmd.exe: + +```cmd +set RUST_LOG=debug && cargo run --bin waste-daemon -- --alias alice --data-dir ./.local-dev/waste-alice --peer-port 17338 --ipc-port 17337 +``` + +Peer B (terminal 3) + +Linux/macOS (bash/zsh): + +```bash +RUST_LOG=debug cargo run --bin waste-daemon -- \ + --alias bob --data-dir ./.local-dev/waste-bob \ + --peer-port 17340 --ipc-port 17341 +``` + +Windows PowerShell: + +```powershell +$env:RUST_LOG = "debug" +cargo run --bin waste-daemon -- --alias bob --data-dir ./.local-dev/waste-bob --peer-port 17340 --ipc-port 17341 +``` + +Windows cmd.exe: + +```cmd +set RUST_LOG=debug && cargo run --bin waste-daemon -- --alias bob --data-dir ./.local-dev/waste-bob --peer-port 17340 --ipc-port 17341 +``` + +### 4) Connect B -> A via IPC + +If nc/netcat is available: + +```bash +echo '{"type":"connect","addr":"127.0.0.1:17338"}' | nc 127.0.0.1 17341 +``` + +PowerShell equivalent: + +```powershell +$json = '{"type":"connect","addr":"127.0.0.1:17338"}' + "`n" +$client = [System.Net.Sockets.TcpClient]::new("127.0.0.1", 17341) +$stream = $client.GetStream() +$writer = New-Object System.IO.StreamWriter($stream) +$writer.AutoFlush = $true +$writer.Write($json) +$writer.Dispose(); $stream.Dispose(); $client.Dispose() +``` + +## Relay on Hetzner VPS + +```bash +cargo build --release --bin waste-relay +scp target/release/waste-relay user@your-vps:~/ +ssh user@your-vps './waste-relay --bind 0.0.0.0:17339' +``` + +Then start the daemon with `--relay your-vps-ip:17339`. + +## IPC protocol + +The daemon exposes a newline-delimited JSON API on `127.0.0.1:17337`. + +Commands (send to daemon): + +```json +{"type":"send_message","room":"general","body":"hello"} +{"type":"connect","addr":"1.2.3.4:17338"} +{"type":"get_state"} +``` + +Events (daemon pushes to you): + +```json +{"type":"message_received","id":"...","from":"...","room":"general","body":"hello"} +{"type":"peer_connected","peer":{...}} +{"type":"state_snapshot","local_peer":{...},"connected_peers":[...]} +``` + +## Roadmap + +- [ ] UDP hole-punching (STUN) in `nat.rs` +- [ ] Invite file format (`.waste-invite`) for easy onboarding +- [ ] File transfer implementation +- [ ] Tauri UI wrapping the daemon +- [ ] Peer gossip -> auto-connect to friends-of-friends +- [ ] Message persistence (SQLite) +- [ ] Mobile daemon (Android/iOS via Rust cross-compilation) + +## Crypto choices + +| Purpose | Algorithm | Why | +|---|---|---| +| Identity | Ed25519 | Fast, small keys, strong | +| Key exchange | X25519 ECDH | Modern, fast, safe | +| Symmetric | ChaCha20-Poly1305 | No timing side-channels, fast without AES-NI | +| Hashing | SHA-256 (ring) | File integrity | + +Replaces WASTE's original Blowfish/PCBC (broken mode) + RSA. diff --git a/daemon/Cargo.toml b/daemon/Cargo.toml new file mode 100644 index 0000000..8bfc3fd --- /dev/null +++ b/daemon/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "waste-daemon" +version = "0.1.0" +edition = "2021" + +[[bin]] +name = "waste-daemon" +path = "src/main.rs" + +[dependencies] +proto = { path = "../proto" } +tokio = { workspace = true } +tokio-util = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +anyhow = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +ring = { workspace = true } +base64 = { workspace = true } +rand = { workspace = true } +bytes = { workspace = true } +clap = { workspace = true } +uuid = { workspace = true } +chrono = { workspace = true } diff --git a/daemon/src/config.rs b/daemon/src/config.rs new file mode 100644 index 0000000..d30c54a --- /dev/null +++ b/daemon/src/config.rs @@ -0,0 +1,41 @@ +use anyhow::{Context, Result}; +use std::path::PathBuf; +use tokio::fs; + +pub struct Config { + pub data_dir: PathBuf, +} + +impl Config { + pub async fn init(raw_path: &str) -> Result { + let data_dir = expand_tilde(raw_path); + fs::create_dir_all(&data_dir) + .await + .with_context(|| format!("creating data dir {:?}", data_dir))?; + Ok(Self { data_dir }) + } + + pub fn identity_path(&self) -> PathBuf { + self.data_dir.join("identity.json") + } + + pub fn peers_path(&self) -> PathBuf { + self.data_dir.join("known_peers.json") + } +} + +fn expand_tilde(path: &str) -> PathBuf { + if let Some(rest) = path.strip_prefix("~/").or_else(|| path.strip_prefix("~\\")) { + if let Some(home) = home_dir() { + return home.join(rest); + } + } + PathBuf::from(path) +} + +fn home_dir() -> Option { + // $HOME on Unix, $USERPROFILE on Windows + std::env::var_os("HOME") + .or_else(|| std::env::var_os("USERPROFILE")) + .map(PathBuf::from) +} diff --git a/daemon/src/crypto.rs b/daemon/src/crypto.rs new file mode 100644 index 0000000..63eeda6 --- /dev/null +++ b/daemon/src/crypto.rs @@ -0,0 +1,186 @@ +/// Cryptography primitives for WASTE-rs. +/// +/// Identity: Ed25519 keypair (sign/verify peer identity) +/// Session: X25519 ECDH → shared secret → ChaCha20-Poly1305 session key +/// Storage: Keys persisted as JSON in the data directory +use anyhow::{Context, Result}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use chrono::Utc; +use proto::{PeerId, PeerInfo}; +use ring::{ + aead::{self, BoundKey, Nonce, NonceSequence, CHACHA20_POLY1305}, + agreement::{self, EphemeralPrivateKey, UnparsedPublicKey, X25519}, + rand::{SecureRandom, SystemRandom}, + signature::{self, Ed25519KeyPair, KeyPair}, +}; +use serde::{Deserialize, Serialize}; +use std::path::Path; +use tokio::fs; + +// ── Identity keypair ────────────────────────────────────────────────────────── + +#[derive(Clone)] +pub struct Identity { + /// PKCS#8 Ed25519 keypair bytes (secret!) + pkcs8: Vec, + alias: String, +} + +#[derive(Serialize, Deserialize)] +struct IdentityFile { + pkcs8_base64: String, + alias: String, +} + +impl Identity { + /// Load from disk, or generate a new keypair if none exists. + pub async fn load_or_create(data_dir: &str, alias: &str) -> Result { + let path = Path::new(data_dir).join("identity.json"); + if path.exists() { + let raw = fs::read_to_string(&path) + .await + .context("reading identity file")?; + let file: IdentityFile = serde_json::from_str(&raw)?; + let pkcs8 = URL_SAFE_NO_PAD.decode(&file.pkcs8_base64)?; + tracing::info!("Loaded existing identity from {:?}", path); + Ok(Self { pkcs8, alias: file.alias }) + } else { + tracing::info!("Generating new Ed25519 identity keypair"); + let rng = SystemRandom::new(); + let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng) + .map_err(|e| anyhow::anyhow!("keygen failed: {:?}", e))?; + let identity = Self { + pkcs8: pkcs8.as_ref().to_vec(), + alias: alias.to_string(), + }; + let file = IdentityFile { + pkcs8_base64: URL_SAFE_NO_PAD.encode(&identity.pkcs8), + alias: alias.to_string(), + }; + fs::create_dir_all(data_dir).await?; + fs::write(&path, serde_json::to_string_pretty(&file)?).await?; + tracing::info!("Saved new identity to {:?}", path); + Ok(identity) + } + } + + fn keypair(&self) -> Result { + Ed25519KeyPair::from_pkcs8(&self.pkcs8) + .map_err(|e| anyhow::anyhow!("loading keypair: {:?}", e)) + } + + /// Our stable peer ID (base64url of the public key). + pub fn peer_id(&self) -> PeerId { + let kp = self.keypair().expect("identity keypair valid"); + PeerId(URL_SAFE_NO_PAD.encode(kp.public_key().as_ref())) + } + + /// Full peer info for the Hello handshake. + pub fn peer_info(&self) -> PeerInfo { + PeerInfo { + id: self.peer_id(), + alias: self.alias.clone(), + public_key: self.peer_id().0.clone(), // public key == peer id encoding + created_at: Utc::now(), + } + } + + /// Sign arbitrary bytes. Returns base64url signature. + pub fn sign(&self, data: &[u8]) -> Result { + let kp = self.keypair()?; + let sig = kp.sign(data); + Ok(URL_SAFE_NO_PAD.encode(sig.as_ref())) + } + + /// Verify a signature from a peer (given their base64url public key). + pub fn verify(public_key_b64: &str, data: &[u8], sig_b64: &str) -> Result<()> { + let pk_bytes = URL_SAFE_NO_PAD.decode(public_key_b64)?; + let sig_bytes = URL_SAFE_NO_PAD.decode(sig_b64)?; + let peer_pk = signature::UnparsedPublicKey::new(&signature::ED25519, &pk_bytes); + peer_pk + .verify(data, &sig_bytes) + .map_err(|_| anyhow::anyhow!("signature verification failed")) + } +} + +// ── X25519 ECDH session key derivation ─────────────────────────────────────── + +/// Generate an ephemeral X25519 keypair. Returns (private_key, public_key_b64). +pub fn generate_ephemeral() -> Result<(EphemeralPrivateKey, String)> { + let rng = SystemRandom::new(); + let private = EphemeralPrivateKey::generate(&X25519, &rng) + .map_err(|e| anyhow::anyhow!("X25519 keygen: {:?}", e))?; + let public_b64 = URL_SAFE_NO_PAD.encode( + private + .compute_public_key() + .map_err(|e| anyhow::anyhow!("pubkey: {:?}", e))? + .as_ref(), + ); + Ok((private, public_b64)) +} + +/// Complete ECDH: our ephemeral private key + their ephemeral public key → 32-byte shared secret. +pub fn ecdh(our_private: EphemeralPrivateKey, their_public_b64: &str) -> Result> { + let their_bytes = URL_SAFE_NO_PAD.decode(their_public_b64)?; + let their_pub = UnparsedPublicKey::new(&X25519, &their_bytes); + agreement::agree_ephemeral(our_private, &their_pub, |key_material| { + // In production: run through HKDF here + key_material.to_vec() + }) + .map_err(|e| anyhow::anyhow!("ECDH failed: {:?}", e)) +} + +// ── ChaCha20-Poly1305 AEAD ──────────────────────────────────────────────────── + +/// Encrypt plaintext with a 32-byte key. Returns (nonce_b64, ciphertext_b64). +pub fn encrypt(key: &[u8; 32], plaintext: &[u8]) -> Result<(String, String)> { + let rng = SystemRandom::new(); + let mut nonce_bytes = [0u8; 12]; + rng.fill(&mut nonce_bytes) + .map_err(|_| anyhow::anyhow!("RNG fill failed"))?; + + let unbound = aead::UnboundKey::new(&CHACHA20_POLY1305, key) + .map_err(|e| anyhow::anyhow!("key: {:?}", e))?; + let mut sealing = aead::SealingKey::new(unbound, OneNonce(Some(nonce_bytes))); + + let mut in_out = plaintext.to_vec(); + sealing + .seal_in_place_append_tag(aead::Aad::empty(), &mut in_out) + .map_err(|e| anyhow::anyhow!("encrypt: {:?}", e))?; + + Ok(( + URL_SAFE_NO_PAD.encode(&nonce_bytes), + URL_SAFE_NO_PAD.encode(&in_out), + )) +} + +/// Decrypt ciphertext with a 32-byte key. +pub fn decrypt(key: &[u8; 32], nonce_b64: &str, ciphertext_b64: &str) -> Result> { + let nonce_bytes: [u8; 12] = URL_SAFE_NO_PAD + .decode(nonce_b64)? + .try_into() + .map_err(|_| anyhow::anyhow!("nonce length"))?; + + let unbound = aead::UnboundKey::new(&CHACHA20_POLY1305, key) + .map_err(|e| anyhow::anyhow!("key: {:?}", e))?; + let mut opening = aead::OpeningKey::new(unbound, OneNonce(Some(nonce_bytes))); + + let mut in_out = URL_SAFE_NO_PAD.decode(ciphertext_b64)?; + let plaintext = opening + .open_in_place(aead::Aad::empty(), &mut in_out) + .map_err(|_| anyhow::anyhow!("decryption failed (bad key or tampered)"))?; + + Ok(plaintext.to_vec()) +} + +/// A single-use nonce holder for ring's NonceSequence trait. +struct OneNonce(Option<[u8; 12]>); + +impl NonceSequence for OneNonce { + fn advance(&mut self) -> std::result::Result { + self.0 + .take() + .map(Nonce::assume_unique_for_key) + .ok_or(ring::error::Unspecified) + } +} diff --git a/daemon/src/ipc.rs b/daemon/src/ipc.rs new file mode 100644 index 0000000..ab48053 --- /dev/null +++ b/daemon/src/ipc.rs @@ -0,0 +1,155 @@ +/// IPC server: listens on 127.0.0.1:{port}, speaks newline-delimited JSON. +/// The UI (or any local client) sends IpcCommand and receives IpcEvent. +use crate::mesh::Mesh; +use anyhow::Result; +use chrono::Utc; +use proto::{IpcCommand, IpcEvent}; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + net::{TcpListener, TcpStream}, +}; +use tracing::{info, warn}; +use uuid::Uuid; + +pub async fn run(mesh: Mesh, port: u16) -> Result<()> { + let addr = format!("127.0.0.1:{port}"); + let listener = TcpListener::bind(&addr).await?; + info!("IPC server listening on {addr}"); + + loop { + let (stream, addr) = listener.accept().await?; + info!("UI client connected from {addr}"); + let mesh = mesh.clone(); + tokio::spawn(async move { + if let Err(e) = handle_client(stream, mesh).await { + warn!("IPC client error: {e:#}"); + } + }); + } +} + +async fn handle_client(stream: TcpStream, mesh: Mesh) -> Result<()> { + let (reader, mut writer) = stream.into_split(); + let mut reader = BufReader::new(reader); + + // Subscribe to mesh events before we start reading commands, + // so we don't miss anything. + let mut events = mesh.subscribe_events(); + + // Push events to the UI in a background task + let writer_clone = { + // We need to split writing duties: event pusher vs command replies. + // Use a channel to serialize writes. + let (tx, mut rx) = tokio::sync::mpsc::channel::(128); + + let tx_clone = tx.clone(); + tokio::spawn(async move { + while let Ok(event) = events.recv().await { + if let Ok(line) = serde_json::to_string(&event) { + if tx_clone.send(line + "\n").await.is_err() { + break; + } + } + } + }); + + tokio::spawn(async move { + while let Some(line) = rx.recv().await { + if writer.write_all(line.as_bytes()).await.is_err() { + break; + } + } + }); + + tx + }; + + // Send an initial state snapshot + let snapshot = IpcEvent::StateSnapshot { + local_peer: mesh.identity().peer_info(), + connected_peers: mesh.connected_peers().await, + rooms: vec!["general".to_string()], + }; + if let Ok(line) = serde_json::to_string(&snapshot) { + let _ = writer_clone.send(line + "\n").await; + } + + // Read commands from the UI + let mut line = String::new(); + loop { + line.clear(); + let n = reader.read_line(&mut line).await?; + if n == 0 { + break; + } + let cmd: IpcCommand = match serde_json::from_str(line.trim()) { + Ok(c) => c, + Err(e) => { + warn!("Bad IPC command: {e}"); + continue; + } + }; + handle_command(cmd, &mesh, &writer_clone).await; + } + + info!("UI client disconnected"); + Ok(()) +} + +async fn handle_command( + cmd: IpcCommand, + mesh: &Mesh, + reply_tx: &tokio::sync::mpsc::Sender, +) { + match cmd { + IpcCommand::SendMessage { room, to, body } => { + let msg = proto::ChatMessage { + id: Uuid::new_v4(), + from: mesh.identity().peer_id(), + to, + room, + body, + sent_at: Utc::now(), + }; + mesh.broadcast_chat(msg).await; + } + + IpcCommand::Connect { addr } => { + info!("Connecting to peer at {addr}"); + let mesh = mesh.clone(); + tokio::spawn(async move { + match tokio::net::TcpStream::connect(&addr).await { + Ok(stream) => { + if let Err(e) = + crate::mesh::listener::handle_outbound(stream, mesh).await + { + warn!("Outbound connection to {addr} failed: {e:#}"); + } + } + Err(e) => warn!("TCP connect to {addr} failed: {e}"), + } + }); + } + + IpcCommand::GetState => { + let snapshot = IpcEvent::StateSnapshot { + local_peer: mesh.identity().peer_info(), + connected_peers: mesh.connected_peers().await, + rooms: vec!["general".to_string()], + }; + if let Ok(line) = serde_json::to_string(&snapshot) { + let _ = reply_tx.send(line + "\n").await; + } + } + + IpcCommand::SendFile { to, path } => { + info!("File send to {to} from {path} — not yet implemented"); + let err = IpcEvent::Error { + message: "File transfer not yet implemented".into(), + }; + if let Ok(line) = serde_json::to_string(&err) { + let _ = reply_tx.send(line + "\n").await; + } + } + } +} diff --git a/daemon/src/main.rs b/daemon/src/main.rs new file mode 100644 index 0000000..b5f1e42 --- /dev/null +++ b/daemon/src/main.rs @@ -0,0 +1,74 @@ +mod config; +mod crypto; +mod ipc; +mod mesh; +mod nat; + +use anyhow::Result; +use clap::Parser; +use tracing::info; + +#[derive(Parser, Debug)] +#[command(name = "waste-daemon", about = "WASTE-rs mesh daemon")] +struct Args { + /// Path to config/identity directory + #[arg(long, default_value = "~/.waste")] + data_dir: String, + + /// Local alias shown to peers (advisory only) + #[arg(long, default_value = "anon")] + alias: String, + + /// Port to listen for incoming peer connections + #[arg(long, default_value_t = 17338)] + peer_port: u16, + + /// Port for local IPC (UI talks to daemon here) + #[arg(long, default_value_t = 17337)] + ipc_port: u16, + + /// Optional relay server address (host:port) + #[arg(long)] + relay: Option, +} + +#[tokio::main] +async fn main() -> Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::from_default_env() + .add_directive("waste_daemon=debug".parse()?) + .add_directive("info".parse()?), + ) + .init(); + + let args = Args::parse(); + info!("Starting waste-daemon on peer_port={} ipc_port={}", args.peer_port, args.ipc_port); + + let cfg = config::Config::init(&args.data_dir).await?; + let data_dir = cfg.data_dir.to_string_lossy(); + + // Load or generate identity keypair + let identity = crypto::Identity::load_or_create(&data_dir, &args.alias).await?; + info!("Local peer id: {}", identity.peer_info().id); + + // Shared mesh state + let mesh = mesh::Mesh::new(identity.clone()); + + // Spawn peer listener (incoming connections from other WASTE nodes) + let peer_listener = mesh::listener::run(mesh.clone(), args.peer_port); + + // Spawn NAT traversal / hole-punch coordinator + let nat_task = nat::run(mesh.clone(), args.relay.clone()); + + // Spawn IPC server (local UI connects here) + let ipc_task = ipc::run(mesh.clone(), args.ipc_port); + + tokio::select! { + r = peer_listener => { r?; } + r = nat_task => { r?; } + r = ipc_task => { r?; } + } + + Ok(()) +} diff --git a/daemon/src/mesh/listener.rs b/daemon/src/mesh/listener.rs new file mode 100644 index 0000000..5f76912 --- /dev/null +++ b/daemon/src/mesh/listener.rs @@ -0,0 +1,174 @@ +use crate::{crypto, mesh::Mesh}; +use anyhow::Result; +use proto::{Hello, HelloAck, PeerInfo, PeerMessage}; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + net::{TcpListener, TcpStream}, + sync::mpsc, +}; +use tracing::{error, info, warn}; + +/// Accept incoming peer connections on `port`. +pub async fn run(mesh: Mesh, port: u16) -> Result<()> { + let addr = format!("0.0.0.0:{port}"); + let listener = TcpListener::bind(&addr).await?; + info!("Listening for peers on {addr}"); + + loop { + match listener.accept().await { + Ok((stream, peer_addr)) => { + info!("Incoming connection from {peer_addr}"); + let mesh = mesh.clone(); + tokio::spawn(async move { + if let Err(e) = handle_peer(stream, mesh).await { + warn!("Peer connection error: {e:#}"); + } + }); + } + Err(e) => error!("Accept error: {e}"), + } + } +} + +/// Inbound: we received a TCP connection. Send Hello, read HelloAck. +async fn handle_peer(stream: TcpStream, mesh: Mesh) -> Result<()> { + let peer_addr = stream.peer_addr()?; + let (reader, mut writer) = stream.into_split(); + let mut reader = BufReader::new(reader); + + let (our_ephemeral_priv, our_ephemeral_pub) = crypto::generate_ephemeral()?; + let identity = mesh.identity(); + let hello = Hello { + version: 1, + peer: identity.peer_info(), + ephemeral_key: our_ephemeral_pub.clone(), + signature: identity.sign(our_ephemeral_pub.as_bytes())?, + }; + writer.write_all((serde_json::to_string(&hello)? + "\n").as_bytes()).await?; + + let mut line = String::new(); + reader.read_line(&mut line).await?; + let ack: HelloAck = serde_json::from_str(line.trim())?; + + crypto::Identity::verify(&ack.peer.public_key, ack.ephemeral_key.as_bytes(), &ack.signature)?; + info!("Handshake complete with peer {}", ack.peer.id); + + let shared_secret = crypto::ecdh(our_ephemeral_priv, &ack.ephemeral_key)?; + let session_key: [u8; 32] = shared_secret[..32].try_into()?; + + run_peer_loop(reader, writer, peer_addr.to_string(), ack.peer, session_key, mesh).await +} + +/// Outbound: we initiated the TCP connection. Read their Hello, send HelloAck. +pub async fn handle_outbound(stream: TcpStream, mesh: Mesh) -> Result<()> { + let peer_addr = stream.peer_addr()?; + let (reader, mut writer) = stream.into_split(); + let mut reader = BufReader::new(reader); + + let mut line = String::new(); + reader.read_line(&mut line).await?; + let hello: Hello = serde_json::from_str(line.trim())?; + + crypto::Identity::verify(&hello.peer.public_key, hello.ephemeral_key.as_bytes(), &hello.signature)?; + info!("Got Hello from peer {} ({})", hello.peer.id, hello.peer.alias); + + let (our_ephemeral_priv, our_ephemeral_pub) = crypto::generate_ephemeral()?; + let identity = mesh.identity(); + let ack = HelloAck { + peer: identity.peer_info(), + ephemeral_key: our_ephemeral_pub.clone(), + signature: identity.sign(our_ephemeral_pub.as_bytes())?, + relay_capable: false, + }; + writer.write_all((serde_json::to_string(&ack)? + "\n").as_bytes()).await?; + + let shared_secret = crypto::ecdh(our_ephemeral_priv, &hello.ephemeral_key)?; + let session_key: [u8; 32] = shared_secret[..32].try_into()?; + + run_peer_loop(reader, writer, peer_addr.to_string(), hello.peer, session_key, mesh).await +} + +/// Shared post-handshake loop: register in mesh, encrypt/decrypt messages. +async fn run_peer_loop( + mut reader: BufReader, + mut writer: tokio::net::tcp::OwnedWriteHalf, + peer_addr: String, + peer_info: PeerInfo, + session_key: [u8; 32], + mesh: Mesh, +) -> Result<()> { + let (tx, mut rx) = mpsc::channel::(64); + let peer_id = peer_info.id.clone(); + mesh.add_peer(crate::mesh::PeerConn { info: peer_info, tx }).await; + + tokio::spawn(async move { + while let Some(msg) = rx.recv().await { + match crypto::encrypt(&session_key, msg.as_bytes()) { + Ok((nonce, ct)) => { + let env = proto::Envelope { nonce, payload: ct }; + if let Ok(line) = serde_json::to_string(&env) { + let _ = writer.write_all((line + "\n").as_bytes()).await; + } + } + Err(e) => warn!("Encrypt error: {e}"), + } + } + }); + + let result = async { + loop { + let mut line = String::new(); + let n = reader.read_line(&mut line).await?; + if n == 0 { + break; + } + let env: proto::Envelope = match serde_json::from_str(line.trim()) { + Ok(e) => e, + Err(e) => { + warn!("Bad envelope from {peer_addr}: {e}"); + continue; + } + }; + match crypto::decrypt(&session_key, &env.nonce, &env.payload) { + Ok(plaintext) => { + if let Ok(msg) = serde_json::from_slice::(&plaintext) { + handle_message(msg, &mesh).await; + } + } + Err(e) => warn!("Decrypt error from {peer_addr}: {e}"), + } + } + Ok::<(), anyhow::Error>(()) + } + .await; + + mesh.remove_peer(&peer_id).await; + info!("Peer {peer_addr} disconnected"); + result +} + +async fn handle_message(msg: PeerMessage, mesh: &Mesh) { + match msg { + PeerMessage::Chat(chat) => { + mesh.emit(proto::IpcEvent::MessageReceived(chat)); + } + PeerMessage::PeerGossip(gossip) => { + // TODO: attempt connections to new peers from gossip + info!("Received gossip with {} peer hints", gossip.peers.len()); + } + PeerMessage::Ping { seq } => { + // Pong is sent directly — for now just log + info!("Ping seq={seq}"); + } + PeerMessage::Pong { seq } => { + info!("Pong seq={seq}"); + } + PeerMessage::FileOffer(offer) => { + mesh.emit(proto::IpcEvent::IncomingFileOffer { + from: proto::PeerId("unknown".into()), // TODO: track per-conn sender + offer, + }); + } + _ => {} + } +} diff --git a/daemon/src/mesh/mod.rs b/daemon/src/mesh/mod.rs new file mode 100644 index 0000000..0e6b491 --- /dev/null +++ b/daemon/src/mesh/mod.rs @@ -0,0 +1,112 @@ +pub mod listener; + +use crate::crypto::Identity; +use proto::{ChatMessage, PeerId, PeerInfo}; +use std::collections::HashMap; +use std::sync::Arc; +use tokio::sync::{broadcast, RwLock}; + +// ── Peer connection handle ──────────────────────────────────────────────────── + +/// A live connection to a peer. Cloneable handle backed by a channel sender. +#[derive(Clone)] +pub struct PeerConn { + pub info: PeerInfo, + /// Send raw JSON lines to this peer. + pub tx: tokio::sync::mpsc::Sender, +} + +// ── Mesh ────────────────────────────────────────────────────────────────────── + +#[derive(Clone)] +pub struct Mesh(Arc); + +struct Inner { + pub identity: Identity, + peers: RwLock>, + /// Broadcast channel for events that the IPC server fans out to UI clients. + pub event_tx: broadcast::Sender, +} + +impl Mesh { + pub fn new(identity: Identity) -> Self { + let (event_tx, _) = broadcast::channel(256); + Mesh(Arc::new(Inner { + identity, + peers: RwLock::new(HashMap::new()), + event_tx, + })) + } + + pub fn identity(&self) -> &Identity { + &self.0.identity + } + + pub fn subscribe_events(&self) -> broadcast::Receiver { + self.0.event_tx.subscribe() + } + + pub async fn add_peer(&self, conn: PeerConn) { + let peer_info = conn.info.clone(); + { + let mut peers = self.0.peers.write().await; + peers.insert(conn.info.id.clone(), conn); + } + let _ = self + .0 + .event_tx + .send(proto::IpcEvent::PeerConnected { peer: peer_info }); + } + + pub async fn remove_peer(&self, peer_id: &PeerId) { + { + let mut peers = self.0.peers.write().await; + peers.remove(peer_id); + } + let _ = self + .0 + .event_tx + .send(proto::IpcEvent::PeerDisconnected { + peer_id: peer_id.clone(), + }); + } + + pub async fn connected_peers(&self) -> Vec { + self.0 + .peers + .read() + .await + .values() + .map(|c| c.info.clone()) + .collect() + } + + /// Broadcast a chat message to all connected peers. + pub async fn broadcast_chat(&self, msg: ChatMessage) { + let peers = self.0.peers.read().await; + let payload = serde_json::to_string(&proto::PeerMessage::Chat(msg.clone())) + .unwrap_or_default(); + for conn in peers.values() { + let _ = conn.tx.try_send(payload.clone()); + } + // Also emit locally so the UI sees our own messages + let _ = self + .0 + .event_tx + .send(proto::IpcEvent::MessageReceived(msg)); + } + + /// Send a message to a specific peer only. + pub async fn send_to(&self, peer_id: &PeerId, payload: String) -> bool { + let peers = self.0.peers.read().await; + if let Some(conn) = peers.get(peer_id) { + conn.tx.try_send(payload).is_ok() + } else { + false + } + } + + pub fn emit(&self, event: proto::IpcEvent) { + let _ = self.0.event_tx.send(event); + } +} diff --git a/daemon/src/nat.rs b/daemon/src/nat.rs new file mode 100644 index 0000000..d5f0b7f --- /dev/null +++ b/daemon/src/nat.rs @@ -0,0 +1,88 @@ +/// NAT traversal: connects to the relay server (if configured) and registers +/// this peer so friends can find us and relay-forward messages until a direct +/// connection is established. +/// +/// Future: add UDP hole-punching via STUN / ICE. +use crate::mesh::Mesh; +use anyhow::Result; +use proto::{RelayClientMessage, RelayServerMessage}; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + net::TcpStream, + time::{sleep, Duration}, +}; +use tracing::{info, warn}; + +pub async fn run(mesh: Mesh, relay_addr: Option) -> Result<()> { + let Some(addr) = relay_addr else { + info!("No relay configured — skipping NAT traversal"); + // Sleep forever; the task just needs to stay alive. + std::future::pending::<()>().await; + return Ok(()); + }; + + loop { + info!("Connecting to relay at {addr}"); + match connect_relay(&addr, &mesh).await { + Ok(()) => info!("Relay connection closed cleanly"), + Err(e) => warn!("Relay error: {e:#}"), + } + info!("Reconnecting to relay in 10s..."); + sleep(Duration::from_secs(10)).await; + } +} + +async fn connect_relay(addr: &str, mesh: &Mesh) -> Result<()> { + let stream = TcpStream::connect(addr).await?; + let (reader, mut writer) = stream.into_split(); + let mut reader = BufReader::new(reader); + + // Register with the relay + let identity = mesh.identity(); + let reg = RelayClientMessage::Register { + peer: identity.peer_info(), + signature: identity.sign(identity.peer_id().0.as_bytes())?, + }; + writer + .write_all((serde_json::to_string(®)? + "\n").as_bytes()) + .await?; + info!("Registered with relay as {}", identity.peer_id()); + + // Ask for peer list (bootstrap) + let list_req = RelayClientMessage::ListPeers; + writer + .write_all((serde_json::to_string(&list_req)? + "\n").as_bytes()) + .await?; + + // Read relay messages + let mut line = String::new(); + loop { + line.clear(); + let n = reader.read_line(&mut line).await?; + if n == 0 { + break; + } + let msg: RelayServerMessage = match serde_json::from_str(line.trim()) { + Ok(m) => m, + Err(e) => { + warn!("Bad relay message: {e}"); + continue; + } + }; + match msg { + RelayServerMessage::PeerList { peers } => { + info!("Relay gave us {} peer hints", peers.len()); + // TODO: attempt direct connections to each peer + } + RelayServerMessage::Forwarded { from, envelope: _ } => { + info!("Relayed message from {from} — direct hole-punch not yet implemented"); + // TODO: decrypt envelope, process as PeerMessage + } + RelayServerMessage::Error { message } => { + warn!("Relay error: {message}"); + } + } + } + + Ok(()) +} diff --git a/proto/Cargo.toml b/proto/Cargo.toml new file mode 100644 index 0000000..e77d078 --- /dev/null +++ b/proto/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "proto" +version = "0.1.0" +edition = "2021" + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +uuid = { workspace = true } +chrono = { workspace = true } diff --git a/proto/src/lib.rs b/proto/src/lib.rs new file mode 100644 index 0000000..fe3168e --- /dev/null +++ b/proto/src/lib.rs @@ -0,0 +1,227 @@ +/// Shared protocol types between daemon and relay. +/// +/// Everything on the wire is JSON-framed over TCP (length-prefixed u32 BE). +/// All binary blobs (keys, signatures, ciphertext) are base64url encoded. +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +// ── Identity ───────────────────────────────────────────────────────────────── + +/// A peer's stable identity: their Ed25519 public key, base64url encoded. +/// This IS the peer — display names are advisory only. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct PeerId(pub String); + +impl std::fmt::Display for PeerId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Show first 8 chars as a short fingerprint in UIs + write!(f, "{}", &self.0[..8.min(self.0.len())]) + } +} + +/// A peer's self-description, signed with their Ed25519 key. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PeerInfo { + pub id: PeerId, + /// Human-readable alias, NOT authenticated — treat as a hint only. + pub alias: String, + /// Ed25519 public key bytes, base64url. + pub public_key: String, + /// When this record was created (used to prefer newer gossip entries). + pub created_at: DateTime, +} + +// ── Handshake ───────────────────────────────────────────────────────────────── + +/// First message sent on a new TCP connection (either direction). +#[derive(Debug, Serialize, Deserialize)] +pub struct Hello { + pub version: u8, + pub peer: PeerInfo, + /// X25519 ephemeral public key for this session, base64url. + pub ephemeral_key: String, + /// Ed25519 signature over (ephemeral_key || peer.id), base64url. + pub signature: String, +} + +/// Response to Hello — completes the handshake. +#[derive(Debug, Serialize, Deserialize)] +pub struct HelloAck { + pub peer: PeerInfo, + pub ephemeral_key: String, + pub signature: String, + /// Whether this peer is willing to relay traffic for others. + pub relay_capable: bool, +} + +// ── Encrypted envelope ──────────────────────────────────────────────────────── + +/// All post-handshake messages are wrapped in this envelope. +/// The inner `payload` is ChaCha20-Poly1305 encrypted. +#[derive(Debug, Serialize, Deserialize)] +pub struct Envelope { + /// Random nonce for this message, base64url (12 bytes). + pub nonce: String, + /// Ciphertext, base64url. + pub payload: String, +} + +// ── Peer-to-peer messages (inside Envelope) ─────────────────────────────────── + +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum PeerMessage { + /// Plain chat message to a public room or DM. + Chat(ChatMessage), + /// Gossip: share known peer addresses with a connected peer. + PeerGossip(PeerGossip), + /// File transfer initiation. + FileOffer(FileOffer), + /// Accept or decline a file offer. + FileResponse(FileResponse), + /// A chunk of file data. + FileChunk(FileChunk), + /// Keepalive ping. + Ping { seq: u64 }, + /// Keepalive pong. + Pong { seq: u64 }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChatMessage { + pub id: Uuid, + pub from: PeerId, + /// None = public room broadcast, Some = DM to that peer. + pub to: Option, + pub room: String, + pub body: String, + pub sent_at: DateTime, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct PeerGossip { + /// Peers this node knows about and their last-seen addresses. + pub peers: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct GossipEntry { + pub peer: PeerInfo, + /// IP:port hint (may be behind NAT — use as a hole-punch target). + pub addr_hint: String, + pub last_seen: DateTime, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FileOffer { + pub transfer_id: Uuid, + pub filename: String, + pub size_bytes: u64, + pub sha256: String, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct FileResponse { + pub transfer_id: Uuid, + pub accepted: bool, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct FileChunk { + pub transfer_id: Uuid, + pub seq: u32, + pub data: String, // base64url + pub is_last: bool, +} + +// ── Relay protocol (relay server speaks this) ───────────────────────────────── + +/// Messages sent TO the relay server. +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum RelayClientMessage { + /// Register with the relay so other peers can find you. + Register { + peer: PeerInfo, + signature: String, + }, + /// Ask the relay to forward an envelope to another peer. + Forward { + to: PeerId, + envelope: Envelope, + }, + /// Ask for the relay's current peer list (for bootstrapping). + ListPeers, +} + +/// Messages sent FROM the relay server. +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum RelayServerMessage { + /// Forwarded envelope from another peer. + Forwarded { + from: PeerId, + envelope: Envelope, + }, + /// Response to ListPeers. + PeerList { + peers: Vec, + }, + /// General error. + Error { message: String }, +} + +// ── Local IPC (daemon ↔ UI) ─────────────────────────────────────────────────── + +/// Commands sent from the UI to the daemon over localhost TCP (port 17337). +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum IpcCommand { + /// Send a chat message. + SendMessage { + room: String, + to: Option, + body: String, + }, + /// Offer a file to a peer. + SendFile { + to: PeerId, + path: String, + }, + /// Connect to a peer by address hint. + Connect { addr: String }, + /// Request current state snapshot. + GetState, +} + +/// Events pushed from the daemon to the UI. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum IpcEvent { + /// A chat message arrived. + MessageReceived(ChatMessage), + /// A peer connected. + PeerConnected { peer: PeerInfo }, + /// A peer disconnected. + PeerDisconnected { peer_id: PeerId }, + /// File offer incoming. + IncomingFileOffer { + from: PeerId, + offer: FileOffer, + }, + /// File transfer progress update. + FileProgress { + transfer_id: Uuid, + bytes_received: u64, + total_bytes: u64, + }, + /// Full state snapshot (response to GetState). + StateSnapshot { + local_peer: PeerInfo, + connected_peers: Vec, + rooms: Vec, + }, + /// Generic error event. + Error { message: String }, +} diff --git a/relay/Cargo.toml b/relay/Cargo.toml new file mode 100644 index 0000000..c8c5c48 --- /dev/null +++ b/relay/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "waste-relay" +version = "0.1.0" +edition = "2021" + +[[bin]] +name = "waste-relay" +path = "src/main.rs" + +[dependencies] +proto = { path = "../proto" } +tokio = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +anyhow = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +chrono = { workspace = true } +clap = { workspace = true } diff --git a/relay/src/main.rs b/relay/src/main.rs new file mode 100644 index 0000000..a7bd691 --- /dev/null +++ b/relay/src/main.rs @@ -0,0 +1,153 @@ +/// waste-relay: minimal relay server. +/// +/// Run this on your Hetzner VPS. Peers register with their public key + address, +/// and can ask the relay to forward encrypted envelopes to other peers. +/// The relay NEVER sees plaintext — it only forwards opaque blobs. +use anyhow::Result; +use chrono::Utc; +use clap::Parser; +use proto::{GossipEntry, PeerId, RelayClientMessage, RelayServerMessage}; +use std::{collections::HashMap, sync::Arc}; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + net::{TcpListener, TcpStream}, + sync::{mpsc, RwLock}, +}; +use tracing::{info, warn}; + +#[derive(Parser)] +#[command(name = "waste-relay", about = "WASTE-rs relay/bootstrap server")] +struct Args { + #[arg(long, default_value = "0.0.0.0:17339")] + bind: String, +} + +// ── Peer registry ───────────────────────────────────────────────────────────── + +struct RegisteredPeer { + gossip: GossipEntry, + /// Channel to forward envelopes to this peer's connection handler. + tx: mpsc::Sender, +} + +type Registry = Arc>>; + +#[tokio::main] +async fn main() -> Result<()> { + tracing_subscriber::fmt() + .with_env_filter("waste_relay=debug,info") + .init(); + + let args = Args::parse(); + let registry: Registry = Arc::new(RwLock::new(HashMap::new())); + + let listener = TcpListener::bind(&args.bind).await?; + info!("waste-relay listening on {}", args.bind); + + loop { + let (stream, addr) = listener.accept().await?; + info!("Client connected: {addr}"); + let registry = registry.clone(); + tokio::spawn(async move { + if let Err(e) = handle_client(stream, registry).await { + warn!("Client error: {e:#}"); + } + }); + } +} + +async fn handle_client(stream: TcpStream, registry: Registry) -> Result<()> { + let peer_addr = stream.peer_addr()?.to_string(); + let (reader, mut writer) = stream.into_split(); + let mut reader = BufReader::new(reader); + + let (tx, mut rx) = mpsc::channel::(64); + + // Writer task + tokio::spawn(async move { + while let Some(msg) = rx.recv().await { + if let Ok(line) = serde_json::to_string(&msg) { + if writer.write_all((line + "\n").as_bytes()).await.is_err() { + break; + } + } + } + }); + + let mut my_peer_id: Option = None; + let mut line = String::new(); + + loop { + line.clear(); + let n = reader.read_line(&mut line).await?; + if n == 0 { + break; + } + + let cmd: RelayClientMessage = match serde_json::from_str(line.trim()) { + Ok(c) => c, + Err(e) => { + warn!("Bad relay message from {peer_addr}: {e}"); + continue; + } + }; + + match cmd { + RelayClientMessage::Register { peer, signature: _ } => { + // TODO: verify signature against peer.public_key + info!("Registered peer {} ({}) at {peer_addr}", peer.id, peer.alias); + my_peer_id = Some(peer.id.clone()); + + let entry = GossipEntry { + peer: peer.clone(), + addr_hint: peer_addr.clone(), + last_seen: Utc::now(), + }; + registry.write().await.insert( + peer.id, + RegisteredPeer { + gossip: entry, + tx: tx.clone(), + }, + ); + } + + RelayClientMessage::ListPeers => { + let peers: Vec = registry + .read() + .await + .values() + .map(|p| p.gossip.clone()) + .collect(); + let _ = tx.send(RelayServerMessage::PeerList { peers }).await; + } + + RelayClientMessage::Forward { to, envelope } => { + let reg = registry.read().await; + if let Some(dest) = reg.get(&to) { + let from = my_peer_id + .clone() + .unwrap_or_else(|| PeerId("unknown".into())); + let _ = dest + .tx + .send(RelayServerMessage::Forwarded { from, envelope }) + .await; + } else { + let _ = tx + .send(RelayServerMessage::Error { + message: format!("Peer {to} not registered"), + }) + .await; + } + } + } + } + + // Clean up on disconnect + if let Some(pid) = my_peer_id { + registry.write().await.remove(&pid); + info!("Peer {pid} ({peer_addr}) unregistered"); + } + + Ok(()) +}