Merge
Crypto WASM TESTS
This commit is contained in:
parent
2a00bb35e7
commit
687e6f9642
49 changed files with 6272 additions and 366 deletions
4
example-usage/.gitignore
vendored
4
example-usage/.gitignore
vendored
|
|
@ -3,5 +3,9 @@ host_keys.json
|
|||
host_sig_pk.bin
|
||||
host_sig_pq_pk.bin
|
||||
host_enc_kem_pk.bin
|
||||
host_public_key_bundle.hex
|
||||
clients.json
|
||||
web-client/node_modules
|
||||
dev-cert/
|
||||
web-client/public/host_public_key_bundle.hex
|
||||
web-client/public/mtp_dev_cert_hash.txt
|
||||
|
|
|
|||
2361
example-usage/Cargo.lock
generated
Normal file
2361
example-usage/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -2,13 +2,29 @@ mod auth;
|
|||
mod messages;
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use mtp::client::ClientConfig;
|
||||
use mtp::crypto::{KemPublicKey, PublicKeyBundle, SignaturePqPublicKey, SignaturePublicKey};
|
||||
|
||||
fn dev_cert_path() -> String {
|
||||
std::env::var("MTP_DEV_CERT").unwrap_or_else(|_| {
|
||||
if Path::new("example-usage/dev-cert/cert.pem").exists() {
|
||||
"example-usage/dev-cert/cert.pem".to_string()
|
||||
} else {
|
||||
"dev-cert/cert.pem".to_string()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let cert_pem = fs::read("server.pem").expect("Missing server.pem: run server first");
|
||||
let cert_path = dev_cert_path();
|
||||
let cert_pem = fs::read(&cert_path).unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"Missing TLS certificate at {cert_path}: enter the Nix shell first or run the server to generate it: {e}"
|
||||
)
|
||||
});
|
||||
let host_public_key = PublicKeyBundle::new(
|
||||
KemPublicKey::new(
|
||||
fs::read("host_enc_kem_pk.bin")
|
||||
|
|
|
|||
|
|
@ -27,7 +27,10 @@ pub fn build_demo_message(
|
|||
dv_sig.sign_container(SigAlgorithm::ED25519, &signer);
|
||||
|
||||
let inner_sec = DataValue::Container(vec![
|
||||
(DataTypeId(1), DataValue::Str("signed+encrypted payload".into())),
|
||||
(
|
||||
DataTypeId(1),
|
||||
DataValue::Str("signed+encrypted payload".into()),
|
||||
),
|
||||
(DataTypeId(2), DataValue::UnsignedNumber(7)),
|
||||
]);
|
||||
let mut dv_sec = inner_sec;
|
||||
|
|
@ -38,13 +41,22 @@ pub fn build_demo_message(
|
|||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
CommunicationValue::new(CommunicationType::Ping)
|
||||
.add_typed_default(DataType::Description, DataValue::Str("MTP Data Type Demo".into()))
|
||||
.add_typed_default(DataType::Timestamp, DataValue::UnsignedNumber(timestamp as u128))
|
||||
let msg = CommunicationValue::new(CommunicationType::Ping)
|
||||
.add_typed_default(
|
||||
DataType::Description,
|
||||
DataValue::Str("MTP Data Type Demo".into()),
|
||||
)
|
||||
.add_typed_default(
|
||||
DataType::Timestamp,
|
||||
DataValue::UnsignedNumber(timestamp as u128),
|
||||
)
|
||||
.add_typed_default(DataType::Data, DataValue::Str("Hello, MTP!".into()))
|
||||
.add_typed_default(DataType::Flags, DataValue::BoolTrue)
|
||||
.add_typed_default(DataType::Value, DataValue::Float(2, 12345))
|
||||
.add_typed_default(DataType::BinaryData, DataValue::Bytes(vec![0xDE, 0xAD, 0xBE, 0xEF, 0x42]))
|
||||
.add_typed_default(
|
||||
DataType::BinaryData,
|
||||
DataValue::Bytes(vec![0xDE, 0xAD, 0xBE, 0xEF, 0x42]),
|
||||
)
|
||||
.add_typed_default(
|
||||
DataType::Items,
|
||||
DataValue::Array(vec![
|
||||
|
|
@ -56,7 +68,8 @@ pub fn build_demo_message(
|
|||
.add_typed_default(DataType::EncryptedPayload, dv_enc)
|
||||
.add_typed_default(DataType::SignedPayload, dv_sig)
|
||||
.add_typed_default(DataType::SecurePayload, dv_sec)
|
||||
.with_sender(client_id)
|
||||
.with_sender(client_id);
|
||||
msg
|
||||
}
|
||||
|
||||
pub async fn send_and_receive(
|
||||
|
|
@ -69,7 +82,9 @@ pub async fn send_and_receive(
|
|||
conn.sender.send(&msg).await?;
|
||||
|
||||
match conn.receiver.receive().await {
|
||||
Ok(resp) => println!("Received: {resp}"),
|
||||
Ok(resp) => {
|
||||
println!("Received: {resp}");
|
||||
}
|
||||
Err(e) => eprintln!("Receive error: {e}"),
|
||||
}
|
||||
|
||||
|
|
|
|||
4
example-usage/host_keys.json.stale-no-kem
Normal file
4
example-usage/host_keys.json.stale-no-kem
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"host_id": 1,
|
||||
"keyring": "0000000007a0cc83597da99032dfe763d1e27eb368420b023be3518323638a09c10446e5a1e182beca1c0e8dda17a7b4b69cc0bbf1ec45f0b03c6b3c1052a540f69e4140f7d1d11039398f77a45630b7fe3254b001ce08d5dd92c6cba881ed20f4eefa6153608d7fb766bdb038939348ba091806c8bc5608650ae8c187be3bf90384b3cd227041462ba409d521c3970c7cc3fce096058f2648c6e2e242273e0af2c47fbf4d899be75b910e7d357618248d51c6e608e9c7a247e88f5961cad53bc163cea869a54c4abbc3d6ebbffa918296f4a21694f83941335ac061068ae67edce3783b8a6afb2676171906ba862a97df2b11dc9911d7e654718d2ecfb9e4b69217f50065981f15ce1d7b0b6d249f68a357c9c56b6c3edfbcf876713e7f6376baa181a4535d0ab5811c2b7e7ffef23cfb6a4af0ea4e6e2f55685d594e97a20c0fac2246618120117879f521f7bb2a26a4f697e9451e3f3653695235dac13feeb0cb8999ff41fad6bf55426877bbae8fd1cd8622c2cf90a57701a7136f01a3d03202b6b1488f70c5840ced7509425b1c3ca019bd55060509a8f2bb42977c78187d7d2801309af9ae2f609cb918c1956b0f282fa4eb591b530c7f5f83c1d54bacabe4abe34780e6c6802509082ad38ec1bcc6105eae77e67e3d414c7eb248d3f5582681e9fbbd5183fa978604f094b9013804055745deba587086f2eeb95a911d1cb4d0dd960c64ecfaad2ae0981e44d38c2441b5df03c9ea23338be78dcd0d4e8712ff6e9ab5d751870e7243c06835e2e7a14b7d3005251ab66fbff4820c0e03317035ead18e213846af6325d3e871524708eaa3093f883e223281a8f1be55cd3dc084dbdd461566c35f6a0d418dcc66ab1697242bf1016283f4e50e76e8f42feae937d4b908d6132c7d80755a58120d75489931f58de641f2f8676fca6b60da18e977b38108d8ffe98f96165222c07520c06974b39aa8b5139458ea101727f95818e69a6afcf0fa028224e8c0af5cd4f32db0a0583eb42a11fe7fa08c424563dde4e2977c898f2f68b2f183016c44dba013851d909844981d0d2635e7fe4af8f80ca3acbea30d11a2b92cf4c4866765493217fd078aa8903ea50aeace282d90a156cc37714f95d109c5421f947209656305beffa891717c7bc8802bb3eab87fc753b0450155e5f0b0c7f14bd66db4e69d330b64e8fc6cbc946e515536b06f65966a982435af15c4b612d25434ef3bc98c33c47abc3b98159733c5f03f541342e6d5e1c0ca6caa00e5616cee151771dbf3a73d571ee0b37ae54d4672e411feb1364f5b820dbc0912e8c43a8213d41576d8b207ab8564537a23aa99c08f6079b83a63c376d10b919023cb57363e7562527e634cc45f5131ae3204615ac078bb216677e65cafb2a95246635f76e1a1a7659d8be263ef403395e16ca388ec1b58b51376b221ab64309bb493687e6cfa7587b603a53e00b1eb4d413f299d7741e1de70df3dc6d3190a8c84fffb7a7901d524f4b5d9a7229c5c99f61faf3d5295760f35d3d54bbea944f044c35a2202e6d2865369809d0df2f64151fb83b3a74d8ad1e7b6cc6d0088a535f7ca6dc384bd93cef50132a0d882caac96acecd15d6eeb600ca6c25f7ff19795cf8595d62bdf5022eadc99a471a36a2b46cd1c4f4d999560eadf4994f77c50083eaad96f574100b594a5272b661c80ffed36a364e7aa69e5a0c69f1af9ba44eeb50e892309ca442ec09f0c716d1483f4d74efbf12ff845f5252e83e64d28a83541b5fbef87296e8a19c84c7c6fa46f61299f7375d74c8441e432613a5f721548a010406ab56f18c997a48d74970f6e651f5d1223e233b5b2ff952e3824b72f92755f491110517d71878e7469beaab6c0835c6467598f7969f1b85157dabebb1003b1f9081bab2aa2296a269a35c34f494e706291db5923690c19e4eaafa5bc3e838e3c6434d0ab91c0b95ce4221ed9cfbe011fa24168d821bed5af6f2fbcb75db1e1ea2a71e5a5f38ad4fab3ebf61983745f4464a0fcf5917415b01846d037fdb628637241070287cbcdcdf638353f01c03030bb36df7f48b5b1eba6152d4f569d034b5f2c9b61b1cf0402df910947d100f54bd0b0261445e60c0f4b1e1df292dbf26bb85ab327a19a33bca531d497b4e7181ba54881cfa1b43d35da64436850d298077877bd41cfd172d91413fee1888ad603a2368fedd611690878ca1f789a6fd21b6932b868bb3084e689c8995113478bbf6ba8ad04e937be34dce58b1117ebbd2eddde489fb34028e117b59fac89bf9a6b5970a989840447d3649f6e955fd0561a56d4038fac4fa4f67515400ecbf256a9339a6b61a62ffc101fc7241422e991b54215f2f6ae4d719d99e660cc6800bf33ce2a00a2b8d101908eb32a31ecb311f8d2da5509a4f0800515193d336a716a52868813a8ea5b878aacd5dca3753c66ea38c3f1f48529746581cbc375cdef323d885ee119f4b1397f5828dec90923caae9845c1f189c482d68342a70d979b95943287127996ce137cfdc2ce3f6ecbfe5f5f5b90b8260fc662c897d4cc1414ad77314f4c15b84308f5836d33d8183388dbbc0d15aa2a9c4c14f447450861e373544c25a61b874ba6716af6bce7bec2a42d6408e73fbf0a5b27fbd9aa3055bfd7b0a79cac66c6f51f00ab90bcb0dc28254a8a4fdbfb7c5bc63a6aa7227d0e335eb0eb01124582db8c7b92f8e84515acddc7bb24e2b3059329228c197e3432bead261b2dbf1798491ebb11658700201d4224bc1f165129ac6fac5909a664ef107f70035019ff7051bba3dc980ac3da0020faa51b18eb51dd316605d3842f71c23a1a15ec71c1cc5d650dabe60da9dc7c5600209300a95b9dcf41d3ee469fc9937737d572915f10e5ea2da286e13bf2dbb54ef6"
|
||||
}
|
||||
|
|
@ -14,3 +14,4 @@ tokio = { version = "1", features = ["full"] }
|
|||
serde_json = { version = "1" }
|
||||
hex = "0.4"
|
||||
serde_core = "1.0.228"
|
||||
base64 = "0.22"
|
||||
|
|
|
|||
|
|
@ -8,14 +8,18 @@ pub fn load_client_db(
|
|||
path: &str,
|
||||
) -> Result<(Arc<Mutex<HashMap<u64, PublicKeyBundle>>>, Arc<Mutex<u64>>), Box<dyn std::error::Error>>
|
||||
{
|
||||
let clients: Arc<Mutex<HashMap<u64, PublicKeyBundle>>> =
|
||||
Arc::new(Mutex::new(if let Ok(data) = fs::read_to_string(path) {
|
||||
serde_json::from_str(&data).unwrap_or_default()
|
||||
} else {
|
||||
HashMap::new()
|
||||
}));
|
||||
let next_id = Arc::new(Mutex::new(
|
||||
clients.lock().unwrap().keys().max().unwrap_or(&999) + 1,
|
||||
));
|
||||
let clients_map = match fs::read_to_string(path) {
|
||||
Ok(data) => match serde_json::from_str(&data) {
|
||||
Ok(clients) => clients,
|
||||
Err(e) => {
|
||||
eprintln!("Failed to parse {path}; starting with empty client database: {e}");
|
||||
HashMap::new()
|
||||
}
|
||||
},
|
||||
Err(_) => HashMap::new(),
|
||||
};
|
||||
let clients: Arc<Mutex<HashMap<u64, PublicKeyBundle>>> = Arc::new(Mutex::new(clients_map));
|
||||
let next_value = clients.lock().unwrap().keys().max().unwrap_or(&999) + 1;
|
||||
let next_id = Arc::new(Mutex::new(next_value));
|
||||
Ok((clients, next_id))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -63,6 +63,7 @@ pub fn process_and_respond(
|
|||
enc_status = format!("EncryptedPayload decrypted OK ({} entries)", entries.len());
|
||||
}
|
||||
} else {
|
||||
eprintln!(" EncryptedPayload decryption failed");
|
||||
enc_status = String::from("EncryptedPayload: decryption FAILED");
|
||||
}
|
||||
}
|
||||
|
|
@ -75,13 +76,14 @@ pub fn process_and_respond(
|
|||
if dv.verify_into_container(&verifier).is_some() {
|
||||
if let Some(entries) = dv.as_container() {
|
||||
println!(" Verified SignedPayload: {:?}", entries);
|
||||
sig_status =
|
||||
format!("SignedPayload verified OK ({} entries)", entries.len());
|
||||
sig_status = format!("SignedPayload verified OK ({} entries)", entries.len());
|
||||
}
|
||||
} else {
|
||||
eprintln!(" SignedPayload verification failed");
|
||||
sig_status = String::from("SignedPayload: verification FAILED");
|
||||
}
|
||||
} else {
|
||||
eprintln!(" SignedPayload cannot be verified; no client public key available");
|
||||
sig_status = String::from("SignedPayload: no client public key available");
|
||||
}
|
||||
}
|
||||
|
|
@ -102,9 +104,11 @@ pub fn process_and_respond(
|
|||
);
|
||||
}
|
||||
} else {
|
||||
eprintln!(" SecurePayload decryption/verification failed");
|
||||
secure_status = String::from("SecurePayload: decryption/verification FAILED");
|
||||
}
|
||||
} else {
|
||||
eprintln!(" SecurePayload cannot be verified; no client public key available");
|
||||
secure_status = String::from("SecurePayload: no client public key available");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
use std::fs;
|
||||
|
||||
use mtp::crypto::{Ed25519Signer, Keyring, MlDsaSigner};
|
||||
use mtp::crypto::kem::HybridKem;
|
||||
use mtp::crypto::{Ed25519Signer, Keyring, MlDsaSigner};
|
||||
|
||||
pub fn load_or_generate_host_keys(path: &str) -> Result<(u64, Keyring), Box<dyn std::error::Error>> {
|
||||
pub fn load_or_generate_host_keys(
|
||||
path: &str,
|
||||
) -> Result<(u64, Keyring), Box<dyn std::error::Error>> {
|
||||
if let Ok(data) = fs::read_to_string(path) {
|
||||
let json: serde_json::Value = serde_json::from_str(&data)?;
|
||||
let hid = json["host_id"].as_u64().unwrap_or(1);
|
||||
|
|
@ -27,6 +29,14 @@ pub fn load_or_generate_host_keys(path: &str) -> Result<(u64, Keyring), Box<dyn
|
|||
}
|
||||
|
||||
pub fn export_host_public_keys(host_keyring: &Keyring) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let public_key_bundle_hex = hex::encode(host_keyring.public_key_bundle().as_bytes());
|
||||
|
||||
fs::write("host_public_key_bundle.hex", &public_key_bundle_hex)?;
|
||||
fs::create_dir_all("web-client/public")?;
|
||||
fs::write(
|
||||
"web-client/public/host_public_key_bundle.hex",
|
||||
&public_key_bundle_hex,
|
||||
)?;
|
||||
fs::write(
|
||||
"host_enc_kem_pk.bin",
|
||||
host_keyring.kem_public_key.as_bytes(),
|
||||
|
|
|
|||
|
|
@ -5,10 +5,34 @@ mod tls;
|
|||
|
||||
use mtp::host::{HostConfig, MTPHost};
|
||||
use mtp::type_map::TypeMap;
|
||||
use std::path::Path;
|
||||
|
||||
fn dev_cert_paths() -> (String, String) {
|
||||
let cert = std::env::var("MTP_DEV_CERT").unwrap_or_else(|_| {
|
||||
if Path::new("example-usage/dev-cert/cert.pem").exists() {
|
||||
"example-usage/dev-cert/cert.pem".to_string()
|
||||
} else {
|
||||
"dev-cert/cert.pem".to_string()
|
||||
}
|
||||
});
|
||||
let key = std::env::var("MTP_DEV_KEY").unwrap_or_else(|_| {
|
||||
if Path::new("example-usage/dev-cert/key.pem").exists() {
|
||||
"example-usage/dev-cert/key.pem".to_string()
|
||||
} else {
|
||||
"dev-cert/key.pem".to_string()
|
||||
}
|
||||
});
|
||||
(cert, key)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let (cert_pem, key_pem) = tls::load_or_generate_tls("server.pem", "server.key")?;
|
||||
let (cert_path, key_path) = dev_cert_paths();
|
||||
let (cert_pem, key_pem) = tls::load_or_generate_tls(&cert_path, &key_path)?;
|
||||
let cert_hash = tls::certificate_sha256_hex(&cert_pem)?;
|
||||
tls::export_webtransport_cert_hash(&cert_hash)?;
|
||||
println!("WebTransport certificate sha256: {cert_hash}");
|
||||
|
||||
let (host_id, host_keyring) = keys::load_or_generate_host_keys("host_keys.json")?;
|
||||
keys::export_host_public_keys(&host_keyring)?;
|
||||
|
||||
|
|
@ -21,7 +45,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
|
||||
let clients_for_get = clients.clone();
|
||||
let get_existing_user = Box::new(move |id: u64| -> Option<mtp::crypto::PublicKeyBundle> {
|
||||
clients_for_get.lock().unwrap().get(&id).cloned()
|
||||
let result = clients_for_get.lock().unwrap().get(&id).cloned();
|
||||
if result.is_some() {
|
||||
println!("Auth lookup: client ID {id} found");
|
||||
} else {
|
||||
eprintln!("Auth lookup: unknown client ID {id}");
|
||||
}
|
||||
result
|
||||
});
|
||||
|
||||
let clients_for_register = clients.clone();
|
||||
|
|
@ -33,7 +63,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
let id = *nid;
|
||||
*nid += 1;
|
||||
db.insert(id, bundle);
|
||||
std::fs::write(&clients_path, serde_json::to_string_pretty(&*db).unwrap()).ok();
|
||||
match serde_json::to_string_pretty(&*db) {
|
||||
Ok(json) => match std::fs::write(&clients_path, json) {
|
||||
Ok(()) => {}
|
||||
Err(e) => eprintln!("Failed to persist client database to {clients_path}: {e}"),
|
||||
},
|
||||
Err(e) => eprintln!("Failed to serialize client database after registering {id}: {e}"),
|
||||
}
|
||||
println!("Registered new client with ID: {}", id);
|
||||
id
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use base64::Engine;
|
||||
|
||||
pub fn load_or_generate_tls(
|
||||
cert_path: &str,
|
||||
|
|
@ -10,6 +13,12 @@ pub fn load_or_generate_tls(
|
|||
}
|
||||
|
||||
println!("Generating self-signed TLS certificate ...");
|
||||
if let Some(parent) = Path::new(cert_path).parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
if let Some(parent) = Path::new(key_path).parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
let key_pair = rcgen::KeyPair::generate()?;
|
||||
let params = rcgen::CertificateParams::new(vec!["localhost".into(), "127.0.0.1".into()])?;
|
||||
let cert = params.self_signed(&key_pair)?;
|
||||
|
|
@ -23,3 +32,39 @@ pub fn load_or_generate_tls(
|
|||
|
||||
Ok((cert_str.into_bytes(), key_str.into_bytes()))
|
||||
}
|
||||
|
||||
pub fn certificate_sha256_hex(cert: &[u8]) -> Result<String, Box<dyn std::error::Error>> {
|
||||
let der = if cert.starts_with(b"-----BEGIN CERTIFICATE-----") {
|
||||
let pem = std::str::from_utf8(cert)?;
|
||||
let base64 = pem
|
||||
.lines()
|
||||
.filter(|line| !line.starts_with("-----"))
|
||||
.collect::<String>();
|
||||
base64::engine::general_purpose::STANDARD.decode(base64)?
|
||||
} else {
|
||||
cert.to_vec()
|
||||
};
|
||||
|
||||
Ok(hex::encode(mtp::crypto::sha256(&der)))
|
||||
}
|
||||
|
||||
pub fn export_webtransport_cert_hash(hash: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let public_dir = if Path::new("web-client").exists() {
|
||||
Path::new("web-client/public")
|
||||
} else {
|
||||
Path::new("example-usage/web-client/public")
|
||||
};
|
||||
fs::create_dir_all(public_dir)?;
|
||||
fs::write(public_dir.join("mtp_dev_cert_hash.txt"), hash)?;
|
||||
|
||||
let dev_cert_dir = if Path::new("dev-cert").exists() {
|
||||
Path::new("dev-cert")
|
||||
} else {
|
||||
Path::new("example-usage/dev-cert")
|
||||
};
|
||||
if dev_cert_dir.exists() {
|
||||
fs::write(dev_cert_dir.join("sha256.txt"), hash)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,8 +5,11 @@
|
|||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>MTP Web Client</title>
|
||||
<style>
|
||||
body { font-family: monospace; background: #111; color: #0f0; padding: 2rem; }
|
||||
#status { white-space: pre-wrap; }
|
||||
body { background: #111; color: #eee; font-family: "Public Sans", sans-serif; }
|
||||
label, input, textarea { display: block; margin-bottom: 0.5rem; }
|
||||
input, textarea, button { font-family: "Public Sans", sans-serif; }
|
||||
input, textarea { background: #222; color: #eee; }
|
||||
#status, #key-status { white-space: pre-wrap; }
|
||||
.state { color: #ff0; }
|
||||
.received { color: #0ff; }
|
||||
.error { color: #f00; }
|
||||
|
|
@ -14,7 +17,23 @@
|
|||
</head>
|
||||
<body>
|
||||
<h1>MTP WebTransport Client</h1>
|
||||
<div id="status">Initializing...</div>
|
||||
<label for="server-url">Server URL</label>
|
||||
<input id="server-url" value="https://127.0.0.1:8080" />
|
||||
|
||||
<label for="host-public-key">Host public key bundle hex</label>
|
||||
<textarea id="host-public-key" placeholder="Paste PublicKeyBundle bytes as hex"></textarea>
|
||||
|
||||
<label for="client-public-key">Generated client public key bundle hex</label>
|
||||
<textarea id="client-public-key" readonly></textarea>
|
||||
|
||||
<div>
|
||||
<button id="generate-keypair" type="button">Generate keypair</button>
|
||||
<button id="connect" type="button" disabled>Connect</button>
|
||||
<button id="clear-keys" type="button">Clear saved keys</button>
|
||||
</div>
|
||||
|
||||
<div id="key-status">Initializing...</div>
|
||||
<div id="status"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
0
example-usage/web-client/public/.gitkeep
Normal file
0
example-usage/web-client/public/.gitkeep
Normal file
|
|
@ -2,15 +2,34 @@ import init, {
|
|||
WasmClient,
|
||||
ConnectionConfig,
|
||||
ConnectionState,
|
||||
WasmEd25519Signer,
|
||||
WasmKeyring,
|
||||
ed25519_generate,
|
||||
keyring_from_ed25519,
|
||||
build_demo_message,
|
||||
format_frame,
|
||||
} from "mtp-wasm";
|
||||
|
||||
const STATUS = document.getElementById("status")!;
|
||||
const KEY_STATUS = document.getElementById("key-status")!;
|
||||
const SERVER_URL = document.getElementById("server-url") as HTMLInputElement;
|
||||
const HOST_PUBLIC_KEY = document.getElementById("host-public-key") as HTMLTextAreaElement;
|
||||
const CLIENT_PUBLIC_KEY = document.getElementById("client-public-key") as HTMLTextAreaElement;
|
||||
const GENERATE_KEYPAIR = document.getElementById("generate-keypair") as HTMLButtonElement;
|
||||
const CONNECT = document.getElementById("connect") as HTMLButtonElement;
|
||||
const CLEAR_KEYS = document.getElementById("clear-keys") as HTMLButtonElement;
|
||||
|
||||
const STORAGE_KEY = "mtp-web-client-keys";
|
||||
|
||||
type SavedKeys = {
|
||||
clientId: string | null;
|
||||
keyring: number[];
|
||||
hostPublicKey?: number[];
|
||||
};
|
||||
|
||||
let keyringBytes: Uint8Array | null = null;
|
||||
let clientId: bigint | null = null;
|
||||
let devCertHash = "";
|
||||
|
||||
function log(msg: string, cls = "") {
|
||||
const line = document.createElement("div");
|
||||
line.textContent = msg;
|
||||
|
|
@ -18,28 +37,103 @@ function log(msg: string, cls = "") {
|
|||
STATUS.appendChild(line);
|
||||
}
|
||||
|
||||
function saveKeys(clientId: bigint, keyringBytes: Uint8Array) {
|
||||
const data = {
|
||||
clientId: clientId.toString(),
|
||||
function setKeyStatus(msg: string) {
|
||||
KEY_STATUS.textContent = msg;
|
||||
}
|
||||
|
||||
function bytesToHex(bytes: Uint8Array): string {
|
||||
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
function hexToBytes(value: string): Uint8Array {
|
||||
const hex = value.replace(/[^0-9a-fA-F]/g, "");
|
||||
if (hex.length === 0) throw new Error("host public key is required");
|
||||
if (hex.length % 2 !== 0) throw new Error("host public key hex has an odd length");
|
||||
|
||||
const bytes = new Uint8Array(hex.length / 2);
|
||||
for (let i = 0; i < bytes.length; i += 1) {
|
||||
bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function saveKeys() {
|
||||
if (!keyringBytes) {
|
||||
return;
|
||||
}
|
||||
|
||||
let hostPublicKey: number[] | undefined;
|
||||
try {
|
||||
hostPublicKey = Array.from(hexToBytes(HOST_PUBLIC_KEY.value));
|
||||
} catch {
|
||||
hostPublicKey = undefined;
|
||||
}
|
||||
|
||||
const data: SavedKeys = {
|
||||
clientId: clientId?.toString() ?? null,
|
||||
keyring: Array.from(keyringBytes),
|
||||
hostPublicKey,
|
||||
};
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
|
||||
}
|
||||
|
||||
function loadKeys(): { clientId: bigint; keyringBytes: Uint8Array } | null {
|
||||
function loadKeys() {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
const data = JSON.parse(raw);
|
||||
return {
|
||||
clientId: BigInt(data.clientId),
|
||||
keyringBytes: new Uint8Array(data.keyring),
|
||||
};
|
||||
if (!raw) {
|
||||
setKeyStatus("No client keypair generated yet.");
|
||||
return;
|
||||
}
|
||||
|
||||
const data = JSON.parse(raw) as SavedKeys;
|
||||
keyringBytes = new Uint8Array(data.keyring);
|
||||
clientId = data.clientId ? BigInt(data.clientId) : null;
|
||||
CLIENT_PUBLIC_KEY.value = publicKeyHexFromKeyring(keyringBytes);
|
||||
if (data.hostPublicKey) {
|
||||
HOST_PUBLIC_KEY.value = bytesToHex(new Uint8Array(data.hostPublicKey));
|
||||
}
|
||||
|
||||
setKeyStatus(
|
||||
clientId
|
||||
? `Loaded saved client keypair for client ${clientId}.`
|
||||
: "Loaded generated client keypair. Not registered yet.",
|
||||
);
|
||||
}
|
||||
|
||||
async function loadHostPublicKey() {
|
||||
try {
|
||||
const response = await fetch("/host_public_key_bundle.hex", { cache: "no-store" });
|
||||
if (!response.ok) return;
|
||||
|
||||
const hostPublicKey = (await response.text()).trim();
|
||||
if (!hostPublicKey) return;
|
||||
|
||||
HOST_PUBLIC_KEY.value = hostPublicKey;
|
||||
saveKeys();
|
||||
log(`Loaded host public key bundle (${hostPublicKey.length / 2} bytes).`);
|
||||
} catch {
|
||||
// Manual paste still works when the server has not exported the file yet.
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDevCertHash() {
|
||||
try {
|
||||
const response = await fetch("/mtp_dev_cert_hash.txt", { cache: "no-store" });
|
||||
if (!response.ok) return;
|
||||
|
||||
devCertHash = (await response.text()).trim();
|
||||
if (devCertHash) {
|
||||
log(`Loaded WebTransport certificate hash: ${devCertHash}`);
|
||||
}
|
||||
} catch {
|
||||
devCertHash = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function initWasm() {
|
||||
log("Loading WASM module...");
|
||||
await init();
|
||||
log(`WASM loaded. WebTransport supported: ${WasmClient.is_supported()}`);
|
||||
CONNECT.disabled = !WasmClient.is_supported();
|
||||
}
|
||||
|
||||
function createClient(): WasmClient {
|
||||
|
|
@ -47,11 +141,11 @@ function createClient(): WasmClient {
|
|||
(state: number) =>
|
||||
log(`[state] ${ConnectionState[state] ?? state}`, "state"),
|
||||
(data: Uint8Array) => {
|
||||
const decoder = new TextDecoder();
|
||||
log(
|
||||
`[message] ${data.length} bytes: ${decoder.decode(data)}`,
|
||||
"received",
|
||||
);
|
||||
try {
|
||||
log(`Received: ${format_frame(data)}`, "received");
|
||||
} catch (e) {
|
||||
log(`[message parse error] ${e}`, "error");
|
||||
}
|
||||
},
|
||||
(err: any) => log(`[error] ${err}`, "error"),
|
||||
);
|
||||
|
|
@ -65,55 +159,113 @@ function generateKeyringBytes(): Uint8Array {
|
|||
return keyring_from_ed25519(sk, pk);
|
||||
}
|
||||
|
||||
async function run() {
|
||||
await initWasm();
|
||||
function publicKeyHexFromKeyring(bytes: Uint8Array): string {
|
||||
const keyring = WasmKeyring.from_bytes(bytes);
|
||||
const publicBundle = keyring.public_key_bundle();
|
||||
const publicHex = bytesToHex(publicBundle.to_bytes());
|
||||
publicBundle.free();
|
||||
keyring.free();
|
||||
return publicHex;
|
||||
}
|
||||
|
||||
async function connect() {
|
||||
STATUS.textContent = "";
|
||||
|
||||
if (!WasmClient.is_supported()) {
|
||||
log("WebTransport is not supported in this browser.", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const serverUrl = "https://127.0.0.1:8080";
|
||||
const saved = loadKeys();
|
||||
|
||||
const client = createClient();
|
||||
const config = new ConnectionConfig(serverUrl);
|
||||
|
||||
let clientId: bigint;
|
||||
let keyringBytes: Uint8Array;
|
||||
|
||||
if (saved) {
|
||||
log(`Found saved client keys (ID: ${saved.clientId})`);
|
||||
const hostPk = new Uint8Array(0);
|
||||
clientId = await client.auth_connect(
|
||||
config,
|
||||
hostPk,
|
||||
saved.keyringBytes,
|
||||
saved.clientId,
|
||||
);
|
||||
log(`Authenticated as client ${clientId}`);
|
||||
keyringBytes = saved.keyringBytes;
|
||||
} else {
|
||||
log("No saved keys: registering new client...");
|
||||
const hostPk = new Uint8Array(0);
|
||||
keyringBytes = generateKeyringBytes();
|
||||
clientId = await client.auth_register(config, hostPk, keyringBytes);
|
||||
log(`Registered with ID: ${clientId}`);
|
||||
saveKeys(clientId, keyringBytes);
|
||||
log("Saved client keys to localStorage");
|
||||
if (!keyringBytes) {
|
||||
log("Generate a client keypair first.", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
config.free();
|
||||
const hostPk = hexToBytes(HOST_PUBLIC_KEY.value);
|
||||
await loadDevCertHash();
|
||||
|
||||
log("\nSending demo message...");
|
||||
const frame = build_demo_message(clientId, keyringBytes);
|
||||
await client.send(frame);
|
||||
log(`Sent ${frame.length} bytes`);
|
||||
const client = createClient();
|
||||
const serverUrl = SERVER_URL.value.trim();
|
||||
const config = new ConnectionConfig(serverUrl);
|
||||
if (devCertHash) {
|
||||
log(`Pinning WebTransport certificate hash: sha-256:${devCertHash}`);
|
||||
config.server_certificate_hashes = [`sha-256:${devCertHash}`];
|
||||
} else {
|
||||
log("No WebTransport certificate hash loaded; relying on browser trust store.", "state");
|
||||
}
|
||||
|
||||
log("\nClient running. Waiting for incoming messages...");
|
||||
try {
|
||||
let activeClientId: bigint;
|
||||
if (clientId !== null) {
|
||||
log(`Using saved client ID ${clientId}...`);
|
||||
activeClientId = await client.auth_connect(
|
||||
config,
|
||||
hostPk,
|
||||
keyringBytes,
|
||||
clientId,
|
||||
);
|
||||
log(`Authenticated as client ${activeClientId}`);
|
||||
} else {
|
||||
log("Registering generated client keypair...");
|
||||
activeClientId = await client.auth_register(config, hostPk, keyringBytes);
|
||||
clientId = activeClientId;
|
||||
saveKeys();
|
||||
log(`Registered with ID: ${activeClientId}`);
|
||||
}
|
||||
|
||||
log("\nSending demo message...");
|
||||
const frame = build_demo_message(activeClientId, keyringBytes, hostPk);
|
||||
log(`Sending: ${format_frame(frame)}`, "state");
|
||||
await client.send(frame);
|
||||
log(`Sent ${frame.length} bytes`);
|
||||
|
||||
log("\nClient running. Waiting for incoming messages...");
|
||||
} finally {
|
||||
config.free();
|
||||
}
|
||||
}
|
||||
|
||||
run().catch((e) => {
|
||||
log(`Fatal error: ${e}`, "error");
|
||||
console.error(e);
|
||||
GENERATE_KEYPAIR.addEventListener("click", () => {
|
||||
try {
|
||||
keyringBytes = generateKeyringBytes();
|
||||
clientId = null;
|
||||
saveKeys();
|
||||
CLIENT_PUBLIC_KEY.value = publicKeyHexFromKeyring(keyringBytes);
|
||||
setKeyStatus("Generated client keypair. Not registered yet.");
|
||||
log("Generated and saved a new client keypair.");
|
||||
} catch (e) {
|
||||
log(`Key generation failed: ${e}`, "error");
|
||||
console.error(e);
|
||||
}
|
||||
});
|
||||
|
||||
CONNECT.addEventListener("click", () => {
|
||||
connect().catch((e) => {
|
||||
log(`Fatal error: ${e}`, "error");
|
||||
log(
|
||||
`[fatal context] clientId=${clientId?.toString() ?? "unregistered"}, server=${SERVER_URL.value.trim()}, hostPkChars=${HOST_PUBLIC_KEY.value.replace(/[^0-9a-fA-F]/g, "").length}, keyringBytes=${keyringBytes?.length ?? 0}, certHash=${devCertHash || "none"}`,
|
||||
"error",
|
||||
);
|
||||
console.error(e);
|
||||
});
|
||||
});
|
||||
|
||||
CLEAR_KEYS.addEventListener("click", () => {
|
||||
keyringBytes = null;
|
||||
clientId = null;
|
||||
CLIENT_PUBLIC_KEY.value = "";
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
setKeyStatus("No client keypair generated yet.");
|
||||
log("Cleared saved client keys.");
|
||||
});
|
||||
|
||||
HOST_PUBLIC_KEY.addEventListener("change", saveKeys);
|
||||
|
||||
initWasm()
|
||||
.then(() => {
|
||||
loadKeys();
|
||||
return Promise.all([loadHostPublicKey(), loadDevCertHash()]);
|
||||
})
|
||||
.catch((e) => {
|
||||
log(`Fatal error: ${e}`, "error");
|
||||
console.error(e);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -12,8 +12,12 @@ export function buildAuthResponse(
|
|||
return parse_auth_response(response);
|
||||
}
|
||||
|
||||
export function buildDemoMessage(clientId: bigint, keyringBytes: Uint8Array): Uint8Array {
|
||||
return build_demo_message(clientId, keyringBytes);
|
||||
export function buildDemoMessage(
|
||||
clientId: bigint,
|
||||
keyringBytes: Uint8Array,
|
||||
hostBundle: Uint8Array,
|
||||
): Uint8Array {
|
||||
return build_demo_message(clientId, keyringBytes, hostBundle);
|
||||
}
|
||||
|
||||
export function buildPingFrame(
|
||||
|
|
|
|||
|
|
@ -1,6 +1,13 @@
|
|||
import { defineConfig } from 'vite';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const devCertDir = path.resolve(__dirname, '../dev-cert');
|
||||
const certPath = process.env.MTP_DEV_CERT ?? path.join(devCertDir, 'cert.pem');
|
||||
const keyPath = process.env.MTP_DEV_KEY ?? path.join(devCertDir, 'key.pem');
|
||||
|
||||
const hasDevCert = fs.existsSync(certPath) && fs.existsSync(keyPath);
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
|
|
@ -8,6 +15,12 @@ export default defineConfig({
|
|||
},
|
||||
},
|
||||
server: {
|
||||
https: hasDevCert
|
||||
? {
|
||||
cert: fs.readFileSync(certPath),
|
||||
key: fs.readFileSync(keyPath),
|
||||
}
|
||||
: undefined,
|
||||
fs: {
|
||||
allow: ['.', path.resolve(__dirname, '../../wasm/pkg')],
|
||||
},
|
||||
|
|
|
|||
Loading…
Reference in a new issue