[Fix] Connection issues in example-usage & wasm
This commit is contained in:
parent
f5a80adbc7
commit
3332aa621b
13 changed files with 356 additions and 55 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
|
||||
|
|
|
|||
|
|
@ -14,3 +14,4 @@ tokio = { version = "1", features = ["full"] }
|
|||
serde_json = { version = "1" }
|
||||
hex = "0.4"
|
||||
serde_core = "1.0.228"
|
||||
base64 = "0.22"
|
||||
|
|
|
|||
|
|
@ -27,6 +27,17 @@ 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)?;
|
||||
|
||||
|
|
|
|||
|
|
@ -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,33 @@ import init, {
|
|||
WasmClient,
|
||||
ConnectionConfig,
|
||||
ConnectionState,
|
||||
WasmEd25519Signer,
|
||||
WasmKeyring,
|
||||
ed25519_generate,
|
||||
keyring_from_ed25519,
|
||||
build_demo_message,
|
||||
} 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 +36,101 @@ 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 from public file.");
|
||||
} 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 {
|
||||
|
|
@ -65,55 +156,107 @@ 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 config = new ConnectionConfig(SERVER_URL.value.trim());
|
||||
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);
|
||||
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");
|
||||
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);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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