diff --git a/.gitignore b/.gitignore index 2c539c1..8ce8e7b 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ node_modules/ dist/ *.tgz +wasm/pkg/ diff --git a/client/src/lib.rs b/client/src/lib.rs index ac063d7..a60541c 100644 --- a/client/src/lib.rs +++ b/client/src/lib.rs @@ -1,6 +1,7 @@ use mtp_codec::{CommunicationValue, DataType, DataValue, PROTOCOL_VERSION, Version}; use mtp_common::CommunicationError; use mtp_transport::{Policy, Receiver, Sender}; +#[cfg(feature = "crypto")] use tokio::time::Duration; #[cfg(feature = "crypto")] @@ -81,6 +82,51 @@ pub struct MTPConnection { pub client_id: u64, } +impl MTPConnection { + /* + * Send a request frame and wait for the response with the same frame id. + * Any expected response type is validated after the id match. Frames with + * other ids are consumed by this call, so applications that need broad + * routing should put request correlation in a dedicated receive task. + */ + pub async fn request( + &self, + request: &CommunicationValue, + expected_response: Option, + ) -> Result { + let request_id = request.get_id(); + if request_id == 0 { + return Err(CommunicationError::Other( + "request frame must have a non-zero id".into(), + )); + } + + self.sender.send(request).await?; + + let tm = mtp_codec::TypeMap::latest(); + loop { + let response = self.receiver.receive().await?; + if response.get_id() != request_id { + continue; + } + + if let Some(expected) = expected_response { + let expected_type = expected.to_id(&tm); + if response.get_type() != expected_type { + return Err(CommunicationError::Other(format!( + "unexpected response type: expected {:?}, got {:?}; parsed {}", + expected_type, + response.get_type(), + response + ))); + } + } + + return Ok(response); + } + } +} + #[cfg(feature = "crypto")] #[derive(Debug, Clone, PartialEq, Eq)] pub enum AuthState { @@ -288,7 +334,12 @@ async fn receive_verified_challenge( } }; - verify_host_challenge(&challenge, host_public_key_bundle, bound_id, server_challenge)?; + verify_host_challenge( + &challenge, + host_public_key_bundle, + bound_id, + server_challenge, + )?; Ok(server_challenge) } @@ -437,6 +488,21 @@ impl MTPClient { } } + pub async fn auth_connect_or_register( + mut config: ClientConfig, + existing_client_id: Option, + keys: &mtp_crypto::Keyring, + host_public_key_bundle: &mtp_crypto::PublicKeyBundle, + ) -> Result { + match existing_client_id { + Some(client_id) => { + config.client_id = client_id; + Self::auth_connect(config, keys, host_public_key_bundle).await + } + None => Self::auth_register(config, keys, host_public_key_bundle).await, + } + } + async fn auth_register_inner( config: ClientConfig, keys: &mtp_crypto::Keyring, @@ -588,8 +654,8 @@ mod tests { #[cfg(feature = "crypto")] #[test] fn test_auth_timeout_custom() { - let config = ClientConfig::new("https://localhost:4433") - .with_auth_timeout(Duration::from_secs(10)); + let config = + ClientConfig::new("https://localhost:4433").with_auth_timeout(Duration::from_secs(10)); assert_eq!(config.auth_timeout, Duration::from_secs(10)); } } diff --git a/codec/src/communication_value.rs b/codec/src/communication_value.rs index fafc549..96acccc 100644 --- a/codec/src/communication_value.rs +++ b/codec/src/communication_value.rs @@ -129,7 +129,10 @@ impl CommunicationValue { } }; match tm.data_id_enum(data_type) { - Some(raw_id) => self.data.get(&DataTypeId(raw_id)).unwrap_or(&DataValue::Null), + Some(raw_id) => self + .data + .get(&DataTypeId(raw_id)) + .unwrap_or(&DataValue::Null), None => &DataValue::Null, } } @@ -594,21 +597,28 @@ impl CommunicationValue { } } match *alg { - SigAlgorithm::ED25519 => { - self.verify_frame(&Ed25519Verifier(&pk.sig_cl_public_key)).is_ok() - } - SigAlgorithm::ML_DSA_65 => { - self.verify_frame(&MlDsaVerifier(&pk.sig_pq_public_key)).is_ok() - } + SigAlgorithm::ED25519 => self + .verify_frame(&Ed25519Verifier(&pk.sig_cl_public_key)) + .is_ok(), + SigAlgorithm::ML_DSA_65 => self + .verify_frame(&MlDsaVerifier(&pk.sig_pq_public_key)) + .is_ok(), SigAlgorithm::DUAL => { // For DUAL, verify_frame passes the full combined sig to the verifier. // We wrap a verifier that splits and checks both halves. - struct DualVerifier<'a>(&'a mtp_crypto::SignaturePublicKey, &'a mtp_crypto::SignaturePqPublicKey); + struct DualVerifier<'a>( + &'a mtp_crypto::SignaturePublicKey, + &'a mtp_crypto::SignaturePqPublicKey, + ); impl SignatureScheme for DualVerifier<'_> { fn sign(&self, _: &[u8]) -> Result, mtp_crypto::CryptoError> { Err(mtp_crypto::CryptoError::SigningFailed) } - fn verify(&self, msg: &[u8], sig: &[u8]) -> Result<(), mtp_crypto::CryptoError> { + fn verify( + &self, + msg: &[u8], + sig: &[u8], + ) -> Result<(), mtp_crypto::CryptoError> { const ED_LEN: usize = 64; if sig.len() < ED_LEN { return Err(mtp_crypto::CryptoError::InvalidSignature); @@ -617,7 +627,8 @@ impl CommunicationValue { mtp_crypto::verify_ml_dsa(self.1, msg, &sig[ED_LEN..]) } } - self.verify_frame(&DualVerifier(&pk.sig_cl_public_key, &pk.sig_pq_public_key)).is_ok() + self.verify_frame(&DualVerifier(&pk.sig_cl_public_key, &pk.sig_pq_public_key)) + .is_ok() } _ => false, } diff --git a/codec/src/data_value.rs b/codec/src/data_value.rs index 99fbe35..8b79d75 100644 --- a/codec/src/data_value.rs +++ b/codec/src/data_value.rs @@ -493,7 +493,8 @@ impl DataValue { let container_bytes = &blob[1 + sig_len..]; match alg { SigAlgorithm::ED25519 => { - mtp_crypto::verify_ed25519(&pk.sig_cl_public_key, container_bytes, signature).is_ok() + mtp_crypto::verify_ed25519(&pk.sig_cl_public_key, container_bytes, signature) + .is_ok() } SigAlgorithm::ML_DSA_65 => { mtp_crypto::verify_ml_dsa(&pk.sig_pq_public_key, container_bytes, signature).is_ok() @@ -1046,7 +1047,11 @@ impl Hash for DataValue { impl From for DataValue { fn from(v: bool) -> Self { - if v { DataValue::BoolTrue } else { DataValue::BoolFalse } + if v { + DataValue::BoolTrue + } else { + DataValue::BoolFalse + } } } @@ -1115,7 +1120,10 @@ impl std::error::Error for DataValueTypeMismatch {} impl TryFrom for bool { type Error = DataValueTypeMismatch; fn try_from(v: DataValue) -> Result { - v.as_bool().ok_or(DataValueTypeMismatch { expected: "Bool", got: v.type_name() }) + v.as_bool().ok_or(DataValueTypeMismatch { + expected: "Bool", + got: v.type_name(), + }) } } @@ -1124,7 +1132,10 @@ impl TryFrom for String { fn try_from(v: DataValue) -> Result { match v { DataValue::Str(s) => Ok(s), - other => Err(DataValueTypeMismatch { expected: "Str", got: other.type_name() }), + other => Err(DataValueTypeMismatch { + expected: "Str", + got: other.type_name(), + }), } } } @@ -1132,14 +1143,20 @@ impl TryFrom for String { impl TryFrom for i128 { type Error = DataValueTypeMismatch; fn try_from(v: DataValue) -> Result { - v.as_signed_number().ok_or(DataValueTypeMismatch { expected: "SignedNumber", got: v.type_name() }) + v.as_signed_number().ok_or(DataValueTypeMismatch { + expected: "SignedNumber", + got: v.type_name(), + }) } } impl TryFrom for i64 { type Error = DataValueTypeMismatch; fn try_from(v: DataValue) -> Result { - let n = v.as_signed_number().ok_or(DataValueTypeMismatch { expected: "SignedNumber", got: v.type_name() })?; + let n = v.as_signed_number().ok_or(DataValueTypeMismatch { + expected: "SignedNumber", + got: v.type_name(), + })?; Ok(n as i64) } } @@ -1147,14 +1164,20 @@ impl TryFrom for i64 { impl TryFrom for u128 { type Error = DataValueTypeMismatch; fn try_from(v: DataValue) -> Result { - v.as_unsigned_number().ok_or(DataValueTypeMismatch { expected: "UnsignedNumber", got: v.type_name() }) + v.as_unsigned_number().ok_or(DataValueTypeMismatch { + expected: "UnsignedNumber", + got: v.type_name(), + }) } } impl TryFrom for u64 { type Error = DataValueTypeMismatch; fn try_from(v: DataValue) -> Result { - let n = v.as_unsigned_number().ok_or(DataValueTypeMismatch { expected: "UnsignedNumber", got: v.type_name() })?; + let n = v.as_unsigned_number().ok_or(DataValueTypeMismatch { + expected: "UnsignedNumber", + got: v.type_name(), + })?; Ok(n as u64) } } @@ -1164,7 +1187,10 @@ impl TryFrom for Vec { fn try_from(v: DataValue) -> Result { match v { DataValue::Bytes(b) => Ok(b), - other => Err(DataValueTypeMismatch { expected: "Bytes", got: other.type_name() }), + other => Err(DataValueTypeMismatch { + expected: "Bytes", + got: other.type_name(), + }), } } } @@ -1543,26 +1569,47 @@ mod tests { fn test_from_primitives() { assert_eq!(DataValue::from(true), DataValue::BoolTrue); assert_eq!(DataValue::from(false), DataValue::BoolFalse); - assert_eq!(DataValue::from("hello"), DataValue::Str("hello".to_string())); - assert_eq!(DataValue::from("hello".to_string()), DataValue::Str("hello".to_string())); + assert_eq!( + DataValue::from("hello"), + DataValue::Str("hello".to_string()) + ); + assert_eq!( + DataValue::from("hello".to_string()), + DataValue::Str("hello".to_string()) + ); assert_eq!(DataValue::from(42i64), DataValue::SignedNumber(42)); assert_eq!(DataValue::from(42i128), DataValue::SignedNumber(42)); assert_eq!(DataValue::from(42u64), DataValue::UnsignedNumber(42)); assert_eq!(DataValue::from(42u128), DataValue::UnsignedNumber(42)); - assert_eq!(DataValue::from(vec![1u8, 2, 3]), DataValue::Bytes(vec![1, 2, 3])); - assert_eq!(DataValue::from([1u8, 2, 3].as_ref()), DataValue::Bytes(vec![1, 2, 3])); + assert_eq!( + DataValue::from(vec![1u8, 2, 3]), + DataValue::Bytes(vec![1, 2, 3]) + ); + assert_eq!( + DataValue::from([1u8, 2, 3].as_ref()), + DataValue::Bytes(vec![1, 2, 3]) + ); } #[test] fn test_try_from_ok() { - assert_eq!(bool::try_from(DataValue::BoolTrue).unwrap(), true); - assert_eq!(bool::try_from(DataValue::BoolFalse).unwrap(), false); - assert_eq!(String::try_from(DataValue::Str("hi".to_string())).unwrap(), "hi"); + assert!(bool::try_from(DataValue::BoolTrue).unwrap()); + assert!(!bool::try_from(DataValue::BoolFalse).unwrap()); + assert_eq!( + String::try_from(DataValue::Str("hi".to_string())).unwrap(), + "hi" + ); assert_eq!(i128::try_from(DataValue::SignedNumber(-1)).unwrap(), -1i128); assert_eq!(i64::try_from(DataValue::SignedNumber(10)).unwrap(), 10i64); - assert_eq!(u128::try_from(DataValue::UnsignedNumber(99)).unwrap(), 99u128); + assert_eq!( + u128::try_from(DataValue::UnsignedNumber(99)).unwrap(), + 99u128 + ); assert_eq!(u64::try_from(DataValue::UnsignedNumber(7)).unwrap(), 7u64); - assert_eq!(Vec::::try_from(DataValue::Bytes(vec![0xAB])).unwrap(), vec![0xABu8]); + assert_eq!( + Vec::::try_from(DataValue::Bytes(vec![0xAB])).unwrap(), + vec![0xABu8] + ); } #[test] diff --git a/docs/NATIVE-CLIENT.md b/docs/NATIVE-CLIENT.md index 48d6a76..5f7d1ac 100644 --- a/docs/NATIVE-CLIENT.md +++ b/docs/NATIVE-CLIENT.md @@ -131,6 +131,18 @@ let id = conn.client_id; let keyring_bytes = keyring.to_bytes(); ``` +When callers already know whether a saved client id exists, the convenience +helper chooses login or registration: + +```rust +let conn = MTPClient::auth_connect_or_register( + config, + saved_client_id, // Option + &keyring, + &host_pk, +).await?; +``` + Protocol (challenge-response): 1. Client sends an unsigned `Register` hello (version, public key bundle) 2. Host replies with a `Challenge` carrying a fresh random `server_challenge` @@ -207,6 +219,19 @@ type-map configuration. conn.sender.send(&msg).await?; ``` +For request/response flows, `MTPConnection::request` sends one frame and waits +for a response with the same non-zero frame id. An expected response type can be +provided for validation: + +```rust +let response = conn + .request(&msg, Some(mtp::codec::CommunicationType::Pong)) + .await?; +``` + +Frames with other ids are consumed by this helper. Applications that need +subscriptions or broad routing should use one receive task and correlate there. + Two send modes (configured via `mtp::transport::Policy`): - `PersistentStream` (default) -- reuses one QUIC uni-directional stream - `SingleStreamPerMessage` -- opens a new stream per message diff --git a/docs/WASM-CLIENT.md b/docs/WASM-CLIENT.md index 5cfc3b4..7686f63 100644 --- a/docs/WASM-CLIENT.md +++ b/docs/WASM-CLIENT.md @@ -42,6 +42,8 @@ const client = await MTPClient.create({ credentials, storage, serverCertificateHashes: ["sha-256:abcd1234..."], + maxMessageSize: 1_000_000, + authTimeoutMs: 30_000, pings: true, logger: (event) => console.log(event), }); @@ -139,6 +141,9 @@ await MTPClient.create({ If hashes are omitted, the browser uses its normal TLS root store. +`maxMessageSize` caps inbound and outbound MTP frames before buffering/sending. +`authTimeoutMs` bounds connect/login/register promises at the SDK layer. + ## Sending, Requests, Subscriptions, And Pings `send` accepts either a typed message or a prebuilt raw frame: @@ -157,7 +162,7 @@ await client.send("SomeType", { value: "hello" }, { }); ``` -`request` sends one frame and resolves with the matching parsed response from the WASM layer: +`request` sends one frame and resolves with the parsed response carrying the same frame id. `responseType` is validated after the id match: ```typescript const response = await client.request( @@ -252,6 +257,7 @@ Raw crypto and key helpers include: - `ed25519_generate()` - `ed25519_verify(publicKey, message, signature)` +- `keyring_generate()` - `keyring_from_ed25519(secretKey, publicKey)` - `WasmKeyring.from_bytes(bytes)` and `keyring.to_bytes()` - `WasmPublicKeyBundle.from_bytes(bytes)` and `bundle.to_bytes()` diff --git a/example/.gitignore b/example/.gitignore index 894dd06..0d3408c 100644 --- a/example/.gitignore +++ b/example/.gitignore @@ -5,7 +5,8 @@ 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/node_modules web-client/public/host_public_key_bundle.hex web-client/public/mtp_dev_cert_hash.txt +web-client/dist/ diff --git a/example/web-client/.gitignore b/example/web-client/.gitignore deleted file mode 100644 index 1521c8b..0000000 --- a/example/web-client/.gitignore +++ /dev/null @@ -1 +0,0 @@ -dist diff --git a/host/src/lib.rs b/host/src/lib.rs index 58c79ae..389af78 100644 --- a/host/src/lib.rs +++ b/host/src/lib.rs @@ -1,18 +1,23 @@ use mtp_codec::{ - CommunicationValue, DataType, DataValue, TypeMap, Version, + CommunicationValue, DataType, DataValue, Version, registry::{Registry, VersionedCodec}, }; use mtp_common::CommunicationError; use mtp_transport::{Policy, Receiver, Sender}; use std::net::IpAddr; +#[cfg(feature = "crypto")] use std::pin::Pin; use std::{error::Error, fmt}; +#[cfg(feature = "crypto")] use tokio::time::Duration; /* ---- async callback type aliases ---- */ #[cfg(feature = "crypto")] type GetExistingUser = Box< - dyn Fn(u64) -> Pin> + Send>> + dyn Fn( + u64, + ) + -> Pin> + Send>> + Send + Sync, >; @@ -74,14 +79,19 @@ impl HostConfig { pub fn with_authentication( mut self, host_keyring: mtp_crypto::Keyring, - get_existing_user: impl Fn(u64) -> Pin> + Send>> - + Send - + Sync - + 'static, - complete_register: impl Fn(mtp_crypto::PublicKeyBundle) -> Pin + Send>> - + Send - + Sync - + 'static, + get_existing_user: impl Fn( + u64, + ) -> Pin< + Box> + Send>, + > + Send + + Sync + + 'static, + complete_register: impl Fn( + mtp_crypto::PublicKeyBundle, + ) -> Pin + Send>> + + Send + + Sync + + 'static, ) -> Self { self.require_authentication = true; self.host_keyring = host_keyring; @@ -195,11 +205,8 @@ impl MTPHost { #[cfg(feature = "crypto")] if self.config.require_authentication { let timeout = self.config.auth_timeout; - return match tokio::time::timeout( - timeout, - self.accept_authenticated(sender, receiver), - ) - .await + return match tokio::time::timeout(timeout, self.accept_authenticated(sender, receiver)) + .await { Ok(result) => result, Err(_) => Err(AcceptError::AuthenticationTimedOut), @@ -288,7 +295,7 @@ impl MTPHost { }, } - let tm = TypeMap::latest(); + let tm = mtp_codec::TypeMap::latest(); let pq_enabled = !self .config .host_keyring diff --git a/src/sdk/index.ts b/src/sdk/index.ts index 5e34666..5b2dde7 100644 --- a/src/sdk/index.ts +++ b/src/sdk/index.ts @@ -2,8 +2,7 @@ import initWasm, { ConnectionConfig, ConnectionState, WasmClient, - ed25519_generate, - keyring_from_ed25519, + keyring_generate, } from "mtp/raw"; import * as bindings from "mtp/raw"; import type * as RawBindings from "../raw/index"; @@ -40,6 +39,8 @@ export interface MTPClientOptions { credentialsStorageKey?: string; storage?: MTPCredentialStorage; serverCertificateHashes?: string[]; + maxMessageSize?: number; + authTimeoutMs?: number; pings?: boolean | { intervalMs?: number }; wasm?: RawBindings.InitInput | Promise | { module_or_path: RawBindings.InitInput | Promise }; logger?: (event: MTPLogEvent) => void; @@ -185,12 +186,7 @@ function toBigInt(value) { } function generateKeyringBytes() { - const generated = ed25519_generate(); - try { - return keyring_from_ed25519(generated.secretKey, generated.publicKey); - } finally { - generated.signer?.free?.(); - } + return keyring_generate(); } function serializeCredentials(credentials) { @@ -247,6 +243,30 @@ function validateOptions(options) { } } } + if (options.maxMessageSize != null && (!Number.isSafeInteger(options.maxMessageSize) || options.maxMessageSize <= 0)) { + throw new TypeError("maxMessageSize must be a positive safe integer"); + } + if (options.authTimeoutMs != null && (!Number.isSafeInteger(options.authTimeoutMs) || options.authTimeoutMs <= 0)) { + throw new TypeError("authTimeoutMs must be a positive safe integer"); + } +} + +async function withTimeout(promise, timeoutMs, message) { + if (!timeoutMs) { + return await promise; + } + + let timeoutId; + try { + return await Promise.race([ + promise, + new Promise((_resolve, reject) => { + timeoutId = setTimeout(() => reject(new Error(message)), timeoutMs); + }), + ]); + } finally { + clearTimeout(timeoutId); + } } export class MTPClient { @@ -334,6 +354,9 @@ export class MTPClient { if (this.#options.serverCertificateHashes) { config.server_certificate_hashes = this.#options.serverCertificateHashes; } + if (this.#options.maxMessageSize != null) { + config.max_message_size = this.#options.maxMessageSize; + } return config; } @@ -345,7 +368,11 @@ export class MTPClient { const config = this.#connectionConfig(); try { - await this.raw.client.connect(config); + await withTimeout( + this.raw.client.connect(config), + this.#options.authTimeoutMs, + "connection timed out", + ); this.#startPings(0n); } finally { config.free(); @@ -362,11 +389,15 @@ export class MTPClient { const config = this.#connectionConfig(); try { - const clientId = await this.raw.client.auth_connect( - config, - this.#options.hostPublicKey, - this.#credentials.keyringBytes, - this.#credentials.clientId, + const clientId = await withTimeout( + this.raw.client.auth_connect( + config, + this.#options.hostPublicKey, + this.#credentials.keyringBytes, + this.#credentials.clientId, + ), + this.#options.authTimeoutMs, + "authentication timed out", ); this.#credentials = { ...this.#credentials, clientId }; await this.#persistCredentials(); @@ -391,10 +422,14 @@ export class MTPClient { const config = this.#connectionConfig(); try { - const clientId = await this.raw.client.auth_register( - config, - this.#options.hostPublicKey, - this.#credentials.keyringBytes, + const clientId = await withTimeout( + this.raw.client.auth_register( + config, + this.#options.hostPublicKey, + this.#credentials.keyringBytes, + ), + this.#options.authTimeoutMs, + "authentication timed out", ); this.#credentials = { ...this.#credentials, clientId }; await this.#persistCredentials(); diff --git a/tsconfig.json b/tsconfig.json index 1664c17..5a697e9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -8,6 +8,8 @@ "outDir": "dist", "rootDir": "src", "baseUrl": ".", + "types": ["node"], + "ignoreDeprecations": "6.0", "paths": { "mtp/raw": ["src/raw/index.ts"], "mtp/type-map": ["src/type-map/index.ts"] diff --git a/type-map/build.rs b/type-map/build.rs index 91c342e..9a0fafb 100755 --- a/type-map/build.rs +++ b/type-map/build.rs @@ -1026,11 +1026,7 @@ fn generate_id_display_impls(out: &mut String) { " fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{" ) .unwrap(); - writeln!( - out, - " match communication_type_name(self.0) {{" - ) - .unwrap(); + writeln!(out, " match communication_type_name(self.0) {{").unwrap(); writeln!(out, " Some(name) => f.write_str(name),").unwrap(); writeln!( out, @@ -1048,11 +1044,7 @@ fn generate_id_display_impls(out: &mut String) { " fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{" ) .unwrap(); - writeln!( - out, - " match data_type_name(self.0) {{" - ) - .unwrap(); + writeln!(out, " match data_type_name(self.0) {{").unwrap(); writeln!(out, " Some(name) => f.write_str(name),").unwrap(); writeln!( out, diff --git a/wasm/pkg/mtp_wasm.d.ts b/wasm/pkg/mtp_wasm.d.ts deleted file mode 100644 index 2b169dc..0000000 --- a/wasm/pkg/mtp_wasm.d.ts +++ /dev/null @@ -1,318 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ - -export interface ParsedFrame { - id?: number; - type: string; - sender?: bigint; - receiver?: bigint; - data: Record; - raw: Uint8Array; -} - - - -export class ConnectionConfig { - free(): void; - [Symbol.dispose](): void; - constructor(url: string); - client_id: bigint; - set server_certificate_hashes(value: string[]); - readonly url: string; -} - -export enum ConnectionState { - Disconnected = 0, - Connecting = 1, - Connected = 2, - Failed = 3, -} - -export class WasmChaCha20Poly1305 { - free(): void; - [Symbol.dispose](): void; - /** - * Decrypt `nonce || ciphertext` with `aad`. - */ - decrypt(ciphertext: Uint8Array, aad: Uint8Array): Uint8Array; - /** - * Encrypt `plaintext` with `aad`. - * Returns `nonce || ciphertext`. - */ - encrypt(plaintext: Uint8Array, aad: Uint8Array): Uint8Array; - /** - * Create a new cipher with a 32-byte key. - */ - constructor(key: Uint8Array); -} - -export class WasmClient { - free(): void; - [Symbol.dispose](): void; - /** - * Authenticated login with an existing client ID. - * Exchanges Identification + signatures and verifies the host response. - * - * - `host_public_key_bytes`: serialized PublicKeyBundle from the server - * - `keyring_bytes`: serialized Keyring of this client (must match `client_id`) - * - `client_id`: previously assigned client ID - * - * Returns the confirmed (same) client ID on success. - */ - auth_connect(config: ConnectionConfig, host_public_key_bytes: Uint8Array, keyring_bytes: Uint8Array, client_id: bigint): Promise; - /** - * Authenticated registration with a fresh keyring. - * The server assigns a new client ID. - * - * - `host_public_key_bytes`: serialized PublicKeyBundle from the server - * - `keyring_bytes`: serialized Keyring (must include ed25519 secret key) - * - * Returns the newly assigned client ID. - */ - auth_register(config: ConnectionConfig, host_public_key_bytes: Uint8Array, keyring_bytes: Uint8Array): Promise; - /** - * Unauthenticated connect (sends basic Identification, enables receive loop). - */ - connect(config: ConnectionConfig): Promise; - disconnect(): void; - static is_supported(): boolean; - constructor(on_state_change: Function, on_message: Function, on_error: Function); - request(frame: Uint8Array, response_type?: string | null): Promise; - send(frame: Uint8Array): Promise; - start_protocol_pings(interval_ms: number, client_id: bigint): void; - stop_protocol_pings(): void; - subscribe(message_type: string, callback: Function): number; - unsubscribe(id: number): boolean; - readonly state: number; -} - -export class WasmEd25519Signer { - free(): void; - [Symbol.dispose](): void; - /** - * Load a signer from its 32-byte secret key. - */ - constructor(secret_key: Uint8Array); - /** - * Sign `message` and return the signature bytes. - */ - sign(message: Uint8Array): Uint8Array; - /** - * Verify `signature` against `message`. - */ - verify(message: Uint8Array, signature: Uint8Array): void; -} - -export class WasmKeyring { - private constructor(); - free(): void; - [Symbol.dispose](): void; - /** - * Deserialise a keyring from bytes. - */ - static from_bytes(bytes: Uint8Array): WasmKeyring; - /** - * Return the public half of this keyring as a bundle. - */ - public_key_bundle(): WasmPublicKeyBundle; - /** - * Serialise the keyring to bytes. - */ - to_bytes(): Uint8Array; -} - -/** - * Log severity used by the public SDK when translating raw WASM events. - */ -export enum WasmLogHint { - Info = 0, - Warning = 1, - Error = 2, -} - -export class WasmPublicKeyBundle { - private constructor(); - free(): void; - [Symbol.dispose](): void; - static from_bytes(bytes: Uint8Array): WasmPublicKeyBundle; - to_bytes(): Uint8Array; - readonly kem_public_key: Uint8Array; - readonly sig_cl_public_key: Uint8Array; - readonly sig_pq_public_key: Uint8Array; -} - -/** - * Minimal message router used by higher-level SDK subscription code. - */ -export class WasmSubscriptionRouter { - free(): void; - [Symbol.dispose](): void; - dispatch(message_type: string, message: any): boolean; - constructor(); - subscribe(message_type: string, callback: Function): void; - unsubscribe(message_type: string): boolean; -} - -/** - * Build a typed MTP frame using generated communication/data type names. - */ -export function build_frame(message_type: string, data: any, options: any): Uint8Array; - -/** - * Build a protocol-level Ping frame with description, timestamp, and optional data. - */ -export function build_ping_frame(client_id: bigint, description: string, timestamp: bigint, data: Uint8Array): Uint8Array; - -/** - * Generate a fresh Ed25519 keypair. - * - * Returns `{ signer: WasmEd25519Signer, secretKey: Uint8Array, publicKey: Uint8Array }`. - */ -export function ed25519_generate(): any; - -/** - * Standalone Ed25519 signature verification. - */ -export function ed25519_verify(public_key: Uint8Array, message: Uint8Array, signature: Uint8Array): void; - -/** - * Parse any MTP frame into the human-readable CommunicationValue display form. - */ -export function format_frame(frame: Uint8Array): string; - -/** - * Build a [`Keyring`] containing only an Ed25519 keypair (no KEM, no ML-DSA). - * - * Takes the Ed25519 secret key and public key, each 32 bytes. - * Returns the serialised keyring bytes, suitable for passing to `WasmClient.auth_register`. - */ -export function keyring_from_ed25519(secret_key: Uint8Array, public_key: Uint8Array): Uint8Array; - -export function main(): void; - -/** - * Parse an auth response frame into a JS object. - */ -export function parse_auth_response(response: Uint8Array): any; - -/** - * Parse any MTP frame into structured JavaScript data. - */ -export function parse_frame(frame: Uint8Array): ParsedFrame; - -/** - * Derive a 32-byte encryption key from `ikm` with `salt` and `context`. - */ -export function wasm_derive_encryption_key(ikm: Uint8Array, salt: Uint8Array, context: Uint8Array): Uint8Array; - -/** - * HKDF-expand: derive `len` bytes from `ikm` with `salt` and `info`. - */ -export function wasm_hkdf_expand(ikm: Uint8Array, salt: Uint8Array, info: Uint8Array, len: number): Uint8Array; - -/** - * SHA-256 digest. - */ -export function wasm_sha256(data: Uint8Array): Uint8Array; - -/** - * Double SHA-256 (SHA-256 applied twice). - */ -export function wasm_sha256_double(data: Uint8Array): Uint8Array; - -export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module; - -export interface InitOutput { - readonly memory: WebAssembly.Memory; - readonly build_frame: (a: number, b: number, c: any, d: any) => [number, number, number, number]; - readonly build_ping_frame: (a: bigint, b: number, c: number, d: bigint, e: number, f: number) => [number, number, number, number]; - readonly format_frame: (a: number, b: number) => [number, number, number, number]; - readonly parse_auth_response: (a: number, b: number) => [number, number, number]; - readonly parse_frame: (a: number, b: number) => [number, number, number]; - readonly __wbg_wasmchacha20poly1305_free: (a: number, b: number) => void; - readonly __wbg_wasmed25519signer_free: (a: number, b: number) => void; - readonly __wbg_wasmkeyring_free: (a: number, b: number) => void; - readonly __wbg_wasmpublickeybundle_free: (a: number, b: number) => void; - readonly ed25519_generate: () => [number, number, number]; - readonly ed25519_verify: (a: number, b: number, c: number, d: number, e: number, f: number) => [number, number]; - readonly keyring_from_ed25519: (a: number, b: number, c: number, d: number) => [number, number, number, number]; - readonly wasm_derive_encryption_key: (a: number, b: number, c: number, d: number, e: number, f: number) => [number, number, number, number]; - readonly wasm_hkdf_expand: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => [number, number, number, number]; - readonly wasm_sha256: (a: number, b: number) => [number, number]; - readonly wasm_sha256_double: (a: number, b: number) => [number, number]; - readonly wasmchacha20poly1305_decrypt: (a: number, b: number, c: number, d: number, e: number) => [number, number, number, number]; - readonly wasmchacha20poly1305_encrypt: (a: number, b: number, c: number, d: number, e: number) => [number, number, number, number]; - readonly wasmchacha20poly1305_new: (a: number, b: number) => [number, number, number]; - readonly wasmed25519signer_new: (a: number, b: number) => [number, number, number]; - readonly wasmed25519signer_sign: (a: number, b: number, c: number) => [number, number, number, number]; - readonly wasmed25519signer_verify: (a: number, b: number, c: number, d: number, e: number) => [number, number]; - readonly wasmkeyring_from_bytes: (a: number, b: number) => [number, number, number]; - readonly wasmkeyring_public_key_bundle: (a: number) => number; - readonly wasmkeyring_to_bytes: (a: number) => [number, number]; - readonly wasmpublickeybundle_from_bytes: (a: number, b: number) => [number, number, number]; - readonly wasmpublickeybundle_kem_public_key: (a: number) => [number, number]; - readonly wasmpublickeybundle_sig_cl_public_key: (a: number) => [number, number]; - readonly wasmpublickeybundle_sig_pq_public_key: (a: number) => [number, number]; - readonly wasmpublickeybundle_to_bytes: (a: number) => [number, number]; - readonly __wbg_wasmclient_free: (a: number, b: number) => void; - readonly wasmclient_auth_connect: (a: number, b: number, c: number, d: number, e: number, f: number, g: bigint) => any; - readonly wasmclient_auth_register: (a: number, b: number, c: number, d: number, e: number, f: number) => any; - readonly wasmclient_connect: (a: number, b: number) => any; - readonly wasmclient_disconnect: (a: number) => void; - readonly wasmclient_is_supported: () => number; - readonly wasmclient_new: (a: any, b: any, c: any) => number; - readonly wasmclient_request: (a: number, b: number, c: number, d: number, e: number) => any; - readonly wasmclient_send: (a: number, b: number, c: number) => any; - readonly wasmclient_start_protocol_pings: (a: number, b: number, c: bigint) => [number, number]; - readonly wasmclient_state: (a: number) => number; - readonly wasmclient_stop_protocol_pings: (a: number) => void; - readonly wasmclient_subscribe: (a: number, b: number, c: number, d: any) => number; - readonly wasmclient_unsubscribe: (a: number, b: number) => number; - readonly __wbg_wasmsubscriptionrouter_free: (a: number, b: number) => void; - readonly main: () => void; - readonly wasmsubscriptionrouter_dispatch: (a: number, b: number, c: number, d: any) => number; - readonly wasmsubscriptionrouter_new: () => number; - readonly wasmsubscriptionrouter_subscribe: (a: number, b: number, c: number, d: any) => void; - readonly wasmsubscriptionrouter_unsubscribe: (a: number, b: number, c: number) => number; - readonly __wbg_connectionconfig_free: (a: number, b: number) => void; - readonly connectionconfig_client_id: (a: number) => bigint; - readonly connectionconfig_new: (a: number, b: number) => number; - readonly connectionconfig_set_client_id: (a: number, b: bigint) => void; - readonly connectionconfig_set_server_certificate_hashes: (a: number, b: number, c: number) => void; - readonly connectionconfig_url: (a: number) => [number, number]; - readonly wasm_bindgen__convert__closures_____invoke__h6588d25cdde23584: (a: number, b: number, c: any) => [number, number]; - readonly wasm_bindgen__convert__closures_____invoke__h4bf2427f775cf424: (a: number, b: number, c: any, d: any) => void; - readonly wasm_bindgen__convert__closures_____invoke__h3c511b580d027299: (a: number, b: number, c: any) => void; - readonly wasm_bindgen__convert__closures_____invoke__h99ead69e8d7f5bae: (a: number, b: number) => void; - readonly __wbindgen_malloc: (a: number, b: number) => number; - readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number; - readonly __wbindgen_exn_store: (a: number) => void; - readonly __externref_table_alloc: () => number; - readonly __wbindgen_externrefs: WebAssembly.Table; - readonly __wbindgen_free: (a: number, b: number, c: number) => void; - readonly __wbindgen_destroy_closure: (a: number, b: number) => void; - readonly __externref_table_dealloc: (a: number) => void; - readonly __wbindgen_start: () => void; -} - -export type SyncInitInput = BufferSource | WebAssembly.Module; - -/** - * Instantiates the given `module`, which can either be bytes or - * a precompiled `WebAssembly.Module`. - * - * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated. - * - * @returns {InitOutput} - */ -export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput; - -/** - * If `module_or_path` is {RequestInfo} or {URL}, makes a request and - * for everything else, calls `WebAssembly.instantiate` directly. - * - * @param {{ module_or_path: InitInput | Promise }} module_or_path - Passing `InitInput` directly is deprecated. - * - * @returns {Promise} - */ -export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise } | InitInput | Promise): Promise; diff --git a/wasm/pkg/mtp_wasm.js b/wasm/pkg/mtp_wasm.js deleted file mode 100644 index 86dda08..0000000 --- a/wasm/pkg/mtp_wasm.js +++ /dev/null @@ -1,1483 +0,0 @@ -/* @ts-self-types="./mtp_wasm.d.ts" */ - -export class ConnectionConfig { - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; - ConnectionConfigFinalization.unregister(this); - return ptr; - } - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_connectionconfig_free(ptr, 0); - } - /** - * @returns {bigint} - */ - get client_id() { - const ret = wasm.connectionconfig_client_id(this.__wbg_ptr); - return BigInt.asUintN(64, ret); - } - /** - * @param {string} url - */ - constructor(url) { - const ptr0 = passStringToWasm0(url, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.connectionconfig_new(ptr0, len0); - this.__wbg_ptr = ret; - ConnectionConfigFinalization.register(this, this.__wbg_ptr, this); - return this; - } - /** - * @param {bigint} id - */ - set client_id(id) { - wasm.connectionconfig_set_client_id(this.__wbg_ptr, id); - } - /** - * @param {string[]} hashes - */ - set server_certificate_hashes(hashes) { - const ptr0 = passArrayJsValueToWasm0(hashes, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - wasm.connectionconfig_set_server_certificate_hashes(this.__wbg_ptr, ptr0, len0); - } - /** - * @returns {string} - */ - get url() { - let deferred1_0; - let deferred1_1; - try { - const ret = wasm.connectionconfig_url(this.__wbg_ptr); - deferred1_0 = ret[0]; - deferred1_1 = ret[1]; - return getStringFromWasm0(ret[0], ret[1]); - } finally { - wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); - } - } -} -if (Symbol.dispose) ConnectionConfig.prototype[Symbol.dispose] = ConnectionConfig.prototype.free; - -/** - * @enum {0 | 1 | 2 | 3} - */ -export const ConnectionState = Object.freeze({ - Disconnected: 0, "0": "Disconnected", - Connecting: 1, "1": "Connecting", - Connected: 2, "2": "Connected", - Failed: 3, "3": "Failed", -}); - -export class WasmChaCha20Poly1305 { - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; - WasmChaCha20Poly1305Finalization.unregister(this); - return ptr; - } - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_wasmchacha20poly1305_free(ptr, 0); - } - /** - * Decrypt `nonce || ciphertext` with `aad`. - * @param {Uint8Array} ciphertext - * @param {Uint8Array} aad - * @returns {Uint8Array} - */ - decrypt(ciphertext, aad) { - const ptr0 = passArray8ToWasm0(ciphertext, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passArray8ToWasm0(aad, wasm.__wbindgen_malloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.wasmchacha20poly1305_decrypt(this.__wbg_ptr, ptr0, len0, ptr1, len1); - if (ret[3]) { - throw takeFromExternrefTable0(ret[2]); - } - var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v3; - } - /** - * Encrypt `plaintext` with `aad`. - * Returns `nonce || ciphertext`. - * @param {Uint8Array} plaintext - * @param {Uint8Array} aad - * @returns {Uint8Array} - */ - encrypt(plaintext, aad) { - const ptr0 = passArray8ToWasm0(plaintext, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passArray8ToWasm0(aad, wasm.__wbindgen_malloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.wasmchacha20poly1305_encrypt(this.__wbg_ptr, ptr0, len0, ptr1, len1); - if (ret[3]) { - throw takeFromExternrefTable0(ret[2]); - } - var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v3; - } - /** - * Create a new cipher with a 32-byte key. - * @param {Uint8Array} key - */ - constructor(key) { - const ptr0 = passArray8ToWasm0(key, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.wasmchacha20poly1305_new(ptr0, len0); - if (ret[2]) { - throw takeFromExternrefTable0(ret[1]); - } - this.__wbg_ptr = ret[0]; - WasmChaCha20Poly1305Finalization.register(this, this.__wbg_ptr, this); - return this; - } -} -if (Symbol.dispose) WasmChaCha20Poly1305.prototype[Symbol.dispose] = WasmChaCha20Poly1305.prototype.free; - -export class WasmClient { - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; - WasmClientFinalization.unregister(this); - return ptr; - } - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_wasmclient_free(ptr, 0); - } - /** - * Authenticated login with an existing client ID. - * Exchanges Identification + signatures and verifies the host response. - * - * - `host_public_key_bytes`: serialized PublicKeyBundle from the server - * - `keyring_bytes`: serialized Keyring of this client (must match `client_id`) - * - `client_id`: previously assigned client ID - * - * Returns the confirmed (same) client ID on success. - * @param {ConnectionConfig} config - * @param {Uint8Array} host_public_key_bytes - * @param {Uint8Array} keyring_bytes - * @param {bigint} client_id - * @returns {Promise} - */ - auth_connect(config, host_public_key_bytes, keyring_bytes, client_id) { - _assertClass(config, ConnectionConfig); - const ptr0 = passArray8ToWasm0(host_public_key_bytes, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passArray8ToWasm0(keyring_bytes, wasm.__wbindgen_malloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.wasmclient_auth_connect(this.__wbg_ptr, config.__wbg_ptr, ptr0, len0, ptr1, len1, client_id); - return ret; - } - /** - * Authenticated registration with a fresh keyring. - * The server assigns a new client ID. - * - * - `host_public_key_bytes`: serialized PublicKeyBundle from the server - * - `keyring_bytes`: serialized Keyring (must include ed25519 secret key) - * - * Returns the newly assigned client ID. - * @param {ConnectionConfig} config - * @param {Uint8Array} host_public_key_bytes - * @param {Uint8Array} keyring_bytes - * @returns {Promise} - */ - auth_register(config, host_public_key_bytes, keyring_bytes) { - _assertClass(config, ConnectionConfig); - const ptr0 = passArray8ToWasm0(host_public_key_bytes, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passArray8ToWasm0(keyring_bytes, wasm.__wbindgen_malloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.wasmclient_auth_register(this.__wbg_ptr, config.__wbg_ptr, ptr0, len0, ptr1, len1); - return ret; - } - /** - * Unauthenticated connect (sends basic Identification, enables receive loop). - * @param {ConnectionConfig} config - * @returns {Promise} - */ - connect(config) { - _assertClass(config, ConnectionConfig); - const ret = wasm.wasmclient_connect(this.__wbg_ptr, config.__wbg_ptr); - return ret; - } - disconnect() { - wasm.wasmclient_disconnect(this.__wbg_ptr); - } - /** - * @returns {boolean} - */ - static is_supported() { - const ret = wasm.wasmclient_is_supported(); - return ret !== 0; - } - /** - * @param {Function} on_state_change - * @param {Function} on_message - * @param {Function} on_error - */ - constructor(on_state_change, on_message, on_error) { - const ret = wasm.wasmclient_new(on_state_change, on_message, on_error); - this.__wbg_ptr = ret; - WasmClientFinalization.register(this, this.__wbg_ptr, this); - return this; - } - /** - * @param {Uint8Array} frame - * @param {string | null} [response_type] - * @returns {Promise} - */ - request(frame, response_type) { - const ptr0 = passArray8ToWasm0(frame, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - var ptr1 = isLikeNone(response_type) ? 0 : passStringToWasm0(response_type, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - var len1 = WASM_VECTOR_LEN; - const ret = wasm.wasmclient_request(this.__wbg_ptr, ptr0, len0, ptr1, len1); - return ret; - } - /** - * @param {Uint8Array} frame - * @returns {Promise} - */ - send(frame) { - const ptr0 = passArray8ToWasm0(frame, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.wasmclient_send(this.__wbg_ptr, ptr0, len0); - return ret; - } - /** - * @param {number} interval_ms - * @param {bigint} client_id - */ - start_protocol_pings(interval_ms, client_id) { - const ret = wasm.wasmclient_start_protocol_pings(this.__wbg_ptr, interval_ms, client_id); - if (ret[1]) { - throw takeFromExternrefTable0(ret[0]); - } - } - /** - * @returns {number} - */ - get state() { - const ret = wasm.wasmclient_state(this.__wbg_ptr); - return ret; - } - stop_protocol_pings() { - wasm.wasmclient_stop_protocol_pings(this.__wbg_ptr); - } - /** - * @param {string} message_type - * @param {Function} callback - * @returns {number} - */ - subscribe(message_type, callback) { - const ptr0 = passStringToWasm0(message_type, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.wasmclient_subscribe(this.__wbg_ptr, ptr0, len0, callback); - return ret >>> 0; - } - /** - * @param {number} id - * @returns {boolean} - */ - unsubscribe(id) { - const ret = wasm.wasmclient_unsubscribe(this.__wbg_ptr, id); - return ret !== 0; - } -} -if (Symbol.dispose) WasmClient.prototype[Symbol.dispose] = WasmClient.prototype.free; - -export class WasmEd25519Signer { - static __wrap(ptr) { - const obj = Object.create(WasmEd25519Signer.prototype); - obj.__wbg_ptr = ptr; - WasmEd25519SignerFinalization.register(obj, obj.__wbg_ptr, obj); - return obj; - } - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; - WasmEd25519SignerFinalization.unregister(this); - return ptr; - } - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_wasmed25519signer_free(ptr, 0); - } - /** - * Load a signer from its 32-byte secret key. - * @param {Uint8Array} secret_key - */ - constructor(secret_key) { - const ptr0 = passArray8ToWasm0(secret_key, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.wasmed25519signer_new(ptr0, len0); - if (ret[2]) { - throw takeFromExternrefTable0(ret[1]); - } - this.__wbg_ptr = ret[0]; - WasmEd25519SignerFinalization.register(this, this.__wbg_ptr, this); - return this; - } - /** - * Sign `message` and return the signature bytes. - * @param {Uint8Array} message - * @returns {Uint8Array} - */ - sign(message) { - const ptr0 = passArray8ToWasm0(message, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.wasmed25519signer_sign(this.__wbg_ptr, ptr0, len0); - if (ret[3]) { - throw takeFromExternrefTable0(ret[2]); - } - var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v2; - } - /** - * Verify `signature` against `message`. - * @param {Uint8Array} message - * @param {Uint8Array} signature - */ - verify(message, signature) { - const ptr0 = passArray8ToWasm0(message, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passArray8ToWasm0(signature, wasm.__wbindgen_malloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.wasmed25519signer_verify(this.__wbg_ptr, ptr0, len0, ptr1, len1); - if (ret[1]) { - throw takeFromExternrefTable0(ret[0]); - } - } -} -if (Symbol.dispose) WasmEd25519Signer.prototype[Symbol.dispose] = WasmEd25519Signer.prototype.free; - -export class WasmKeyring { - static __wrap(ptr) { - const obj = Object.create(WasmKeyring.prototype); - obj.__wbg_ptr = ptr; - WasmKeyringFinalization.register(obj, obj.__wbg_ptr, obj); - return obj; - } - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; - WasmKeyringFinalization.unregister(this); - return ptr; - } - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_wasmkeyring_free(ptr, 0); - } - /** - * Deserialise a keyring from bytes. - * @param {Uint8Array} bytes - * @returns {WasmKeyring} - */ - static from_bytes(bytes) { - const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.wasmkeyring_from_bytes(ptr0, len0); - if (ret[2]) { - throw takeFromExternrefTable0(ret[1]); - } - return WasmKeyring.__wrap(ret[0]); - } - /** - * Return the public half of this keyring as a bundle. - * @returns {WasmPublicKeyBundle} - */ - public_key_bundle() { - const ret = wasm.wasmkeyring_public_key_bundle(this.__wbg_ptr); - return WasmPublicKeyBundle.__wrap(ret); - } - /** - * Serialise the keyring to bytes. - * @returns {Uint8Array} - */ - to_bytes() { - const ret = wasm.wasmkeyring_to_bytes(this.__wbg_ptr); - var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v1; - } -} -if (Symbol.dispose) WasmKeyring.prototype[Symbol.dispose] = WasmKeyring.prototype.free; - -/** - * Log severity used by the public SDK when translating raw WASM events. - * @enum {0 | 1 | 2} - */ -export const WasmLogHint = Object.freeze({ - Info: 0, "0": "Info", - Warning: 1, "1": "Warning", - Error: 2, "2": "Error", -}); - -export class WasmPublicKeyBundle { - static __wrap(ptr) { - const obj = Object.create(WasmPublicKeyBundle.prototype); - obj.__wbg_ptr = ptr; - WasmPublicKeyBundleFinalization.register(obj, obj.__wbg_ptr, obj); - return obj; - } - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; - WasmPublicKeyBundleFinalization.unregister(this); - return ptr; - } - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_wasmpublickeybundle_free(ptr, 0); - } - /** - * @param {Uint8Array} bytes - * @returns {WasmPublicKeyBundle} - */ - static from_bytes(bytes) { - const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.wasmpublickeybundle_from_bytes(ptr0, len0); - if (ret[2]) { - throw takeFromExternrefTable0(ret[1]); - } - return WasmPublicKeyBundle.__wrap(ret[0]); - } - /** - * @returns {Uint8Array} - */ - get kem_public_key() { - const ret = wasm.wasmpublickeybundle_kem_public_key(this.__wbg_ptr); - var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v1; - } - /** - * @returns {Uint8Array} - */ - get sig_cl_public_key() { - const ret = wasm.wasmpublickeybundle_sig_cl_public_key(this.__wbg_ptr); - var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v1; - } - /** - * @returns {Uint8Array} - */ - get sig_pq_public_key() { - const ret = wasm.wasmpublickeybundle_sig_pq_public_key(this.__wbg_ptr); - var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v1; - } - /** - * @returns {Uint8Array} - */ - to_bytes() { - const ret = wasm.wasmpublickeybundle_to_bytes(this.__wbg_ptr); - var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v1; - } -} -if (Symbol.dispose) WasmPublicKeyBundle.prototype[Symbol.dispose] = WasmPublicKeyBundle.prototype.free; - -/** - * Minimal message router used by higher-level SDK subscription code. - */ -export class WasmSubscriptionRouter { - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; - WasmSubscriptionRouterFinalization.unregister(this); - return ptr; - } - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_wasmsubscriptionrouter_free(ptr, 0); - } - /** - * @param {string} message_type - * @param {any} message - * @returns {boolean} - */ - dispatch(message_type, message) { - const ptr0 = passStringToWasm0(message_type, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.wasmsubscriptionrouter_dispatch(this.__wbg_ptr, ptr0, len0, message); - return ret !== 0; - } - constructor() { - const ret = wasm.wasmsubscriptionrouter_new(); - this.__wbg_ptr = ret; - WasmSubscriptionRouterFinalization.register(this, this.__wbg_ptr, this); - return this; - } - /** - * @param {string} message_type - * @param {Function} callback - */ - subscribe(message_type, callback) { - const ptr0 = passStringToWasm0(message_type, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - wasm.wasmsubscriptionrouter_subscribe(this.__wbg_ptr, ptr0, len0, callback); - } - /** - * @param {string} message_type - * @returns {boolean} - */ - unsubscribe(message_type) { - const ptr0 = passStringToWasm0(message_type, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.wasmsubscriptionrouter_unsubscribe(this.__wbg_ptr, ptr0, len0); - return ret !== 0; - } -} -if (Symbol.dispose) WasmSubscriptionRouter.prototype[Symbol.dispose] = WasmSubscriptionRouter.prototype.free; - -/** - * Build a typed MTP frame using generated communication/data type names. - * @param {string} message_type - * @param {any} data - * @param {any} options - * @returns {Uint8Array} - */ -export function build_frame(message_type, data, options) { - const ptr0 = passStringToWasm0(message_type, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.build_frame(ptr0, len0, data, options); - if (ret[3]) { - throw takeFromExternrefTable0(ret[2]); - } - var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v2; -} - -/** - * Build a protocol-level Ping frame with description, timestamp, and optional data. - * @param {bigint} client_id - * @param {string} description - * @param {bigint} timestamp - * @param {Uint8Array} data - * @returns {Uint8Array} - */ -export function build_ping_frame(client_id, description, timestamp, data) { - const ptr0 = passStringToWasm0(description, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.build_ping_frame(client_id, ptr0, len0, timestamp, ptr1, len1); - if (ret[3]) { - throw takeFromExternrefTable0(ret[2]); - } - var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v3; -} - -/** - * Generate a fresh Ed25519 keypair. - * - * Returns `{ signer: WasmEd25519Signer, secretKey: Uint8Array, publicKey: Uint8Array }`. - * @returns {any} - */ -export function ed25519_generate() { - const ret = wasm.ed25519_generate(); - if (ret[2]) { - throw takeFromExternrefTable0(ret[1]); - } - return takeFromExternrefTable0(ret[0]); -} - -/** - * Standalone Ed25519 signature verification. - * @param {Uint8Array} public_key - * @param {Uint8Array} message - * @param {Uint8Array} signature - */ -export function ed25519_verify(public_key, message, signature) { - const ptr0 = passArray8ToWasm0(public_key, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passArray8ToWasm0(message, wasm.__wbindgen_malloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passArray8ToWasm0(signature, wasm.__wbindgen_malloc); - const len2 = WASM_VECTOR_LEN; - const ret = wasm.ed25519_verify(ptr0, len0, ptr1, len1, ptr2, len2); - if (ret[1]) { - throw takeFromExternrefTable0(ret[0]); - } -} - -/** - * Parse any MTP frame into the human-readable CommunicationValue display form. - * @param {Uint8Array} frame - * @returns {string} - */ -export function format_frame(frame) { - let deferred3_0; - let deferred3_1; - try { - const ptr0 = passArray8ToWasm0(frame, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.format_frame(ptr0, len0); - var ptr2 = ret[0]; - var len2 = ret[1]; - if (ret[3]) { - ptr2 = 0; len2 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred3_0 = ptr2; - deferred3_1 = len2; - return getStringFromWasm0(ptr2, len2); - } finally { - wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); - } -} - -/** - * Build a [`Keyring`] containing only an Ed25519 keypair (no KEM, no ML-DSA). - * - * Takes the Ed25519 secret key and public key, each 32 bytes. - * Returns the serialised keyring bytes, suitable for passing to `WasmClient.auth_register`. - * @param {Uint8Array} secret_key - * @param {Uint8Array} public_key - * @returns {Uint8Array} - */ -export function keyring_from_ed25519(secret_key, public_key) { - const ptr0 = passArray8ToWasm0(secret_key, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passArray8ToWasm0(public_key, wasm.__wbindgen_malloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.keyring_from_ed25519(ptr0, len0, ptr1, len1); - if (ret[3]) { - throw takeFromExternrefTable0(ret[2]); - } - var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v3; -} - -export function main() { - wasm.main(); -} - -/** - * Parse an auth response frame into a JS object. - * @param {Uint8Array} response - * @returns {any} - */ -export function parse_auth_response(response) { - const ptr0 = passArray8ToWasm0(response, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.parse_auth_response(ptr0, len0); - if (ret[2]) { - throw takeFromExternrefTable0(ret[1]); - } - return takeFromExternrefTable0(ret[0]); -} - -/** - * Parse any MTP frame into structured JavaScript data. - * @param {Uint8Array} frame - * @returns {ParsedFrame} - */ -export function parse_frame(frame) { - const ptr0 = passArray8ToWasm0(frame, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.parse_frame(ptr0, len0); - if (ret[2]) { - throw takeFromExternrefTable0(ret[1]); - } - return takeFromExternrefTable0(ret[0]); -} - -/** - * Derive a 32-byte encryption key from `ikm` with `salt` and `context`. - * @param {Uint8Array} ikm - * @param {Uint8Array} salt - * @param {Uint8Array} context - * @returns {Uint8Array} - */ -export function wasm_derive_encryption_key(ikm, salt, context) { - const ptr0 = passArray8ToWasm0(ikm, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passArray8ToWasm0(salt, wasm.__wbindgen_malloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passArray8ToWasm0(context, wasm.__wbindgen_malloc); - const len2 = WASM_VECTOR_LEN; - const ret = wasm.wasm_derive_encryption_key(ptr0, len0, ptr1, len1, ptr2, len2); - if (ret[3]) { - throw takeFromExternrefTable0(ret[2]); - } - var v4 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v4; -} - -/** - * HKDF-expand: derive `len` bytes from `ikm` with `salt` and `info`. - * @param {Uint8Array} ikm - * @param {Uint8Array} salt - * @param {Uint8Array} info - * @param {number} len - * @returns {Uint8Array} - */ -export function wasm_hkdf_expand(ikm, salt, info, len) { - const ptr0 = passArray8ToWasm0(ikm, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passArray8ToWasm0(salt, wasm.__wbindgen_malloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passArray8ToWasm0(info, wasm.__wbindgen_malloc); - const len2 = WASM_VECTOR_LEN; - const ret = wasm.wasm_hkdf_expand(ptr0, len0, ptr1, len1, ptr2, len2, len); - if (ret[3]) { - throw takeFromExternrefTable0(ret[2]); - } - var v4 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v4; -} - -/** - * SHA-256 digest. - * @param {Uint8Array} data - * @returns {Uint8Array} - */ -export function wasm_sha256(data) { - const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.wasm_sha256(ptr0, len0); - var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v2; -} - -/** - * Double SHA-256 (SHA-256 applied twice). - * @param {Uint8Array} data - * @returns {Uint8Array} - */ -export function wasm_sha256_double(data) { - const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.wasm_sha256_double(ptr0, len0); - var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); - return v2; -} -function __wbg_get_imports() { - const import0 = { - __proto__: null, - __wbg_BigInt_ff69cca7a537413a: function(arg0, arg1) { - const ret = BigInt(getStringFromWasm0(arg0, arg1)); - return ret; - }, - __wbg___wbindgen_boolean_get_fa956cfa2d1bd751: function(arg0) { - const v = arg0; - const ret = typeof(v) === 'boolean' ? v : undefined; - return isLikeNone(ret) ? 0xFFFFFF : ret ? 1 : 0; - }, - __wbg___wbindgen_debug_string_c25d447a39f5578f: function(arg0, arg1) { - const ret = debugString(arg1); - const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }, - __wbg___wbindgen_is_function_1ff95bcc5517c252: function(arg0) { - const ret = typeof(arg0) === 'function'; - return ret; - }, - __wbg___wbindgen_is_null_ea9085d691f535d3: function(arg0) { - const ret = arg0 === null; - return ret; - }, - __wbg___wbindgen_is_object_a27215656b807791: function(arg0) { - const val = arg0; - const ret = typeof(val) === 'object' && val !== null; - return ret; - }, - __wbg___wbindgen_is_string_ea5e6cc2e4141dfe: function(arg0) { - const ret = typeof(arg0) === 'string'; - return ret; - }, - __wbg___wbindgen_is_undefined_c05833b95a3cf397: function(arg0) { - const ret = arg0 === undefined; - return ret; - }, - __wbg___wbindgen_number_get_394265ed1e1b84ee: function(arg0, arg1) { - const obj = arg1; - const ret = typeof(obj) === 'number' ? obj : undefined; - getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true); - }, - __wbg___wbindgen_string_get_b0ca35b86a603356: function(arg0, arg1) { - const obj = arg1; - const ret = typeof(obj) === 'string' ? obj : undefined; - var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - var len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }, - __wbg___wbindgen_throw_344f42d3211c4765: function(arg0, arg1) { - throw new Error(getStringFromWasm0(arg0, arg1)); - }, - __wbg___wbindgen_typeof_b1bf2ff71f77b13e: function(arg0) { - const ret = typeof arg0; - return ret; - }, - __wbg__wbg_cb_unref_fffb441def202758: function(arg0) { - arg0._wbg_cb_unref(); - }, - __wbg_call_8a2dd23819f8a60a: function() { return handleError(function (arg0, arg1) { - const ret = arg0.call(arg1); - return ret; - }, arguments); }, - __wbg_call_a6e5c5dce5018821: function() { return handleError(function (arg0, arg1, arg2) { - const ret = arg0.call(arg1, arg2); - return ret; - }, arguments); }, - __wbg_call_e3b662382210db98: function() { return handleError(function (arg0, arg1, arg2, arg3) { - const ret = arg0.call(arg1, arg2, arg3); - return ret; - }, arguments); }, - __wbg_construct_4e1a16de27aea5b9: function() { return handleError(function (arg0, arg1) { - const ret = Reflect.construct(arg0, arg1); - return ret; - }, arguments); }, - __wbg_crypto_38df2bab126b63dc: function(arg0) { - const ret = arg0.crypto; - return ret; - }, - __wbg_error_a6fa202b58aa1cd3: function(arg0, arg1) { - let deferred0_0; - let deferred0_1; - try { - deferred0_0 = arg0; - deferred0_1 = arg1; - console.error(getStringFromWasm0(arg0, arg1)); - } finally { - wasm.__wbindgen_free(deferred0_0, deferred0_1, 1); - } - }, - __wbg_from_13e323c65fc8f464: function(arg0) { - const ret = Array.from(arg0); - return ret; - }, - __wbg_getRandomValues_c44a50d8cfdaebeb: function() { return handleError(function (arg0, arg1) { - arg0.getRandomValues(arg1); - }, arguments); }, - __wbg_getRandomValues_cc7f052a444bb2ce: function() { return handleError(function (arg0, arg1) { - globalThis.crypto.getRandomValues(getArrayU8FromWasm0(arg0, arg1)); - }, arguments); }, - __wbg_get_78f252d074a84d0b: function() { return handleError(function (arg0, arg1) { - const ret = Reflect.get(arg0, arg1); - return ret; - }, arguments); }, - __wbg_get_unchecked_6e0ad6d2a41b06f6: function(arg0, arg1) { - const ret = arg0[arg1 >>> 0]; - return ret; - }, - __wbg_has_8374cf06984d8bfc: function() { return handleError(function (arg0, arg1) { - const ret = Reflect.has(arg0, arg1); - return ret; - }, arguments); }, - __wbg_instanceof_Promise_4cb210c0b8f8c959: function(arg0) { - let result; - try { - result = arg0 instanceof Promise; - } catch (_) { - result = false; - } - const ret = result; - return ret; - }, - __wbg_instanceof_Uint8Array_309b927aaf7a3fc7: function(arg0) { - let result; - try { - result = arg0 instanceof Uint8Array; - } catch (_) { - result = false; - } - const ret = result; - return ret; - }, - __wbg_isArray_0677c962b281d01a: function(arg0) { - const ret = Array.isArray(arg0); - return ret; - }, - __wbg_keys_58421f8f96795607: function(arg0) { - const ret = Object.keys(arg0); - return ret; - }, - __wbg_length_1f0964f4a5e2c6d8: function(arg0) { - const ret = arg0.length; - return ret; - }, - __wbg_length_370319915dc99107: function(arg0) { - const ret = arg0.length; - return ret; - }, - __wbg_msCrypto_bd5a034af96bcba6: function(arg0) { - const ret = arg0.msCrypto; - return ret; - }, - __wbg_new_227d7c05414eb861: function() { - const ret = new Error(); - return ret; - }, - __wbg_new_32b398fb48b6d94a: function() { - const ret = new Array(); - return ret; - }, - __wbg_new_cd45aabdf6073e84: function(arg0) { - const ret = new Uint8Array(arg0); - return ret; - }, - __wbg_new_da52cf8fe3429cb2: function() { - const ret = new Object(); - return ret; - }, - __wbg_new_from_slice_77cdfb7977362f3c: function(arg0, arg1) { - const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1)); - return ret; - }, - __wbg_new_typed_1824d93f294193e5: function(arg0, arg1) { - try { - var state0 = {a: arg0, b: arg1}; - var cb0 = (arg0, arg1) => { - const a = state0.a; - state0.a = 0; - try { - return wasm_bindgen__convert__closures_____invoke__h4bf2427f775cf424(a, state0.b, arg0, arg1); - } finally { - state0.a = a; - } - }; - const ret = new Promise(cb0); - return ret; - } finally { - state0.a = 0; - } - }, - __wbg_new_with_length_e6785c33c8e4cce8: function(arg0) { - const ret = new Uint8Array(arg0 >>> 0); - return ret; - }, - __wbg_node_84ea875411254db1: function(arg0) { - const ret = arg0.node; - return ret; - }, - __wbg_now_86c0d4ba3fa605b8: function() { - const ret = Date.now(); - return ret; - }, - __wbg_process_44c7a14e11e9f69e: function(arg0) { - const ret = arg0.process; - return ret; - }, - __wbg_prototypesetcall_4770620bbe4688a0: function(arg0, arg1, arg2) { - Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), arg2); - }, - __wbg_push_d2ae3af0c1217ae6: function(arg0, arg1) { - const ret = arg0.push(arg1); - return ret; - }, - __wbg_queueMicrotask_0ab5b2d2393e99b9: function(arg0) { - const ret = arg0.queueMicrotask; - return ret; - }, - __wbg_queueMicrotask_6a09b7bc46549209: function(arg0) { - queueMicrotask(arg0); - }, - __wbg_randomFillSync_6c25eac9869eb53c: function() { return handleError(function (arg0, arg1) { - arg0.randomFillSync(arg1); - }, arguments); }, - __wbg_require_b4edbdcf3e2a1ef0: function() { return handleError(function () { - const ret = module.require; - return ret; - }, arguments); }, - __wbg_resolve_2191a4dfe481c25b: function(arg0) { - const ret = Promise.resolve(arg0); - return ret; - }, - __wbg_set_8535240470bf2500: function() { return handleError(function (arg0, arg1, arg2) { - const ret = Reflect.set(arg0, arg1, arg2); - return ret; - }, arguments); }, - __wbg_stack_3b0d974bbf31e44f: function(arg0, arg1) { - const ret = arg1.stack; - const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }, - __wbg_static_accessor_GLOBAL_4ef717fb391d88b7: function() { - const ret = typeof global === 'undefined' ? null : global; - return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); - }, - __wbg_static_accessor_GLOBAL_THIS_8d1badc68b5a74f4: function() { - const ret = typeof globalThis === 'undefined' ? null : globalThis; - return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); - }, - __wbg_static_accessor_SELF_146583524fe1469b: function() { - const ret = typeof self === 'undefined' ? null : self; - return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); - }, - __wbg_static_accessor_WINDOW_f2829a2234d7819e: function() { - const ret = typeof window === 'undefined' ? null : window; - return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); - }, - __wbg_subarray_3ed232c8a6baee09: function(arg0, arg1, arg2) { - const ret = arg0.subarray(arg1 >>> 0, arg2 >>> 0); - return ret; - }, - __wbg_then_16d107c451e9905d: function(arg0, arg1, arg2) { - const ret = arg0.then(arg1, arg2); - return ret; - }, - __wbg_then_6ec10ae38b3e92f7: function(arg0, arg1) { - const ret = arg0.then(arg1); - return ret; - }, - __wbg_toString_34387d7c1df9ca1e: function() { return handleError(function (arg0, arg1) { - const ret = arg0.toString(arg1); - return ret; - }, arguments); }, - __wbg_versions_276b2795b1c6a219: function(arg0) { - const ret = arg0.versions; - return ret; - }, - __wbg_wasmed25519signer_new: function(arg0) { - const ret = WasmEd25519Signer.__wrap(arg0); - return ret; - }, - __wbindgen_cast_0000000000000001: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 128, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h6588d25cdde23584); - return ret; - }, - __wbindgen_cast_0000000000000002: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 65, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h3c511b580d027299); - return ret; - }, - __wbindgen_cast_0000000000000003: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 63, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h99ead69e8d7f5bae); - return ret; - }, - __wbindgen_cast_0000000000000004: function(arg0) { - // Cast intrinsic for `F64 -> Externref`. - const ret = arg0; - return ret; - }, - __wbindgen_cast_0000000000000005: function(arg0, arg1) { - // Cast intrinsic for `Ref(Slice(U8)) -> NamedExternref("Uint8Array")`. - const ret = getArrayU8FromWasm0(arg0, arg1); - return ret; - }, - __wbindgen_cast_0000000000000006: function(arg0, arg1) { - // Cast intrinsic for `Ref(String) -> Externref`. - const ret = getStringFromWasm0(arg0, arg1); - return ret; - }, - __wbindgen_cast_0000000000000007: function(arg0) { - // Cast intrinsic for `U64 -> Externref`. - const ret = BigInt.asUintN(64, arg0); - return ret; - }, - __wbindgen_init_externref_table: function() { - const table = wasm.__wbindgen_externrefs; - const offset = table.grow(4); - table.set(0, undefined); - table.set(offset + 0, undefined); - table.set(offset + 1, null); - table.set(offset + 2, true); - table.set(offset + 3, false); - }, - }; - return { - __proto__: null, - "./mtp_wasm_bg.js": import0, - }; -} - -function wasm_bindgen__convert__closures_____invoke__h99ead69e8d7f5bae(arg0, arg1) { - wasm.wasm_bindgen__convert__closures_____invoke__h99ead69e8d7f5bae(arg0, arg1); -} - -function wasm_bindgen__convert__closures_____invoke__h3c511b580d027299(arg0, arg1, arg2) { - wasm.wasm_bindgen__convert__closures_____invoke__h3c511b580d027299(arg0, arg1, arg2); -} - -function wasm_bindgen__convert__closures_____invoke__h6588d25cdde23584(arg0, arg1, arg2) { - const ret = wasm.wasm_bindgen__convert__closures_____invoke__h6588d25cdde23584(arg0, arg1, arg2); - if (ret[1]) { - throw takeFromExternrefTable0(ret[0]); - } -} - -function wasm_bindgen__convert__closures_____invoke__h4bf2427f775cf424(arg0, arg1, arg2, arg3) { - wasm.wasm_bindgen__convert__closures_____invoke__h4bf2427f775cf424(arg0, arg1, arg2, arg3); -} - -const ConnectionConfigFinalization = (typeof FinalizationRegistry === 'undefined') - ? { register: () => {}, unregister: () => {} } - : new FinalizationRegistry(ptr => wasm.__wbg_connectionconfig_free(ptr, 1)); -const WasmChaCha20Poly1305Finalization = (typeof FinalizationRegistry === 'undefined') - ? { register: () => {}, unregister: () => {} } - : new FinalizationRegistry(ptr => wasm.__wbg_wasmchacha20poly1305_free(ptr, 1)); -const WasmClientFinalization = (typeof FinalizationRegistry === 'undefined') - ? { register: () => {}, unregister: () => {} } - : new FinalizationRegistry(ptr => wasm.__wbg_wasmclient_free(ptr, 1)); -const WasmEd25519SignerFinalization = (typeof FinalizationRegistry === 'undefined') - ? { register: () => {}, unregister: () => {} } - : new FinalizationRegistry(ptr => wasm.__wbg_wasmed25519signer_free(ptr, 1)); -const WasmKeyringFinalization = (typeof FinalizationRegistry === 'undefined') - ? { register: () => {}, unregister: () => {} } - : new FinalizationRegistry(ptr => wasm.__wbg_wasmkeyring_free(ptr, 1)); -const WasmPublicKeyBundleFinalization = (typeof FinalizationRegistry === 'undefined') - ? { register: () => {}, unregister: () => {} } - : new FinalizationRegistry(ptr => wasm.__wbg_wasmpublickeybundle_free(ptr, 1)); -const WasmSubscriptionRouterFinalization = (typeof FinalizationRegistry === 'undefined') - ? { register: () => {}, unregister: () => {} } - : new FinalizationRegistry(ptr => wasm.__wbg_wasmsubscriptionrouter_free(ptr, 1)); - -function addToExternrefTable0(obj) { - const idx = wasm.__externref_table_alloc(); - wasm.__wbindgen_externrefs.set(idx, obj); - return idx; -} - -function _assertClass(instance, klass) { - if (!(instance instanceof klass)) { - throw new Error(`expected instance of ${klass.name}`); - } -} - -const CLOSURE_DTORS = (typeof FinalizationRegistry === 'undefined') - ? { register: () => {}, unregister: () => {} } - : new FinalizationRegistry(state => wasm.__wbindgen_destroy_closure(state.a, state.b)); - -function debugString(val) { - // primitive types - const type = typeof val; - if (type == 'number' || type == 'boolean' || val == null) { - return `${val}`; - } - if (type == 'string') { - return `"${val}"`; - } - if (type == 'symbol') { - const description = val.description; - if (description == null) { - return 'Symbol'; - } else { - return `Symbol(${description})`; - } - } - if (type == 'function') { - const name = val.name; - if (typeof name == 'string' && name.length > 0) { - return `Function(${name})`; - } else { - return 'Function'; - } - } - // objects - if (Array.isArray(val)) { - const length = val.length; - let debug = '['; - if (length > 0) { - debug += debugString(val[0]); - } - for(let i = 1; i < length; i++) { - debug += ', ' + debugString(val[i]); - } - debug += ']'; - return debug; - } - // Test for built-in - const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); - let className; - if (builtInMatches && builtInMatches.length > 1) { - className = builtInMatches[1]; - } else { - // Failed to match the standard '[object ClassName]' - return toString.call(val); - } - if (className == 'Object') { - // we're a user defined class or Object - // JSON.stringify avoids problems with cycles, and is generally much - // easier than looping through ownProperties of `val`. - try { - return 'Object(' + JSON.stringify(val) + ')'; - } catch (_) { - return 'Object'; - } - } - // errors - if (val instanceof Error) { - return `${val.name}: ${val.message}\n${val.stack}`; - } - // TODO we could test for more things here, like `Set`s and `Map`s. - return className; -} - -function getArrayU8FromWasm0(ptr, len) { - ptr = ptr >>> 0; - return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len); -} - -let cachedDataViewMemory0 = null; -function getDataViewMemory0() { - if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) { - cachedDataViewMemory0 = new DataView(wasm.memory.buffer); - } - return cachedDataViewMemory0; -} - -function getStringFromWasm0(ptr, len) { - return decodeText(ptr >>> 0, len); -} - -let cachedUint8ArrayMemory0 = null; -function getUint8ArrayMemory0() { - if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { - cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); - } - return cachedUint8ArrayMemory0; -} - -function handleError(f, args) { - try { - return f.apply(this, args); - } catch (e) { - const idx = addToExternrefTable0(e); - wasm.__wbindgen_exn_store(idx); - } -} - -function isLikeNone(x) { - return x === undefined || x === null; -} - -function makeMutClosure(arg0, arg1, f) { - const state = { a: arg0, b: arg1, cnt: 1 }; - const real = (...args) => { - - // First up with a closure we increment the internal reference - // count. This ensures that the Rust closure environment won't - // be deallocated while we're invoking it. - state.cnt++; - const a = state.a; - state.a = 0; - try { - return f(a, state.b, ...args); - } finally { - state.a = a; - real._wbg_cb_unref(); - } - }; - real._wbg_cb_unref = () => { - if (--state.cnt === 0) { - wasm.__wbindgen_destroy_closure(state.a, state.b); - state.a = 0; - CLOSURE_DTORS.unregister(state); - } - }; - CLOSURE_DTORS.register(real, state, state); - return real; -} - -function passArray8ToWasm0(arg, malloc) { - const ptr = malloc(arg.length * 1, 1) >>> 0; - getUint8ArrayMemory0().set(arg, ptr / 1); - WASM_VECTOR_LEN = arg.length; - return ptr; -} - -function passArrayJsValueToWasm0(array, malloc) { - const ptr = malloc(array.length * 4, 4) >>> 0; - for (let i = 0; i < array.length; i++) { - const add = addToExternrefTable0(array[i]); - getDataViewMemory0().setUint32(ptr + 4 * i, add, true); - } - WASM_VECTOR_LEN = array.length; - return ptr; -} - -function passStringToWasm0(arg, malloc, realloc) { - if (realloc === undefined) { - const buf = cachedTextEncoder.encode(arg); - const ptr = malloc(buf.length, 1) >>> 0; - getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); - WASM_VECTOR_LEN = buf.length; - return ptr; - } - - let len = arg.length; - let ptr = malloc(len, 1) >>> 0; - - const mem = getUint8ArrayMemory0(); - - let offset = 0; - - for (; offset < len; offset++) { - const code = arg.charCodeAt(offset); - if (code > 0x7F) break; - mem[ptr + offset] = code; - } - if (offset !== len) { - if (offset !== 0) { - arg = arg.slice(offset); - } - ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; - const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); - const ret = cachedTextEncoder.encodeInto(arg, view); - - offset += ret.written; - ptr = realloc(ptr, len, offset, 1) >>> 0; - } - - WASM_VECTOR_LEN = offset; - return ptr; -} - -function takeFromExternrefTable0(idx) { - const value = wasm.__wbindgen_externrefs.get(idx); - wasm.__externref_table_dealloc(idx); - return value; -} - -let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); -cachedTextDecoder.decode(); -const MAX_SAFARI_DECODE_BYTES = 2146435072; -let numBytesDecoded = 0; -function decodeText(ptr, len) { - numBytesDecoded += len; - if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) { - cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); - cachedTextDecoder.decode(); - numBytesDecoded = len; - } - return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); -} - -const cachedTextEncoder = new TextEncoder(); - -if (!('encodeInto' in cachedTextEncoder)) { - cachedTextEncoder.encodeInto = function (arg, view) { - const buf = cachedTextEncoder.encode(arg); - view.set(buf); - return { - read: arg.length, - written: buf.length - }; - }; -} - -let WASM_VECTOR_LEN = 0; - -let wasmModule, wasmInstance, wasm; -function __wbg_finalize_init(instance, module) { - wasmInstance = instance; - wasm = instance.exports; - wasmModule = module; - cachedDataViewMemory0 = null; - cachedUint8ArrayMemory0 = null; - wasm.__wbindgen_start(); - return wasm; -} - -async function __wbg_load(module, imports) { - if (typeof Response === 'function' && module instanceof Response) { - if (typeof WebAssembly.instantiateStreaming === 'function') { - try { - return await WebAssembly.instantiateStreaming(module, imports); - } catch (e) { - const validResponse = module.ok && expectedResponseType(module.type); - - if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') { - console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); - - } else { throw e; } - } - } - - const bytes = await module.arrayBuffer(); - return await WebAssembly.instantiate(bytes, imports); - } else { - const instance = await WebAssembly.instantiate(module, imports); - - if (instance instanceof WebAssembly.Instance) { - return { instance, module }; - } else { - return instance; - } - } - - function expectedResponseType(type) { - switch (type) { - case 'basic': case 'cors': case 'default': return true; - } - return false; - } -} - -function initSync(module) { - if (wasm !== undefined) return wasm; - - - if (module !== undefined) { - if (Object.getPrototypeOf(module) === Object.prototype) { - ({module} = module) - } else { - console.warn('using deprecated parameters for `initSync()`; pass a single object instead') - } - } - - const imports = __wbg_get_imports(); - if (!(module instanceof WebAssembly.Module)) { - module = new WebAssembly.Module(module); - } - const instance = new WebAssembly.Instance(module, imports); - return __wbg_finalize_init(instance, module); -} - -async function __wbg_init(module_or_path) { - if (wasm !== undefined) return wasm; - - - if (module_or_path !== undefined) { - if (Object.getPrototypeOf(module_or_path) === Object.prototype) { - ({module_or_path} = module_or_path) - } else { - console.warn('using deprecated parameters for the initialization function; pass a single object instead') - } - } - - if (module_or_path === undefined) { - module_or_path = new URL('mtp_wasm_bg.wasm', import.meta.url); - } - const imports = __wbg_get_imports(); - - if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) { - module_or_path = fetch(module_or_path); - } - - const { instance, module } = await __wbg_load(await module_or_path, imports); - - return __wbg_finalize_init(instance, module); -} - -export { initSync, __wbg_init as default }; diff --git a/wasm/pkg/mtp_wasm_bg.wasm b/wasm/pkg/mtp_wasm_bg.wasm deleted file mode 100644 index 42eeb79..0000000 Binary files a/wasm/pkg/mtp_wasm_bg.wasm and /dev/null differ diff --git a/wasm/pkg/mtp_wasm_bg.wasm.d.ts b/wasm/pkg/mtp_wasm_bg.wasm.d.ts deleted file mode 100644 index 99637c2..0000000 --- a/wasm/pkg/mtp_wasm_bg.wasm.d.ts +++ /dev/null @@ -1,72 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ -export const memory: WebAssembly.Memory; -export const build_frame: (a: number, b: number, c: any, d: any) => [number, number, number, number]; -export const build_ping_frame: (a: bigint, b: number, c: number, d: bigint, e: number, f: number) => [number, number, number, number]; -export const format_frame: (a: number, b: number) => [number, number, number, number]; -export const parse_auth_response: (a: number, b: number) => [number, number, number]; -export const parse_frame: (a: number, b: number) => [number, number, number]; -export const __wbg_wasmchacha20poly1305_free: (a: number, b: number) => void; -export const __wbg_wasmed25519signer_free: (a: number, b: number) => void; -export const __wbg_wasmkeyring_free: (a: number, b: number) => void; -export const __wbg_wasmpublickeybundle_free: (a: number, b: number) => void; -export const ed25519_generate: () => [number, number, number]; -export const ed25519_verify: (a: number, b: number, c: number, d: number, e: number, f: number) => [number, number]; -export const keyring_from_ed25519: (a: number, b: number, c: number, d: number) => [number, number, number, number]; -export const wasm_derive_encryption_key: (a: number, b: number, c: number, d: number, e: number, f: number) => [number, number, number, number]; -export const wasm_hkdf_expand: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => [number, number, number, number]; -export const wasm_sha256: (a: number, b: number) => [number, number]; -export const wasm_sha256_double: (a: number, b: number) => [number, number]; -export const wasmchacha20poly1305_decrypt: (a: number, b: number, c: number, d: number, e: number) => [number, number, number, number]; -export const wasmchacha20poly1305_encrypt: (a: number, b: number, c: number, d: number, e: number) => [number, number, number, number]; -export const wasmchacha20poly1305_new: (a: number, b: number) => [number, number, number]; -export const wasmed25519signer_new: (a: number, b: number) => [number, number, number]; -export const wasmed25519signer_sign: (a: number, b: number, c: number) => [number, number, number, number]; -export const wasmed25519signer_verify: (a: number, b: number, c: number, d: number, e: number) => [number, number]; -export const wasmkeyring_from_bytes: (a: number, b: number) => [number, number, number]; -export const wasmkeyring_public_key_bundle: (a: number) => number; -export const wasmkeyring_to_bytes: (a: number) => [number, number]; -export const wasmpublickeybundle_from_bytes: (a: number, b: number) => [number, number, number]; -export const wasmpublickeybundle_kem_public_key: (a: number) => [number, number]; -export const wasmpublickeybundle_sig_cl_public_key: (a: number) => [number, number]; -export const wasmpublickeybundle_sig_pq_public_key: (a: number) => [number, number]; -export const wasmpublickeybundle_to_bytes: (a: number) => [number, number]; -export const __wbg_wasmclient_free: (a: number, b: number) => void; -export const wasmclient_auth_connect: (a: number, b: number, c: number, d: number, e: number, f: number, g: bigint) => any; -export const wasmclient_auth_register: (a: number, b: number, c: number, d: number, e: number, f: number) => any; -export const wasmclient_connect: (a: number, b: number) => any; -export const wasmclient_disconnect: (a: number) => void; -export const wasmclient_is_supported: () => number; -export const wasmclient_new: (a: any, b: any, c: any) => number; -export const wasmclient_request: (a: number, b: number, c: number, d: number, e: number) => any; -export const wasmclient_send: (a: number, b: number, c: number) => any; -export const wasmclient_start_protocol_pings: (a: number, b: number, c: bigint) => [number, number]; -export const wasmclient_state: (a: number) => number; -export const wasmclient_stop_protocol_pings: (a: number) => void; -export const wasmclient_subscribe: (a: number, b: number, c: number, d: any) => number; -export const wasmclient_unsubscribe: (a: number, b: number) => number; -export const __wbg_wasmsubscriptionrouter_free: (a: number, b: number) => void; -export const main: () => void; -export const wasmsubscriptionrouter_dispatch: (a: number, b: number, c: number, d: any) => number; -export const wasmsubscriptionrouter_new: () => number; -export const wasmsubscriptionrouter_subscribe: (a: number, b: number, c: number, d: any) => void; -export const wasmsubscriptionrouter_unsubscribe: (a: number, b: number, c: number) => number; -export const __wbg_connectionconfig_free: (a: number, b: number) => void; -export const connectionconfig_client_id: (a: number) => bigint; -export const connectionconfig_new: (a: number, b: number) => number; -export const connectionconfig_set_client_id: (a: number, b: bigint) => void; -export const connectionconfig_set_server_certificate_hashes: (a: number, b: number, c: number) => void; -export const connectionconfig_url: (a: number) => [number, number]; -export const wasm_bindgen__convert__closures_____invoke__h6588d25cdde23584: (a: number, b: number, c: any) => [number, number]; -export const wasm_bindgen__convert__closures_____invoke__h4bf2427f775cf424: (a: number, b: number, c: any, d: any) => void; -export const wasm_bindgen__convert__closures_____invoke__h3c511b580d027299: (a: number, b: number, c: any) => void; -export const wasm_bindgen__convert__closures_____invoke__h99ead69e8d7f5bae: (a: number, b: number) => void; -export const __wbindgen_malloc: (a: number, b: number) => number; -export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number; -export const __wbindgen_exn_store: (a: number) => void; -export const __externref_table_alloc: () => number; -export const __wbindgen_externrefs: WebAssembly.Table; -export const __wbindgen_free: (a: number, b: number, c: number) => void; -export const __wbindgen_destroy_closure: (a: number, b: number) => void; -export const __externref_table_dealloc: (a: number) => void; -export const __wbindgen_start: () => void; diff --git a/wasm/pkg/package.json b/wasm/pkg/package.json deleted file mode 100644 index 632853f..0000000 --- a/wasm/pkg/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "mtp-wasm", - "type": "module", - "version": "0.1.0", - "files": [ - "mtp_wasm_bg.wasm", - "mtp_wasm.js", - "mtp_wasm.d.ts" - ], - "main": "mtp_wasm.js", - "types": "mtp_wasm.d.ts", - "sideEffects": [ - "./snippets/*" - ] -} diff --git a/wasm/src/client.rs b/wasm/src/client.rs index 8b7603b..8fdde48 100644 --- a/wasm/src/client.rs +++ b/wasm/src/client.rs @@ -71,21 +71,6 @@ fn route_incoming_frame( } } - if let Some(message_type) = message_type.as_ref() { - let matching_id = pending_requests - .borrow() - .iter() - .find_map(|(id, pending)| match pending.response_type.as_ref() { - Some(response_type) if response_type == message_type => Some(*id), - _ => None, - }); - if let Some(id) = matching_id { - if let Some(pending) = pending_requests.borrow_mut().remove(&id) { - let _ = pending.sender.send(Ok(frame.clone())); - } - } - } - let _ = on_message.call1(&JsValue::NULL, frame); let Some(message_type) = message_type else { @@ -154,7 +139,7 @@ fn unexpected_response_type_error( */ fn verify_host_challenge( challenge: &CommunicationValue, - tm: &mtp_codec::TypeMap, + _tm: &mtp_codec::TypeMap, host_pk: &mtp_crypto::PublicKeyBundle, id: u64, server_challenge: u128, @@ -185,7 +170,7 @@ fn verify_host_challenge( */ fn verify_host_final( resp: &CommunicationValue, - tm: &mtp_codec::TypeMap, + _tm: &mtp_codec::TypeMap, host_pk: &mtp_crypto::PublicKeyBundle, id: u64, client_nonce: u128, @@ -230,12 +215,24 @@ fn signed_challenge_response_bytes( .sign(proof_payload) .map_err(|e| js_error(&format!("signature failed: {}", e)))?; - CommunicationValue::new(CommunicationType::ChallengeResponse) + let mut proof = CommunicationValue::new(CommunicationType::ChallengeResponse) .add_typed_default( DataType::ClientNonce, DataValue::UnsignedNumber(client_nonce), ) - .add_typed_default(DataType::Signature, DataValue::Bytes(signature)) + .add_typed_default(DataType::Signature, DataValue::Bytes(signature)); + + if !keyring.sig_pq_secret_key.as_bytes().is_empty() { + let pq_signer = + mtp_crypto::MlDsaSigner::new(&keyring.sig_pq_secret_key, &keyring.sig_pq_public_key) + .map_err(|e| js_error(&format!("PQ signer creation failed: {}", e)))?; + let pq_signature = pq_signer + .sign(proof_payload) + .map_err(|e| js_error(&format!("PQ signature failed: {}", e)))?; + proof = proof.add_typed_default(DataType::PqSignature, DataValue::Bytes(pq_signature)); + } + + proof .to_bytes() .map_err(|e| js_error(&format!("encode failed: {}", e))) } @@ -297,8 +294,12 @@ impl WasmClient { #[wasm_bindgen] pub async fn connect(&mut self, config: &ConnectionConfig) -> Result<(), JsValue> { self.set_state(ConnectionState::Connecting); - let transport = - WasmTransport::connect(&config.url, config.server_certificate_hashes.clone()).await?; + let transport = WasmTransport::connect( + &config.url, + config.server_certificate_hashes.clone(), + config.max_message_size, + ) + .await?; let version_str = format!("{}", PROTOCOL_VERSION); let ident = CommunicationValue::new(CommunicationType::Identification) @@ -342,8 +343,12 @@ impl WasmClient { let tm = mtp_codec::TypeMap::latest(); let version_str = format!("{}", PROTOCOL_VERSION); - let transport = - WasmTransport::connect(&config.url, config.server_certificate_hashes.clone()).await?; + let transport = WasmTransport::connect( + &config.url, + config.server_certificate_hashes.clone(), + config.max_message_size, + ) + .await?; // 1. Send the unsigned Identification hello. let hello = CommunicationValue::new(CommunicationType::Identification) @@ -450,8 +455,12 @@ impl WasmClient { let version_str = format!("{}", PROTOCOL_VERSION); let pk_bytes = keyring.public_key_bundle().as_bytes(); - let transport = - WasmTransport::connect(&config.url, config.server_certificate_hashes.clone()).await?; + let transport = WasmTransport::connect( + &config.url, + config.server_certificate_hashes.clone(), + config.max_message_size, + ) + .await?; // 1. Send the unsigned Register hello (version + public-key bundle). let hello = CommunicationValue::new(CommunicationType::Register) diff --git a/wasm/src/config.rs b/wasm/src/config.rs index 42f1f27..381d76e 100644 --- a/wasm/src/config.rs +++ b/wasm/src/config.rs @@ -5,6 +5,7 @@ pub struct ConnectionConfig { pub(crate) url: String, pub(crate) server_certificate_hashes: Option>, pub(crate) client_id: u64, + pub(crate) max_message_size: u32, } #[wasm_bindgen] @@ -15,6 +16,7 @@ impl ConnectionConfig { url, server_certificate_hashes: None, client_id: 0, + max_message_size: 1_000_000_000, } } @@ -37,4 +39,14 @@ impl ConnectionConfig { pub fn set_server_certificate_hashes(&mut self, hashes: Vec) { self.server_certificate_hashes = Some(hashes); } + + #[wasm_bindgen(setter)] + pub fn set_max_message_size(&mut self, max_message_size: u32) { + self.max_message_size = max_message_size; + } + + #[wasm_bindgen(getter)] + pub fn max_message_size(&self) -> u32 { + self.max_message_size + } } diff --git a/wasm/src/crypto.rs b/wasm/src/crypto.rs index 08032bf..48aa4dc 100644 --- a/wasm/src/crypto.rs +++ b/wasm/src/crypto.rs @@ -42,6 +42,12 @@ impl WasmKeyring { } } +/// Generate a full keyring with KEM, ML-DSA, and Ed25519 keys. +#[wasm_bindgen] +pub fn keyring_generate() -> Vec { + Keyring::generate().to_bytes() +} + /// Build a [`Keyring`] containing only an Ed25519 keypair (no KEM, no ML-DSA). /// /// Takes the Ed25519 secret key and public key, each 32 bytes. diff --git a/wasm/src/frame.rs b/wasm/src/frame.rs index d003bda..691b2cc 100644 --- a/wasm/src/frame.rs +++ b/wasm/src/frame.rs @@ -253,10 +253,7 @@ pub fn parse_auth_response(response: &[u8]) -> Result { let comm = CommunicationValue::from_bytes(response) .map_err(|e| js_error(&format!("parse failed: {}", e)))?; - let connected = matches!( - comm.get_data(DataType::Connected), - DataValue::BoolTrue - ); + let connected = matches!(comm.get_data(DataType::Connected), DataValue::BoolTrue); let client_nonce = match comm.get_data(DataType::ClientNonce) { DataValue::UnsignedNumber(n) => Some(*n), diff --git a/wasm/src/transport.rs b/wasm/src/transport.rs index c9cdd94..df59c30 100644 --- a/wasm/src/transport.rs +++ b/wasm/src/transport.rs @@ -55,6 +55,7 @@ enum FrameOutcome { #[derive(Clone)] pub struct WasmTransport { inner: JsValue, + max_message_size: u32, /// Reader over `incoming_unidirectional_streams()` (a singleton stream of streams). streams_reader: Rc>>, /// Reader over the host's current uni-directional stream, if one is open. @@ -64,7 +65,11 @@ pub struct WasmTransport { } impl WasmTransport { - pub async fn connect(url: &str, cert_hashes: Option>) -> Result { + pub async fn connect( + url: &str, + cert_hashes: Option>, + max_message_size: u32, + ) -> Result { let ctor = js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("WebTransport"))? .dyn_into::() .map_err(|_| js_error("WebTransport not available"))?; @@ -111,6 +116,7 @@ impl WasmTransport { .map_err(|e| js_error(&format!("WebTransport ready failed: {:?}", e)))?; Ok(Self { inner: transport, + max_message_size, streams_reader: Rc::new(RefCell::new(None)), stream_reader: Rc::new(RefCell::new(None)), buffer: Rc::new(RefCell::new(Vec::new())), @@ -122,6 +128,12 @@ impl WasmTransport { } pub async fn send_frame(&self, frame: &[u8]) -> Result<(), JsValue> { + if frame.len() as u64 > self.max_message_size as u64 + || frame.len() as u64 >= CLOSE_FRAME_LEN as u64 + { + return Err(js_error("message too large")); + } + let create_stream = js_sys::Reflect::get( &self.inner, &JsValue::from_str("createUnidirectionalStream"), @@ -273,6 +285,9 @@ impl WasmTransport { if frame_len == CLOSE_FRAME_LEN { return Ok(Some(FrameOutcome::Closed)); } + if frame_len > self.max_message_size { + return Err(js_error("message too large")); + } let frame_len = frame_len as usize; let Some(frame_end) = 4usize.checked_add(frame_len) else { return Err(js_error("invalid frame length")); diff --git a/wasm/types/mtp_wasm.d.ts b/wasm/types/mtp_wasm.d.ts index 532ea10..4ecec6b 100644 --- a/wasm/types/mtp_wasm.d.ts +++ b/wasm/types/mtp_wasm.d.ts @@ -48,6 +48,7 @@ export class ConnectionConfig implements DisposableWasmObject { free(): void; [Symbol.dispose](): void; client_id: bigint; + max_message_size: number; server_certificate_hashes: string[]; readonly url: string; } @@ -158,6 +159,7 @@ export function ed25519_generate(): Ed25519GenerateResult; export function ed25519_verify(public_key: Uint8Array, message: Uint8Array, signature: Uint8Array): void; export function format_frame(frame: Uint8Array): string; export function keyring_from_ed25519(secret_key: Uint8Array, public_key: Uint8Array): Uint8Array; +export function keyring_generate(): Uint8Array; export function main(): void; export function parse_auth_response(response: Uint8Array): AuthResponse; export function parse_frame(frame: Uint8Array): ParsedFrame;