diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ca3aa62..d99138f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,11 +33,17 @@ jobs: libudev-dev - name: Install Rust 1.85.1 uses: dtolnay/rust-toolchain@1.85.1 + with: + components: rustfmt, clippy - name: Run ESLint run: npm run lint - name: Check Prettier formatting run: npm run format:check + - name: Test Desktop channel requests + run: npm run test:channel - name: Check Rust formatting run: npm run tauri:format:check - name: Run Rust Clippy run: mkdir dist && npm run tauri:lint + - name: Test channel protocol + run: cd src-tauri && cargo test channel::tests --all-features diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 870fbff..d45f425 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,6 +2,11 @@ name: "release" on: workflow_dispatch: + inputs: + qa_only: + description: Build an unsigned QA app without creating or updating a release + type: boolean + default: false push: branches: - release @@ -9,7 +14,67 @@ on: # This workflow will trigger on each push to the `release` branch to create or update a GitHub release, build your app, and upload the artifacts to the release. jobs: + build-qa: + if: github.event_name == 'workflow_dispatch' && inputs.qa_only + permissions: + contents: read + runs-on: macos-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22' + - uses: dtolnay/rust-toolchain@1.85.1 + with: + targets: aarch64-apple-darwin + - name: Install frontend and pinned HWI dependencies + run: npm ci + - name: Prepare separate QA identity + run: | + python3 - <<'PYQA' + import json + from pathlib import Path + config = json.loads(Path("src-tauri/tauri.release.conf.json").read_text()) + config["package"].update(productName="Keeper Desktop R3 QA", version="0.2.6-qa.1") + config["tauri"]["bundle"]["identifier"] = "com.keeper.desktop.r3qa" + config["tauri"]["bundle"]["macOS"]["signingIdentity"] = "-" + Path("src-tauri/tauri.qa.conf.json").write_text(json.dumps(config)) + package = json.loads(Path("package.json").read_text()) + package["version"] = "0.2.6-qa.1" + Path("package.json").write_text(json.dumps(package)) + PYQA + - name: Build QA application only + run: npm run tauri build -- --target aarch64-apple-darwin --bundles app --config src-tauri/tauri.qa.conf.json + - name: Verify QA metadata and endpoint + run: | + python3 - <<'PYQA' + import json, plistlib, hashlib + from pathlib import Path + app = next(Path("src-tauri/target/aarch64-apple-darwin/release/bundle/macos").glob("*.app")) + info = plistlib.loads((app / "Contents/Info.plist").read_bytes()) + executable = app / "Contents/MacOS" / info["CFBundleExecutable"] + binary = executable.read_bytes() + assert info["CFBundleIdentifier"] == "com.keeper.desktop.r3qa" + assert info["CFBundleShortVersionString"] == "0.2.6-qa.1" + assert b"https://channel.bitcoinkeeper.app/" in binary + assert b"https://keeper-channel.herokuapp.com/" not in binary + Path("desktop-qa-evidence.json").write_text(json.dumps({ + "version": info["CFBundleShortVersionString"], "identifier": info["CFBundleIdentifier"], + "executable_sha256": hashlib.sha256(binary).hexdigest(), "live_endpoint": True, + "source": "${{ github.sha }}", "signing": "ad hoc QA; not production notarized" + }, indent=2)) + PYQA + ditto -c -k --sequesterRsrc --keepParent "src-tauri/target/aarch64-apple-darwin/release/bundle/macos/Keeper Desktop R3 QA.app" keeper-desktop-r3-qa.zip + - uses: actions/upload-artifact@v4 + with: + name: keeper-desktop-r3-qa-${{ github.sha }} + path: | + keeper-desktop-r3-qa.zip + desktop-qa-evidence.json + retention-days: 14 + publish-tauri: + if: github.event_name != 'workflow_dispatch' || !inputs.qa_only permissions: contents: write actions: read diff --git a/package.json b/package.json index 718dea1..9e3f69e 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "lint:fix": "eslint 'src/**/*.{js,jsx,ts,tsx}' --fix", "format": "prettier --write 'src/**/*.{js,jsx,ts,tsx,json,css,md}'", "format:check": "prettier --check 'src/**/*.{js,jsx,ts,tsx,json,css,md}'", + "test:channel": "tsx --test src/screens/ConnectScreen/validateChannelMessage.test.ts", "get-hwi": "tsx scripts/get-hwi.ts --cleanup", "postinstall": "tsx scripts/get-hwi.ts", "tauri:lint": "cd src-tauri && cargo clippy --all-targets --all-features -- -D warnings", diff --git a/src-tauri/src/channel.rs b/src-tauri/src/channel.rs index 6e5530a..5252f6c 100644 --- a/src-tauri/src/channel.rs +++ b/src-tauri/src/channel.rs @@ -1,6 +1,6 @@ use aes_gcm::aead::rand_core::RngCore; use aes_gcm::aead::{Aead, KeyInit, OsRng}; -use aes_gcm::{Aes256Gcm, Key, Nonce}; +use aes_gcm::{Aes256Gcm, Nonce}; use log::{error, info, warn}; use rust_socketio::client::Client; use rust_socketio::{ClientBuilder, Event, Payload}; @@ -12,10 +12,6 @@ use tauri::Manager; use thiserror::Error; use tokio::time::timeout; -#[cfg(not(feature = "release"))] -static URL: &str = "https://keeper-channel-dev-8d01fa5233d0.herokuapp.com/"; - -#[cfg(feature = "release")] static URL: &str = "https://channel.bitcoinkeeper.app/"; #[derive(Error, Debug)] @@ -26,6 +22,8 @@ pub enum ChannelError { NoRoom, #[error("No encryption key set")] NoEncryptionKey, + #[error("Invalid encryption key")] + InvalidEncryptionKey, #[error("Invalid IV")] InvalidIV, #[error("Invalid encrypted data")] @@ -150,8 +148,8 @@ impl Channel { .ok_or(ChannelError::NoEncryptionKey)?; let key_bytes = hex::decode(encryption_key)?; - let key = Key::::from_slice(&key_bytes); - let cipher = Aes256Gcm::new(key); + let cipher = Aes256Gcm::new_from_slice(&key_bytes) + .map_err(|_| ChannelError::InvalidEncryptionKey)?; let mut nonce_bytes = [0u8; 12]; OsRng.fill_bytes(&mut nonce_bytes); @@ -185,8 +183,8 @@ impl Channel { .ok_or(ChannelError::NoEncryptionKey)?; let key_bytes = hex::decode(encryption_key)?; - let key = Key::::from_slice(&key_bytes); - let cipher = Aes256Gcm::new(key); + let cipher = Aes256Gcm::new_from_slice(&key_bytes) + .map_err(|_| ChannelError::InvalidEncryptionKey)?; let nonce = hex::decode(encrypted["iv"].as_str().ok_or(ChannelError::InvalidIV)?)?; let encrypted_data = hex::decode( @@ -200,6 +198,12 @@ impl Channel { .ok_or(ChannelError::InvalidEncryptedData)?, )?; + if nonce.len() != 12 { + return Err(ChannelError::InvalidIV); + } + if auth_tag.len() != 16 { + return Err(ChannelError::InvalidEncryptedData); + } let nonce = Nonce::from_slice(&nonce); let mut combined_data = Vec::with_capacity(encrypted_data.len() + auth_tag.len()); @@ -224,6 +228,11 @@ impl Channel { .and_then(|arr| arr.first()) .ok_or("Failed to parse message")?; + let room = self.room.as_deref().ok_or("No active channel room")?; + if data.get("room").and_then(|value| value.as_str()) != Some(room) { + return Err("Message received from inactive room".to_string()); + } + let request_data = data .get("requestData") .ok_or("Failed to parse message data")?; @@ -232,12 +241,9 @@ impl Channel { .get("network") .ok_or("Failed to parse message network")?; - let data = if request_data.get("encryptedData").is_some() { - self.decrypt_data(request_data) - .map_err(|_| "Failed to decrypt message from channel")? - } else { - request_data.clone() - }; + let data = self + .decrypt_data(request_data) + .map_err(|_| "Failed to decrypt message from channel")?; Ok(json!({ "data": data, "network": network })) } @@ -302,3 +308,175 @@ fn create_client(app_handle: tauri::AppHandle) -> Result { .connect() .map_err(|e| ChannelError::SocketIoError(e.to_string())) } + +#[cfg(test)] +mod tests { + use super::*; + + fn fixture() -> serde_json::Value { + serde_json::from_str(include_str!("fixtures/channel-crypto-vectors.json")).unwrap() + } + + fn test_channel(key: &str) -> Channel { + Channel { + client: None, + room: Some(hex::encode(Sha256::digest(key))), + encryption_key: Some(key.to_string()), + } + } + + fn request_message(room: &str, request_data: serde_json::Value) -> serde_json::Value { + json!([{"room": room, "requestData": request_data, "network": "TESTNET"}]) + } + + #[test] + fn mobile_signing_vector_is_accepted_with_testnet_network() { + let fixture = fixture(); + let channel = test_channel(fixture["key"].as_str().unwrap()); + let message = request_message( + channel.room.as_deref().unwrap(), + fixture["request"]["ciphertext"].clone(), + ); + assert_eq!( + channel.process_channel_message(&message).unwrap(), + json!({"data": fixture["request"]["plaintext"], "network": "TESTNET"}) + ); + } + + #[test] + fn missing_or_inactive_room_never_reaches_desktop() { + let fixture = fixture(); + let mut channel = test_channel(fixture["key"].as_str().unwrap()); + let ciphertext = fixture["request"]["ciphertext"].clone(); + let missing_room = json!([{"requestData": ciphertext.clone(), "network": "TESTNET"}]); + assert!(channel.process_channel_message(&missing_room).is_err()); + + let old_room = request_message(&"00".repeat(32), ciphertext.clone()); + assert!(channel.process_channel_message(&old_room).is_err()); + + let current_room = request_message(channel.room.as_deref().unwrap(), ciphertext); + channel.room = None; + assert!(channel.process_channel_message(¤t_room).is_err()); + } + + #[test] + fn plaintext_or_incomplete_envelope_is_rejected_in_active_room() { + let fixture = fixture(); + let channel = test_channel(fixture["key"].as_str().unwrap()); + let room = channel.room.as_deref().unwrap(); + let plaintext = request_message(room, fixture["request"]["plaintext"].clone()); + assert!(channel.process_channel_message(&plaintext).is_err()); + + let mut incomplete = fixture["request"]["ciphertext"].clone(); + incomplete.as_object_mut().unwrap().remove("authTag"); + assert!(channel + .process_channel_message(&request_message(room, incomplete)) + .is_err()); + } + + #[test] + fn rotating_qr_rejects_old_room_and_accepts_new_session() { + let fixture = fixture(); + let mut channel = test_channel(fixture["key"].as_str().unwrap()); + let old_request = request_message( + channel.room.as_deref().unwrap(), + fixture["request"]["ciphertext"].clone(), + ); + + let new_key = "01".repeat(32); + channel.room = Some(hex::encode(Sha256::digest(&new_key))); + channel.encryption_key = Some(new_key); + assert!(channel.process_channel_message(&old_request).is_err()); + + let new_ciphertext = channel + .encrypt_data(fixture["request"]["plaintext"].clone()) + .unwrap(); + let new_request = request_message(channel.room.as_deref().unwrap(), new_ciphertext); + assert_eq!( + channel.process_channel_message(&new_request).unwrap(), + json!({"data": fixture["request"]["plaintext"], "network": "TESTNET"}) + ); + } + + #[test] + fn desktop_response_keeps_mobile_event_data_response_shape() { + let fixture = fixture(); + let channel = test_channel(fixture["key"].as_str().unwrap()); + let encrypted = channel + .encrypt_data(fixture["response"]["plaintext"].clone()) + .unwrap(); + assert_eq!(encrypted["iv"].as_str().unwrap().len(), 24); + assert_eq!(encrypted["authTag"].as_str().unwrap().len(), 32); + assert_eq!( + channel.decrypt_data(&encrypted).unwrap(), + fixture["response"]["plaintext"] + ); + assert_eq!( + channel + .decrypt_data(&fixture["response"]["ciphertext"]) + .unwrap(), + fixture["response"]["plaintext"] + ); + } + + #[test] + fn malformed_nonce_returns_error_without_panicking() { + let fixture = fixture(); + let channel = test_channel(fixture["key"].as_str().unwrap()); + for iv in ["", "00", "000102030405060708090a0b0c"] { + let mut encrypted = fixture["request"]["ciphertext"].clone(); + encrypted["iv"] = json!(iv); + assert!(matches!( + channel.decrypt_data(&encrypted), + Err(ChannelError::InvalidIV) + )); + } + } + + #[test] + fn malformed_key_returns_error_without_panicking() { + let fixture = fixture(); + for key in ["", "00", "000102030405060708090a0b0c0d0e0f"] { + let channel = test_channel(key); + assert!(matches!( + channel.decrypt_data(&fixture["request"]["ciphertext"]), + Err(ChannelError::InvalidEncryptionKey) + )); + assert!(matches!( + channel.encrypt_data(json!({"action": "SIGN_TX"})), + Err(ChannelError::InvalidEncryptionKey) + )); + } + } + + #[test] + fn invalid_auth_tag_or_ciphertext_never_returns_signing_data() { + let fixture = fixture(); + let channel = test_channel(fixture["key"].as_str().unwrap()); + let mut encrypted = fixture["request"]["ciphertext"].clone(); + encrypted["authTag"] = json!("00"); + assert!(matches!( + channel.decrypt_data(&encrypted), + Err(ChannelError::InvalidEncryptedData) + )); + for field in ["iv", "encryptedData", "authTag"] { + let mut encrypted = fixture["request"]["ciphertext"].clone(); + let original = encrypted[field].as_str().unwrap(); + let altered = format!( + "{}{}", + if original.starts_with('0') { '1' } else { '0' }, + &original[1..] + ); + encrypted[field] = json!(altered); + assert!(channel.decrypt_data(&encrypted).is_err()); + } + } + + #[test] + fn different_qr_session_cannot_decrypt_request() { + let fixture = fixture(); + assert!(test_channel(&"01".repeat(32)) + .decrypt_data(&fixture["request"]["ciphertext"]) + .is_err()); + } +} diff --git a/src-tauri/src/fixtures/channel-crypto-vectors.json b/src-tauri/src/fixtures/channel-crypto-vectors.json new file mode 100644 index 0000000..dba3f21 --- /dev/null +++ b/src-tauri/src/fixtures/channel-crypto-vectors.json @@ -0,0 +1,40 @@ +{ + "description": "Disposable public AES-GCM protocol vectors; payload strings are not valid or spendable PSBTs.", + "key": "0000000000000000000000000000000000000000000000000000000000000000", + "request": { + "plaintext": { + "action": "SIGN_TX", + "signerType": "LEDGER", + "psbt": { + "serializedPSBT": "fixture-only-psbt" + }, + "miniscriptPolicy": null, + "walletName": "Disposable Testnet Vault", + "hmac": null + }, + "ciphertext": { + "iv": "000102030405060708090a0b", + "encryptedData": "f3e952317494e097e04270b6b444905300348ab69deee691a1ae965ff4456a4dd6d5f0e0082074ae1afceffadddf3a200e8fb58982ffe4bfc090272676dae0e4d416d0f1f52962d833a9ccb89e36d04e52859462da27a96c15bfc60345ade264c870cf71bbdf77b26686255990581a165c29e365bf4ee4c9009b026998837a8f03e20a4039428b0ab3301fc4974fc101d831992717cc61a830fde80893d92c03af43e6f4", + "authTag": "8f6e3b25da67fe3d36a80480936ad896" + } + }, + "response": { + "plaintext": { + "event": "CHANNEL_MESSAGE", + "data": { + "responseData": { + "action": "SIGN_TX", + "data": { + "signedSerializedPSBT": "fixture-only-signed-psbt", + "hmac": null + } + } + } + }, + "ciphertext": { + "iv": "000102030405060708090a0b", + "encryptedData": "f3e956246593fbdbf85a11adbc4d90491833e5dfecceceb18ae9c829e9547b0ececdc7873e02428c57bebeefeadc3a6316ceecd886eef9b7c3977f7930d9fae1ce6bbe8bb16c38c827afc8b7cb239e4416928965ca56b1325eb3c30456bbe546f242ef03ee9178b867d06a45801919541227af7aba4cfee205db1738c0d51cca52fa08523b02dd01e60816ca9e5cd9", + "authTag": "aa74a11d43ab5df18d52ef140b5f92d1" + } + } +} diff --git a/src/screens/ConnectScreen/ConnectScreen.tsx b/src/screens/ConnectScreen/ConnectScreen.tsx index 38d4ae5..7822bc4 100644 --- a/src/screens/ConnectScreen/ConnectScreen.tsx +++ b/src/screens/ConnectScreen/ConnectScreen.tsx @@ -16,29 +16,11 @@ import { NetworkType, } from "../../helpers/devices"; import ModalsManager from "../../modals/ModalManager"; +import ErrorModal from "../../modals/ErrorModal/ErrorModal"; import SubscriptionsModal from "../../modals/SubscriptionsModal/SubscriptionsModal"; import hwiService from "../../services/hwiService"; import { version } from "../../../package.json"; - -interface ChannelMessagePayload { - data: { - signerType: string; - action: string; - accountNumber?: number; - psbt?: { serializedPSBT: string }; - descriptorString?: string; - miniscriptPolicy?: string; - addressIndex?: number; - walletName?: string; - hmac?: string; - firstExtAdd?: string; - receivingAddress?: string; - // Subscription data - appId?: string; - roomId?: string; - }; - network: string; -} +import { validateChannelMessage } from "./validateChannelMessage"; const ConnectScreen = () => { const { openModal, openModalHandler, closeModalHandler } = useModalState(); @@ -56,6 +38,7 @@ const ConnectScreen = () => { const [hmac, setHmac] = useState(null); const [expectedAddress, setExpectedAddress] = useState(null); const [errorMessage, setErrorMessage] = useState(""); + const [packetError, setPacketError] = useState(null); const [pairingCode, setPairingCode] = useState(null); // Subscriptions state variables @@ -109,38 +92,46 @@ const ConnectScreen = () => { useEffect(() => { const unsubscribe = listen( "channel-message", - async (channelMessage: { payload: ChannelMessagePayload }) => { + (channelMessage: { payload: unknown }) => { + const request = validateChannelMessage(channelMessage.payload); + if (!request.ok) { + openModalHandler(null); + setPacketError(request.error); + return; + } + + setPacketError(null); + if (request.kind === "purchase") { + setSubscriptionsData({ + appId: request.appId, + roomId: request.roomId, + }); + openSubscriptionsModal(); + return; + } + setAccountNumber(null); + setAddressIndex(null); setDescriptor(null); setExpectedAddress(null); setHmac(null); setMiniscriptPolicy(null); setPsbt(null); setWalletName(null); - const { data, network } = channelMessage.payload; + const { data, network, deviceType } = request; switch (data.action) { case "ADD_DEVICE": - if (data.accountNumber) { - setAccountNumber(data.accountNumber); - } else { - setAccountNumber(0); - } + setAccountNumber(data.accountNumber ?? 0); setActionType("shareXpubs"); break; case "HEALTH_CHECK": - if (data.accountNumber) { - setAccountNumber(data.accountNumber); - } else { - setAccountNumber(0); - } + setAccountNumber(data.accountNumber ?? 0); setActionType("healthCheck"); break; case "SIGN_TX": setActionType("signTx"); if (data.psbt) { setPsbt(data.psbt.serializedPSBT); - } else { - handleError("PSBT was not provided"); } if (data.miniscriptPolicy) { setMiniscriptPolicy(data.miniscriptPolicy); @@ -165,15 +156,9 @@ const ConnectScreen = () => { } else { setWalletName("Vault"); } - } else { - handleError( - "No descriptor or Miniscript policy was not provided", - ); } if (data.firstExtAdd) { setExpectedAddress(data.firstExtAdd); - } else { - handleError("Expected address was not provided"); } break; case "VERIFY_ADDRESS": @@ -191,30 +176,17 @@ const ConnectScreen = () => { } else { setWalletName("Vault"); } - } else { - handleError("Descriptor or Miniscript policy is required"); } if (data.hmac) { setHmac(data.hmac); } if (data.receivingAddress) { setExpectedAddress(data.receivingAddress); - } else { - handleError("Expected address was not provided"); } break; - case "PURCHASE_SUBS": - setSubscriptionsData({ - appId: data.appId, - roomId: data.roomId, - }); - openSubscriptionsModal(); - return; - default: - handleError("Unsupported action received"); } - setDeviceType(data.signerType.toLowerCase() as HWIDeviceType); - setNetwork(network as NetworkType); + setDeviceType(deviceType); + setNetwork(network); setCurrentAction("connect"); openModalHandler("deviceAction"); }, @@ -223,7 +195,7 @@ const ConnectScreen = () => { return () => { unsubscribe.then((f) => f()); }; - }, [openModalHandler, handleError]); + }, [openModalHandler]); useEffect(() => { const unsubscribe = listen( @@ -331,6 +303,12 @@ const ConnectScreen = () => { pairingCode={pairingCode} /> )} + setPacketError(null)} + errorMessage={packetError ?? ""} + onRetry={() => setPacketError(null)} + />
Version {version}
, + network: unknown = "TESTNET", +) => ({ + data: { action: "ADD_DEVICE", signerType: "LEDGER", ...data }, + network, +}); + +test("accepts a valid device request and keeps its normalized routing fields", () => { + const result = validateChannelMessage(deviceRequest({ accountNumber: 0 })); + assert.equal(result.ok, true); + if (result.ok && result.kind === "device") { + assert.equal(result.deviceType, "ledger"); + assert.equal(result.network, "TESTNET"); + assert.equal(result.data.action, "ADD_DEVICE"); + } else { + assert.fail("Expected a device request"); + } +}); + +test("keeps subscription requests independent of device fields", () => { + assert.deepEqual( + validateChannelMessage({ + data: { action: "PURCHASE_SUBS", appId: "app", roomId: "room" }, + }), + { ok: true, kind: "purchase", appId: "app", roomId: "room" }, + ); +}); + +test("rejects missing transaction data before it can become a device action", () => { + assert.deepEqual( + validateChannelMessage(deviceRequest({ action: "SIGN_TX" })), + { + ok: false, + error: "PSBT was not provided", + }, + ); +}); + +test("accepts the mobile signing shape with nullable optional fields", () => { + const result = validateChannelMessage( + deviceRequest({ + action: "SIGN_TX", + psbt: { serializedPSBT: "cHNidP8=" }, + miniscriptPolicy: null, + walletName: null, + hmac: null, + }), + ); + assert.equal(result.ok, true); + if (result.ok) assert.equal(result.kind, "device"); +}); + +test("rejects incomplete registration and address verification requests", () => { + for (const data of [ + { action: "REGISTER_MULTISIG", firstExtAdd: "address" }, + { action: "REGISTER_MULTISIG", descriptorString: "descriptor" }, + { + action: "VERIFY_ADDRESS", + miniscriptPolicy: "policy", + receivingAddress: "address", + }, + { action: "VERIFY_ADDRESS", descriptorString: "descriptor" }, + ]) { + assert.equal(validateChannelMessage(deviceRequest(data)).ok, false); + } +}); + +test("accepts valid registration and address verification requests", () => { + for (const data of [ + { + action: "REGISTER_MULTISIG", + descriptorString: "descriptor", + miniscriptPolicy: null, + firstExtAdd: "address", + }, + { + action: "VERIFY_ADDRESS", + descriptorString: null, + miniscriptPolicy: "policy", + addressIndex: 0, + receivingAddress: "address", + hmac: null, + }, + ]) { + const result = validateChannelMessage(deviceRequest(data)); + assert.equal(result.ok, true); + if (result.ok) assert.equal(result.kind, "device"); + } +}); + +test("rejects unsupported actions and malformed signer or network", () => { + for (const request of [ + deviceRequest({ action: "UNKNOWN" }), + deviceRequest({ signerType: null }), + deviceRequest({ signerType: "UNKNOWN" }), + deviceRequest({}, "SIGNET"), + { data: null, network: "TESTNET" }, + ]) { + assert.equal(validateChannelMessage(request).ok, false); + } +}); diff --git a/src/screens/ConnectScreen/validateChannelMessage.ts b/src/screens/ConnectScreen/validateChannelMessage.ts new file mode 100644 index 0000000..809979a --- /dev/null +++ b/src/screens/ConnectScreen/validateChannelMessage.ts @@ -0,0 +1,149 @@ +import type { HWIDeviceType, NetworkType } from "../../helpers/devices"; + +type DeviceAction = + | "ADD_DEVICE" + | "HEALTH_CHECK" + | "SIGN_TX" + | "REGISTER_MULTISIG" + | "VERIFY_ADDRESS"; + +export interface DeviceRequestData { + action: DeviceAction; + signerType: string; + accountNumber?: number | null; + psbt?: { serializedPSBT: string }; + descriptorString?: string | null; + miniscriptPolicy?: string | null; + addressIndex?: number | null; + walletName?: string | null; + hmac?: string | null; + firstExtAdd?: string | null; + receivingAddress?: string | null; +} + +type ValidatedChannelMessage = + | { + ok: true; + kind: "device"; + data: DeviceRequestData; + deviceType: HWIDeviceType; + network: NetworkType; + } + | { + ok: true; + kind: "purchase"; + appId?: string; + roomId?: string; + } + | { ok: false; error: string }; + +const deviceTypes: Record = { + ledger: true, + trezor: true, + bitbox02: true, + coldcard: true, + jade: true, +}; + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +const hasText = (value: unknown): value is string => + typeof value === "string" && value.trim().length > 0; + +const isOptionalString = (value: unknown): value is string | null | undefined => + value == null || typeof value === "string"; + +const isOptionalIndex = (value: unknown): value is number | null | undefined => + value == null || + (typeof value === "number" && Number.isSafeInteger(value) && value >= 0); + +export const validateChannelMessage = ( + payload: unknown, +): ValidatedChannelMessage => { + if (!isRecord(payload) || !isRecord(payload.data)) { + return { ok: false, error: "Malformed channel request" }; + } + + const { data } = payload; + if (data.action === "PURCHASE_SUBS") { + if (!isOptionalString(data.appId) || !isOptionalString(data.roomId)) { + return { ok: false, error: "Malformed subscription request" }; + } + return { + ok: true, + kind: "purchase", + appId: data.appId ?? undefined, + roomId: data.roomId ?? undefined, + }; + } + + if ( + data.action !== "ADD_DEVICE" && + data.action !== "HEALTH_CHECK" && + data.action !== "SIGN_TX" && + data.action !== "REGISTER_MULTISIG" && + data.action !== "VERIFY_ADDRESS" + ) { + return { ok: false, error: "Unsupported action received" }; + } + + if (!hasText(data.signerType)) { + return { ok: false, error: "Signer type was not provided" }; + } + const deviceType = data.signerType.toLowerCase(); + if (!Object.prototype.hasOwnProperty.call(deviceTypes, deviceType)) { + return { ok: false, error: "Unsupported signer type received" }; + } + if (payload.network !== "MAINNET" && payload.network !== "TESTNET") { + return { ok: false, error: "Unsupported network received" }; + } + + if ( + !isOptionalIndex(data.accountNumber) || + !isOptionalIndex(data.addressIndex) || + !isOptionalString(data.descriptorString) || + !isOptionalString(data.miniscriptPolicy) || + !isOptionalString(data.walletName) || + !isOptionalString(data.hmac) || + !isOptionalString(data.firstExtAdd) || + !isOptionalString(data.receivingAddress) + ) { + return { ok: false, error: "Malformed device request" }; + } + + if ( + data.action === "SIGN_TX" && + (!isRecord(data.psbt) || !hasText(data.psbt.serializedPSBT)) + ) { + return { ok: false, error: "PSBT was not provided" }; + } + if ( + data.action === "REGISTER_MULTISIG" && + !hasText(data.descriptorString) && + !hasText(data.miniscriptPolicy) + ) { + return { ok: false, error: "Descriptor or Miniscript policy is required" }; + } + if (data.action === "REGISTER_MULTISIG" && !hasText(data.firstExtAdd)) { + return { ok: false, error: "Expected address was not provided" }; + } + if ( + data.action === "VERIFY_ADDRESS" && + !hasText(data.descriptorString) && + !(hasText(data.miniscriptPolicy) && typeof data.addressIndex === "number") + ) { + return { ok: false, error: "Descriptor or Miniscript policy is required" }; + } + if (data.action === "VERIFY_ADDRESS" && !hasText(data.receivingAddress)) { + return { ok: false, error: "Expected address was not provided" }; + } + + return { + ok: true, + kind: "device", + data: data as unknown as DeviceRequestData, + deviceType: deviceType as HWIDeviceType, + network: payload.network, + }; +};