(feat): redesign WASM module, add TypeScript SDK, migrate to pnpm
Some checks failed
CI / rustfmt (push) Successful in 17s
CI / wasm build (push) Successful in 1m16s
CI / clippy (push) Successful in 1m28s
CI / test (push) Successful in 1m48s
CI / example (push) Successful in 1m31s
CI / duplicate code (push) Failing after 33s
CI / web client (push) Failing after 34s
CI / cargo-machete (push) Successful in 1m18s
CI / cargo-deny (push) Failing after 3m2s

This commit is contained in:
Alois 2026-06-27 23:44:27 +02:00
commit 5caa1c9d5f
49 changed files with 3717 additions and 1501 deletions

1
example/Cargo.lock generated
View file

@ -952,7 +952,6 @@ dependencies = [
name = "mtp-host"
version = "0.1.0"
dependencies = [
"log",
"mtp-codec",
"mtp-common",
"mtp-crypto",

View file

@ -41,11 +41,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Connecting to 127.0.0.1:8080 ...");
let config = ClientConfig {
url: "https://127.0.0.1:8080".into(),
server_cert: Some(cert_pem),
client_id: 0,
};
let config = ClientConfig::new("https://127.0.0.1:8080").with_pinned_pem(cert_pem);
let server_bundle = host_public_key.clone();
let (conn, keyring) =

View file

@ -33,7 +33,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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")?;
let (_host_id, host_keyring) = keys::load_or_generate_host_keys("host_keys.json")?;
keys::export_host_public_keys(&host_keyring)?;
// The keyring is moved into the host config; keep a copy for decrypting the
@ -44,7 +44,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let (clients, next_id) = clients::load_client_db("clients.json")?;
let clients_for_get = clients.clone();
let get_existing_user = Box::new(move |id: u64| -> Option<mtp::crypto::PublicKeyBundle> {
let get_existing_user = move |id: u64| -> Option<mtp::crypto::PublicKeyBundle> {
let result = clients_for_get.lock().unwrap().get(&id).cloned();
if result.is_some() {
println!("Auth lookup: client ID {id} found");
@ -52,12 +52,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
eprintln!("Auth lookup: unknown client ID {id}");
}
result
});
};
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: mtp::crypto::PublicKeyBundle| -> u64 {
let complete_register = 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;
@ -72,26 +72,22 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
println!("Registered new client with ID: {}", id);
id
});
};
println!("Starting MTP server on port 8080 ...");
let config = HostConfig {
ip: std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
port: 8080,
tls_fullchain: cert_pem,
tls_key: key_pem,
require_authentication: true,
host_id,
host_keyring,
get_existing_user,
complete_register,
};
let config = HostConfig::new(
std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
8080,
cert_pem,
key_pem,
)
.with_authentication(host_keyring, get_existing_user, complete_register);
let mut host = MTPHost::new(config).await?;
println!("Server listening on {}", host.local_addr());
while let Some(conn) = host.accept().await {
while let Some(conn) = host.accept().await? {
println!(
"\n--- New authenticated connection (version {}) ---",
conn.version

View file

@ -1,130 +0,0 @@
{
"lockfileVersion": 1,
"configVersion": 0,
"workspaces": {
"": {
"name": "mtp-web-client",
"devDependencies": {
"typescript": "^5.4.0",
"vite": "^5.4.0",
},
},
},
"packages": {
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.21.5", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ=="],
"@esbuild/android-arm": ["@esbuild/android-arm@0.21.5", "", { "os": "android", "cpu": "arm" }, "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg=="],
"@esbuild/android-arm64": ["@esbuild/android-arm64@0.21.5", "", { "os": "android", "cpu": "arm64" }, "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A=="],
"@esbuild/android-x64": ["@esbuild/android-x64@0.21.5", "", { "os": "android", "cpu": "x64" }, "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA=="],
"@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.21.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ=="],
"@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.21.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw=="],
"@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.21.5", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g=="],
"@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.21.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ=="],
"@esbuild/linux-arm": ["@esbuild/linux-arm@0.21.5", "", { "os": "linux", "cpu": "arm" }, "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA=="],
"@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.21.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q=="],
"@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.21.5", "", { "os": "linux", "cpu": "ia32" }, "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg=="],
"@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg=="],
"@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg=="],
"@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.21.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w=="],
"@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA=="],
"@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.21.5", "", { "os": "linux", "cpu": "s390x" }, "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A=="],
"@esbuild/linux-x64": ["@esbuild/linux-x64@0.21.5", "", { "os": "linux", "cpu": "x64" }, "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ=="],
"@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.21.5", "", { "os": "none", "cpu": "x64" }, "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg=="],
"@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.21.5", "", { "os": "openbsd", "cpu": "x64" }, "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow=="],
"@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.21.5", "", { "os": "sunos", "cpu": "x64" }, "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg=="],
"@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.21.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A=="],
"@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.21.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA=="],
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.21.5", "", { "os": "win32", "cpu": "x64" }, "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw=="],
"@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.62.2", "", { "os": "android", "cpu": "arm" }, "sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg=="],
"@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.62.2", "", { "os": "android", "cpu": "arm64" }, "sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw=="],
"@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.62.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-v39RCCvj4He82I9sFmk+M1VZ0PLM9sfsLVikjfx2hYBNALhrrOR2D3JjQA6AhlaSOgcR+RzrKY7e1+bT6SUO/A=="],
"@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.62.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-yl0y2vq3S3lHeuXhEdss6TWfKW8vkujImO12tn4ZkG/4oghr09LvdYm2RElVjokTQiUvDUGXLGsYeLqUMCKpGA=="],
"@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.62.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-tT4pvt4qXD+vEoezupCWi+a1F0vvDiksiHc+PxRlYTOH1I6/X4id9jPxTP+Fg+545euaFT1jJVs4CEdHZAU1vw=="],
"@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.62.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-6nU5F2wCW+qvCBhTn1pdIU3bzsIoF7EUwsCDRxilWGprQR6yd508YnH9+OKFCwpfS8pjZqDUmnCAr7exax0XCg=="],
"@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.62.2", "", { "os": "linux", "cpu": "arm" }, "sha512-n1GJHPOvpIfhi3TmrCeh6S6URt9BFCt0KQE3qvexyGCTAKpR4Lg+eWvNZEqu7epxwus/8ElT3hacYEucm49SZg=="],
"@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.62.2", "", { "os": "linux", "cpu": "arm" }, "sha512-JqgflS8wEB+UXV/vS1RpRbifGBeN4D5lz8D8oOFbFZw4vedvdOgCFAjfBmIMdW3yL10XpQQ0Ambepw6MXrhOnA=="],
"@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.62.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-wnFJkogWvN4jm/hQRF2UBaeUmk20j5+DmHvoyWii2b8HJDyvz1MF2OU/6ynXt2KR63rbZLWkFpoytpdc/yBuSA=="],
"@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.62.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-HVu2bp0zhvJ8xHEV9+UUs7S90VadmBSY3LcIMvozbPo4AuMGDWlz3ymHLHZPX4hR67TKTt8Qp5PJ5RBg/i+RMQ=="],
"@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.62.2", "", { "os": "linux", "cpu": "none" }, "sha512-mQqqAV8QaoSgr9I2fKDLY2BAVvmKjWoGiu/cSYQonsLvtqwEn1E4QYfnCOcp5zoEqNhsDYin1s6jx/VJmrxlZg=="],
"@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.62.2", "", { "os": "linux", "cpu": "none" }, "sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ=="],
"@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.62.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A=="],
"@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.62.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w=="],
"@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.62.2", "", { "os": "linux", "cpu": "none" }, "sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg=="],
"@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.62.2", "", { "os": "linux", "cpu": "none" }, "sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q=="],
"@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.62.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg=="],
"@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.62.2", "", { "os": "linux", "cpu": "x64" }, "sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A=="],
"@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.62.2", "", { "os": "linux", "cpu": "x64" }, "sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg=="],
"@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.62.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg=="],
"@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.62.2", "", { "os": "none", "cpu": "arm64" }, "sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA=="],
"@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.62.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg=="],
"@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.62.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q=="],
"@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.62.2", "", { "os": "win32", "cpu": "x64" }, "sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg=="],
"@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.62.2", "", { "os": "win32", "cpu": "x64" }, "sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA=="],
"@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="],
"esbuild": ["esbuild@0.21.5", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.21.5", "@esbuild/android-arm": "0.21.5", "@esbuild/android-arm64": "0.21.5", "@esbuild/android-x64": "0.21.5", "@esbuild/darwin-arm64": "0.21.5", "@esbuild/darwin-x64": "0.21.5", "@esbuild/freebsd-arm64": "0.21.5", "@esbuild/freebsd-x64": "0.21.5", "@esbuild/linux-arm": "0.21.5", "@esbuild/linux-arm64": "0.21.5", "@esbuild/linux-ia32": "0.21.5", "@esbuild/linux-loong64": "0.21.5", "@esbuild/linux-mips64el": "0.21.5", "@esbuild/linux-ppc64": "0.21.5", "@esbuild/linux-riscv64": "0.21.5", "@esbuild/linux-s390x": "0.21.5", "@esbuild/linux-x64": "0.21.5", "@esbuild/netbsd-x64": "0.21.5", "@esbuild/openbsd-x64": "0.21.5", "@esbuild/sunos-x64": "0.21.5", "@esbuild/win32-arm64": "0.21.5", "@esbuild/win32-ia32": "0.21.5", "@esbuild/win32-x64": "0.21.5" }, "bin": "bin/esbuild" }, "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"nanoid": ["nanoid@3.3.15", "", { "bin": "bin/nanoid.cjs" }, "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA=="],
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"postcss": ["postcss@8.5.15", "", { "dependencies": { "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A=="],
"rollup": ["rollup@4.62.2", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.62.2", "@rollup/rollup-android-arm64": "4.62.2", "@rollup/rollup-darwin-arm64": "4.62.2", "@rollup/rollup-darwin-x64": "4.62.2", "@rollup/rollup-freebsd-arm64": "4.62.2", "@rollup/rollup-freebsd-x64": "4.62.2", "@rollup/rollup-linux-arm-gnueabihf": "4.62.2", "@rollup/rollup-linux-arm-musleabihf": "4.62.2", "@rollup/rollup-linux-arm64-gnu": "4.62.2", "@rollup/rollup-linux-arm64-musl": "4.62.2", "@rollup/rollup-linux-loong64-gnu": "4.62.2", "@rollup/rollup-linux-loong64-musl": "4.62.2", "@rollup/rollup-linux-ppc64-gnu": "4.62.2", "@rollup/rollup-linux-ppc64-musl": "4.62.2", "@rollup/rollup-linux-riscv64-gnu": "4.62.2", "@rollup/rollup-linux-riscv64-musl": "4.62.2", "@rollup/rollup-linux-s390x-gnu": "4.62.2", "@rollup/rollup-linux-x64-gnu": "4.62.2", "@rollup/rollup-linux-x64-musl": "4.62.2", "@rollup/rollup-openbsd-x64": "4.62.2", "@rollup/rollup-openharmony-arm64": "4.62.2", "@rollup/rollup-win32-arm64-msvc": "4.62.2", "@rollup/rollup-win32-ia32-msvc": "4.62.2", "@rollup/rollup-win32-x64-gnu": "4.62.2", "@rollup/rollup-win32-x64-msvc": "4.62.2", "fsevents": "~2.3.2" }, "bin": "dist/bin/rollup" }, "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA=="],
"source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"vite": ["vite@5.4.21", "", { "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", "rollup": "^4.20.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || >=20.0.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.4.0" }, "optionalPeers": ["@types/node", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser"], "bin": "bin/vite.js" }, "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw=="],
}
}

