Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Add Rust workspace and the nectarlink-protocol crate
Bee2fb08ff643d6
diff --git a/Cargo.lock b/Cargo.locknew file mode 100644index 0000000..ebd6790--- /dev/null+++ b/Cargo.lock@@ -0,0 +1,628 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "block-buffer"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"+dependencies = [+ "hybrid-array",+]++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "ciborium"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"+dependencies = [+ "ciborium-io",+ "ciborium-ll",+ "serde",+]++[[package]]+name = "ciborium-io"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"++[[package]]+name = "ciborium-ll"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"+dependencies = [+ "ciborium-io",+ "half",+]++[[package]]+name = "cmov"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"++[[package]]+name = "const-oid"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"++[[package]]+name = "cpufeatures"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"+dependencies = [+ "libc",+]++[[package]]+name = "crunchy"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"++[[package]]+name = "crypto-common"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"+dependencies = [+ "hybrid-array",+]++[[package]]+name = "ctutils"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"+dependencies = [+ "cmov",+]++[[package]]+name = "data-encoding"+version = "2.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"++[[package]]+name = "digest"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"+dependencies = [+ "block-buffer",+ "const-oid",+ "crypto-common",+ "ctutils",+]++[[package]]+name = "displaydoc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "half"+version = "2.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"+dependencies = [+ "cfg-if",+ "crunchy",+ "zerocopy",+]++[[package]]+name = "hmac"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"+dependencies = [+ "digest",+]++[[package]]+name = "hybrid-array"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"+dependencies = [+ "typenum",+]++[[package]]+name = "icu_collections"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"++[[package]]+name = "icu_properties"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"+dependencies = [+ "displaydoc",+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"++[[package]]+name = "icu_provider"+version = "2.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]++[[package]]+name = "libc"+version = "0.2.190"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"++[[package]]+name = "litemap"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"++[[package]]+name = "nectarlink-cli"+version = "0.0.1"+dependencies = [+ "nectarlink-core",+]++[[package]]+name = "nectarlink-core"+version = "0.0.1"+dependencies = [+ "nectarlink-protocol",+]++[[package]]+name = "nectarlink-protocol"+version = "0.0.1"+dependencies = [+ "ciborium",+ "data-encoding",+ "hmac",+ "serde",+ "serde_bytes",+ "sha2",+ "thiserror",+ "tokio",+ "url",+]++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "potential_utf"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"+dependencies = [+ "zerovec",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_bytes"+version = "0.11.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"+dependencies = [+ "serde",+ "serde_core",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "sha2"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]++[[package]]+name = "smallvec"+version = "1.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "synstructure"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "thiserror"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "tinystr"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"+dependencies = [+ "displaydoc",+ "zerovec",+]++[[package]]+name = "tokio"+version = "1.53.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044"+dependencies = [+ "bytes",+ "pin-project-lite",+ "tokio-macros",+]++[[package]]+name = "tokio-macros"+version = "2.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]]+name = "unicode-ident"+version = "1.0.26"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+]++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"++[[package]]+name = "writeable"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"++[[package]]+name = "yoke"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "synstructure",+]++[[package]]+name = "zerocopy"+version = "0.8.59"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.59"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "synstructure",+]++[[package]]+name = "zerotrie"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]diff --git a/Cargo.toml b/Cargo.tomlnew file mode 100644index 0000000..2aa8ba1--- /dev/null+++ b/Cargo.toml@@ -0,0 +1,48 @@+[workspace]+resolver = "3"+members = [+ "core/nectarlink-protocol",+ "core/nectarlink-core",+ "core/nectarlink-cli",+]++[workspace.package]+version = "0.0.1"+edition = "2024"+rust-version = "1.91"+authors = ["The Nectarlink contributors"]+repository = "https://github.com/thtbee/nectarlink"++[workspace.dependencies]+nectarlink-protocol = { path = "core/nectarlink-protocol" }+nectarlink-core = { path = "core/nectarlink-core" }++anyhow = "1"+ciborium = "0.2"+clap = { version = "4.6", features = ["derive"] }+data-encoding = "2.11"+hmac = "0.13"+iroh = "1.3"+rand = "0.10"+rusqlite = { version = "0.40", features = ["bundled"] }+serde = { version = "1", features = ["derive"] }+serde_bytes = "0.11"+sha2 = "0.11"+tempfile = "3"+thiserror = "2"+tokio = { version = "1.53", features = ["rt-multi-thread", "macros", "io-util", "sync", "time", "fs"] }+tracing = "0.1"+tracing-subscriber = { version = "0.3", features = ["env-filter"] }+url = "2.5"++[workspace.lints.rust]+unsafe_code = "deny"+missing_debug_implementations = "warn"++[workspace.lints.clippy]+all = { level = "warn", priority = -1 }++[profile.release]+lto = "thin"+codegen-units = 1+strip = "symbols"diff --git a/core/nectarlink-cli/Cargo.toml b/core/nectarlink-cli/Cargo.tomlnew file mode 100644index 0000000..d516245--- /dev/null+++ b/core/nectarlink-cli/Cargo.toml@@ -0,0 +1,19 @@+[package]+name = "nectarlink-cli"+description = "Nectarlink command-line client for development and scripting"+license = "GPL-3.0-or-later"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+authors.workspace = true+repository.workspace = true++[[bin]]+name = "nectarlink"+path = "src/main.rs"++[dependencies]+nectarlink-core.workspace = true++[lints]+workspace = truediff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsnew file mode 100644index 0000000..2af84e4--- /dev/null+++ b/core/nectarlink-cli/src/main.rs@@ -0,0 +1,2 @@+// SPDX-License-Identifier: GPL-3.0-or-later+fn main() {}diff --git a/core/nectarlink-core/Cargo.toml b/core/nectarlink-core/Cargo.tomlnew file mode 100644index 0000000..2868acd--- /dev/null+++ b/core/nectarlink-core/Cargo.toml@@ -0,0 +1,15 @@+[package]+name = "nectarlink-core"+description = "Nectarlink engine: identity, pairing, sessions and storage"+license = "MPL-2.0"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+authors.workspace = true+repository.workspace = true++[dependencies]+nectarlink-protocol.workspace = true++[lints]+workspace = truediff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsnew file mode 100644index 0000000..f3d2e70--- /dev/null+++ b/core/nectarlink-core/src/lib.rs@@ -0,0 +1,2 @@+// SPDX-License-Identifier: MPL-2.0+//! Nectarlink engine (work in progress).diff --git a/core/nectarlink-protocol/Cargo.toml b/core/nectarlink-protocol/Cargo.tomlnew file mode 100644index 0000000..d374acd--- /dev/null+++ b/core/nectarlink-protocol/Cargo.toml@@ -0,0 +1,26 @@+[package]+name = "nectarlink-protocol"+description = "Nectarlink wire protocol: message types, framing and pairing primitives"+license = "MPL-2.0"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+authors.workspace = true+repository.workspace = true++[dependencies]+ciborium.workspace = true+data-encoding.workspace = true+hmac.workspace = true+serde.workspace = true+serde_bytes.workspace = true+sha2.workspace = true+thiserror.workspace = true+tokio = { workspace = true, features = ["io-util"] }+url.workspace = true++[dev-dependencies]+tokio = { workspace = true, features = ["rt", "macros"] }++[lints]+workspace = truediff --git a/core/nectarlink-protocol/src/envelope.rs b/core/nectarlink-protocol/src/envelope.rsnew file mode 100644index 0000000..cf89a68--- /dev/null+++ b/core/nectarlink-protocol/src/envelope.rs@@ -0,0 +1,138 @@+// SPDX-License-Identifier: MPL-2.0+//! The message envelope carried in every frame (protocol §3.1).++use ciborium::Value;+use serde::{Deserialize, Serialize, de::DeserializeOwned};++use crate::{+ ErrorCode, ProtocolError,+ messages::{ErrorBody, types},+};++/// `{ t: type, id?: request id, re?: reply-to id, b?: body }`+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct Envelope {+ pub t: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub id: Option<u64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub re: Option<u64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub b: Option<Value>,+}++impl Envelope {+ /// A message with a typed body.+ pub fn new<T: Serialize>(t: &str, body: &T) -> Result<Self, ProtocolError> {+ let b = Value::serialized(body).map_err(|e| ProtocolError::BadMessage(e.to_string()))?;+ Ok(Envelope { t: t.to_owned(), id: None, re: None, b: Some(b) })+ }++ /// A message without a body.+ pub fn empty(t: &str) -> Self {+ Envelope { t: t.to_owned(), id: None, re: None, b: None }+ }++ /// An `error` reply.+ pub fn error(code: ErrorCode, msg: impl Into<String>) -> Self {+ let body = ErrorBody { code, msg: Some(msg.into()) };+ Envelope::new(types::ERROR, &body).expect("error bodies always serialize")+ }++ pub fn with_id(mut self, id: u64) -> Self {+ self.id = Some(id);+ self+ }++ pub fn reply_to(mut self, id: Option<u64>) -> Self {+ self.re = id;+ self+ }++ /// Decodes the body. A missing body decodes as an empty map, so messages+ /// whose fields are all optional work without one.+ pub fn body<T: DeserializeOwned>(&self) -> Result<T, ProtocolError> {+ let value = self.b.clone().unwrap_or(Value::Map(Vec::new()));+ value.deserialized().map_err(|e| ProtocolError::BadMessage(format!("{}: {e}", self.t)))+ }++ /// Checks the message type, turning a peer `error` into+ /// [`ProtocolError::Remote`].+ pub fn expect(&self, expected: &'static str) -> Result<(), ProtocolError> {+ if self.t == expected {+ return Ok(());+ }+ if self.t == types::ERROR {+ let err: ErrorBody = self.body()?;+ return Err(ProtocolError::Remote { code: err.code, msg: err.msg.unwrap_or_default() });+ }+ Err(ProtocolError::UnexpectedType { expected, got: self.t.clone() })+ }++ /// Like [`expect`](Self::expect), then decodes the body.+ pub fn expect_body<T: DeserializeOwned>(&self, expected: &'static str) -> Result<T, ProtocolError> {+ self.expect(expected)?;+ self.body()+ }++ pub fn to_cbor(&self) -> Vec<u8> {+ let mut out = Vec::new();+ ciborium::into_writer(self, &mut out).expect("writing to a Vec cannot fail");+ out+ }++ pub fn from_cbor(bytes: &[u8]) -> Result<Self, ProtocolError> {+ ciborium::from_reader(bytes).map_err(|e| ProtocolError::BadMessage(e.to_string()))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::messages::{Ping, types};++ #[test]+ fn round_trips_through_cbor() {+ let env = Envelope::new(types::PING, &Ping { ts: 42 }).unwrap().with_id(7);+ let decoded = Envelope::from_cbor(&env.to_cbor()).unwrap();+ assert_eq!(decoded, env);+ assert_eq!(decoded.expect_body::<Ping>(types::PING).unwrap().ts, 42);+ }++ #[test]+ fn ignores_unknown_fields() {+ // A future peer adds an envelope key and a body field.+ let raw = Value::Map(vec![+ (Value::Text("t".into()), Value::Text("ping".into())),+ (Value::Text("future".into()), Value::Bool(true)),+ (+ Value::Text("b".into()),+ Value::Map(vec![+ (Value::Text("ts".into()), Value::Integer(5.into())),+ (Value::Text("extra".into()), Value::Text("ignored".into())),+ ]),+ ),+ ]);+ let mut bytes = Vec::new();+ ciborium::into_writer(&raw, &mut bytes).unwrap();+ let env = Envelope::from_cbor(&bytes).unwrap();+ assert_eq!(env.body::<Ping>().unwrap().ts, 5);+ }++ #[test]+ fn remote_errors_surface_through_expect() {+ let env = Envelope::error(ErrorCode::Denied, "nope").reply_to(Some(1));+ match env.expect(types::OK) {+ Err(ProtocolError::Remote { code, msg }) => {+ assert_eq!(code, ErrorCode::Denied);+ assert_eq!(msg, "nope");+ }+ other => panic!("unexpected {other:?}"),+ }+ }++ #[test]+ fn garbage_is_a_bad_message() {+ assert!(matches!(Envelope::from_cbor(&[0xff, 0x00, 0x13]), Err(ProtocolError::BadMessage(_))));+ }+}diff --git a/core/nectarlink-protocol/src/error.rs b/core/nectarlink-protocol/src/error.rsnew file mode 100644index 0000000..120f902--- /dev/null+++ b/core/nectarlink-protocol/src/error.rs@@ -0,0 +1,132 @@+// SPDX-License-Identifier: MPL-2.0+use std::{fmt, str::FromStr};++use serde::{Deserialize, Deserializer, Serialize, Serializer};++/// Error codes carried in `error` messages (protocol §8).+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub enum ErrorCode {+ Unsupported,+ Unpaired,+ VersionTooOld,+ FrameTooLarge,+ BadMessage,+ Denied,+ Busy,+ Internal,+ /// A code this implementation doesn't know yet (forward compatibility).+ Other(String),+}++impl ErrorCode {+ pub fn as_str(&self) -> &str {+ match self {+ ErrorCode::Unsupported => "UNSUPPORTED",+ ErrorCode::Unpaired => "UNPAIRED",+ ErrorCode::VersionTooOld => "VERSION_TOO_OLD",+ ErrorCode::FrameTooLarge => "FRAME_TOO_LARGE",+ ErrorCode::BadMessage => "BAD_MESSAGE",+ ErrorCode::Denied => "DENIED",+ ErrorCode::Busy => "BUSY",+ ErrorCode::Internal => "INTERNAL",+ ErrorCode::Other(code) => code,+ }+ }++ /// Numeric QUIC application close code for this error.+ pub fn close_code(&self) -> u32 {+ match self {+ ErrorCode::Unsupported => 1,+ ErrorCode::Unpaired => 2,+ ErrorCode::VersionTooOld => 3,+ ErrorCode::FrameTooLarge => 4,+ ErrorCode::BadMessage => 5,+ ErrorCode::Denied => 6,+ ErrorCode::Busy => 7,+ ErrorCode::Internal | ErrorCode::Other(_) => 8,+ }+ }+}++impl fmt::Display for ErrorCode {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.write_str(self.as_str())+ }+}++impl FromStr for ErrorCode {+ type Err = std::convert::Infallible;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ Ok(match s {+ "UNSUPPORTED" => ErrorCode::Unsupported,+ "UNPAIRED" => ErrorCode::Unpaired,+ "VERSION_TOO_OLD" => ErrorCode::VersionTooOld,+ "FRAME_TOO_LARGE" => ErrorCode::FrameTooLarge,+ "BAD_MESSAGE" => ErrorCode::BadMessage,+ "DENIED" => ErrorCode::Denied,+ "BUSY" => ErrorCode::Busy,+ "INTERNAL" => ErrorCode::Internal,+ other => ErrorCode::Other(other.to_owned()),+ })+ }+}++impl Serialize for ErrorCode {+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ serializer.serialize_str(self.as_str())+ }+}++impl<'de> Deserialize<'de> for ErrorCode {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ let s = String::deserialize(deserializer)?;+ Ok(s.parse().expect("infallible"))+ }+}++/// Errors produced while encoding, decoding or framing messages.+#[derive(Debug, thiserror::Error)]+pub enum ProtocolError {+ #[error("frame of {0} bytes exceeds the {max} byte limit", max = crate::MAX_FRAME_LEN)]+ FrameTooLarge(usize),+ #[error("malformed frame length prefix")]+ BadLength,+ #[error("malformed message: {0}")]+ BadMessage(String),+ #[error("unexpected message type {got:?}, expected {expected:?}")]+ UnexpectedType { expected: &'static str, got: String },+ #[error("peer returned error {code}: {msg}")]+ Remote { code: ErrorCode, msg: String },+ #[error("stream closed")]+ Closed,+ #[error("i/o error: {0}")]+ Io(#[from] std::io::Error),+}++impl ProtocolError {+ /// The error code to report to the peer for this local failure.+ pub fn code(&self) -> ErrorCode {+ match self {+ ProtocolError::FrameTooLarge(_) => ErrorCode::FrameTooLarge,+ ProtocolError::BadLength+ | ProtocolError::BadMessage(_)+ | ProtocolError::UnexpectedType { .. } => ErrorCode::BadMessage,+ ProtocolError::Remote { code, .. } => code.clone(),+ ProtocolError::Closed | ProtocolError::Io(_) => ErrorCode::Internal,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn codes_round_trip_and_tolerate_unknown_values() {+ for code in ["UNSUPPORTED", "UNPAIRED", "DENIED", "VERSION_TOO_OLD"] {+ assert_eq!(code.parse::<ErrorCode>().unwrap().as_str(), code);+ }+ assert_eq!("FUTURE_CODE".parse::<ErrorCode>().unwrap(), ErrorCode::Other("FUTURE_CODE".into()));+ }+}diff --git a/core/nectarlink-protocol/src/frame.rs b/core/nectarlink-protocol/src/frame.rsnew file mode 100644index 0000000..fbc0e0e--- /dev/null+++ b/core/nectarlink-protocol/src/frame.rs@@ -0,0 +1,144 @@+// SPDX-License-Identifier: MPL-2.0+//! Length-prefixed framing: `unsigned LEB128 length || payload` (protocol §3).++use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};++use crate::ProtocolError;++/// Maximum payload length of a frame on control and RPC streams (1 MiB).+pub const MAX_FRAME_LEN: usize = 1 << 20;++/// The longest LEB128 prefix we accept: 4 bytes encodes up to 2^28 - 1.+const MAX_PREFIX_LEN: usize = 4;++fn encode_len(mut len: usize, out: &mut Vec<u8>) {+ loop {+ let byte = (len & 0x7f) as u8;+ len >>= 7;+ if len == 0 {+ out.push(byte);+ return;+ }+ out.push(byte | 0x80);+ }+}++/// Encodes one frame into a new buffer.+pub fn encode_frame(payload: &[u8]) -> Result<Vec<u8>, ProtocolError> {+ if payload.len() > MAX_FRAME_LEN {+ return Err(ProtocolError::FrameTooLarge(payload.len()));+ }+ let mut out = Vec::with_capacity(payload.len() + MAX_PREFIX_LEN);+ encode_len(payload.len(), &mut out);+ out.extend_from_slice(payload);+ Ok(out)+}++/// Decodes one frame from the start of `buf`.+///+/// Returns `Ok(None)` if `buf` doesn't yet contain a complete frame, or+/// `Ok(Some((payload, consumed)))` with the number of bytes consumed.+pub fn decode_frame(buf: &[u8]) -> Result<Option<(&[u8], usize)>, ProtocolError> {+ let mut len = 0usize;+ for (i, &byte) in buf.iter().enumerate().take(MAX_PREFIX_LEN) {+ len |= ((byte & 0x7f) as usize) << (7 * i);+ if byte & 0x80 == 0 {+ if len > MAX_FRAME_LEN {+ return Err(ProtocolError::FrameTooLarge(len));+ }+ let start = i + 1;+ let end = start + len;+ return Ok((buf.len() >= end).then(|| (&buf[start..end], end)));+ }+ }+ if buf.len() >= MAX_PREFIX_LEN { Err(ProtocolError::BadLength) } else { Ok(None) }+}++/// Writes one frame to an async writer.+pub async fn write_frame<W: AsyncWrite + Unpin>(writer: &mut W, payload: &[u8]) -> Result<(), ProtocolError> {+ let frame = encode_frame(payload)?;+ writer.write_all(&frame).await?;+ Ok(())+}++/// Reads one frame from an async reader.+///+/// Returns `Ok(None)` on a clean end of stream before a new frame starts.+pub async fn read_frame<R: AsyncRead + Unpin>(reader: &mut R) -> Result<Option<Vec<u8>>, ProtocolError> {+ let mut len = 0usize;+ for i in 0..MAX_PREFIX_LEN {+ let byte = match reader.read_u8().await {+ Ok(b) => b,+ Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {+ return if i == 0 { Ok(None) } else { Err(ProtocolError::Closed) };+ }+ Err(e) => return Err(e.into()),+ };+ len |= ((byte & 0x7f) as usize) << (7 * i);+ if byte & 0x80 == 0 {+ if len > MAX_FRAME_LEN {+ return Err(ProtocolError::FrameTooLarge(len));+ }+ let mut payload = vec![0u8; len];+ reader.read_exact(&mut payload).await.map_err(|e| {+ if e.kind() == std::io::ErrorKind::UnexpectedEof { ProtocolError::Closed } else { e.into() }+ })?;+ return Ok(Some(payload));+ }+ }+ Err(ProtocolError::BadLength)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn length_prefix_boundaries() {+ for (len, prefix) in [(0usize, 1usize), (127, 1), (128, 2), (16_383, 2), (16_384, 3)] {+ let frame = encode_frame(&vec![0xAB; len]).unwrap();+ assert_eq!(frame.len(), len + prefix, "len {len}");+ let (payload, used) = decode_frame(&frame).unwrap().unwrap();+ assert_eq!(payload.len(), len);+ assert_eq!(used, frame.len());+ }+ }++ #[test]+ fn rejects_oversized_frames() {+ assert!(matches!(encode_frame(&vec![0; MAX_FRAME_LEN + 1]), Err(ProtocolError::FrameTooLarge(_))));+ // Prefix announcing MAX_FRAME_LEN + 1 bytes.+ let mut prefix = Vec::new();+ encode_len(MAX_FRAME_LEN + 1, &mut prefix);+ assert!(matches!(decode_frame(&prefix), Err(ProtocolError::FrameTooLarge(_))));+ }++ #[test]+ fn partial_and_malformed_input() {+ let frame = encode_frame(b"hello").unwrap();+ assert!(decode_frame(&frame[..3]).unwrap().is_none());+ assert!(decode_frame(&[]).unwrap().is_none());+ assert!(matches!(decode_frame(&[0x80, 0x80, 0x80, 0x80]), Err(ProtocolError::BadLength)));+ }++ #[tokio::test]+ async fn async_round_trip() {+ let mut buf = Vec::new();+ write_frame(&mut buf, b"one").await.unwrap();+ write_frame(&mut buf, b"").await.unwrap();+ write_frame(&mut buf, &[9u8; 300]).await.unwrap();++ let mut reader = buf.as_slice();+ assert_eq!(read_frame(&mut reader).await.unwrap().unwrap(), b"one");+ assert_eq!(read_frame(&mut reader).await.unwrap().unwrap(), b"");+ assert_eq!(read_frame(&mut reader).await.unwrap().unwrap(), vec![9u8; 300]);+ assert!(read_frame(&mut reader).await.unwrap().is_none());+ }++ #[tokio::test]+ async fn truncated_stream_is_an_error() {+ let frame = encode_frame(b"truncated").unwrap();+ let mut reader = &frame[..5];+ assert!(matches!(read_frame(&mut reader).await, Err(ProtocolError::Closed)));+ }+}diff --git a/core/nectarlink-protocol/src/id.rs b/core/nectarlink-protocol/src/id.rsnew file mode 100644index 0000000..9297d08--- /dev/null+++ b/core/nectarlink-protocol/src/id.rs@@ -0,0 +1,102 @@+// SPDX-License-Identifier: MPL-2.0+use std::{fmt, str::FromStr, sync::LazyLock};++use data_encoding::{BitOrder, Encoding, Specification};+use serde::{Deserialize, Deserializer, Serialize, Serializer};++/// z-base-32 (human-oriented base32), as used for Device IDs in the UI and in+/// pairing URIs.+static ZBASE32: LazyLock<Encoding> = LazyLock::new(|| {+ let mut spec = Specification::new();+ spec.symbols.push_str("ybndrfg8ejkmcpqxot1uwisza345h769");+ spec.bit_order = BitOrder::MostSignificantFirst;+ spec.encoding().expect("valid z-base-32 specification")+});++/// A device's identity: its Ed25519 public key (32 bytes).+///+/// Equal to the iroh endpoint ID of the device. Displayed in lowercase+/// z-base-32 (52 characters).+#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct DeviceId(pub [u8; 32]);++impl DeviceId {+ pub fn as_bytes(&self) -> &[u8; 32] {+ &self.0+ }++ /// A short form for logs and debugging, e.g. `ybndrfg8`.+ pub fn short(&self) -> String {+ self.to_string()[..8].to_owned()+ }+}++impl fmt::Display for DeviceId {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.write_str(&ZBASE32.encode(&self.0))+ }+}++impl fmt::Debug for DeviceId {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "DeviceId({})", self.short())+ }+}++#[derive(Debug, thiserror::Error, PartialEq, Eq)]+#[error("invalid device ID")]+pub struct ParseDeviceIdError;++impl FromStr for DeviceId {+ type Err = ParseDeviceIdError;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ let bytes =+ ZBASE32.decode(s.trim().to_ascii_lowercase().as_bytes()).map_err(|_| ParseDeviceIdError)?;+ let bytes: [u8; 32] = bytes.try_into().map_err(|_| ParseDeviceIdError)?;+ Ok(DeviceId(bytes))+ }+}++impl Serialize for DeviceId {+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ serde_bytes::Bytes::new(&self.0).serialize(serializer)+ }+}++impl<'de> Deserialize<'de> for DeviceId {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ let bytes = serde_bytes::ByteBuf::deserialize(deserializer)?;+ let bytes: [u8; 32] = bytes+ .into_vec()+ .try_into()+ .map_err(|_| serde::de::Error::custom("device ID must be 32 bytes"))?;+ Ok(DeviceId(bytes))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn display_round_trips() {+ let id = DeviceId([7u8; 32]);+ let text = id.to_string();+ assert_eq!(text.len(), 52);+ assert_eq!(text.parse::<DeviceId>().unwrap(), id);+ assert_eq!(text.to_uppercase().parse::<DeviceId>().unwrap(), id);+ }++ #[test]+ fn zbase32_matches_reference_vector() {+ // From the z-base-32 specification: 0xF0 0xBF 0xC7 -> "6n9hq".+ assert_eq!(ZBASE32.encode(&[0xF0, 0xBF, 0xC7]), "6n9hq");+ }++ #[test]+ fn rejects_bad_input() {+ assert!("not-an-id".parse::<DeviceId>().is_err());+ assert!(ZBASE32.encode(&[1u8; 16]).parse::<DeviceId>().is_err());+ }+}diff --git a/core/nectarlink-protocol/src/lib.rs b/core/nectarlink-protocol/src/lib.rsnew file mode 100644index 0000000..f6531df--- /dev/null+++ b/core/nectarlink-protocol/src/lib.rs@@ -0,0 +1,58 @@+// SPDX-License-Identifier: MPL-2.0+//! The Nectarlink wire protocol (version 0).+//!+//! This crate is pure protocol logic with no networking: device IDs, message+//! types, the CBOR envelope, length-prefixed framing and the pairing+//! primitives. It is specified in `docs/protocol/v0.md`.++mod envelope;+mod error;+mod frame;+mod id;+pub mod messages;+pub mod pairing;++pub use envelope::Envelope;+pub use error::{ErrorCode, ProtocolError};+pub use frame::{MAX_FRAME_LEN, decode_frame, encode_frame, read_frame, write_frame};+pub use id::{DeviceId, ParseDeviceIdError};++/// ALPN for normal sessions between paired devices.+pub const ALPN_SESSION: &[u8] = b"nectarlink/0";+/// ALPN for the pairing ceremony.+pub const ALPN_PAIR: &[u8] = b"nectarlink-pair/0";++/// Protocol version spoken by this implementation.+pub const PROTOCOL_VERSION: u32 = 0;+/// Oldest protocol version this implementation still accepts.+pub const MIN_PROTOCOL_VERSION: u32 = 0;++/// Negotiates the protocol version for a session.+///+/// Returns the version both sides will speak, or `None` if either side's+/// minimum is above what the other speaks.+pub fn negotiate_version(local: (u32, u32), remote: (u32, u32)) -> Option<u32> {+ let (local_proto, local_min) = local;+ let (remote_proto, remote_min) = remote;+ let version = local_proto.min(remote_proto);+ (version >= local_min && version >= remote_min).then_some(version)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn negotiates_lowest_common_version() {+ assert_eq!(negotiate_version((3, 1), (2, 0)), Some(2));+ assert_eq!(negotiate_version((0, 0), (0, 0)), Some(0));+ }++ #[test]+ fn rejects_versions_below_minimum() {+ // Local speaks 5 but needs at least 4; remote only speaks 3.+ assert_eq!(negotiate_version((5, 4), (3, 0)), None);+ // Remote requires at least 2; local only speaks 1.+ assert_eq!(negotiate_version((1, 0), (4, 2)), None);+ }+}diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsnew file mode 100644index 0000000..1b56335--- /dev/null+++ b/core/nectarlink-protocol/src/messages.rs@@ -0,0 +1,237 @@+// SPDX-License-Identifier: MPL-2.0+//! Message bodies for protocol v0 (protocol §5, §7, §9).++use serde::{Deserialize, Serialize};++use crate::{DeviceId, ErrorCode};++/// Message type names (the envelope's `t` field).+pub mod types {+ pub const HELLO: &str = "hello";+ pub const HELLO_UPDATE: &str = "hello.update";+ pub const PING: &str = "ping";+ pub const PONG: &str = "pong";+ pub const OK: &str = "ok";+ pub const ERROR: &str = "error";+ pub const STREAM: &str = "stream";+ pub const EVENT_BATTERY: &str = "event.battery";+ pub const EVENT_DEVICE: &str = "event.device";+ pub const DEVICE_RING: &str = "device.ring";++ pub const PAIR_REQUEST: &str = "pair.request";+ pub const PAIR_ACCEPT: &str = "pair.accept";+ pub const PAIR_COMMIT: &str = "pair.commit";+ pub const PAIR_NONCE: &str = "pair.nonce";+ pub const PAIR_REVEAL: &str = "pair.reveal";+ pub const PAIR_CONFIRM: &str = "pair.confirm";+ pub const PAIR_REVOKE: &str = "pair.revoke";+}++/// What kind of device this is.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum DeviceKind {+ Phone,+ Tablet,+ Desktop,+ Laptop,+ #[serde(other)]+ Unknown,+}++/// A device's power level (see PLAN.md §4.6). Desktops report `NotApplicable`.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum PowerLevel {+ Basic,+ Assist,+ Elevated,+ #[serde(rename = "n/a")]+ NotApplicable,+ /// Unknown values (e.g. from a newer peer) are treated as Basic.+ #[serde(other)]+ Unknown,+}++impl PowerLevel {+ /// The level to use for capability decisions.+ pub fn effective(self) -> PowerLevel {+ match self {+ PowerLevel::Unknown => PowerLevel::Basic,+ other => other,+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct DeviceInfo {+ pub name: String,+ pub kind: DeviceKind,+ pub os: String,+ pub os_ver: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub model: Option<String>,+ /// Optional ARGB seed color for Material You sync.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub accent: Option<u32>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Hello {+ pub proto: u32,+ pub min: u32,+ pub app: String,+ pub device: DeviceInfo,+ #[serde(default)]+ pub caps: Vec<String>,+ pub power: PowerLevel,+}++#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct HelloUpdate {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub caps: Option<Vec<String>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub power: Option<PowerLevel>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub device: Option<DeviceInfo>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub struct Ping {+ /// Sender's monotonic clock in milliseconds.+ pub ts: u64,+}++/// Echoes the `ts` of the matching ping.+pub type Pong = Ping;++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Battery {+ pub level: u8,+ pub charging: bool,+ /// "ac", "usb" or "wireless".+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub plugged: Option<String>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub struct Ring {+ pub on: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ErrorBody {+ pub code: ErrorCode,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub msg: Option<String>,+}++/// First frame of every non-control stream.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct StreamHeader {+ pub svc: String,+ pub op: String,+ pub v: u32,+}++/// An empty body (`{}`).+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct Empty {}++// ---- Pairing (protocol §9) ----++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PairRequest {+ pub device: DeviceInfo,+ #[serde(with = "serde_bytes")]+ pub proof: Vec<u8>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PairAccept {+ pub device: DeviceInfo,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PairCommit {+ pub device: DeviceInfo,+ #[serde(with = "serde_bytes")]+ pub c: Vec<u8>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PairNonce {+ pub device: DeviceInfo,+ #[serde(rename = "nB", with = "serde_bytes")]+ pub n_b: Vec<u8>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PairReveal {+ #[serde(rename = "nA", with = "serde_bytes")]+ pub n_a: Vec<u8>,+}++/// A paired device identity as stored in trust stores and exchanged in tests.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PeerIdentity {+ pub id: DeviceId,+ pub device: DeviceInfo,+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::Envelope;++ fn info() -> DeviceInfo {+ DeviceInfo {+ name: "Pixel 9".into(),+ kind: DeviceKind::Phone,+ os: "android".into(),+ os_ver: "16".into(),+ model: Some("Google Pixel 9".into()),+ accent: None,+ }+ }++ #[test]+ fn hello_round_trips() {+ let hello = Hello {+ proto: 0,+ min: 0,+ app: "0.0.1".into(),+ device: info(),+ caps: vec!["core.ping".into(), "device.battery".into()],+ power: PowerLevel::Elevated,+ };+ let env = Envelope::new(types::HELLO, &hello).unwrap();+ let back: Hello = Envelope::from_cbor(&env.to_cbor()).unwrap().expect_body(types::HELLO).unwrap();+ assert_eq!(back, hello);+ }++ #[test]+ fn unknown_enum_values_are_tolerated() {+ #[derive(Serialize)]+ struct Raw<'a> {+ kind: &'a str,+ power: &'a str,+ }+ #[derive(Deserialize)]+ struct Parsed {+ kind: DeviceKind,+ power: PowerLevel,+ }+ let env = Envelope::new("x", &Raw { kind: "watch", power: "root" }).unwrap();+ let parsed: Parsed = env.body().unwrap();+ assert_eq!(parsed.kind, DeviceKind::Unknown);+ assert_eq!(parsed.power.effective(), PowerLevel::Basic);+ }++ #[test]+ fn power_level_wire_names() {+ let env = Envelope::new("x", &PowerLevel::NotApplicable).unwrap();+ assert_eq!(env.b, Some(ciborium::Value::Text("n/a".into())));+ }+}diff --git a/core/nectarlink-protocol/src/pairing.rs b/core/nectarlink-protocol/src/pairing.rsnew file mode 100644index 0000000..ad76fb0--- /dev/null+++ b/core/nectarlink-protocol/src/pairing.rs@@ -0,0 +1,224 @@+// SPDX-License-Identifier: MPL-2.0+//! Pairing primitives (protocol §9): the QR pairing URI, the pairing proof,+//! and the numeric-comparison commitment and short authentication string.++use std::net::SocketAddr;++use data_encoding::BASE64URL_NOPAD;+use hmac::{Hmac, KeyInit, Mac};+use sha2::{Digest, Sha256};+use url::Url;++use crate::DeviceId;++type HmacSha256 = Hmac<Sha256>;++/// Length of the one-time pairing secret in the QR code (128 bits).+pub const SECRET_LEN: usize = 16;+/// Length of the nonces used in the nearby (numeric comparison) flow.+pub const NONCE_LEN: usize = 16;++const PROOF_LABEL: &[u8] = b"nectarlink-pair-v0";+const SAS_LABEL: &[u8] = b"nectarlink-sas-v0";++/// Contents of the pairing QR code shown by the PC.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PairingUri {+ pub id: DeviceId,+ pub secret: [u8; SECRET_LEN],+ pub name: String,+ pub addrs: Vec<SocketAddr>,+}++#[derive(Debug, thiserror::Error, PartialEq, Eq)]+pub enum PairingUriError {+ #[error("not a Nectarlink pairing link")]+ NotPairing,+ #[error("pairing link version {0} is not supported; please update Nectarlink")]+ UnsupportedVersion(String),+ #[error("pairing link is missing {0}")]+ Missing(&'static str),+ #[error("pairing link has an invalid {0}")]+ Invalid(&'static str),+}++impl PairingUri {+ /// `nectarlink://pair?v=0&id=…&s=…&n=…[&a=ip:port,…]`+ pub fn to_uri(&self) -> String {+ let mut url = Url::parse("nectarlink://pair").expect("static URL");+ {+ let mut q = url.query_pairs_mut();+ q.append_pair("v", "0");+ q.append_pair("id", &self.id.to_string());+ q.append_pair("s", &BASE64URL_NOPAD.encode(&self.secret));+ q.append_pair("n", &self.name);+ if !self.addrs.is_empty() {+ let addrs: Vec<String> = self.addrs.iter().map(ToString::to_string).collect();+ q.append_pair("a", &addrs.join(","));+ }+ }+ url.into()+ }++ pub fn parse(uri: &str) -> Result<Self, PairingUriError> {+ let url = Url::parse(uri.trim()).map_err(|_| PairingUriError::NotPairing)?;+ if url.scheme() != "nectarlink" || url.host_str() != Some("pair") {+ return Err(PairingUriError::NotPairing);+ }+ let get = |key: &str| url.query_pairs().find(|(k, _)| k == key).map(|(_, v)| v.into_owned());++ let version = get("v").ok_or(PairingUriError::Missing("version"))?;+ if version != "0" {+ return Err(PairingUriError::UnsupportedVersion(version));+ }+ let id = get("id")+ .ok_or(PairingUriError::Missing("device ID"))?+ .parse()+ .map_err(|_| PairingUriError::Invalid("device ID"))?;+ let secret: [u8; SECRET_LEN] = BASE64URL_NOPAD+ .decode(get("s").ok_or(PairingUriError::Missing("secret"))?.as_bytes())+ .ok()+ .and_then(|b| b.try_into().ok())+ .ok_or(PairingUriError::Invalid("secret"))?;+ let name = get("n").unwrap_or_default();+ let addrs = match get("a") {+ None => Vec::new(),+ Some(list) => list+ .split(',')+ .filter(|s| !s.is_empty())+ .map(|s| s.parse().map_err(|_| PairingUriError::Invalid("address")))+ .collect::<Result<_, _>>()?,+ };+ Ok(PairingUri { id, secret, name, addrs })+ }+}++fn proof_mac(secret: &[u8; SECRET_LEN], joining: &DeviceId, host: &DeviceId) -> HmacSha256 {+ let mut mac = HmacSha256::new_from_slice(secret).expect("HMAC accepts any key length");+ mac.update(PROOF_LABEL);+ mac.update(joining.as_bytes());+ mac.update(host.as_bytes());+ mac+}++/// Proof that the joining device (phone) scanned the host's (PC's) QR code:+/// `HMAC-SHA256(S, "nectarlink-pair-v0" || joining_id || host_id)`.+pub fn pair_proof(secret: &[u8; SECRET_LEN], joining: &DeviceId, host: &DeviceId) -> [u8; 32] {+ proof_mac(secret, joining, host).finalize().into_bytes().into()+}++/// Verifies a pairing proof in constant time.+pub fn verify_pair_proof(+ secret: &[u8; SECRET_LEN],+ joining: &DeviceId,+ host: &DeviceId,+ proof: &[u8],+) -> bool {+ proof_mac(secret, joining, host).verify_slice(proof).is_ok()+}++/// Commitment to the initiator's nonce: `SHA-256(nA)`.+pub fn commitment(n_a: &[u8]) -> [u8; 32] {+ Sha256::digest(n_a).into()+}++/// Checks a revealed nonce against its commitment.+pub fn verify_commitment(commitment_bytes: &[u8], n_a: &[u8]) -> bool {+ let expected = commitment(n_a);+ // Not secret, but compare without early exit anyway.+ commitment_bytes.len() == expected.len()+ && commitment_bytes.iter().zip(expected).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0+}++/// The 6-digit short authentication string both screens show:+/// `uint32(HMAC-SHA256(nA || nB, "nectarlink-sas-v0" || idA || idB)[0..4]) mod 1,000,000`,+/// where A is the initiator and B the responder.+pub fn sas_code(n_a: &[u8], n_b: &[u8], id_a: &DeviceId, id_b: &DeviceId) -> String {+ let mut key = Vec::with_capacity(n_a.len() + n_b.len());+ key.extend_from_slice(n_a);+ key.extend_from_slice(n_b);+ let mut mac = HmacSha256::new_from_slice(&key).expect("HMAC accepts any key length");+ mac.update(SAS_LABEL);+ mac.update(id_a.as_bytes());+ mac.update(id_b.as_bytes());+ let digest = mac.finalize().into_bytes();+ let value = u32::from_be_bytes([digest[0], digest[1], digest[2], digest[3]]) % 1_000_000;+ format!("{value:06}")+}++#[cfg(test)]+mod tests {+ use super::*;++ fn id(b: u8) -> DeviceId {+ DeviceId([b; 32])+ }++ #[test]+ fn uri_round_trips() {+ let uri = PairingUri {+ id: id(3),+ secret: [9; SECRET_LEN],+ name: "Bee's Desktop".into(),+ addrs: vec!["192.168.1.20:41641".parse().unwrap(), "[fe80::1]:41641".parse().unwrap()],+ };+ let text = uri.to_uri();+ assert!(text.starts_with("nectarlink://pair?v=0&id="));+ assert_eq!(PairingUri::parse(&text).unwrap(), uri);+ }++ #[test]+ fn uri_without_addresses() {+ let uri = PairingUri { id: id(1), secret: [0; SECRET_LEN], name: String::new(), addrs: vec![] };+ assert_eq!(PairingUri::parse(&uri.to_uri()).unwrap(), uri);+ }++ #[test]+ fn uri_errors() {+ assert_eq!(PairingUri::parse("https://example.com"), Err(PairingUriError::NotPairing));+ assert_eq!(+ PairingUri::parse("nectarlink://pair?v=9&id=x&s=y"),+ Err(PairingUriError::UnsupportedVersion("9".into()))+ );+ assert_eq!(+ PairingUri::parse("nectarlink://pair?v=0&s=AAAA"),+ Err(PairingUriError::Missing("device ID"))+ );+ let good =+ PairingUri { id: id(1), secret: [0; SECRET_LEN], name: "x".into(), addrs: vec![] }.to_uri();+ let bad_secret = good.replace("s=AAAAAAAAAAAAAAAAAAAAAA", "s=AAAA");+ assert_eq!(PairingUri::parse(&bad_secret), Err(PairingUriError::Invalid("secret")));+ }++ #[test]+ fn proof_binds_secret_and_both_ids() {+ let secret = [5u8; SECRET_LEN];+ let proof = pair_proof(&secret, &id(1), &id(2));+ assert!(verify_pair_proof(&secret, &id(1), &id(2), &proof));+ assert!(!verify_pair_proof(&[6u8; SECRET_LEN], &id(1), &id(2), &proof), "wrong secret");+ assert!(!verify_pair_proof(&secret, &id(9), &id(2), &proof), "wrong joining device");+ assert!(!verify_pair_proof(&secret, &id(1), &id(9), &proof), "wrong host");+ assert!(!verify_pair_proof(&secret, &id(1), &id(2), &proof[..31]), "truncated");+ }++ #[test]+ fn commitment_checks() {+ let n_a = [1u8; NONCE_LEN];+ let c = commitment(&n_a);+ assert!(verify_commitment(&c, &n_a));+ assert!(!verify_commitment(&c, &[2u8; NONCE_LEN]));+ assert!(!verify_commitment(&c[..10], &n_a));+ }++ #[test]+ fn sas_is_six_digits_and_order_sensitive() {+ let (n_a, n_b) = ([1u8; NONCE_LEN], [2u8; NONCE_LEN]);+ let code = sas_code(&n_a, &n_b, &id(1), &id(2));+ assert_eq!(code.len(), 6);+ assert!(code.chars().all(|c| c.is_ascii_digit()));+ assert_eq!(code, sas_code(&n_a, &n_b, &id(1), &id(2)), "deterministic");+ // A man in the middle presents a different identity on one side.+ assert_ne!(code, sas_code(&n_a, &n_b, &id(1), &id(3)));+ assert_ne!(code, sas_code(&n_b, &n_a, &id(1), &id(2)));+ }+}diff --git a/rust-toolchain.toml b/rust-toolchain.tomlnew file mode 100644index 0000000..73cb934--- /dev/null+++ b/rust-toolchain.toml@@ -0,0 +1,3 @@+[toolchain]+channel = "stable"+components = ["rustfmt", "clippy"]diff --git a/rustfmt.toml b/rustfmt.tomlnew file mode 100644index 0000000..caafbf6--- /dev/null+++ b/rustfmt.toml@@ -0,0 +1,2 @@+max_width = 110+use_small_heuristics = "Max"