WASM
This commit is contained in:
parent
ade0c3cde4
commit
298253d6fa
31 changed files with 2899 additions and 276 deletions
1
example-usage/.gitignore
vendored
1
example-usage/.gitignore
vendored
|
|
@ -4,3 +4,4 @@ host_sig_pk.bin
|
|||
host_sig_pq_pk.bin
|
||||
host_enc_kem_pk.bin
|
||||
clients.json
|
||||
web-client/node_modules
|
||||
|
|
|
|||
52
example-usage/client/src/auth.rs
Normal file
52
example-usage/client/src/auth.rs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
use std::fs;
|
||||
|
||||
use mtp::client::{ClientConfig, MTPClient, MTPConnection};
|
||||
use mtp::crypto::{Ed25519Signer, Keyring, MlDsaSigner, PublicKeyBundle};
|
||||
|
||||
pub async fn connect_or_register(
|
||||
mut config: ClientConfig,
|
||||
host_public_key: PublicKeyBundle,
|
||||
client_key_path: &str,
|
||||
) -> Result<(MTPConnection, Keyring), Box<dyn std::error::Error>> {
|
||||
if let Ok(data) = fs::read_to_string(client_key_path) {
|
||||
let json: serde_json::Value = serde_json::from_str(&data)?;
|
||||
let client_id = json["client_id"].as_u64().expect("Invalid client_id");
|
||||
let keyring = Keyring::from_bytes(&hex::decode(
|
||||
json["keyring"].as_str().expect("Missing keyring"),
|
||||
)?)?;
|
||||
|
||||
println!("Loaded client keys (ID: {})", client_id);
|
||||
|
||||
config.client_id = client_id;
|
||||
let conn = MTPClient::auth_connect(config, &keyring, &host_public_key).await?;
|
||||
println!("Authenticated (version {})", conn.version);
|
||||
Ok((conn, keyring))
|
||||
} else {
|
||||
println!("No existing keys found: registering new client");
|
||||
|
||||
let (_ed_signer, sig_sk, sig_pk) = Ed25519Signer::generate();
|
||||
let (_pq_signer, sig_pq_sk, sig_pq_pk) = MlDsaSigner::generate();
|
||||
let keyring = Keyring::new(
|
||||
mtp::crypto::KemPublicKey::new(vec![]),
|
||||
mtp::crypto::KemPrivateKey::new(vec![]),
|
||||
sig_pq_pk,
|
||||
sig_pq_sk,
|
||||
sig_pk,
|
||||
sig_sk,
|
||||
);
|
||||
|
||||
let keyring_bytes = keyring.to_bytes();
|
||||
let conn = MTPClient::auth_register(config, &keyring, &host_public_key).await?;
|
||||
println!("Registered with ID: {}", conn.client_id);
|
||||
|
||||
let json = serde_json::json!({
|
||||
"client_id": conn.client_id,
|
||||
"keyring": hex::encode(&keyring_bytes),
|
||||
});
|
||||
fs::write(client_key_path, serde_json::to_string_pretty(&json)?)?;
|
||||
println!("Saved client keys -> {client_key_path}");
|
||||
|
||||
let keyring = Keyring::from_bytes(&keyring_bytes)?;
|
||||
Ok((conn, keyring))
|
||||
}
|
||||
}
|
||||
|
|
@ -1,105 +1,22 @@
|
|||
mod auth;
|
||||
mod messages;
|
||||
|
||||
use std::fs;
|
||||
|
||||
use mtp::client::{ClientConfig, MTPClient, MTPConnection};
|
||||
use mtp::codec::{CommunicationType, CommunicationValue, DataType, DataValue};
|
||||
use mtp::crypto::{
|
||||
Ed25519Signer, KemPublicKey, Keyring, MlDsaSigner, PublicKeyBundle, SignaturePqPublicKey,
|
||||
SignaturePublicKey,
|
||||
};
|
||||
|
||||
/*
|
||||
* Either load a saved keyring from disk (login) or generate a fresh
|
||||
* keypair and register with the server. Returns the established
|
||||
* connection and the local keyring.
|
||||
*/
|
||||
async fn connect_or_register(
|
||||
mut config: ClientConfig,
|
||||
host_public_key: PublicKeyBundle,
|
||||
client_key_path: &str,
|
||||
) -> Result<(MTPConnection, Keyring), Box<dyn std::error::Error>> {
|
||||
if let Ok(data) = fs::read_to_string(client_key_path) {
|
||||
let json: serde_json::Value = serde_json::from_str(&data)?;
|
||||
let client_id = json["client_id"].as_u64().expect("Invalid client_id");
|
||||
let keyring = Keyring::from_bytes(&hex::decode(
|
||||
json["keyring"].as_str().expect("Missing keyring"),
|
||||
)?)?;
|
||||
|
||||
println!("Loaded client keys (ID: {})", client_id);
|
||||
|
||||
config.client_id = client_id;
|
||||
let conn = MTPClient::auth_connect(config, &keyring, &host_public_key).await?;
|
||||
println!("Authenticated (version {})", conn.version);
|
||||
Ok((conn, keyring))
|
||||
} else {
|
||||
println!("No existing keys found: registering new client");
|
||||
|
||||
let (_ed_signer, sig_sk, sig_pk) = Ed25519Signer::generate();
|
||||
let (_pq_signer, sig_pq_sk, sig_pq_pk) = MlDsaSigner::generate();
|
||||
let keyring = Keyring::new(
|
||||
mtp::crypto::KemPublicKey::new(vec![]),
|
||||
mtp::crypto::KemPrivateKey::new(vec![]),
|
||||
sig_pq_pk,
|
||||
sig_pq_sk,
|
||||
sig_pk,
|
||||
sig_sk,
|
||||
);
|
||||
|
||||
let keyring_bytes = keyring.to_bytes();
|
||||
let conn = MTPClient::auth_register(config, &keyring, &host_public_key).await?;
|
||||
println!("Registered with ID: {}", conn.client_id);
|
||||
|
||||
let json = serde_json::json!({
|
||||
"client_id": conn.client_id,
|
||||
"keyring": hex::encode(&keyring_bytes),
|
||||
});
|
||||
fs::write(client_key_path, serde_json::to_string_pretty(&json)?)?;
|
||||
println!("Saved client keys -> {client_key_path}");
|
||||
|
||||
let keyring = Keyring::from_bytes(&keyring_bytes)?;
|
||||
Ok((conn, keyring))
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Send a Ping greeting with description, timestamp, and data fields,
|
||||
* then print the server's Pong response.
|
||||
*/
|
||||
async fn send_ping_and_receive(conn: &MTPConnection) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let timestamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
let greeting = CommunicationValue::new(CommunicationType::Ping)
|
||||
.add_typed_default(DataType::Description, DataValue::Str("Hello MTP!".into()))
|
||||
.add_typed_default(
|
||||
DataType::Timestamp,
|
||||
DataValue::UnsignedNumber(timestamp as u128),
|
||||
)
|
||||
.add_typed_default(DataType::Data, DataValue::UnsignedNumber(42))
|
||||
.with_sender(conn.client_id);
|
||||
|
||||
println!("Sending: {greeting}");
|
||||
conn.sender.send(&greeting).await?;
|
||||
|
||||
match conn.receiver.receive().await {
|
||||
Ok(msg) => println!("Received: {msg}"),
|
||||
Err(e) => eprintln!("Receive error: {e}"),
|
||||
}
|
||||
|
||||
conn.sender.close();
|
||||
Ok(())
|
||||
}
|
||||
use mtp::client::ClientConfig;
|
||||
use mtp::crypto::{KemPublicKey, PublicKeyBundle, SignaturePqPublicKey, SignaturePublicKey};
|
||||
|
||||
#[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 host_public_key = PublicKeyBundle::new(
|
||||
KemPublicKey::new(
|
||||
fs::read("host_enc_kem_pk.bin").expect("Missing host_enc_kem_pk.bin: run server first"),
|
||||
fs::read("host_enc_kem_pk.bin")
|
||||
.expect("Missing host_enc_kem_pk.bin: run server first"),
|
||||
),
|
||||
SignaturePqPublicKey::new(
|
||||
fs::read("host_sig_pq_pk.bin").expect("Missing host_sig_pq_pk.bin: run server first"),
|
||||
fs::read("host_sig_pq_pk.bin")
|
||||
.expect("Missing host_sig_pq_pk.bin: run server first"),
|
||||
),
|
||||
SignaturePublicKey::new(
|
||||
fs::read("host_sig_pk.bin").expect("Missing host_sig_pk.bin: run server first"),
|
||||
|
|
@ -114,8 +31,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
client_id: 0,
|
||||
};
|
||||
|
||||
let (conn, _keyring) = connect_or_register(config, host_public_key, "client_keys.json").await?;
|
||||
send_ping_and_receive(&conn).await?;
|
||||
let (conn, keyring) =
|
||||
auth::connect_or_register(config, host_public_key, "client_keys.json").await?;
|
||||
messages::send_and_receive(&conn, &keyring).await?;
|
||||
|
||||
println!("\nDone");
|
||||
Ok(())
|
||||
|
|
|
|||
81
example-usage/client/src/messages.rs
Normal file
81
example-usage/client/src/messages.rs
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
use mtp::client::MTPConnection;
|
||||
use mtp::codec::{CommunicationType, CommunicationValue, DataType, DataTypeId, DataValue};
|
||||
use mtp::crypto::{ChaCha20Poly1305, Ed25519Signer, Keyring, SigAlgorithm};
|
||||
|
||||
fn derive_demo_key() -> [u8; 32] {
|
||||
mtp::crypto::derive_encryption_key(
|
||||
b"MTP-demo-shared-secret",
|
||||
b"MTP-demo-salt",
|
||||
b"encrypted-container-demo",
|
||||
)
|
||||
.expect("key derivation must succeed")
|
||||
}
|
||||
|
||||
pub fn build_demo_message(client_id: u64, keyring: &Keyring) -> CommunicationValue {
|
||||
let cipher = ChaCha20Poly1305::new(derive_demo_key());
|
||||
let signer = Ed25519Signer::new(&keyring.sig_cl_secret_key)
|
||||
.expect("Ed25519 signer from keyring");
|
||||
|
||||
let inner_enc = DataValue::Container(vec![
|
||||
(DataTypeId(1), DataValue::Str("secret inner data".into())),
|
||||
(DataTypeId(2), DataValue::UnsignedNumber(42)),
|
||||
]);
|
||||
let mut dv_enc = inner_enc;
|
||||
dv_enc.encrypt_container(&cipher, b"demo-aad");
|
||||
|
||||
let inner_sig = DataValue::Container(vec![
|
||||
(DataTypeId(1), DataValue::Str("signed by client".into())),
|
||||
(DataTypeId(2), DataValue::UnsignedNumber(99)),
|
||||
]);
|
||||
let mut dv_sig = inner_sig;
|
||||
dv_sig.sign_container(SigAlgorithm::ED25519, &signer);
|
||||
|
||||
let inner_sec = DataValue::Container(vec![
|
||||
(DataTypeId(1), DataValue::Str("signed+encrypted payload".into())),
|
||||
(DataTypeId(2), DataValue::UnsignedNumber(7)),
|
||||
]);
|
||||
let mut dv_sec = inner_sec;
|
||||
dv_sec.sign_and_encrypt_container(SigAlgorithm::ED25519, &signer, &cipher, b"demo-aad");
|
||||
|
||||
let timestamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.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))
|
||||
.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::Items,
|
||||
DataValue::Array(vec![
|
||||
DataValue::Str("alpha".into()),
|
||||
DataValue::Str("beta".into()),
|
||||
DataValue::Str("gamma".into()),
|
||||
]),
|
||||
)
|
||||
.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)
|
||||
}
|
||||
|
||||
pub async fn send_and_receive(
|
||||
conn: &MTPConnection,
|
||||
keyring: &Keyring,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let msg = build_demo_message(conn.client_id, keyring);
|
||||
println!("Sending: {msg}");
|
||||
conn.sender.send(&msg).await?;
|
||||
|
||||
match conn.receiver.receive().await {
|
||||
Ok(resp) => println!("Received: {resp}"),
|
||||
Err(e) => eprintln!("Receive error: {e}"),
|
||||
}
|
||||
|
||||
conn.sender.close();
|
||||
Ok(())
|
||||
}
|
||||
21
example-usage/server/src/clients.rs
Normal file
21
example-usage/server/src/clients.rs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use mtp::crypto::PublicKeyBundle;
|
||||
|
||||
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,
|
||||
));
|
||||
Ok((clients, next_id))
|
||||
}
|
||||
139
example-usage/server/src/handlers.rs
Normal file
139
example-usage/server/src/handlers.rs
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
use mtp::codec::{CommunicationType, CommunicationValue, DataType, DataTypeId, DataValue, TypeMap};
|
||||
use mtp::crypto::{ChaCha20Poly1305, CryptoError, SignatureScheme, SignaturePublicKey, verify_ed25519};
|
||||
|
||||
struct Ed25519Verifier(SignaturePublicKey);
|
||||
|
||||
impl SignatureScheme for Ed25519Verifier {
|
||||
fn sign(&self, _msg: &[u8]) -> Result<Vec<u8>, CryptoError> {
|
||||
Err(CryptoError::SigningFailed)
|
||||
}
|
||||
fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<(), CryptoError> {
|
||||
verify_ed25519(&self.0, msg, signature)
|
||||
}
|
||||
}
|
||||
|
||||
fn derive_demo_key() -> [u8; 32] {
|
||||
mtp::crypto::derive_encryption_key(
|
||||
b"MTP-demo-shared-secret",
|
||||
b"MTP-demo-salt",
|
||||
b"encrypted-container-demo",
|
||||
)
|
||||
.expect("key derivation must succeed")
|
||||
}
|
||||
|
||||
pub fn process_and_respond(
|
||||
msg: &CommunicationValue,
|
||||
tm: &TypeMap,
|
||||
client_pk: Option<&mtp::crypto::PublicKeyBundle>,
|
||||
) -> CommunicationValue {
|
||||
let desc_id = DataTypeId(tm.data_id_enum(DataType::Description).unwrap());
|
||||
let ts_id = DataTypeId(tm.data_id_enum(DataType::Timestamp).unwrap());
|
||||
let data_id = DataTypeId(tm.data_id_enum(DataType::Data).unwrap());
|
||||
let flags_id = DataTypeId(tm.data_id_enum(DataType::Flags).unwrap());
|
||||
let value_id = DataTypeId(tm.data_id_enum(DataType::Value).unwrap());
|
||||
let bin_id = DataTypeId(tm.data_id_enum(DataType::BinaryData).unwrap());
|
||||
let items_id = DataTypeId(tm.data_id_enum(DataType::Items).unwrap());
|
||||
let enc_id = DataTypeId(tm.data_id_enum(DataType::EncryptedPayload).unwrap());
|
||||
let sig_id = DataTypeId(tm.data_id_enum(DataType::SignedPayload).unwrap());
|
||||
let secure_id = DataTypeId(tm.data_id_enum(DataType::SecurePayload).unwrap());
|
||||
|
||||
let description = msg.get_data(desc_id);
|
||||
let timestamp = msg.get_data(ts_id);
|
||||
let data = msg.get_data(data_id);
|
||||
let flags = msg.get_data(flags_id);
|
||||
let value = msg.get_data(value_id);
|
||||
let binary = msg.get_data(bin_id);
|
||||
let items = msg.get_data(items_id);
|
||||
|
||||
println!(
|
||||
" Description: {}",
|
||||
description.as_str().unwrap_or("(missing)")
|
||||
);
|
||||
println!(" Timestamp: {:?}", timestamp.as_unsigned_number());
|
||||
println!(" Data: {}", data.as_str().unwrap_or("(missing)"));
|
||||
println!(" Flags: {:?}", flags.as_bool());
|
||||
println!(" Value: {:?}", value.as_float());
|
||||
println!(" Binary: {:?}", binary.as_bytes());
|
||||
println!(" Items: {:?}", items.as_array());
|
||||
|
||||
let cipher = ChaCha20Poly1305::new(derive_demo_key());
|
||||
|
||||
let mut enc_status = String::from("EncryptedPayload: not present");
|
||||
let mut sig_status = String::from("SignedPayload: not present");
|
||||
let mut secure_status = String::from("SecurePayload: not present");
|
||||
|
||||
let enc = msg.get_data(enc_id);
|
||||
if matches!(enc, DataValue::EncryptedContainer(_)) {
|
||||
let mut dv = enc.clone();
|
||||
if dv.decrypt_into_container(&cipher, b"demo-aad").is_some() {
|
||||
if let Some(entries) = dv.as_container() {
|
||||
println!(" Decrypted EncryptedPayload: {:?}", entries);
|
||||
enc_status = format!("EncryptedPayload decrypted OK ({} entries)", entries.len());
|
||||
}
|
||||
} else {
|
||||
enc_status = String::from("EncryptedPayload: decryption FAILED");
|
||||
}
|
||||
}
|
||||
|
||||
let sig = msg.get_data(sig_id);
|
||||
if matches!(sig, DataValue::SignedContainer(_)) {
|
||||
if let Some(pk_bundle) = client_pk {
|
||||
let verifier = Ed25519Verifier(pk_bundle.sig_cl_public_key.clone());
|
||||
let mut dv = sig.clone();
|
||||
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());
|
||||
}
|
||||
} else {
|
||||
sig_status = String::from("SignedPayload: verification FAILED");
|
||||
}
|
||||
} else {
|
||||
sig_status = String::from("SignedPayload: no client public key available");
|
||||
}
|
||||
}
|
||||
|
||||
let secure = msg.get_data(secure_id);
|
||||
if matches!(secure, DataValue::SignedEncryptedContainer(_)) {
|
||||
if let Some(pk_bundle) = client_pk {
|
||||
let verifier = Ed25519Verifier(pk_bundle.sig_cl_public_key.clone());
|
||||
let mut dv = secure.clone();
|
||||
if dv.decrypt_signed_encrypted_container(&cipher, b"demo-aad").is_some()
|
||||
&& dv.verify_into_container(&verifier).is_some()
|
||||
{
|
||||
if let Some(entries) = dv.as_container() {
|
||||
println!(" Verified SecurePayload: {:?}", entries);
|
||||
secure_status = format!(
|
||||
"SecurePayload decrypted+verified OK ({} entries)",
|
||||
entries.len()
|
||||
);
|
||||
}
|
||||
} else {
|
||||
secure_status = String::from("SecurePayload: decryption/verification FAILED");
|
||||
}
|
||||
} else {
|
||||
secure_status = String::from("SecurePayload: no client public key available");
|
||||
}
|
||||
}
|
||||
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
CommunicationValue::from_comm(CommunicationType::Pong, tm)
|
||||
.add_data(desc_id, description.clone())
|
||||
.add_data(ts_id, DataValue::UnsignedNumber(now as u128))
|
||||
.add_data(
|
||||
data_id,
|
||||
DataValue::Str(format!(
|
||||
"{}. {}. {}.",
|
||||
enc_status, sig_status, secure_status
|
||||
)),
|
||||
)
|
||||
.add_data(flags_id, flags.clone())
|
||||
.add_data(value_id, value.clone())
|
||||
.add_data(bin_id, binary.clone())
|
||||
.add_data(items_id, items.clone())
|
||||
}
|
||||
40
example-usage/server/src/keys.rs
Normal file
40
example-usage/server/src/keys.rs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
use std::fs;
|
||||
|
||||
use mtp::crypto::{Ed25519Signer, Keyring, MlDsaSigner};
|
||||
use mtp::crypto::kem::HybridKem;
|
||||
|
||||
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);
|
||||
let keyring = Keyring::from_bytes(&hex::decode(json["keyring"].as_str().unwrap())?)?;
|
||||
println!("Loaded host keys (ID: {})", hid);
|
||||
return Ok((hid, keyring));
|
||||
}
|
||||
|
||||
let (_ed_signer, sig_sk, sig_pk) = Ed25519Signer::generate();
|
||||
let (_pq_signer, sig_pq_sk, sig_pq_pk) = MlDsaSigner::generate();
|
||||
let (kem_sk, kem_pk) = HybridKem::generate_keypair();
|
||||
let keyring = Keyring::new(kem_pk, kem_sk, sig_pq_pk, sig_pq_sk, sig_pk, sig_sk);
|
||||
|
||||
let json = serde_json::json!({
|
||||
"host_id": 1,
|
||||
"keyring": hex::encode(keyring.to_bytes()),
|
||||
});
|
||||
fs::write(path, serde_json::to_string_pretty(&json)?)?;
|
||||
println!("Generated host keys -> {path}");
|
||||
Ok((1u64, keyring))
|
||||
}
|
||||
|
||||
pub fn export_host_public_keys(host_keyring: &Keyring) -> Result<(), Box<dyn std::error::Error>> {
|
||||
fs::write(
|
||||
"host_enc_kem_pk.bin",
|
||||
host_keyring.kem_public_key.as_bytes(),
|
||||
)?;
|
||||
fs::write("host_sig_pk.bin", host_keyring.sig_cl_public_key.as_bytes())?;
|
||||
fs::write(
|
||||
"host_sig_pq_pk.bin",
|
||||
host_keyring.sig_pq_public_key.as_bytes(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -1,149 +1,34 @@
|
|||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::sync::{Arc, Mutex};
|
||||
mod clients;
|
||||
mod handlers;
|
||||
mod keys;
|
||||
mod tls;
|
||||
|
||||
use mtp::codec::{CommunicationType, CommunicationValue, DataType, DataTypeId, DataValue, TypeMap};
|
||||
use mtp::crypto::{Ed25519Signer, Keyring, MlDsaSigner, PublicKeyBundle, kem::HybridKem};
|
||||
use mtp::host::{HostConfig, MTPHost};
|
||||
|
||||
/*
|
||||
* Load an existing TLS certificate and key pair from disk. If neither
|
||||
* file exists, generate a self-signed certificate so the server is
|
||||
* immediately usable without external tooling.
|
||||
*/
|
||||
fn load_or_generate_tls(
|
||||
cert_path: &str,
|
||||
key_path: &str,
|
||||
) -> Result<(Vec<u8>, Vec<u8>), Box<dyn std::error::Error>> {
|
||||
if let (Ok(c), Ok(k)) = (fs::read(cert_path), fs::read(key_path)) {
|
||||
println!("Using existing TLS cert from {cert_path}");
|
||||
return Ok((c, k));
|
||||
}
|
||||
|
||||
println!("Generating self-signed TLS certificate ...");
|
||||
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)?;
|
||||
|
||||
let cert_str = cert.pem();
|
||||
let key_str = key_pair.serialize_pem();
|
||||
|
||||
fs::write(cert_path, cert_str.as_bytes())?;
|
||||
fs::write(key_path, key_str.as_bytes())?;
|
||||
println!("Wrote {cert_path} and {key_path}");
|
||||
|
||||
Ok((cert_str.into_bytes(), key_str.into_bytes()))
|
||||
}
|
||||
|
||||
/*
|
||||
* Load the host's Ed25519 identity from a JSON file, or generate a
|
||||
* fresh one and persist it. Clients need the corresponding public key
|
||||
* (exported separately as host_sig_pk.bin) to authenticate the host
|
||||
* during the handshake.
|
||||
*/
|
||||
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);
|
||||
let keyring = Keyring::from_bytes(&hex::decode(json["keyring"].as_str().unwrap())?)?;
|
||||
println!("Loaded host keys (ID: {})", hid);
|
||||
return Ok((hid, keyring));
|
||||
}
|
||||
|
||||
let (_ed_signer, sig_sk, sig_pk) = Ed25519Signer::generate();
|
||||
let (_pq_signer, sig_pq_sk, sig_pq_pk) = MlDsaSigner::generate();
|
||||
let (kem_sk, kem_pk) = HybridKem::generate_keypair();
|
||||
let keyring = Keyring::new(kem_pk, kem_sk, sig_pq_pk, sig_pq_sk, sig_pk, sig_sk);
|
||||
|
||||
let json = serde_json::json!({
|
||||
"host_id": 1,
|
||||
"keyring": hex::encode(keyring.to_bytes()),
|
||||
});
|
||||
fs::write(path, serde_json::to_string_pretty(&json)?)?;
|
||||
println!("Generated host keys -> {path}");
|
||||
Ok((1u64, keyring))
|
||||
}
|
||||
|
||||
/*
|
||||
* Load the client database from disk. Each entry maps a numeric
|
||||
* client ID to its PublicKeyBundle. next_id starts one past the
|
||||
* highest known ID (or 1000 if the DB is empty).
|
||||
*/
|
||||
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,
|
||||
));
|
||||
Ok((clients, next_id))
|
||||
}
|
||||
|
||||
/*
|
||||
* Build a Pong response carrying a description, a Unix timestamp, and
|
||||
* a custom payload according to the negotiated type map.
|
||||
*/
|
||||
fn build_pong_response(tm: &TypeMap) -> CommunicationValue {
|
||||
let timestamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
CommunicationValue::from_comm(CommunicationType::Pong, tm)
|
||||
.add_data(
|
||||
DataTypeId(tm.data_id_enum(DataType::Description).unwrap()),
|
||||
DataValue::Str("Hello from server!".into()),
|
||||
)
|
||||
.add_data(
|
||||
DataTypeId(tm.data_id_enum(DataType::Timestamp).unwrap()),
|
||||
DataValue::UnsignedNumber(timestamp as u128),
|
||||
)
|
||||
.add_data(
|
||||
DataTypeId(tm.data_id_enum(DataType::Data).unwrap()),
|
||||
DataValue::Str("custom payload".into()),
|
||||
)
|
||||
}
|
||||
use mtp::type_map::TypeMap;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let (cert_pem, key_pem) = load_or_generate_tls("server.pem", "server.key")?;
|
||||
let (host_id, host_keyring) = load_or_generate_host_keys("host_keys.json")?;
|
||||
let (cert_pem, key_pem) = tls::load_or_generate_tls("server.pem", "server.key")?;
|
||||
let (host_id, host_keyring) = keys::load_or_generate_host_keys("host_keys.json")?;
|
||||
keys::export_host_public_keys(&host_keyring)?;
|
||||
|
||||
// Export the host's public keys so clients can verify it
|
||||
fs::write(
|
||||
"host_enc_kem_pk.bin",
|
||||
host_keyring.kem_public_key.as_bytes(),
|
||||
)?;
|
||||
fs::write("host_sig_pk.bin", host_keyring.sig_cl_public_key.as_bytes())?;
|
||||
fs::write(
|
||||
"host_sig_pq_pk.bin",
|
||||
host_keyring.sig_pq_public_key.as_bytes(),
|
||||
)?;
|
||||
let (clients, next_id) = clients::load_client_db("clients.json")?;
|
||||
|
||||
let (clients, next_id) = load_client_db("clients.json")?;
|
||||
|
||||
// Clone the Arc so each closure owns its own reference
|
||||
let clients_for_get = clients.clone();
|
||||
let get_existing_user = Box::new(move |id: u64| -> Option<PublicKeyBundle> {
|
||||
let get_existing_user = Box::new(move |id: u64| -> Option<mtp::crypto::PublicKeyBundle> {
|
||||
clients_for_get.lock().unwrap().get(&id).cloned()
|
||||
});
|
||||
|
||||
let clients_for_register = clients.clone();
|
||||
let next_id_for_register = next_id.clone();
|
||||
let clients_path = "clients.json".to_string();
|
||||
let complete_register = Box::new(move |bundle: PublicKeyBundle| -> u64 {
|
||||
let complete_register = Box::new(move |bundle: mtp::crypto::PublicKeyBundle| -> u64 {
|
||||
let mut db = clients_for_register.lock().unwrap();
|
||||
let mut nid = next_id_for_register.lock().unwrap();
|
||||
let id = *nid;
|
||||
*nid += 1;
|
||||
db.insert(id, bundle);
|
||||
fs::write(&clients_path, serde_json::to_string_pretty(&*db).unwrap()).ok();
|
||||
std::fs::write(&clients_path, serde_json::to_string_pretty(&*db).unwrap()).ok();
|
||||
println!("Registered new client with ID: {}", id);
|
||||
id
|
||||
});
|
||||
|
|
@ -177,7 +62,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
match conn.receiver.receive().await {
|
||||
Ok(msg) => {
|
||||
println!("Received: {msg}");
|
||||
let response = build_pong_response(tm);
|
||||
let response =
|
||||
handlers::process_and_respond(&msg, tm, conn.client_public_key.as_ref());
|
||||
println!("Sending: {response}");
|
||||
conn.sender.send(&response).await?;
|
||||
}
|
||||
|
|
|
|||
25
example-usage/server/src/tls.rs
Normal file
25
example-usage/server/src/tls.rs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
use std::fs;
|
||||
|
||||
pub fn load_or_generate_tls(
|
||||
cert_path: &str,
|
||||
key_path: &str,
|
||||
) -> Result<(Vec<u8>, Vec<u8>), Box<dyn std::error::Error>> {
|
||||
if let (Ok(c), Ok(k)) = (fs::read(cert_path), fs::read(key_path)) {
|
||||
println!("Using existing TLS cert from {cert_path}");
|
||||
return Ok((c, k));
|
||||
}
|
||||
|
||||
println!("Generating self-signed TLS certificate ...");
|
||||
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)?;
|
||||
|
||||
let cert_str = cert26.pem();
|
||||
let key_str = key_pair.serialize_pem();
|
||||
|
||||
fs::write(cert_path, cert_str.as_bytes())?;
|
||||
fs::write(key_path, key_str.as_bytes())?;
|
||||
println!("Wrote {cert_path} and {key_path}");
|
||||
|
||||
Ok((cert_str.into_bytes(), key_str.into_bytes()))
|
||||
}
|
||||
|
|
@ -8,7 +8,21 @@ type_maps:
|
|||
CommunicationTypes:
|
||||
DataTypes:
|
||||
Data: 32
|
||||
Flags: 33
|
||||
Value: 34
|
||||
BinaryData: 35
|
||||
Items: 36
|
||||
EncryptedPayload: 37
|
||||
SignedPayload: 38
|
||||
SecurePayload: 39
|
||||
"2.0":
|
||||
CommunicationTypes:
|
||||
DataTypes:
|
||||
Data: 34
|
||||
Flags: 33
|
||||
Value: 35
|
||||
BinaryData: 36
|
||||
Items: 37
|
||||
EncryptedPayload: 38
|
||||
SignedPayload: 39
|
||||
SecurePayload: 40
|
||||
|
|
|
|||
20
example-usage/web-client/index.html
Normal file
20
example-usage/web-client/index.html
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<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; }
|
||||
.state { color: #ff0; }
|
||||
.received { color: #0ff; }
|
||||
.error { color: #f00; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>MTP WebTransport Client</h1>
|
||||
<div id="status">Initializing...</div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
1041
example-usage/web-client/package-lock.json
generated
Normal file
1041
example-usage/web-client/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
15
example-usage/web-client/package.json
Normal file
15
example-usage/web-client/package.json
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"name": "mtp-web-client",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.4.0",
|
||||
"vite": "^5.4.0"
|
||||
}
|
||||
}
|
||||
110
example-usage/web-client/src/main.ts
Normal file
110
example-usage/web-client/src/main.ts
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
import init, {
|
||||
WasmClient,
|
||||
ConnectionConfig,
|
||||
ConnectionState,
|
||||
WasmEd25519Signer,
|
||||
ed25519_generate,
|
||||
keyring_from_ed25519,
|
||||
build_demo_message,
|
||||
} from 'mtp-wasm';
|
||||
|
||||
const STATUS = document.getElementById('status')!;
|
||||
const STORAGE_KEY = 'mtp-web-client-keys';
|
||||
|
||||
function log(msg: string, cls = '') {
|
||||
const line = document.createElement('div');
|
||||
line.textContent = msg;
|
||||
if (cls) line.className = cls;
|
||||
STATUS.appendChild(line);
|
||||
}
|
||||
|
||||
function saveKeys(clientId: bigint, keyringBytes: Uint8Array) {
|
||||
const data = {
|
||||
clientId: clientId.toString(),
|
||||
keyring: Array.from(keyringBytes),
|
||||
};
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
|
||||
}
|
||||
|
||||
function loadKeys(): { clientId: bigint; keyringBytes: Uint8Array } | null {
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
async function initWasm() {
|
||||
log('Loading WASM module...');
|
||||
await init();
|
||||
log(`WASM loaded. WebTransport supported: ${WasmClient.is_supported()}`);
|
||||
}
|
||||
|
||||
function createClient(): WasmClient {
|
||||
return new WasmClient(
|
||||
(state: number) => log(`[state] ${ConnectionState[state] ?? state}`, 'state'),
|
||||
(data: Uint8Array) => {
|
||||
const decoder = new TextDecoder();
|
||||
log(`[message] ${data.length} bytes: ${decoder.decode(data)}`, 'received');
|
||||
},
|
||||
(err: any) => log(`[error] ${err}`, 'error'),
|
||||
);
|
||||
}
|
||||
|
||||
function generateKeyringBytes(): Uint8Array {
|
||||
const gen = ed25519_generate();
|
||||
const sk = gen.secretKey as Uint8Array;
|
||||
const pk = gen.publicKey as Uint8Array;
|
||||
gen.signer.free();
|
||||
return keyring_from_ed25519(sk, pk);
|
||||
}
|
||||
|
||||
async function run() {
|
||||
await initWasm();
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
config.free();
|
||||
|
||||
log('\nSending demo message...');
|
||||
const frame = build_demo_message(clientId, keyringBytes);
|
||||
await client.send(frame);
|
||||
log(`Sent ${frame.length} bytes`);
|
||||
|
||||
log('\nClient running. Waiting for incoming messages...');
|
||||
}
|
||||
|
||||
run().catch((e) => {
|
||||
log(`Fatal error: ${e}`, 'error');
|
||||
console.error(e);
|
||||
});
|
||||
26
example-usage/web-client/src/messages.ts
Normal file
26
example-usage/web-client/src/messages.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { build_demo_message, build_ping_frame, parse_auth_response } from 'mtp-wasm';
|
||||
|
||||
export function buildAuthResponse(
|
||||
response: Uint8Array,
|
||||
): {
|
||||
connected: boolean;
|
||||
clientNonce: Uint8Array;
|
||||
assignedId: bigint;
|
||||
timestamp: bigint;
|
||||
signature: Uint8Array;
|
||||
} {
|
||||
return parse_auth_response(response);
|
||||
}
|
||||
|
||||
export function buildDemoMessage(clientId: bigint, keyringBytes: Uint8Array): Uint8Array {
|
||||
return build_demo_message(clientId, keyringBytes);
|
||||
}
|
||||
|
||||
export function buildPingFrame(
|
||||
clientId: bigint,
|
||||
description: string,
|
||||
timestamp: bigint,
|
||||
data?: Uint8Array,
|
||||
): Uint8Array {
|
||||
return build_ping_frame(clientId, description, timestamp, data ?? new Uint8Array());
|
||||
}
|
||||
18
example-usage/web-client/tsconfig.json
Normal file
18
example-usage/web-client/tsconfig.json
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"isolatedModules": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"paths": {
|
||||
"mtp-wasm": ["../../wasm/pkg"]
|
||||
},
|
||||
"rootDir": "../.."
|
||||
},
|
||||
"include": ["src", "../../wasm/pkg"]
|
||||
}
|
||||
10
example-usage/web-client/vite.config.ts
Normal file
10
example-usage/web-client/vite.config.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { defineConfig } from 'vite';
|
||||
import path from 'path';
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
'mtp-wasm': path.resolve(__dirname, '../../wasm/pkg'),
|
||||
},
|
||||
},
|
||||
});
|
||||
Loading…
Reference in a new issue