View file

@ -23,11 +23,11 @@
<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>
<label for="client-credentials">Saved SDK credentials</label>
<textarea id="client-credentials" readonly></textarea>
<div>
<button id="generate-keypair" type="button">Generate keypair</button>
<button id="generate-keypair" type="button">Use new credentials</button>
<button id="connect" type="button" disabled>Connect</button>
<button id="clear-keys" type="button">Clear saved keys</button>
</div>

View file

@ -3,13 +3,17 @@
"private": true,
"version": "0.1.0",
"type": "module",
"packageManager": "pnpm@11.8.0",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"mtp": "workspace:*"
},
"devDependencies": {
"typescript": "^5.4.0",
"vite": "^5.4.0"
"typescript": "^6.0.3",
"vite": "^8.1.0"
}
}

View file

@ -1,35 +1,34 @@
import init, {
WasmClient,
ConnectionConfig,
ConnectionState,
WasmKeyring,
ed25519_generate,
keyring_from_ed25519,
build_demo_message,
format_frame,
} from "mtp-wasm";
import { MTPClient } from "mtp";
import type { MTPCredentialStorage, MTPLogEvent, ParsedFrame } from "mtp";
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 CLIENT_CREDENTIALS = document.getElementById("client-credentials") 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";
const CREDENTIALS_KEY = "mtp-web-client-credentials";
const HOST_PUBLIC_KEY_KEY = "mtp-web-client-host-public-key";
type SavedKeys = {
clientId: string | null;
keyring: number[];
keyring?: number[];
keyringBytes?: number[];
hostPublicKey?: number[];
};
let keyringBytes: Uint8Array | null = null;
let clientId: bigint | null = null;
let devCertHash = "";
const credentialStorage: MTPCredentialStorage = {
getItem: (key) => localStorage.getItem(key),
setItem: (key, value) => localStorage.setItem(key, value),
removeItem: (key) => localStorage.removeItem(key),
};
function log(msg: string, cls = "") {
const line = document.createElement("div");
line.textContent = msg;
@ -37,6 +36,35 @@ function log(msg: string, cls = "") {
STATUS.appendChild(line);
}
function renderStructured(value: unknown): string {
return JSON.stringify(value, (_key, item) => {
if (typeof item === "bigint") {
return item.toString();
}
if (item instanceof Uint8Array) {
return { bytes: item.length, hex: bytesToHex(item.slice(0, 32)) };
}
return item;
});
}
function formatParsedFrame(frame: ParsedFrame): string {
return renderStructured({
id: frame.id,
type: frame.type,
sender: frame.sender,
receiver: frame.receiver,
data: frame.data,
rawBytes: frame.raw.length,
});
}
function renderLoggerEvent(event: MTPLogEvent): string {
return event.hint === "error"
? `[${event.hint}] ${event.type}: ${event.error}`
: `[${event.hint}] ${event.type}: ${renderStructured(event.data)}`;
}
function setKeyStatus(msg: string) {
KEY_STATUS.textContent = msg;
}
@ -57,37 +85,35 @@ function hexToBytes(value: string): Uint8Array {
return bytes;
}
function saveKeys() {
if (!keyringBytes) {
return;
}
let hostPublicKey: number[] | undefined;
function saveHostPublicKey() {
try {
hostPublicKey = Array.from(hexToBytes(HOST_PUBLIC_KEY.value));
localStorage.setItem(HOST_PUBLIC_KEY_KEY, bytesToHex(hexToBytes(HOST_PUBLIC_KEY.value)));
} catch {
hostPublicKey = undefined;
localStorage.removeItem(HOST_PUBLIC_KEY_KEY);
}
const data: SavedKeys = {
clientId: clientId?.toString() ?? null,
keyring: Array.from(keyringBytes),
hostPublicKey,
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
}
function loadKeys() {
const raw = localStorage.getItem(STORAGE_KEY);
const raw = localStorage.getItem(CREDENTIALS_KEY);
const savedHostPublicKey = localStorage.getItem(HOST_PUBLIC_KEY_KEY);
if (savedHostPublicKey) {
HOST_PUBLIC_KEY.value = savedHostPublicKey;
}
if (!raw) {
setKeyStatus("No client keypair generated yet.");
CLIENT_CREDENTIALS.value = "";
setKeyStatus("No saved SDK credentials. The next connection will generate and store a reusable keyring.");
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);
const keyringLength = (data.keyring ?? data.keyringBytes ?? []).length;
CLIENT_CREDENTIALS.value = renderStructured({
clientId: data.clientId,
keyringBytes: keyringLength,
hostPublicKeyBytes: data.hostPublicKey?.length ?? 0,
});
if (data.hostPublicKey) {
HOST_PUBLIC_KEY.value = bytesToHex(new Uint8Array(data.hostPublicKey));
}
@ -108,7 +134,7 @@ async function loadHostPublicKey() {
if (!hostPublicKey) return;
HOST_PUBLIC_KEY.value = hostPublicKey;
saveKeys();
saveHostPublicKey();
log(`Loaded host public key bundle (${hostPublicKey.length / 2} bytes).`);
} catch {
// Manual paste still works when the server has not exported the file yet.
@ -131,109 +157,82 @@ async function loadDevCertHash() {
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 {
return new WasmClient(
(state: number) =>
log(`[state] ${ConnectionState[state] ?? state}`, "state"),
(data: Uint8Array) => {
try {
log(`Received: ${format_frame(data)}`, "received");
} catch (e) {
log(`[message parse error] ${e}`, "error");
}
},
(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);
}
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;
await MTPClient.create({ url: SERVER_URL.value, storage: credentialStorage, credentialsStorageKey: CREDENTIALS_KEY });
const supported = MTPClient.isSupported();
log(`WASM loaded. WebTransport supported: ${supported}`);
CONNECT.disabled = !supported;
}
async function connect() {
STATUS.textContent = "";
if (!WasmClient.is_supported()) {
if (!MTPClient.isSupported()) {
log("WebTransport is not supported in this browser.", "error");
return;
}
if (!keyringBytes) {
log("Generate a client keypair first.", "error");
return;
}
const hostPk = hexToBytes(HOST_PUBLIC_KEY.value);
saveHostPublicKey();
await loadDevCertHash();
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}`];
const serverCertificateHashes = devCertHash ? [`sha-256:${devCertHash}`] : undefined;
if (serverCertificateHashes) {
log(`Pinning WebTransport certificate hash: ${serverCertificateHashes[0]}`);
} else {
log("No WebTransport certificate hash loaded; relying on browser trust store.", "state");
}
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}`);
}
const client = await MTPClient.create({
url: serverUrl,
hostPublicKey: hostPk,
storage: credentialStorage,
credentialsStorageKey: CREDENTIALS_KEY,
serverCertificateHashes,
pings: { intervalMs: 30_000 },
logger(event) {
log(renderLoggerEvent(event), event.hint === "error" ? "error" : event.type === "state" ? "state" : "");
},
});
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`);
client.subscribe("Pong", (frame: ParsedFrame) => {
log(`Subscribed Pong: ${formatParsedFrame(frame)}`, "received");
});
const activeClientId = await client.connectOrRegister();
clientId = activeClientId;
loadKeys();
log(`Connected as client ${activeClientId}`);
log("\nSending typed Ping...");
await client.send("Ping", {
Description: "MTP web client send ping",
Timestamp: BigInt(Date.now()),
}, { sender: activeClientId });
log("Typed Ping sent.");
log("\nRequesting Pong by Ping frame id...");
const response = await client.request("Ping", {
Description: "MTP web client request ping",
Timestamp: BigInt(Date.now()),
}, { sender: activeClientId, responseType: "Pong" });
log(`Request response: ${formatParsedFrame(response)}`, "received");
log("\nClient running. Waiting for incoming messages...");
} finally {
config.free();
} catch (error) {
log(`[error] ${error}`, "error");
}
}
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.");
localStorage.removeItem(CREDENTIALS_KEY);
CLIENT_CREDENTIALS.value = "";
setKeyStatus("Cleared saved credentials. The next connection will generate a new reusable keyring.");
log("Cleared saved SDK credentials.");
} catch (e) {
log(`Key generation failed: ${e}`, "error");
log(`Credential reset failed: ${e}`, "error");
console.error(e);
}
});
@ -242,7 +241,7 @@ 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"}`,
`[fatal context] clientId=${clientId?.toString() ?? "unregistered"}, server=${SERVER_URL.value.trim()}, hostPkChars=${HOST_PUBLIC_KEY.value.replace(/[^0-9a-fA-F]/g, "").length}, hasStoredCredentials=${localStorage.getItem(CREDENTIALS_KEY) ? "yes" : "no"}, certHash=${devCertHash || "none"}`,
"error",
);
console.error(e);
@ -250,15 +249,15 @@ CONNECT.addEventListener("click", () => {
});
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.");
CLIENT_CREDENTIALS.value = "";
localStorage.removeItem(CREDENTIALS_KEY);
localStorage.removeItem(HOST_PUBLIC_KEY_KEY);
setKeyStatus("No saved SDK credentials.");
log("Cleared saved SDK credentials and host public key.");
});
HOST_PUBLIC_KEY.addEventListener("change", saveKeys);
HOST_PUBLIC_KEY.addEventListener("change", saveHostPublicKey);
initWasm()
.then(() => {

View file

@ -1,30 +0,0 @@
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,
hostBundle: Uint8Array,
): Uint8Array {
return build_demo_message(clientId, keyringBytes, hostBundle);
}
export function buildPingFrame(
clientId: bigint,
description: string,
timestamp: bigint,
data?: Uint8Array,
): Uint8Array {
return build_ping_frame(clientId, description, timestamp, data ?? new Uint8Array());
}

View file

@ -8,11 +8,7 @@
"isolatedModules": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"paths": {
"mtp-wasm": ["../../wasm/pkg"]
},
"rootDir": "../.."
"forceConsistentCasingInFileNames": true
},
"include": ["src", "../../wasm/pkg"]
"include": ["src"]
}

View file

@ -1,6 +1,7 @@
import { defineConfig } from 'vite';
import fs from 'fs';
import path from 'path';
import { mtp } from 'mtp/vite';
const devCertDir = path.resolve(__dirname, '../dev-cert');
const certPath = process.env.MTP_DEV_CERT ?? path.join(devCertDir, 'cert.pem');
@ -9,11 +10,7 @@ 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: {
'mtp-wasm': path.resolve(__dirname, '../../wasm/pkg'),
},
},
plugins: [mtp({ typeMaps: '../../example/type-maps.yaml' })],
server: {
https: hasDevCert
? {
@ -21,8 +18,5 @@ export default defineConfig({
key: fs.readFileSync(keyPath),
}
: undefined,
fs: {
allow: ['.', path.resolve(__dirname, '../../wasm/pkg')],
},
},
});