From e79e16b572d6e3472ac94500bf812d937bd89135 Mon Sep 17 00:00:00 2001 From: Anant Date: Fri, 25 Sep 2026 21:28:56 +0530 Subject: [PATCH 01/19] fix: synchronize release versions and verify packaged artifacts --- Gemfile.lock | 5 +- android/app/build.gradle | 22 +- android/fastlane/Fastfile | 42 ++-- android/fastlane/README.md | 2 +- android/gradle.properties | 4 - ios/Podfile.lock | 214 +++++++++--------- ios/fastlane/Fastfile | 19 +- ios/hexa_keeper.xcodeproj/project.pbxproj | 16 +- ios/hexa_keeper/Info.plist | 2 +- ios/hexa_keeper_dev-Info.plist | 2 +- .../.openspec.yaml | 2 + .../fix-release-version-consistency/design.md | 46 ++++ .../proposal.md | 33 +++ .../specs/release-version-consistency/spec.md | 76 +++++++ .../fix-release-version-consistency/tasks.md | 35 +++ openspec/config.yaml | 2 +- package.json | 7 +- release/README.md | 40 ++++ release/version.json | 21 ++ scripts/release-version.cjs | 168 ++++++++++++++ scripts/release-version.test.cjs | 80 +++++++ scripts/test_release_artifact.py | 86 +++++++ scripts/verify-release-artifact.py | 112 +++++++++ 23 files changed, 873 insertions(+), 163 deletions(-) create mode 100644 openspec/changes/fix-release-version-consistency/.openspec.yaml create mode 100644 openspec/changes/fix-release-version-consistency/design.md create mode 100644 openspec/changes/fix-release-version-consistency/proposal.md create mode 100644 openspec/changes/fix-release-version-consistency/specs/release-version-consistency/spec.md create mode 100644 openspec/changes/fix-release-version-consistency/tasks.md create mode 100644 release/README.md create mode 100644 release/version.json create mode 100644 scripts/release-version.cjs create mode 100644 scripts/release-version.test.cjs create mode 100644 scripts/test_release_artifact.py create mode 100644 scripts/verify-release-artifact.py diff --git a/Gemfile.lock b/Gemfile.lock index 1dabd56760..c60ef7ba78 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -288,8 +288,11 @@ PLATFORMS ruby DEPENDENCIES - cocoapods (>= 1.11.3) + activesupport (>= 6.1.7.5, != 7.1.0) + cocoapods (>= 1.13, != 1.15.1, != 1.15.0) + concurrent-ruby (< 1.3.4) fastlane (~> 2.225.0) + xcodeproj (< 1.26.0) RUBY VERSION ruby 3.3.0p0 diff --git a/android/app/build.gradle b/android/app/build.gradle index e8ead00b0a..a56f8d534d 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -98,8 +98,8 @@ android { applicationId "io.hexawallet.keeper" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 621 - versionName "2.3.15" + versionCode 622 + versionName "2.5.15" missingDimensionStrategy 'react-native-camera', 'general' missingDimensionStrategy 'store', 'play' multiDexEnabled true @@ -115,12 +115,11 @@ android { signingConfigs { release { - if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) { - storeFile file(MYAPP_RELEASE_STORE_FILE) - storePassword MYAPP_RELEASE_STORE_PASSWORD - keyAlias MYAPP_RELEASE_KEY_ALIAS - keyPassword MYAPP_RELEASE_KEY_PASSWORD - } + // Release credentials belong in the build environment, never in Git. + storeFile file(System.getenv('KEEPER_ANDROID_KEYSTORE') ?: 'release.keystore') + storePassword System.getenv('STORE_PASSWORD') + keyAlias System.getenv('KEY_ALIAS') + keyPassword System.getenv('KEY_PASSWORD') } debug { storeFile file('debug.keystore') @@ -134,13 +133,16 @@ android { signingConfig signingConfigs.debug } release { - signingConfig signingConfigs.release + // Caution! In production, you need to generate your own keystore file. + // see https://reactnative.dev/docs/signed-apk-android. + // signingConfig signingConfigs.debug minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } productFlavors { production { + signingConfig signingConfigs.release minSdkVersion rootProject.ext.minSdkVersion applicationId "io.hexawallet.bitcoinkeeper" targetSdkVersion rootProject.ext.targetSdkVersion @@ -203,4 +205,4 @@ dependencies { implementation 'com.itextpdf:itextg:5.5.10' -} +} \ No newline at end of file diff --git a/android/fastlane/Fastfile b/android/fastlane/Fastfile index 6765414875..cfc909f0db 100644 --- a/android/fastlane/Fastfile +++ b/android/fastlane/Fastfile @@ -47,20 +47,18 @@ platform :android do ) end - desc "Push a new live build to Slack and internal track on Play Store" + desc "Build explicitly versioned production artifacts and upload to Play internal testing" lane :live do - file_name = "../../.env" - file_url = "https://raw.githubusercontent.com/bithyve/bitcoin-keeper-envs/live/app.live.env" - auth_header = "Authorization: token #{ENV["GITHUB_ACCESS_TOKEN"]}" - sh( - "curl -H '#{auth_header}' -o '#{file_name}' -s '#{file_url}'", - step_name: "curl -H '***' -o '#{file_name}' -s '#{file_url}'" - ) + sh("node", File.expand_path("../../scripts/release-version.cjs", __dir__), "release-check") + production_env = File.expand_path("../../.env.production", __dir__) + UI.user_error!("Missing reviewed .env.production") unless File.file?(production_env) + ENV['ENVFILE'] = production_env store_password = ENV["STORE_PASSWORD"] key_password = ENV["KEY_PASSWORD"] key_alias = ENV["KEY_ALIAS"] - releaseFilePath = File.join(Dir.pwd, "../app", "release.keystore") - bump_version_code() + UI.user_error!("Missing Android release signing credentials") if [store_password, key_password, key_alias].any? { |value| value.to_s.empty? } + releaseFilePath = ENV["KEEPER_ANDROID_KEYSTORE"] || File.expand_path("../app/release.keystore", __dir__) + UI.user_error!("Missing Android release keystore") unless File.file?(releaseFilePath) gradle(task: 'clean') gradle( task: 'bundle', @@ -73,9 +71,8 @@ platform :android do "android.injected.signing.key.password" => key_password, } ) - upload_to_play_store( - track: 'internal' - ) + aab_path = Actions.lane_context[SharedValues::GRADLE_AAB_OUTPUT_PATH].to_s + UI.user_error!("Build did not return an AAB path") if aab_path.empty? gradle( task: 'assemble', build_type: 'productionRelease', @@ -87,21 +84,36 @@ platform :android do "android.injected.signing.key.password" => key_password, } ) + apk_path = Actions.lane_context[SharedValues::GRADLE_APK_OUTPUT_PATH].to_s + UI.user_error!("Build did not return an APK path") if apk_path.empty? + verifier = File.expand_path("../../scripts/verify-release-artifact.py", __dir__) + sh("python3", verifier, aab_path) + sh("python3", verifier, apk_path) + upload_to_play_store( + track: 'internal', + aab: aab_path + ) end end after_all do |lane| versionCode = android_get_version_code() - slack(message: "Build success :rocket:\nVersion Code: " + versionCode.to_s) + UI.message("Build success. Version Code: " + versionCode.to_s) + if ENV['KEEPER_NOTIFY_SLACK'] == '1' + slack(message: "Build success :rocket:\nVersion Code: " + versionCode.to_s) end +end - error do |lane, exception| +error do |lane, exception| + UI.error("Fastlane failed: " + exception.message.to_s) + if ENV['KEEPER_NOTIFY_SLACK'] == '1' slack( message: exception.message, success:false ) end +end lane :bump_version_code do path = '../app/build.gradle' diff --git a/android/fastlane/README.md b/android/fastlane/README.md index a0074a4078..2e7a754656 100644 --- a/android/fastlane/README.md +++ b/android/fastlane/README.md @@ -40,7 +40,7 @@ Push a new dev build to Slack [bundle exec] fastlane android live ``` -Push a new live build to Slack and internal track on Play Store +Build explicitly versioned production artifacts and upload to Play internal testing ---- diff --git a/android/gradle.properties b/android/gradle.properties index 4e6e2e1b48..2f15da72f1 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -36,10 +36,6 @@ reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 # are providing them. newArchEnabled=true -MYAPP_RELEASE_STORE_FILE=release.keystore -MYAPP_RELEASE_KEY_ALIAS=hexawallet -MYAPP_RELEASE_STORE_PASSWORD=hexa@2021 -MYAPP_RELEASE_KEY_PASSWORD=hexa@2021 org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=2048m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 # Use this property to enable or disable the Hermes JS engine. diff --git a/ios/Podfile.lock b/ios/Podfile.lock index 85cbf1ecf8..a5c2f9af0b 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -131,7 +131,7 @@ PODS: - nanopb/encode (= 3.30910.0) - nanopb/decode (3.30910.0) - nanopb/encode (3.30910.0) - - NitroIap (14.4.18): + - NitroIap (16.5.0): - boost - DoubleConversion - fast_float @@ -139,7 +139,7 @@ PODS: - glog - hermes-engine - NitroModules - - openiap (= 1.2.22) + - openiap (= 3.4.0) - RCT-Folly - RCT-Folly/Fabric - RCTRequired @@ -193,7 +193,7 @@ PODS: - ReactCommon/turbomodule/core - SocketRocket - Yoga - - NitroModules (0.29.6): + - NitroModules (0.35.4): - boost - DoubleConversion - fast_float @@ -222,7 +222,7 @@ PODS: - ReactCommon/turbomodule/core - SocketRocket - Yoga - - openiap (1.2.22) + - openiap (3.4.0) - PDFGenerator (3.1.0) - PromisesObjC (2.4.0) - QRCoder (1.1.0) @@ -3971,7 +3971,7 @@ CHECKOUT OPTIONS: SPEC CHECKSUMS: boost: 7e761d76ca2ce687f7cc98e698152abd03a18f90 - BVLinearGradient: cb006ba232a1f3e4f341bb62c42d1098c284da70 + BVLinearGradient: 880f91a7854faff2df62518f0281afb1c60d49a3 CocoaAsyncSocket: 065fd1e645c7abab64f7a6a2007a48038fdc6a99 DoubleConversion: cb417026b2400c8f53ae97020b2be961b59470cb fast_float: b32c788ed9c6a8c584d114d0047beda9664e7cc6 @@ -3987,16 +3987,16 @@ SPEC CHECKSUMS: GoogleDataTransport: aae35b7ea0c09004c3797d53c8c41f66f219d6a7 GoogleUtilities: 00c88b9a86066ef77f0da2fab05f65d7768ed8e1 hermes-engine: 4ec27e7c84ed7950da6e65008539685455d8bef4 - HtmlToPdf: 6a9c28f54ec810d1d120a698a9b3c83e2bdb1672 + HtmlToPdf: 5c0649e93aa1c6583f400268eedea00f15e0fa5f libportal-ios: d9aa55474e2d5be8e38e96345dd37be34fda45b4 - libportal-react-native: 91b6bec36f7e92a0bcc4e9d51d6ce3ee7c163728 + libportal-react-native: 05778ef04321517c8366dc7173d05aa9fe131ff2 libwebp: 02b23773aedb6ff1fd38cec7a77b81414c6842a8 MMKVCore: 3d16ce9f7d411e135020915fde98a056859a1efa nanopb: fad817b59e0457d11a5dfbde799381cd727c1275 - NitroIap: 4567529625c807049c148f8cecfc0d774d67b584 - NitroMmkv: 320feb7789986e3ba45582d5c630ebcfeca807ae - NitroModules: 7d693306799405ca141ef5c24efc0936f20a09c0 - openiap: a6c203f0e8f4ace4f05477f90a2967327ef3ad70 + NitroIap: 2aab68488ccce3c0d6046f0e896b3ed4a5838314 + NitroMmkv: 1f66a0e71a3a3c5677921aca853aabf7911d92c1 + NitroModules: b632f83915f059473b72b5d6fb90ff2c2ca674c1 + openiap: 253070b2afe71078a2cae63a2b8e282bdd44a059 PDFGenerator: 17d6bc525db0a3fcd156fbf00f9d1b8d5cc75d1e PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47 QRCoder: cbd2bee531cc86d286df7942334cfed94c803ae4 @@ -4004,115 +4004,115 @@ SPEC CHECKSUMS: RCTDeprecation: c7d33f6bc08dbb8be7dfa70d219bfb034480a406 RCTRequired: 42b13c9504609bae9a9f65673a6b4fcbd8d07bd1 RCTSwiftUI: cef2010e1e5e699600b2064d3aa702e53c35816c - RCTSwiftUIWrapper: 18f0f0601b556e27593928c36697d5f651db760f + RCTSwiftUIWrapper: dc8026f15059e65ae5f23ce8b7032f52318e04bb RCTTypeSafety: c5fd6a8092bee25eaa31d4cca03794e902b5fdfd React: 6c36d83b2afecc1d45ec2a637158750edad20d87 React-callinvoker: 813372c3165324939d57b849f2db0c99390b9aac - React-Core: b2a189a7e16fc88a768908152201f14379708ac0 - React-CoreModules: 7ff1464d8c75a63c4028571217e4f4d01b008919 - React-cxxreact: 06aed26685cbd29a55d1648a14f13491549cea9d + React-Core: 497da2fa08060213b5b265b38cb64af2e0f0526c + React-CoreModules: 255a3150b3a24c8628ef050e7ae448d198dd003b + React-cxxreact: e6a1142898716d391d27bd7d05091fca0046e2c5 React-debug: eeaaa885aed6766643a249e186cb55910847f32d - React-defaultsnativemodule: 137369659d426f45688b7467775a6dc153abf127 - React-domnativemodule: 5c80b3bd89b4d14d1e57f2c2ac2a8e7a3d2a7dcc - React-Fabric: be18c20ebb56a507b6f04dd701fdc79ab7111763 - React-FabricComponents: 648428bb2ea49ee4db5796d9670994280c93e447 - React-FabricImage: 44232bb0498164e155ffb33621acc1851146d964 - React-featureflags: 840962f151a33d44a93f289d59bcffd166fa8e39 - React-featureflagsnativemodule: 2dac13fa41ee8eff0c45e2a336f5c98291ef9a96 - React-graphics: 8f80ab9311f947fade8d34ddd3cff8870441d000 - React-hermes: f241babdb4e8595933d856ab78f5d5d49218cac0 - React-idlecallbacksnativemodule: 2d0687f8820e232f4686109721ec066c169f9232 - React-ImageManager: cda1751f63b04e8a7df4cb65894ed34c6043fb2e - React-intersectionobservernativemodule: 34d7b434d4df27a113158bed316a4e0dff658d2b - React-jserrorhandler: e8ad51be4b0e29eadfdd7854675cf5087a4ea5f9 - React-jsi: ee1dbc3b2635ce07783e6638656c0b472573bb48 - React-jsiexecutor: 05fe7918c713a64a39474915f725fe0e61d65309 - React-jsinspector: 57db0ee88c1471b7310d3feb5c3c92cec6db4702 - React-jsinspectorcdp: 757575b5a8151ca2f253f21e73ef371bc92482a8 - React-jsinspectornetwork: 443fb13ccad11b861d5810f572e6eceb7dd98e05 - React-jsinspectortracing: 59c88018cbc7855bb26c49d8b3bb5ce0d7a6c00a - React-jsitooling: abc1f89dd35866995bcb873c60a15e8af82d0d96 - React-jsitracing: e8993f012752e5f7a5e749d9348095c30091bb27 - React-logger: cf2064f903777a5bdca904c4265f17396d4d8568 - React-Mapbuffer: c546207c9ac05ba26b90ba26f1288f84c8867f2e - React-microtasksnativemodule: ad2becc1076529952b6db26d0a1476ec489b9067 - React-mutationobservernativemodule: 867e9c215f21b4308fa98473f3c38585b5897e44 - react-native-background-timer: 4638ae3bee00320753647900b21260b10587b6f7 - react-native-biometrics: ecca256a9e1c8b430f78c4e3dcb16b57ea1418e0 - react-native-blob-util: 6dec9023ecc3ee5ac8ad377598e943f9ca63f741 - react-native-change-icon: 2abab62ecabf10adf6e03cc9516484a27385b580 - react-native-config: 8e425892a531627c52db765be3088185cb871e19 - react-native-contacts: 2a259e02b85c9510a5fcbdf06c56c828387d47c1 - react-native-document-picker: dc2d83366e47e89e7c51e8a41eab99c1d54e941c - react-native-get-random-values: e2acf4070fe4b7325705a05af047449637a27a21 - react-native-hce: ad5462e792d84e87924308dda1ee516757f1c0eb - react-native-image-picker: 1f5318beec2ebed6695454ffb9bea8c4152f1598 - react-native-netinfo: cec9c4e86083cb5b6aba0e0711f563e2fbbff187 - react-native-nfc-manager: e5d2ce2f7fee42d1ee0eb6b99f3405d5e330112e - react-native-pdf: 2886351f9ea698a820f53056afdabd6fa0ab726d - react-native-randombytes: 3c8f3e89d12487fd03a2f966c288d495415fc116 - react-native-rsa-native: a7931cdda1f73a8576a46d7f431378c5550f0c38 - react-native-safe-area-context: befb5404eb8a16fdc07fa2bebab3568ecabcbb8a - react-native-tcp-socket: 7c7e53a07f122ecf00fb3626684bc0ca82c4f044 - react-native-worklets-core: aaaac7d17f7e576592369a54f30e96fe4875c983 - React-NativeModulesApple: 519f9f98375db6458a7220becd25db81b3860b76 - React-networking: 2318cba8288ec5df38e899feed3baaac0629b4bd + React-defaultsnativemodule: ff63dc721adb5db6eef0951035d4a2935ac99aa8 + React-domnativemodule: eb73ab018bdd17b950515fc6d1b06fa0ae953110 + React-Fabric: 2815ec8bfd1c71a8696bbee7d3ff2a97af27b1c3 + React-FabricComponents: caf3e972e0d2b7feed1f0003377a74a6d9e12cac + React-FabricImage: 9c0298b399cf042d937f42ffcdde9047637fdc0f + React-featureflags: 7ff07b72680999f92cf82fdf58477b38a876d3b1 + React-featureflagsnativemodule: ad7919cff5b36a45af42433d323b8fd23931dadd + React-graphics: 57c9e72ea57228e83474a27367c4182a79acc803 + React-hermes: 85101b86c76672bdfc78def14feb93c15445f029 + React-idlecallbacksnativemodule: d8402e2ed16af4bc0f506315bfdf96007decd80b + React-ImageManager: f0f9fafd26ff52e16781fbc8844a55bd3ba21513 + React-intersectionobservernativemodule: 5bc884eb7e1fe8fec87faf712c963adcec95da69 + React-jserrorhandler: 0a5be1ec13b7ae0404545422bef137be0d36b38b + React-jsi: abd0559cbfcd75539f61bc6ee3ae1e72c38b8727 + React-jsiexecutor: e96ff30c2e7ab4c1a1652e6a48d44f80b774b411 + React-jsinspector: 0199e40d52099d06060387d5143dc32cce90aa83 + React-jsinspectorcdp: 6ca5a4774f941b0a791790adeb94fa55f5338b88 + React-jsinspectornetwork: 1551f3fb9c1db9e1e178acfca43aec29c99f82a9 + React-jsinspectortracing: ea86019081a9a746470d85307209118daa6aa6cc + React-jsitooling: 3c1dfec708ea756367d36784c158487d149a3b96 + React-jsitracing: ef17de0220ff8f0bbf95b5a41b63b44b81cf5a55 + React-logger: 532b0b1405e20c08146a739fbaf6fd16fd771291 + React-Mapbuffer: a803b9ab86de5b3cacfd1f7e324300a4e932d201 + React-microtasksnativemodule: 5b3728f26cfad14e7d05bba8e36f19ae083a787b + React-mutationobservernativemodule: db471fd2cc188f72dc7d5add41d2bebf5361f0ce + react-native-background-timer: 17ea5e06803401a379ebf1f20505b793ac44d0fe + react-native-biometrics: 3b95f2eb074d537d3a8b05d853c17778f6685c4a + react-native-blob-util: ca455d4d8cc8ed667b6c3dfd7ca00aef09f6ee63 + react-native-change-icon: 5bfde1910111f603e75b77e1bf9feabaf2bb070e + react-native-config: 7cd105e71d903104e8919261480858940a6b9c0e + react-native-contacts: 8787d1e792bae8ba6edd1c7ea2749689440ab4bd + react-native-document-picker: 063f6391c62fafd49f97490a3ebb1255e4e30781 + react-native-get-random-values: 9856c21cab42a6d8db71dcb35c3059fdaeac2b16 + react-native-hce: ae425226cd27e1831b98e5577f15f686a1a0dab8 + react-native-image-picker: 60f4246eb5bb7187fc15638a8c1f13abd3820695 + react-native-netinfo: f0a9899081c185db1de5bb2fdc1c88c202a059ac + react-native-nfc-manager: 1bcdf6f96c9065a8f4c8d9a0c6fb2db625205b2c + react-native-pdf: cd45064d7ef704e69f44c2cee14f0635764c752b + react-native-randombytes: 421f1c7d48c0af8dbcd471b0324393ebf8fe7846 + react-native-rsa-native: 12132eb627797529fdb1f0d22fd0f8f9678df64a + react-native-safe-area-context: 0f4986a88ec555aff660503b483d6e4bd6980a9a + react-native-tcp-socket: c9290d77fea17ee75bee93e599b604bae63166f0 + react-native-worklets-core: 30da6af07bef6fcb77ed2b53787958c3d56048e8 + React-NativeModulesApple: 74bee0c16a7a5426aeadd753179a41d7da413c99 + React-networking: 08d6e4f20fc02f240fb1c7b48bc0d72fdc66b1ea React-oscompat: 4524d8ccb12b7f07beb12e2ea9c5ea55b55d604b - React-perflogger: 2b2a2bc9173796cc58fece00d3df1c99b39c2b8e - React-performancecdpmetrics: 162db18cc31c25256d393383890cb0f3de27cf73 - React-performancetimeline: a3b28cf401e8cb2027fb282a697ea87d97cd320a + React-perflogger: ccc20d34acfe74605f0f2d2a414fddf731b14bd1 + React-performancecdpmetrics: a750a2a3276b32d543542bfe72f7509b65fd8a3a + React-performancetimeline: a7bf3ba360917c9001e26c47e55ccab2f6895d00 React-RCTActionSheet: e1c8afe045a25f3a8d73da52bb28e6186718e206 - React-RCTAnimation: 7681b2367405b53d4e91ac76b36bd8fb1ce50a53 - React-RCTAppDelegate: e8d05c439051bd6860638e59fc8fb81cf3ac0f9b - React-RCTBlob: fa0e5ab89883e4bf5eb05e534b68ce2951ca514b - React-RCTFabric: d505530c38fada112559a19e91d200a6b8381d4f - React-RCTFBReactNativeSpec: 2d7c44c5b4349957cec8c77bb5cd401d9348c4fc - React-RCTImage: 8d32ede0e9f07aa7a446a54e924f23b3347d2960 - React-RCTLinking: ef0c625de1ce2b78189cb65391888628b5d2d6ed - React-RCTNetwork: 5e6a3678c23c0b8c4e2b69e85551215f1fcfe2b2 - React-RCTRuntime: ec85cc9d0ca3bd98bfcc0674c59f011eacc96d91 - React-RCTSettings: c7f2c32bee82c3f4e757d779fff3c2bf47cc7e46 - React-RCTText: cc134029a95773223502a9aeac47300586426ca5 - React-RCTVibration: 9ed48065a50d4a4311aed5c17272061f2cae910b + React-RCTAnimation: f350cac40fbf4d2f7269c50a4809812a51e7143a + React-RCTAppDelegate: c7e4dd9a3a94f348a9c9e3f6ec30a2fa45713d0b + React-RCTBlob: 8215edb879697c37ebc3d93d44210c136b0f8f12 + React-RCTFabric: e2a194c2ae6cba49dc67f72250bd48d5457a0711 + React-RCTFBReactNativeSpec: 77b5b284baa526512b143c24ae44d7e24c688e65 + React-RCTImage: 55ce5873af9d447dde76711c84ea545688eb5e01 + React-RCTLinking: 803e8a4356dc848d1cff0882e70b81c2c28f67e1 + React-RCTNetwork: 5e13fe88a73150e7cd7eff989a55b5c1c7e4b701 + React-RCTRuntime: ab3bddd645d86fd1858d9005fe4943cf333384a2 + React-RCTSettings: 3a6fd39c7169fe408f6cf16d939ba7910b02fe6e + React-RCTText: 5a2c8addcbe6d3d36636407423d9969012fcdaa7 + React-RCTVibration: 460b55fcd5ae2f028e9910ccad192f5ffea1d6b8 React-rendererconsistency: 9262a6a4c4be861ffd7e3149c517bd4076a8851f - React-renderercss: 4840f91b676f4000cc704f9214f950df02be54f1 - React-rendererdebug: 613c8b53e6032d16c4c499d52bbd21c9df6873fa - React-RuntimeApple: d53d701e0ac401fa6caca87d22881559617e5a5a - React-RuntimeCore: 2232f165e559a6edf997a5b18e9669a63e997cba - React-runtimeexecutor: fbe7aa46f3c1233e903fa6758a1c8c372070c33b - React-RuntimeHermes: a5ada5beb920f09b3fb3fce491d8d3d132c6e677 - React-runtimescheduler: 81f357f73c68c93459b714b1f917e30a40f1a1ea - React-timing: 5ace10dca5f52437bb6d4212404898d9ab7df82f - React-utils: 29d70520468725a40da28decabd1c58dda7f6f90 - React-webperformancenativemodule: a5f9909a36ae47ea244e38efd25e479c01d39e14 - ReactAppDependencyProvider: 87593e9dfdba8dac1d7b2af1af05f0eff2a05684 - ReactCodegen: 417334350a76a91784cc20f7aff392327e217dc4 - ReactCommon: 5f2db7556b60816bdc5761a359539bacd2d0250d - RealmJS: 10fb99cdac98cad8a6c4471c967bd6be10307741 - RNCClipboard: adba6334687b7fb2c37760e26dedd550b4846a72 - RNDeviceInfo: f9d6fd102f8b11daa7ee322391b23cebee3bd95f - RNFastImage: 462a183c4b0b6b26fdfd639e1ed6ba37536c3b87 - RNFBApp: 022bf8a1be198c5b8dc8af4dcb656d49f903aa8d - RNFBMessaging: e42061ab9fab61081c38b5661b292c1f295bbc96 - RNFS: 89de7d7f4c0f6bafa05343c578f61118c8282ed8 - RNGestureHandler: be7148bc663eac98c0ad6474b4b105f8cadd56be - RNKeychain: a2c134ab796272c3d605e035ab727591000b30f3 - RNLocalize: 19917c3f32cf6386f7d2957a638a4281669cae57 - RNQrGenerator: af2f0888eb81b8ff99517a3929d6399444dcc56d - RNReanimated: 4e6187f2ba1e30e6ddc7c8fc9f19b2dd2b6b2532 - RNScreens: 7f643ee0fd1407dc5085c7795460bd93da113b8f - RNSentry: 80792b62c5fa701a58e27d022e1eb20d52a796e5 - RNShare: 51d221e8ac06263e91168c604b94274fdcc4784f - RNSVG: 3405336c4507ee0bafb02b08058d57216daa2c50 - RNWorklets: 6daa3975bebe6047822c7485666d501a716674ca + React-renderercss: 1641d6d12b7aa54fda225dd0f1fa24f199d523ae + React-rendererdebug: 92ee565692a4a3e6806e88fa4ee816bda5cee693 + React-RuntimeApple: a4f51fa6ebd62e5ac0d3445e47d2a71efd750939 + React-RuntimeCore: c5f51bd6afd2884341749817c5ec512d0dcbc4a7 + React-runtimeexecutor: 3e96660fb93a17185bc8b23c6bbe10fe25f6d3e2 + React-RuntimeHermes: 8382231d2cdfc51bb67785fbc6cc4218f7e934c4 + React-runtimescheduler: 44aa1cbed3ce2759678a1e544ad27108c934a046 + React-timing: ac50e2e44dc82ec7241557bad16adcae184a693b + React-utils: 493a45d877f410d62476c045fbf220acbffba194 + React-webperformancenativemodule: 9b212313b01f5489f21963fbd4a81ef20f280097 + ReactAppDependencyProvider: 5bf52020fdc0d0a337068ea42d4a6676ce4a04bc + ReactCodegen: 5c808345ff57b4f4f1eab230f541921ad9e37500 + ReactCommon: 3b79ecfd327035654f6c36cf1de8e222d8b835e6 + RealmJS: a2e97359d58d72ca9fc2deb2e14ba34a218652e5 + RNCClipboard: a9d5216cbfaf2f51cfe80bcb132856bb9158fe0d + RNDeviceInfo: 0a7c1d2532aa7691f9b9925a27e43af006db4dae + RNFastImage: 5c9c9fed9c076e521b3f509fe79e790418a544e8 + RNFBApp: bb2b158188e3bd5161cbdcd7e9058c2edfaa8c11 + RNFBMessaging: 994290a71d043bc0837e89514be19ce02805790c + RNFS: 4ac0f0ea233904cb798630b3c077808c06931688 + RNGestureHandler: afae32614741017de0f813f74586eee29773f31a + RNKeychain: 182d986f809280edd9444a557adc21845f7d1e6f + RNLocalize: 95a43f85e41a966be7bc9cff2437128911c52da0 + RNQrGenerator: 36f1af182d7673bc36e317aca0d293d19883d6e3 + RNReanimated: 6b69a94db352e4dae7eb540f6fab60ff05c18508 + RNScreens: 7179cc1ba31b4e18ed29f10abf20c24a7961cf4c + RNSentry: f07853ff3fcbb69df26da1d9744e95ee97f683fd + RNShare: 11923289a9964c6bd5f507eaa7fe61ec51b0adce + RNSVG: 6a91afc99237de70b617c7a84ba84c988ad5573b + RNWorklets: 3f35c2c01e5839d4fee0496d10ada185628ba328 SDWebImage: a7f831e1a65eb5e285e3fb046a23fcfbf08e696d SDWebImageWebPCoder: 908b83b6adda48effe7667cd2b7f78c897e5111d Sentry: 4e85b40e4b0235853f40f959d315a6b28e3148d8 SocketRocket: d4aabe649be1e368d1318fdf28a022d714d65748 - VisionCamera: 0044a94f7489f19e19d5938e97dfc36f4784af3c + VisionCamera: 47f10351a1b6a8d251b90986ae72ca5f52331954 Yoga: e6489bbfdab9b98f8d51993484d6bd40216b7834 ZXingObjC: 8898711ab495761b2dbbdec76d90164a6d7e14c5 PODFILE CHECKSUM: b6c63a86c263fb282b75313bfa3faf16def35484 -COCOAPODS: 1.16.2 +COCOAPODS: 1.15.2 diff --git a/ios/fastlane/Fastfile b/ios/fastlane/Fastfile index 7147a897aa..b231891c82 100644 --- a/ios/fastlane/Fastfile +++ b/ios/fastlane/Fastfile @@ -35,11 +35,7 @@ def resolved_ipa_path! ipa_path = Actions.lane_context[SharedValues::IPA_OUTPUT_PATH].to_s if ipa_path.strip.empty? - ipa_path = Dir["./builds/*.ipa"].sort_by { |path| File.mtime(path) }.last.to_s - end - - if ipa_path.strip.empty? - UI.user_error!("Unable to locate generated .ipa file for TestFlight upload") + UI.user_error!("Current build did not return an IPA path; refusing to reuse an older archive") end ipa_path @@ -108,14 +104,10 @@ platform :ios do desc "Push a new live build to TestFlight" lane :live do - file_name = "../../.env" - file_url = "https://raw.githubusercontent.com/bithyve/bitcoin-keeper-envs/live/app.live.env" - auth_header = "Authorization: token #{ENV["GITHUB_ACCESS_TOKEN"]}" - sh( - "curl -H '#{auth_header}' -o '#{file_name}' -s '#{file_url}'", - step_name: "curl -H '***' -o '#{file_name}' -s '#{file_url}'" - ) - increment_build_number(xcodeproj: "hexa_keeper.xcodeproj") + sh("node", File.expand_path("../../scripts/release-version.cjs", __dir__), "release-check") + production_env = File.expand_path("../../.env.production", __dir__) + UI.user_error!("Missing reviewed .env.production") unless File.file?(production_env) + ENV['ENVFILE'] = production_env get_certificates( # Create or get certificate, and install it output_path: "./builds" # Download certificate in the build folder (you don't need to create the folder) @@ -148,6 +140,7 @@ platform :ios do }, build_path: "./builds", output_directory: "./builds") + sh("python3", File.expand_path("../../scripts/verify-release-artifact.py", __dir__), resolved_ipa_path!) upload_build_to_testflight! end end diff --git a/ios/hexa_keeper.xcodeproj/project.pbxproj b/ios/hexa_keeper.xcodeproj/project.pbxproj index 7f0b8da754..cc49992030 100644 --- a/ios/hexa_keeper.xcodeproj/project.pbxproj +++ b/ios/hexa_keeper.xcodeproj/project.pbxproj @@ -748,7 +748,7 @@ CODE_SIGN_ENTITLEMENTS = hexa_keeper/hexa_keeper.entitlements; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 614; + CURRENT_PROJECT_VERSION = 615; DEVELOPMENT_TEAM = Y5TCB759QL; ENABLE_BITCODE = NO; HEADER_SEARCH_PATHS = ( @@ -849,7 +849,7 @@ "$(inherited)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.14; + MARKETING_VERSION = 2.5.15; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -876,7 +876,7 @@ CODE_SIGN_IDENTITY = "Apple Development"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 614; + CURRENT_PROJECT_VERSION = 615; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; HEADER_SEARCH_PATHS = ( @@ -977,7 +977,7 @@ "$(inherited)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.14; + MARKETING_VERSION = 2.5.15; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1147,7 +1147,7 @@ CODE_SIGN_IDENTITY = "Apple Development"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 614; + CURRENT_PROJECT_VERSION = 615; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; ENABLE_BITCODE = NO; @@ -1250,7 +1250,7 @@ "$(PROJECT_DIR)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.14; + MARKETING_VERSION = 2.5.15; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1278,7 +1278,7 @@ CODE_SIGN_ENTITLEMENTS = hexa_keeper_dev.entitlements; CODE_SIGN_IDENTITY = "Apple Distribution"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; - CURRENT_PROJECT_VERSION = 614; + CURRENT_PROJECT_VERSION = 615; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; HEADER_SEARCH_PATHS = ( @@ -1380,7 +1380,7 @@ "$(PROJECT_DIR)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.14; + MARKETING_VERSION = 2.5.15; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", diff --git a/ios/hexa_keeper/Info.plist b/ios/hexa_keeper/Info.plist index 9e1349847b..43c97bae1e 100644 --- a/ios/hexa_keeper/Info.plist +++ b/ios/hexa_keeper/Info.plist @@ -62,7 +62,7 @@ CFBundleVersion - 614 + $(CURRENT_PROJECT_VERSION) ITSAppUsesNonExemptEncryption LSApplicationQueriesSchemes diff --git a/ios/hexa_keeper_dev-Info.plist b/ios/hexa_keeper_dev-Info.plist index 794948f0ac..ae098530a3 100644 --- a/ios/hexa_keeper_dev-Info.plist +++ b/ios/hexa_keeper_dev-Info.plist @@ -36,7 +36,7 @@ CFBundleVersion - 614 + $(CURRENT_PROJECT_VERSION) ITSAppUsesNonExemptEncryption LSApplicationQueriesSchemes diff --git a/openspec/changes/fix-release-version-consistency/.openspec.yaml b/openspec/changes/fix-release-version-consistency/.openspec.yaml new file mode 100644 index 0000000000..abd7c5ae1c --- /dev/null +++ b/openspec/changes/fix-release-version-consistency/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-25 diff --git a/openspec/changes/fix-release-version-consistency/design.md b/openspec/changes/fix-release-version-consistency/design.md new file mode 100644 index 0000000000..f8df1e8d18 --- /dev/null +++ b/openspec/changes/fix-release-version-consistency/design.md @@ -0,0 +1,46 @@ +## Context + +T-050 is the selected development item. The user authorized public App Store, Play production and normal APK publication after testing. Google Play API inspection on 2026-09-25 confirmed production package `io.hexawallet.bitcoinkeeper` is `621 (2.3.15)`, with highest returned bundle code 621. Authenticated App Store Connect inspection confirmed 2.5.14/build 612 on September 25, 2026. Local source has package.json 2.5.13, Android 2.5.14/616, iOS 2.5.14/614. Do not mistake the old `io.hexawallet.keeper` Play app for production. + +## Goals / Non-Goals + +**Goals:** One explicit marketing version, independently verified monotonically increasing platform build numbers, and a reproducible manifest of the exact released source/artifacts. Catch the observed 2.5.14 -> 2.3.15 regression before upload. + +**Non-Goals:** No new screen, copy, assets, navigation, React components, wallet behavior, signing implementation, Redux slice/saga, Realm schema, MMKV key or persisted-state migration. No PSBT or hardware interaction. No timestamp fix. Preserve the user's existing IAP fix. + +## Decisions + +- Add `release/version.json` as explicit version intent and `scripts/release-version.cjs` for check/apply commands. Use Node's standard library so preflight does not depend on mobile native build tools. +- Keep native values explicit in Gradle and Xcode for compatibility with existing build tools. An apply command synchronizes them; a check command verifies every Keeper target configuration and package.json. Fail on missing/ambiguous targets rather than silently skipping a platform. +- Store baselines separately from candidate values. Version intent can be drafted while store access is unavailable, but publication preflight must reject an unverified baseline. Numeric build values are not chosen until the relevant store is checked. +- Source preflight verifies semver progression, platform counters and matching source declarations. An artifact verifier separately checks metadata extracted from APK/AAB/IPA. Source checks alone do not prove artifacts were built correctly. +- Packaged feature checks use stable Ask Keeper / Dust route and data markers verified against fresh optimized Hermes bundles. These supplement UI tests. Reject a missing current-build IPA path instead of falling back to an older output. Verify both Android artifacts before the first upload. +- Production Android signing credentials come from the environment and the existing keystore. Remove the committed Gradle credential properties, preserving debug signing. This prevents bringing the newer sprint credential strings into the prepared integration; it does not erase repository history or resolve key-custody review. +- Build both Android outputs from one source/configuration and the same versionCode. Sign with the existing appropriate identities and compare fingerprints to the established release identities; never generate replacement release keys. +- Remove independent Fastlane bump operations for production; use explicit preflight instead. Production lanes must not post Slack messages as a side effect of this task. New public distribution steps require verified source provenance and correct environment configuration. +- Keep draft planning possible with unverified baselines, but make final release checks fail closed. Use the highest verified marketing baseline across platforms (at least 2.5.14), so the Android regression is not treated as the new semantic baseline. +- Supply the reconciled source SHA through `KEEPER_RELEASE_COMMIT`; preflight compares it to HEAD and requires a clean checkout. Keeping the SHA outside the committed manifest avoids a self-referential commit hash. + +## Affected files + +New: `release/version.json`, `scripts/release-version.cjs`, `scripts/release-version.test.cjs`, release documentation and verification evidence. Modified: `package.json`, `android/app/build.gradle`, `ios/hexa_keeper.xcodeproj/project.pbxproj`, `android/fastlane/Fastfile`, `ios/fastlane/Fastfile`, and CI validation workflow as needed. No UI files. Both iOS Info.plist files must use project version variables: a real simulator rebuild demonstrated that hardcoded CFBundleVersion silently overrode the otherwise consistent project settings. + +## Risks / Trade-offs + +- Missing Apple uploaded-build evidence -> keep iOS release blocked and do not invent the next build number. +- Native metadata drift -> check every app target and extracted artifact, not only a root version string. +- Existing Fastlane lanes overwrite `.env` and increment builds -> provide a checked release route before invoking publication; do not invoke legacy lanes blindly. +- Store state changes after checking -> refresh baselines immediately before upload. +- Different branch content -> record the canonical release SHA and verify all three artifacts against it. Resolve release-source reconciliation before publishing. + +## Validation and rollout + +Regression tests must fail on the actual 2.3.15 regression, mismatched package/native versions, missing metadata, reused build codes, and unverified store evidence, and pass a consistent fixture. Run existing startup/settings smoke tests with explicit development app IDs on Android and iOS. User checks: launch/unlock, existing wallet visibility without migration loss, displayed version/build, and upgrade installation for existing production identities. Full wallet/signing testing is outside the version change, but relevant release regressions still gate publication. + +DESIGN.md reviewed: no UI change, so existing typography, colors, components and navigation are preserved. No new screenshots/assets/SVGs or design tokens are needed. + +## Open Questions + +- Candidate selected: 2.5.15, Android 622, iOS 615. Refresh store baselines before upload. +- Canonical release source after reconciling iOS and Android published-build provenance. +- Public APK channel is GitHub Releases with SHA256SUM.asc and KEEPER_DETACHED_SIGN.sign. Existing local keystore certificate matches public APK 2.5.13; PGP signing access remains to be resolved. diff --git a/openspec/changes/fix-release-version-consistency/proposal.md b/openspec/changes/fix-release-version-consistency/proposal.md new file mode 100644 index 0000000000..2cb26b3f55 --- /dev/null +++ b/openspec/changes/fix-release-version-consistency/proposal.md @@ -0,0 +1,33 @@ +## Why + +Tracked task T-050 records a release-version regression: commit `1adf4f66399a2bfac4572d9da94440323bff02f2` changes Android versionName from `2.5.14` to `2.3.15` while increasing versionCode from 616 to 621. The local package version also differs from native version metadata. Release preparation must reconcile actual store uploads and built artifacts so this cannot silently recur. + +## What Changes + +- Establish an explicit release-version manifest and a dependency-free preflight validator for package.json, Android and all Keeper iOS target configurations. +- Record verified published/uploaded baselines, source commit, intended marketing version and platform build numbers before selecting final release values. +- Fail release validation when platform versions differ, the marketing version goes backwards, or a build number is reused against the verified baseline. +- Verify the actual IPA, Android App Bundle and public APK metadata, signing identity and source provenance before publication. +- Prevent Fastlane from independently changing build numbers after validation; preserve existing distribution destinations until explicitly selected. + +## Capabilities + +### New Capabilities + +- `release-version-consistency`: Reconciled source versions and verified release artifact metadata across iOS, Play and APK distribution. + +### Modified Capabilities + +None. + +## Impact + +T-050 under T-053 is the selected first development task. This affects release tooling and version metadata on iOS and Android, with identical marketing version for Mainnet and Testnet builds of the release. No changes to Wallet, Vault, Signer or UTXO behavior, subscription tiers, hardware compatibility, PSBTs, wallet storage, or product UI copy. No new network calls in the app. Release tooling uses authorized store access without embedding credentials in source or logs. Maestro impact: run startup and existing settings smoke checks; no new UI flow is introduced. + +## Non-goals + +Fixing Version History timestamps, unrelated feature development, changing production backend code, rotating signing keys, migrating wallets, or pretending a public listing proves the highest uploaded store build. Local-backend setup remains separate environment work. + +## First milestone scope — 25 September 2026 + +The user requests a small test release with high confidence and explicitly separates security remediation. T-040/T-044 completion and private-advisory sign-in are not prerequisites for this milestone. Make no security-fix claims. The versioning patch introduces no wallet/transaction/storage feature changes. Local Docker packaging and broader feature development remain separate work. Determine regression coverage from the actual selected release source; do not call an unverified sprint-to-production delta version-only. The user reconfirmed public App Store, Play production and the normal public APK channel. diff --git a/openspec/changes/fix-release-version-consistency/specs/release-version-consistency/spec.md b/openspec/changes/fix-release-version-consistency/specs/release-version-consistency/spec.md new file mode 100644 index 0000000000..05498238e0 --- /dev/null +++ b/openspec/changes/fix-release-version-consistency/specs/release-version-consistency/spec.md @@ -0,0 +1,76 @@ +## ADDED Requirements + +### Requirement: Consistent release metadata +The release tooling SHALL require a single marketing version in package.json, Android versionName and every Keeper iOS MARKETING_VERSION. Android versionCode SHALL match the explicit Android release counter and every Keeper iOS CURRENT_PROJECT_VERSION SHALL match the explicit iOS release counter. + +#### Scenario: Matching source metadata +- **GIVEN** verified release intent and matching source versions +- **WHEN** the source preflight runs +- **THEN** it succeeds and prints only non-secret version information. + +#### Scenario: Platform metadata differs +- **GIVEN** one native target or package.json has a different version +- **WHEN** preflight runs +- **THEN** it fails and identifies the mismatched file/field before any build upload. + +### Requirement: Prevent backwards versions and reused builds +The release tooling MUST compare semantic version components numerically and require the new marketing version to exceed the highest verified published marketing baseline. It MUST require platform build counters to exceed the highest verified already-uploaded counter for that platform. Missing or unverified store baselines MUST block publication checks. + +#### Scenario: Observed Android regression +- **GIVEN** a previously released marketing version of 2.5.14 +- **WHEN** a candidate has version 2.3.15 and Android code 621 +- **THEN** the marketing-version check fails even if its numeric Android code increased. + +#### Scenario: Reused Android code +- **GIVEN** the highest verified uploaded Android code is 621 +- **WHEN** the candidate also uses 621 +- **THEN** preflight fails regardless of marketing version. + +#### Scenario: Apple access unavailable +- **GIVEN** the public App Store version is known but uploaded-build evidence is unverified +- **WHEN** publication preflight runs +- **THEN** it fails with an actionable evidence error and does not invent a build number. + +### Requirement: Verify distribution artifacts +The release process MUST verify the packaged IPA version/build and bundle identifier, the AAB/APK versionName/versionCode and production package identifier, and their expected signing identities. The AAB and APK MUST originate from the same release source and carry matching Android version metadata. Source-only checks MUST NOT count as artifact verification. + +#### Scenario: Wrong Android package +- **GIVEN** a build uses `io.hexawallet.keeper` or `.development` instead of `io.hexawallet.bitcoinkeeper` +- **WHEN** production artifact validation runs +- **THEN** it fails before upload. + +#### Scenario: Correct three-platform artifacts +- **GIVEN** the IPA, AAB and APK match the release manifest and verified source/signing identities +- **WHEN** release verification completes +- **THEN** their checksums, versions, build numbers and canonical source SHA are recorded before publication. + +#### Scenario: Stale packaged content despite correct source metadata +- **GIVEN** source declarations match but the packaged binary has an older native counter or lacks required Ask Keeper / Dust markers +- **WHEN** production artifact validation runs +- **THEN** it fails before upload; marker checks use stable route/data strings that survive release compilation. + +#### Scenario: Current iOS build did not return an artifact +- **GIVEN** an earlier IPA remains in the output directory and the current build returns no IPA path +- **WHEN** upload is prepared +- **THEN** the lane fails rather than selecting the older file. + +### Requirement: Preserve app behavior +The change SHALL preserve Wallet, Vault, Signer and UTXO behavior, app storage and existing navigation. It SHALL require startup/settings smoke checks for both native platforms and record actual test outcomes rather than assuming a successful build implies a working app. + +#### Scenario: Development smoke test +- **GIVEN** a development build installed on the intended simulator/emulator +- **WHEN** it launches and the tester navigates to Version History +- **THEN** startup succeeds and the visible installed version/build matches that installed artifact. + +### Requirement: Reconciled feature coverage across platforms +The release candidate SHALL include Ask Keeper and the intended Dust Protection changes together. Both native platforms MUST be built from the same reviewed source commit and checked for the intended feature entry points and behavior. Matching version numbers or a conflict-free Git merge MUST NOT be treated as proof of feature coverage. Historical release-source claims MUST distinguish verified provenance from hypotheses. + +#### Scenario: Reported iOS and Android feature mismatch +- **GIVEN** the prior report of Ask Keeper on Android and Dust with old Concierge on iOS +- **WHEN** the next release candidate is verified +- **THEN** Ask Keeper and Dust Protection, Dust Report and Donate Dust are checked on both platforms and their test results are tied to the common source SHA. + +#### Scenario: Branches merge without textual conflicts +- **GIVEN** a merge preview succeeds without conflicts +- **WHEN** release reconciliation is assessed +- **THEN** feature regression tests and build provenance checks are still required before declaring reconciliation complete. diff --git a/openspec/changes/fix-release-version-consistency/tasks.md b/openspec/changes/fix-release-version-consistency/tasks.md new file mode 100644 index 0000000000..bd3e768fad --- /dev/null +++ b/openspec/changes/fix-release-version-consistency/tasks.md @@ -0,0 +1,35 @@ +> Milestone clarification (25 September 2026): security remediation and Docker contributor packaging are separate from the small test release. Broader Ask/Dust investigation below remains tracked; it does not add feature development to the versioning patch. Apply feature regression gates to actual app-code differences from the chosen release baseline. The user reconfirmed all three public destinations; publication tasks below remain required. + +## 1. Release-source investigation + +- [x] 1.1 Confirm T-050 and inspect the original version-regression commit. +- [x] 1.2 Read the production Play package's tracks and uploaded version codes without publishing changes. +- [ ] 1.3 Verify App Store Connect uploaded-build baseline and reconcile canonical release source. + +- [x] 1.4 Recover the prior Ask Keeper / Dust platform-mismatch context and compare current remote branch tips without modifying any branch. +- [ ] 1.5 Establish the historical build provenance where evidence exists; label the suspected stale Dust iOS source as unconfirmed until artifact/build records support it. +- [ ] 1.6 Prepare one reviewed integration source containing Ask Keeper, Dust Protection and intended fixes; document actual conflicts and preserve unrelated stashes/worktrees. + +## 2. Release metadata and tooling + +- [x] 2.1 Add an explicit manifest and source-version check/apply commands. +- [x] 2.2 Add regression tests for backwards marketing versions, reused builds, metadata drift and missing store evidence. +- [x] 2.3 Add production preflight to Fastlane and remove independent production build-number increments. +- [x] 2.4 Apply final verified version/build numbers consistently across package.json, Android and all Keeper iOS targets. +- [x] 2.5 Reject stale/wrong packaged metadata and missing feature markers before upload; verify APK signing identity and remove the iOS stale-IPA fallback. Validate markers against fresh optimized bundles for both platforms. + +## 3. Native tests and artifacts + +- [x] 3.1 Run automated release-tool tests and OpenSpec validation. +- [x] 3.2 Build and test local development apps on Android and iOS; record startup/settings smoke results. +- [ ] 3.3 Build the production IPA, AAB and APK from reconciled source; verify metadata, signing identities, configuration and checksums. +- [ ] 3.4 Provide and record the user's upgrade and basic app regression test checklist. + +- [ ] 3.5 Verify Ask Keeper entry and Dust Protection/Report/Donate Dust on both platforms from the same candidate source; include dust coin-selection regression tests. UI-only checks do not prove backend AI responses or transaction signing. + +## 4. Publication + +- [ ] 4.1 Refresh store baselines and publish the verified iOS build through App Store review. +- [ ] 4.2 Publish the verified Android bundle to Play production. +- [ ] 4.3 Publish the verified APK through the established public release channel with source tag/checksums/signature as required. +- [ ] 4.4 Record actual submission/publication status separately for all three channels and archive only when all tasks are complete. diff --git a/openspec/config.yaml b/openspec/config.yaml index 9ddaec95ff..86bf7c7fed 100644 --- a/openspec/config.yaml +++ b/openspec/config.yaml @@ -93,7 +93,7 @@ rules: - Confirm the agent implementation checklist in DESIGN.md before finalizing UI design - For UI/user-journey changes, specify affected Maestro flow files under flows/ and whether selectors/assertions need updates tasks: - - Group tasks by layer: UI Components, Business Logic / Hooks, Store (Slice + Saga), Storage, Tests, E2E Flows (Maestro) + - "Group tasks by layer: UI Components, Business Logic / Hooks, Store (Slice + Saga), Storage, Tests, E2E Flows (Maestro)" - Keep each task completable in a single focused session - Add a task for updating the Redux Persist migration version if store shape changes - Add a task for unit/integration tests covering the new behaviour diff --git a/package.json b/package.json index 307289bc12..28f4341087 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,17 @@ { "name": "hexa_keeper", - "version": "2.5.13", + "version": "2.5.15", "private": true, "scripts": { "ios": "npx react-native run-ios --scheme=hexa_keeper_dev --simulator 'iPhone 16' ", "iosProd": "npx react-native run-ios --scheme=hexa_keeper --simulator 'iPhone 16' ", "start": "react-native start", "test": "jest", + "test:release": "node --test scripts/release-version.test.cjs && python3 -B -m unittest discover -s scripts -p 'test_release_artifact.py'", + "version:inspect": "node scripts/release-version.cjs inspect", + "version:check": "node scripts/release-version.cjs check", + "version:apply": "node scripts/release-version.cjs apply", + "release:preflight": "node scripts/release-version.cjs release-check", "lint": "eslint . --ext .js,.jsx,.ts,.tsx", "lint:fix": "npm run lint -- --fix", "prepare": "husky install && chmod +x setup.sh && sh ./setup.sh", diff --git a/release/README.md b/release/README.md new file mode 100644 index 0000000000..215fdfb721 --- /dev/null +++ b/release/README.md @@ -0,0 +1,40 @@ +# Release version verification + +**Current milestone:** a small test release of the version-consistency change. Per the user’s 25 September direction, security remediation is separate and private-advisory sign-in is not a prerequisite. No security fixes are claimed. Docker contributor packaging is separate from the release patch. The user reconfirmed all three public destinations: App Store, Play production and the normal public APK channel. + +T-050 addresses the Android regression from marketing version 2.5.14 to 2.3.15 despite an increased build code. Marketing versions and platform build counters must both move forward. + +`version.json` selects candidate 2.5.15, Android 622 and iOS 615 using authenticated store observations from September 25, 2026. The iOS counter also exceeds local source build 614. This is not publication approval or proof of tested binaries. Do not substitute the public App Store listing for uploaded-build history. + +1. Read all uploaded builds and release tracks for Android package `io.hexawallet.bitcoinkeeper`, and uploaded iOS builds for `io.hexawallet.keeper`. Preserve the timestamp and evidence outside the repository. Refresh before upload; preflight accepts evidence at most 24 hours old. +2. Update the manifest with the highest known marketing version and highest uploaded build per platform. Select one greater marketing version for both stores and greater platform build counters. Check unpublished App Store version records as well. +3. Run `npm run version:apply` to synchronize package.json, Android versionName/versionCode and both Keeper iOS targets. Both Info.plist files must reference `$(CURRENT_PROJECT_VERSION)` and `$(MARKETING_VERSION)`; hardcoded values are rejected. Review the diff, then run `npm run version:check` and `npm run test:release`. +4. Reconcile release source with the published versions, prepare a clean release checkout and set `KEEPER_RELEASE_COMMIT` to its complete verified commit SHA. Run `npm run release:preflight`. The manifest cannot contain its own commit SHA. +5. Build from a reviewed production configuration and existing signing identities. Check extracted IPA, APK and AAB metadata against the manifest, verify signing fingerprints and record checksums. A source preflight does not verify the resulting binaries. +6. Test the signed builds, including upgrades, before public submission. + +Both existing Fastlane `live` lanes run preflight before building and consume `.env.production` without downloading over `.env`. They no longer increment production build numbers. Android notifications require explicit `KEEPER_NOTIFY_SLACK=1`. + +These existing lanes still upload to **TestFlight** and **Play internal testing** respectively. Neither constitutes the requested public release. Public submission must record App Store review/submission state, Play production state and GitHub APK publication separately. + +## Packaged artifact checks + +Run `python3 scripts/verify-release-artifact.py /absolute/path/to/build.ipa` (or `.apk` / `.aab`). The production lanes run this before uploading. Android builds both artifacts and verifies them before its first upload. The iOS lane requires the current build's IPA path and never falls back to an older file in the builds directory. + +The verifier checks the production application ID, marketing version, native counter, and bundled Ask Keeper / Dust route and data markers, then emits artifact and bundle SHA-256 hashes. Marker presence supplements device testing; it does not prove behavior or source provenance. Compiler-generated component names are unsuitable markers because release optimization removes them. + +For Android, set `AAPT` and `APKSIGNER` to SDK build-tool paths (or put them on PATH), `BUNDLETOOL_JAR` to an installed bundletool jar, and `KEEPER_ANDROID_CERT_SHA256` to the certificate fingerprint independently verified from the established public APK. The verifier checks the APK signature and certificate. IPA code signing/provisioning and AAB signing still require separate verification before distribution. The seven packaged-artifact regression tests run with `npm run test:release` alongside the source-version tests; Python 3 is required. + +The normal public APK channel is the repository's GitHub Releases. Publish the APK together with `SHA256SUM.asc` and `KEEPER_DETACHED_SIGN.sign` using the established PGP identity, as documented in the root README. Do not replace release signing keys to work around missing access. + +Android production signing reads `STORE_PASSWORD`, `KEY_PASSWORD`, and `KEY_ALIAS` from the build environment. `KEEPER_ANDROID_KEYSTORE` may select an absolute existing keystore path; otherwise the existing ignored `android/app/release.keystore` is used. Repository Gradle properties no longer contain release credentials. The development debug build continues to use its development keystore. + +## Manual release checks + +- Upgrade an existing installation with a designated test wallet on a physical iPhone and Android device; do not uninstall first. Confirm unlock, wallet visibility and settings survive. +- Check the displayed marketing version and native build counter against the release manifest on both platforms. +- Open Ask Keeper on both platforms and send a non-sensitive sample question to the intended backend. Confirm the response and error/retry behavior; local isolated-backend entry checks do not test AI responses. +- Open Wallet Settings > Dust Report. Check an empty test wallet, then a designated testnet fixture with Do Not Spend coins. Confirm the report, ordinary-spend exclusion, and Donate Dust confirmation/amount/fee behavior. Record separately whether a testnet signing transaction completed; an empty-wallet result cannot verify donation. +- Exercise wallet navigation, receive and a test transaction/signing flow with designated test funds and hardware where applicable. Verify that production build configuration is correct; do not send real funds merely to test this versioning change. +- Install the public APK as an upgrade over the previous public APK and verify its signature/checksum. The APK and AAB must carry the same Android version and code. +- Record each channel's actual submission/publication state and public download links. Do not report a TestFlight/internal upload as a public release. diff --git a/release/version.json b/release/version.json new file mode 100644 index 0000000000..626a58552f --- /dev/null +++ b/release/version.json @@ -0,0 +1,21 @@ +{ + "version": "2.5.15", + "androidVersionCode": 622, + "iosBuildNumber": 615, + "baselines": { + "android": { + "applicationId": "io.hexawallet.bitcoinkeeper", + "verifiedAt": "2026-09-25T13:10:54Z", + "highestUploadedBuild": 621, + "highestMarketingVersion": "2.5.14", + "productionRelease": "621 (2.3.15)" + }, + "ios": { + "applicationId": "io.hexawallet.keeper", + "verifiedAt": "2026-09-25T13:44:11Z", + "highestUploadedBuild": 612, + "highestMarketingVersion": "2.5.14", + "productionRelease": "612 (2.5.14)" + } + } +} diff --git a/scripts/release-version.cjs b/scripts/release-version.cjs new file mode 100644 index 0000000000..c1ba39d0b6 --- /dev/null +++ b/scripts/release-version.cjs @@ -0,0 +1,168 @@ +#!/usr/bin/env node +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync } = require('node:child_process'); + +const appIds = { android: 'io.hexawallet.bitcoinkeeper', ios: 'io.hexawallet.keeper' }; +const iosIds = new Set([appIds.ios, 'io.hexawallet.hexakeeper.dev']); + +function versionParts(version) { + if (typeof version !== 'string' || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(version)) { + throw new Error(`Invalid marketing version: ${String(version)}`); + } + const parts = version.split('.').map(Number); + if (!parts.every(Number.isSafeInteger)) throw new Error('Marketing version exceeds safe integer range'); + return parts; +} + +function compareVersions(a, b) { + const left = versionParts(a); + const right = versionParts(b); + for (let i = 0; i < 3; i += 1) { + if (left[i] !== right[i]) return left[i] > right[i] ? 1 : -1; + } + return 0; +} + +function validateIntent(manifest, { requireEvidence = true, now = Date.now() } = {}) { + const errors = []; + try { versionParts(manifest.version); } catch (e) { errors.push(e.message); } + for (const [platform, field] of [['android', 'androidVersionCode'], ['ios', 'iosBuildNumber']]) { + const value = manifest[field]; + if (!Number.isSafeInteger(value) || value <= 0 || value > 2100000000) { + errors.push(`${field} must be an explicit positive integer`); + } + const baseline = manifest.baselines?.[platform]; + if (!baseline || baseline.applicationId !== appIds[platform]) { + errors.push(`${platform}: missing baseline or wrong production application ID`); + continue; + } + try { + if (compareVersions(manifest.version, baseline.highestMarketingVersion) <= 0) { + errors.push(`${platform}: marketing version must exceed ${baseline.highestMarketingVersion}`); + } + } catch (e) { errors.push(`${platform}: ${e.message}`); } + if (!Number.isSafeInteger(baseline.highestUploadedBuild) || baseline.highestUploadedBuild < 0) { + errors.push(`${platform}: highest uploaded build has not been verified`); + } else if (Number.isSafeInteger(value) && value <= baseline.highestUploadedBuild) { + errors.push(`${platform}: build ${value} must exceed uploaded build ${baseline.highestUploadedBuild}`); + } + if (requireEvidence) { + const verified = Date.parse(baseline.verifiedAt); + if (!Number.isFinite(verified) || verified > now || now - verified > 24 * 60 * 60 * 1000) { + errors.push(`${platform}: refresh authenticated store baseline (must be within 24 hours)`); + } + } + } + return errors; +} + +function iosConfigurations(text) { + const blocks = [...text.matchAll(/^\t\t[A-F0-9]{24} \/\*.*?\*\/ = \{\n([\s\S]*?)^\t\t\};/gm)]; + return blocks.filter((m) => m[1].includes('isa = XCBuildConfiguration;')).map((m) => { + const value = (name) => m[1].match(new RegExp(`\\b${name} = ([^;]+);`))?.[1]?.replace(/^"|"$/g, ''); + return { block: m[0], id: value('PRODUCT_BUNDLE_IDENTIFIER'), version: value('MARKETING_VERSION'), build: value('CURRENT_PROJECT_VERSION') }; + }).filter((config) => iosIds.has(config.id)); +} + +function readSources(root) { + return { + packageText: fs.readFileSync(path.join(root, 'package.json'), 'utf8'), + android: fs.readFileSync(path.join(root, 'android/app/build.gradle'), 'utf8'), + ios: fs.readFileSync(path.join(root, 'ios/hexa_keeper.xcodeproj/project.pbxproj'), 'utf8'), + iosPlists: ['ios/hexa_keeper/Info.plist', 'ios/hexa_keeper_dev-Info.plist'].map((file) => fs.readFileSync(path.join(root, file), 'utf8')), + }; +} + +function validateSources(manifest, sources) { + const errors = []; + if (JSON.parse(sources.packageText).version !== manifest.version) errors.push('package.json version differs from manifest'); + const names = [...sources.android.matchAll(/^\s*versionName\s+"([^"]+)"/gm)]; + const codes = [...sources.android.matchAll(/^\s*versionCode\s+(\d+)/gm)]; + if (names.length !== 1 || names[0][1] !== manifest.version) errors.push('Android versionName missing, ambiguous or different from manifest'); + if (codes.length !== 1 || Number(codes[0][1]) !== manifest.androidVersionCode) errors.push('Android versionCode missing, ambiguous or different from manifest'); + if (!Array.isArray(sources.iosPlists) || sources.iosPlists.length !== 2) { + errors.push('Expected both Keeper Info.plist files'); + } else { + for (const plist of sources.iosPlists) { + for (const [key, expected] of [['CFBundleVersion', '$(CURRENT_PROJECT_VERSION)'], ['CFBundleShortVersionString', '$(MARKETING_VERSION)']]) { + const matches = [...plist.matchAll(new RegExp(`${key}\\s*([^<]*)`, 'g'))]; + if (matches.length !== 1 || matches[0][1] !== expected) errors.push(`iOS Info.plist ${key} must reference ${expected}`); + } + } + } + const configs = iosConfigurations(sources.ios); + for (const id of iosIds) { + if (configs.filter((c) => c.id === id).length !== 2) errors.push(`Expected Debug and Release configurations for ${id}`); + } + for (const c of configs) { + if (c.version !== manifest.version || c.build !== String(manifest.iosBuildNumber)) errors.push(`iOS ${c.id} version/build differs from manifest`); + } + return errors; +} + +function applyVersions(manifest, sources) { + // Validate structure before writing anything. Existing version differences are + // expected here; missing/ambiguous fields must never be silently ignored. + const configs = iosConfigurations(sources.ios); + if ([...sources.android.matchAll(/^\s*versionName\s+"([^"]+)"/gm)].length !== 1 || + [...sources.android.matchAll(/^\s*versionCode\s+(\d+)/gm)].length !== 1 || + [...iosIds].some((id) => configs.filter((c) => c.id === id).length !== 2)) throw new Error('Unexpected native version structure; no files written'); + const pkg = JSON.parse(sources.packageText); + pkg.version = manifest.version; + const android = sources.android.replace(/(^\s*versionName\s+)"[^"]+"/m, (_match, prefix) => `${prefix}"${manifest.version}"`) + .replace(/(^\s*versionCode\s+)\d+/m, (_match, prefix) => `${prefix}${manifest.androidVersionCode}`); + let ios = sources.ios; + for (const c of iosConfigurations(ios)) { + if (!c.version || !c.build) throw new Error('Missing iOS version fields; no files written'); + const block = c.block.replace(/\bMARKETING_VERSION = [^;]+;/, `MARKETING_VERSION = ${manifest.version};`) + .replace(/\bCURRENT_PROJECT_VERSION = [^;]+;/, `CURRENT_PROJECT_VERSION = ${manifest.iosBuildNumber};`); + ios = ios.replace(c.block, block); + } + const result = { packageText: JSON.stringify(pkg, null, 2) + '\n', android, ios, iosPlists: sources.iosPlists }; + const errors = validateSources(manifest, result); + if (errors.length) throw new Error(errors.join('\n')); + return result; +} + +function main() { + const command = process.argv[2] || 'check'; + if (!['check', 'release-check', 'apply', 'inspect'].includes(command)) throw new Error('Usage: release-version.cjs check|release-check|apply|inspect'); + const root = path.resolve(__dirname, '..'); + const manifest = JSON.parse(fs.readFileSync(path.join(root, 'release/version.json'), 'utf8')); + const sources = readSources(root); + if (command === 'inspect') { + console.log(JSON.stringify({ manifest, packageVersion: JSON.parse(sources.packageText).version, + androidVersion: sources.android.match(/versionName\s+"([^"]+)"/)?.[1], + androidBuild: sources.android.match(/versionCode\s+(\d+)/)?.[1], + ios: iosConfigurations(sources.ios).map(({ id, version, build }) => ({ id, version, build })) }, null, 2)); + return; + } + const errors = validateIntent(manifest); + if (errors.length) throw new Error(errors.join('\n')); + if (command === 'apply') { + const updated = applyVersions(manifest, sources); + fs.writeFileSync(path.join(root, 'package.json'), updated.packageText); + fs.writeFileSync(path.join(root, 'android/app/build.gradle'), updated.android); + fs.writeFileSync(path.join(root, 'ios/hexa_keeper.xcodeproj/project.pbxproj'), updated.ios); + console.log(`Applied ${manifest.version}; Android ${manifest.androidVersionCode}; iOS ${manifest.iosBuildNumber}`); + return; + } + errors.push(...validateSources(manifest, sources)); + const head = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim(); + if (command === 'release-check') { + const expectedCommit = process.env.KEEPER_RELEASE_COMMIT; + if (!/^[a-f0-9]{40}$/.test(expectedCommit || '') || expectedCommit !== head) errors.push('KEEPER_RELEASE_COMMIT must identify the verified canonical HEAD'); + const dirty = execFileSync('git', ['status', '--porcelain', '--untracked-files=normal'], { cwd: root, encoding: 'utf8' }).trim(); + if (dirty) errors.push('Release checkout must be clean; preserve existing work and prepare an isolated release checkout'); + } + if (errors.length) throw new Error(errors.join('\n')); + console.log(`Release versions verified: ${manifest.version}; Android ${manifest.androidVersionCode}; iOS ${manifest.iosBuildNumber}; source ${head}`); +} + +module.exports = { versionParts, compareVersions, validateIntent, validateSources, applyVersions, iosConfigurations }; +if (require.main === module) { + try { main(); } catch (e) { console.error(`Release preflight failed:\n${e.message}`); process.exitCode = 1; } +} diff --git a/scripts/release-version.test.cjs b/scripts/release-version.test.cjs new file mode 100644 index 0000000000..ca3387c611 --- /dev/null +++ b/scripts/release-version.test.cjs @@ -0,0 +1,80 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { compareVersions, validateIntent, validateSources, applyVersions } = require('./release-version.cjs'); + +const now = Date.parse('2026-09-25T14:00:00Z'); +const intent = () => ({ + version: '2.5.15', androidVersionCode: 622, iosBuildNumber: 622, + baselines: { + android: { applicationId: 'io.hexawallet.bitcoinkeeper', verifiedAt: '2026-09-25T13:00:00Z', highestUploadedBuild: 621, highestMarketingVersion: '2.5.14' }, + ios: { applicationId: 'io.hexawallet.keeper', verifiedAt: '2026-09-25T13:00:00Z', highestUploadedBuild: 615, highestMarketingVersion: '2.5.14' }, + }, +}); +const fixtures = () => ({ + packageText: '{"name":"keeper","version":"2.5.15"}', + iosPlists: Array(2).fill('CFBundleVersion$(CURRENT_PROJECT_VERSION)CFBundleShortVersionString$(MARKETING_VERSION)'), + android: 'android {\n versionName "2.5.15"\n versionCode 622\n}\n', + ios: ['io.hexawallet.keeper', 'io.hexawallet.keeper', 'io.hexawallet.hexakeeper.dev', 'io.hexawallet.hexakeeper.dev'].map((id, i) => + `\t\t${String(i).padStart(24, 'A')} /* Build config */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = ${id};\n\t\t\t\tMARKETING_VERSION = 2.5.15;\n\t\t\t\tCURRENT_PROJECT_VERSION = 622;\n\t\t\t};\n\t\t};\n`).join(''), +}); + +test('consistent versions with authenticated fresh baselines pass', () => { + assert.deepEqual(validateIntent(intent(), { now }), []); + assert.deepEqual(validateSources(intent(), fixtures()), []); +}); +test('rejects the actual 2.5.14 -> 2.3.15 regression even with higher build code', () => { + const m = intent(); m.version = '2.3.15'; + assert.ok(validateIntent(m, { now }).some((e) => e.includes('marketing version must exceed 2.5.14'))); +}); +test('numeric version comparison handles multi-digit segments', () => { + assert.equal(compareVersions('2.10.0', '2.9.99'), 1); + assert.equal(compareVersions('2.5.15', '2.5.15'), 0); + assert.throws(() => compareVersions('2.05.15', '2.5.14')); +}); +test('rejects a reused Android build', () => { + const m = intent(); m.androidVersionCode = 621; + assert.ok(validateIntent(m, { now }).some((e) => e.includes('must exceed uploaded build 621'))); +}); +test('does not turn missing iOS evidence or a public listing into a verified baseline', () => { + const m = intent(); m.iosBuildNumber = null; m.baselines.ios.verifiedAt = null; m.baselines.ios.highestUploadedBuild = null; + assert.ok(validateIntent(m, { now }).some((e) => e.includes('highest uploaded build has not been verified'))); + assert.ok(validateIntent(m, { now }).some((e) => e.includes('refresh authenticated store baseline'))); +}); +test('rejects stale and future-dated evidence', () => { + for (const date of ['2026-09-20T00:00:00Z', '2026-09-26T00:00:00Z']) { + const m = intent(); m.baselines.android.verifiedAt = date; + assert.ok(validateIntent(m, { now }).some((e) => e.includes('refresh authenticated store baseline'))); + } +}); +test('rejects the similarly named non-production Play package', () => { + const m = intent(); m.baselines.android.applicationId = 'io.hexawallet.keeper'; + assert.ok(validateIntent(m, { now }).some((e) => e.includes('wrong production application ID'))); +}); +test('detects package drift and a single stale iOS configuration', () => { + const s = fixtures(); s.packageText = '{"version":"2.5.13"}'; s.ios = s.ios.replace('CURRENT_PROJECT_VERSION = 622;', 'CURRENT_PROJECT_VERSION = 614;'); + const errors = validateSources(intent(), s); + assert.ok(errors.some((e) => e.includes('package.json'))); + assert.ok(errors.some((e) => e.includes('iOS'))); +}); +test('apply synchronizes all version fields while preserving unrelated text', () => { + const s = fixtures(); s.android += '// Preserve existing signing configuration\n'; + const m = intent(); m.version = '2.5.16'; m.androidVersionCode = 623; m.iosBuildNumber = 624; + const updated = applyVersions(m, s); + assert.deepEqual(validateSources(m, updated), []); + assert.ok(updated.android.includes('// Preserve existing signing configuration')); + assert.equal(JSON.parse(updated.packageText).name, 'keeper'); + assert.ok(s.android.includes('versionCode 622')); +}); +test('apply refuses ambiguous Android values and missing iOS targets', () => { + const s = fixtures(); s.android += '\nversionCode 999\n'; + assert.throws(() => applyVersions(intent(), s), /Unexpected native version structure/); + const incomplete = fixtures(); incomplete.ios = ''; + assert.throws(() => applyVersions(intent(), incomplete), /Unexpected native version structure/); +}); + +test('rejects hardcoded plist build numbers even when Xcode project versions agree', () => { + const s = fixtures(); + s.iosPlists[0] = s.iosPlists[0].replace('$(CURRENT_PROJECT_VERSION)', '614'); + assert.ok(validateSources(intent(), s).some((e) => e.includes('CFBundleVersion'))); + assert.throws(() => applyVersions(intent(), s), /CFBundleVersion/); +}); diff --git a/scripts/test_release_artifact.py b/scripts/test_release_artifact.py new file mode 100644 index 0000000000..d105e52dff --- /dev/null +++ b/scripts/test_release_artifact.py @@ -0,0 +1,86 @@ +"""Packaged-build regression tests; no store access or signing keys required.""" +import hashlib +import importlib.util +import os +from pathlib import Path +import plistlib +import tempfile +import unittest +from unittest.mock import patch +import zipfile + +spec = importlib.util.spec_from_file_location("artifact", Path(__file__).with_name("verify-release-artifact.py")) +artifact = importlib.util.module_from_spec(spec) +spec.loader.exec_module(artifact) +MANIFEST = {"version": "2.5.15", "iosBuildNumber": 615, "androidVersionCode": 622} +FEATURES = b"HelpAiEntry\0DustReport\0doNotSpend" + + +class PackagedBuildTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + + def ipa(self, *, app_id="io.hexawallet.keeper", version="2.5.15", build="615", bundle=FEATURES): + path = Path(self.directory.name) / "Keeper.ipa" + with zipfile.ZipFile(path, "w") as archive: + archive.writestr("Payload/Keeper.app/Info.plist", plistlib.dumps({ + "CFBundleIdentifier": app_id, "CFBundleShortVersionString": version, + "CFBundleVersion": build, + }, fmt=plistlib.FMT_BINARY)) + archive.writestr("Payload/Keeper.app/main.jsbundle", bundle) + return path + + def test_candidate_metadata_and_hashes(self): + path = self.ipa() + result = artifact.inspect(path, MANIFEST) + self.assertEqual(result["sha256"], hashlib.sha256(path.read_bytes()).hexdigest()) + self.assertEqual(result["bundleSha256"], hashlib.sha256(FEATURES).hexdigest()) + self.assertEqual(result["signing"], "separate verification required") + + def test_stale_binary_rejected_even_if_source_manifest_is_correct(self): + for kwargs, message in [({"version": "2.5.14"}, "Marketing version"), + ({"build": "614"}, "Build counter"), + ({"app_id": "io.hexawallet.hexakeeper.dev"}, "Application identifier")]: + with self.subTest(kwargs=kwargs), self.assertRaisesRegex(ValueError, message): + artifact.inspect(self.ipa(**kwargs), MANIFEST) + + def test_missing_feature_rejected_despite_correct_versions(self): + with self.assertRaisesRegex(ValueError, "DustReport"): + artifact.inspect(self.ipa(bundle=b"HelpAiEntry\0doNotSpend"), MANIFEST) + + def test_utf16_feature_table(self): + artifact.verify_features(FEATURES.decode().encode("utf-16-le")) + + def test_missing_bundle_is_not_a_pass(self): + path = self.ipa() + with zipfile.ZipFile(path, "w") as archive: + archive.writestr("Payload/Keeper.app/Info.plist", plistlib.dumps({})) + with self.assertRaises(KeyError): + artifact.inspect(path, MANIFEST) + + def test_apk_must_match_independent_signing_identity(self): + path = Path(self.directory.name) / "Keeper.apk" + with zipfile.ZipFile(path, "w") as archive: + archive.writestr("assets/index.android.bundle", FEATURES) + metadata = "package: name='io.hexawallet.bitcoinkeeper' versionCode='622' versionName='2.5.15'" + for actual, should_pass in [("a" * 64, True), ("b" * 64, False)]: + with self.subTest(actual=actual), patch.dict(os.environ, {"KEEPER_ANDROID_CERT_SHA256": "a" * 64}), \ + patch.object(artifact, "output", side_effect=[metadata, "Signer #1 certificate SHA-256 digest: " + actual]): + if should_pass: + self.assertEqual(artifact.inspect(path, MANIFEST)["signing"], "APK certificate verified") + else: + with self.assertRaisesRegex(ValueError, "signing certificate"): + artifact.inspect(path, MANIFEST) + + def test_aab_reads_base_manifest_and_bundle(self): + path = Path(self.directory.name) / "Keeper.aab" + with zipfile.ZipFile(path, "w") as archive: + archive.writestr("base/assets/index.android.bundle", FEATURES) + xml = '' + with patch.dict(os.environ, {"BUNDLETOOL_JAR": str(path)}), patch.object(artifact, "output", return_value=xml): + self.assertEqual(artifact.inspect(path, MANIFEST)["build"], "622") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/verify-release-artifact.py b/scripts/verify-release-artifact.py new file mode 100644 index 0000000000..0de412db51 --- /dev/null +++ b/scripts/verify-release-artifact.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Inspect packaged release metadata and required feature markers without dumping secrets. + +APK: Android SDK aapt and apksigner are required. +AAB: BUNDLETOOL_JAR and Java are required. +IPA: Python standard library; signing is verified separately by codesign/export evidence. +This verifier supplements device tests; bytecode markers do not prove feature behavior. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import plistlib +import re +import subprocess +import sys +import zipfile +import xml.etree.ElementTree as ET + +ANDROID_NS = "{http://schemas.android.com/apk/res/android}" + + +def require_equal(actual, expected, label): + if str(actual) != str(expected): + raise ValueError(f"{label}: expected {expected}, got {actual}") + + +def verify_features(bundle): + missing = [] + # Route names and data properties survive Metro/Hermes optimization; + # implementation function names (e.g. DustReportScreen) do not. + for feature in ("HelpAiEntry", "DustReport", "doNotSpend"): + if feature.encode() not in bundle and feature.encode("utf-16-le") not in bundle: + missing.append(feature) + if missing: + raise ValueError("Required packaged feature markers absent: " + ", ".join(missing)) + + +def output(command): + result = subprocess.run(command, capture_output=True, text=True) + if result.returncode: + raise ValueError(f"{Path(command[0]).name} failed; inspect tool/environment configuration") + return result.stdout + + +def inspect(path, manifest): + suffix = path.suffix.lower() + with zipfile.ZipFile(path) as archive: + if suffix == ".ipa": + names = [n for n in archive.namelist() if re.fullmatch(r"Payload/[^/]+\.app/Info\.plist", n)] + if len(names) != 1: + raise ValueError("Expected one main app Info.plist") + info = plistlib.loads(archive.read(names[0])) + app_id, version, build = (info.get(k) for k in ("CFBundleIdentifier", "CFBundleShortVersionString", "CFBundleVersion")) + platform = "ios" + bundle = archive.read(names[0].rsplit("/", 1)[0] + "/main.jsbundle") + elif suffix == ".apk": + text = output([os.environ.get("AAPT", "aapt"), "dump", "badging", str(path)]) + match = re.search(r"package: name='([^']+)' versionCode='([^']+)' versionName='([^']+)'", text) + if not match: + raise ValueError("Cannot read APK package/version metadata") + app_id, build, version = match.groups() + platform = "android" + bundle = archive.read("assets/index.android.bundle") + elif suffix == ".aab": + jar = os.environ.get("BUNDLETOOL_JAR") + if not jar or not Path(jar).is_file(): + raise ValueError("Set BUNDLETOOL_JAR to the installed bundletool jar") + xml = output(["java", "-jar", jar, "dump", "manifest", "--bundle=" + str(path), "--module=base"]) + root = ET.fromstring(xml) + app_id, build, version = root.get("package"), root.get(ANDROID_NS + "versionCode"), root.get(ANDROID_NS + "versionName") + platform = "android" + bundle = archive.read("base/assets/index.android.bundle") + else: + raise ValueError("Expected an IPA, APK or AAB") + expected_id = {"ios": "io.hexawallet.keeper", "android": "io.hexawallet.bitcoinkeeper"}[platform] + require_equal(app_id, expected_id, "Application identifier") + require_equal(version, manifest["version"], "Marketing version") + require_equal(build, manifest["iosBuildNumber" if platform == "ios" else "androidVersionCode"], "Build counter") + verify_features(bundle) + result = {"artifact": path.name, "applicationId": app_id, "version": version, "build": str(build), + "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + "bundleSha256": hashlib.sha256(bundle).hexdigest(), "featureMarkers": "present", + "signing": "separate verification required"} + if suffix == ".apk": + certs = output([os.environ.get("APKSIGNER", "apksigner"), "verify", "--print-certs", str(path)]) + expected = os.environ.get("KEEPER_ANDROID_CERT_SHA256", "").lower().replace(":", "") + if not re.fullmatch(r"[0-9a-f]{64}", expected): + raise ValueError("Set KEEPER_ANDROID_CERT_SHA256 to the independently verified release certificate") + actual = re.findall(r"certificate SHA-256 digest: ([0-9a-fA-F]+)", certs) + if len(actual) != 1 or actual[0].lower() != expected: + raise ValueError("APK signing certificate differs from verified release identity") + result["signing"] = "APK certificate verified" + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("artifact", type=Path) + parser.add_argument("--manifest", type=Path, default=Path(__file__).resolve().parents[1] / "release/version.json") + args = parser.parse_args() + try: + print(json.dumps(inspect(args.artifact, json.loads(args.manifest.read_text())), indent=2)) + except (ValueError, OSError, KeyError, zipfile.BadZipFile, ET.ParseError) as exc: + print("Artifact verification failed: " + str(exc), file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 30d74df0260d2e86d2f22d0648da408f5a55fbfa Mon Sep 17 00:00:00 2001 From: Anant Date: Mon, 28 Sep 2026 18:23:24 +0530 Subject: [PATCH 02/19] fix: preserve Ask tab navigation for 2.5.16 candidate --- android/app/build.gradle | 4 +- flows/ask-history-navigation.yaml | 51 ++++++++++ flows/ask-tab-navigation.yaml | 46 +++++++++ ios/hexa_keeper.xcodeproj/project.pbxproj | 16 ++-- .../changes/fix-ask-tab-navigation/design.md | 38 ++++++++ .../fix-ask-tab-navigation/proposal.md | 28 ++++++ .../specs/home-navigation/spec.md | 36 +++++++ .../changes/fix-ask-tab-navigation/tasks.md | 25 +++++ .../fix-ask-tab-navigation/verification.md | 96 +++++++++++++++++++ package.json | 2 +- release/README.md | 6 +- release/version.json | 22 ++--- src/components/MenuFooter.tsx | 5 + src/screens/Home/HomeScreen.tsx | 7 +- 14 files changed, 354 insertions(+), 28 deletions(-) create mode 100644 flows/ask-history-navigation.yaml create mode 100644 flows/ask-tab-navigation.yaml create mode 100644 openspec/changes/fix-ask-tab-navigation/design.md create mode 100644 openspec/changes/fix-ask-tab-navigation/proposal.md create mode 100644 openspec/changes/fix-ask-tab-navigation/specs/home-navigation/spec.md create mode 100644 openspec/changes/fix-ask-tab-navigation/tasks.md create mode 100644 openspec/changes/fix-ask-tab-navigation/verification.md diff --git a/android/app/build.gradle b/android/app/build.gradle index a56f8d534d..90d90807c5 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -98,8 +98,8 @@ android { applicationId "io.hexawallet.keeper" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 622 - versionName "2.5.15" + versionCode 623 + versionName "2.5.16" missingDimensionStrategy 'react-native-camera', 'general' missingDimensionStrategy 'store', 'play' multiDexEnabled true diff --git a/flows/ask-history-navigation.yaml b/flows/ask-history-navigation.yaml new file mode 100644 index 0000000000..fd8731ee88 --- /dev/null +++ b/flows/ask-history-navigation.yaml @@ -0,0 +1,51 @@ +# Run on an unlocked disposable app with an existing Ask conversation. +appId: ${APP_ID} +--- +- repeat: + times: 3 + commands: + - tapOn: + id: home_tab_ask + - assertVisible: + id: chat_thread_0 + - tapOn: + id: chat_thread_0 + - tapOn: + id: btn_learn_more + - assertVisible: Before you use Ask Keeper + - tapOn: Got it + - tapOn: + id: btn_learn_more + - tapOn: Learn more about Ask Keeper.* + - assertVisible: About Ask Keeper + - tapOn: + id: btn_back + - tapOn: + id: input_message + - assertVisible: + id: btn_back + - tapOn: + id: btn_back + - assertVisible: + id: chat_thread_0 + - assertVisible: + id: home_tab_wallets + - assertVisible: + id: home_tab_keys + - assertVisible: + id: home_tab_ask + - assertVisible: + id: home_tab_more + - tapOn: + id: home_tab_more + - assertVisible: More Options + - assertNotVisible: + id: chat_thread_0 + - tapOn: + id: home_tab_wallets + - assertVisible: + id: wallet_item_.* +- tapOn: + id: home_tab_ask +- assertVisible: + id: chat_thread_0 diff --git a/flows/ask-tab-navigation.yaml b/flows/ask-tab-navigation.yaml new file mode 100644 index 0000000000..59700d5714 --- /dev/null +++ b/flows/ask-tab-navigation.yaml @@ -0,0 +1,46 @@ +# Run on an unlocked disposable app at Home with no Ask conversations. +# maestro test -e APP_ID=io.hexawallet.keeper flows/ask-tab-navigation.yaml +appId: ${APP_ID} +--- +- repeat: + times: 3 + commands: + - tapOn: + id: home_tab_ask + - assertVisible: "Something isn't working" + - tapOn: + id: home_tab_more + - assertVisible: More Options + - assertNotVisible: "Something isn't working" + - assertNotVisible: I have an idea for Keeper + - assertNotVisible: Never share seed words or private keys. + - assertVisible: + id: home_tab_wallets + - assertVisible: + id: home_tab_keys + - assertVisible: + id: home_tab_ask + - assertVisible: + id: home_tab_more + - tapOn: + id: home_tab_ask + - assertVisible: "Something isn't working" + - tapOn: + id: home_tab_wallets + - assertVisible: + id: wallet_item_.* + - assertNotVisible: "Something isn't working" + - tapOn: + id: home_tab_ask + - assertVisible: "Something isn't working" + - tapOn: + id: home_tab_keys + - assertNotVisible: "Something isn't working" + - assertVisible: + id: home_tab_wallets + - assertVisible: + id: home_tab_keys + - assertVisible: + id: home_tab_ask + - assertVisible: + id: home_tab_more diff --git a/ios/hexa_keeper.xcodeproj/project.pbxproj b/ios/hexa_keeper.xcodeproj/project.pbxproj index cc49992030..c77033da6c 100644 --- a/ios/hexa_keeper.xcodeproj/project.pbxproj +++ b/ios/hexa_keeper.xcodeproj/project.pbxproj @@ -748,7 +748,7 @@ CODE_SIGN_ENTITLEMENTS = hexa_keeper/hexa_keeper.entitlements; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 615; + CURRENT_PROJECT_VERSION = 616; DEVELOPMENT_TEAM = Y5TCB759QL; ENABLE_BITCODE = NO; HEADER_SEARCH_PATHS = ( @@ -849,7 +849,7 @@ "$(inherited)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.15; + MARKETING_VERSION = 2.5.16; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -876,7 +876,7 @@ CODE_SIGN_IDENTITY = "Apple Development"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 615; + CURRENT_PROJECT_VERSION = 616; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; HEADER_SEARCH_PATHS = ( @@ -977,7 +977,7 @@ "$(inherited)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.15; + MARKETING_VERSION = 2.5.16; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1147,7 +1147,7 @@ CODE_SIGN_IDENTITY = "Apple Development"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 615; + CURRENT_PROJECT_VERSION = 616; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; ENABLE_BITCODE = NO; @@ -1250,7 +1250,7 @@ "$(PROJECT_DIR)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.15; + MARKETING_VERSION = 2.5.16; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1278,7 +1278,7 @@ CODE_SIGN_ENTITLEMENTS = hexa_keeper_dev.entitlements; CODE_SIGN_IDENTITY = "Apple Distribution"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; - CURRENT_PROJECT_VERSION = 615; + CURRENT_PROJECT_VERSION = 616; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; HEADER_SEARCH_PATHS = ( @@ -1380,7 +1380,7 @@ "$(PROJECT_DIR)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.15; + MARKETING_VERSION = 2.5.16; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", diff --git a/openspec/changes/fix-ask-tab-navigation/design.md b/openspec/changes/fix-ask-tab-navigation/design.md new file mode 100644 index 0000000000..d2f781b63f --- /dev/null +++ b/openspec/changes/fix-ask-tab-navigation/design.md @@ -0,0 +1,38 @@ +## Existing behavior and investigation + +HomeScreen conditionally renders one content subtree inside a layout-only Box, +with MenuFooter as its sibling. Ask's empty and history components use native +Views and an absolutely positioned Fab with zIndex. Fabric can flatten these +layout-only ancestors. The repository also carries prior iOS mounting patches. +Native logs did not +identify the exact failing mount transaction; do not infer a proven upstream +renderer cause from this app-level reproduction alone. + +Verified correction: retain a native, non-collapsing content boundary for the +selected tab, +with explicit tab identity, so outgoing native descendants are removed together +and cannot share the footer's native parent. The same flow failed before and +passed after this change, with the same +disposable wallet state. See verification.md for device results and build limits. + +## Design and data constraints + +Read DESIGN.md: preserve its App shell, Bottom navigation, Spacing and +Accessibility rules. Reuse HomeScreenHeader, MenuFooter, existing hp/wp spacing, +colors and typography. No new visible components, assets, strings or screens. +No Redux slice/saga edits, Realm schema/MMKV keys, or persist version migration. +No PSBT, transaction, recovery or hardware interaction. + +## Affected files and verification + +- src/screens/Home/HomeScreen.tsx: verified native tab boundary. +- src/components/MenuFooter.tsx: stable selectors for the existing four tabs. +- flows/ask-tab-navigation.yaml: repeated empty-state switching. +- flows/ask-history-navigation.yaml: existing-chat/back/tab regression. +- This OpenSpec package: results and remaining device limits. + +Native screenshots and assertions must check both absence of outgoing Ask text +and presence/operability of tabs. A React-only pass is insufficient. Distinguish +the user's physical iPhone 15 Pro Max evidence from simulator and emulator checks. +Test a smaller iPhone and larger text where available. Store only disposable QA +data in evidence; never commit user screenshots or wallet secrets without need. diff --git a/openspec/changes/fix-ask-tab-navigation/proposal.md b/openspec/changes/fix-ask-tab-navigation/proposal.md new file mode 100644 index 0000000000..4a9a5e1c09 --- /dev/null +++ b/openspec/changes/fix-ask-tab-navigation/proposal.md @@ -0,0 +1,28 @@ +## Why + +T-066: the live iOS 2.5.15 app can retain Ask Keeper prompt text over another +Home tab and lose its bottom navigation. The user confirmed Ask → More on an +iPhone 15 Pro Max, with a screenshot; restarting is currently required. An +earlier Release simulator check also lost navigation after returning from chat +to Ask history. These are related symptoms; shared root cause must be verified. + +## What Changes + +- Reproduce empty-state tab switching and the chat/history return separately. +- Correct native view ownership at the Home tab-content boundary, with the + smallest verified change; retain the existing MenuFooter and navigation routes. +- Add repeatable native regression coverage for stale Ask text and reachable tabs. + +## Non-goals + +No new UX or copy, dependency-wide/native-renderer workaround, chat deletion, +Recovery Key fix, wallet changes, platform feature merge, or release submission. +Any subsequent release must use the existing version/artifact checks and a new +approved version/build; never replace the published 2.5.15 tag or artifacts. + +## Impact + +Both mainnet and testnet; all tiers. No Wallet, Vault, Signer or UTXO data changes, +key-material access, storage migrations, new network calls or hardware signer +compatibility changes. Native Maestro coverage is required because mocked React +tests do not validate Fabric mounting or on-screen tab placement. diff --git a/openspec/changes/fix-ask-tab-navigation/specs/home-navigation/spec.md b/openspec/changes/fix-ask-tab-navigation/specs/home-navigation/spec.md new file mode 100644 index 0000000000..063deff016 --- /dev/null +++ b/openspec/changes/fix-ask-tab-navigation/specs/home-navigation/spec.md @@ -0,0 +1,36 @@ +## ADDED Requirements + +### Requirement: Home tab content has an isolated lifecycle +The application SHALL remove the outgoing tab's native content when selecting +another Home tab and SHALL preserve visible, operable bottom navigation. + +#### Scenario: Leave an empty Ask screen +- **GIVEN** Ask Keeper shows its existing suggested prompts and safety warning +- **WHEN** the user selects More, Wallets, or Keys +- **THEN** only the destination's content and header are shown +- **AND** Ask-only prompts and warning text are absent +- **AND** all four existing bottom tabs remain visible and tappable without restart. + +#### Scenario: Repeated tab changes +- **GIVEN** an unlocked app on either supported platform +- **WHEN** the user repeatedly changes Ask → More → Ask → Wallets → Ask → Keys +- **THEN** each selected tab renders correctly and the footer remains available. + +#### Scenario: Return from chat to history +- **GIVEN** an existing disposable Ask conversation +- **WHEN** the user opens it, returns to Ask history, and selects another main tab +- **THEN** history remains saved and only the selected tab is shown +- **AND** navigation remains usable, including subsequent re-entry to Ask. + +#### Scenario: Recovery reminder and larger text +- **GIVEN** the existing Recovery Key reminder is visible or system text is enlarged +- **WHEN** the user switches between Ask and other main tabs +- **THEN** the reminder retains its existing behavior and bottom tabs remain reachable +- **AND** no security-critical copy is truncated to make the layout fit. + +#### Scenario: Return through chat information with keyboard focus +- **GIVEN** an existing disposable Ask conversation +- **WHEN** the user opens and dismisses its disclaimer, opens About Ask Keeper, + returns to chat, focuses the input, then goes back to history and another tab +- **THEN** the modal and keyboard do not cover the destination +- **AND** the saved conversation remains accessible and all Home tabs work. diff --git a/openspec/changes/fix-ask-tab-navigation/tasks.md b/openspec/changes/fix-ask-tab-navigation/tasks.md new file mode 100644 index 0000000000..9469b1333e --- /dev/null +++ b/openspec/changes/fix-ask-tab-navigation/tasks.md @@ -0,0 +1,25 @@ +## 1. Investigation +- [x] Inspect user screenshot and existing T-066 evidence; inspect Home/Ask/footer code. +- [x] Reproduce the empty Ask tab-switch failure in the unmodified release simulator. +- [x] Identify and verify the smallest native-lifecycle correction. + +## 2. UI components +- [x] Implement the verified boundary correction and stable footer selectors. +- [x] Preserve copy, styling, routes and wallet/chat data. + +## 3. Business logic, store and storage +- [x] No changes required; no migrations or signing/recovery changes. + +## 4. Tests and Maestro +- [x] Run the same regression before/after on iOS, retaining failure evidence. +- [x] Verify repeated tab changes and chat-history return on iOS. +- [x] Check Android and smaller-screen/larger-text behavior; record exact limits. +- [x] Run relevant automated checks and strict OpenSpec validation. +- [x] Record the physical-device follow-up under Office, update T-066 and prepare the local review package. + +## 5. T-053 maintenance candidate — authorised 28 September 2026 +- [x] Review the prepared local fix for the selected maintenance batch. +- [ ] Allocate new verified version/build numbers; build and test signed artifacts. +- [ ] Optional physical iPhone follow-up; record simulator coverage separately. + +Fresh release candidates are requested. Preserve published 2.5.15. See verification.md for earlier evidence and test limits; record fresh-build results separately. diff --git a/openspec/changes/fix-ask-tab-navigation/verification.md b/openspec/changes/fix-ask-tab-navigation/verification.md new file mode 100644 index 0000000000..d623061651 --- /dev/null +++ b/openspec/changes/fix-ask-tab-navigation/verification.md @@ -0,0 +1,96 @@ +# Navigation regression verification — 26 September 2026 + +## Status and scope + +Fix prepared locally on `codex/fix-ask-tab-navigation`, based on published source +`e79e16b572d6e3472ac94500bf812d937bd89135`. Not committed, pushed, merged or +released. The user explicitly requested holding this fix for a later grouped +release. No version allocation is needed until that release is prepared; use a +new version/build and the existing release checks then. Published 2.5.15 remains +unchanged. + +Only runtime changes: retain a native, non-collapsing Home content View with the +selected tab as its key; add stable selectors to the existing footer controls. +No wallet, key, transaction, recovery, storage or chat logic changed. + +## Before/after evidence + +The user's physical iPhone 15 Pro Max report was reproduced in the unmodified +2.5.15 Release simulator app on a fresh iPhone 15 Pro Max simulator running +iOS 26.4: empty Ask → More retained Ask prompts/security text and lost the +footer. The same sequence passed after replacing the JS bundle with the fix. + +This verifies the app-level boundary correction. It does not establish the exact +upstream Fabric mounting defect; the native logs did not expose the failing +transaction. The user's physical iOS version is unknown. + +Private evidence directory: +`/Users/devaccount/Workspace/keeper-local-dev/ask-navigation-evidence/` + +- Before: `empty-switch-baseline.log`, `empty-before.png`, `empty-after.png`. +- After: `fixed-ios-retry.log`, `fixed-empty-before.png`, `fixed-empty-after.png`. + +## Test matrix + +| Check | Environment | Result / evidence | +| --- | --- | --- | +| Original empty Ask → More failure | iPhone 15 Pro Max / iOS 26.4 simulator | Reproduced before; passed after | +| Ask → More / Wallets / Keys, three cycles (nine exits) | Same iPhone simulator | PASS, `ios-repeated-tabs-retry.log` | +| Same nine exits with Recovery Key reminder present | iPhone 13 mini / iOS 26.4 simulator | PASS, `small-ios.log` | +| Three exits at extra-extra-extra-large system text size | iPhone 15 Pro Max simulator | PASS, `ios-large-text.log`; restored normal size afterward | +| Nine empty-state exits | Android 17 emulator, disposable user 10 | PASS, `android-tabs-final.log` | +| Existing chat → keyboard focus → back → history → main tabs, three cycles | Android emulator | PASS, `android-history.log` | +| Repeated disclaimer dismiss/reopen, About Ask return, keyboard/back/history/tab switches | Android emulator | PASS, three cycles, `android-info-retry.log` | +| Same information/modal/keyboard/history flow, three cycles | iPhone 15 Pro Max simulator | PASS, `ios-history-final.log` | +| Keys add-sheet and Wallets type-sheet open/cancel, then Ask → More | iPhone 13 mini simulator | PASS, `small-key-modal.log`, `small-wallet-modal.log`; no key or wallet created | +| Relevant existing unit suites | Local Jest | PASS, 27 tests in two suites, `jest.log` | +| Formatting, whitespace, release-version consistency, strict OpenSpec validation | Local checks | PASS | + +The automated flows assert both absence of stale Ask content and presence and +operation of the footer, rather than merely checking that no crash occurred. +Chat checks use disposable conversations with a predefined nonsensitive question. +An iOS response was received; Android AI-provider availability is not an acceptance +claim of these navigation tests. No funds were transferred. + +## Test build limits + +- iOS: existing Release simulator native binary, with a fresh production-mode + Hermes JS bundle containing the fix, locally ad-hoc signed. No new native + dependencies; not a fresh Xcode archive or distributable IPA. +- Android: existing debug native app using the fixed JS through Metro and local + backend configuration. Not a signed production APK/AAB validation. +- Two iPhone device sizes share iOS 26.4. No second iOS-version coverage or + physical-device verification. Enlarged-text checks concern navigation, not a + full accessibility audit. +- The physical iPhone follow-up remains tagged **Office** in T-066. When an + eventual test build is available, repeat the reported exits and history/back + sequence on that iPhone. No user action is needed now. +- Before public release: review/commit the patch, create fresh signed artifacts + with new verified version/build numbers, and rerun these flows on the intended + release builds. Do not overwrite published artifacts or the existing tag. + +## Earlier harness failures, retained for audit + +Initial attempts encountered onboarding/notification dialogs, an overly strict +wallet text selector (iOS merges accessibility labels), and an information-link +selector that omitted its arrow. The info button opens a disclaimer first, then +its Learn more link opens About Ask Keeper. The flow now follows that real path. +These setup/selector failures are retained separately from the reproduced +application failure; they are not counted as successful test runs. + +## Reusable regression rule + +When changing Home content or navigation, exercise both empty Ask and saved-chat +history, with the Recovery Key reminder visible, including keyboard dismissal, +modal/information return and repeated exits to every sibling tab. Check rendered +content and footer reachability on native iOS and Android; mocked React tests do +not validate native view mounting. Preserve an explicit native tab-content +boundary around elevated/absolute-positioned children and keep the footer outside +it. Do not weaken native renderer assertions as a substitute for regression tests. + +## Environment restored + +The Android disposable profile's debug preferences were restored and verified, +the task-specific port 8085 reverse was removed, and the emulator was returned to +its original user 0. Disposable QA data and evidence were retained. iOS system +text size was restored to its original setting. Other Metro servers were untouched. diff --git a/package.json b/package.json index 28f4341087..6d67e4c205 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hexa_keeper", - "version": "2.5.15", + "version": "2.5.16", "private": true, "scripts": { "ios": "npx react-native run-ios --scheme=hexa_keeper_dev --simulator 'iPhone 16' ", diff --git a/release/README.md b/release/README.md index 215fdfb721..2554527896 100644 --- a/release/README.md +++ b/release/README.md @@ -1,10 +1,8 @@ # Release version verification -**Current milestone:** a small test release of the version-consistency change. Per the user’s 25 September direction, security remediation is separate and private-advisory sign-in is not a prerequisite. No security fixes are claimed. Docker contributor packaging is separate from the release patch. The user reconfirmed all three public destinations: App Store, Play production and the normal public APK channel. +**Current milestone:** T-053 maintenance candidate, authorised 28 September 2026: finish the prepared Ask Keeper navigation correction and regression-test existing Dust/Testnet behaviour. Version 2.5.15 remains untouched. Physical-device follow-up is optional; simulator coverage must be labelled accurately. -T-050 addresses the Android regression from marketing version 2.5.14 to 2.3.15 despite an increased build code. Marketing versions and platform build counters must both move forward. - -`version.json` selects candidate 2.5.15, Android 622 and iOS 615 using authenticated store observations from September 25, 2026. The iOS counter also exceeds local source build 614. This is not publication approval or proof of tested binaries. Do not substitute the public App Store listing for uploaded-build history. +`version.json` selects candidate 2.5.16, Android 623 and iOS 616. Authenticated Google Play tracks/uploaded bundles and App Store Connect upload history were checked on 28 September: Android highest 622 and iOS highest 615, both marketing version 2.5.15. The iOS distribution page shows 2.5.15 Ready for Distribution with no newer iOS draft. Keep private investigation and diagnostics outside public release material. 1. Read all uploaded builds and release tracks for Android package `io.hexawallet.bitcoinkeeper`, and uploaded iOS builds for `io.hexawallet.keeper`. Preserve the timestamp and evidence outside the repository. Refresh before upload; preflight accepts evidence at most 24 hours old. 2. Update the manifest with the highest known marketing version and highest uploaded build per platform. Select one greater marketing version for both stores and greater platform build counters. Check unpublished App Store version records as well. diff --git a/release/version.json b/release/version.json index 626a58552f..c8c776defd 100644 --- a/release/version.json +++ b/release/version.json @@ -1,21 +1,21 @@ { - "version": "2.5.15", - "androidVersionCode": 622, - "iosBuildNumber": 615, + "version": "2.5.16", + "androidVersionCode": 623, + "iosBuildNumber": 616, "baselines": { "android": { "applicationId": "io.hexawallet.bitcoinkeeper", - "verifiedAt": "2026-09-25T13:10:54Z", - "highestUploadedBuild": 621, - "highestMarketingVersion": "2.5.14", - "productionRelease": "621 (2.3.15)" + "verifiedAt": "2026-09-28T12:51:36.298748+00:00", + "highestUploadedBuild": 622, + "highestMarketingVersion": "2.5.15", + "productionRelease": "622 (2.5.15)" }, "ios": { "applicationId": "io.hexawallet.keeper", - "verifiedAt": "2026-09-25T13:44:11Z", - "highestUploadedBuild": 612, - "highestMarketingVersion": "2.5.14", - "productionRelease": "612 (2.5.14)" + "verifiedAt": "2026-09-28T12:51:36.298975+00:00", + "highestUploadedBuild": 615, + "highestMarketingVersion": "2.5.15", + "productionRelease": "615 (2.5.15)" } } } diff --git a/src/components/MenuFooter.tsx b/src/components/MenuFooter.tsx index 6547ec6923..bfdc8d492b 100644 --- a/src/components/MenuFooter.tsx +++ b/src/components/MenuFooter.tsx @@ -20,21 +20,25 @@ const MenuFooter = ({ selectedOption, onOptionChange }) => { const menuOptions = [ { + testID: 'home_tab_wallets', name: walletTranslation.homeWallets, defaultIcon: , selectedIcon: , }, { + testID: 'home_tab_keys', name: walletTranslation.keys, defaultIcon: , selectedIcon: , }, { + testID: 'home_tab_ask', name: askAi.ask, defaultIcon: , selectedIcon: , }, { + testID: 'home_tab_more', name: walletTranslation.more, defaultIcon: , selectedIcon: , @@ -53,6 +57,7 @@ const MenuFooter = ({ selectedOption, onOptionChange }) => { {menuOptions.map((option) => ( onOptionChange(option.name)} style={[styles.menuItem]} > diff --git a/src/screens/Home/HomeScreen.tsx b/src/screens/Home/HomeScreen.tsx index d6846a9e42..9640e147c5 100644 --- a/src/screens/Home/HomeScreen.tsx +++ b/src/screens/Home/HomeScreen.tsx @@ -1,4 +1,4 @@ -import { StyleSheet, TouchableOpacity } from 'react-native'; +import { StyleSheet, TouchableOpacity, View } from 'react-native'; import { Box, useColorMode } from '@gluestack-ui/themed-native-base'; import React, { useContext, useEffect, useRef, useState } from 'react'; import useWallets from 'src/hooks/useWallets'; @@ -268,7 +268,10 @@ function NewHomeScreen({ route }) { )} - {content} + {/* Keep tab descendants (including elevated FABs) out of the footer's native parent. */} + + {content} + { From 7fdd502702a8aa149f5a3ad87aac7a274a61e6e8 Mon Sep 17 00:00:00 2001 From: Anant Date: Mon, 28 Sep 2026 18:49:25 +0530 Subject: [PATCH 03/19] fix: initialize Android screen fragment restoration --- .../app/src/main/java/com/hexa_keeper/MainActivity.kt | 3 +++ openspec/changes/fix-ask-tab-navigation/design.md | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/android/app/src/main/java/com/hexa_keeper/MainActivity.kt b/android/app/src/main/java/com/hexa_keeper/MainActivity.kt index b9dd5e2ac9..c807d76e6e 100644 --- a/android/app/src/main/java/com/hexa_keeper/MainActivity.kt +++ b/android/app/src/main/java/com/hexa_keeper/MainActivity.kt @@ -8,6 +8,7 @@ import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate +import com.swmansion.rnscreens.fragment.restoration.RNScreensFragmentFactory class MainActivity : ReactActivity() { @@ -17,6 +18,8 @@ class MainActivity : ReactActivity() { DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) override fun onCreate(savedInstanceState: Bundle?) { + // React Native owns screen state; discard stale native screen fragments on recreation. + supportFragmentManager.fragmentFactory = RNScreensFragmentFactory() super.onCreate(savedInstanceState) window.decorView.post { diff --git a/openspec/changes/fix-ask-tab-navigation/design.md b/openspec/changes/fix-ask-tab-navigation/design.md index d2f781b63f..244040a94b 100644 --- a/openspec/changes/fix-ask-tab-navigation/design.md +++ b/openspec/changes/fix-ask-tab-navigation/design.md @@ -36,3 +36,13 @@ and presence/operability of tabs. A React-only pass is insufficient. Distinguish the user's physical iPhone 15 Pro Max evidence from simulator and emulator checks. Test a smaller iPhone and larger text where available. Store only disposable QA data in evidence; never commit user screenshots or wallet secrets without need. + +## Android activity recreation follow-up + +Fresh release testing on 28 September reproduced a native crash when the system +font scale changed: Android attempted to restore a ScreenStackFragment without +React Native owning its screen state. Register the installed react-native-screens +4.24.0 RNScreensFragmentFactory in MainActivity before super.onCreate, as required +by that version's Android setup instructions. Preserve the existing insets setup. +This is native screen-lifecycle handling only; no wallet storage or authentication +change. Recheck activity recreation, unlock/state retention and Ask navigation. From d9cabbc5de55370f911c12b034b9601caea05033 Mon Sep 17 00:00:00 2001 From: Anant Date: Tue, 29 Sep 2026 18:44:18 +0530 Subject: [PATCH 04/19] Prepare Now 2.5.17 recovery and signing fixes --- android/app/build.gradle | 4 +- ios/Podfile.lock | 8 +- ios/hexa_keeper.xcodeproj/project.pbxproj | 16 +- .../fix-recovery-backup-freshness/design.md | 36 ++ .../evidence/migration-tests.txt | 19 + .../evidence/recovery-tests.txt | 49 ++ .../nfr-benchmark.json | 43 ++ .../nfr-review.md | 50 ++ .../fix-recovery-backup-freshness/proposal.md | 16 + .../specs/assisted-server-backup/spec.md | 65 +++ .../fix-recovery-backup-freshness/tasks.md | 27 ++ .../validation.md | 36 ++ package.json | 5 +- release/README.md | 4 +- release/version.json | 22 +- .../Backup/BackupHealthCheckList.tsx | 3 +- src/components/Modal/PasscodeVerify.tsx | 41 +- src/context/Localization/language/en.json | 47 +- src/context/Localization/language/es.json | 47 +- src/hooks/useSettingKeeper.tsx | 2 +- src/hooks/useUSDTWallets.ts | 52 +- src/navigation/Navigator.tsx | 2 + src/navigation/types.ts | 1 + .../AppSettings/AssistedBackupStatus.tsx | 95 ++++ .../BackupWallet/ViewRecoveryKeyScreen.tsx | 9 +- .../Notifications/NotificationsCenter.tsx | 3 +- src/screens/LoginScreen/CreatePin.tsx | 9 +- src/screens/LoginScreen/Login.tsx | 17 +- src/screens/Recovery/EnterSeedScreen.tsx | 17 +- src/screens/SeedScreens/ExportSeedScreen.tsx | 6 +- src/screens/Vault/ResetEmergencyKey.tsx | 4 +- src/screens/Vault/ResetInheritanceKey.tsx | 3 +- .../Vault/VaultMigrationController.tsx | 15 +- src/services/backend/Relay.ts | 32 +- src/services/backup/image.ts | 269 +++++++++++ src/services/backup/repair.ts | 238 ++++++++++ src/services/backup/restore.ts | 27 ++ src/services/backup/transport.ts | 71 +++ src/services/rest/RestClient.ts | 10 +- .../operations/miniscript/initialTimelock.ts | 20 + src/store/reducers/bhr.ts | 24 + src/store/sagaActions/bhr.ts | 7 +- src/store/sagaActions/upgrade.ts | 4 +- src/store/sagas/bhr.ts | 449 +++++++----------- src/store/sagas/index.ts | 9 +- src/store/sagas/login.ts | 17 +- src/store/sagas/upgrade.ts | 12 +- src/store/sagas/utxos.ts | 39 +- src/store/sagas/wallets.ts | 105 ++-- src/utils/utilities.ts | 39 +- tests/recovery/backupFeedback.test.cjs | 54 +++ tests/recovery/backupFreshness.test.cjs | 169 +++++++ tests/recovery/benchmarks/backup-cost.cjs | 74 +++ tests/recovery/helpers.cjs | 58 +++ tests/recovery/keyRecovery.test.cjs | 280 +++++++++++ tests/recovery/manualCoinChoices.test.cjs | 136 ++++++ tests/recovery/nodeReplacement.test.cjs | 29 ++ tests/recovery/recoveryErrorFeedback.test.cjs | 81 ++++ tests/recovery/repair.test.cjs | 119 +++++ tests/recovery/restoreIntegrity.test.cjs | 203 ++++++++ tests/recovery/sagaHarness.cjs | 290 +++++++++++ tests/recovery/sagaState.test.cjs | 62 +++ tests/recovery/transport.test.cjs | 56 +++ tests/recovery/usdtBackup.test.cjs | 169 +++++++ tests/screens/PinEntry.test.tsx | 155 ++++++ tests/services/initialTimelock.test.ts | 113 +++++ tests/services/resetTimelockBoundary.test.ts | 161 +++++++ tests/services/resetTimelockRoute.test.ts | 53 +++ tests/store/versionHistory.test.ts | 249 ++++++++++ 69 files changed, 4209 insertions(+), 447 deletions(-) create mode 100644 openspec/changes/fix-recovery-backup-freshness/design.md create mode 100644 openspec/changes/fix-recovery-backup-freshness/evidence/migration-tests.txt create mode 100644 openspec/changes/fix-recovery-backup-freshness/evidence/recovery-tests.txt create mode 100644 openspec/changes/fix-recovery-backup-freshness/nfr-benchmark.json create mode 100644 openspec/changes/fix-recovery-backup-freshness/nfr-review.md create mode 100644 openspec/changes/fix-recovery-backup-freshness/proposal.md create mode 100644 openspec/changes/fix-recovery-backup-freshness/specs/assisted-server-backup/spec.md create mode 100644 openspec/changes/fix-recovery-backup-freshness/tasks.md create mode 100644 openspec/changes/fix-recovery-backup-freshness/validation.md create mode 100644 src/screens/AppSettings/AssistedBackupStatus.tsx create mode 100644 src/services/backup/image.ts create mode 100644 src/services/backup/repair.ts create mode 100644 src/services/backup/restore.ts create mode 100644 src/services/backup/transport.ts create mode 100644 src/services/wallets/operations/miniscript/initialTimelock.ts create mode 100644 tests/recovery/backupFeedback.test.cjs create mode 100644 tests/recovery/backupFreshness.test.cjs create mode 100644 tests/recovery/benchmarks/backup-cost.cjs create mode 100644 tests/recovery/helpers.cjs create mode 100644 tests/recovery/keyRecovery.test.cjs create mode 100644 tests/recovery/manualCoinChoices.test.cjs create mode 100644 tests/recovery/nodeReplacement.test.cjs create mode 100644 tests/recovery/recoveryErrorFeedback.test.cjs create mode 100644 tests/recovery/repair.test.cjs create mode 100644 tests/recovery/restoreIntegrity.test.cjs create mode 100644 tests/recovery/sagaHarness.cjs create mode 100644 tests/recovery/sagaState.test.cjs create mode 100644 tests/recovery/transport.test.cjs create mode 100644 tests/recovery/usdtBackup.test.cjs create mode 100644 tests/screens/PinEntry.test.tsx create mode 100644 tests/services/initialTimelock.test.ts create mode 100644 tests/services/resetTimelockBoundary.test.ts create mode 100644 tests/services/resetTimelockRoute.test.ts create mode 100644 tests/store/versionHistory.test.ts diff --git a/android/app/build.gradle b/android/app/build.gradle index 90d90807c5..c2f737d4d3 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -98,8 +98,8 @@ android { applicationId "io.hexawallet.keeper" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 623 - versionName "2.5.16" + versionCode 624 + versionName "2.5.17" missingDimensionStrategy 'react-native-camera', 'general' missingDimensionStrategy 'store', 'play' multiDexEnabled true diff --git a/ios/Podfile.lock b/ios/Podfile.lock index a5c2f9af0b..97a5cb82e6 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -3986,7 +3986,7 @@ SPEC CHECKSUMS: glog: 5683914934d5b6e4240e497e0f4a3b42d1854183 GoogleDataTransport: aae35b7ea0c09004c3797d53c8c41f66f219d6a7 GoogleUtilities: 00c88b9a86066ef77f0da2fab05f65d7768ed8e1 - hermes-engine: 4ec27e7c84ed7950da6e65008539685455d8bef4 + hermes-engine: 497c47216fdf505312e6e9fb53a413e085f8a8e1 HtmlToPdf: 5c0649e93aa1c6583f400268eedea00f15e0fa5f libportal-ios: d9aa55474e2d5be8e38e96345dd37be34fda45b4 libportal-react-native: 05778ef04321517c8366dc7173d05aa9fe131ff2 @@ -4086,7 +4086,7 @@ SPEC CHECKSUMS: React-utils: 493a45d877f410d62476c045fbf220acbffba194 React-webperformancenativemodule: 9b212313b01f5489f21963fbd4a81ef20f280097 ReactAppDependencyProvider: 5bf52020fdc0d0a337068ea42d4a6676ce4a04bc - ReactCodegen: 5c808345ff57b4f4f1eab230f541921ad9e37500 + ReactCodegen: e99a2b210dade5f08acfabb6309357e7f8c22640 ReactCommon: 3b79ecfd327035654f6c36cf1de8e222d8b835e6 RealmJS: a2e97359d58d72ca9fc2deb2e14ba34a218652e5 RNCClipboard: a9d5216cbfaf2f51cfe80bcb132856bb9158fe0d @@ -4099,12 +4099,12 @@ SPEC CHECKSUMS: RNKeychain: 182d986f809280edd9444a557adc21845f7d1e6f RNLocalize: 95a43f85e41a966be7bc9cff2437128911c52da0 RNQrGenerator: 36f1af182d7673bc36e317aca0d293d19883d6e3 - RNReanimated: 6b69a94db352e4dae7eb540f6fab60ff05c18508 + RNReanimated: dd6943b67163a2fa23ecaefc457cf34e7f94df74 RNScreens: 7179cc1ba31b4e18ed29f10abf20c24a7961cf4c RNSentry: f07853ff3fcbb69df26da1d9744e95ee97f683fd RNShare: 11923289a9964c6bd5f507eaa7fe61ec51b0adce RNSVG: 6a91afc99237de70b617c7a84ba84c988ad5573b - RNWorklets: 3f35c2c01e5839d4fee0496d10ada185628ba328 + RNWorklets: 9daaf5ec29337d9b12503e9d2618a4e7d8d91475 SDWebImage: a7f831e1a65eb5e285e3fb046a23fcfbf08e696d SDWebImageWebPCoder: 908b83b6adda48effe7667cd2b7f78c897e5111d Sentry: 4e85b40e4b0235853f40f959d315a6b28e3148d8 diff --git a/ios/hexa_keeper.xcodeproj/project.pbxproj b/ios/hexa_keeper.xcodeproj/project.pbxproj index c77033da6c..88ff8d481f 100644 --- a/ios/hexa_keeper.xcodeproj/project.pbxproj +++ b/ios/hexa_keeper.xcodeproj/project.pbxproj @@ -748,7 +748,7 @@ CODE_SIGN_ENTITLEMENTS = hexa_keeper/hexa_keeper.entitlements; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 616; + CURRENT_PROJECT_VERSION = 617; DEVELOPMENT_TEAM = Y5TCB759QL; ENABLE_BITCODE = NO; HEADER_SEARCH_PATHS = ( @@ -849,7 +849,7 @@ "$(inherited)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.16; + MARKETING_VERSION = 2.5.17; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -876,7 +876,7 @@ CODE_SIGN_IDENTITY = "Apple Development"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 616; + CURRENT_PROJECT_VERSION = 617; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; HEADER_SEARCH_PATHS = ( @@ -977,7 +977,7 @@ "$(inherited)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.16; + MARKETING_VERSION = 2.5.17; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1147,7 +1147,7 @@ CODE_SIGN_IDENTITY = "Apple Development"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 616; + CURRENT_PROJECT_VERSION = 617; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; ENABLE_BITCODE = NO; @@ -1250,7 +1250,7 @@ "$(PROJECT_DIR)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.16; + MARKETING_VERSION = 2.5.17; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1278,7 +1278,7 @@ CODE_SIGN_ENTITLEMENTS = hexa_keeper_dev.entitlements; CODE_SIGN_IDENTITY = "Apple Distribution"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; - CURRENT_PROJECT_VERSION = 616; + CURRENT_PROJECT_VERSION = 617; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; HEADER_SEARCH_PATHS = ( @@ -1380,7 +1380,7 @@ "$(PROJECT_DIR)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.16; + MARKETING_VERSION = 2.5.17; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", diff --git a/openspec/changes/fix-recovery-backup-freshness/design.md b/openspec/changes/fix-recovery-backup-freshness/design.md new file mode 100644 index 0000000000..3ab14e30c9 --- /dev/null +++ b/openspec/changes/fix-recovery-backup-freshness/design.md @@ -0,0 +1,36 @@ +# Design + +## Entry points and user flow +Reuse More → Backup and Recovery → Assisted Server Backup. The row opens `AssistedBackupStatus`; its existing switch retains enable/delete behavior. The existing server-backup notification opens the same status screen. Login dispatches a read-only check after wallet sync for opted-in accounts with pending/unverified status. Login does not await the result. + +The status screen uses ScreenWrapper, WalletHeader, KeeperText, Buttons, themed cards and a ScrollView. Body text explicitly enables system font scaling. Full-width actions are stacked. Back is available throughout and does not cancel or imply rollback. No progress percentages or promises of continued background execution are shown. + +Copy is maintained in `recoveryBackup` in both existing locale JSON files. States: disabled, checking, different, preparing, uploading, verifying, verified, conflict, unverified. Different offers **Back Up Now**; terminal enabled states offer **Check Again**. Slow-stage text appears after ten seconds. Restart maps persisted in-progress phases to unverified until the new check starts. + +## Backup comparison and repair +`src/services/backup/image.ts` compares canonical decrypted recovery data, with deterministic object ordering. Exclude rebuildable chain caches, balance, sync timestamps, receiving-address caches and live node connection flags. Retain user-authored manual UTXO spendability overrides by outpoint, independent of confirmation/cache ordering. Retain keys, derivation, address counters, signer policy, vault policy/archive state, labels and user metadata. Include BTC wallets from both networks, USDT, signers, vaults, nodes and labels. Sanitize local signer/vault secrets using the existing helpers and never mutate Realm during checking. + +Server-only records, differing key identities and server address counters ahead of local data produce conflict with no upload. Invalid/decryption-failed/partial responses produce unverified with no upload. Capture a local snapshot and check it again before upload and completion. Final success requires the uploaded recovery data to match the server readback and current local recovery data. + +A lost upload response has an ambiguous outcome. Attempt readback within the same overall deadline. A matching readback is sufficient for verified success; otherwise keep unverified and let the user check again. No automatic retry loop or repeated full upload on startup. + +## Ordering and persistence +All client backup mutation endpoints use a shared per-account queue in `transport.ts`; full inspection owns the queue through readback. Pending incremental writes increment an account revision and invalidate any in-flight completion claim. Vault `appID` and `appId` payload variants share the correct account queue. A new wallet's incremental write is never replaced with a pre-creation snapshot. + +BHR is separately persisted. `backupRepairStateByAppId` and `backupRepairCompletedByAppId` are durable; `backupRepairRunningByAppId` is blacklisted. Only phase verified sets completion. Old persisted states use nullish defaults. Account changes cannot clear the next account's pending flag or enable its backup setting. No Realm migration is needed. + +## NFR implementation and remaining limits +Transport aborts after 30 seconds without advancing upload/download bytes, with a ten-minute overall attempt deadline. Both are engineering limits requiring native/deployed-backend validation. Progress callbacks reporting the same byte count do not extend the timer. Error messages discard Axios request bodies/headers. No new telemetry is added. + +AES encrypt/decrypt yields between 16 KiB chunks using CryptoJS's existing OpenSSL format. Local JSON text is guarded using a conservative three bytes per UTF-16 code unit against an 8 MiB record budget; encrypted aggregate payloads are limited to 32 MiB. Reject oversized data without truncation or verified success. Realm extraction, JSON serialization/parsing, Base64 conversion and UTF-8 decoding still have synchronous sections; native frame-time and memory budgets are NOT established by these guards or desktop tests. + +## Server contract and release gates +Repair now requires `getBackupSnapshot` and `repairAppBackup` from the paired relay candidate. The snapshot returns a SHA-256 revision over encrypted recovery records. Repair supplies that revision and rechecks it inside a MongoDB snapshot transaction. Vaults, labels, signer maps and the app image update atomically; stale revisions, missing referenced records and attempts to omit existing recovery records fail closed. Existing label IDs update their encrypted content. Archived metadata is preserved. No fallback to the legacy full replacement endpoint is permitted. + +Local database and HTTP tests establish this contract for the new endpoints. Production requires a transaction-capable replica set, compatible deployed request limits and relay deployment before the mobile update. Those deployment facts are not yet verified. + +The legacy full-backup endpoint remains callable by older clients and does not participate in the new revision contract. Mixed-version full replacement remains an unresolved release gate. Normal incremental wallet/signer updates in the relay candidate now set individual records atomically, including a version-only call without `nodes`, but that does not make every legacy mutation transactional. Server-only/conflicting data is preserved pending reconciliation. + +## Restore integrity follow-up + +Actual Recovery Key restoration predecodes the complete server image, verifies referenced vault/label identities, and requires each local persistence operation to succeed. A failed fetch cannot masquerade as an empty backup. Success is exposed only after the expected derived Recovery Key signing material is present; failed records are not skipped. Database writes remain sequential rather than one atomic transaction. A correct Recovery Key with unavailable/corrupt backup receives retry feedback instead of an incorrect-words error. Existing private-material policy is preserved per key type. diff --git a/openspec/changes/fix-recovery-backup-freshness/evidence/migration-tests.txt b/openspec/changes/fix-recovery-backup-freshness/evidence/migration-tests.txt new file mode 100644 index 0000000000..322481c078 --- /dev/null +++ b/openspec/changes/fix-recovery-backup-freshness/evidence/migration-tests.txt @@ -0,0 +1,19 @@ +PASS tests/services/recoveryKeyMigration.test.ts + migration 4: recoveryKeyBackedUpByAppId → recoveryKeyStatusByAppId + ✓ maps Boolean true → "confirmed" (1 ms) + ✓ maps Boolean false → "generated" + ✓ maps missing entry → "generated" (1 ms) + ✓ handles undefined recoveryKeyBackedUpByAppId gracefully + ✓ maps multiple apps correctly + setRecoveryKeyStatus reducer + ✓ sets status to "generated" + ✓ sets status to "viewed" + ✓ sets status to "skipped" + ✓ sets status to "confirmed" and syncs legacy boolean to true + ✓ non-confirmed statuses do not change legacy boolean field + +Test Suites: 1 passed, 1 total +Tests: 10 passed, 10 total +Snapshots: 0 total +Time: 0.199 s, estimated 1 s +Ran all test suites matching /tests\/services\/recoveryKeyMigration.test.ts/i. diff --git a/openspec/changes/fix-recovery-backup-freshness/evidence/recovery-tests.txt b/openspec/changes/fix-recovery-backup-freshness/evidence/recovery-tests.txt new file mode 100644 index 0000000000..7686867b20 --- /dev/null +++ b/openspec/changes/fix-recovery-backup-freshness/evidence/recovery-tests.txt @@ -0,0 +1,49 @@ +✔ BackupHealthCheckList.tsx never enables backup or shows success after failure (33.969708ms) +✔ ExportSeedScreen.tsx never enables backup or shows success after failure (16.320167ms) +✔ ViewRecoveryKeyScreen.tsx never enables backup or shows success after failure (7.27875ms) +✔ wallet added after initial backup survives encrypted restore: MAINNET (132.903666ms) +✔ wallet added after initial backup survives encrypted restore: TESTNET (46.145042ms) +✔ pending repair never suppresses a not-yet-persisted incremental addition (36.970166ms) +✔ disabled backup makes no uploads and preserves local creation (31.466583ms) +✔ backup failure retains wallet and retry: {"online":false} (20.890333ms) +✔ backup failure retains wallet and retry: {"incrementalError":true} (20.1545ms) +✔ recovery restores saved wallets and confirms Recovery Key status: MAINNET (27.787625ms) +✔ recovery restores saved wallets and confirms Recovery Key status: TESTNET (16.323292ms) +✔ recovery restores saved wallets and confirms Recovery Key status: MAINNET,TESTNET (16.082333ms) +✔ relay rejection retains the existing wallet-creation failure contract (15.722292ms) +✔ backup gate never performs an unsolicited full repair: true (13.974042ms) +✔ backup gate never performs an unsolicited full repair: false (13.935875ms) +✔ repair markers are stored in the separately persisted backup slice (12.869875ms) +✔ pending repair does not suppress explicit wallet deletion (14.204791ms) +✔ upgrade check detects omissions without uploading; explicit repair verifies readback (90.5965ms) +✔ matching upgrade only reads and does not reupload (67.046166ms) +✔ readError never claims success (35.042917ms) +✔ reject never claims success (55.039708ms) +✔ corruptWrite never claims success (22.31275ms) +✔ lost upload acknowledgement is resolved by readback without duplicate upload (31.242375ms) +✔ server-only wallet is preserved and blocks replacement (20.713375ms) +✔ same IDs with different recovery keys are a conflict (0.321708ms) +✔ same IDs with changed user metadata require an update (0.939583ms) +✔ canonical comparison ignores object order and chain caches but retains address counters (0.628959ms) +✔ BTC both networks, USDT, vaults, keys, labels and nodes are verified without mutating local data (101.287291ms) +✔ malformed or partial server response is unavailable, never an empty snapshot (40.127625ms) +✔ mutation arriving during upload invalidates completion and remains queued until readback (15.497666ms) +✔ account switch during check cannot upload one account with another account data (11.366333ms) +✔ chunked encryption remains compatible with existing recovery including Unicode (27.616042ms) +✔ oversized record fails without uploading or truncating (13.001333ms) +✔ only verified readback sets durable per-account completion and clears pending (100.407291ms) +✔ offline/unverified remains pending and retryable, never spins indefinitely (34.430583ms) +✔ account switch preserves per-account result without clearing another account pending state (42.929ms) +✔ a later mutation invalidates verified status without affecting a second account (0.530667ms) +✔ stalled transport aborts after 30 seconds and redacts request errors (27.97925ms) +✔ only real progress resets stall clock; active transfer still has overall deadline (17.014792ms) +✔ same-account writes serialize, another account runs independently, rejected queue recovers (10.398833ms) +✔ repeated repair actions share one upload and readback (69.173875ms) +ℹ tests 41 +ℹ suites 0 +ℹ pass 41 +ℹ fail 0 +ℹ cancelled 0 +ℹ skipped 0 +ℹ todo 0 +ℹ duration_ms 868.918958 diff --git a/openspec/changes/fix-recovery-backup-freshness/nfr-benchmark.json b/openspec/changes/fix-recovery-backup-freshness/nfr-benchmark.json new file mode 100644 index 0000000000..d4c357f7d1 --- /dev/null +++ b/openspec/changes/fix-recovery-backup-freshness/nfr-benchmark.json @@ -0,0 +1,43 @@ +{ + "environment": "darwin/arm64 Node v25.9.0", + "samples": "one warm-up and three measured repetitions per case", + "networkTiming": "theoretical payload transfer only; no measured network or protocol latency", + "results": [ + { + "records": 10, + "recordKiB": 50, + "plaintextMiB": 0.49, + "ciphertextMiB": 0.65, + "encryptMs": 19.3, + "decryptAndParseMs": 13.5, + "uploadPlusReadbackSecondsAt1Mbps": 10.9 + }, + { + "records": 100, + "recordKiB": 50, + "plaintextMiB": 4.89, + "ciphertextMiB": 6.52, + "encryptMs": 175.5, + "decryptAndParseMs": 136.2, + "uploadPlusReadbackSecondsAt1Mbps": 109.4 + }, + { + "records": 100, + "recordKiB": 200, + "plaintextMiB": 19.54, + "ciphertextMiB": 26.05, + "encryptMs": 718, + "decryptAndParseMs": 498.4, + "uploadPlusReadbackSecondsAt1Mbps": 437.1 + }, + { + "records": 1, + "recordKiB": 20000, + "plaintextMiB": 19.53, + "ciphertextMiB": 26.04, + "encryptMs": 916.6, + "decryptAndParseMs": 503.8, + "uploadPlusReadbackSecondsAt1Mbps": 436.9 + } + ] +} diff --git a/openspec/changes/fix-recovery-backup-freshness/nfr-review.md b/openspec/changes/fix-recovery-backup-freshness/nfr-review.md new file mode 100644 index 0000000000..ec2645a4ea --- /dev/null +++ b/openspec/changes/fix-recovery-backup-freshness/nfr-review.md @@ -0,0 +1,50 @@ +# Backup comparison and repair: NFR review + +Reviewed 29 September 2026. This audit records the original baseline for the check → prompt → update → verify flow. The flow and safeguards are now implemented locally; see design.md and validation.md for current status. The observations below describe the pre-change candidate, not the final implementation. No approved numerical backup performance budgets were found in the synced product sources or repository OpenSpec documents searched. The thresholds below are proposed engineering targets, subject to native validation. + +## Original observed gaps (addressed unless listed as a remaining gate in design.md) + +- `src/services/rest/RestClient.ts:64`: POST passes headers only to Axios. The backup endpoints supply no explicit request timeout, abort signal, or transfer progress callbacks. No global Axios timeout override was found. A stalled request can leave the loading state pending indefinitely. An existing unrelated call passes `{timeout: 20000}` as the headers argument, so that pattern must not be copied as a timeout implementation. +- `src/store/sagas/bhr.ts`: full backup synchronously serializes/encrypts all wallet, signer, vault, node and label records before posting one large request. Saga orchestration does not move synchronous encryption off the React Native JavaScript thread. One large wallet can stall it even if work yields between smaller records. +- `ActivityIndicatorView` is an overlay modal with a spinner and no stage text or explicit exit/retry control. Existing backup consumers use a global loading flag. It is unsuitable as the entire long-running repair experience. +- Existing `validateServerBackupWorker` compares most collections by IDs/counts, decrypts records synchronously, omits local USDT wallet records from its wallet comparison, and mutates the local node object's `isConnected` field during comparison. It cannot be reused unchanged as read-only semantic verification. +- The generic watcher forks each request, so repeated repair actions can overlap. Full snapshots replace server collections; concurrent mutations need ordering/version checks, not merely button disabling. +- The candidate's repair marker currently means server acknowledgement, not post-upload readback verification. That is insufficient for the proposed final verified-success message. +- Candidate upgrade repair currently uploads automatically for opted-in accounts. Adopting the proposed comparison/prompt flow requires replacing that upgrade behavior; it is not yet done. + +## Measured local baseline + +`node tests/recovery/benchmarks/backup-cost.cjs` exercises production AES encryption/decryption with disposable synthetic records, one warm-up and three measured repetitions. Median measurements on this Mac (Node darwin/arm64), not React Native/device results: + +| Synthetic input | Encrypted payload | Encrypt | Decrypt + parse | Upload + readback at 1 Mbps each way, theoretical minimum | +| --- | --- | --- | --- | --- | +| 10 × 50 KiB records, 0.49 MiB total | 0.65 MiB | 19 ms | 14 ms | 11 s | +| 100 × 50 KiB, 4.89 MiB total | 6.52 MiB | 176 ms | 136 ms | 109 s | +| 100 × 200 KiB, 19.54 MiB total | 26.05 MiB | 718 ms | 498 ms | 437 s | +| One 19.53 MiB record | 26.04 MiB | 917 ms | 504 ms | 437 s | + +Transfer estimates exclude the initial comparison download, protocol overhead, latency, retries and server processing. They assume symmetric sustained 1 Mbps, not typical user throughput. Synthetic sizes are stress cases, not observed user backup sizes or proposed supported limits. JSON request overhead and peak memory were not measured. Local relay source accepts JSON bodies up to 50 MB; deployed proxy/server limits remain unverified. + +## Required behavior + +1. **Startup and interaction:** show the unlocked app without awaiting the upgrade comparison's network result. Schedule the check after essential startup work. Encryption/comparison must not freeze navigation or signing UI. Proposed native target: no backup-induced JavaScript-thread task longer than 50 ms; measure on the slowest supported device, including a single large wallet. Yielding between records alone does not solve large-record stalls. +2. **Progress:** display the real current stage: checking, preparing, uploading, verifying. Proposed response target: visible feedback within 250 ms of the user starting repair. Show explanatory slow-operation status after 10 seconds. Do not invent a percent, remaining time, or completion while bytes/server work are unobserved. +3. **No trapped waiting screen:** allow users to leave the progress view from the outset and expose the operation status from the existing backup area. Leaving the view must not claim that an upload has been undone. OS background suspension/app termination must leave durable pending/unverified state; do not promise continued execution in the background. +4. **Bounded stalls:** implement transport-level cancellation/deadlines, not only a UI timer. Proposed stall threshold: 30 seconds without genuine transfer or stage progress. A healthy large transfer may take minutes, so a blanket 30-second total timeout is inappropriate. Establish a bounded overall attempt budget and supported payload ceiling from native and deployed-backend measurements before release; do not guess those limits from the Mac benchmark. +5. **Ambiguous outcomes and retries:** timeout/cancellation after upload may mean the server already accepted it. Mark the outcome unverified, re-read before retrying, and never treat a retrieval error as mismatch or empty backup. Use bounded retry/backoff with manual retry available; no tight loops or repeated prompts at every unlock. +6. **Correct comparison:** compare canonical recovery-relevant plaintext locally after decryption, not randomized ciphertext, volatile balances or live connection flags. Include all supported wallet types/networks and associated recovery material. Preserve server-only/conflicting records pending explicit reconciliation. Comparison must not mutate live Realm objects or alter keys. +7. **Consistent verification:** freeze/version the intended snapshot; coalesce repair work per account and coordinate full/incremental writes. New wallet activity during repair must remain pending until included and verified. Only a readback matching the intended complete recovery data can produce verified success or permanently clear the reminder. +8. **Privacy and consent:** preserve Assisted Server Backup opt-out. Report diagnostic sizes, durations, stage and error category only; no Recovery Key, private keys, plaintext backup, wallet IDs or addresses in telemetry/logs. Do not add new analytics as part of this review. +9. **Accessibility:** use existing Keeper components; stage/failure text must remain readable at small widths and enlarged system text sizes. Controls remain reachable, progress changes are accessible, and a spinner is not the only status signal. + +## Native acceptance matrix / current status + +**Completed locally:** native small-fixture upgrade and clean recovery on Android/iOS, Android repair/readback, iOS backend failure/retry. These are development/simulator results. + +**Remaining native matrix:** large/single-large-record datasets; many labels/signers; both networks and USDT; normal network, 1 Mbps network, high latency, no response, offline/reconnect; background/foreground, OS kill/relaunch, screen navigation, account switch, repeated taps, and wallet mutation during upload. Measure UI stalls, end-to-end stage durations, peak memory, bytes and retry count. Verify bounded stalled-state exit and uncertain-outcome readback, and that matching backups produce no repair prompt. + +**Infrastructure update:** the shared Docker VM still has storage errors. A separate `keeper-recovery-qa` Colima profile now runs a healthy disposable MongoDB replica set and local relay; database/HTTP contract tests pass. Native performance acceptance is still pending. The Mac benchmark is a finding, not an NFR pass; keep the candidate in Now until applicable release gates pass. + +## Current desktop stress follow-up + +The real production AES/comparison path under Node 22, with mocked Realm/transport, repaired 10 wallets + 10 keys in 487 ms, 100 + 100 in 3,866 ms and 1,000 + 1,000 in 35,314 ms. Comparison took 189 / 2,050 / 20,145 ms; maximum event-loop delays were 36 / 37 / 91 ms on a busy Mac. The largest case exceeds the proposed 50 ms task target even here. This is not native NFR acceptance. Evidence: now-candidate-2026-09-29/evidence/backup-performance.json. diff --git a/openspec/changes/fix-recovery-backup-freshness/proposal.md b/openspec/changes/fix-recovery-backup-freshness/proposal.md new file mode 100644 index 0000000000..c19dfb9f77 --- /dev/null +++ b/openspec/changes/fix-recovery-backup-freshness/proposal.md @@ -0,0 +1,16 @@ +# Recovery Key: keep Assisted Server Backup current + +## Why +T-060 reproduced a later-created Testnet Mobile Wallet missing from an acknowledged server backup and from recovery with the correct Recovery Key. The enabled-backup gate skipped incremental writes when no full backup was pending. Permanent loss of wallet keys or funds was not established. + +## What changes +- Enabled backups execute incremental mutations, including wallets not yet persisted to Realm. Pending historical repair does not suppress them. +- Upgraded opted-in accounts check the server against local recovery content without automatically replacing the backup. A mismatch prompts the user through Notifications and More → Backup and Recovery → Assisted Server Backup. +- Back Up Now checks again, prepares the snapshot, uploads and verifies by readback. Matching backups require no upload. Retrieval failure is not treated as an empty backup. +- Show real stages, slow-operation explanation, an immediate Back action, and explicit conflict/unverified states. Preserve per-account status across restart; active spinner state is transient. +- Serialize app, vault, label and deletion writes per account; coalesce repeated repair actions and invalidate completion when local mutations arrive. +- Bound stalled requests and overall attempts; chunk AES work while preserving the existing backup format. Never truncate large records. +- Use the current Recovery Key confirmation reducer after successful recovery. Fix three existing UI branches that enabled Assisted Server Backup or displayed success after server-backup failure. + +## Status +Implemented locally in the isolated `keeper-recovery-t060` checkout. Not committed, integrated, deployed or release-approved. Native QA and relay concurrency/label-write limitations remain release gates; see validation.md. Existing backups missing data require the original device to still hold it; this change does not reconstruct arbitrarily missing wallets. diff --git a/openspec/changes/fix-recovery-backup-freshness/specs/assisted-server-backup/spec.md b/openspec/changes/fix-recovery-backup-freshness/specs/assisted-server-backup/spec.md new file mode 100644 index 0000000000..6503d510c2 --- /dev/null +++ b/openspec/changes/fix-recovery-backup-freshness/specs/assisted-server-backup/spec.md @@ -0,0 +1,65 @@ +## MODIFIED Requirements + +### Requirement: Enabled Assisted Server Backup includes subsequent mutations +The app SHALL upload enabled incremental backup mutations even when no full backup is pending. It SHALL preserve explicit relay rejection semantics and pending repair after transport failure. + +#### Scenario: A wallet is created after the initial backup +- **WHEN** an opted-in user creates a Bitcoin wallet on either network after backing up +- **THEN** its encrypted incremental payload is sent before local creation completes +- **AND** a pending historical repair does not skip the new wallet's write + +#### Scenario: Backup is disabled +- **WHEN** the user creates or changes a wallet with Assisted Server Backup disabled +- **THEN** the automatic writer and upgrade check make no backup upload + +## ADDED Requirements + +### Requirement: Upgrade repair requires comparison and user action +The app SHALL compare local recovery content with a decrypted server snapshot for an opted-in unverified account. Retrieval or decryption errors SHALL NOT be interpreted as a mismatch or empty backup. + +#### Scenario: Old backup omits local data +- **WHEN** comparison detects recovery data present locally but missing from the backup +- **THEN** show a mismatch and Back Up Now through the existing backup area +- **AND** do not replace the backup until the user starts repair + +#### Scenario: Backups match +- **WHEN** canonical recovery content matches +- **THEN** mark that account verified without uploading + +#### Scenario: Server-only data or conflicting recovery identity +- **WHEN** comparison detects server-only records, different keys or address counters ahead of this device +- **THEN** preserve the server backup and show the conflict state without upload + +### Requirement: Completion means verified recovery content +The app SHALL read back the upload and compare it with the intended snapshot and current local data. It SHALL invalidate completion if a local backup mutation occurs during the operation. A server acknowledgement alone SHALL NOT mark repair complete. + +#### Scenario: An upload response is lost +- **WHEN** the request fails after it may have reached the server +- **THEN** attempt readback within the deadline +- **AND** report verified only if the recovery data matches, otherwise leave unverified + +#### Scenario: Another local wallet is created during repair +- **WHEN** a mutation arrives during full backup +- **THEN** serialize the incremental write and keep repair unverified until a subsequent check includes it + +#### Scenario: The app restarts or changes accounts +- **WHEN** an operation is interrupted or the active account changes +- **THEN** retain unverified state for the original account without clearing another account's pending status + +### Requirement: Repair has bounded, accessible progress +The repair screen SHALL expose real checking, preparing, uploading and verifying stages, a slow-operation explanation after ten seconds, and a Back action throughout. It SHALL NOT claim background execution or rollback on navigation. Stalled transport SHALL be aborted, repeated repair actions coalesced, and oversized records rejected without truncation. + +#### Scenario: The server stops responding +- **WHEN** no upload/download bytes advance for thirty seconds +- **THEN** abort the transport and return an unverified state with manual checking available + +#### Scenario: The user leaves the waiting screen +- **WHEN** Back is selected during repair +- **THEN** navigation remains available and operation status can be revisited in Assisted Server Backup + +### Requirement: Failed server backup is not shown as success +Existing backup screens SHALL NOT enable Assisted Server Backup or show server-backup success following backupAllFailure. Physical Recovery Key confirmation remains a separate state. + +#### Scenario: Server backup fails after Recovery Key confirmation +- **WHEN** the user confirmed the Recovery Key but server verification fails +- **THEN** retain the physical confirmation and show backup-not-verified feedback without falsely enabling the server backup setting diff --git a/openspec/changes/fix-recovery-backup-freshness/tasks.md b/openspec/changes/fix-recovery-backup-freshness/tasks.md new file mode 100644 index 0000000000..94fd60121a --- /dev/null +++ b/openspec/changes/fix-recovery-backup-freshness/tasks.md @@ -0,0 +1,27 @@ +## Implementation +- [x] Fix enabled incremental backup gate and preserve explicit subscription rejection. +- [x] Check upgraded opted-in accounts without an unsolicited replacement upload. +- [x] Implement comparison, prompt, repair stages, readback verification and manual retry. +- [x] Include both Bitcoin networks, USDT, keys, vaults, labels and nodes; protect detected server-only/conflicting data. +- [x] Persist account-specific verification and interruption state separately from transient running state. +- [x] Serialize local backup writes, coalesce repair requests and invalidate completion during mutations/account switch. +- [x] Add transport abort, stall/deadline bounds, slow status, leave-screen affordance and bounded/chunked crypto work. +- [x] Fix recovered Recovery Key confirmation and existing backup UI failure-as-success branches. + +## Verification +- [x] Run targeted production-code recovery/repair/transport/state/UI feedback tests with disposable adapters. +- [x] Run the existing Recovery Key migration/status suite. +- [x] Bundle Android JavaScript and inspect baseline versus candidate TypeScript diagnostics. +- [x] Lint all new modules/screen with the missing Jest plugin supplied to the existing ESLint configuration. +- [x] Bundle iOS JavaScript. +- [x] Run native Android/iOS upgrade and clean recovery using disposable data against a working backend. Final consent follow-up is recorded separately in validation.md. +- [ ] Measure small-screen and increased-text layout, crypto frame time, memory, throughput, foreground/background and kill/restart. +- [ ] Validate deployed request-size limits and approve/tune provisional record, transfer and deadline bounds. + +## Release gates +- [x] Implement and test revision-checked atomic repair on the paired relay. +- [x] Protect repaired backups from legacy full replacement, including transaction retries and unchanged-ciphertext races. +- [ ] Validate production transaction topology and relay-first deployment. +- [x] Fix same-ID label-content upserts in the paired relay candidate; verify against real MongoDB and HTTP. +- [ ] Resolve ordinary CLI lint's inherited Jest environment/plugin error. +- [ ] Review and integrate only after applicable checks pass; commit/push/release require established owner approval. diff --git a/openspec/changes/fix-recovery-backup-freshness/validation.md b/openspec/changes/fix-recovery-backup-freshness/validation.md new file mode 100644 index 0000000000..b2db3ee842 --- /dev/null +++ b/openspec/changes/fix-recovery-backup-freshness/validation.md @@ -0,0 +1,36 @@ +# Recovery candidate validation — 29 September 2026 + +Local, uncommitted public source at `/Users/devaccount/Workspace/keeper-recovery-t060`, based on `7fdd502702a8aa149f5a3ad87aac7a274a61e6e8`. Paired relay source at `/Users/devaccount/Workspace/keeper-recovery-relay`, based on `5551550d7ba0e84ce239a7f154f34613081c5c20`. No production deployment, commit, push or store submission has occurred. T-060 remains Now. + +## Automated evidence + +- 162 Node recovery tests pass against production functions and real AES with disposable storage/transport adapters. Includes wallet/key lifecycle, exact key identity, shared registration updates, USDT metadata, manual coin choices, explicit last-node deletion, strict restore, repair races, readback, failures and transport limits. +- 20 related Jest tests pass: 10 Recovery Key migration/status, 6 Version History and 4 PIN. +- 32 relay tests pass against a disposable real MongoDB replica set, including atomic repair, rollback, ownership, archive state, node replacement, old/new writer races and HTTP failure responses. TypeScript compilation passes under Node 22. +- 3 paired real HTTP tests pass using production encryption and comparison. +- Release tooling: 11 Node plus 7 Python tests pass. Existing source version consistency passes at 2.5.16 / Android 623 / iOS 616; those counters cannot be reused for a new store upload. + +## Native evidence and final follow-up + +Fresh Android development and iOS Debug simulator builds installed over existing disposable QA apps. Android mismatch → Back Up Now → Backup verified passed. Clean native restoration of the same encrypted backup passed on both platforms: one hot wallet, seven signer records and two vault records (active and archived). Native key cards include Mobile Key and five imported Seed Keys; the Recovery Key signer is intentionally hidden. Android retained wallet/key data on upgrade. iOS retained the wallet and showed Recovered Wallet in Version History. PIN creation, mismatch/correction and login checks passed where recorded. + +An actual local database outage produced a retryable iOS recovery failure; the same Recovery Key succeeded after the database restarted. This is evidence for that failure/retry, not the full native interruption matrix. + +A subsequent iOS check found that recovery's transient `seedConfirmed=true` signal could be replayed by the Recovery Key backup page and enable Assisted Server Backup. Recovery now clears this transient signal while retaining persistent confirmed Recovery Key status/history. A regression exercises recovery and the actual health-check effect; 162 tests pass. The refreshed Android QA artifact is 2.5.17-qa.3 (626), signature-verified and installed as an upgrade. Final-source clean iOS recovery passed again; opening Recovery Key retained confirmed status while Assisted Server Backup remained off. Evidence: ios-recovered-consent-preserved.log and evidence/ios-final-recovery.log. + +Evidence root: `/Users/devaccount/Workspace/keeper-local-dev/now-candidate-2026-09-29`. Artifact manifests identify exact source hashes and the distinction between embedded Android JS and iOS Metro JS. Earlier APK results must not be represented as final post-follow-up binaries. + +## Compatibility and recovery guarantees + +Successful revisioned repair marks the backup as requiring the new full-write contract. Legacy full replacement checks that marker inside the transaction, including retries, and returns 409 after repair. Before repair it rejects omissions and preserves archive state. Incremental routes remain compatible; stale same-ID writes by older clients are not universally prevented, and the comparison must detect subsequent differences. + +All recovery records are decoded and checked before persistence. Failed Realm writes and regenerated Recovery Key identity mismatches prevent success. Local Realm writes remain sequential; a failed attempt can leave partial records without completing recovery. Native interrupted-recovery acceptance remains open. + +## Remaining gates + +- Native large/single-large-record performance, enlarged text/accessibility, interruption/relaunch and slow-network acceptance; desktop stress results are not phone performance evidence. +- Production transaction topology, endpoint authorization/request limits and relay-first rollout. +- Final clean reviewed source, refreshed store history/counters, production signed artifacts and artifact-level upgrade/smoke checks. +- Whole-repository lint/typechecking retain inherited failures. Focused new modules were linted via the installed nested Jest plugin; no repository-wide clean pass is claimed. + +No physical tester onboarding or automation programme is required by this candidate; that work is deferred separately by the owner. diff --git a/package.json b/package.json index 6d67e4c205..072f11b411 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hexa_keeper", - "version": "2.5.16", + "version": "2.5.17", "private": true, "scripts": { "ios": "npx react-native run-ios --scheme=hexa_keeper_dev --simulator 'iPhone 16' ", @@ -28,7 +28,8 @@ "release android prod": "cd android && ENVFILE=.env.production bundle exec fastlane live --env production", "release ios dev": "cd ios && ENVFILE=.env bundle exec fastlane dev --env dev", "release ios prod": "cd ios && ENVFILE=.env.production bundle exec fastlane live --env production", - "maestro:test:regression": "maestro test flows/regression.yaml" + "maestro:test:regression": "maestro test flows/regression.yaml", + "test:recovery": "node --test tests/recovery/*.test.cjs" }, "dependencies": { "@bitcoinerlab/miniscript": "1.4.0", diff --git a/release/README.md b/release/README.md index 2554527896..ea88ab6702 100644 --- a/release/README.md +++ b/release/README.md @@ -1,8 +1,8 @@ # Release version verification -**Current milestone:** T-053 maintenance candidate, authorised 28 September 2026: finish the prepared Ask Keeper navigation correction and regression-test existing Dust/Testnet behaviour. Version 2.5.15 remains untouched. Physical-device follow-up is optional; simulator coverage must be labelled accurately. +**Current milestone:** Now candidate 2.5.17: Recovery Key backup comparison/repair and complete data restore, Version History, PIN handling, and the privately reviewed timelock prevention change. Keep advisory details and private fixtures out of public release material. -`version.json` selects candidate 2.5.16, Android 623 and iOS 616. Authenticated Google Play tracks/uploaded bundles and App Store Connect upload history were checked on 28 September: Android highest 622 and iOS highest 615, both marketing version 2.5.15. The iOS distribution page shows 2.5.15 Ready for Distribution with no newer iOS draft. Keep private investigation and diagnostics outside public release material. +`version.json` selects 2.5.17, Android 624 and iOS 617. Authenticated Google Play evidence on 29 September shows highest uploaded Android code 623; App Store Connect shows latest iOS upload 2.5.16 (616), Complete, and the production version Ready for Distribution. Refresh store baselines again before upload. The paired Recovery relay is deployed and its live encrypted repair/readback smoke passed. Independent security acceptance and final physical testing remain pending. 1. Read all uploaded builds and release tracks for Android package `io.hexawallet.bitcoinkeeper`, and uploaded iOS builds for `io.hexawallet.keeper`. Preserve the timestamp and evidence outside the repository. Refresh before upload; preflight accepts evidence at most 24 hours old. 2. Update the manifest with the highest known marketing version and highest uploaded build per platform. Select one greater marketing version for both stores and greater platform build counters. Check unpublished App Store version records as well. diff --git a/release/version.json b/release/version.json index c8c776defd..9a4e7ebc01 100644 --- a/release/version.json +++ b/release/version.json @@ -1,21 +1,21 @@ { - "version": "2.5.16", - "androidVersionCode": 623, - "iosBuildNumber": 616, + "version": "2.5.17", + "androidVersionCode": 624, + "iosBuildNumber": 617, "baselines": { "android": { "applicationId": "io.hexawallet.bitcoinkeeper", - "verifiedAt": "2026-09-28T12:51:36.298748+00:00", - "highestUploadedBuild": 622, - "highestMarketingVersion": "2.5.15", - "productionRelease": "622 (2.5.15)" + "verifiedAt": "2026-09-29T10:32:44Z", + "highestUploadedBuild": 623, + "highestMarketingVersion": "2.5.16", + "productionRelease": "623 (2.5.16)" }, "ios": { "applicationId": "io.hexawallet.keeper", - "verifiedAt": "2026-09-28T12:51:36.298975+00:00", - "highestUploadedBuild": 615, - "highestMarketingVersion": "2.5.15", - "productionRelease": "615 (2.5.15)" + "verifiedAt": "2026-09-29T12:45:29.673796+00:00", + "highestUploadedBuild": 616, + "highestMarketingVersion": "2.5.16", + "productionRelease": "616 (2.5.16)" } } } diff --git a/src/components/Backup/BackupHealthCheckList.tsx b/src/components/Backup/BackupHealthCheckList.tsx index 1c6fa4f475..f59e845194 100644 --- a/src/components/Backup/BackupHealthCheckList.tsx +++ b/src/components/Backup/BackupHealthCheckList.tsx @@ -105,7 +105,7 @@ function BackupHealthCheckList({ isUaiFlow }) { useEffect(() => { - if (backupAllSuccess || backupAllFailure) { + if (backupAllSuccess) { if (!automaticCloudBackup) setAsbEnabled(true); dispatch(setBackupAllSuccess(false)); dispatch(setBackupAllFailure(false)); @@ -132,6 +132,7 @@ function BackupHealthCheckList({ isUaiFlow }) { useEffect(() => { if (backupAllFailure && isFocused) { + setFailedVerificationModal(true); dispatch(setBackupAllFailure(false)); } }, [backupAllFailure]); diff --git a/src/components/Modal/PasscodeVerify.tsx b/src/components/Modal/PasscodeVerify.tsx index 87d53ba498..246ec585c7 100644 --- a/src/components/Modal/PasscodeVerify.tsx +++ b/src/components/Modal/PasscodeVerify.tsx @@ -76,21 +76,16 @@ function PasscodeVerifyModal({ }; const onPressNumber = (text) => { - let tmpPasscode = passcode; - if (passcode.length < 4) { - if (text !== 'x') { - tmpPasscode += text; - setPasscode(tmpPasscode); - } - } - if (passcode && text === 'x') { - setPasscode(passcode.slice(0, -1)); + if (text === 'x') { + setPasscode((current) => current.slice(0, -1)); setLoginError(false); + } else { + setPasscode((current) => (current.length < 4 ? current + text : current)); } }; - const onDeletePressed = (text) => { - setPasscode(passcode.slice(0, passcode.length - 1)); + const onDeletePressed = () => { + setPasscode((current) => current.slice(0, -1)); }; const disableCTA = () => { @@ -152,19 +147,17 @@ function PasscodeVerifyModal({ )} {/* */} - {passcode.length === 4 && ( - { - setBtnDisable(true); - setLoginError(false); - attemptLogin(passcode); - }} - primaryText={primaryText ? primaryText : common.proceed} - activeOpacity={0.5} - primaryDisable={btnDisable} - fullWidth - /> - )} + { + setBtnDisable(true); + setLoginError(false); + attemptLogin(passcode); + }} + primaryText={primaryText ? primaryText : common.proceed} + activeOpacity={0.5} + primaryDisable={btnDisable || passcode.length !== 4} + fullWidth + /> {/* keyboardview start */} diff --git a/src/context/Localization/language/en.json b/src/context/Localization/language/en.json index 962b29aee2..446ba2d6cb 100644 --- a/src/context/Localization/language/en.json +++ b/src/context/Localization/language/en.json @@ -803,6 +803,7 @@ "keeperVerified": "Keeper Verified Successfully", "SeedErrorToast": "Please fill in all seed word fields", "appRecoveredSuccessfulTitle": "App Recovered Successfully!", + "recoveryIncomplete": "Recovery could not be completed. Your backup may be unavailable or some data could not be restored. Please try again.", "appRecoveredSuccessfulSubTitle": "All your wallets and data about your vault has been recovered", "appRecoveredSuccessfulDesc": "The vault keys always stay within the signing devices and therefore do not have to be recovered", "mobileKey": "Mobile Key", @@ -2217,5 +2218,49 @@ "disclaimerPoint3": "Your messages are processed securely to help Ask Keeper respond.", "disclaimerLearnMore": "Learn more about Ask Keeper", "disclaimerCta": "Got it" + }, + "recoveryBackup": { + "title": "Assisted Server Backup", + "backUp": "Back Up Now", + "check": "Check Again", + "back": "Back", + "slow": "This is taking longer than usual. A slow connection or a large backup can take more time.", + "leave": "You can leave this screen. Return here to check the result. If the app closes, check again when you reopen it.", + "disabled": { + "title": "Backup is off", + "body": "Enable Assisted Server Backup in Backup and Recovery to use this check." + }, + "checking": { + "title": "Checking your backup", + "body": "Comparing your encrypted backup with the recovery data on this device." + }, + "different": { + "title": "Your backup needs updating", + "body": "Your Assisted Server Backup differs from this device. Back up now to update it, then Keeper will check that it matches." + }, + "preparing": { + "title": "Preparing your backup", + "body": "Preparing and encrypting the recovery data on this device." + }, + "uploading": { + "title": "Updating your backup", + "body": "Sending your encrypted backup to Keeper’s servers." + }, + "verifying": { + "title": "Verifying your backup", + "body": "Reading your backup back from the server and checking that the recovery data matches." + }, + "verified": { + "title": "Backup verified", + "body": "Your Assisted Server Backup matches the recovery data checked on this device. Keep your Recovery Key safe; you still need it for recovery." + }, + "conflict": { + "title": "Backup needs review", + "body": "The server backup contains recovery data that is missing or different on this device. Keeper has not replaced it. Check your other Keeper devices before making changes, then check again." + }, + "unverified": { + "title": "Backup not verified", + "body": "Keeper could not confirm that your backup matches. Your connection may have been interrupted, the backup may be too large, or data may have changed during the check. Check again before assuming the backup is complete." } -} \ No newline at end of file +} +} diff --git a/src/context/Localization/language/es.json b/src/context/Localization/language/es.json index a59ae5abda..8e95a7f68a 100644 --- a/src/context/Localization/language/es.json +++ b/src/context/Localization/language/es.json @@ -791,6 +791,7 @@ "keeperVerified": "Keeper Verified Successfully", "SeedErrorToast": "Please fill in all seed word fields", "appRecoveredSuccessfulTitle": "App Recovered Successfully!", + "recoveryIncomplete": "No se pudo completar la recuperación. Es posible que la copia de seguridad no esté disponible o que algunos datos no se hayan podido restaurar. Inténtalo de nuevo.", "appRecoveredSuccessfulSubTitle": "All your wallets and data about your vault has been recovered", "appRecoveredSuccessfulDesc": "The vault keys always stay within the signing devices and therefore do not have to be recovered", "mobileKey": "Mobile Key", @@ -2198,5 +2199,49 @@ "disclaimerPoint3": "Your messages are processed securely to help Ask Keeper respond.", "disclaimerLearnMore": "Learn more about Ask Keeper", "disclaimerCta": "Got it" + }, + "recoveryBackup": { + "title": "Copia de seguridad asistida", + "backUp": "Guardar ahora", + "check": "Volver a comprobar", + "back": "Atrás", + "slow": "Está tardando más de lo habitual. Una conexión lenta o una copia grande puede necesitar más tiempo.", + "leave": "Puedes salir de esta pantalla y volver para consultar el resultado. Si la aplicación se cierra, comprueba de nuevo al abrirla.", + "disabled": { + "title": "Copia desactivada", + "body": "Activa la copia de seguridad asistida en Copia de seguridad y recuperación para usar esta comprobación." + }, + "checking": { + "title": "Comprobando la copia", + "body": "Comparando tu copia cifrada con los datos de recuperación de este dispositivo." + }, + "different": { + "title": "Actualiza tu copia", + "body": "Tu copia de seguridad asistida difiere de este dispositivo. Guarda una copia ahora y Keeper comprobará que coincide." + }, + "preparing": { + "title": "Preparando la copia", + "body": "Preparando y cifrando los datos de recuperación de este dispositivo." + }, + "uploading": { + "title": "Actualizando la copia", + "body": "Enviando tu copia cifrada a los servidores de Keeper." + }, + "verifying": { + "title": "Verificando la copia", + "body": "Leyendo la copia del servidor y comprobando que los datos de recuperación coinciden." + }, + "verified": { + "title": "Copia verificada", + "body": "Tu copia de seguridad asistida coincide con los datos de recuperación comprobados en este dispositivo. Guarda tu clave de recuperación; sigue siendo necesaria para recuperar." + }, + "conflict": { + "title": "Revisa la copia", + "body": "El servidor contiene datos de recuperación que faltan o son diferentes en este dispositivo. Keeper no los ha reemplazado. Revisa tus otros dispositivos Keeper antes de hacer cambios y vuelve a comprobar." + }, + "unverified": { + "title": "Copia sin verificar", + "body": "Keeper no pudo confirmar que tu copia coincida. La conexión puede haberse interrumpido, la copia puede ser demasiado grande o los datos pueden haber cambiado. Comprueba de nuevo antes de dar la copia por completa." } -} \ No newline at end of file +} +} diff --git a/src/hooks/useSettingKeeper.tsx b/src/hooks/useSettingKeeper.tsx index d9242915b3..ae020d4cc8 100644 --- a/src/hooks/useSettingKeeper.tsx +++ b/src/hooks/useSettingKeeper.tsx @@ -262,7 +262,7 @@ export const useSettingKeeper = () => { title: settings.assistedServerBackup, description: settings.assistedServerBackupSubtitle, icon: , - onPress: debouncedAutomaticBackupToggle, + onPress: () => navigation.navigate('AssistedBackupStatus'), rightIcon: isOnL2Above ? ( ) : ( diff --git a/src/hooks/useUSDTWallets.ts b/src/hooks/useUSDTWallets.ts index dba1d6e868..12578e9f78 100644 --- a/src/hooks/useUSDTWallets.ts +++ b/src/hooks/useUSDTWallets.ts @@ -23,6 +23,9 @@ import { useDispatch } from 'react-redux'; import { useAppSelector } from 'src/store/hooks'; import { updateAppImage } from 'src/store/sagaActions/bhr'; import Relay from 'src/services/backend/Relay'; +import { canonical, recoveryContent } from 'src/services/backup/image'; +import { markBackupMutation } from 'src/services/backup/transport'; +import { invalidateBackupRepair, setPendingAllBackup } from 'src/store/reducers/bhr'; export interface UseUSDTWalletsOptions { getAll?: boolean; @@ -171,18 +174,45 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall /** * Update a wallet in the database */ - const updateWallet = useCallback(async (wallet: USDTWallet): Promise => { - try { - const { id, ...walletUpdateData } = wallet; - await dbManager.updateObjectById(RealmSchema.USDTWallet, wallet.id, walletUpdateData); // Remove the primary key 'id' from the update object to avoid Realm primary key change error + const updateWallet = useCallback( + async (wallet: USDTWallet): Promise => { + let recoveryChanged = false; + try { + const previous = dbManager.getObjectById(RealmSchema.USDTWallet, wallet.id); + if (!previous) throw new Error('Wallet not found'); + const previousWallet = previous.toJSON ? previous.toJSON() : previous; + recoveryChanged = + canonical(recoveryContent('wallets', previousWallet)) !== + canonical(recoveryContent('wallets', wallet)); + const { id, ...walletUpdateData } = wallet; + const updated = await dbManager.updateObjectById( + RealmSchema.USDTWallet, + id, + walletUpdateData + ); // Realm updates must omit the primary key. + if (!updated) throw new Error('Failed to update wallet'); - return true; - } catch (err) { - setError(err.message || 'Failed to update wallet'); - captureError(err); - return false; - } - }, []); + // Metadata and visibility must survive recovery. Balance/account refreshes + // are rebuildable caches and must not cause an upload on every sync. + if (recoveryChanged) + dispatch(updateAppImage({ wallets: [wallet], signers: null, updateNodes: false })); + + return true; + } catch (err) { + // The database helper can fail after partially writing fields. Do not + // upload the requested state or leave a previous verification trusted. + if (recoveryChanged) { + markBackupMutation(appId); + dispatch(invalidateBackupRepair(appId)); + dispatch(setPendingAllBackup(true)); + } + setError(err.message || 'Failed to update wallet'); + captureError(err); + return false; + } + }, + [appId, dispatch] + ); /** * Syncs a single wallet account status with latest data diff --git a/src/navigation/Navigator.tsx b/src/navigation/Navigator.tsx index d5ecfc5bbc..dd9327ee96 100644 --- a/src/navigation/Navigator.tsx +++ b/src/navigation/Navigator.tsx @@ -1,3 +1,4 @@ +import AssistedBackupStatus from 'src/screens/AppSettings/AssistedBackupStatus'; import { DefaultTheme, NavigationContainer } from '@react-navigation/native'; import React, { useContext, useRef } from 'react'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; @@ -263,6 +264,7 @@ function AppStack() { + diff --git a/src/navigation/types.ts b/src/navigation/types.ts index 3f71fa0806..1bf30f6349 100644 --- a/src/navigation/types.ts +++ b/src/navigation/types.ts @@ -155,6 +155,7 @@ export type AppStackParams = { }; ConfirmWalletDetails: undefined; AppBackupSettings: undefined; + AssistedBackupStatus: undefined; BuyBitcoin: undefined; DeleteKeys: undefined; HandleFile: undefined; diff --git a/src/screens/AppSettings/AssistedBackupStatus.tsx b/src/screens/AppSettings/AssistedBackupStatus.tsx new file mode 100644 index 0000000000..cdc54fc004 --- /dev/null +++ b/src/screens/AppSettings/AssistedBackupStatus.tsx @@ -0,0 +1,95 @@ +import React, { useContext, useEffect, useState } from 'react'; +import { ActivityIndicator, StyleSheet } from 'react-native'; +import { Box, ScrollView, useColorMode } from '@gluestack-ui/themed-native-base'; +import { useQuery } from '@realm/react'; +import { useNavigation } from '@react-navigation/native'; +import { RealmSchema } from 'src/storage/realm/enum'; +import { useAppDispatch, useAppSelector } from 'src/store/hooks'; +import { checkBackupFreshness, repairBackup } from 'src/store/sagaActions/bhr'; +import { LocalizationContext } from 'src/context/Localization/LocContext'; +import ScreenWrapper from 'src/components/ScreenWrapper'; +import WalletHeader from 'src/components/WalletHeader'; +import Buttons from 'src/components/Buttons'; +import Text from 'src/components/KeeperText'; +import { hp } from 'src/constants/responsive'; + +export default function AssistedBackupStatus() { + const { colorMode } = useColorMode(); + const navigation = useNavigation(); + const dispatch = useAppDispatch(); + const { recoveryBackup: copy } = useContext(LocalizationContext).translations; + const app = useQuery(RealmSchema.KeeperApp)[0] as any; + const id = app?.id as string; + const { + automaticCloudBackup, + backupRepairStateByAppId = {}, + backupRepairRunningByAppId = {}, + } = useAppSelector((state) => state.bhr); + const phase = backupRepairStateByAppId[id]; + const running = !!backupRepairRunningByAppId[id]; + const [slow, setSlow] = useState(false); + useEffect(() => { + if (automaticCloudBackup) dispatch(checkBackupFreshness()); + }, [id]); + useEffect(() => { + setSlow(false); + if (!running) return undefined; + const timer = setTimeout(() => setSlow(true), 10_000); + return () => clearTimeout(timer); + }, [running, phase]); + const state = !automaticCloudBackup + ? 'disabled' + : !running && ['checking', 'preparing', 'uploading', 'verifying'].includes(phase) + ? 'unverified' + : phase || 'unverified'; + return ( + + + + + + {copy[state].title} + + {running && } + + {copy[state].body} + + {slow && ( + + {copy.slow} + + )} + {running && ( + + {copy.leave} + + )} + + {!running && automaticCloudBackup && ( + + dispatch(state === 'different' ? repairBackup() : checkBackupFreshness()) + } + /> + )} + + navigation.goBack()} + /> + + + + ); +} +const styles = StyleSheet.create({ + content: { paddingVertical: hp(24) }, + card: { padding: 20, borderRadius: 16, marginBottom: hp(24) }, + title: { fontSize: 18, marginBottom: hp(16) }, + body: { fontSize: 14, marginTop: hp(12) }, +}); diff --git a/src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx b/src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx index 7ede2e2cde..f5a9ef668b 100644 --- a/src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx +++ b/src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx @@ -33,7 +33,7 @@ type KeeperApp = { export const ViewRecoveryKeyScreen = ({ navigation }) => { const { colorMode } = useColorMode(); - const { home: homeTxt, common, BackupWallet: backupTxt } = useContext(LocalizationContext).translations; + const { home: homeTxt, common, BackupWallet: backupTxt, recoveryBackup } = useContext(LocalizationContext).translations; const { primaryMnemonic, id: appId } = useQuery(RealmSchema.KeeperApp).map( getJSONFromRealmObject )[0] as KeeperApp; @@ -47,7 +47,7 @@ export const ViewRecoveryKeyScreen = ({ navigation }) => { const { showToast } = useToastMessage(); useEffect(() => { - if (backupAllSuccess || backupAllFailure) { + if (backupAllSuccess) { dispatch(setBackupAllSuccess(false)); dispatch(setBackupAllFailure(false)); dispatch(setAutomaticCloudBackup(true)); @@ -55,6 +55,11 @@ export const ViewRecoveryKeyScreen = ({ navigation }) => { showToast(backupTxt.recoveryKeyBackedUpSuccessfully, ); navigation.goBack(); } + if (backupAllFailure) { + dispatch(setBackupAllFailure(false)); + setLoader(false); + showToast(recoveryBackup.unverified.title); + } }, [backupAllSuccess, backupAllFailure]); const SeedCard = ({ item, index }: { item; index }) => { diff --git a/src/screens/Home/Notifications/NotificationsCenter.tsx b/src/screens/Home/Notifications/NotificationsCenter.tsx index 26abf067b2..efcca03f94 100644 --- a/src/screens/Home/Notifications/NotificationsCenter.tsx +++ b/src/screens/Home/Notifications/NotificationsCenter.tsx @@ -35,7 +35,6 @@ import { useAppSelector } from 'src/store/hooks'; import { cachedTxSnapshot } from 'src/store/reducers/cachedTxn'; import UAIView from '../components/UAIView'; import { setStateFromSnapshot } from 'src/store/reducers/send_and_receive'; -import { backupAllSignersAndVaults } from 'src/store/sagaActions/bhr'; import { LocalizationContext } from 'src/context/Localization/LocContext'; import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg'; import Fonts from 'src/constants/Fonts'; @@ -298,7 +297,7 @@ const Card = memo(({ uai }: CardProps) => { text: common.View, cta: () => { dispatch(uaiActioned({ uaiId: uai.id, action: false })); - dispatch(backupAllSignersAndVaults()); + navigtaion.navigate('AssistedBackupStatus'); }, }, }, diff --git a/src/screens/LoginScreen/CreatePin.tsx b/src/screens/LoginScreen/CreatePin.tsx index 853336524a..cfa93415a5 100644 --- a/src/screens/LoginScreen/CreatePin.tsx +++ b/src/screens/LoginScreen/CreatePin.tsx @@ -16,7 +16,6 @@ import BiometricIcon from 'src/assets/images/biometric-icon.svg'; import { changeLoginMethod, storeCreds, switchCredsChanged } from 'src/store/sagaActions/login'; import KeeperModal from 'src/components/KeeperModal'; import { setIsInitialLogin } from 'src/store/reducers/login'; -import { throttle } from 'src/utils/utilities'; import Buttons from 'src/components/Buttons'; import PinDotView from 'src/components/AppPinInput/PinDotView'; import ReactNativeBiometrics from 'react-native-biometrics'; @@ -83,7 +82,7 @@ export default function CreatePin(props) { } }, [credsChanged]); - const onPressNumber = throttle((text) => { + const onPressNumber = (text) => { setPinState((currentState) => { const currentLength = currentState.value.length; @@ -104,9 +103,9 @@ export default function CreatePin(props) { return currentState; }); - }, 300); + }; - const onDeletePressed = throttle(() => { + const onDeletePressed = () => { setPinState((currentState) => { const currentLength = currentState.value.length; @@ -123,7 +122,7 @@ export default function CreatePin(props) { stage: currentLength <= 5 ? PasscodeStages.CREATE : PasscodeStages.CONFIRM, }; }); - }, 300); + }; const handleNext = () => { dispatch(setIsInitialLogin(true)); diff --git a/src/screens/LoginScreen/Login.tsx b/src/screens/LoginScreen/Login.tsx index 40353f905d..862b39879d 100644 --- a/src/screens/LoginScreen/Login.tsx +++ b/src/screens/LoginScreen/Login.tsx @@ -209,21 +209,16 @@ function LoginScreen({ navigation, route }) { }; const onPressNumber = (text) => { - let tmpPasscode = passcode; - if (passcode.length < 4) { - if (text !== 'x') { - tmpPasscode += text; - setPasscode(tmpPasscode); - } - } - if (passcode && text === 'x') { - setPasscode(passcode.slice(0, -1)); + if (text === 'x') { + setPasscode((current) => current.slice(0, -1)); setLoginError(false); + } else { + setPasscode((current) => (current.length < 4 ? current + text : current)); } }; - const onDeletePressed = (text) => { - setPasscode(passcode.slice(0, passcode.length - 1)); + const onDeletePressed = () => { + setPasscode((current) => current.slice(0, -1)); }; useEffect(() => { diff --git a/src/screens/Recovery/EnterSeedScreen.tsx b/src/screens/Recovery/EnterSeedScreen.tsx index ecace068df..b133caf23a 100644 --- a/src/screens/Recovery/EnterSeedScreen.tsx +++ b/src/screens/Recovery/EnterSeedScreen.tsx @@ -1,5 +1,12 @@ import * as bip39 from 'bip39'; -import { Box, Input, Pressable, ScrollView, View, useColorMode } from '@gluestack-ui/themed-native-base'; +import { + Box, + Input, + Pressable, + ScrollView, + View, + useColorMode, +} from '@gluestack-ui/themed-native-base'; import { Keyboard, KeyboardAvoidingView, Platform, StyleSheet } from 'react-native'; import React, { useCallback, useContext, useEffect, useRef, useState } from 'react'; import { hp, wp } from 'src/constants/responsive'; @@ -130,7 +137,13 @@ function EnterSeedScreen({ route, navigation }) { dispatch(setAppImageError('')); setRecoveryLoading(false); setShowNetworkModal(true); - } else openInvalidSeedsModal(); + } else if (appImageError === 'Invalid mnemonic') { + openInvalidSeedsModal(); + } else { + setRecoveryLoading(false); + showToast(seed.recoveryIncomplete, ); + dispatch(setAppImageError('')); + } } }, [appImageError]); diff --git a/src/screens/SeedScreens/ExportSeedScreen.tsx b/src/screens/SeedScreens/ExportSeedScreen.tsx index bb2ec226a5..447e6c1741 100644 --- a/src/screens/SeedScreens/ExportSeedScreen.tsx +++ b/src/screens/SeedScreens/ExportSeedScreen.tsx @@ -107,13 +107,17 @@ function ExportSeedScreen({ route, navigation }) { }, [backupMethod]); useEffect(() => { - if (backupAllSuccess || backupAllFailure) { + if (backupAllSuccess) { if (!automaticCloudBackup) setAsbEnabled(true); dispatch(setBackupAllSuccess(false)); dispatch(setBackupAllFailure(false)); dispatch(setAutomaticCloudBackup(true)); setBackupSuccessModal(true); } + if (backupAllFailure) { + dispatch(setBackupAllFailure(false)); + showToast(translations.recoveryBackup.unverified.title); + } }, [backupAllSuccess, backupAllFailure]); diff --git a/src/screens/Vault/ResetEmergencyKey.tsx b/src/screens/Vault/ResetEmergencyKey.tsx index 838e055488..9233607be2 100644 --- a/src/screens/Vault/ResetEmergencyKey.tsx +++ b/src/screens/Vault/ResetEmergencyKey.tsx @@ -33,7 +33,7 @@ import { isVaultUsingBlockHeightTimelock } from 'src/services/wallets/factories/ function ResetEmergencyKey({ route }) { const { inheritanceKeys = [], - initialTimelockDuration = 0, + initialTimelockDuration, vault, }: { inheritanceKeys; initialTimelockDuration; vault: Vault } = route.params; const { colorMode } = useColorMode(); @@ -257,7 +257,7 @@ function ResetEmergencyKey({ route }) { key: signer, duration: selectedOptions[getKeyUID(signer)]?.label, }))} - initialTimelockDuration={initialTimelockDuration ?? 0} + initialTimelockDuration={initialTimelockDuration} currentBlockHeight={currentBlockHeight} miniscriptTypes={vault.scheme.miniscriptScheme.usedMiniscriptTypes} /> diff --git a/src/screens/Vault/ResetInheritanceKey.tsx b/src/screens/Vault/ResetInheritanceKey.tsx index 72e0b55046..23f7fb67a7 100644 --- a/src/screens/Vault/ResetInheritanceKey.tsx +++ b/src/screens/Vault/ResetInheritanceKey.tsx @@ -236,6 +236,7 @@ function ResetInheritanceKey({ route }) { CommonActions.navigate({ name: 'ResetEmergencyKey', params: { + initialTimelockDuration, inheritanceKeys: inheritanceSigners.map((signer) => ({ key: signer, duration: selectedOptions[getKeyUID(signer)]?.label, @@ -265,7 +266,7 @@ function ResetInheritanceKey({ route }) { key: signer, duration: selectedOptions[getKeyUID(signer)]?.label, }))} - initialTimelockDuration={initialTimelockDuration ?? 0} + initialTimelockDuration={initialTimelockDuration} currentBlockHeight={currentBlockHeight} miniscriptTypes={vault.scheme.miniscriptScheme.usedMiniscriptTypes} /> diff --git a/src/screens/Vault/VaultMigrationController.tsx b/src/screens/Vault/VaultMigrationController.tsx index bfb688e194..66736912d3 100644 --- a/src/screens/Vault/VaultMigrationController.tsx +++ b/src/screens/Vault/VaultMigrationController.tsx @@ -1,3 +1,4 @@ +import { resolveInitialTimelock } from 'src/services/wallets/operations/miniscript/initialTimelock'; import { CommonActions, useNavigation, useFocusEffect } from '@react-navigation/native'; import React, { useEffect, useState, useRef, useCallback, useContext } from 'react'; import { @@ -375,7 +376,11 @@ function VaultMigrationController({ return; } - let initialTimelock = 0; + const initialTimelock = resolveInitialTimelock( + miniscriptTypes, + initialTimelockDuration, + (label) => getTimelockDuration(label, bitcoinNetworkType) + ); const multisigScriptType = MultisigScriptType.MINISCRIPT_MULTISIG; // let currentSyncedBlockHeight = currentBlockHeight; @@ -396,14 +401,6 @@ function VaultMigrationController({ // } // } - if (initialTimelockDuration) { - initialTimelock = getTimelockDuration(initialTimelockDuration, bitcoinNetworkType); - if (!initialTimelock) { - showToast('Failed to determine initial timelock duration', ); - return; - } - } - const inheritanceSignerWithTimelocks = []; const emergencySignerWithTimelocks = []; diff --git a/src/services/backend/Relay.ts b/src/services/backend/Relay.ts index 8a35b6ae26..d9a33502ad 100644 --- a/src/services/backend/Relay.ts +++ b/src/services/backend/Relay.ts @@ -1,3 +1,4 @@ +import { backupPost } from '../backup/transport'; import { NetworkType } from 'src/services/wallets/enums'; import { SubScriptionPlan } from 'src/models/interfaces/Subscription'; import { @@ -106,16 +107,25 @@ export default class Relay { return res.data || res.json; }; - public static updateAppImage = async ( - appImage - ): Promise<{ + public static updateAppImage = async (appImage: { + appId: string; + publicId?: string; + walletsObject?: Record; + signersObject?: Record; + networkType?: string; + subscription?: string; + version?: string; + nodes?: string[]; + // Required to clear nodes: older clients send [] for unrelated updates. + replaceNodes?: boolean; + }): Promise<{ status: string; updated: boolean; err?: string; message?: string; }> => { try { - const res = await RestClient.post(`${RELAY}updateAppImage`, appImage); + const res = await backupPost(`${RELAY}updateAppImage`, appImage); const data = res.data || res.json; return data; } catch (err) { @@ -150,7 +160,7 @@ export default class Relay { message?: string; }> => { try { - const res = await RestClient.post(`${RELAY}deleteAppImageEntity`, entityList); + const res = await backupPost(`${RELAY}deleteAppImageEntity`, entityList); const data = res.data || res.json; return data; } catch (err) { @@ -168,7 +178,7 @@ export default class Relay { message?: string; }> => { try { - const res = await RestClient.post(`${RELAY}deleteVaults`, entityList); + const res = await backupPost(`${RELAY}deleteVaults`, entityList); const data = res.data || res.json; return data; } catch (err) { @@ -188,7 +198,7 @@ export default class Relay { message?: string; }> => { try { - const res = await RestClient.post(`${RELAY}updateVaultImage`, vaultData); + const res = await backupPost(`${RELAY}updateVaultImage`, vaultData); const data = res.data || res.json; return data; } catch (err) { @@ -275,7 +285,7 @@ export default class Relay { updated: boolean; }> => { try { - const res = (await RestClient.post(`${RELAY}modifyLabels`, { + const res = (await backupPost(`${RELAY}modifyLabels`, { appId, addLabels, deleteLabels, @@ -429,6 +439,7 @@ export default class Relay { public static backupAllSignersAndVaults = async ( allData ): Promise<{ + updated?: boolean; status?: number; data?: { updated: boolean; @@ -437,7 +448,7 @@ export default class Relay { message?: string; }> => { try { - const res = await RestClient.post(`${RELAY}backupAllSignersAndVaults`, allData); + const res = await backupPost(`${RELAY}backupAllSignersAndVaults`, allData); const data = res.data || res.json; return data; } catch (err) { @@ -482,7 +493,7 @@ export default class Relay { message?: string; }> => { try { - const res = await RestClient.post(`${RELAY}deleteBackup`, body); + const res = await backupPost(`${RELAY}deleteBackup`, body); const data = res.data || res.json; return data; } catch (err) { @@ -804,4 +815,3 @@ export default class Relay { } }; } - diff --git a/src/services/backup/image.ts b/src/services/backup/image.ts new file mode 100644 index 0000000000..1ef9342ddd --- /dev/null +++ b/src/services/backup/image.ts @@ -0,0 +1,269 @@ +/* eslint-disable no-await-in-loop -- Sequential work bounds memory and yields to the mobile UI. */ +import cryptoJS from 'crypto-js'; +import { decrypt, encrypt } from 'src/utils/service-utilities/encryption'; + +export type BackupImage = Record< + 'wallets' | 'signers' | 'vaults' | 'nodes' | 'labels', + Record +>; +export type BackupComparison = 'matched' | 'different' | 'conflict'; +export const pauseBackup = () => + new Promise((resolve) => { + setTimeout(resolve, 0); + }); +// Conservative local guard below the relay's 50 MB body limit. Native capacity +// testing is still required; never truncate a backup to satisfy these guards. +export const MAX_RECORD_BYTES = 8 * 1024 * 1024; +export const MAX_BACKUP_BYTES = 32 * 1024 * 1024; + +export function canonical(value: any): string { + if (value === undefined) return 'null'; + if (value === null || typeof value !== 'object') return JSON.stringify(value); + if (value instanceof Date) return JSON.stringify(value.toISOString()); + if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`; + return `{${Object.keys(value) + .filter((key) => value[key] !== undefined) + .sort() + .map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`) + .join(',')}}`; +} + +export function recoveryContent(kind: keyof BackupImage, record: any) { + if (kind === 'nodes') return { ...record, isConnected: false }; + if (kind !== 'wallets' && kind !== 'vaults') return record; + // Chain caches can be rebuilt. Keep keys, derivation, counters, policies, + // archive state and user metadata in the comparison. + const result = { ...record }; + delete result.receivingAddress; + delete result.accountStatus; + const specs = { ...record.specs }; + // Manual coin-control choices cannot be reconstructed from the chain. Compare + // them by outpoint, independent of confirmation state or UTXO/cache ordering. + // The encrypted record still retains the original UTXOs for existing restore + // and refresh code to reapply each choice after syncing with the node. + const manualCoinChoices: Record = {}; + for (const utxo of [ + ...(record.specs?.confirmedUTXOs || []), + ...(record.specs?.unconfirmedUTXOs || []), + ]) { + if (utxo.isManualOverride) manualCoinChoices[`${utxo.txId}:${utxo.vout}`] = utxo.spendability; + } + for (const field of [ + 'balances', + 'balance', + 'transactions', + 'confirmedUTXOs', + 'unconfirmedUTXOs', + 'addresses', + 'addressPubs', + 'receivingAddress', + 'hasNewUpdates', + 'lastSynched', + ]) + delete specs[field]; + specs.manualCoinChoices = manualCoinChoices; + return { ...result, specs }; +} + +function identity(kind: keyof BackupImage, record: any) { + if (kind === 'wallets') + return { + networkType: record.networkType, + type: record.type, + entityKind: record.entityKind, + derivationDetails: record.derivationDetails, + scriptType: record.scriptType, + xpub: record.specs?.xpub, + xpriv: record.specs?.xpriv, + address: record.specs?.address, + privateKey: record.specs?.privateKey, + }; + if (kind === 'vaults') + return { + networkType: record.networkType, + scheme: record.scheme, + signers: record.signers, + scriptType: record.scriptType, + }; + if (kind === 'signers') + return { + masterFingerprint: record.masterFingerprint, + signerXpubs: record.signerXpubs, + networkType: record.networkType, + type: record.type, + }; + return null; +} + +export async function compareImages( + local: BackupImage, + remote: BackupImage, + checkpoint = () => {} +): Promise { + let result: BackupComparison = 'matched'; + for (const kind of Object.keys(local) as (keyof BackupImage)[]) { + for (const [id, record] of Object.entries(remote[kind])) { + checkpoint(); + const current = local[kind][id]; + if (!current || canonical(identity(kind, current)) !== canonical(identity(kind, record))) + return 'conflict'; + for (const counter of [ + 'nextFreeAddressIndex', + 'nextFreeChangeAddressIndex', + 'totalExternalAddresses', + ]) { + if ((record.specs?.[counter] || 0) > (current.specs?.[counter] || 0)) return 'conflict'; + } + } + for (const [id, record] of Object.entries(local[kind])) { + checkpoint(); + if ( + !remote[kind][id] || + canonical(recoveryContent(kind, record)) !== + canonical(recoveryContent(kind, remote[kind][id])) + ) + result = 'different'; + await pauseBackup(); + } + } + return result; +} + +// Preserve the existing CryptoJS/OpenSSL wire format. Chunk the expensive AES +// work so a large wallet does not monopolize the JS thread for the whole cipher. +export async function encryptRecord(key: string, record: any): Promise { + const text = JSON.stringify(record); + if (text.length * 3 > MAX_RECORD_BYTES) throw new Error('Backup record exceeds supported size'); + if (text.length < 16_384) { + await pauseBackup(); + return encrypt(key, text); + } + const salt = cryptoJS.lib.WordArray.random(8); + const derived = cryptoJS.kdf.OpenSSL.execute(key, 8, 4, salt); + const cipher = cryptoJS.algo.AES.createEncryptor(derived.key, { iv: derived.iv }); + const output = cryptoJS.lib.WordArray.create(); + for (let offset = 0; offset < text.length; ) { + let end = Math.min(offset + 16_384, text.length); + if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1])) end--; + output.concat(cipher.process(text.slice(offset, end))); + offset = end; + await pauseBackup(); + } + output.concat(cipher.finalize()); + return cryptoJS.format.OpenSSL.stringify( + cryptoJS.lib.CipherParams.create({ ciphertext: output, salt }) + ); +} + +export async function decryptRecord(key: string, value: unknown) { + if (typeof value !== 'string' || value.length > MAX_RECORD_BYTES * 2) + throw new Error('Invalid backup record'); + // Parsing/format decoding still require native performance validation at the + // supported size ceiling. Yield before and after each record. + await pauseBackup(); + let text: string; + if (value.length < 16_384) text = decrypt(key, value); + else { + const params = cryptoJS.format.OpenSSL.parse(value); + if (!params.salt) throw new Error('Missing backup encryption salt'); + const derived = cryptoJS.kdf.OpenSSL.execute(key, 8, 4, params.salt); + const decipher = cryptoJS.algo.AES.createDecryptor(derived.key, { iv: derived.iv }); + const output = cryptoJS.lib.WordArray.create(); + const data = params.ciphertext; + for (let offset = 0; offset < data.words.length; offset += 4096) { + const bytes = Math.min(4096 * 4, data.sigBytes - offset * 4); + output.concat( + decipher.process( + cryptoJS.lib.WordArray.create(data.words.slice(offset, offset + 4096), bytes) + ) + ); + await pauseBackup(); + } + output.concat(decipher.finalize()); + text = output.toString(cryptoJS.enc.Utf8); + } + const record = JSON.parse(text); + if (!record || typeof record !== 'object' || Array.isArray(record)) + throw new Error('Invalid backup record'); + await pauseBackup(); + return record; +} + +export async function decodeImage( + key: string, + response: any, + appId: string, + checkpoint = () => {} +): Promise { + const app = response?.appImage; + if ( + !app || + app.appId !== appId || + !app.wallets || + !app.signers || + !Array.isArray(app.nodes) || + !Array.isArray(response.allVaultImages) || + !Array.isArray(response.labels) + ) + throw new Error('Incomplete backup response'); + const checkReferences = (expected: unknown, actual: unknown[]) => { + if (expected === undefined) return; // Legacy backups can omit reference lists. + if ( + !Array.isArray(expected) || + expected.length !== actual.length || + new Set(expected).size !== expected.length || + new Set(actual).size !== actual.length || + actual.some((id) => typeof id !== 'string' || !expected.includes(id)) + ) + throw new Error('Incomplete backup references'); + }; + checkReferences( + app.vaults, + response.allVaultImages.map((record) => record?.vaultId) + ); + checkReferences( + app.labels, + response.labels.map((record) => record?.id) + ); + const image: BackupImage = { wallets: {}, signers: {}, vaults: {}, nodes: {}, labels: {} }; + let totalBytes = 0; + const decode = async (value: unknown) => { + checkpoint(); + if (typeof value !== 'string') throw new Error('Invalid backup record'); + totalBytes += value.length; + if (totalBytes > MAX_BACKUP_BYTES) throw new Error('Backup exceeds supported size'); + return decryptRecord(key, value); + }; + const add = (kind: keyof BackupImage, id: string, record: any) => { + if (!id || image[kind][id]) throw new Error('Duplicate or unidentified backup record'); + image[kind][id] = record; + }; + for (const value of Object.values(app.wallets)) { + const record = await decode(value); + add('wallets', record.id, record); + } + for (const [id, value] of Object.entries(app.signers)) { + const record = await decode(value); + add('signers', id, record); + } + for (const value of response.allVaultImages) { + const record = await decode(value?.vault); + if (value.vaultId !== undefined && value.vaultId !== record.id) + throw new Error('Vault backup identity mismatch'); + add('vaults', record.id, record); + } + for (const value of app.nodes) { + const record = await decode(value); + add('nodes', record.id || canonical(recoveryContent('nodes', record)), record); + } + for (const value of response.labels) { + const record = await decode(value?.content); + add('labels', record.id, record); + } + // A partial relay response must never look like an empty backup. + if (Array.isArray(app.vaults) && app.vaults.length !== Object.keys(image.vaults).length) + throw new Error('Incomplete vault backup'); + if (Array.isArray(app.labels) && app.labels.length !== Object.keys(image.labels).length) + throw new Error('Incomplete label backup'); + return image; +} diff --git a/src/services/backup/repair.ts b/src/services/backup/repair.ts new file mode 100644 index 0000000000..afb8d67947 --- /dev/null +++ b/src/services/backup/repair.ts @@ -0,0 +1,238 @@ +/* eslint-disable no-await-in-loop -- Serialize backup records to bound memory and yield to the UI. */ +import dbManager from 'src/storage/realm/dbManager'; +import { RealmSchema } from 'src/storage/realm/enum'; +import config from 'src/utils/service-utilities/config'; +import { generateEncryptionKey, hash256 } from 'src/utils/service-utilities/encryption'; +import { + getKeyUID, + sanitizeSeedKeyForBackup, + sanitizeVaultSignersForSeedKeyBackup, +} from 'src/utils/utilities'; +import { + BACKUP_DEADLINE_MS, + backupRevision, + boundedBackupPost, + withBackupSession, +} from './transport'; +import { + BackupImage, + canonical, + compareImages, + decodeImage, + encryptRecord, + MAX_BACKUP_BYTES, + MAX_RECORD_BYTES, + pauseBackup, + recoveryContent, +} from './image'; + +export type RepairPhase = + | 'checking' + | 'different' + | 'preparing' + | 'uploading' + | 'verifying' + | 'verified' + | 'conflict' + | 'unverified'; +const inFlight = new Map< + string, + { + repair: boolean; + promise: Promise; + listeners: Set<(phase: RepairPhase) => void>; + phase?: RepairPhase; + } +>(); +const clone = (value: any) => JSON.parse(JSON.stringify(value)); + +export async function captureBackupImage(checkpoint = () => {}): Promise { + const image: BackupImage = { wallets: {}, signers: {}, vaults: {}, nodes: {}, labels: {} }; + const sources: [keyof BackupImage, RealmSchema][] = [ + ['wallets', RealmSchema.Wallet], + ['wallets', RealmSchema.USDTWallet], + ['signers', RealmSchema.Signer], + ['vaults', RealmSchema.Vault], + ['nodes', RealmSchema.NodeConnect], + ['labels', RealmSchema.Tags], + ]; + for (const [kind, schema] of sources) { + const records = dbManager.getObjectByIndex(schema, null, true) as any; + for (const value of records) { + checkpoint(); + const text = JSON.stringify(value); + if (text.length * 3 > MAX_RECORD_BYTES) + throw new Error('Backup record exceeds supported size'); + const raw = JSON.parse(text); + const record = + kind === 'signers' + ? sanitizeSeedKeyForBackup(raw) + : kind === 'vaults' + ? sanitizeVaultSignersForSeedKeyBackup(raw) + : kind === 'nodes' + ? { ...raw, isConnected: false } + : raw; + const id = + kind === 'signers' + ? getKeyUID(record) + : record.id || canonical(recoveryContent(kind, record)); + if (image[kind][id]) throw new Error('Duplicate local backup record'); + image[kind][id] = record; + await pauseBackup(); + } + } + return image; +} + +async function encodeImage(app: any, image: BackupImage, checkpoint = () => {}) { + const key = generateEncryptionKey(app.primarySeed); + const payload = { + appId: app.id, + publicId: app.publicId, + subscription: JSON.stringify(app.subscription), + networkType: app.networkType, + version: app.version, + walletObject: {}, + signersObject: {}, + vaultObject: {}, + nodes: [], + labels: [], + }; + let size = 0; + for (const kind of Object.keys(image) as (keyof BackupImage)[]) { + for (const [id, record] of Object.entries(image[kind])) { + checkpoint(); + const encrypted = await encryptRecord(key, record); + size += encrypted.length; + if (size > MAX_BACKUP_BYTES) throw new Error('Backup exceeds supported size'); + if (kind === 'wallets') payload.walletObject[id] = encrypted; + if (kind === 'signers') payload.signersObject[id] = encrypted; + if (kind === 'vaults') + payload.vaultObject[id] = { + vaultId: id, + vault: encrypted, + isArchived: !!record.archived, + scheme: record.scheme, + signersData: record.signers.map((signer) => ({ + signerId: getKeyUID(signer), + xfpHash: hash256(signer.masterFingerprint), + })), + }; + if (kind === 'nodes') payload.nodes.push(encrypted); + if (kind === 'labels') + payload.labels.push({ id: hash256(hash256(key + id)), content: encrypted }); + } + } + return payload; +} + +// Read-only checks never upload. A repair rechecks immediately before writing. +// Session ownership extends through readback; incremental writes wait, and their +// revision invalidates a concurrent repair's completion claim. +export function inspectBackup( + appId: string, + repair: boolean, + onPhase: (phase: RepairPhase) => void +): Promise { + const running = inFlight.get(appId); + if (running) { + if (repair && !running.repair) + return running.promise.then(() => inspectBackup(appId, true, onPhase)); + running.listeners.add(onPhase); + if (running.phase) onPhase(running.phase); + return running.promise; + } + const listeners = new Set([onPhase]); + const notify = (phase: RepairPhase) => { + const active = inFlight.get(appId); + if (active) active.phase = phase; + listeners.forEach((listener) => listener(phase)); + }; + const result = withBackupSession(appId, async () => { + const deadline = Date.now() + BACKUP_DEADLINE_MS; + const revision = backupRevision(appId); + const assertCurrent = () => { + if ( + Date.now() >= deadline || + (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id !== appId || + backupRevision(appId) !== revision + ) + throw new Error('Backup changed during check'); + }; + try { + notify('checking'); + const app = clone(dbManager.getObjectByIndex(RealmSchema.KeeperApp)); + assertCurrent(); + const key = generateEncryptionKey(app.primarySeed); + const local = await captureBackupImage(assertCurrent); + assertCurrent(); + let expectedRevision: string; + const read = async () => { + const response = await boundedBackupPost( + `${config.RELAY}getBackupSnapshot`, + { appId }, + deadline + ); + assertCurrent(); + if (!/^[a-f0-9]{64}$/.test(response.data?.revision)) + throw new Error('Backup snapshot revision unavailable'); + expectedRevision = response.data.revision; + return decodeImage(key, response.data, appId, assertCurrent); + }; + const remote = await read(); + const comparison = await compareImages(local, remote, assertCurrent); + assertCurrent(); + if (comparison === 'conflict') { + notify('conflict'); + return 'conflict'; + } + if (comparison === 'different' && !repair) { + notify('different'); + return 'different'; + } + if (comparison === 'different') { + notify('preparing'); + const payload = await encodeImage(app, local, assertCurrent); + assertCurrent(); + // Local Realm may change without a relay call (e.g. address generation). + if ( + (await compareImages(local, await captureBackupImage(assertCurrent), assertCurrent)) !== + 'matched' + ) + throw new Error('Local backup changed'); + assertCurrent(); + notify('uploading'); + try { + const response = await boundedBackupPost( + `${config.RELAY}repairAppBackup`, + { ...payload, expectedRevision }, + deadline + ); + if (response.data?.updated !== true) throw new Error('Backup rejected'); + } catch { + // A lost response is not proof the upload failed. Always read back. + } + notify('verifying'); + if ((await compareImages(local, await read(), assertCurrent)) !== 'matched') + throw new Error('Backup not verified'); + } + if ( + (await compareImages(local, await captureBackupImage(assertCurrent), assertCurrent)) !== + 'matched' + ) + throw new Error('Local backup changed'); + assertCurrent(); + notify('verified'); + return 'verified'; + } catch { + notify('unverified'); + return 'unverified'; + } + }); + inFlight.set(appId, { repair, promise: result, listeners }); + const clean = () => { + if (inFlight.get(appId)?.promise === result) inFlight.delete(appId); + }; + result.then(clean, clean); + return result; +} diff --git a/src/services/backup/restore.ts b/src/services/backup/restore.ts new file mode 100644 index 0000000000..80a7b8bdf7 --- /dev/null +++ b/src/services/backup/restore.ts @@ -0,0 +1,27 @@ +import { decodeImage } from './image'; + +// Decode every record before changing Realm. Older backups may omit collections +// introduced later; an unreadable response or a missing referenced record is not +// an empty backup and must never trigger successful partial recovery. +export async function prepareRecoveryImage( + encryptionKey: string, + appId: string, + appImage: any, + allVaultImages: any[], + labels: any[] +) { + if (!appImage || appImage.appId !== appId) throw new Error('Recovery data unavailable'); + return decodeImage( + encryptionKey, + { + appImage: { + ...appImage, + signers: appImage.signers === undefined ? {} : appImage.signers, + nodes: appImage.nodes === undefined ? [] : appImage.nodes, + }, + allVaultImages, + labels, + }, + appId + ); +} diff --git a/src/services/backup/transport.ts b/src/services/backup/transport.ts new file mode 100644 index 0000000000..21339041ec --- /dev/null +++ b/src/services/backup/transport.ts @@ -0,0 +1,71 @@ +import RestClient from '../rest/RestClient'; + +// One queue per account covers repair, incremental writes, labels and deletion. +const queues = new Map>(); +const revisions = new Map(); +export const backupRevision = (id: string) => revisions.get(id) || 0; +export const markBackupMutation = (id: string) => revisions.set(id, backupRevision(id) + 1); +export const BACKUP_STALL_MS = 30_000; +export const BACKUP_DEADLINE_MS = 10 * 60_000; + +export function withBackupSession(id: string, work: () => Promise): Promise { + const previous = queues.get(id) || Promise.resolve(); + const result = previous.catch(() => undefined).then(work); + queues.set(id, result); + const clean = () => { + if (queues.get(id) === result) queues.delete(id); + }; + result.then(clean, clean); + return result; +} + +// Abort the actual transport, not just the saga waiting on it. A stalled upload +// has an unknown outcome; callers must read back before deciding to upload again. +export async function boundedBackupPost( + path: string, + body: object, + deadline = Date.now() + BACKUP_DEADLINE_MS +) { + const controller = new AbortController(); + let idle: ReturnType; + let uploaded = 0; + let downloaded = 0; + const resetIdle = () => { + clearTimeout(idle); + idle = setTimeout(() => controller.abort(), BACKUP_STALL_MS); + }; + const remaining = deadline - Date.now(); + if (remaining <= 0) throw new Error('Backup deadline exceeded'); + const total = setTimeout(() => controller.abort(), remaining); + resetIdle(); + try { + return await RestClient.post(path, body, undefined, { + signal: controller.signal, + onUploadProgress: ({ loaded }) => { + if (loaded > uploaded) { + uploaded = loaded; + resetIdle(); + } + }, + onDownloadProgress: ({ loaded }) => { + if (loaded > downloaded) { + downloaded = loaded; + resetIdle(); + } + }, + }); + } catch { + // Do not propagate Axios errors: they can contain request bodies and headers. + throw new Error('Backup request could not be completed'); + } finally { + clearTimeout(idle); + clearTimeout(total); + } +} + +export function backupPost(path: string, body: any) { + const appId = body.appId || body.appID; + if (!appId) return Promise.reject(new Error('Missing backup account')); + markBackupMutation(appId); + return withBackupSession(appId, () => boundedBackupPost(path, body)); +} diff --git a/src/services/rest/RestClient.ts b/src/services/rest/RestClient.ts index 456df553f4..e505ec76f1 100644 --- a/src/services/rest/RestClient.ts +++ b/src/services/rest/RestClient.ts @@ -1,4 +1,4 @@ -import axios, { AxiosResponse } from 'axios'; +import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; import DeviceInfo from 'react-native-device-info'; import { Platform } from 'react-native'; @@ -61,8 +61,14 @@ class RestClient { return RestClient.torStatus; } - async post(path: string, body: object, headers?: object): Promise { + async post( + path: string, + body: object, + headers?: object, + options?: AxiosRequestConfig + ): Promise { return axios.post(path, body, { + ...options, headers: { ...RestClient.headers, ...headers, diff --git a/src/services/wallets/operations/miniscript/initialTimelock.ts b/src/services/wallets/operations/miniscript/initialTimelock.ts new file mode 100644 index 0000000000..ab742181de --- /dev/null +++ b/src/services/wallets/operations/miniscript/initialTimelock.ts @@ -0,0 +1,20 @@ +import { MiniscriptTypes } from 'src/services/wallets/enums'; + +/** Reject a lost duration before generating any replacement policy. */ +export function resolveInitialTimelock( + types: MiniscriptTypes[], + selectedDuration: string | number | null | undefined, + durationForLabel: (label: string) => number | undefined +): number { + const required = types.includes(MiniscriptTypes.TIMELOCKED); + const absent = selectedDuration == null || selectedDuration === '' || selectedDuration === 0; + if (absent && !required) return 0; + if (absent || typeof selectedDuration !== 'string') { + throw new Error('Failed to determine initial timelock duration'); + } + const duration = durationForLabel(selectedDuration); + if (typeof duration !== 'number' || !Number.isSafeInteger(duration) || duration <= 0) { + throw new Error('Failed to determine initial timelock duration'); + } + return duration; +} diff --git a/src/store/reducers/bhr.ts b/src/store/reducers/bhr.ts index fa6788d752..dcd6edd455 100644 --- a/src/store/reducers/bhr.ts +++ b/src/store/reducers/bhr.ts @@ -1,3 +1,4 @@ +import { RepairPhase } from 'src/services/backup/repair'; import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { BackupType, homeToastMessageType } from 'src/models/enums/BHR'; import _ from 'lodash'; @@ -43,6 +44,9 @@ const initialState: { backupAllFailure: boolean; pendingAllBackup: boolean; + backupRepairCompletedByAppId: Record; + backupRepairStateByAppId: Record; + backupRepairRunningByAppId: Record; automaticCloudBackup: boolean; @@ -84,6 +88,9 @@ const initialState: { backupAllSuccess: false, pendingAllBackup: false, + backupRepairCompletedByAppId: {}, + backupRepairStateByAppId: {}, + backupRepairRunningByAppId: {}, automaticCloudBackup: false, @@ -226,6 +233,19 @@ const bhrSlice = createSlice({ state.pendingAllBackup = action.payload; }, + setBackupRepairState: (state, action: PayloadAction<{ appId: string; phase: RepairPhase }>) => { + const { appId, phase } = action.payload; + (state.backupRepairStateByAppId ??= {})[appId] = phase; + (state.backupRepairCompletedByAppId ??= {})[appId] = phase === 'verified'; + }, + setBackupRepairRunning: (state, action: PayloadAction<{ appId: string; running: boolean }>) => { + (state.backupRepairRunningByAppId ??= {})[action.payload.appId] = action.payload.running; + }, + invalidateBackupRepair: (state, action: PayloadAction) => { + (state.backupRepairCompletedByAppId ??= {})[action.payload] = false; + if (state.backupRepairStateByAppId?.[action.payload] === 'verified') + state.backupRepairStateByAppId[action.payload] = 'unverified'; + }, setAutomaticCloudBackup: (state, action: PayloadAction) => { state.automaticCloudBackup = action.payload; }, @@ -281,6 +301,9 @@ export const { setBackupAllFailure, setPendingAllBackup, + setBackupRepairState, + setBackupRepairRunning, + invalidateBackupRepair, setAutomaticCloudBackup, @@ -294,6 +317,7 @@ const bhrPersistConfig = { key: 'bhr', storage: reduxStorage, blacklist: [ + 'backupRepairRunningByAppId', 'isBackupError', 'backupError', 'seedConfirmed', diff --git a/src/store/sagaActions/bhr.ts b/src/store/sagaActions/bhr.ts index 39e8eadfd3..24ed5515ad 100644 --- a/src/store/sagaActions/bhr.ts +++ b/src/store/sagaActions/bhr.ts @@ -106,4 +106,9 @@ export const deleteBackup = () => ({ export const validateServerBackup = (callback) => ({ type: VALIDATE_SERVER_BACKUP, callback, -}); \ No newline at end of file +}); + +export const CHECK_BACKUP_FRESHNESS = 'CHECK_BACKUP_FRESHNESS'; +export const REPAIR_BACKUP = 'REPAIR_BACKUP'; +export const checkBackupFreshness = () => ({ type: CHECK_BACKUP_FRESHNESS }); +export const repairBackup = () => ({ type: REPAIR_BACKUP }); diff --git a/src/store/sagaActions/upgrade.ts b/src/store/sagaActions/upgrade.ts index e10adaa871..d6b6a14fc7 100644 --- a/src/store/sagaActions/upgrade.ts +++ b/src/store/sagaActions/upgrade.ts @@ -2,9 +2,9 @@ export const RESET_REDUX_STORE = 'RESET_REDUX_STORE'; export const UPDATE_VERSION_HISTORY = 'UPDATE_VERSION_HISTORY'; export const MIGRATE_LABELS_329 = 'MIGRATE_LABELS_329'; -export const updateVersionHistory = (previousVersion, newVersion) => ({ +export const updateVersionHistory = (previousVersion, newVersion, isRecovery = false) => ({ type: UPDATE_VERSION_HISTORY, - payload: { previousVersion, newVersion }, + payload: { previousVersion, newVersion, isRecovery }, }); export const migrateLabelsToBip329 = () => ({ diff --git a/src/store/sagas/bhr.ts b/src/store/sagas/bhr.ts index 063d9dc263..c60ec711eb 100644 --- a/src/store/sagas/bhr.ts +++ b/src/store/sagas/bhr.ts @@ -1,13 +1,13 @@ +import { buffers, END, eventChannel } from 'redux-saga'; +import { inspectBackup, RepairPhase } from 'src/services/backup/repair'; +import { prepareRecoveryImage } from 'src/services/backup/restore'; +import { BackupImage } from 'src/services/backup/image'; +import { markBackupMutation } from 'src/services/backup/transport'; import * as bip39 from 'bip39'; import { Wallet } from 'src/services/wallets/interfaces/wallet'; -import { call, put, select } from 'redux-saga/effects'; +import { call, put, select, takeMaybe, takeEvery } from 'redux-saga/effects'; import config from 'src/utils/service-utilities/config'; -import { - decrypt, - encrypt, - generateEncryptionKey, - hash256, -} from 'src/utils/service-utilities/encryption'; +import { encrypt, generateEncryptionKey, hash256 } from 'src/utils/service-utilities/encryption'; import BIP85 from 'src/services/wallets/operations/BIP85'; import DeviceInfo from 'react-native-device-info'; import { KeeperApp } from 'src/models/interfaces/KeeperApp'; @@ -51,16 +51,20 @@ import { setBackupAllFailure, setBackupAllLoading, setBackupAllSuccess, + setBackupRepairState, + setBackupRepairRunning, + invalidateBackupRepair, setBackupLoading, setBackupType, setDeleteBackupFailure, setDeleteBackupSuccess, - setHomeToastMessage, setIsCloudBsmsBackupRequired, setPendingAllBackup, setSeedConfirmed, } from '../reducers/bhr'; import { + CHECK_BACKUP_FRESHNESS, + REPAIR_BACKUP, BACKUP_ALL_SIGNERS_AND_VAULTS, BACKUP_BSMS_ON_CLOUD, BSMS_CLOUD_HEALTH_CHECK, @@ -83,14 +87,13 @@ import { RootState } from '../store'; import { setupRecoveryKeySigningKey } from 'src/hardware/signerSetup'; import { addNewWalletsWorker, addSigningDeviceWorker, NewWalletInfo } from './wallets'; import { - areSetsEqual, getKeyUID, sanitizeSeedKeyForBackup, sanitizeVaultSignersForSeedKeyBackup, } from 'src/utils/utilities'; import NetInfo from '@react-native-community/netinfo'; import { addToUaiStackWorker, uaiActionedWorker } from './uai'; -import { addAccount, saveDefaultWalletState, setRecoveryKeyBackedUp } from '../reducers/account'; +import { addAccount, saveDefaultWalletState, setRecoveryKeyStatus } from '../reducers/account'; import { loadConciergeTickets, loadConciergeUser } from '../reducers/concierge'; import { USDTWallet } from 'src/services/wallets/factories/USDTWalletFactory'; @@ -121,7 +124,8 @@ export function* updateAppImageWorker({ const encrytedWallet = encrypt(encryptionKey, JSON.stringify(wallet)); walletsObject[wallet.id] = encrytedWallet; } - } else if (signers) { + } + if (signers) { for (const signer of signers) { const encrytedSigner = encrypt( encryptionKey, @@ -129,12 +133,12 @@ export function* updateAppImageWorker({ ); signersObject[getKeyUID(signer)] = encrytedSigner; } - } else if (updateNodes) { + } + if (updateNodes) { const nodes: NodeDetail[] = yield call(dbManager.getCollection, RealmSchema.NodeConnect); if (nodes && nodes.length > 0) { for (const index in nodes) { - const node = nodes[index]; - node.isConnected = false; + const node = { ...nodes[index], isConnected: false }; const encrytedNode = encrypt(encryptionKey, JSON.stringify(node)); nodesList.push(encrytedNode); } @@ -150,7 +154,9 @@ export function* updateAppImageWorker({ subscription: JSON.stringify(subscription), version, nodes: nodesList, + replaceNodes: !!updateNodes, }); + if (!response?.updated) yield call(setServerBackupFailed); return response; } catch (err) { console.log({ err }); @@ -186,6 +192,7 @@ export function* updateVaultImageWorker({ if (isUpdate) { const response = yield call(Relay.updateVaultImage, { isUpdate, + appId: id, vaultId: vault.id, vault: vaultEncrypted, }); @@ -353,23 +360,11 @@ function* getAppImageWorker({ payload }) { } const encryptionKey = generateEncryptionKey(primarySeed.toString('hex')); - let appImage = { appId: appID, version: null, wallets: {}, signers: {}, nodes: [] }; - let subscription = null; - let labels = []; - let allVaultImages = []; - - try { - const response = yield call(Relay.getAppImage, appID); - if (response) { - appImage = response.appImage || appImage; - subscription = response.subscription || subscription; - labels = response.labels || labels; - allVaultImages = response.allVaultImages || allVaultImages; - } - } catch (err) { - console.log('Error retrieving app image from relay:', err); - // Continue with empty defaults - } + const response = yield call(Relay.getAppImage, appID); + if (!response?.appImage) throw new Error('Recovery data unavailable'); + const { appImage } = response; + const labels = response.labels === undefined ? [] : response.labels; + const allVaultImages = response.allVaultImages === undefined ? [] : response.allVaultImages; const previousVersion = appImage.version; @@ -417,17 +412,39 @@ function* getAppImageWorker({ payload }) { instanceNum: 0, }, }; - yield call(addNewWalletsWorker, { payload: [defaultWallet] }); + const created = yield call(addNewWalletsWorker, { payload: [defaultWallet] }); + if (created !== true) throw new Error('Recovery data unavailable'); } const recoveryKeySigner = setupRecoveryKeySigningKey(primaryMnemonic); yield call(addSigningDeviceWorker, { payload: { signers: [recoveryKeySigner] } }); + const recoveredSigners: Signer[] = yield call(dbManager.getCollection, RealmSchema.Signer); + const recoveredKey = recoveredSigners.find( + (signer) => getKeyUID(signer) === getKeyUID(recoveryKeySigner) + ); + // Key creation/merging can return without throwing after a rejected write. + // Verify the required derived key material before exposing recovery success. + if ( + !recoveredKey || + !Object.values(recoveryKeySigner.signerXpubs).some((entries) => entries.length > 0) || + !Object.entries(recoveryKeySigner.signerXpubs).every(([type, entries]) => + entries.every((expected) => + recoveredKey.signerXpubs[type]?.some( + (actual) => + actual.xpub === expected.xpub && + actual.derivationPath === expected.derivationPath && + actual.xpriv === expected.xpriv + ) + ) + ) + ) + throw new Error('Recovery data unavailable'); // applying the restore upgrade sequence if required const newVersion = DeviceInfo.getVersion(); if (previousVersion && semver.lt(previousVersion, newVersion)) { console.log(`applying restore upgarde sequence - from: ${previousVersion} to ${newVersion}`); - yield call(applyUpgradeSequence, { previousVersion, newVersion }); + yield call(applyUpgradeSequence, { previousVersion, newVersion, isRecovery: true }); try { yield call(Relay.updateAppImage, { appId: appImage.appId, @@ -448,7 +465,8 @@ function* getAppImageWorker({ payload }) { yield put(uaiChecks([uaiType.SECURE_VAULT])); yield put(loadConciergeUser(null)); yield put(loadConciergeTickets([])); - yield put(setRecoveryKeyBackedUp({ appId: appID, status: true })); + yield put(setRecoveryKeyStatus({ appId: appID, status: 'confirmed' })); + yield put(setAppCreated(true)); } catch (err) { yield put(setAppImageError(err.message)); } finally { @@ -468,6 +486,14 @@ function* recoverApp( previousVersion ) { const { bitcoinNetworkType } = yield select((state: RootState) => state.settings); + const recovered: BackupImage = yield call( + prepareRecoveryImage, + encryptionKey, + appID, + appImage, + allVaultImages, + labels + ); const entropy = yield call( BIP85.bip39MnemonicToEntropy, config.BIP85_IMAGE_ENCRYPTIONKEY_DERIVATION_PATH, @@ -495,28 +521,25 @@ function* recoverApp( networkType: bitcoinNetworkType, }; - yield call(dbManager.createObject, RealmSchema.KeeperApp, app); + yield call(writeRecoveredObject, RealmSchema.KeeperApp, app); // Wallet recreation if (appImage.wallets) { - for (const [key, value] of Object.entries(appImage.wallets)) { + for (const decryptedWallet of Object.values(recovered.wallets) as Wallet[]) { try { - const decryptedWallet: Wallet = JSON.parse(decrypt(encryptionKey, value)); if (decryptedWallet.entityKind === EntityKind.USDT_WALLET) - yield call(dbManager.createObject, RealmSchema.USDTWallet, decryptedWallet); - else yield call(dbManager.createObject, RealmSchema.Wallet, decryptedWallet); + yield call(writeRecoveredObject, RealmSchema.USDTWallet, decryptedWallet); + else yield call(writeRecoveredObject, RealmSchema.Wallet, decryptedWallet); } catch (err) { - console.log('Error recovering a wallet: ', err); - continue; + throw new Error('Recovery data unavailable'); } } } // Signers recreatin if (appImage.signers) { - for (const [key, value] of Object.entries(appImage.signers)) { + for (const decrytpedSigner of Object.values(recovered.signers) as Signer[]) { try { - const decrytpedSigner: Signer = JSON.parse(decrypt(encryptionKey, value)); if (!decrytpedSigner?.id) { decrytpedSigner.id = getKeyUID(decrytpedSigner); } @@ -526,20 +549,18 @@ function* recoverApp( ? NetworkType.TESTNET : NetworkType.MAINNET; } - yield call(dbManager.createObject, RealmSchema.Signer, decrytpedSigner); + yield call(writeRecoveredObject, RealmSchema.Signer, decrytpedSigner); } catch (err) { - console.log('Error recovering a signer: ', err); - continue; + throw new Error('Recovery data unavailable'); } } } // Vault recreation if (allVaultImages.length > 0) { - for (const vaultImage of allVaultImages) { + // Legacy vaults carry the pre-key-management signer shape until migration. + for (const vault of Object.values(recovered.vaults)) { try { - const vault = JSON.parse(decrypt(encryptionKey, vaultImage.vault)); - if (semver.lt(previousVersion, KEY_MANAGEMENT_VERSION)) { if (vault?.signers?.length) { vault.signers.forEach((signer, index) => { @@ -590,31 +611,22 @@ function* recoverApp( hidden: false, signerXpubs, }; - yield call(dbManager.createObject, RealmSchema.Signer, signerObject); + yield call(writeRecoveredObject, RealmSchema.Signer, signerObject); } } - - yield call(dbManager.createObject, RealmSchema.Vault, vault); } - yield call(dbManager.createObject, RealmSchema.Vault, vault); + yield call(writeRecoveredObject, RealmSchema.Vault, vault); } catch (err) { - console.log('Error recovering a vault: ', err); - continue; + throw new Error('Recovery data unavailable'); } } } // Labels Restore if (labels) { - const restoredLabels = []; - for (const label of labels) { - try { - restoredLabels.push(JSON.parse(decrypt(encryptionKey, label.content))); - } catch { - console.log('Failed to restore label'); - } + for (const label of Object.values(recovered.labels)) { + yield call(writeRecoveredObject, RealmSchema.Tags, label); } - yield call(dbManager.createObjectBulk, RealmSchema.Tags, restoredLabels); } if (appImage.nodes) { @@ -625,21 +637,24 @@ function* recoverApp( ); for (const node of existingNodes) { if (node && node.id) { - yield call(dbManager.deleteObjectById, RealmSchema.NodeConnect, node.id.toString()); + const deleted = yield call( + dbManager.deleteObjectById, + RealmSchema.NodeConnect, + node.id.toString() + ); + if (deleted !== true) throw new Error('Recovery data unavailable'); } } - for (const node of appImage.nodes) { + for (const decryptedNode of Object.values(recovered.nodes) as NodeDetail[]) { try { - const decryptedNode = JSON.parse(decrypt(encryptionKey, node)); if (!decryptedNode?.networkType) { decryptedNode.networkType = config.isDevMode() ? NetworkType.TESTNET : NetworkType.MAINNET; } - yield call(dbManager.createObject, RealmSchema.NodeConnect, decryptedNode); + yield call(writeRecoveredObject, RealmSchema.NodeConnect, decryptedNode); } catch (err) { - console.log('Error recovering a node: ', err); - continue; + throw new Error('Recovery data unavailable'); } } } @@ -650,35 +665,46 @@ function* recoverApp( const firstNode = savedNodes[0]; firstNode.isConnected = true; - yield call( + const connected = yield call( dbManager.updateObjectById, RealmSchema.NodeConnect, firstNode.id.toString(), firstNode ); + if (connected !== true) throw new Error('Recovery data unavailable'); } // seed confirm for recovery - yield call(dbManager.createObject, RealmSchema.BackupHistory, { + yield call(writeRecoveredObject, RealmSchema.BackupHistory, { title: BackupAction.SEED_BACKUP_CONFIRMED, date: moment().unix(), confirmed: true, subtitle: 'Recovered using backup phrase', }); - yield put(setSeedConfirmed(true)); + // Recovery proves possession of the Recovery Key, but is not consent to + // enable Assisted Server Backup. This transient flag triggers a new upload + // when the health-check screen mounts; persistent key status is set by the + // completed recovery worker instead. + yield put(setSeedConfirmed(false)); yield put(setBackupType(BackupType.SEED)); yield put(uaiActioned({ uaiType: uaiType.RECOVERY_PHRASE_HEALTH_CHECK, action: true })); // create/add restored object for version - yield call(dbManager.createObject, RealmSchema.VersionHistory, { + yield call(writeRecoveredObject, RealmSchema.VersionHistory, { version: `${DeviceInfo.getVersion()}(${DeviceInfo.getBuildNumber()})`, date: new Date().toString(), - title: 'Restored version', + title: 'Recovered Wallet', }); yield put(setAppId(appID)); - yield put(setAppCreated(true)); +} + +function* writeRecoveredObject(schema: RealmSchema, record: any) { + // Realm's adapter returns false/undefined on a rejected write instead of + // throwing. Never count that record as recovered or report partial success. + const written = yield call(dbManager.createObject, schema, record); + if (written !== true) throw new Error('Recovery data unavailable'); } function* healthCheckSatutsUpdateWorker({ @@ -946,120 +972,78 @@ export const deleteAppImageEntityWatcher = createWatcher( DELETE_APP_IMAGE_ENTITY ); -function* backupAllSignersAndVaultsWorker() { - yield put(setBackupAllSuccess(false)); - yield put(setBackupAllFailure(false)); - yield put(setBackupAllLoading(true)); - try { - // clear backup failure notification - const uaiCollection = dbManager.getObjectByField( - RealmSchema.UAI, - uaiType.SERVER_BACKUP_FAILURE, - 'uaiType' +function* runBackupInspection(repair: boolean) { + const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + yield put(setBackupRepairRunning({ appId: id, running: true })); + let finalPhase: RepairPhase = 'unverified'; + const updates = eventChannel((emit) => { + inspectBackup(id, repair, (phase) => emit(phase)).then( + () => emit(END), + () => emit(END) ); - for (const uai of uaiCollection) { - if (uai.uaiType === uaiType.SERVER_BACKUP_FAILURE) { - yield call(uaiActionedWorker, { - payload: { uaiId: uai.id, action: false }, - }); - } - } - - const { primarySeed, id, publicId, subscription, networkType, version }: KeeperApp = yield call( - dbManager.getObjectByIndex, - RealmSchema.KeeperApp - ); - const encryptionKey = generateEncryptionKey(primarySeed); - const walletObject = {}; - const signersObject = {}; - const vaultObject = {}; - - // update all wallets and signers - const btcWallets: Wallet[] = yield call(dbManager.getCollection, RealmSchema.Wallet); - const usdtWallets = yield call(dbManager.getObjectByIndex, RealmSchema.USDTWallet, null, true); - const wallets = [...btcWallets, ...usdtWallets]; - - for (const index in wallets) { - const wallet = wallets[index]; - const encrytedWallet = encrypt(encryptionKey, JSON.stringify(wallet)); - walletObject[wallet.id] = encrytedWallet; - } - const signers: Signer[] = yield call(dbManager.getCollection, RealmSchema.Signer); - for (const index in signers) { - const signer = signers[index]; - const encrytedSigner = encrypt( - encryptionKey, - JSON.stringify(sanitizeSeedKeyForBackup(signer)) - ); - signersObject[getKeyUID(signer)] = encrytedSigner; + return () => {}; + }, buffers.expanding()); + try { + while (true) { + const phase = yield takeMaybe(updates); + if (phase === END) break; + finalPhase = phase; + yield put(setBackupRepairState({ appId: id, phase })); } - const vaults: Vault[] = yield call(dbManager.getCollection, RealmSchema.Vault); - for (const index in vaults) { - const vault = vaults[index]; - const vaultEncrypted = encrypt( - encryptionKey, - JSON.stringify(sanitizeVaultSignersForSeedKeyBackup(vault)) - ); - const signersData: Array<{ - signerId: string; - xfpHash: string; - }> = []; - for (const signer of vault.signers) { - signersData.push({ - signerId: getKeyUID(signer), - xfpHash: hash256(signer.masterFingerprint), + const current: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (current?.id === id) { + yield put(setPendingAllBackup(finalPhase !== 'verified')); + if (finalPhase === 'verified') { + const notifications = dbManager.getObjectByField( + RealmSchema.UAI, + uaiType.SERVER_BACKUP_FAILURE, + 'uaiType' + ); + for (const uai of notifications) + yield call(uaiActionedWorker, { payload: { uaiId: uai.id, action: true } }); + } else if ( + !dbManager.getObjectByField(RealmSchema.UAI, uaiType.SERVER_BACKUP_FAILURE, 'uaiType') + ?.length + ) { + yield call(addToUaiStackWorker, { + payload: { + uaiType: uaiType.SERVER_BACKUP_FAILURE, + uaiDetails: { + heading: 'Check Your Backup', + body: 'Your Assisted Server Backup may differ from this device. View details to check it.', + }, + }, }); } - vaultObject[vault.id] = { - vaultId: vault.id, - signersData, - vault: vaultEncrypted, - }; } + return finalPhase === 'verified'; + } finally { + updates.close(); + yield put(setBackupRepairRunning({ appId: id, running: false })); + } +} - const nodes: NodeDetail[] = yield call(dbManager.getCollection, RealmSchema.NodeConnect); - const nodesToUpdate = []; - if (nodes && nodes.length > 0) { - for (const index in nodes) { - const node = nodes[index]; - node.isConnected = false; - const encryptedNode = encrypt(encryptionKey, JSON.stringify(node)); - nodesToUpdate.push(encryptedNode); - } - } +function* backupFreshnessWorker({ type }) { + const { automaticCloudBackup } = yield select((state: RootState) => state.bhr); + if (!automaticCloudBackup) return; + yield call(runBackupInspection, type === REPAIR_BACKUP); +} - const labels = yield call(dbManager.getCollection, RealmSchema.Tags); - const tagsToBackup = labels.map((tag) => ({ - id: hash256(hash256(encryptionKey + tag.id)), - content: encrypt(encryptionKey, JSON.stringify(tag)), - })); +export function* backupFreshnessWatcher() { + yield takeEvery([CHECK_BACKUP_FRESHNESS, REPAIR_BACKUP], backupFreshnessWorker); +} - yield call(Relay.backupAllSignersAndVaults, { - appId: id, - publicId, - walletObject, - signersObject, - vaultObject, - networkType, - subscription: JSON.stringify(subscription), - version, - nodes: nodesToUpdate, - labels: tagsToBackup, - }); - yield put(setBackupAllSuccess(true)); - yield put(setPendingAllBackup(false)); - return true; - } catch (error) { - yield put(setBackupAllFailure(true)); - yield call(setServerBackupFailed); - console.log('🚀 ~ function*backupAllSignersAndVaultsWorker ~ error:', error); - yield put( - setHomeToastMessage({ - message: 'Assisted server backup failed. Please try again later.', - isError: true, - }) - ); - return false; +function* backupAllSignersAndVaultsWorker() { + const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + yield put(setBackupAllSuccess(false)); + yield put(setBackupAllFailure(false)); + yield put(setBackupAllLoading(true)); + try { + const verified = yield call(runBackupInspection, true); + const current: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + if (current?.id === id) + yield put(verified ? setBackupAllSuccess(true) : setBackupAllFailure(true)); + return verified; } finally { yield put(setBackupAllLoading(false)); } @@ -1093,22 +1077,19 @@ function* deleteBackupWorker() { export const deleteBackupWatcher = createWatcher(deleteBackupWorker, DELETE_BACKUP); export function* checkBackupCondition() { - const { pendingAllBackup, automaticCloudBackup } = yield select((state: RootState) => state.bhr); - const { subscription }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); - // if (automaticCloudBackup && subscription.level === AppSubscriptionLevel.L1 && !pendingAllBackup) { - if (automaticCloudBackup && !pendingAllBackup) { - return true; - } + const { automaticCloudBackup } = yield select((state: RootState) => state.bhr); if (!automaticCloudBackup) return true; + const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + markBackupMutation(id); + yield put(invalidateBackupRepair(id)); const netInfo = yield call(NetInfo.fetch); if (!netInfo.isConnected) { yield call(setServerBackupFailed); return true; } - if (pendingAllBackup) { - yield call(backupAllSignersAndVaultsWorker); - return true; - } + // Never suppress this incremental write or replace it with a snapshot: wallet + // creation invokes us before persisting the new wallet to Realm. An old + // mismatch is repaired only after Back Up Now, separately from this mutation. return false; } @@ -1138,84 +1119,14 @@ export function* setServerBackupFailed() { } function* validateServerBackupWorker({ callback }) { - try { - const { primarySeed, id }: KeeperApp = yield call( - dbManager.getObjectByIndex, - RealmSchema.KeeperApp - ); - const encryptionKey = generateEncryptionKey(primarySeed as string); - let { allVaultImages, appImage, labels } = yield call(Relay.getAppImage, id); - const { nodes, wallets, signers = {} } = appImage; - - // Check for vaults - let localVaultIds = yield call(dbManager.getCollection, RealmSchema.Vault); - localVaultIds = localVaultIds.map((item) => item.id); - let decryptedVaultIds = []; - for (const index in allVaultImages) { - decryptedVaultIds.push(JSON.parse(decrypt(encryptionKey, allVaultImages[index].vault)).id); - } - if (!areSetsEqual(new Set(localVaultIds), new Set(decryptedVaultIds))) - return callback({ status: false, message: 'Vaults do not match' }); - - // Check for labels - let localLabelIds: any = yield call(dbManager.getCollection, RealmSchema.Tags); - localLabelIds = localLabelIds.map((item) => item.id); - if (labels.length !== localLabelIds.length) - return callback({ status: false, message: 'Labels do not match' }); - const decryptedLabelIds = []; - for (const index in labels) { - decryptedLabelIds.push(JSON.parse(decrypt(encryptionKey, labels[index].content)).id); - } - if (!areSetsEqual(new Set(localLabelIds), new Set(decryptedLabelIds))) - return callback({ status: false, message: 'Labels do not match' }); - - // Check for Signers - let localSignerIds: any = yield call(dbManager.getCollection, RealmSchema.Signer); - localSignerIds = localSignerIds.map((item) => item.id); - if (Object.keys(signers).length !== localSignerIds.length) - return callback({ status: false, message: 'Signers do not match' }); - let decryptedSignerIds = []; - for (const index in signers) { - decryptedSignerIds.push(JSON.parse(decrypt(encryptionKey, signers[index])).id); - } - if (!areSetsEqual(new Set(localSignerIds), new Set(decryptedSignerIds))) - return callback({ status: false, message: 'Signers do not match' }); - - // Check for Wallets - let localWallets: any = yield call(dbManager.getCollection, RealmSchema.Wallet); - const walletsBackupLength = Array.isArray(wallets) - ? wallets.length - : Object.keys(wallets).length; - if (walletsBackupLength !== localWallets.length) - return callback({ status: false, message: 'Wallets do not match' }); - const localWalletIds = localWallets.map((item) => item.id); - let decryptedWalletIds = []; - for (const index in wallets) { - decryptedWalletIds.push(JSON.parse(decrypt(encryptionKey, wallets[index])).id); - } - if (!areSetsEqual(new Set(localWalletIds), new Set(decryptedWalletIds))) - return callback({ status: false, message: 'Wallets do not match' }); - - // Check for nodes - let localNodes: any = yield call(dbManager.getCollection, RealmSchema.NodeConnect); - localNodes = localNodes.map((node) => { - node.isConnected = false; - return JSON.stringify(node); - }); - if (localNodes.length !== nodes.length) - return callback({ status: false, message: 'Nodes do not match' }); - const decryptedNodes = []; - for (const index in nodes) { - decryptedNodes.push(JSON.stringify(JSON.parse(decrypt(encryptionKey, nodes[index])))); - } - const missingNodes = decryptedNodes.filter((item) => !localNodes.includes(item)); - if (missingNodes.length > 0) return callback({ status: false, message: 'Nodes do not match' }); - - return callback({ status: true, message: 'Backup verified successfully.' }); - } catch (error) { - console.log('🚀 ~ function*validateServerBackupWorker ~ error:', error); - return callback({ status: false, message: 'Backup verification failed.', error: true }); - } + const matched = yield call(runBackupInspection, false); + const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); + const { backupRepairStateByAppId = {} } = yield select((state: RootState) => state.bhr); + callback({ + status: matched, + error: backupRepairStateByAppId[id] === 'unverified', + message: matched ? 'Backup verified successfully.' : 'Backup could not be verified.', + }); } export const validateSeverBackupWatcher = createWatcher( diff --git a/src/store/sagas/index.ts b/src/store/sagas/index.ts index dc4698337a..80ce4fc59d 100644 --- a/src/store/sagas/index.ts +++ b/src/store/sagas/index.ts @@ -45,6 +45,7 @@ import { backupAllSignersAndVaultsWatcher, deleteBackupWatcher, validateSeverBackupWatcher, + backupFreshnessWatcher, } from './bhr'; import { calculateCustomFeeWatcher, @@ -64,7 +65,12 @@ import { setupKeeperAppWatcher, } from './storage'; import { migrateLablesWatcher, updateVersionHistoryWatcher } from './upgrade'; -import { addLabelsWatcher, bulkUpdateLabelWatcher, importLabelsWatcher, markUTXOSpendabilityWatcher } from './utxos'; +import { + addLabelsWatcher, + bulkUpdateLabelWatcher, + importLabelsWatcher, + markUTXOSpendabilityWatcher, +} from './utxos'; import { connectToNodeWatcher } from './network'; import { loadConciergeUserWatcher, @@ -154,6 +160,7 @@ const rootSaga = function* () { backupAllSignersAndVaultsWatcher, deleteBackupWatcher, validateSeverBackupWatcher, + backupFreshnessWatcher, // upgrade updateVersionHistoryWatcher, diff --git a/src/store/sagas/login.ts b/src/store/sagas/login.ts index 497834d986..1f2c839f9a 100644 --- a/src/store/sagas/login.ts +++ b/src/store/sagas/login.ts @@ -51,7 +51,7 @@ import { createWatcher } from '../utilities'; import { fetchExchangeRates } from '../sagaActions/send_and_receive'; import { setLoginMethod } from '../reducers/settings'; import { setSubscription } from 'src/store/sagaActions/settings'; -import { backupAllSignersAndVaults } from '../sagaActions/bhr'; +import { checkBackupFreshness } from '../sagaActions/bhr'; import { uaiChecks } from '../sagaActions/uai'; import { applyUpgradeSequence } from './upgrade'; import { resetSyncing } from '../reducers/wallets'; @@ -214,7 +214,7 @@ function* credentialsAuthWorker({ payload }) { } if (appId) { try { - const { id, publicId, subscription }: KeeperApp = yield call( + const { id }: KeeperApp = yield call( dbManager.getObjectByIndex, RealmSchema.KeeperApp ); @@ -249,10 +249,15 @@ function* credentialsAuthWorker({ payload }) { yield put(resetSyncing()); - const { pendingAllBackup, automaticCloudBackup } = yield select( - (state: RootState) => state.bhr - ); - if (pendingAllBackup && automaticCloudBackup) yield put(backupAllSignersAndVaults()); + const { + pendingAllBackup, + automaticCloudBackup, + backupRepairCompletedByAppId = {}, + } = yield select((state: RootState) => state.bhr); + // Check without uploading; a mismatch requires Back Up Now. + if (automaticCloudBackup && (pendingAllBackup || !backupRepairCompletedByAppId[id])) { + yield put(checkBackupFreshness()); + } if (!allAccounts.length) { // upgraded app yield put(addAccount(appId)); diff --git a/src/store/sagas/upgrade.ts b/src/store/sagas/upgrade.ts index 133d332277..e7dd01185f 100644 --- a/src/store/sagas/upgrade.ts +++ b/src/store/sagas/upgrade.ts @@ -51,9 +51,11 @@ export const SIGNER_POLICY_MIGRATION_VERSION = '2.1.0'; export function* applyUpgradeSequence({ previousVersion, newVersion, + isRecovery = false, }: { previousVersion: string; newVersion: string; + isRecovery?: boolean; }) { console.log(`applying upgrade sequence - from: ${previousVersion} to ${newVersion}`); @@ -80,15 +82,15 @@ export function* applyUpgradeSequence({ } yield put(setAppVersion(newVersion)); - yield put(updateVersionHistory(previousVersion, newVersion)); + yield put(updateVersionHistory(previousVersion, newVersion, isRecovery)); } -function* updateVersionHistoryWorker({ +export function* updateVersionHistoryWorker({ payload, }: { - payload: { previousVersion: string; newVersion: string }; + payload: { previousVersion: string; newVersion: string; isRecovery?: boolean }; }) { - const { previousVersion, newVersion } = payload; + const { previousVersion, newVersion, isRecovery = false } = payload; try { const app: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); const response = yield call(Relay.updateAppImage, { @@ -98,7 +100,7 @@ function* updateVersionHistoryWorker({ yield call(dbManager.createObject, RealmSchema.VersionHistory, { version: `${newVersion}(${DeviceInfo.getBuildNumber()})`, date: new Date().toString(), - title: `Upgraded from ${previousVersion} to ${newVersion}`, + title: isRecovery ? 'Recovered Wallet' : `Upgraded from ${previousVersion} to ${newVersion}`, }); const firebaseApp = getApp(); const messagingInstance = getMessaging(firebaseApp); diff --git a/src/store/sagas/utxos.ts b/src/store/sagas/utxos.ts index 909c03dec7..7f3d1addec 100644 --- a/src/store/sagas/utxos.ts +++ b/src/store/sagas/utxos.ts @@ -11,9 +11,19 @@ import { KeeperApp } from 'src/models/interfaces/KeeperApp'; import { createWatcher } from '../utilities'; import { getJSONFromRealmObject } from 'src/storage/realm/utils'; -import { ADD_LABELS, BULK_UPDATE_LABELS, IMPORT_LABELS, MARK_UTXO_SPENDABILITY } from '../sagaActions/utxos'; +import { + ADD_LABELS, + BULK_UPDATE_LABELS, + IMPORT_LABELS, + MARK_UTXO_SPENDABILITY, +} from '../sagaActions/utxos'; import { resetState, setSyncingUTXOError, setSyncingUTXOs } from '../reducers/utxos'; -import { checkBackupCondition, setServerBackupFailed } from './bhr'; +import { + checkBackupCondition, + setServerBackupFailed, + updateAppImageWorker, + updateVaultImageWorker, +} from './bhr'; import { encrypt, generateEncryptionKey, hash256 } from 'src/utils/service-utilities/encryption'; export function* addLabelsWorker({ @@ -217,30 +227,47 @@ export function* markUTXOSpendabilityWorker({ try { const { wallet, txId, vout, spendability } = payload; - const schema = - wallet.entityKind === EntityKind.VAULT ? RealmSchema.Vault : RealmSchema.Wallet; + const schema = wallet.entityKind === EntityKind.VAULT ? RealmSchema.Vault : RealmSchema.Wallet; const storedWallet: any = yield call(dbManager.getObjectById, schema, wallet.id); if (!storedWallet) return; // Deep plain-JS copy so Realm embedded lists are proper arrays - const walletJSON = getJSONFromRealmObject(storedWallet); + const walletJSON = getJSONFromRealmObject(storedWallet) as unknown as Wallet | Vault; const specs = walletJSON.specs; const allUTXOArrays: Array<'confirmedUTXOs' | 'unconfirmedUTXOs'> = [ 'confirmedUTXOs', 'unconfirmedUTXOs', ]; + let changed = false; for (const arrayKey of allUTXOArrays) { const utxoArray: any[] = specs[arrayKey] || []; const idx = utxoArray.findIndex((u: any) => u.txId === txId && u.vout === vout); if (idx !== -1) { + if (utxoArray[idx].isManualOverride && utxoArray[idx].spendability === spendability) return; utxoArray[idx] = { ...utxoArray[idx], spendability, isManualOverride: true }; + changed = true; break; } } - yield call(dbManager.updateObjectById, schema, wallet.id, { specs }); + if (!changed) return; + const persisted = yield call(dbManager.updateObjectById, schema, wallet.id, { specs }); + if (persisted !== true) return; + // Persist the user's choice first, then invalidate/refresh Assisted Server + // Backup through its normal opt-in/offline-aware incremental path. + try { + const response = + schema === RealmSchema.Vault + ? yield call(updateVaultImageWorker, { + payload: { vault: walletJSON as Vault, isUpdate: true }, + }) + : yield call(updateAppImageWorker, { payload: { wallets: [walletJSON as Wallet] } }); + if (!response?.updated) yield call(setServerBackupFailed); + } catch { + yield call(setServerBackupFailed); + } } catch (e) { console.log('markUTXOSpendabilityWorker error:', e); } diff --git a/src/store/sagas/wallets.ts b/src/store/sagas/wallets.ts index 4f54a44ec0..d212e033db 100644 --- a/src/store/sagas/wallets.ts +++ b/src/store/sagas/wallets.ts @@ -63,7 +63,12 @@ import ElectrumClient, { import idx from 'idx'; import _ from 'lodash'; import { SyncedWallet } from 'src/services/wallets/interfaces'; -import { checkSignerAccountsMatch, getAccountFromSigner, getKeyUID } from 'src/utils/utilities'; +import { + checkSignerAccountsMatch, + getAccountFromSigner, + getKeyUID, + sanitizeSeedKeyForBackup, +} from 'src/utils/utilities'; import { COLLABORATIVE_SCHEME } from 'src/screens/SigningDevices/SetupCollaborativeWallet'; import { RootState } from '../store'; @@ -109,6 +114,7 @@ import { deleteVaultImageWorker, updateAppImageWorker, updateVaultImageWorker, + setServerBackupFailed, } from './bhr'; import { relaySignersUpdateFail, @@ -435,20 +441,20 @@ export function* addSigningDeviceWorker({ multiSigMatch || taprootMatch; - if (signerMergeCondition) { - const { type, signerName } = [SignerType.UNKOWN_SIGNER, SignerType.OTHER_SD].includes( - existingSigner.type - ) - ? newSigner - : existingSigner; - signersToUpdate.push({ - ...existingSigner, - type, - signerXpubs: _.merge(existingSigner.signerXpubs, newSigner.signerXpubs), - signerName, - }); - continue; - } + if (signerMergeCondition) { + const { type, signerName } = [SignerType.UNKOWN_SIGNER, SignerType.OTHER_SD].includes( + existingSigner.type + ) + ? newSigner + : existingSigner; + signersToUpdate.push({ + ...existingSigner, + type, + signerXpubs: _.merge(existingSigner.signerXpubs, newSigner.signerXpubs), + signerName, + }); + continue; + } const singleSigDifferent = keysDifferent(XpubTypes.P2WPKH, newSigner, existingSigner); const multiSigDifferent = keysDifferent(XpubTypes.P2WSH, newSigner, existingSigner); @@ -725,7 +731,10 @@ function* refreshWalletsWorker({ } } - if (synchedWallet.entityKind === EntityKind.VAULT && synchedWallet.type === VaultType.CANARY) { + if ( + synchedWallet.entityKind === EntityKind.VAULT && + synchedWallet.type === VaultType.CANARY + ) { yield put(uaiChecks([uaiType.CANARAY_WALLET])); } @@ -800,14 +809,13 @@ function* refreshWalletsWorker({ } } - const { taintedAddresses, initialTaintAddresses, dustSpendTxids } = - classifyDustByAddress( - synchedWallet as any, - externalAddresses, - internalAddresses, - manualOverrideAddresses, - options.dustScan ? 'full' : 'current' - ); + const { taintedAddresses, initialTaintAddresses, dustSpendTxids } = classifyDustByAddress( + synchedWallet as any, + externalAddresses, + internalAddresses, + manualOverrideAddresses, + options.dustScan ? 'full' : 'current' + ); // Mark UTXOs — only restore snapshot for soft/hard refresh or when user made a manual override; // always re-run classification otherwise so reclassification is not blocked. @@ -1176,15 +1184,45 @@ function* updateKeyDetailsWorker({ payload }) { if (!updatedFlag) { updatedRegsteredVaults.push(value); } - yield call(dbManager.updateObjectByPrimaryId, RealmSchema.VaultSigner, 'xpub', signer.xpub, { - registeredVaults: updatedRegsteredVaults, - }); - return; + const saved = yield call( + dbManager.updateObjectByPrimaryId, + RealmSchema.VaultSigner, + 'xpub', + signer.xpub, + { registeredVaults: updatedRegsteredVaults } + ); + if (saved !== true) { + yield put(relaySignersUpdateFail('Key registration could not be saved')); + return false; + } + // VaultSigner is shared by every vault using this xpub. Back up each fresh + // containing vault so an older copy cannot overwrite the restored metadata. + try { + const vaults: Vault[] = yield call(dbManager.getCollection, RealmSchema.Vault); + for (const vault of vaults) { + if (vault.signers.some((key) => key.xpub === signer.xpub)) { + const response = yield call(updateVaultImageWorker, { + payload: { vault, isUpdate: true }, + }); + if (!response?.updated) yield call(setServerBackupFailed); + } + } + } catch (error) { + yield call(setServerBackupFailed); + } + return true; } - yield call(dbManager.updateObjectByPrimaryId, RealmSchema.VaultSigner, 'xpub', signer.xpub, { - [key]: value, - }); + const updated = yield call( + dbManager.updateObjectByPrimaryId, + RealmSchema.VaultSigner, + 'xpub', + signer.xpub, + { + [key]: value, + } + ); + return updated === true; } export const updateKeyDetails = createWatcher(updateKeyDetailsWorker, UPDATE_KEY_DETAILS); @@ -1364,7 +1402,10 @@ function* mergeSimilarKeysWorker({ payload }: { payload: { signer: Signer } }) { RealmSchema.KeeperApp ); const encryptionKey = generateEncryptionKey(primarySeed); - const encrytedSigner = encrypt(encryptionKey, JSON.stringify(signer)); + const encrytedSigner = encrypt( + encryptionKey, + JSON.stringify(sanitizeSeedKeyForBackup(signer)) + ); const updated = yield call(Relay.migrateXfp, id, [ { oldSignerId: s.masterFingerprint, diff --git a/src/utils/utilities.ts b/src/utils/utilities.ts index 67d4a549df..de54e775f6 100644 --- a/src/utils/utilities.ts +++ b/src/utils/utilities.ts @@ -714,12 +714,29 @@ export const sanitizeSeedKeyForBackup = (signer: Signer) => { }; export const sanitizeVaultSignersForSeedKeyBackup = (vault: Vault) => { - let updatedVault = _.cloneDeep(vault); - let signer = dbManager.getCollection(RealmSchema.Signer); + const updatedVault = _.cloneDeep(vault); + const signers = dbManager.getCollection(RealmSchema.Signer) as unknown as Signer[]; updatedVault.signers = updatedVault.signers.map((vaultSigner) => { - const selectedSigner = signer.find( - (signer) => signer.masterFingerprint === vaultSigner.masterFingerprint - ); + const matches = signers.filter((signer) => { + if (signer.masterFingerprint !== vaultSigner.masterFingerprint) return false; + // A fingerprint can appear on several accounts/networks. Match the actual + // vault key before deciding whether its private material may be backed up. + const sameIdentity = + signer.type === SignerType.POLICY_SERVER + ? signer.networkType === vault.networkType + : getKeyUID(signer) === getKeyUID(vaultSigner); + return ( + sameIdentity && + Object.values(signer.signerXpubs).some((keys) => + keys.some( + (key) => + key.xpub === vaultSigner.xpub && key.derivationPath === vaultSigner.derivationPath + ) + ) + ); + }); + if (matches.length !== 1) throw new Error('Cannot identify a vault key for backup'); + const selectedSigner = matches[0]; if ( selectedSigner.type === SignerType.SEED_WORDS && selectedSigner.signerName !== RECOVERY_KEY_SIGNER_NAME @@ -870,9 +887,13 @@ export const manipulateBitcoinPrices = (data) => { export const validatePSBT = (unsigned, signed, signer, errorText) => { if ( - [SignerType.TAPSIGNER, SignerType.SATOCHIP, SignerType.SPECTER, SignerType.SEEDSIGNER, SignerType.KRUX].includes( - signer.type - ) + [ + SignerType.TAPSIGNER, + SignerType.SATOCHIP, + SignerType.SPECTER, + SignerType.SEEDSIGNER, + SignerType.KRUX, + ].includes(signer.type) ) return; const unsignedHex = bitcoin.Psbt.fromBase64(unsigned).__CACHE.__TX.toHex(); @@ -931,4 +952,4 @@ export const combineSignedPsbt = (PsbtEnvelops) => { combinedPSBT.combine(bitcoin.Psbt.fromBase64(PsbtEnvelops[i].serializedPSBT)); } return combinedPSBT.toBase64(); -}; \ No newline at end of file +}; diff --git a/tests/recovery/backupFeedback.test.cjs b/tests/recovery/backupFeedback.test.cjs new file mode 100644 index 0000000000..5656622b5a --- /dev/null +++ b/tests/recovery/backupFeedback.test.cjs @@ -0,0 +1,54 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); +const { fixture, wallet, encryption, enums } = require('./sagaHarness.cjs'); + +test('opening Recovery Key after restore does not replay health-check consent or enable backup', async () => { + const f = fixture({ bhr: { automaticCloudBackup: false, seedConfirmed: true } }); + const key = encryption.generateEncryptionKey(f.scope.bip39.mnemonicToSeedSync().toString('hex')); + f.remote.wallets.local = encryption.encrypt(key, JSON.stringify(wallet('local', enums.NetworkType.MAINNET))); + await f.run('getAppImageWorker', { payload: { primaryMnemonic: 'mock fixture only' } }); + assert.equal(f.state.account.recoveryKeyStatusByAppId[f.app.id], 'confirmed'); + const signal = f.actions.filter((a) => a.type === 'setSeedConfirmed').at(-1); + assert.equal(signal?.payload, false, 'restore must clear the transient health-check signal'); + assert.equal(f.state.bhr.automaticCloudBackup, false); + const file = 'src/components/Backup/BackupHealthCheckList.tsx'; + const source = ts.createSourceFile(file, fs.readFileSync(path.join(__dirname, '../..', file), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + let callback; + function visit(node) { + if (ts.isCallExpression(node) && node.expression.getText(source) === 'useEffect' && node.arguments[0]?.getText(source).includes('if (seedConfirmed)')) callback = node.arguments[0].getText(source); + ts.forEachChild(node, visit); + } + visit(source); + assert.ok(callback); + const actions = []; + vm.runInNewContext(ts.transpileModule(`(${callback})()`, { compilerOptions: { target: ts.ScriptTarget.ES2020 } }).outputText, { + seedConfirmed: signal.payload, automaticCloudBackup: false, + dispatch: (action) => actions.push(action), + }); + assert.deepEqual(actions, [], 'mounting the backup page must not upload or enable backup'); +}); +for (const file of ['src/components/Backup/BackupHealthCheckList.tsx', 'src/screens/SeedScreens/ExportSeedScreen.tsx', 'src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx']) { + test(`${path.basename(file)} never enables backup or shows success after failure`, () => { + const source = ts.createSourceFile(file,fs.readFileSync(path.join(__dirname,'../..',file),'utf8'),ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX); + let callback; + function visit(node) { + if (!callback && ts.isCallExpression(node) && node.expression.getText(source)==='useEffect' && node.arguments[0]?.getText(source).includes('backupAllSuccess')) callback=node.arguments[0].getText(source); + ts.forEachChild(node,visit); + } + visit(source); assert.ok(callback); + const actions=[], ui=[]; + const context={ backupAllSuccess:false,backupAllFailure:true,automaticCloudBackup:false, + dispatch:a=>actions.push(a),setBackupAllSuccess:v=>({type:'success',value:v}),setBackupAllFailure:v=>({type:'failure',value:v}),setAutomaticCloudBackup:v=>({type:'enabled',value:v}), + setAsbEnabled:v=>ui.push(['enabled',v]),setHealthCheckModal:v=>ui.push(['success',v]),setBackupSuccessModal:v=>ui.push(['success',v]), + showToast:()=>ui.push(['toast']),setLoader:()=>{},navigation:{goBack:()=>{}}, + translations:{recoveryBackup:{unverified:{title:'not verified'}}},recoveryBackup:{unverified:{title:'not verified'}}, + }; + const js=ts.transpileModule(`(${callback})()`,{compilerOptions:{target:ts.ScriptTarget.ES2020,jsx:ts.JsxEmit.React}}).outputText; + vm.runInNewContext(js,context); + assert.ok(!actions.some(a=>a.type==='enabled'&&a.value)); assert.ok(!ui.some(a=>(a[0]==='enabled'||a[0]==='success')&&a[1])); + }); +} diff --git a/tests/recovery/backupFreshness.test.cjs b/tests/recovery/backupFreshness.test.cjs new file mode 100644 index 0000000000..03ff4b9ab2 --- /dev/null +++ b/tests/recovery/backupFreshness.test.cjs @@ -0,0 +1,169 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { fixture, enums, encryption, wallet, loadModule } = require('./sagaHarness.cjs'); +const { NetworkType, WalletType } = enums; + +for (const network of [NetworkType.MAINNET, NetworkType.TESTNET]) { + test(`wallet added after initial backup survives encrypted restore: ${network}`, async () => { + const f = fixture(); + const initial = wallet('initial', NetworkType.MAINNET); + const added = wallet('later', network, 1); + f.collections.Wallet.push(initial); + await f.run('updateAppImageWorker', { payload: { wallets: [initial] } }); + assert.equal( + await f.run('addNewWalletsWorker', { + payload: [{ walletType: WalletType.DEFAULT, walletDetails: { fixture: added } }], + }), + true + ); + assert.deepEqual(Object.keys(f.remote.wallets).sort(), ['initial', 'later']); + assert.ok(!f.remote.wallets.later.includes('later-address')); + f.collections.Wallet = []; + await f.run( + 'recoverApp', + 'mock mnemonic', + Buffer.from('fixture'), + encryption.generateEncryptionKey(f.app.primarySeed), + f.app.id, + f.app.subscription, + f.remote, + [], + [], + '2.5.16' + ); + assert.deepEqual(JSON.parse(JSON.stringify(f.collections.Wallet)), [initial, added]); + }); +} + +test('pending repair never suppresses a not-yet-persisted incremental addition', async () => { + const f = fixture({ bhr: { pendingAllBackup: true } }); + f.collections.Wallet.push(wallet('initial', NetworkType.MAINNET)); + await f.run('addNewWalletsWorker', { payload: [{ walletType: WalletType.DEFAULT, + walletDetails: { fixture: wallet('new', NetworkType.TESTNET) } }] }); + assert.ok(f.remote.wallets.new); + assert.deepEqual(f.calls.map(([type]) => type), ['incremental']); + assert.equal(f.state.bhr.pendingAllBackup, true); +}); + +test('disabled backup makes no uploads and preserves local creation', async () => { + const f = fixture({ bhr: { automaticCloudBackup: false, pendingAllBackup: true } }); + await f.run('addNewWalletsWorker', { + payload: [ + { + walletType: WalletType.DEFAULT, + walletDetails: { fixture: wallet('local', NetworkType.MAINNET) }, + }, + ], + }); + assert.equal(f.calls.length, 0); + assert.equal(f.collections.Wallet.length, 1); +}); + +for (const failure of [ + { online: false }, + { incrementalError: true }, +]) { + test(`backup failure retains wallet and retry: ${JSON.stringify(failure)}`, async () => { + const f = fixture(failure); + await f.run('addNewWalletsWorker', { + payload: [ + { + walletType: WalletType.DEFAULT, + walletDetails: { fixture: wallet('local', NetworkType.MAINNET) }, + }, + ], + }); + assert.equal(f.collections.Wallet.length, 1); + assert.equal(f.state.bhr.pendingAllBackup, true); + assert.ok(!f.remote.wallets.local); + assert.ok(!f.actions.some((a) => a.type === 'setBackupAllSuccess' && a.payload === true)); + }); +} + +for (const networks of [ + [NetworkType.MAINNET], + [NetworkType.TESTNET], + [NetworkType.MAINNET, NetworkType.TESTNET], +]) { + test(`recovery restores saved wallets and confirms Recovery Key status: ${networks}`, async () => { + const f = fixture(); + // Recovery orchestration computes its own key from the fixture mnemonic. + const seed = f.scope.bip39.mnemonicToSeedSync().toString('hex'); + const key = encryption.generateEncryptionKey(seed); + networks.forEach((network) => { + const w = wallet(network, network); + f.remote.wallets[w.id] = encryption.encrypt(key, JSON.stringify(w)); + }); + await f.run('getAppImageWorker', { payload: { primaryMnemonic: 'mock fixture only' } }); + assert.deepEqual( + f.actions.filter((a) => a.type === 'setAppImageError' && a.payload), + [] + ); + const id = f.app.id; + assert.equal(f.collections.Wallet.length, networks.length); + assert.equal(f.state.account.recoveryKeyStatusByAppId[id], 'confirmed'); + }); +} + +test('relay rejection retains the existing wallet-creation failure contract', async () => { + const f = fixture({ rejectIncremental: true }); + const result = await f.run('addNewWalletsWorker', { + payload: [ + { + walletType: WalletType.DEFAULT, + walletDetails: { fixture: wallet('rejected', NetworkType.MAINNET) }, + }, + ], + }); + assert.equal(result, false); + assert.equal(f.collections.Wallet.length, 0); + assert.equal(f.state.bhr.pendingAllBackup, true); + assert.ok(f.actions.some((a) => a.type === 'relayWalletUpdateFail' && a.payload === 'rejected')); +}); + +for (const enabled of [true, false]) { + test(`backup gate never performs an unsolicited full repair: ${enabled}`, async () => { + const f = fixture({ bhr: { automaticCloudBackup: enabled, backupRepairCompletedByAppId: {} } }); + f.collections.Wallet.push(wallet('old', NetworkType.MAINNET)); + assert.equal(await f.run('checkBackupCondition'), !enabled); + assert.equal(f.calls.length, 0); + assert.equal(f.state.bhr.backupRepairCompletedByAppId[f.app.id], undefined); + }); +} + +test('repair markers are stored in the separately persisted backup slice', () => { + let config; + const bhr = loadModule('src/store/reducers/bhr.ts', { + 'src/models/enums/BHR': loadModule('src/models/enums/BHR.ts'), + 'src/storage': { reduxStorage: {} }, + 'redux-persist': { + persistReducer: (settings, reducer) => { + config = settings; + return reducer; + }, + }, + }); + let state = bhr.default(undefined, { type: 'init' }); + assert.equal(config.key, 'bhr'); + assert.ok(!config.blacklist.includes('backupRepairCompletedByAppId')); + state = bhr.default(state, bhr.setBackupRepairState({ appId: 'first', phase: 'verified' })); + state = bhr.default(state, bhr.setBackupRepairState({ appId: 'second', phase: 'verified' })); + assert.equal(state.backupRepairCompletedByAppId.first, true); + assert.equal(state.backupRepairCompletedByAppId.second, true); + assert.equal(state.automaticCloudBackup, false); +}); + +test('pending repair does not suppress explicit wallet deletion', async () => { + const f = fixture({ bhr: { pendingAllBackup: true } }); + f.collections.Wallet.push(wallet('deleted', NetworkType.MAINNET)); + const response = await f.run('deleteAppImageEntityWorker', { + payload: { walletIds: ['deleted'] }, + }); + assert.equal(response.updated, true); + assert.deepEqual( + f.calls.map(([type]) => type), + ['delete'] + ); + assert.equal(f.collections.Wallet.length, 0); + assert.equal(Object.keys(f.remote.wallets).length, 0); +}); diff --git a/tests/recovery/benchmarks/backup-cost.cjs b/tests/recovery/benchmarks/backup-cost.cjs new file mode 100644 index 0000000000..eb7b9e44ab --- /dev/null +++ b/tests/recovery/benchmarks/backup-cost.cjs @@ -0,0 +1,74 @@ +// Synthetic local CPU/size baseline. Not a mobile benchmark or network measurement. +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); +const { performance } = require('node:perf_hooks'); +const file = path.join(__dirname, '../../..', 'src/utils/service-utilities/encryption.ts'); +const mod = { exports: {} }; +vm.runInNewContext( + ts.transpileModule(fs.readFileSync(file, 'utf8'), { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2020, + esModuleInterop: true, + }, + }).outputText, + { + module: mod, + exports: mod.exports, + require: (name) => (name === 'react-native-rsa-native' ? { RSA: {} } : require(name)), + } +); +const { encrypt, decrypt, generateEncryptionKey } = mod.exports; +const key = generateEncryptionKey('synthetic-benchmark-only'); +const median = (values) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]; +const results = []; +for (const [count, recordKiB] of [ + [10, 50], + [100, 50], + [100, 200], + [1, 20000], +]) { + const records = Array.from({ length: count }, (_, index) => ({ + id: `synthetic-${index}`, + networkType: 'TESTNET', + data: 'x'.repeat(recordKiB * 1024), + })); + const repetitions = []; + let plaintextBytes = 0, + ciphertextBytes = 0; + for (let iteration = 0; iteration < 4; iteration++) { + const start = performance.now(); + const payload = records.map((record) => JSON.stringify(record)); + const ciphertext = payload.map((record) => encrypt(key, record)); + const encrypted = performance.now(); + const ids = ciphertext.map((record) => JSON.parse(decrypt(key, record)).id); + const done = performance.now(); + if (ids.length !== count) throw Error('incomplete synthetic round trip'); + plaintextBytes = payload.reduce((n, v) => n + Buffer.byteLength(v), 0); + ciphertextBytes = ciphertext.reduce((n, v) => n + Buffer.byteLength(v), 0); + if (iteration) repetitions.push({ encrypt: encrypted - start, decrypt: done - encrypted }); + } + results.push({ + records: count, + recordKiB, + plaintextMiB: +(plaintextBytes / 2 ** 20).toFixed(2), + ciphertextMiB: +(ciphertextBytes / 2 ** 20).toFixed(2), + encryptMs: +median(repetitions.map((r) => r.encrypt)).toFixed(1), + decryptAndParseMs: +median(repetitions.map((r) => r.decrypt)).toFixed(1), + uploadPlusReadbackSecondsAt1Mbps: +((2 * ciphertextBytes * 8) / 1e6).toFixed(1), + }); +} +console.log( + JSON.stringify( + { + environment: `${process.platform}/${process.arch} Node ${process.version}`, + samples: 'one warm-up and three measured repetitions per case', + networkTiming: 'theoretical payload transfer only; no measured network or protocol latency', + results, + }, + null, + 2 + ) +); diff --git a/tests/recovery/helpers.cjs b/tests/recovery/helpers.cjs new file mode 100644 index 0000000000..ccc8e1ad5e --- /dev/null +++ b/tests/recovery/helpers.cjs @@ -0,0 +1,58 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); +function loadModule(file, mocks = {}, globals = {}) { + const module = { exports: {} }; + const code = ts.transpileModule(fs.readFileSync(path.join(__dirname, '../..', file), 'utf8'), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020, esModuleInterop: true }, + }).outputText; + vm.runInNewContext(code, { module, exports: module.exports, setTimeout, clearTimeout, + AbortController, Date, Buffer, console, + require: (name) => name in mocks ? mocks[name] : require(name), ...globals }); + return module.exports; +} +const encryption = loadModule('src/utils/service-utilities/encryption.ts', { 'react-native-rsa-native': { RSA: {} } }); +const image = loadModule('src/services/backup/image.ts', { 'src/utils/service-utilities/encryption': encryption }); +const makeImage = () => ({ wallets: {}, signers: {}, vaults: {}, nodes: {}, labels: {} }); +function harness(options = {}) { + const app = { id: 'disposable', publicId: 'fixture', primarySeed: 'ab'.repeat(32), subscription: { level: 1 }, version: '2.5.16' }; + const local = { Wallet: [], USDTWallet: [], Signer: [], Vault: [], NodeConnect: [], Tags: [] }; + const remote = { appId: app.id, wallets: {}, signers: {}, nodes: [], vaults: [], labels: [] }; + let vaults = [], labels = []; + const revision = () => require('node:crypto').createHash('sha256').update(JSON.stringify({remote,vaults,labels})).digest('hex'); + const calls = [], phases = []; + const db = { getObjectByIndex: (schema) => schema === 'KeeperApp' ? app : local[schema] }; + const rest = { post: async (path, payload, _headers, config) => { + calls.push(path.replace('fixture/', '')); + if (options.post) await options.post({ path, payload, config, remote, app, local }); + if (options.adapter) return options.adapter(path.replace('fixture/', ''), payload, config); + if (path.endsWith('getBackupSnapshot')) { + if (options.readError) throw Error('offline'); + return { data: options.response || { appImage: remote, allVaultImages: vaults, labels, revision: revision() } }; + } + if (payload.expectedRevision !== revision()) throw Error('Backup changed'); + if (options.reject) return { data: { updated: false } }; + remote.wallets = { ...payload.walletObject }; remote.signers = { ...payload.signersObject }; remote.nodes = payload.nodes; + vaults = Object.values(payload.vaultObject); labels = payload.labels; + remote.vaults = vaults.map(v => v.vaultId); remote.labels = labels.map(v => v.id); + if (options.corruptWrite) remote.wallets = {}; + if (options.lostResponse) throw Error('response lost after commit'); + return { data: { updated: true } }; + } }; + const transport = loadModule('src/services/backup/transport.ts', { '../rest/RestClient': rest }); + const repair = loadModule('src/services/backup/repair.ts', { + 'src/storage/realm/dbManager': db, + 'src/storage/realm/enum': { RealmSchema: new Proxy({}, { get: (_, name) => name }) }, + 'src/utils/service-utilities/config': { RELAY: 'fixture/' }, + 'src/utils/service-utilities/encryption': encryption, + 'src/utils/utilities': { getKeyUID: s => s.id || s.masterFingerprint, sanitizeSeedKeyForBackup: s => s, sanitizeVaultSignersForSeedKeyBackup: s => s }, + './transport': transport, './image': image, + }); + return { app, local, remote, calls, phases, transport, repair, + run: (write = false) => repair.inspectBackup(app.id, write, phase => phases.push(phase)) }; +} +const wallet = (id = 'wallet', networkType = 'MAINNET') => ({ id, networkType, type: 'DEFAULT', + derivationDetails: { instanceNum: 0 }, presentationData: { name: 'Disposable wallet' }, + specs: { xpub: 'disposable-test-key', nextFreeAddressIndex: 1, balances: { confirmed: 0 }, transactions: [] } }); +module.exports = { loadModule, encryption, image, makeImage, harness, wallet }; diff --git a/tests/recovery/keyRecovery.test.cjs b/tests/recovery/keyRecovery.test.cjs new file mode 100644 index 0000000000..905ada0ddd --- /dev/null +++ b/tests/recovery/keyRecovery.test.cjs @@ -0,0 +1,280 @@ +// Key lifecycle coverage uses production backup, key identity, sanitization and +// restore functions with real AES. Native Realm, physical signing and BIP32 key +// derivation remain separate acceptance checks; these are disposable records. +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { fixture, enums, encryption, signer, wallet } = require('./sagaHarness.cjs'); +const { NetworkType, SignerType, XpubTypes } = enums; +const plain = (value) => JSON.parse(JSON.stringify(value)); +const keyFor = (f) => encryption.generateEncryptionKey(f.app.primarySeed); + +async function restoreKeys(f) { + f.collections.Signer = []; + await f.run('recoverApp', 'mock mnemonic', Buffer.from('ab'.repeat(32), 'hex'), + keyFor(f), f.app.id, f.app.subscription, f.remote, [], [], '2.5.16'); + return plain(f.collections.Signer); +} + +for (const network of [NetworkType.MAINNET, NetworkType.TESTNET]) { + for (const pendingAllBackup of [false, true]) { + test(`later-added key survives encrypted restore: ${network}, pending=${pendingAllBackup}`, async () => { + const f = fixture({ bhr: { pendingAllBackup } }); + f.state.settings.bitcoinNetworkType = network; + const first = signer('AABBCCDD', network); + const later = signer('11223344', network, SignerType.LEDGER, 2); + later.signerName = 'Travel device'; + later.hidden = true; + await f.run('addSigningDeviceWorker', { payload: { signers: [first] } }); + await f.run('addSigningDeviceWorker', { payload: { signers: [later] } }); + assert.equal(f.calls.length, 2); + assert.equal(f.collections.Signer.length, 2); + const expected = plain(f.collections.Signer); + const id = f.scope.getKeyUID(later); + assert.ok(f.remote.signers[id]); + assert.ok(!f.remote.signers[id].includes('Travel device')); + assert.deepEqual(await restoreKeys(f), expected); + assert.equal(f.state.bhr.pendingAllBackup, pendingAllBackup); + }); + } +} + +test('same fingerprint on different networks and accounts retains three distinct keys', async () => { + const f = fixture(); + for (const [network, account] of [[NetworkType.MAINNET, 0], [NetworkType.TESTNET, 0], [NetworkType.MAINNET, 1]]) { + f.state.settings.bitcoinNetworkType = network; + await f.run('addSigningDeviceWorker', { + payload: { signers: [signer('AABBCCDD', network, SignerType.COLDCARD, account)] }, + }); + } + assert.deepEqual(Object.keys(f.remote.signers).sort(), ['AABBCCDD0M', 'AABBCCDD0T', 'AABBCCDD1M']); + const expected = plain(f.collections.Signer); + assert.deepEqual(await restoreKeys(f), expected); +}); + +test('mixed wallet, signer and node update backs up every requested record', async () => { + const f = fixture(); + const key = signer('AABBCCDD', NetworkType.MAINNET); + key.id = f.scope.getKeyUID(key); + f.collections.NodeConnect.push({ id: 'node-fixture', host: 'fixture.invalid', isConnected: true }); + await f.run('updateAppImageWorker', { + payload: { wallets: [wallet('wallet', NetworkType.MAINNET)], signers: [key], updateNodes: true }, + }); + assert.equal(f.calls.length, 1); + assert.ok(f.remote.wallets.wallet); + assert.ok(f.remote.signers[key.id]); + assert.equal(f.remote.nodes.length, 1); + assert.equal(JSON.parse(encryption.decrypt(keyFor(f), f.remote.nodes[0])).isConnected, false); + assert.deepEqual(await restoreKeys(f), [plain(key)]); +}); + +test('empty wallet array does not suppress signer migration', async () => { + const f = fixture(); + const key = signer('AABBCCDD', NetworkType.MAINNET); + key.id = f.scope.getKeyUID(key); + await f.run('updateAppImageWorker', { payload: { wallets: [], signers: [key] } }); + assert.ok(f.remote.signers[key.id]); +}); + +test('key name, description, archive and health metadata updates survive clean restore', async () => { + const f = fixture(); + await f.run('addSigningDeviceWorker', { payload: { signers: [signer('AABBCCDD', NetworkType.MAINNET)] } }); + const key = f.collections.Signer[0]; + for (const [field, value] of Object.entries({ + signerName: 'Renamed device', signerDescription: 'Recorded on physical device', + archived: true, hidden: true, + healthCheckDetails: [{ type: 'address-verification', actionDate: '2026-09-29T00:00:00.000Z' }], + })) await f.run('updateSignerDetailsWorker', { payload: { signer: key, key: field, value } }); + const expected = plain(f.collections.Signer); + assert.deepEqual(await restoreKeys(f), expected); +}); + +test('seed-key private material is omitted while software and Recovery Key material retain existing policy', async () => { + const f = fixture(); + const ordinary = signer('11111111', NetworkType.MAINNET, SignerType.SEED_WORDS); + const recovery = signer('22222222', NetworkType.MAINNET, SignerType.SEED_WORDS); + recovery.signerName = f.scope.RECOVERY_KEY_SIGNER_NAME; + recovery.hidden = true; + const software = signer('33333333', NetworkType.MAINNET, SignerType.MY_KEEPER); + software.extraData = { instanceNumber: 1 }; + for (const record of [ordinary, recovery, software]) { + record.signerXpubs[XpubTypes.P2WPKH][0].xpriv = `${record.masterFingerprint}-disposable-private`; + await f.run('addSigningDeviceWorker', { payload: { signers: [record] } }); + } + const localBefore = plain(f.collections.Signer); + const expected = plain(f.collections.Signer.map(f.scope.sanitizeSeedKeyForBackup)); + assert.deepEqual(plain(f.collections.Signer), localBefore, 'sanitizing must not erase local signing material'); + const restored = await restoreKeys(f); + assert.deepEqual(restored, expected); + assert.equal(restored[0].signerXpubs[XpubTypes.P2WPKH][0].xpriv, null); + assert.equal(restored[1].signerXpubs[XpubTypes.P2WPKH][0].xpriv, '22222222-disposable-private'); + assert.equal(restored[2].signerXpubs[XpubTypes.P2WPKH][0].xpriv, '33333333-disposable-private'); +}); + +test('server-key policy and software key metadata survive encrypted recovery', async () => { + const f = fixture(); + const key = signer('AABBCCDD', NetworkType.TESTNET, SignerType.POLICY_SERVER); + key.signerXpubs = {}; + key.signerPolicy = { signingDelay: 3600, backupDisabled: false, + verification: { method: 'email', verifier: 'fixture.invalid' }, secondaryVerification: [] }; + key.isBIP85 = true; + key.linkedViaSecondary = true; + f.state.settings.bitcoinNetworkType = NetworkType.TESTNET; + await f.run('addSigningDeviceWorker', { payload: { signers: [key] } }); + assert.ok(f.remote.signers.AABBCCDDT); + const expected = plain(f.collections.Signer); + assert.deepEqual(await restoreKeys(f), expected); + const restored = f.collections.Signer[0]; + assert.deepEqual(plain(restored.signerPolicy), key.signerPolicy); + assert.equal(restored.isBIP85, true); +}); + +test('vault sanitizer excludes ordinary imported seed xpriv without changing source data', () => { + const f = fixture(); + const key = signer('AABBCCDD', NetworkType.MAINNET, SignerType.SEED_WORDS); + const recovery = signer('11223344', NetworkType.MAINNET, SignerType.SEED_WORDS); + recovery.signerName = f.scope.RECOVERY_KEY_SIGNER_NAME; + f.collections.Signer.push(key, recovery); + const vault = { id: 'vault-fixture', signers: [key, recovery].map((record) => ({ + masterFingerprint: record.masterFingerprint, ...record.signerXpubs[XpubTypes.P2WPKH][0], + xpriv: `${record.masterFingerprint}-disposable-private`, + })) }; + const before = plain(vault); + const sanitized = f.scope.sanitizeVaultSignersForSeedKeyBackup(vault); + assert.equal(sanitized.signers[0].xpriv, null); + assert.equal(sanitized.signers[1].xpriv, '11223344-disposable-private'); + assert.deepEqual(plain(vault), before); +}); + +for (const [network, account] of [[NetworkType.MAINNET, 1], [NetworkType.TESTNET, 0]]) { + test(`vault sanitization selects exact key across duplicated fingerprint: ${network}, account=${account}`, () => { + const f = fixture(); + const unrelated = signer('AABBCCDD', NetworkType.MAINNET, SignerType.MY_KEEPER); + const ordinarySeed = signer('AABBCCDD', network, SignerType.SEED_WORDS, account); + f.collections.Signer.push(unrelated, ordinarySeed); + const vault = { id: 'fixture', networkType: network, signers: [{ + masterFingerprint: ordinarySeed.masterFingerprint, + ...ordinarySeed.signerXpubs[XpubTypes.P2WPKH][0], xpriv: 'fixture-private', + }] }; + assert.equal(f.scope.sanitizeVaultSignersForSeedKeyBackup(vault).signers[0].xpriv, null); + assert.equal(vault.signers[0].xpriv, 'fixture-private'); + }); +} + +for (const type of Object.values(SignerType)) { + test(`vault sanitizer preserves existing backup policy for ${type}`, () => { + const f = fixture(); + const record = signer('AABBCCDD', NetworkType.MAINNET, type); + f.collections.Signer.push(record); + const vault = { id: 'fixture', networkType: NetworkType.MAINNET, signers: [{ + masterFingerprint: record.masterFingerprint, ...record.signerXpubs[XpubTypes.P2WPKH][0], + xpriv: type === SignerType.SEED_WORDS || type === SignerType.MY_KEEPER ? 'fixture-private' : null, + }] }; + const before = plain(vault); + const sanitized = f.scope.sanitizeVaultSignersForSeedKeyBackup(vault); + assert.equal(sanitized.signers[0].xpriv, type === SignerType.SEED_WORDS ? null : vault.signers[0].xpriv); + assert.deepEqual(plain(vault), before); + }); +} + +for (const problem of ['missing', 'ambiguous', 'different-public-key', 'different-path', 'server-wrong-network']) { + test(`vault key cannot be silently classified for backup: ${problem}`, () => { + const f = fixture(); + const record = signer('AABBCCDD', NetworkType.MAINNET, + problem === 'server-wrong-network' ? SignerType.POLICY_SERVER : SignerType.SEED_WORDS); + const vault = { id: 'fixture', networkType: NetworkType.MAINNET, signers: [{ + masterFingerprint: record.masterFingerprint, ...record.signerXpubs[XpubTypes.P2WPKH][0], + xpriv: 'fixture-private', + }] }; + if (problem === 'different-public-key') vault.signers[0].xpub = 'different-public-fixture'; + if (problem === 'different-path') vault.signers[0].derivationPath = "m/86'/0'/0'"; + if (problem === 'server-wrong-network') record.networkType = NetworkType.TESTNET; + if (problem !== 'missing') f.collections.Signer.push(record); + if (problem === 'ambiguous') f.collections.Signer.push(plain(record)); + assert.throws(() => f.scope.sanitizeVaultSignersForSeedKeyBackup(vault), /Cannot identify a vault key/); + }); +} + +test('fingerprint migration applies the same seed-secret exclusion as normal backups', async () => { + const f = fixture(); + const old = signer('AAAAAAAA', NetworkType.MAINNET, SignerType.SEED_WORDS); + const updated = plain(old); + updated.masterFingerprint = 'BBBBBBBB'; + updated.signerXpubs[XpubTypes.P2WPKH][0].xpriv = 'disposable-private'; + f.collections.Signer.push(old); + f.scope.dbManager.getObjectByQuery = () => []; + let migrated; + f.scope.Relay.migrateXfp = async (_appId, records) => { migrated = records[0]; return true; }; + assert.equal(await f.run('mergeSimilarKeysWorker', { payload: { signer: updated } }), true); + const restored = JSON.parse(encryption.decrypt(keyFor(f), migrated.newSignerDetails)); + assert.equal(restored.signerXpubs[XpubTypes.P2WPKH][0].xpriv, null); + assert.equal(updated.signerXpubs[XpubTypes.P2WPKH][0].xpriv, 'disposable-private'); + assert.equal(restored.masterFingerprint, 'BBBBBBBB'); +}); + +function registrationFixture(options = {}) { + const f = fixture(options); + const device = signer('AABBCCDD', NetworkType.MAINNET); + device.id = f.scope.getKeyUID(device); + const key = { masterFingerprint: device.masterFingerprint, + ...device.signerXpubs[XpubTypes.P2WPKH][0], registeredVaults: [] }; + f.collections.Signer.push(device); + f.collections.Vault.push(...['vault-a', 'vault-b'].map((id) => ({ id, networkType: NetworkType.MAINNET, + signers: [key], scheme: { m: 1, n: 1 } }))); + f.scope.dbManager.getObjectByPrimaryId = () => ({ toJSON: () => plain(key) }); + f.scope.dbManager.updateObjectByPrimaryId = (_schema, _field, _id, patch) => { + if (options.writeFails) return false; + Object.assign(key, patch); + return true; + }; + const uploaded = []; + f.scope.Relay.updateVaultImage = async (payload) => { + if (options.uploadFails) throw Error('fixture offline'); + uploaded.push(payload); + return { updated: true }; + }; + return { f, key, uploaded }; +} + +test('key registration is backed up after persistence in every containing vault', async () => { + const { f, key, uploaded } = registrationFixture(); + const registration = { vaultId: 'vault-a', registered: true, registrationInfo: 'fixture-info', hmac: 'fixture-hmac' }; + await f.run('updateKeyDetailsWorker', { payload: { signer: key, key: 'registered', value: registration } }); + assert.deepEqual(uploaded.map((payload) => payload.vaultId), ['vault-a', 'vault-b']); + for (const payload of uploaded) { + const restored = JSON.parse(encryption.decrypt(keyFor(f), payload.vault)); + assert.deepEqual(restored.signers[0].registeredVaults, [registration]); + } +}); + +for (const options of [{ online: false }, { uploadFails: true }]) { + test(`key registration survives backup failure with retry pending: ${JSON.stringify(options)}`, async () => { + const { f, key, uploaded } = registrationFixture(options); + await f.run('updateKeyDetailsWorker', { payload: { signer: key, key: 'registered', value: { vaultId: 'vault-a', registered: true } } }); + assert.equal(key.registeredVaults[0].registered, true); + assert.equal(uploaded.length, 0); + assert.equal(f.state.bhr.pendingAllBackup, true); + }); +} + +test('disabled server backup preserves local key registration without uploading', async () => { + const { f, key, uploaded } = registrationFixture({ bhr: { automaticCloudBackup: false } }); + await f.run('updateKeyDetailsWorker', { payload: { signer: key, key: 'registered', value: { vaultId: 'vault-a', registered: true } } }); + assert.equal(key.registeredVaults[0].registered, true); + assert.equal(uploaded.length, 0); + assert.equal(f.state.bhr.pendingAllBackup, false); +}); + +test('failed local key registration write never publishes an unpersisted success', async () => { + const { f, key, uploaded } = registrationFixture({ writeFails: true }); + assert.equal(await f.run('updateKeyDetailsWorker', { payload: { signer: key, key: 'registered', value: { vaultId: 'vault-a', registered: true } } }), false); + assert.equal(uploaded.length, 0); + assert.equal(key.registeredVaults.length, 0); + assert.ok(f.actions.some((action) => action.type === 'relaySignersUpdateFail' && action.payload === 'Key registration could not be saved')); +}); + +test('remembering an imported seed for signing remains local and does not trigger a vault upload', async () => { + const { f, key, uploaded } = registrationFixture(); + await f.run('updateKeyDetailsWorker', { payload: { signer: key, key: 'xpriv', value: 'disposable-local-private' } }); + assert.equal(key.xpriv, 'disposable-local-private'); + assert.equal(uploaded.length, 0); +}); diff --git a/tests/recovery/manualCoinChoices.test.cjs b/tests/recovery/manualCoinChoices.test.cjs new file mode 100644 index 0000000000..2f7a4ae47c --- /dev/null +++ b/tests/recovery/manualCoinChoices.test.cjs @@ -0,0 +1,136 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); +const { image, makeImage, harness } = require('./helpers.cjs'); +const { fixture, enums, encryption, wallet } = require('./sagaHarness.cjs'); +const clone = value => JSON.parse(JSON.stringify(value)); +const coin = (spendability = 'doNotSpend', extra = {}) => ({ + txId: 'disposable-transaction', vout: 0, value: 10000, address: 'disposable-address', + spendability, isManualOverride: true, ...extra, +}); +const withCoins = (kind = 'Wallet') => ({ + ...wallet('manual-choice', enums.NetworkType.MAINNET), + entityKind: kind === 'Vault' ? enums.EntityKind.VAULT : enums.EntityKind.WALLET, + signers: [], scheme: { m: 1, n: 1 }, + specs: { confirmedUTXOs: [coin('spendable', { isManualOverride: false })], + unconfirmedUTXOs: [], transactions: [], addresses: { external: {}, internal: {} } }, +}); +function loadFunctions(scope, file, names) { + const source = ts.createSourceFile(file, fs.readFileSync(path.join(__dirname, '../..', file), 'utf8'), ts.ScriptTarget.Latest, true); + const code = source.statements.filter(node => ts.isFunctionDeclaration(node) && names.includes(node.name?.text)) + .map(node => node.getText(source).replace(/^export /, '')).join('\n'); + assert.equal(source.statements.filter(node => ts.isFunctionDeclaration(node) && names.includes(node.name?.text)).length, names.length); + vm.runInNewContext(ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ES2020 } }).outputText, scope); +} +function sagaFixture(options = {}) { + const f = fixture(options); + f.scope.getJSONFromRealmObject = clone; + f.scope.captureError = error => { throw error; }; + f.scope.dbManager.getObjectById = (kind, id) => f.collections[kind].find(row => row.id === id); + f.scope.dbManager.updateObjectById = (kind, id, update) => { + if (options.rejectLocalWrite) return false; + Object.assign(f.scope.dbManager.getObjectById(kind, id), clone(update)); + return true; + }; + f.scope.Relay.updateVaultImage = async payload => { + f.calls.push(['vault', payload]); + if (options.incrementalError) throw Error('offline'); + if (options.rejectIncremental) return { updated: false }; + f.remote.vault = payload.vault; + return { updated: true }; + }; + loadFunctions(f.scope, 'src/store/sagas/bhr.ts', ['updateVaultImageWorker']); + loadFunctions(f.scope, 'src/store/sagas/utxos.ts', ['markUTXOSpendabilityWorker']); + return f; +} +for (const kind of ['wallets', 'vaults']) test(`${kind}: compare manual choices but ignore chain-derived UTXO fields and confirmation order`, async () => { + const local = makeImage(), remote = makeImage(); + local[kind].wallet = withCoins(); remote[kind].wallet = clone(local[kind].wallet); + local[kind].wallet.specs.confirmedUTXOs = [coin()]; + assert.equal(await image.compareImages(local, remote), 'different'); + remote[kind].wallet.specs.confirmedUTXOs = []; + remote[kind].wallet.specs.unconfirmedUTXOs = [coin('doNotSpend', { value: 20000, height: 0 })]; + assert.equal(await image.compareImages(local, remote), 'matched'); + remote[kind].wallet.specs.unconfirmedUTXOs[0].spendability = 'spendable'; + assert.equal(await image.compareImages(local, remote), 'different'); +}); + +test('upgrade inspection detects a missing manual choice and repair includes it in encrypted readback', async () => { + const f = harness(); f.local.Wallet.push(withCoins()); + assert.equal(await f.run(true), 'verified'); + f.local.Wallet[0].specs.confirmedUTXOs[0] = coin(); + assert.equal(await f.run(), 'different'); + assert.equal(await f.run(true), 'verified'); + const restored = JSON.parse(encryption.decrypt(encryption.generateEncryptionKey(f.app.primarySeed), f.remote.wallets['manual-choice'])); + assert.equal(restored.specs.confirmedUTXOs[0].spendability, 'doNotSpend'); + assert.equal(restored.specs.confirmedUTXOs[0].isManualOverride, true); +}); + +for (const kind of ['Wallet', 'Vault']) test(`${kind}: manual choice persists before incremental backup and invalidates prior verification`, async () => { + const f = sagaFixture(); const w = withCoins(kind); f.collections[kind].push(w); + const relayName = kind === 'Vault' ? 'updateVaultImage' : 'updateAppImage'; + const original = f.scope.Relay[relayName]; + f.scope.Relay[relayName] = payload => { + assert.equal(f.collections[kind][0].specs.confirmedUTXOs[0].spendability, 'doNotSpend'); + return original(payload); + }; + await f.run('markUTXOSpendabilityWorker', { payload: { wallet: w, txId: coin().txId, vout: 0, spendability: 'doNotSpend' } }); + const encrypted = kind === 'Vault' ? f.remote.vault : f.remote.wallets[w.id]; + const restored = JSON.parse(encryption.decrypt(encryption.generateEncryptionKey(f.app.primarySeed), encrypted)); + assert.equal(restored.specs.confirmedUTXOs[0].spendability, 'doNotSpend'); + assert.ok(f.actions.some(action => action.type === 'invalidateBackupRepair')); +}); + +for (const kind of ['Wallet', 'Vault']) for (const options of [ + { bhr: { automaticCloudBackup: false } }, { online: false }, { rejectIncremental: true }, { incrementalError: true }, +]) test(`${kind}: local manual choice survives backup unavailability ${JSON.stringify(options)}`, async () => { + const f = sagaFixture(options); const w = withCoins(kind); f.collections[kind].push(w); + await f.run('markUTXOSpendabilityWorker', { payload: { wallet: w, txId: coin().txId, vout: 0, spendability: 'doNotSpend' } }); + assert.equal(f.collections[kind][0].specs.confirmedUTXOs[0].spendability, 'doNotSpend'); + if (options.bhr || options.online === false) assert.equal(f.calls.length, 0); + if (!options.bhr) assert.equal(f.state.bhr.pendingAllBackup, true); + assert.equal(f.remote.wallets[w.id], undefined); + assert.equal(f.remote.vault, undefined); +}); + +test('missing outpoint and repeated identical choice do not upload', async () => { + const f = sagaFixture(); const w = withCoins(); w.specs.confirmedUTXOs[0] = coin(); f.collections.Wallet.push(w); + for (const txId of ['missing', coin().txId]) { + await f.run('markUTXOSpendabilityWorker', { payload: { wallet: w, txId, vout: 0, spendability: 'doNotSpend' } }); + } + assert.equal(f.calls.length, 0); +}); + +test('rejected local persistence never uploads an unapplied coin choice', async () => { + const f = sagaFixture({ rejectLocalWrite: true }); const w = withCoins(); f.collections.Wallet.push(w); + await f.run('markUTXOSpendabilityWorker', { payload: { wallet: w, txId: coin().txId, vout: 0, spendability: 'doNotSpend' } }); + assert.equal(f.collections.Wallet[0].specs.confirmedUTXOs[0].spendability, 'spendable'); + assert.equal(f.calls.length, 0); +}); + +for (const kind of ['Wallet', 'Vault']) for (const choice of ['doNotSpend', 'spendable']) test(`${kind}: restored manual ${choice} survives real refresh orchestration`, async () => { + const f = sagaFixture(); const restored = withCoins(kind); restored.specs.confirmedUTXOs = [coin(choice)]; + f.collections[kind].push(restored); + f.scope.ELECTRUM_CLIENT = { isClientConnected: true }; + f.scope.WalletUtilities.getNetworkByType = () => ({}); + f.scope.WalletOperations = { syncWalletsViaElectrumClient: async () => { + const synced = clone(restored); + synced.specs.confirmedUTXOs = [coin('spendable', { isManualOverride: false })]; + return { synchedWallets: [{ synchedWallet: synced, newUTXOs: [] }] }; + } }; + // Oppose the user's choice to prove the production manual-override branch wins. + f.scope.classifyDustByAddress = () => ({ + taintedAddresses: new Set(choice === 'spendable' ? [coin().address] : []), + initialTaintAddresses: new Set(), dustSpendTxids: new Set(), + }); + f.scope.setSyncing = payload => ({ type: 'syncing', payload }); + f.scope.setElectrumNotConnectedErr = error => { throw Error(error); }; + f.scope.ELECTRUM_NOT_CONNECTED_ERR = 'offline'; f.scope.ELECTRUM_NOT_CONNECTED_ERR_TOR = 'tor-offline'; + loadFunctions(f.scope, 'src/store/sagas/wallets.ts', ['refreshWalletsWorker']); + await f.run('refreshWalletsWorker', { payload: { wallets: [restored], options: { hardRefresh: true } } }); + assert.equal(f.collections[kind][0].specs.confirmedUTXOs[0].spendability, choice); + assert.equal(f.collections[kind][0].specs.confirmedUTXOs[0].isManualOverride, true); +}); diff --git a/tests/recovery/nodeReplacement.test.cjs b/tests/recovery/nodeReplacement.test.cjs new file mode 100644 index 0000000000..0d2a6fee98 --- /dev/null +++ b/tests/recovery/nodeReplacement.test.cjs @@ -0,0 +1,29 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { fixture, encryption, wallet, enums } = require('./sagaHarness.cjs'); + +test('removing the final node emits an explicit empty-list replacement', async () => { + const f = fixture(); + await f.run('updateAppImageWorker', { payload: { updateNodes: true } }); + assert.equal(f.calls.length, 1); + assert.equal(f.calls[0][1].replaceNodes, true); + assert.deepEqual(Array.from(f.calls[0][1].nodes), []); +}); + +test('unrelated wallet update never requests node replacement', async () => { + const f = fixture(); + await f.run('updateAppImageWorker', { payload: { wallets: [wallet('one', enums.NetworkType.MAINNET)] } }); + assert.equal(f.calls[0][1].replaceNodes, false); +}); + +test('node-list replacement encrypts nodes without changing local connection state', async () => { + const f = fixture(); + const node = { id: 'disposable', host: 'fixture.invalid', port: 50002, isConnected: true }; + f.collections.NodeConnect.push(node); + await f.run('updateAppImageWorker', { payload: { updateNodes: true } }); + const sent = f.calls[0][1]; + assert.equal(sent.replaceNodes, true); + const restored = JSON.parse(encryption.decrypt(encryption.generateEncryptionKey(f.app.primarySeed), sent.nodes[0])); + assert.deepEqual(restored, { ...node, isConnected: false }); + assert.equal(node.isConnected, true); +}); diff --git a/tests/recovery/recoveryErrorFeedback.test.cjs b/tests/recovery/recoveryErrorFeedback.test.cjs new file mode 100644 index 0000000000..7071af5184 --- /dev/null +++ b/tests/recovery/recoveryErrorFeedback.test.cjs @@ -0,0 +1,81 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); + +const file = 'src/screens/Recovery/EnterSeedScreen.tsx'; +const source = ts.createSourceFile(file, + fs.readFileSync(path.join(__dirname, '../..', file), 'utf8'), + ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); +let callback; +function visit(node) { + if (ts.isCallExpression(node) && node.expression.getText(source) === 'useEffect' && + node.arguments[1]?.getText(source) === '[appImageError]') + callback = node.arguments[0].getText(source); + ts.forEachChild(node, visit); +} +visit(source); +assert.ok(callback, 'Production recovery error feedback effect exists'); +const code = ts.transpileModule(`(${callback})()`, { + compilerOptions: { target: ts.ScriptTarget.ES2020, jsx: ts.JsxEmit.React }, +}).outputText; +const seed = require('../../src/context/Localization/language/en.json').seed; + +function feedback(appImageError) { + const observed = { loading: true, invalid: false, network: false, messages: [], actions: [] }; + vm.runInNewContext(code, { + appImageError, + seed, + React: { createElement: (type) => ({ type }) }, + ToastErrorIcon: 'error-icon', + dispatch: (action) => observed.actions.push(action), + setAppImageError: (payload) => ({ type: 'setAppImageError', payload }), + setRecoveryLoading: (value) => { observed.loading = value; }, + setShowNetworkModal: (value) => { observed.network = value; }, + openInvalidSeedsModal: () => { observed.loading = false; observed.invalid = true; }, + showToast: (message) => observed.messages.push(message), + }); + return observed; +} + +test('invalid mnemonic retains the invalid Recovery Key feedback', () => { + const result = feedback('Invalid mnemonic'); + assert.equal(result.invalid, true); + assert.equal(result.loading, false); + assert.equal(result.network, false); + assert.deepEqual(result.messages, []); +}); + +test('network error stops recovery and retains the existing network modal', () => { + const result = feedback('Network Error'); + assert.equal(result.network, true); + assert.equal(result.loading, false); + assert.equal(result.invalid, false); + assert.deepEqual(result.messages, []); + assert.deepEqual(result.actions, [{ type: 'setAppImageError', payload: '' }]); +}); + +for (const error of ['Recovery data unavailable', 'Incomplete backup response', + 'Invalid backup record', 'Backup request could not be completed']) { + test(`${error} offers retry without blaming the Recovery Key or clearing entered words`, () => { + const result = feedback(error); + assert.equal(result.loading, false); + assert.equal(result.invalid, false); + assert.equal(result.network, false); + assert.deepEqual(result.messages, [seed.recoveryIncomplete]); + assert.match(result.messages[0], /try again/i); + assert.doesNotMatch(result.messages[0], /invalid (seed|mnemonic|recovery key)/i); + assert.deepEqual(result.actions, [{ type: 'setAppImageError', payload: '' }]); + }); +} + +test('empty recovery error does not interrupt loading or display an error', () => { + const result = feedback(''); + assert.equal(result.loading, true); + assert.equal(result.invalid, false); + assert.equal(result.network, false); + assert.deepEqual(result.messages, []); + assert.deepEqual(result.actions, []); +}); diff --git a/tests/recovery/repair.test.cjs b/tests/recovery/repair.test.cjs new file mode 100644 index 0000000000..c6b7d39151 --- /dev/null +++ b/tests/recovery/repair.test.cjs @@ -0,0 +1,119 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { encryption, image, makeImage, harness, wallet } = require('./helpers.cjs'); + +test('upgrade check detects omissions without uploading; explicit repair verifies readback', async () => { + const f = harness(); f.local.Wallet.push(wallet()); + assert.equal(await f.run(), 'different'); assert.deepEqual(f.calls, ['getBackupSnapshot']); + assert.equal(await f.run(true), 'verified'); + assert.deepEqual(f.phases, ['checking','different','checking','preparing','uploading','verifying','verified']); + assert.deepEqual(JSON.parse(encryption.decrypt(encryption.generateEncryptionKey(f.app.primarySeed), f.remote.wallets.wallet)), wallet()); +}); + +test('matching upgrade only reads and does not reupload', async () => { + const f = harness(); f.local.Wallet.push(wallet()); await f.run(true); f.calls.length = 0; + assert.equal(await f.run(), 'verified'); assert.deepEqual(f.calls, ['getBackupSnapshot']); +}); + +for (const failure of ['readError','reject','corruptWrite']) test(`${failure} never claims success`, async () => { + const f = harness({ [failure]: true }); f.local.Wallet.push(wallet()); + assert.equal(await f.run(true), 'unverified'); assert.ok(!f.phases.includes('verified')); + if (failure === 'readError') assert.deepEqual(f.calls, ['getBackupSnapshot']); +}); + +test('lost upload acknowledgement is resolved by readback without duplicate upload', async () => { + const f = harness({ lostResponse: true }); f.local.Wallet.push(wallet()); + assert.equal(await f.run(true), 'verified'); assert.deepEqual(f.calls, ['getBackupSnapshot','repairAppBackup','getBackupSnapshot']); +}); + +test('server-only wallet is preserved and blocks replacement', async () => { + const f = harness(); f.remote.wallets.other = encryption.encrypt(encryption.generateEncryptionKey(f.app.primarySeed), JSON.stringify(wallet('other'))); + assert.equal(await f.run(true), 'conflict'); assert.deepEqual(f.calls, ['getBackupSnapshot']); assert.ok(f.remote.wallets.other); +}); + +test('same IDs with different recovery keys are a conflict', async () => { + const l = makeImage(), r = makeImage(); l.wallets.a = wallet(); r.wallets.a = wallet(); r.wallets.a.specs.xpub = 'other'; + assert.equal(await image.compareImages(l, r), 'conflict'); +}); + +test('same IDs with changed user metadata require an update', async () => { + const l = makeImage(), r = makeImage(); l.wallets.a = wallet(); r.wallets.a = wallet(); r.wallets.a.presentationData.name = 'Old'; + assert.equal(await image.compareImages(l, r), 'different'); +}); + +test('canonical comparison ignores object order and chain caches but retains address counters', async () => { + const l = makeImage(), r = makeImage(); l.wallets.a = wallet(); r.wallets.a = wallet(); r.wallets.a.specs.balances.confirmed = 100; + assert.equal(await image.compareImages(l, r), 'matched'); r.wallets.a.specs.nextFreeAddressIndex = 2; + assert.equal(await image.compareImages(l, r), 'conflict'); + assert.equal(image.canonical({ b:2,a:1 }), image.canonical({ a:1,b:2 })); +}); + +test('BTC both networks, USDT, vaults, keys, labels and nodes are verified without mutating local data', async () => { + const f = harness(); f.local.Wallet.push(wallet('main'), wallet('test','TESTNET')); + f.local.USDTWallet.push({ ...wallet('usdt'), specs: { privateKey:'fixture-only', address:'fixture-only' } }); + f.local.Signer.push({ id:'signer', masterFingerprint:'fixture', signerXpubs:{} }); + f.local.Vault.push({ ...wallet('vault'), archived:true, signers:[{ masterFingerprint:'fixture' }], scheme:{m:1,n:1} }); + f.local.Tags.push({ id:'tag', label:'label', ref:'tx', type:'TXN' }); f.local.NodeConnect.push({ id:'node', isConnected:true, host:'fixture' }); + const before = JSON.stringify(f.local); + assert.equal(await f.run(true), 'verified'); assert.equal(JSON.stringify(f.local), before); + assert.deepEqual(Object.keys(f.remote.wallets).sort(), ['main','test','usdt']); +}); + +test('malformed or partial server response is unavailable, never an empty snapshot', async () => { + for (const response of [{}, { appImage:{} }, { appImage:{appId:'another',wallets:{},signers:{},nodes:[]}, allVaultImages:[],labels:[] }]) { + const f = harness({ response }); f.local.Wallet.push(wallet()); + assert.equal(await f.run(true), 'unverified'); assert.deepEqual(f.calls, ['getBackupSnapshot']); + } +}); + +test('mutation arriving during upload invalidates completion and remains queued until readback', async () => { + let f; + f = harness({ post: async ({ path }) => { if (path.endsWith('repairAppBackup')) f.transport.markBackupMutation(f.app.id); } }); + f.local.Wallet.push(wallet()); assert.equal(await f.run(true), 'unverified'); assert.ok(!f.phases.includes('verified')); +}); + +test('account switch during check cannot upload one account with another account data', async () => { + const f = harness({ post: async ({ app }) => { app.id = 'second'; } }); f.local.Wallet.push(wallet()); + assert.equal(await f.run(true), 'unverified'); assert.deepEqual(f.calls, ['getBackupSnapshot']); +}); + +test('chunked encryption remains compatible with existing recovery including Unicode', async () => { + const record = { id:'fixture', text: ('A'.repeat(16370) + '🔑বাংলা').repeat(5) }; + let yielded = false; setTimeout(() => { yielded = true; }, 0); + const cipher = await image.encryptRecord('test-only', record); + assert.equal(yielded, true); assert.deepEqual(JSON.parse(encryption.decrypt('test-only',cipher)),record); + assert.deepEqual(JSON.parse(JSON.stringify(await image.decryptRecord('test-only',cipher))), record); +}); + +test('oversized record fails without uploading or truncating', async () => { + const f = harness(); f.local.Wallet.push({ ...wallet(), text:'x'.repeat(image.MAX_RECORD_BYTES) }); + assert.equal(await f.run(true),'unverified'); assert.deepEqual(f.calls,[]); +}); + + +test('server change after read rejects stale upload and preserves remote data', async () => { + const f = harness({ post: async ({ path, remote }) => { + if (path.endsWith('repairAppBackup')) remote.wallets.other = 'new-device-encrypted-data'; + } }); + f.local.Wallet.push(wallet()); + assert.equal(await f.run(true), 'unverified'); + assert.equal(f.remote.wallets.other, 'new-device-encrypted-data'); + assert.equal(f.remote.wallets.wallet, undefined); +}); + +test('relay without revision support fails closed without legacy replacement', async () => { + const f = harness({ response: { appImage:{appId:'disposable',wallets:{},signers:{},nodes:[],vaults:[],labels:[]},allVaultImages:[],labels:[] } }); + f.local.Wallet.push(wallet()); + assert.equal(await f.run(true), 'unverified'); + assert.deepEqual(f.calls, ['getBackupSnapshot']); +}); + +test('archived vault is uploaded with archived server metadata', async () => { + let archived; + const f = harness({ post: async ({ path,payload }) => { + if (path.endsWith('repairAppBackup')) archived=payload.vaultObject.vault.isArchived; + } }); + f.local.Vault.push({ ...wallet('vault'), archived:true,signers:[],scheme:{m:1,n:1} }); + assert.equal(await f.run(true), 'verified'); + assert.equal(archived,true); +}); diff --git a/tests/recovery/restoreIntegrity.test.cjs b/tests/recovery/restoreIntegrity.test.cjs new file mode 100644 index 0000000000..dc2b4f6025 --- /dev/null +++ b/tests/recovery/restoreIntegrity.test.cjs @@ -0,0 +1,203 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { fixture, enums, encryption, wallet, signer } = require('./sagaHarness.cjs'); + +const plain = (value) => JSON.parse(JSON.stringify(value)); +function recoveryFixture() { + const f = fixture(); + const key = encryption.generateEncryptionKey(f.app.primarySeed); + const seal = (record) => encryption.encrypt(key, JSON.stringify(record)); + const mobile = signer('LOCAL001', enums.NetworkType.MAINNET, enums.SignerType.MY_KEEPER); + mobile.id = f.scope.getKeyUID(mobile); + const vault = { + ...wallet('vault', enums.NetworkType.MAINNET), + entityKind: enums.EntityKind.VAULT, + archived: true, + scheme: { m: 1, n: 1 }, + signers: [ + { + masterFingerprint: mobile.masterFingerprint, + xpub: mobile.signerXpubs[enums.XpubTypes.P2WPKH][0].xpub, + derivationPath: mobile.signerXpubs[enums.XpubTypes.P2WPKH][0].derivationPath, + }, + ], + }; + const label = { id: 'label', label: 'Disposable label', ref: 'tx', type: 'TXN' }; + const node = { + id: 42, + networkType: enums.NetworkType.MAINNET, + host: 'fixture', + isConnected: false, + }; + const btc = wallet('btc', enums.NetworkType.MAINNET); + const usdt = { + ...wallet('usdt', enums.NetworkType.MAINNET), + entityKind: enums.EntityKind.USDT_WALLET, + specs: { address: 'fixture', privateKey: 'fixture-only' }, + }; + f.remote.wallets = { btc: seal(btc), usdt: seal(usdt) }; + f.remote.signers = { [f.scope.getKeyUID(mobile)]: seal(mobile) }; + f.remote.nodes = [seal(node)]; + f.remote.vaults = ['vault']; + f.remote.labels = ['encrypted-label-id']; + const response = { + appImage: f.remote, + allVaultImages: [{ vaultId: 'vault', vault: seal(vault) }], + labels: [{ id: 'encrypted-label-id', content: seal(label) }], + }; + f.scope.Relay.getAppImage = async () => response; + const writes = []; + const create = f.scope.dbManager.createObject; + f.scope.dbManager.createObject = (schema, value) => { + writes.push(schema); + return create(schema, value); + }; + return { + ...f, + response, + writes, + expected: { mobile, vault, label, node, btc, usdt }, + restore: () => + f.run('getAppImageWorker', { payload: { primaryMnemonic: 'mock fixture only' } }), + }; +} +const completed = (f) => f.actions.some((a) => a.type === 'setAppCreated' && a.payload === true); +const errors = (f) => f.actions.filter((a) => a.type === 'setAppImageError' && a.payload); + +test('clean recovery recreates keys, BTC/USDT, archived vault, labels and custom nodes', async () => { + const f = recoveryFixture(); + await f.restore(); + assert.deepEqual(errors(f), []); + assert.equal(completed(f), true); + assert.deepEqual(plain(f.collections.Wallet), [f.expected.btc]); + assert.deepEqual(plain(f.collections.USDTWallet), [f.expected.usdt]); + assert.deepEqual( + plain(f.collections.Signer.find((s) => s.masterFingerprint === 'LOCAL001')), + f.expected.mobile + ); + assert.deepEqual(plain(f.collections.Vault), [f.expected.vault]); + assert.deepEqual(plain(f.collections.Tags), [f.expected.label]); + assert.deepEqual(plain(f.collections.NodeConnect), [{ ...f.expected.node, isConnected: true }]); +}); + +for (const kind of ['wallet', 'usdt', 'signer', 'vault', 'label', 'node']) { + test(`corrupt ${kind} prevents every recovery write and success`, async () => { + const f = recoveryFixture(); + if (kind === 'wallet') f.remote.wallets.btc = 'corrupt'; + if (kind === 'usdt') f.remote.wallets.usdt = 'corrupt'; + if (kind === 'signer') f.remote.signers[Object.keys(f.remote.signers)[0]] = 'corrupt'; + if (kind === 'vault') f.response.allVaultImages[0].vault = 'corrupt'; + if (kind === 'label') f.response.labels[0].content = 'corrupt'; + if (kind === 'node') f.remote.nodes[0] = 'corrupt'; + await f.restore(); + assert.equal(errors(f).length, 1); + assert.equal(completed(f), false); + assert.deepEqual(f.writes, []); + assert.equal(f.calls.length, 0, 'failed recovery must not upload an empty replacement'); + }); +} + +for (const schema of [ + 'KeeperApp', + 'Wallet', + 'USDTWallet', + 'Signer', + 'Vault', + 'Tags', + 'NodeConnect', +]) { + for (const failedResult of [false, undefined]) { + test(`${schema} persistence returning ${failedResult} cannot report recovery success`, async () => { + const f = recoveryFixture(); + const create = f.scope.dbManager.createObject; + f.scope.dbManager.createObject = (target, value) => + target === schema ? failedResult : create(target, value); + await f.restore(); + assert.equal(errors(f).length, 1); + assert.equal(completed(f), false); + assert.equal( + f.actions.some( + (a) => a.type === 'setRecoveryKeyStatus' && a.payload?.status === 'confirmed' + ), + false + ); + }); + } +} + +for (const kind of [ + 'offline', + 'missing image', + 'other account', + 'missing vault', + 'missing label', + 'wrong vault reference', + 'wrong label reference', + 'wrong encrypted vault identity', +]) { + test(`${kind} is never treated as a successful empty recovery`, async () => { + const f = recoveryFixture(); + if (kind === 'offline') + f.scope.Relay.getAppImage = async () => { + throw Error('Network Error'); + }; + if (kind === 'missing image') delete f.response.appImage; + if (kind === 'other account') f.remote.appId = 'other'; + if (kind === 'missing vault') f.response.allVaultImages = []; + if (kind === 'missing label') f.response.labels = []; + if (kind === 'wrong vault reference') f.remote.vaults = ['another-vault']; + if (kind === 'wrong label reference') f.remote.labels = ['another-label']; + if (kind === 'wrong encrypted vault identity') { + f.remote.vaults = ['another-vault']; + f.response.allVaultImages[0].vaultId = 'another-vault'; + } + await f.restore(); + assert.equal(errors(f).length, 1); + assert.equal(completed(f), false); + assert.deepEqual(f.writes, []); + }); +} + +test('explicit empty backup keeps the established first-wallet recovery path', async () => { + const f = fixture(); + let recreated = 0; + f.scope.WalletUtilities.getDerivationPath = () => 'fixture'; + f.scope.DerivationPurpose = { BIP84: 'BIP84' }; + f.scope.addNewWalletsWorker = () => { + recreated++; + return true; + }; + await f.run('getAppImageWorker', { payload: { primaryMnemonic: 'mock fixture only' } }); + assert.deepEqual(errors(f), []); + assert.equal(completed(f), true); + assert.equal(recreated, 1); +}); + +test('failed first-wallet recreation cannot complete empty-backup recovery', async () => { + const f = fixture(); + f.scope.WalletUtilities.getDerivationPath = () => 'fixture'; + f.scope.DerivationPurpose = { BIP84: 'BIP84' }; + f.scope.addNewWalletsWorker = () => false; + await f.run('getAppImageWorker', { payload: { primaryMnemonic: 'mock fixture only' } }); + assert.equal(completed(f), false); + assert.equal(errors(f).length, 1); +}); + +for (const failure of ['missing key', 'missing private material']) { + test(`regenerated Recovery Key signer with ${failure} prevents success`, async () => { + const f = recoveryFixture(); + const expected = signer('RECOVERY', enums.NetworkType.MAINNET, enums.SignerType.SEED_WORDS); + expected.signerXpubs[enums.XpubTypes.P2WPKH][0].xpriv = 'fixture-derived-private'; + f.scope.setupRecoveryKeySigningKey = () => expected; + f.scope.addSigningDeviceWorker = () => { + if (failure === 'missing private material') { + const incomplete = plain(expected); + incomplete.signerXpubs[enums.XpubTypes.P2WPKH][0].xpriv = null; + f.collections.Signer.push(incomplete); + } + }; + await f.restore(); + assert.equal(completed(f), false); + assert.equal(errors(f).length, 1); + }); +} diff --git a/tests/recovery/sagaHarness.cjs b/tests/recovery/sagaHarness.cjs new file mode 100644 index 0000000000..3a378a08d9 --- /dev/null +++ b/tests/recovery/sagaHarness.cjs @@ -0,0 +1,290 @@ +// Runs the production saga functions with redux-saga and real AES encryption. +// Realm and the relay are disposable in-memory adapters; no user keys or network calls. +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); +const { runSaga } = require('redux-saga'); +const effects = require('redux-saga/effects'); + +function functions(file, names) { + const source = ts.createSourceFile( + file, + fs.readFileSync(path.join(__dirname, '../..', file), 'utf8'), + ts.ScriptTarget.Latest, + true + ); + return source.statements + .filter((n) => (ts.isFunctionDeclaration(n) && names.includes(n.name?.text)) || + (ts.isVariableStatement(n) && n.declarationList.declarations.some(d => names.includes(d.name?.text)))) + .map((n) => n.getText(source).replace(/^export /, '').replace(/^const /, 'var ')) + .join('\n'); +} +function loadModule(file, mocks = {}) { + const module = { exports: {} }; + const code = ts.transpileModule(fs.readFileSync(path.join(__dirname, '../..', file), 'utf8'), { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2020, + esModuleInterop: true, + }, + }).outputText; + vm.runInNewContext(code, { + module, + exports: module.exports, + require: (name) => (name in mocks ? mocks[name] : require(name)), + }); + return module.exports; +} +const enums = loadModule('src/services/wallets/enums/index.ts'); +const { NetworkType, WalletType, EntityKind } = enums; +const encryption = loadModule('src/utils/service-utilities/encryption.ts', { + 'react-native-rsa-native': { RSA: {} }, +}); +const { image } = require('./helpers.cjs'); +const { prepareRecoveryImage } = loadModule('src/services/backup/restore.ts', { './image': image }); +const account = loadModule('src/store/reducers/account.ts', { + 'src/services/wallets/enums': enums, + 'src/models/enums/BHR': loadModule('src/models/enums/BHR.ts'), +}); +const wallet = (id, networkType, instanceNum = 0, type = WalletType.DEFAULT) => ({ + id, + networkType, + type, + entityKind: EntityKind.WALLET, + derivationDetails: { instanceNum, xDerivationPath: "m/84'/0'/0'" }, + presentationData: { name: 'Disposable fixture', visibility: 'DEFAULT' }, + specs: { receivingAddress: `${id}-address`, balances: { confirmed: 10000, unconfirmed: 0 } }, +}); +const signer = (fingerprint, networkType, type = enums.SignerType.COLDCARD, account = 0) => ({ + masterFingerprint: fingerprint, + type, + storageType: type === enums.SignerType.COLDCARD ? enums.SignerStorage.COLD : enums.SignerStorage.WARM, + networkType, + signerName: 'Disposable key', + signerDescription: 'Key lifecycle regression fixture', + signerXpubs: { + [enums.XpubTypes.P2WPKH]: [{ xpub: `${fingerprint}-${networkType}-${account}-public`, + derivationPath: `m/84'/${networkType === NetworkType.MAINNET ? 0 : 1}'/${account}'`, + xpriv: null }], + }, + addedOn: '2026-09-01T00:00:00.000Z', + lastHealthCheck: '2026-09-01T00:00:00.000Z', + healthCheckDetails: [{ type: 'fixture-check', actionDate: '2026-09-01T00:00:00.000Z' }], + hidden: false, + archived: false, +}); +function fixture(options = {}) { + const appId = require('crypto').createHash('sha256').update(Buffer.from('ab'.repeat(32), 'hex')).digest('hex'); + const state = { + bhr: { + automaticCloudBackup: true, + pendingAllBackup: false, + backupRepairCompletedByAppId: { [appId]: true }, + ...options.bhr, + }, + settings: { bitcoinNetworkType: NetworkType.MAINNET }, + account: account.default( + undefined, + account.setTempDetails({ hash: 'fixture', realmId: 'fixture', accountIdentifier: '' }) + ), + }; + const app = { + id: appId, + primarySeed: 'ab'.repeat(32), + publicId: 'fixture', + subscription: { level: 1 }, + networkType: NetworkType.MAINNET, + version: '2.5.16', + }; + const collections = { + Wallet: [], + USDTWallet: [], + Signer: [], + Vault: [], + Tags: [], + NodeConnect: [], + UAI: [], + VersionHistory: [], + BackupHistory: [], + }; + const remote = { appId, wallets: {}, signers: {}, nodes: [], version: '2.5.16' }; + const calls = []; + const actions = []; + const scope = { + ...effects, + markBackupMutation: () => {}, + ...encryption, + ...enums, + ...account, + prepareRecoveryImage, + console: { log() {}, error() {} }, + Buffer, + _: require('lodash'), + // Metro normally transforms idx into guarded property access. The extracted + // functions run in a separate VM realm, so emulate those access semantics. + idx: (value, getter) => { + try { return getter(value); } catch (error) { + if (error.name === 'TypeError') return undefined; + throw error; + } + }, + Realm: { UpdateMode: { Modified: 'modified' } }, + captureError: (error) => { throw error; }, + getJSONFromRealmObject: (object) => object, + RealmSchema: new Proxy({}, { get: (_, name) => name }), + dbManager: { + getObjectByIndex: (schema, _index, all) => + schema === 'KeeperApp' ? app : all ? collections[schema] : collections[schema]?.[0], + getCollection: (schema) => collections[schema] || [], + getObjectByField: (schema) => collections[schema] || [], + createObject: (schema, value) => { + if (schema === 'KeeperApp') Object.assign(app, value); + else { + const rows = (collections[schema] ||= []); + const index = rows.findIndex((row) => row.id && row.id === value.id); + if (index < 0) rows.push(value); + else rows[index] = value; + } + return true; + }, + createObjectBulk: (schema, values) => { + values.forEach((value) => scope.dbManager.createObject(schema, value)); + return true; + }, + deleteObjectById: (schema, id) => { + collections[schema] = collections[schema].filter((row) => String(row.id) !== String(id)); + return true; + }, + updateObjectById: (schema, id, patch) => { + const row = collections[schema].find((record) => String(record.id) === String(id)); + if (!row) return false; + Object.assign(row, patch); + return true; + }, + updateObjectByQuery: (schema, predicate, patch) => { + collections[schema].filter(predicate).forEach((row) => Object.assign(row, patch)); + }, + }, + Relay: { + updateAppImage: async (payload) => { + calls.push(['incremental', payload]); + if (options.incrementalError) throw Error('offline'); + if (options.rejectIncremental) return { updated: false, error: 'rejected' }; + Object.assign(remote.wallets, payload.walletsObject); + Object.assign(remote.signers, payload.signersObject); + if (payload.nodes?.length) remote.nodes = payload.nodes; + return { updated: true, error: '' }; + }, + backupAllSignersAndVaults: async (payload) => { + calls.push(['full', payload]); + if (options.fullError) throw Error('offline'); + if (options.rejectFull) return { updated: false }; + remote.wallets = { ...payload.walletObject }; + return { updated: true, error: '' }; + }, + deleteAppImageEntity: async ({ walletIds }) => { + calls.push(['delete']); + walletIds.forEach((id) => delete remote.wallets[id]); + return { updated: true, error: '' }; + }, + getAppImage: async () => ({ appImage: remote, labels: [], allVaultImages: [] }), + }, + NetInfo: { fetch: async () => ({ isConnected: options.online !== false }) }, + addToUaiStackWorker: () => {}, + uaiActionedWorker: () => {}, + uaiType: { SERVER_BACKUP_FAILURE: 'backup-failed' }, + addNewWallet: (_type, details) => details.fixture, + DeviceInfo: { getVersion: () => '2.5.16', getBuildNumber: () => '624' }, + bip39: { + validateMnemonic: () => true, + mnemonicToSeedSync: () => Buffer.from('ab'.repeat(32), 'hex'), + }, + crypto: require('crypto'), + BIP85: { bip39MnemonicToEntropy: () => Buffer.from('fixture') }, + config: { BIP85_IMAGE_ENCRYPTIONKEY_DERIVATION_PATH: 'fixture', isDevMode: () => false }, + WalletUtilities: { getFingerprintFromSeed: () => 'AAAAAAAA' }, + SubscriptionTier: { L1: 'L1', L3: 'L3' }, + AppSubscriptionLevel: { L1: 1, L3: 3 }, + BackupType: { SEED: 'SEED' }, + BackupAction: { SEED_BACKUP_CONFIRMED: 'confirmed' }, + moment: () => ({ unix: () => 1 }), + semver: require('semver'), + setupRecoveryKeySigningKey: () => signer('RECOVERY', NetworkType.MAINNET, enums.SignerType.SEED_WORDS), + applyUpgradeSequence: () => {}, + }; + const names = [ + 'setBackupRepairCompleted', + 'invalidateBackupRepair', + 'setBackupAllSuccess', + 'setBackupAllFailure', + 'setBackupAllLoading', + 'setPendingAllBackup', + 'setHomeToastMessage', + 'setRelayWalletUpdateLoading', + 'relayWalletUpdateSuccess', + 'relayWalletUpdateFail', + 'setRelaySignersUpdateLoading', + 'relaySignersUpdateSuccess', + 'relaySignersUpdateFail', + 'setAppImageError', + 'setSeedConfirmed', + 'setBackupType', + 'uaiActioned', + 'setAppId', + 'setAppCreated', + 'autoSyncWallets', + 'uaiChecks', + 'loadConciergeUser', + 'loadConciergeTickets', + 'appImagerecoveryRetry', + ]; + names.forEach((name) => { + scope[name] = (payload) => ({ type: name, payload }); + }); + const code = + functions('src/constants/defaultData.tsx', ['RECOVERY_KEY_SIGNER_NAME']) + '\n' + + functions('src/store/sagas/upgrade.ts', ['KEY_MANAGEMENT_VERSION']) + '\n' + + functions('src/utils/utilities.ts', [ + 'getAccountFromSigner', 'getKeyUID', 'checkSignerAccountsMatch', + 'sanitizeSeedKeyForBackup', 'sanitizeVaultSignersForSeedKeyBackup', + ]) + '\n' + + functions('src/store/sagas/bhr.ts', [ + 'deleteAppImageEntityWorker', + 'checkBackupCondition', + 'setServerBackupFailed', + 'updateAppImageWorker', + 'updateVaultImageWorker', + 'recoverApp', + 'writeRecoveredObject', + 'getAppImageWorker', + ]) + + '\n' + + functions('src/store/sagas/wallets.ts', [ + 'addNewWalletsWorker', 'addSigningDeviceWorker', 'mergeSimilarKeysWorker', + 'updateVaultSignerXprivWorker', 'updateSignerDetailsWorker', + 'updateKeyDetailsWorker', + ]); + vm.runInNewContext( + ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ES2020 } }).outputText, + scope + ); + const run = (name, ...args) => + runSaga( + { + getState: () => state, + dispatch(action) { + actions.push(action); + if (action.type === 'setBackupRepairCompleted') + state.bhr.backupRepairCompletedByAppId[action.payload] = true; + if (action.type === 'setPendingAllBackup') state.bhr.pendingAllBackup = action.payload; + state.account = account.default(state.account, action); + }, + }, + scope[name], + ...args + ).toPromise(); + return { scope, app, collections, remote, calls, actions, state, run }; +} + +module.exports = { fixture, enums, encryption, account, wallet, signer, loadModule, functions }; diff --git a/tests/recovery/sagaState.test.cjs b/tests/recovery/sagaState.test.cjs new file mode 100644 index 0000000000..9285b375c1 --- /dev/null +++ b/tests/recovery/sagaState.test.cjs @@ -0,0 +1,62 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); +const saga = require('redux-saga'); +const effects = require('redux-saga/effects'); +const { harness, wallet, loadModule } = require('./helpers.cjs'); +const bhr = loadModule('src/store/reducers/bhr.ts', { + 'src/models/enums/BHR': loadModule('src/models/enums/BHR.ts'), + 'src/storage': { reduxStorage:{} }, + 'redux-persist': { persistReducer: (_config,reducer) => reducer }, +}); +function runInspection(f, repair) { + const filename = 'src/store/sagas/bhr.ts'; + const source = ts.createSourceFile(filename,fs.readFileSync(path.join(__dirname,'../..',filename),'utf8'),ts.ScriptTarget.Latest,true); + const code = source.statements.filter(n => ts.isFunctionDeclaration(n) && n.name?.text === 'runBackupInspection').map(n => n.getText(source)).join('\n'); + const scope = { ...saga, ...effects, ...bhr, inspectBackup:f.repair.inspectBackup, + RealmSchema:{KeeperApp:'KeeperApp',UAI:'UAI'}, + dbManager:{ getObjectByIndex:()=>f.app, getObjectByField:()=>[] }, + uaiType:{SERVER_BACKUP_FAILURE:'failure'}, uaiActionedWorker:()=>{}, addToUaiStackWorker:()=>{}, + }; + vm.runInNewContext(ts.transpileModule(code,{ compilerOptions:{ target:ts.ScriptTarget.ES2020 }}).outputText,scope); + let state = bhr.default(undefined,{type:'init'}); const actions = []; + const task = saga.runSaga({getState:()=>({bhr:state}),dispatch:action=>{ actions.push(action); state=bhr.default(state,action); }},scope.runBackupInspection,repair).toPromise(); + return {task,get state(){ return state; }, actions}; +} + +test('only verified readback sets durable per-account completion and clears pending', async () => { + const f = harness(); f.local.Wallet.push(wallet()); const run=runInspection(f,true); + assert.equal(await run.task,true); + assert.equal(run.state.backupRepairCompletedByAppId.disposable,true); + assert.equal(run.state.backupRepairStateByAppId.disposable,'verified'); + assert.equal(run.state.backupRepairRunningByAppId.disposable,false); + assert.equal(run.state.pendingAllBackup,false); + const phases=run.actions.filter(a=>a.type==='bhr/setBackupRepairState').map(a=>a.payload.phase); + assert.deepEqual(phases,['checking','preparing','uploading','verifying','verified']); +}); + +test('offline/unverified remains pending and retryable, never spins indefinitely', async () => { + const f=harness({readError:true}); f.local.Wallet.push(wallet()); const run=runInspection(f,true); + assert.equal(await run.task,false); assert.equal(run.state.pendingAllBackup,true); + assert.equal(run.state.backupRepairCompletedByAppId.disposable,false); + assert.equal(run.state.backupRepairRunningByAppId.disposable,false); +}); + +test('account switch preserves per-account result without clearing another account pending state', async () => { + const f=harness({post:async ({app})=>{app.id='other';}}); f.local.Wallet.push(wallet()); + const run=runInspection(f,true); await run.task; + assert.equal(run.state.backupRepairStateByAppId.disposable,'unverified'); + assert.equal(run.state.backupRepairStateByAppId.other,undefined); + assert.ok(!run.actions.some(a=>a.type==='bhr/setPendingAllBackup')); +}); + +test('a later mutation invalidates verified status without affecting a second account', () => { + let state=bhr.default(undefined,bhr.setBackupRepairState({appId:'one',phase:'verified'})); + state=bhr.default(state,bhr.setBackupRepairState({appId:'two',phase:'verified'})); + state=bhr.default(state,bhr.invalidateBackupRepair('one')); + assert.equal(state.backupRepairCompletedByAppId.one,false); assert.equal(state.backupRepairStateByAppId.one,'unverified'); + assert.equal(state.backupRepairCompletedByAppId.two,true); +}); diff --git a/tests/recovery/transport.test.cjs b/tests/recovery/transport.test.cjs new file mode 100644 index 0000000000..de400afaf2 --- /dev/null +++ b/tests/recovery/transport.test.cjs @@ -0,0 +1,56 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { loadModule, harness, wallet } = require('./helpers.cjs'); + +function fakeTransport() { + let now = 0, next = 0, config; + const timers = new Map(); + const module = loadModule('src/services/backup/transport.ts', { + '../rest/RestClient': { post: (_path, _body, _headers, options) => { + config = options; + return new Promise((_, reject) => options.signal.addEventListener('abort', () => reject(new Error('secret request body')))); + } }, + }, { Date: { now: () => now }, setTimeout: (fn, ms) => { const id = ++next; timers.set(id, { at:now+ms, fn }); return id; }, clearTimeout: id => timers.delete(id) }); + const tick = (ms) => { + const until = now+ms; + while (true) { + const first = [...timers.entries()].filter(([,t]) => t.at <= until).sort((a,b) => a[1].at-b[1].at)[0]; + if (!first) break; + now = first[1].at; timers.delete(first[0]); first[1].fn(); + } + now = until; + }; + return { module, tick, get config() { return config; }, timers }; +} + +test('stalled transport aborts after 30 seconds and redacts request errors', async () => { + const f = fakeTransport(); const promise = f.module.boundedBackupPost('fixture', {}); + f.tick(29999); assert.equal(f.config.signal.aborted,false); f.tick(1); + await assert.rejects(promise, /^Error: Backup request could not be completed$/); assert.equal(f.timers.size,0); +}); + +test('only real progress resets stall clock; active transfer still has overall deadline', async () => { + const f = fakeTransport(); const promise = f.module.boundedBackupPost('fixture', {}); + for (let n=1;n<30;n++) { f.tick(20000); f.config.onDownloadProgress({ loaded:n }); } + assert.equal(f.config.signal.aborted,false); f.tick(20000); + assert.equal(f.config.signal.aborted,true); await assert.rejects(promise); assert.equal(f.timers.size,0); + const g = fakeTransport(); const stalled = g.module.boundedBackupPost('fixture', {}); + g.tick(20000); g.config.onUploadProgress({ loaded:0 }); g.tick(10000); await assert.rejects(stalled); +}); + +test('same-account writes serialize, another account runs independently, rejected queue recovers', async () => { + const f = fakeTransport(); const order = []; let release; + const first = f.module.withBackupSession('a', () => new Promise(resolve => { order.push('first'); release=resolve; })); + const next = f.module.withBackupSession('a', async () => { order.push('next'); throw Error('fixture'); }); + const recovered = f.module.withBackupSession('a', async () => order.push('recovered')); + await f.module.withBackupSession('b', async () => order.push('other')); + assert.deepEqual(order,['first','other']); release(); await first; await assert.rejects(next); await recovered; + assert.deepEqual(order,['first','other','next','recovered']); +}); + +test('repeated repair actions share one upload and readback', async () => { + const f = harness(); f.local.Wallet.push(wallet()); + const results = await Promise.all([f.run(true),f.run(true),f.run(true)]); + assert.deepEqual(results,['verified','verified','verified']); + assert.deepEqual(f.calls,['getBackupSnapshot','repairAppBackup','getBackupSnapshot']); +}); diff --git a/tests/recovery/usdtBackup.test.cjs b/tests/recovery/usdtBackup.test.cjs new file mode 100644 index 0000000000..aedac01595 --- /dev/null +++ b/tests/recovery/usdtBackup.test.cjs @@ -0,0 +1,169 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); +const { fixture, enums, encryption, loadModule } = require('./sagaHarness.cjs'); +const { image } = require('./helpers.cjs'); +const { updateAppImage } = loadModule('src/store/sagaActions/bhr.ts'); +const copy = (value) => JSON.parse(JSON.stringify(value)); + +// Run the production hook callback without React/Realm native bindings, then +// drive its dispatched action through the production saga and real AES codec. +function hookFixture(options = {}) { + const f = fixture(options); + const source = ts.createSourceFile('useUSDTWallets.ts', fs.readFileSync( + path.join(__dirname, '../../src/hooks/useUSDTWallets.ts'), 'utf8'), + ts.ScriptTarget.Latest, true); + let callback; + function visit(node) { + if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'updateWallet') + callback = node.initializer.arguments[0].getText(source); + ts.forEachChild(node, visit); + } + visit(source); + assert.ok(callback, 'Production updateWallet callback exists'); + const pending = [], order = [], errors = [], mutations = []; + const dbManager = { + getObjectById: (_schema, id) => { + const stored = f.collections.USDTWallet.find((wallet) => wallet.id === id); + return stored && { toJSON: () => copy(stored) }; + }, + updateObjectById: async (_schema, id, patch) => { + assert.equal('id' in patch, false, 'Realm primary key must not be updated'); + order.push('persist'); + if (options.failPersistence) return false; + const stored = f.collections.USDTWallet.find((wallet) => wallet.id === id); + Object.assign(stored, copy(patch)); + return true; + }, + }; + const updateWallet = vm.runInNewContext(ts.transpileModule(`(${callback})`, { + compilerOptions: { target: ts.ScriptTarget.ES2020 }, + }).outputText, { + dbManager, + RealmSchema: { USDTWallet: 'USDTWallet' }, + canonical: image.canonical, + recoveryContent: image.recoveryContent, + appId: f.app.id, + markBackupMutation: (id) => mutations.push(id), + invalidateBackupRepair: (payload) => ({ type: 'invalidateBackupRepair', payload }), + setPendingAllBackup: (payload) => ({ type: 'setPendingAllBackup', payload }), + updateAppImage, + dispatch(action) { + if (action.type === 'UPDATE_APP_IMAGE') { + order.push('backup'); + assert.deepEqual(copy(f.collections.USDTWallet[0]), copy(action.payload.wallets[0]), + 'Backup must contain the successfully persisted wallet'); + pending.push(f.run('updateAppImageWorker', action)); + } else { + f.actions.push(action); + if (action.type === 'setPendingAllBackup') f.state.bhr.pendingAllBackup = action.payload; + } + }, + setError: (message) => errors.push(message), + captureError: () => {}, + }); + return { ...f, order, errors, mutations, + update: async (wallet) => { + const result = await updateWallet(wallet); + await Promise.all(pending); + return result; + }, + }; +} + +const usdtWallet = (type = 'DEFAULT') => ({ + id: `usdt-${type}`, + entityKind: enums.EntityKind.USDT_WALLET, + type, + networkType: enums.NetworkType.TESTNET, + derivationDetails: { + instanceNum: type === 'DEFAULT' ? 1 : null, + mnemonic: 'disposable fixture mnemonic; not a usable wallet', + xDerivationPath: "m/44'/195'/0'/0/0", + }, + presentationData: { name: 'Before edit', description: 'Before', visibility: 'DEFAULT' }, + specs: { address: 'disposable-tron-address', privateKey: 'fixture-only-private-key', + balance: 10, transactions: [], hasNewUpdates: false, lastSynched: 1 }, + accountStatus: { isActive: true, nextNonce: 0 }, + createdAt: 1, +}); + +for (const type of ['DEFAULT', 'IMPORTED']) { + test(`USDT ${type} metadata and hidden state survive encrypted backup and restore`, async () => { + const f = hookFixture(); + const original = usdtWallet(type); + f.collections.USDTWallet.push(copy(original)); + await f.run('updateAppImageWorker', { payload: { wallets: [original] } }); + const edited = { ...original, + presentationData: { name: 'After edit', description: 'Updated description', visibility: 'HIDDEN' } }; + assert.equal(await f.update(edited), true); + assert.deepEqual(f.order, ['persist', 'backup']); + const key = encryption.generateEncryptionKey(f.app.primarySeed); + const cipher = f.remote.wallets[original.id]; + assert.ok(!cipher.includes(edited.specs.privateKey)); + assert.deepEqual(JSON.parse(encryption.decrypt(key, cipher)), edited); + f.collections.USDTWallet = []; + await f.run('recoverApp', 'mock mnemonic', Buffer.from('fixture'), key, + f.app.id, f.app.subscription, f.remote, [], [], '2.5.16'); + assert.deepEqual(copy(f.collections.USDTWallet), [edited]); + }); +} + +for (const failure of [{ online: false }, { incrementalError: true }, { rejectIncremental: true }]) { + test(`USDT edit remains local and retryable when backup fails: ${JSON.stringify(failure)}`, async () => { + const f = hookFixture(failure); + const original = usdtWallet(); + f.collections.USDTWallet.push(copy(original)); + const edited = { ...original, presentationData: { ...original.presentationData, name: 'Changed' } }; + assert.equal(await f.update(edited), true, 'A remote failure must not discard the saved edit'); + assert.deepEqual(copy(f.collections.USDTWallet), [edited]); + assert.equal(f.state.bhr.pendingAllBackup, true); + assert.ok(f.actions.some((a) => a.type === 'invalidateBackupRepair' && a.payload === f.app.id)); + assert.equal(f.remote.wallets[edited.id], undefined); + assert.ok(!f.actions.some((a) => a.type === 'setBackupAllSuccess' && a.payload)); + }); +} + +test('failed USDT persistence cannot report success or upload an unsaved edit', async () => { + const f = hookFixture({ failPersistence: true }); + const original = usdtWallet(); + f.collections.USDTWallet.push(copy(original)); + const edited = { ...original, presentationData: { ...original.presentationData, name: 'Not saved' } }; + assert.equal(await f.update(edited), false); + assert.deepEqual(f.order, ['persist']); + assert.equal(f.calls.length, 0); + assert.deepEqual(copy(f.collections.USDTWallet), [original]); + assert.equal(f.state.bhr.pendingAllBackup, true, 'Partial-write uncertainty requires inspection'); + assert.deepEqual(f.mutations, [f.app.id]); + assert.ok(f.actions.some((a) => a.type === 'invalidateBackupRepair' && a.payload === f.app.id)); + assert.deepEqual(f.errors, ['Failed to update wallet']); +}); + +test('USDT balance, transaction and account sync avoids redundant backup uploads', async () => { + const f = hookFixture(); + const original = usdtWallet(); + f.collections.USDTWallet.push(copy(original)); + const synced = { ...original, + specs: { ...original.specs, balance: 12, transactions: [{ txId: 'fixture-tx' }], + hasNewUpdates: true, lastSynched: 2 }, + accountStatus: { isActive: true, nextNonce: 1 }, + }; + assert.equal(await f.update(synced), true); + assert.deepEqual(copy(f.collections.USDTWallet), [synced]); + assert.deepEqual(f.order, ['persist']); + assert.equal(f.calls.length, 0); + assert.equal(f.actions.length, 0); +}); + +test('USDT metadata edits respect disabled Assisted Server Backup', async () => { + const f = hookFixture({ bhr: { automaticCloudBackup: false } }); + const original = usdtWallet(); + f.collections.USDTWallet.push(copy(original)); + const edited = { ...original, presentationData: { ...original.presentationData, visibility: 'HIDDEN' } }; + assert.equal(await f.update(edited), true); + assert.deepEqual(copy(f.collections.USDTWallet), [edited]); + assert.equal(f.calls.length, 0); +}); diff --git a/tests/screens/PinEntry.test.tsx b/tests/screens/PinEntry.test.tsx new file mode 100644 index 0000000000..42d7deb06e --- /dev/null +++ b/tests/screens/PinEntry.test.tsx @@ -0,0 +1,155 @@ +import React from 'react'; +import { act, create, ReactTestRenderer } from 'react-test-renderer'; +import { TouchableOpacity } from 'react-native'; +import LoginScreen from 'src/screens/LoginScreen/Login'; +import CreatePin from 'src/screens/LoginScreen/CreatePin'; +import PasscodeVerify from 'src/components/Modal/PasscodeVerify'; +import KeyPadView from 'src/components/AppNumPad/KeyPadView'; +import PinDotView from 'src/components/AppPinInput/PinDotView'; +import PinInputsView from 'src/components/AppPinInput/PinInputsView'; +import Buttons from 'src/components/Buttons'; + +const mockDispatch = jest.fn(); +const mockState = { + login: { hasCreds: false, authenticationFailed: false, isAuthenticated: false }, + settings: { loginMethod: 'PIN' }, + account: { allAccounts: [] }, + storage: { appId: 'disposable-test', failedAttempts: 0, lastLoginFailedAt: 0 }, + notifications: {}, + bhr: {}, +}; +jest.mock('src/store/hooks', () => ({ + useAppDispatch: () => mockDispatch, + useAppSelector: (selector) => selector(mockState), +})); +jest.mock('src/context/Localization/LocContext', () => ({ + LocalizationContext: require('react').createContext({ + translations: { + common: { proceed: 'Proceed', create: 'Create' }, + login: { Incorrect: 'Incorrect PIN' }, + error: {}, + }, + }), +})); +jest.mock('@gluestack-ui/themed-native-base', () => ({ + Box: require('react-native').View, + View: require('react-native').View, + StatusBar: () => null, + useColorMode: () => ({ colorMode: 'light' }), +})); +jest.mock('src/components/KeeperText', () => require('react-native').Text); +jest.mock('src/components/AppNumPad/KeyPadView', () => jest.fn(() => null)); +jest.mock('src/components/AppPinInput/PinDotView', () => jest.fn(() => null)); +jest.mock('src/components/AppPinInput/PinInputsView', () => jest.fn(() => null)); +jest.mock('src/components/KeeperModal', () => () => null); +jest.mock('src/components/ThemedColor/ThemedColor', () => () => '#000'); +jest.mock('src/components/ThemedSvg.tsx/ThemedSvg', () => () => null); +jest.mock('src/components/Loader', () => () => null); +jest.mock('src/components/BounceLoader', () => () => null); +jest.mock('src/components/TestnetIndicator', () => () => null); +jest.mock('src/hooks/useToastMessage', () => () => ({ showToast: jest.fn() })); +jest.mock('src/constants/defaultData', () => ({ getSecurityTip: () => ({}) })); +jest.mock('src/constants/Bitcoin', () => ({ isTestnet: () => false })); +jest.mock('src/services/rest/RestClient', () => ({ + __esModule: true, + default: { getTorStatus: () => 0, subToTorStatus: jest.fn(), unsubscribe: jest.fn() }, + TorStatus: {}, +})); +jest.mock('src/storage/realm/dbManager', () => ({})); +jest.mock('src/services/backend/Relay', () => ({})); +jest.mock('react-native-biometrics', () => jest.fn(() => ({}))); +jest.mock('@react-native-firebase/app', () => ({ getApp: jest.fn() })); +jest.mock('@react-native-firebase/messaging', () => ({ + AuthorizationStatus: { AUTHORIZED: 1, PROVISIONAL: 2 }, + getMessaging: jest.fn(), + getToken: jest.fn(), + requestPermission: jest.fn(async () => 0), +})); + +let screen: ReactTestRenderer; +const keypad = () => screen.root.findByType(KeyPadView).props; +const input = () => screen.root.findByType(PinDotView).props.passCode; +function enter(value: string) { + // Deliberately retain one render's handler and queue taps in one batch. + const press = keypad().onPressNumber; + act(() => [...value].forEach(press)); +} +function erase(count: number) { + const press = keypad().onDeletePressed; + act(() => { + for (let i = 0; i < count; i++) press(); + }); +} +function mount(component: React.ReactElement) { + act(() => { + screen = create(component); + }); +} +beforeEach(() => { + jest.useFakeTimers(); + mockDispatch.mockClear(); +}); +afterEach(() => { + act(() => screen?.unmount()); + jest.clearAllTimers(); + jest.useRealTimers(); +}); + +describe('PIN entry under batched rapid taps', () => { + test('login keeps every digit, caps at four and deletes in order', () => { + mount(); + enter('123456'); + expect(input()).toBe('1234'); + erase(2); + expect(input()).toBe('12'); + enter('98'); + expect(input()).toBe('1298'); + erase(6); + expect(input()).toBe(''); + }); + + test('creation accepts rapid confirmation and repeated digits without throttling', () => { + mount(); + enter('11111111'); + const dots = screen.root.findAllByType(PinDotView); + expect(dots.map((dot) => dot.props.passCode)).toEqual(['1111', '1111']); + expect(screen.root.findByType(Buttons).props.primaryDisable).toBe(false); + enter('9'); + expect(screen.root.findAllByType(PinDotView)[1].props.passCode).toBe('1111'); + erase(5); + expect(input()).toBe('111'); + expect(screen.root.findByType(Buttons).props.primaryDisable).toBe(true); + }); + + test('creation mismatch stays disabled and can be corrected by rapid deletion', () => { + mount(); + enter('12345678'); + expect(screen.root.findByType(Buttons).props.primaryDisable).toBe(true); + erase(4); + enter('1234'); + expect(screen.root.findByType(Buttons).props.primaryDisable).toBe(false); + }); + + test('confirmation keeps Proceed mounted, blocks partial PINs and submits exactly four digits', () => { + mount(); + const button = screen.root.findByType(Buttons); + const nativeButton = () => screen.root.findByType(TouchableOpacity); + expect(button.props.primaryText).toBe('Proceed'); + expect(nativeButton().props.disabled).toBe(true); + act(() => nativeButton().props.onPress()); + expect(mockDispatch).not.toHaveBeenCalled(); + enter('123'); + expect(screen.root.findByType(Buttons)).toBe(button); + expect(nativeButton().props.disabled).toBe(true); + enter('45'); + expect(screen.root.findByType(PinInputsView).props.passCode).toBe('1234'); + expect(screen.root.findByType(Buttons)).toBe(button); + expect(nativeButton().props.disabled).toBe(false); + act(() => nativeButton().props.onPress()); + expect(mockDispatch).toHaveBeenCalledTimes(1); + expect(mockDispatch.mock.calls[0][0].payload.passcode).toBe('1234'); + expect(nativeButton().props.disabled).toBe(true); + erase(2); + expect(screen.root.findByType(PinInputsView).props.passCode).toBe('12'); + }); +}); diff --git a/tests/services/initialTimelock.test.ts b/tests/services/initialTimelock.test.ts new file mode 100644 index 0000000000..d2e1530bcb --- /dev/null +++ b/tests/services/initialTimelock.test.ts @@ -0,0 +1,113 @@ +import { resolveInitialTimelock } from 'src/services/wallets/operations/miniscript/initialTimelock'; +import { MiniscriptTypes } from 'src/services/wallets/enums'; +import { + generateEnhancedVaultElements, + ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_MAINNET, + ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_TESTNET, + ENHANCED_VAULT_TIMELOCKS_BLOCK_HEIGHT_MAINNET, + ENHANCED_VAULT_TIMELOCKS_BLOCK_HEIGHT_TESTNET, +} from 'src/services/wallets/operations/miniscript/default/EnhancedVault'; +import { generateMiniscriptPolicy } from 'src/services/wallets/operations/miniscript/policy-generator'; + +jest.mock('src/utils/utilities', () => ({ getKeyUID: (s) => s.masterFingerprint })); +jest.mock('src/utils/service-utilities/utils', () => ({ + getDerivationPath: (p) => p.replace('m/', ''), +})); +const required = [ + MiniscriptTypes.TIMELOCKED, + MiniscriptTypes.INHERITANCE, + MiniscriptTypes.EMERGENCY, +]; +const mk = (fp) => + ({ + masterFingerprint: fp, + derivationPath: "m/48'/0'/0'/2'", + xpub: `xpub${fp}`, + account: 0, + } as any); + +describe('Timelock generation boundary', () => { + test.each([undefined, null, '', 0, NaN, -1, 123])( + 'rejects missing or malformed required selection %s', + (value) => { + expect(() => resolveInitialTimelock(required, value, () => 100)).toThrow(); + } + ); + test.each([0, -1, NaN, Infinity, 0.5, undefined])( + 'rejects invalid resolved duration %s', + (value) => { + expect(() => resolveInitialTimelock(required, 'invalid', () => value)).toThrow(); + } + ); + test.each([ + [], + [MiniscriptTypes.INHERITANCE], + [MiniscriptTypes.EMERGENCY], + [MiniscriptTypes.INHERITANCE, MiniscriptTypes.EMERGENCY], + ])('allows legitimate no-initial-timelock %j', (...args) => { + const types = args.flat() as MiniscriptTypes[]; + for (const value of [undefined, null, '', 0]) + expect(resolveInitialTimelock(types, value, () => undefined)).toBe(0); + }); + test.each([ + ['mainnet timestamp', ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_MAINNET, 1767225600], + ['testnet timestamp', ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_TESTNET, 1767225600], + ['mainnet height', ENHANCED_VAULT_TIMELOCKS_BLOCK_HEIGHT_MAINNET, 950000], + ['testnet height', ENHANCED_VAULT_TIMELOCKS_BLOCK_HEIGHT_TESTNET, 100000], + ])('preserves all policy activation times for %s', (_name, table: any, base: number) => { + for (const durationLabel of ['MONTHS_3', 'MONTHS_6', 'MONTHS_9', 'MONTHS_12']) { + const duration = resolveInitialTimelock(required, durationLabel, (label) => table[label]); + const elements = generateEnhancedVaultElements( + [mk('AAAAAAAA'), mk('BBBBBBBB'), mk('CCCCCCCC')], + [{ signer: mk('DDDDDDDD'), timelock: base + duration + table.MONTHS_12 }], + [{ signer: mk('EEEEEEEE'), timelock: base + duration + table.MONTHS_36 }], + { m: 2, n: 3 }, + base + duration + ); + const { policy, miniscriptPhases } = generateMiniscriptPolicy(elements); + expect(miniscriptPhases.map((p) => p.timelock)).toEqual([ + base + duration, + base + duration + table.MONTHS_12, + base + duration + table.MONTHS_36, + ]); + for (const phase of miniscriptPhases) expect(policy).toContain(`after(${phase.timelock})`); + } + }); +}); + +describe('Already-affected disposable policy assessment', () => { + test.each([ + ['timestamp', ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_MAINNET, 1767225600], + ['block height', ENHANCED_VAULT_TIMELOCKS_BLOCK_HEIGHT_MAINNET, 950000], + ])( + 'distinguishes an omitted initial lock and shifted fallback schedule (%s)', + (_name, table: any, base: number) => { + const generate = (initial: number) => + generateMiniscriptPolicy( + generateEnhancedVaultElements( + [mk('AAAAAAAA'), mk('BBBBBBBB'), mk('CCCCCCCC')], + [{ signer: mk('DDDDDDDD'), timelock: base + initial + table.MONTHS_12 }], + [{ signer: mk('EEEEEEEE'), timelock: base + initial + table.MONTHS_36 }], + { m: 2, n: 3 }, + initial ? base + initial : 0 + ) + ); + const affected = generate(0); + const intended = generate(table.MONTHS_6); + // Inspect the policy generated from each fixture, not a TIMELOCKED metadata flag. + expect(affected.miniscriptPhases.map((p) => p.timelock)).toEqual([ + 0, + base + table.MONTHS_12, + base + table.MONTHS_36, + ]); + expect(intended.miniscriptPhases.map((p) => p.timelock)).toEqual([ + base + table.MONTHS_6, + base + table.MONTHS_6 + table.MONTHS_12, + base + table.MONTHS_6 + table.MONTHS_36, + ]); + expect(affected.policy).not.toContain(`after(${base + table.MONTHS_6})`); + expect(intended.policy).toContain(`after(${base + table.MONTHS_6})`); + expect(affected.policy).not.toBe(intended.policy); + } + ); +}); diff --git a/tests/services/resetTimelockBoundary.test.ts b/tests/services/resetTimelockBoundary.test.ts new file mode 100644 index 0000000000..f58a48d6a1 --- /dev/null +++ b/tests/services/resetTimelockBoundary.test.ts @@ -0,0 +1,161 @@ +import fs from 'fs'; +import path from 'path'; +import vm from 'vm'; +import ts from 'typescript'; +import { resolveInitialTimelock } from 'src/services/wallets/operations/miniscript/initialTimelock'; +import { + MiniscriptTypes, + VaultType, + MultisigScriptType, + NetworkType, +} from 'src/services/wallets/enums'; + +const source = ts.createSourceFile( + 'VaultMigrationController.tsx', + fs.readFileSync( + path.join(process.cwd(), 'src/screens/Vault/VaultMigrationController.tsx'), + 'utf8' + ), + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX +); +let prepareExpression: ts.Expression; +let initiateExpression: ts.Expression; +function visit(node: ts.Node) { + if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'prepareMiniscriptScheme') + prepareExpression = node.initializer; + if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'initiateNewVault') + initiateExpression = node.initializer; + ts.forEachChild(node, visit); +} +visit(source); +function fixture() { + const generateEnhancedVaultElements = jest.fn(() => ({})); + const scope: any = { + resolveInitialTimelock, + MiniscriptTypes, + VaultType, + MultisigScriptType, + NetworkType, + bitcoinNetworkType: NetworkType.TESTNET, + getTimelockDuration: () => 6, + getCurrentTimeForLock: () => 100000, + generateEnhancedVaultElements, + generateMiniscriptScheme: () => ({}), + getKeyUID: (key) => key.id, + }; + vm.runInNewContext( + ts.transpileModule(`prepare = (${prepareExpression.getText(source)});`, { + fileName: 'boundary.tsx', + compilerOptions: { target: ts.ScriptTarget.ES2019, jsx: ts.JsxEmit.React }, + }).outputText, + scope + ); + return { + scope, + generateEnhancedVaultElements, + info: { + vaultType: VaultType.MINISCRIPT, + vaultScheme: { m: 1, n: 1 }, + vaultSigners: [{ id: 'test' }], + }, + }; +} +describe('Actual migration preparation boundary', () => { + test.each([undefined, null, '', 0])( + 'rejects dropped required value %s before policy construction', + async (value) => { + const { scope, generateEnhancedVaultElements, info } = fixture(); + await expect( + scope.prepare( + info, + [MiniscriptTypes.TIMELOCKED, MiniscriptTypes.EMERGENCY], + [], + [{ key: { id: 'emergency' }, duration: '12 months' }], + value + ) + ).rejects.toThrow('initial timelock'); + expect(generateEnhancedVaultElements).not.toHaveBeenCalled(); + expect(info).not.toHaveProperty('miniscriptElements'); + } + ); + test('uses the selected initial lock in primary and emergency policy inputs', async () => { + const { scope, generateEnhancedVaultElements, info } = fixture(); + await scope.prepare( + info, + [MiniscriptTypes.TIMELOCKED, MiniscriptTypes.EMERGENCY], + [], + [{ key: { id: 'emergency' }, duration: '12 months' }], + '6 months' + ); + const call = generateEnhancedVaultElements.mock.calls[0] as any[]; + expect(call[4]).toBe(100006); + expect(call[2][0].timelock).toBe(100012); + }); + test('still accepts an emergency-only wallet with no initial lock', async () => { + const { scope, generateEnhancedVaultElements, info } = fixture(); + await scope.prepare( + info, + [MiniscriptTypes.EMERGENCY], + [], + [{ key: { id: 'emergency' }, duration: '12 months' }], + undefined + ); + const call = generateEnhancedVaultElements.mock.calls[0] as any[]; + expect(call[4]).toBe(0); + expect(call[2][0].timelock).toBe(100006); + }); +}); + +describe('Migration caller fails closed', () => { + test.each([false, true])( + 'does not dispatch creation or migration on missing required lock (existing=%s)', + async (existing) => { + const { scope, info } = fixture(); + Object.assign(scope, { + vaultType: VaultType.MINISCRIPT, + scheme: info.vaultScheme, + vaultKeys: info.vaultSigners, + name: 'Disposable fixture', + description: '', + miniscriptTypes: [MiniscriptTypes.TIMELOCKED, MiniscriptTypes.EMERGENCY], + inheritanceKeys: [], + emergencyKeys: [{ key: { id: 'emergency' }, duration: '12 months' }], + initialTimelockDuration: undefined, + activeVault: existing ? { id: 'old-wallet', scheme: { miniscriptScheme: {} } } : null, + allVaults: [], + archivedVaults: [], + vaultAlreadyExists: jest.fn(() => false), + dispatch: jest.fn(), + migrateVault: jest.fn(), + addNewVault: jest.fn(), + generateVaultId: jest.fn(), + setGeneratedVaultId: jest.fn(), + setSavedGeneratedVaultId: jest.fn(), + showToast: jest.fn(), + setCreating: jest.fn(), + captureError: jest.fn(), + React: { createElement: () => null }, + ToastErrorIcon: () => null, + prepareMiniscriptScheme: scope.prepare, + }); + vm.runInNewContext( + ts.transpileModule(`initiate = (${initiateExpression.getText(source)});`, { + fileName: 'caller.tsx', + compilerOptions: { target: ts.ScriptTarget.ES2019, jsx: ts.JsxEmit.React }, + }).outputText, + scope + ); + await scope.initiate(); + expect(scope.dispatch).not.toHaveBeenCalled(); + expect(scope.vaultAlreadyExists).not.toHaveBeenCalled(); + expect(scope.generateVaultId).not.toHaveBeenCalled(); + expect(scope.setCreating).toHaveBeenCalledWith(false); + expect(scope.showToast.mock.calls[0][0]).toContain( + 'Failed to prepare enhanced vault: Failed to determine initial timelock duration' + ); + expect(scope.captureError).toHaveBeenCalledTimes(1); + } + ); +}); diff --git a/tests/services/resetTimelockRoute.test.ts b/tests/services/resetTimelockRoute.test.ts new file mode 100644 index 0000000000..524d190b3e --- /dev/null +++ b/tests/services/resetTimelockRoute.test.ts @@ -0,0 +1,53 @@ +import fs from 'fs'; +import path from 'path'; +import vm from 'vm'; +import ts from 'typescript'; + +// Execute the real route-parameter expression, without native UI or wallet secrets. +const source = ts.createSourceFile( + 'ResetInheritanceKey.tsx', + fs.readFileSync(path.join(process.cwd(), 'src/screens/Vault/ResetInheritanceKey.tsx'), 'utf8'), + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX +); +let params: ts.Expression; +function visit(node: ts.Node) { + if (ts.isObjectLiteralExpression(node)) { + const name = node.properties.find( + (p) => ts.isPropertyAssignment(p) && p.name.getText(source) === 'name' + ) as ts.PropertyAssignment; + if (name?.initializer.getText(source) === "'ResetEmergencyKey'") { + params = ( + node.properties.find( + (p) => ts.isPropertyAssignment(p) && p.name.getText(source) === 'params' + ) as ts.PropertyAssignment + ).initializer; + } + } + ts.forEachChild(node, visit); +} +visit(source); + +describe('Reset Keys navigation contract', () => { + test.each(['3 months', '6 months', '9 months', '12 months'])( + 'forwards selected initial duration %s', + (initialTimelockDuration) => { + const vault = { id: 'disposable' }; + const script = ts.transpile(`result = (${params.getText(source)});`, { + target: ts.ScriptTarget.ES2019, + }); + const scope: any = { + initialTimelockDuration, + vault, + inheritanceSigners: [{ id: 'test-key' }], + selectedOptions: { 'test-key': { label: '12 months' } }, + getKeyUID: (s) => s.id, + }; + vm.runInNewContext(script, scope); + expect(scope.result.initialTimelockDuration).toBe(initialTimelockDuration); + expect(scope.result.vault).toBe(vault); + expect(scope.result.inheritanceKeys[0].duration).toBe('12 months'); + } + ); +}); diff --git a/tests/store/versionHistory.test.ts b/tests/store/versionHistory.test.ts new file mode 100644 index 0000000000..2343a8c9db --- /dev/null +++ b/tests/store/versionHistory.test.ts @@ -0,0 +1,249 @@ +import fs from 'fs'; +import path from 'path'; +import { call, put, select } from 'redux-saga/effects'; +import ts from 'typescript'; +import vm from 'vm'; +import semver from 'semver'; +import { applyUpgradeSequence, updateVersionHistoryWorker } from 'src/store/sagas/upgrade'; +import { updateVersionHistory } from 'src/store/sagaActions/upgrade'; +import { RealmSchema } from 'src/storage/realm/enum'; +import dbManager from 'src/storage/realm/dbManager'; +import Relay from 'src/services/backend/Relay'; +import { setAppVersion } from 'src/store/reducers/storage'; + +jest.mock('src/storage/realm/dbManager', () => ({ + getObjectByIndex: jest.fn(), + createObject: jest.fn(), +})); +jest.mock('src/services/backend/Relay', () => ({ updateAppImage: jest.fn() })); +jest.mock('src/services/backend/SigningServer', () => ({})); +jest.mock('src/utils/service-utilities/utils', () => ({})); +jest.mock('src/services/wallets/factories/WalletFactory', () => ({})); +jest.mock('src/utils/service-utilities/encryption', () => ({})); +jest.mock('src/utils/utilities', () => ({})); +jest.mock('src/services/wallets/operations/utils', () => ({})); +jest.mock('src/store/sagas/bhr', () => ({})); +jest.mock('@react-native-firebase/app', () => ({ getApp: jest.fn() })); +jest.mock('@react-native-firebase/messaging', () => ({ + getMessaging: jest.fn(), + subscribeToTopic: jest.fn(), + unsubscribeFromTopic: jest.fn(), +})); +jest.mock('react-native-device-info', () => ({ getBuildNumber: () => '624' })); + +const previousVersion = '2.5.15'; +const newVersion = '2.5.16'; + +function writeHistory(action) { + const worker = updateVersionHistoryWorker(action); + expect(worker.next().value).toEqual(call(dbManager.getObjectByIndex, RealmSchema.KeeperApp)); + expect(worker.next({ id: 'test-app' } as any).value).toEqual( + call(Relay.updateAppImage, { appId: 'test-app', version: newVersion }) + ); + const write = worker.next({} as any).value as any; + expect(write.payload.fn).toBe(dbManager.createObject); + expect(write.payload.args[0]).toBe(RealmSchema.VersionHistory); + expect(worker.next().done).toBe(true); + return write.payload.args[1]; +} + +describe('Version History retains recovery provenance through required upgrades', () => { + test.each([true, false])('upgrade passes recovery=%s to the history writer', (isRecovery) => { + const upgrade = applyUpgradeSequence({ previousVersion, newVersion, isRecovery }); + expect(upgrade.next().value).toEqual(put(setAppVersion(newVersion))); + const history = upgrade.next().value as any; + expect(history).toEqual(put(updateVersionHistory(previousVersion, newVersion, isRecovery))); + const record = writeHistory(history.payload.action); + expect(record.version).toBe('2.5.16(624)'); + expect(record.title).toBe(isRecovery ? 'Recovered Wallet' : 'Upgraded from 2.5.15 to 2.5.16'); + expect(upgrade.next().done).toBe(true); + }); + + test('older callers still record ordinary upgrades by default', () => { + expect(writeHistory({ payload: { previousVersion, newVersion } }).title).toBe( + 'Upgraded from 2.5.15 to 2.5.16' + ); + }); + + test('recovery does not skip any of the legacy migrations', () => { + const ordinary = [...applyUpgradeSequence({ previousVersion: '1.0.4', newVersion })]; + const recovered = [ + ...applyUpgradeSequence({ previousVersion: '1.0.4', newVersion, isRecovery: true }), + ]; + expect(recovered.slice(0, -1)).toEqual(ordinary.slice(0, -1)); + expect(recovered.length).toBeGreaterThan(3); + }); +}); + +// Execute the real recovery orchestration with disposable in-memory dependencies. +// This verifies call-site provenance; it does not claim native Realm or wallet recovery QA. +function recoveryFixture(backupVersion: string) { + const source = ts.createSourceFile( + 'bhr.ts', + fs.readFileSync(path.join(process.cwd(), 'src/store/sagas/bhr.ts'), 'utf8'), + ts.ScriptTarget.Latest, + true + ); + const functions = source.statements.filter( + (node) => + ts.isFunctionDeclaration(node) && + ['getAppImageWorker', 'recoverApp', 'writeRecoveredObject'].includes(node.name?.text) + ); + const writes = new Map(); + const recoveryUpgrades = []; + const errors = []; + const scope: any = { + call, + put, + select, + semver, + console, + RealmSchema, + applyUpgradeSequence, + DeviceInfo: { getVersion: () => newVersion, getBuildNumber: () => '624' }, + bip39: { validateMnemonic: () => true, mnemonicToSeedSync: () => Buffer.from('fixture') }, + crypto: require('crypto'), + BIP85: { bip39MnemonicToEntropy: () => Buffer.from('fixture') }, + config: { BIP85_IMAGE_ENCRYPTIONKEY_DERIVATION_PATH: 'fixture' }, + generateEncryptionKey: () => 'fixture', + decrypt: (_key, content) => content, + prepareRecoveryImage: (_key, _appId, image) => ({ + wallets: Object.fromEntries( + Object.entries(image.wallets).map(([id, content]) => [id, JSON.parse(content as string)]) + ), + signers: {}, + vaults: {}, + nodes: {}, + labels: {}, + }), + WalletUtilities: { getFingerprintFromSeed: () => 'AAAAAAAA' }, + SubscriptionTier: { L1: 'L1', L3: 'L3' }, + AppSubscriptionLevel: { L1: 1, L3: 3 }, + BackupType: { SEED: 'SEED' }, + EntityKind: { USDT_WALLET: 'USDT_WALLET' }, + BackupAction: { SEED_BACKUP_CONFIRMED: 'confirmed' }, + NetworkType: { MAINNET: 'MAINNET', TESTNET: 'TESTNET' }, + uaiType: {}, + moment: () => ({ unix: () => 1 }), + setupRecoveryKeySigningKey: () => ({ + id: 'recovery', + signerXpubs: { + fixture: [ + { + xpub: 'fixture-public', + xpriv: 'fixture-private', + derivationPath: 'fixture-path', + }, + ], + }, + }), + getKeyUID: (signer) => signer.id, + addSigningDeviceWorker: () => {}, + dbManager: { + createObject: (schema, record) => { + if (schema === RealmSchema.VersionHistory) writes.set(record.version, record); + return true; + }, + createObjectBulk: () => {}, + getCollection: (schema) => + schema === RealmSchema.Signer + ? [ + { + id: 'recovery', + signerXpubs: { + fixture: [ + { + xpub: 'fixture-public', + xpriv: 'fixture-private', + derivationPath: 'fixture-path', + }, + ], + }, + }, + ] + : [], + }, + Relay: { + getAppImage: () => ({ + appImage: { + appId: 'disposable', + version: backupVersion, + wallets: { test: JSON.stringify({ id: 'test-wallet' }) }, + signers: {}, + nodes: [], + }, + }), + updateAppImage: () => ({}), + }, + }; + for (const name of [ + 'setAppImageError', + 'setSeedConfirmed', + 'setBackupType', + 'uaiActioned', + 'setAppId', + 'setAppCreated', + 'addAccount', + 'autoSyncWallets', + 'saveDefaultWalletState', + 'uaiChecks', + 'loadConciergeUser', + 'loadConciergeTickets', + 'setRecoveryKeyBackedUp', + 'setRecoveryKeyStatus', + 'appImagerecoveryRetry', + ]) { + scope[name] = (payload) => ({ type: name, payload }); + } + vm.runInNewContext( + ts.transpileModule(functions.map((node) => node.getText(source)).join('\n'), { + compilerOptions: { target: ts.ScriptTarget.ES2019 }, + }).outputText, + scope + ); + function drive(generator) { + let result = generator.next(); + while (!result.done) { + const effect = result.value; + let response; + if (effect.type === 'SELECT') response = { bitcoinNetworkType: 'TESTNET' }; + if (effect.type === 'CALL') { + const { fn, args } = effect.payload; + if (fn === applyUpgradeSequence) recoveryUpgrades.push(args[0]); + response = fn(...args); + if (response?.next) response = drive(response); + } + if (effect.type === 'PUT') { + const action = effect.payload.action; + if (action.type === 'setAppImageError' && action.payload) errors.push(action.payload); + if (action.type === 'UPDATE_VERSION_HISTORY') { + const record = writeHistory(action); + writes.set(record.version, record); + } + } + result = generator.next(response); + } + return result.value; + } + drive(scope.getAppImageWorker({ payload: { primaryMnemonic: 'disposable mocked fixture' } })); + return { writes, recoveryUpgrades, errors }; +} + +test.each(['2.5.15', '2.5.16'])( + 'recovery of backup %s finishes with one recovered entry', + (backupVersion) => { + const { writes, recoveryUpgrades, errors } = recoveryFixture(backupVersion); + expect(errors).toEqual([]); + expect([...writes.values()]).toEqual([ + expect.objectContaining({ + version: '2.5.16(624)', + title: 'Recovered Wallet', + }), + ]); + expect(recoveryUpgrades).toEqual( + backupVersion === '2.5.15' + ? [{ previousVersion: backupVersion, newVersion, isRecovery: true }] + : [] + ); + } +); From 380196e43ff4838094b6167dc7133f3ef238bd6f Mon Sep 17 00:00:00 2001 From: Anant Date: Tue, 29 Sep 2026 19:04:11 +0530 Subject: [PATCH 05/19] Open backup comparison from the home warning --- src/components/HomeScreenHeader.tsx | 3 +-- tests/recovery/backupFeedback.test.cjs | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/components/HomeScreenHeader.tsx b/src/components/HomeScreenHeader.tsx index ac9727a035..6a48c248e1 100644 --- a/src/components/HomeScreenHeader.tsx +++ b/src/components/HomeScreenHeader.tsx @@ -23,7 +23,6 @@ import useToastMessage from 'src/hooks/useToastMessage'; import { SignerType } from 'src/services/wallets/enums'; import useSignerMap from 'src/hooks/useSignerMap'; import { setStateFromSnapshot } from 'src/store/reducers/send_and_receive'; -import { backupAllSignersAndVaults } from 'src/store/sagaActions/bhr'; import Fonts from 'src/constants/Fonts'; import ThemedColor from './ThemedColor/ThemedColor'; @@ -164,7 +163,7 @@ const HomeScreenHeader: React.FC = ({ }, [uaiType.SERVER_BACKUP_FAILURE]: () => { dispatch(uaiActioned({ uaiId: localLatestUnseenUai.id, action: false })); - dispatch(backupAllSignersAndVaults()); + navigation.navigate('AssistedBackupStatus'); }, }; diff --git a/tests/recovery/backupFeedback.test.cjs b/tests/recovery/backupFeedback.test.cjs index 5656622b5a..c94c89b29d 100644 --- a/tests/recovery/backupFeedback.test.cjs +++ b/tests/recovery/backupFeedback.test.cjs @@ -52,3 +52,26 @@ for (const file of ['src/components/Backup/BackupHealthCheckList.tsx', 'src/scre assert.ok(!actions.some(a=>a.type==='enabled'&&a.value)); assert.ok(!ui.some(a=>(a[0]==='enabled'||a[0]==='success')&&a[1])); }); } + + +test('home backup warning opens comparison without starting a backup', () => { + const file = 'src/components/HomeScreenHeader.tsx'; + const source = ts.createSourceFile(file, fs.readFileSync(path.join(__dirname, '../..', file), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + let callback; + function visit(node) { + if (ts.isPropertyAssignment(node) && node.name.getText(source) === '[uaiType.SERVER_BACKUP_FAILURE]') callback = node.initializer.getText(source); + ts.forEachChild(node, visit); + } + visit(source); + assert.ok(callback); + const actions = [], destinations = []; + vm.runInNewContext(ts.transpileModule(`(${callback})()`, { compilerOptions: { target: ts.ScriptTarget.ES2020 } }).outputText, { + localLatestUnseenUai: { id: 'disposable-backup-warning' }, + dispatch: action => actions.push(action), + uaiActioned: payload => ({ type: 'uaiActioned', payload }), + backupAllSignersAndVaults: () => ({ type: 'backupAllSignersAndVaults' }), + navigation: { navigate: route => destinations.push(route) }, + }); + assert.deepEqual(destinations, ['AssistedBackupStatus']); + assert.ok(!actions.some(action => action.type === 'backupAllSignersAndVaults'), 'view details must not write a backup before the user chooses Back Up Now'); +}); From a224bc9fde6ffaea2dded9df51a11bb8909009da Mon Sep 17 00:00:00 2001 From: Anant Date: Fri, 2 Oct 2026 22:02:45 +0530 Subject: [PATCH 06/19] Add R02 current-state backup verification and faster login --- src/context/Localization/language/en.json | 6 +++--- src/context/Localization/language/es.json | 6 +++--- src/screens/LoginScreen/Login.tsx | 20 +++++++++++++++----- src/services/backup/image.ts | 9 ++++++++- src/services/backup/repair.ts | 5 ++++- src/store/sagas/login.ts | 20 ++++++-------------- tests/recovery/repair.test.cjs | 23 ++++++++++++++++++++--- tests/screens/PinEntry.test.tsx | 21 ++++++++++++++++++++- 8 files changed, 79 insertions(+), 31 deletions(-) diff --git a/src/context/Localization/language/en.json b/src/context/Localization/language/en.json index 446ba2d6cb..3a451be678 100644 --- a/src/context/Localization/language/en.json +++ b/src/context/Localization/language/en.json @@ -223,8 +223,8 @@ "failedToConnectTor": "Failed to connect to tor", "networkCallsAndTor": "Network calls and some functions may work slower when the Tor is enabled", "checkConnection": "Please check your internet connection and try again. If you continue offline, some features may not be available.", - "incorrectPassword": "Incorrect Password", - "youEnteredIncorrectPasscode": "The passcode you entered is incorrect. Please try again. If you’ve forgotten your passcode, you can recover your wallet using the Forgot Passcode flow with your recovery key.", + "incorrectPassword": "Incorrect passcode", + "youEnteredIncorrectPasscode": "The passcode you entered is incorrect. Try again.", "checkinternetConnection": "Please check your internet connection and try again.", "forgotPasscode": "Forgot passcode?", "resetPasscodeTitle": "Reset Passcode", @@ -2236,7 +2236,7 @@ }, "different": { "title": "Your backup needs updating", - "body": "Your Assisted Server Backup differs from this device. Back up now to update it, then Keeper will check that it matches." + "body": "Back Up Now replaces the server backup with this device’s current recovery data, including hidden and archived items. Items absent from this device will be removed from the backup. Check other Keeper devices first. Keeper will then read back and verify the result." }, "preparing": { "title": "Preparing your backup", diff --git a/src/context/Localization/language/es.json b/src/context/Localization/language/es.json index 8e95a7f68a..4670ae75db 100644 --- a/src/context/Localization/language/es.json +++ b/src/context/Localization/language/es.json @@ -223,8 +223,8 @@ "failedToConnectTor": "Failed to connect to tor", "networkCallsAndTor": "Network calls and some functions may work slower when the Tor is enabled", "checkConnection": "Please check your internet connection and try again. If you continue offline, some features may not be available.", - "incorrectPassword": "Incorrect Password", - "youEnteredIncorrectPasscode": "The passcode you entered is incorrect. Please try again. If you’ve forgotten your passcode, you can recover your wallet using the Forgot Passcode flow with your recovery key.", + "incorrectPassword": "Código incorrecto", + "youEnteredIncorrectPasscode": "El código introducido es incorrecto. Inténtalo de nuevo.", "checkinternetConnection": "Please check your internet connection and try again.", "forgotPasscode": "Forgot passcode?", "resetPasscodeTitle": "Reset Passcode", @@ -2217,7 +2217,7 @@ }, "different": { "title": "Actualiza tu copia", - "body": "Tu copia de seguridad asistida difiere de este dispositivo. Guarda una copia ahora y Keeper comprobará que coincide." + "body": "Guardar ahora reemplaza la copia del servidor con los datos de recuperación actuales de este dispositivo, incluidos los elementos ocultos y archivados. Los elementos que no estén en este dispositivo se eliminarán de la copia. Revisa primero tus otros dispositivos Keeper. Después, Keeper volverá a leer y verificar la copia." }, "preparing": { "title": "Preparando la copia", diff --git a/src/screens/LoginScreen/Login.tsx b/src/screens/LoginScreen/Login.tsx index 862b39879d..e28e8922c3 100644 --- a/src/screens/LoginScreen/Login.tsx +++ b/src/screens/LoginScreen/Login.tsx @@ -1,7 +1,7 @@ /* eslint-disable react/no-unstable-nested-components */ import Text from 'src/components/KeeperText'; import { Box, StatusBar, useColorMode } from '@gluestack-ui/themed-native-base'; -import React, { useContext, useEffect, useState, useMemo } from 'react'; +import React, { useContext, useEffect, useState, useMemo, useRef } from 'react'; import { Pressable, StyleSheet } from 'react-native'; import { widthPercentageToDP } from 'react-native-responsive-screen'; import { hp, windowWidth, wp } from 'src/constants/responsive'; @@ -104,6 +104,7 @@ function LoginScreen({ navigation, route }) { const { common } = translations; const { allAccounts, biometricEnabledAppId } = useAppSelector((state) => state.account); const [forgotModal, setForgotModal] = useState(false); + const completedLogin = useRef(false); const onChangeTorStatus = (status: TorStatus) => { settorStatus(status); @@ -262,8 +263,14 @@ function LoginScreen({ navigation, route }) { } }, [isAuthenticated, internalCheck]); + useEffect(() => { + if (isAuthenticated && !internalCheck) void loginModalAction(); + }, [isAuthenticated, internalCheck]); + const loginModalAction = async () => { - if (isAuthenticated) { + if (isAuthenticated && !completedLogin.current) { + completedLogin.current = true; + setLogging(false); setLoginModal(false); if (relogin) { navigation.navigate({ @@ -278,9 +285,12 @@ function LoginScreen({ navigation, route }) { navigation.reset({ index: 0, routes: [{ name: 'NewKeeperApp' }] }); } dispatch(credsAuthenticated(false)); - const res = await Relay.getAccountManagerDetails(appId); - if (res) dispatch(setAccountManagerDetails(res)); - else dispatch(setAccountManagerDetails(null)); + try { + const res = await Relay.getAccountManagerDetails(appId); + dispatch(setAccountManagerDetails(res || null)); + } catch { + dispatch(setAccountManagerDetails(null)); + } } }; diff --git a/src/services/backup/image.ts b/src/services/backup/image.ts index 1ef9342ddd..0a9446967b 100644 --- a/src/services/backup/image.ts +++ b/src/services/backup/image.ts @@ -105,7 +105,14 @@ export async function compareImages( for (const [id, record] of Object.entries(remote[kind])) { checkpoint(); const current = local[kind][id]; - if (!current || canonical(identity(kind, current)) !== canonical(identity(kind, record))) + // A server-only record may have been deliberately removed on this device. + // Surface it as a difference so the user can explicitly replace the + // backup with the current recoverable state. Never upload during a check. + if (!current) { + result = 'different'; + continue; + } + if (canonical(identity(kind, current)) !== canonical(identity(kind, record))) return 'conflict'; for (const counter of [ 'nextFreeAddressIndex', diff --git a/src/services/backup/repair.ts b/src/services/backup/repair.ts index afb8d67947..160ab288cb 100644 --- a/src/services/backup/repair.ts +++ b/src/services/backup/repair.ts @@ -205,7 +205,10 @@ export function inspectBackup( try { const response = await boundedBackupPost( `${config.RELAY}repairAppBackup`, - { ...payload, expectedRevision }, + // This explicit action replaces the server snapshot with the + // current local state, including intentional deletions. The relay + // still checks the revision atomically before accepting it. + { ...payload, expectedRevision, replaceCurrentState: true }, deadline ); if (response.data?.updated !== true) throw new Error('Backup rejected'); diff --git a/src/store/sagas/login.ts b/src/store/sagas/login.ts index 1f2c839f9a..35028a9bc8 100644 --- a/src/store/sagas/login.ts +++ b/src/store/sagas/login.ts @@ -1,4 +1,4 @@ -import { call, delay, put, race, select } from 'redux-saga/effects'; +import { call, put, select } from 'redux-saga/effects'; import { decrypt, encrypt, @@ -55,10 +55,10 @@ import { checkBackupFreshness } from '../sagaActions/bhr'; import { uaiChecks } from '../sagaActions/uai'; import { applyUpgradeSequence } from './upgrade'; import { resetSyncing } from '../reducers/wallets'; +import { autoSyncWallets } from '../sagaActions/wallets'; import { connectToNode } from '../sagaActions/network'; import { fetchDelayedPolicyUpdate, fetchSignedDelayedTransaction } from '../sagaActions/storage'; import { setAutomaticCloudBackup, setBackupType } from '../reducers/bhr'; -import { autoWalletsSyncWorker } from './wallets'; import { addAccount, saveDefaultWalletState, @@ -225,16 +225,10 @@ function* credentialsAuthWorker({ payload }) { yield put(fetchExchangeRates()); yield put(fetchSignedDelayedTransaction()); yield put(fetchDelayedPolicyUpdate()); - yield race({ - sync: call(autoWalletsSyncWorker, { - payload: { - syncAll: false, - hardRefresh: false, - addNotifications: true, - }, - }), - timeout: delay(15000), - }); + // Wallet/node refresh runs through its watcher after local unlock. + // Waiting for network work here can hold the success modal for 15s. + yield put(resetSyncing()); + yield put(autoSyncWallets(false, false, true)); yield put( uaiChecks([ @@ -247,8 +241,6 @@ function* credentialsAuthWorker({ payload }) { ]) ); - yield put(resetSyncing()); - const { pendingAllBackup, automaticCloudBackup, diff --git a/tests/recovery/repair.test.cjs b/tests/recovery/repair.test.cjs index c6b7d39151..f72053092f 100644 --- a/tests/recovery/repair.test.cjs +++ b/tests/recovery/repair.test.cjs @@ -26,9 +26,26 @@ test('lost upload acknowledgement is resolved by readback without duplicate uplo assert.equal(await f.run(true), 'verified'); assert.deepEqual(f.calls, ['getBackupSnapshot','repairAppBackup','getBackupSnapshot']); }); -test('server-only wallet is preserved and blocks replacement', async () => { - const f = harness(); f.remote.wallets.other = encryption.encrypt(encryption.generateEncryptionKey(f.app.primarySeed), JSON.stringify(wallet('other'))); - assert.equal(await f.run(true), 'conflict'); assert.deepEqual(f.calls, ['getBackupSnapshot']); assert.ok(f.remote.wallets.other); +test('server-only wallet needs user action, then repair removes it and verifies readback', async () => { + const f = harness({ post: async ({ path, payload }) => { + if (path.endsWith('repairAppBackup')) assert.equal(payload.replaceCurrentState, true); + } }); f.remote.wallets.other = encryption.encrypt(encryption.generateEncryptionKey(f.app.primarySeed), JSON.stringify(wallet('other'))); + assert.equal(await f.run(), 'different'); assert.deepEqual(f.calls, ['getBackupSnapshot']); assert.ok(f.remote.wallets.other); + assert.equal(await f.run(true), 'verified'); assert.deepEqual(f.calls.slice(1), ['getBackupSnapshot','repairAppBackup','getBackupSnapshot']); + assert.equal(f.remote.wallets.other, undefined); +}); + +test('current-state repair keeps hidden keys and archived wallets while dropping deleted records', async () => { + const f = harness(); + const key = encryption.generateEncryptionKey(f.app.primarySeed); + f.local.Signer.push({ id:'hidden-key', masterFingerprint:'hidden', signerXpubs:{}, hidden:true }); + f.local.Vault.push({ ...wallet('archived'), archived:true, signers:[], scheme:{m:1,n:1} }); + f.remote.wallets.deleted = encryption.encrypt(key, JSON.stringify(wallet('deleted'))); + assert.equal(await f.run(), 'different'); + assert.equal(await f.run(true), 'verified'); + assert.equal(f.remote.wallets.deleted, undefined); + assert.equal(JSON.parse(encryption.decrypt(key, f.remote.signers['hidden-key'])).hidden, true); + assert.deepEqual(f.remote.vaults, ['archived']); }); test('same IDs with different recovery keys are a conflict', async () => { diff --git a/tests/screens/PinEntry.test.tsx b/tests/screens/PinEntry.test.tsx index 42d7deb06e..8c47e37b08 100644 --- a/tests/screens/PinEntry.test.tsx +++ b/tests/screens/PinEntry.test.tsx @@ -56,7 +56,10 @@ jest.mock('src/services/rest/RestClient', () => ({ TorStatus: {}, })); jest.mock('src/storage/realm/dbManager', () => ({})); -jest.mock('src/services/backend/Relay', () => ({})); +jest.mock('src/services/backend/Relay', () => ({ + __esModule: true, + default: { getAccountManagerDetails: jest.fn(async () => null) }, +})); jest.mock('react-native-biometrics', () => jest.fn(() => ({}))); jest.mock('@react-native-firebase/app', () => ({ getApp: jest.fn() })); jest.mock('@react-native-firebase/messaging', () => ({ @@ -88,6 +91,7 @@ function mount(component: React.ReactElement) { beforeEach(() => { jest.useFakeTimers(); mockDispatch.mockClear(); + mockState.login.isAuthenticated = false; }); afterEach(() => { act(() => screen?.unmount()); @@ -96,6 +100,21 @@ afterEach(() => { }); describe('PIN entry under batched rapid taps', () => { + test('successful local authentication enters the app without a second tap', async () => { + const navigation = { replace: jest.fn() }; + const route = { params: {} }; + mount(); + await act(async () => { + mockState.login.isAuthenticated = true; + screen.update(); + }); + expect(navigation.replace).toHaveBeenCalledWith('App'); + await act(async () => { + screen.update(); + }); + expect(navigation.replace).toHaveBeenCalledTimes(1); + }); + test('login keeps every digit, caps at four and deletes in order', () => { mount(); enter('123456'); From 5254796dabb56f56d5c2aeb52e7d79c242112c53 Mon Sep 17 00:00:00 2001 From: Anant Date: Mon, 5 Oct 2026 17:58:48 +0530 Subject: [PATCH 07/19] fix: complete backup and timelock validation for 2.6.2 --- android/app/build.gradle | 4 +- ios/hexa_keeper.xcodeproj/project.pbxproj | 16 +- package.json | 2 +- release/README.md | 10 +- release/version.json | 22 +- src/hooks/useSignerIntel.tsx | 10 +- src/screens/Vault/AddEmergencyKey.tsx | 8 +- src/screens/Vault/AddReserveKey.tsx | 10 +- src/screens/Vault/AddSigningDevice.tsx | 47 +- .../Vault/VaultMigrationController.tsx | 52 +- src/services/backup/image.ts | 51 +- src/services/backup/repair.ts | 51 +- src/store/sagas/bhr.ts | 28 +- tests/recovery/restoreIntegrity.test.cjs | 25 + tests/recovery/sagaHarness.cjs | 1 + tests/recovery/sharedVaultRepair.test.cjs | 96 +++ tests/recovery/signerPersistence.test.cjs | 37 ++ tests/recovery/vaultPersistence.test.cjs | 49 ++ .../addReserveTimelockBoundary.test.ts | 561 ++++++++++++++++++ .../services/addSigningDeviceTimelock.test.ts | 450 ++++++++++++++ 20 files changed, 1449 insertions(+), 81 deletions(-) create mode 100644 tests/recovery/sharedVaultRepair.test.cjs create mode 100644 tests/recovery/signerPersistence.test.cjs create mode 100644 tests/recovery/vaultPersistence.test.cjs create mode 100644 tests/services/addReserveTimelockBoundary.test.ts create mode 100644 tests/services/addSigningDeviceTimelock.test.ts diff --git a/android/app/build.gradle b/android/app/build.gradle index c2f737d4d3..eebb1acfe2 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -98,8 +98,8 @@ android { applicationId "io.hexawallet.keeper" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 624 - versionName "2.5.17" + versionCode 625 + versionName "2.6.2" missingDimensionStrategy 'react-native-camera', 'general' missingDimensionStrategy 'store', 'play' multiDexEnabled true diff --git a/ios/hexa_keeper.xcodeproj/project.pbxproj b/ios/hexa_keeper.xcodeproj/project.pbxproj index 88ff8d481f..52aa23ef44 100644 --- a/ios/hexa_keeper.xcodeproj/project.pbxproj +++ b/ios/hexa_keeper.xcodeproj/project.pbxproj @@ -748,7 +748,7 @@ CODE_SIGN_ENTITLEMENTS = hexa_keeper/hexa_keeper.entitlements; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 617; + CURRENT_PROJECT_VERSION = 618; DEVELOPMENT_TEAM = Y5TCB759QL; ENABLE_BITCODE = NO; HEADER_SEARCH_PATHS = ( @@ -849,7 +849,7 @@ "$(inherited)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.17; + MARKETING_VERSION = 2.6.2; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -876,7 +876,7 @@ CODE_SIGN_IDENTITY = "Apple Development"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 617; + CURRENT_PROJECT_VERSION = 618; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; HEADER_SEARCH_PATHS = ( @@ -977,7 +977,7 @@ "$(inherited)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.17; + MARKETING_VERSION = 2.6.2; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1147,7 +1147,7 @@ CODE_SIGN_IDENTITY = "Apple Development"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 617; + CURRENT_PROJECT_VERSION = 618; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; ENABLE_BITCODE = NO; @@ -1250,7 +1250,7 @@ "$(PROJECT_DIR)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.17; + MARKETING_VERSION = 2.6.2; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1278,7 +1278,7 @@ CODE_SIGN_ENTITLEMENTS = hexa_keeper_dev.entitlements; CODE_SIGN_IDENTITY = "Apple Distribution"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; - CURRENT_PROJECT_VERSION = 617; + CURRENT_PROJECT_VERSION = 618; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; HEADER_SEARCH_PATHS = ( @@ -1380,7 +1380,7 @@ "$(PROJECT_DIR)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.5.17; + MARKETING_VERSION = 2.6.2; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", diff --git a/package.json b/package.json index 072f11b411..dc78f187da 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hexa_keeper", - "version": "2.5.17", + "version": "2.6.2", "private": true, "scripts": { "ios": "npx react-native run-ios --scheme=hexa_keeper_dev --simulator 'iPhone 16' ", diff --git a/release/README.md b/release/README.md index ea88ab6702..4e484e0251 100644 --- a/release/README.md +++ b/release/README.md @@ -1,15 +1,17 @@ # Release version verification -**Current milestone:** Now candidate 2.5.17: Recovery Key backup comparison/repair and complete data restore, Version History, PIN handling, and the privately reviewed timelock prevention change. Keep advisory details and private fixtures out of public release material. +**Current milestone:** R02 / 2.6.2: faster entry after local authentication, Assisted Server Backup current-state correctness, narrow timelock prevention, and the selected cloud credential follow-ups. Keep private advisory details, credentials and fixtures out of public release material. -`version.json` selects 2.5.17, Android 624 and iOS 617. Authenticated Google Play evidence on 29 September shows highest uploaded Android code 623; App Store Connect shows latest iOS upload 2.5.16 (616), Complete, and the production version Ready for Distribution. Refresh store baselines again before upload. The paired Recovery relay is deployed and its live encrypted repair/readback smoke passed. Independent security acceptance and final physical testing remain pending. +`version.json` selects 2.6.2, Android 625 and iOS 618. Authenticated store checks on 5 October 2026 found highest uploaded Android code 624 and iOS build 617, both at 2.5.17. Refresh these baselines before upload. Development builds and local relay validation are separate from reviewed production builds, deployment and store submission. R02 is not released. + +For R02, the owner accepts real-phone upgrade, Face ID and camera feedback after release. Do not require Developer Mode or physical-device connections to finish preparation. Record simulator, automated and funded testnet evidence accurately; they do not establish physical or hardware-signer acceptance. Already-affected-wallet assessment and consented repair are scheduled for R04 / 2.6.3; R03 is the backend open-source milestone. 1. Read all uploaded builds and release tracks for Android package `io.hexawallet.bitcoinkeeper`, and uploaded iOS builds for `io.hexawallet.keeper`. Preserve the timestamp and evidence outside the repository. Refresh before upload; preflight accepts evidence at most 24 hours old. 2. Update the manifest with the highest known marketing version and highest uploaded build per platform. Select one greater marketing version for both stores and greater platform build counters. Check unpublished App Store version records as well. 3. Run `npm run version:apply` to synchronize package.json, Android versionName/versionCode and both Keeper iOS targets. Both Info.plist files must reference `$(CURRENT_PROJECT_VERSION)` and `$(MARKETING_VERSION)`; hardcoded values are rejected. Review the diff, then run `npm run version:check` and `npm run test:release`. 4. Reconcile release source with the published versions, prepare a clean release checkout and set `KEEPER_RELEASE_COMMIT` to its complete verified commit SHA. Run `npm run release:preflight`. The manifest cannot contain its own commit SHA. 5. Build from a reviewed production configuration and existing signing identities. Check extracted IPA, APK and AAB metadata against the manifest, verify signing fingerprints and record checksums. A source preflight does not verify the resulting binaries. -6. Test the signed builds, including upgrades, before public submission. +6. Test the signed builds before public submission; record the R02 physical-device deferral above separately. Both existing Fastlane `live` lanes run preflight before building and consume `.env.production` without downloading over `.env`. They no longer increment production build numbers. Android notifications require explicit `KEEPER_NOTIFY_SLACK=1`. @@ -29,7 +31,7 @@ Android production signing reads `STORE_PASSWORD`, `KEY_PASSWORD`, and `KEY_ALIA ## Manual release checks -- Upgrade an existing installation with a designated test wallet on a physical iPhone and Android device; do not uninstall first. Confirm unlock, wallet visibility and settings survive. +- Post-release for R02 by owner decision: upgrade an existing installation with a designated test wallet on a physical iPhone and Android device; do not uninstall first. Confirm unlock, wallet visibility and settings survive. - Check the displayed marketing version and native build counter against the release manifest on both platforms. - Open Ask Keeper on both platforms and send a non-sensitive sample question to the intended backend. Confirm the response and error/retry behavior; local isolated-backend entry checks do not test AI responses. - Open Wallet Settings > Dust Report. Check an empty test wallet, then a designated testnet fixture with Do Not Spend coins. Confirm the report, ordinary-spend exclusion, and Donate Dust confirmation/amount/fee behavior. Record separately whether a testnet signing transaction completed; an empty-wallet result cannot verify donation. diff --git a/release/version.json b/release/version.json index 9a4e7ebc01..553cacad87 100644 --- a/release/version.json +++ b/release/version.json @@ -1,21 +1,21 @@ { - "version": "2.5.17", - "androidVersionCode": 624, - "iosBuildNumber": 617, + "version": "2.6.2", + "androidVersionCode": 625, + "iosBuildNumber": 618, "baselines": { "android": { "applicationId": "io.hexawallet.bitcoinkeeper", - "verifiedAt": "2026-09-29T10:32:44Z", - "highestUploadedBuild": 623, - "highestMarketingVersion": "2.5.16", - "productionRelease": "623 (2.5.16)" + "verifiedAt": "2026-10-05T10:04:03Z", + "highestUploadedBuild": 624, + "highestMarketingVersion": "2.5.17", + "productionRelease": "624 (2.5.17)" }, "ios": { "applicationId": "io.hexawallet.keeper", - "verifiedAt": "2026-09-29T12:45:29.673796+00:00", - "highestUploadedBuild": 616, - "highestMarketingVersion": "2.5.16", - "productionRelease": "616 (2.5.16)" + "verifiedAt": "2026-10-05T10:04:36Z", + "highestUploadedBuild": 617, + "highestMarketingVersion": "2.5.17", + "productionRelease": "617 (2.5.17)" } } } diff --git a/src/hooks/useSignerIntel.tsx b/src/hooks/useSignerIntel.tsx index adef347341..e76f725862 100644 --- a/src/hooks/useSignerIntel.tsx +++ b/src/hooks/useSignerIntel.tsx @@ -1,4 +1,4 @@ -import { MiniscriptTypes, SignerType } from 'src/services/wallets/enums'; +import { SignerType } from 'src/services/wallets/enums'; import { getSignerNameFromType, isSignerAMF } from 'src/hardware'; import { SubscriptionTier } from 'src/models/enums/SubscriptionTier'; import { VaultScheme, VaultSigner } from 'src/services/wallets/interfaces/vault'; @@ -64,11 +64,9 @@ const useSignerIntel = ({ areSignersValid = false; } else { const signerCount = Array.from(selectedSigners.keys()).length; - const maxKeys = scheme?.miniscriptScheme?.usedMiniscriptTypes?.includes( - MiniscriptTypes.INHERITANCE - ) - ? scheme.n + 1 - : scheme.n; + // AddSigningDevice selects the primary quorum. Inheritance and Emergency + // Keys are retained/configured separately and must not disable this step. + const maxKeys = scheme.n; areSignersValid = signerCount > 0 && !( diff --git a/src/screens/Vault/AddEmergencyKey.tsx b/src/screens/Vault/AddEmergencyKey.tsx index b13a5a2f10..83a24e8d14 100644 --- a/src/screens/Vault/AddEmergencyKey.tsx +++ b/src/screens/Vault/AddEmergencyKey.tsx @@ -92,7 +92,7 @@ function AddEmergencyKey({ route }) { const isDarkMode = colorMode === 'dark'; useEffect(() => { - if (selectedSigner || keyToRotate) return; + if (selectedSigner) return; if ( !activeVault?.id || @@ -110,7 +110,7 @@ function AddEmergencyKey({ route }) { (key) => key.masterFingerprint === emergencyKeyFingerprint ); - if (emergencyKey) { + if (emergencyKey && (!keyToRotate || getKeyUID(emergencyKey) !== getKeyUID(keyToRotate))) { setSelectedSigner([emergencyKey]); } }, [activeVault?.id, keyToRotate, selectedSigner]); @@ -149,6 +149,7 @@ function AddEmergencyKey({ route }) { isAddInheritanceKey, isAddEmergencyKey, hasInitialTimelock, + initialTimelockDuration, currentBlockHeight, onGoBack: (signer) => setSelectedSigner(signer), }); @@ -161,6 +162,7 @@ function AddEmergencyKey({ route }) { isAddInheritanceKey, isAddEmergencyKey, hasInitialTimelock, + initialTimelockDuration, currentBlockHeight, ]); @@ -302,7 +304,7 @@ function AddEmergencyKey({ route }) { emergencyKeys={ selectedSigner ? [{ key: selectedSigner[0], duration: selectedOption.label }] : [] } - initialTimelockDuration={initialTimelockDuration ?? 0} + initialTimelockDuration={initialTimelockDuration} currentBlockHeight={currentBlockHeight} miniscriptTypes={[ ...(hasInitialTimelock ? [MiniscriptTypes.TIMELOCKED] : []), diff --git a/src/screens/Vault/AddReserveKey.tsx b/src/screens/Vault/AddReserveKey.tsx index 51fa4dd5fd..fdcf2db141 100644 --- a/src/screens/Vault/AddReserveKey.tsx +++ b/src/screens/Vault/AddReserveKey.tsx @@ -98,7 +98,7 @@ function AddReserveKey({ route }) { const isDarkMode = colorMode === 'dark'; useEffect(() => { - if (selectedSigner || keyToRotate) return; + if (selectedSigner) return; if ( !activeVault?.id || @@ -117,7 +117,7 @@ function AddReserveKey({ route }) { (key) => key.masterFingerprint === inheritanceKeyFingerprint ); - if (inheritanceKey) { + if (inheritanceKey && (!keyToRotate || getKeyUID(inheritanceKey) !== getKeyUID(keyToRotate))) { setSelectedSigner([inheritanceKey]); } }, [activeVault?.id, keyToRotate, selectedSigner]); @@ -156,6 +156,7 @@ function AddReserveKey({ route }) { isAddInheritanceKey, isAddEmergencyKey, hasInitialTimelock, + initialTimelockDuration, currentBlockHeight, onGoBack: (signer) => setSelectedSigner(signer), }); @@ -168,6 +169,7 @@ function AddReserveKey({ route }) { isAddInheritanceKey, isAddEmergencyKey, hasInitialTimelock, + initialTimelockDuration, currentBlockHeight, ]); @@ -322,10 +324,10 @@ function AddReserveKey({ route }) { inheritanceKeys={ selectedSigner ? [{ key: selectedSigner[0], duration: selectedOption.label }] : [] } - initialTimelockDuration={initialTimelockDuration ?? 0} + initialTimelockDuration={initialTimelockDuration} currentBlockHeight={currentBlockHeight} miniscriptTypes={[ - ...(initialTimelockDuration ? [MiniscriptTypes.TIMELOCKED] : []), + ...(hasInitialTimelock ? [MiniscriptTypes.TIMELOCKED] : []), MiniscriptTypes.INHERITANCE, ]} setVaultCreatedModalVisible={setVaultCreatedModalVisible} diff --git a/src/screens/Vault/AddSigningDevice.tsx b/src/screens/Vault/AddSigningDevice.tsx index 4143c03f8b..300a814692 100644 --- a/src/screens/Vault/AddSigningDevice.tsx +++ b/src/screens/Vault/AddSigningDevice.tsx @@ -243,8 +243,27 @@ const setInitialKeys = ( keyToRotate ) => { if (activeVault) { - // setting initital keys (update if scheme has changed) - const vaultKeys = activeVault.signers.filter( + const isEnhancedVault = + activeVault.type === VaultType.MINISCRIPT && + activeVault.scheme?.miniscriptScheme?.usedMiniscriptTypes?.some((type) => + [ + MiniscriptTypes.TIMELOCKED, + MiniscriptTypes.INHERITANCE, + MiniscriptTypes.EMERGENCY, + ].includes(type) + ); + // Select the stored primary K roles before limiting the number of keys. + const primaryFingerprints = new Set( + Object.entries( + activeVault.scheme?.miniscriptScheme?.miniscriptElements?.signerFingerprints || {} + ) + .filter(([identifier]) => /^K[1-9]\d*$/.test(identifier)) + .map(([, fingerprint]) => fingerprint) + ); + const existingKeys = isEnhancedVault + ? activeVault.signers.filter((key) => primaryFingerprints.has(key.masterFingerprint)) + : activeVault.signers; + const vaultKeys = existingKeys.filter( (key) => keyToRotate && getKeyUID(key) !== getKeyUID(keyToRotate) ); const isMultisig = @@ -361,6 +380,7 @@ function Footer({ isCollaborativeFlow, isAssistedWalletFlow, hasInitialTimelock, + initialTimelockDuration, isReserveKeyFlow, isEmergencyKeyFlow, isAddInheritanceKey, @@ -409,7 +429,7 @@ function Footer({ primaryLoading={relayVaultUpdateLoading} primaryText={keyToRotate ? 'Replace Key' : common.proceed} primaryCallback={ - !hasInitialTimelock + !hasInitialTimelock || initialTimelockDuration !== undefined ? !isAddInheritanceKey ? !isAddEmergencyKey ? keyToRotate @@ -423,11 +443,13 @@ function Footer({ isHotWallet, vaultType, hasInitialTimelock, + initialTimelockDuration, isAddInheritanceKey, currentBlockHeight, hotWalletInstanceNum, selectedSigners: signersList, vaultId, + keyToRotate, }); } : () => @@ -461,8 +483,10 @@ function Footer({ isAddInheritanceKey, isAddEmergencyKey, hasInitialTimelock, + initialTimelockDuration, currentBlockHeight, selectedSigners: signersList, + keyToRotate, }) ) : () => @@ -489,8 +513,10 @@ function Footer({ isAddInheritanceKey, isAddEmergencyKey, hasInitialTimelock, + initialTimelockDuration, currentBlockHeight, selectedSigners: signersList, + keyToRotate, }) ) : () => @@ -504,8 +530,10 @@ function Footer({ isAddInheritanceKey, isAddEmergencyKey, hasInitialTimelock, + initialTimelockDuration, currentBlockHeight, selectedSigners: signersList, + keyToRotate, }) ) } @@ -1174,6 +1202,7 @@ function AddSigningDevice() { isNewSchemeFlow?: boolean; signerFilters?: SignerType | Array; hasInitialTimelock?: boolean; + initialTimelockDuration?: string; }; }; const { @@ -1191,7 +1220,8 @@ function AddSigningDevice() { selectedSignersFromParams, isAddInheritanceKey: isAddInheritanceKeyParam = false, isAddEmergencyKey: isAddEmergencyKeyParam = false, - hasInitialTimelock, + hasInitialTimelock: hasInitialTimelockParam, + initialTimelockDuration, isNewSchemeFlow = false, currentBlockHeight, signerFilters = [], @@ -1216,6 +1246,13 @@ function AddSigningDevice() { const [vaultKeys, setVaultKeys] = useState([]); const { activeVault, allVaults } = useVault({ vaultId }); const scheme = isNewSchemeFlow ? schemeParam : activeVault ? activeVault.scheme : schemeParam; + // Existing wallets keep their policy requirement even if a caller drops the route flag. + const hasInitialTimelock = isNewSchemeFlow + ? hasInitialTimelockParam + : hasInitialTimelockParam || + activeVault?.scheme?.miniscriptScheme?.usedMiniscriptTypes?.includes( + MiniscriptTypes.TIMELOCKED + ); const isAddInheritanceKey = isNewSchemeFlow ? isAddInheritanceKeyParam : activeVault @@ -1466,6 +1503,7 @@ function AddSigningDevice() { setCreating={setCreating} vaultType={vaultType} currentBlockHeight={currentBlockHeight} + initialTimelockDuration={initialTimelockDuration} miniscriptTypes={[ ...(hasInitialTimelock ? [MiniscriptTypes.TIMELOCKED] : []), ...(isAddInheritanceKey ? [MiniscriptTypes.INHERITANCE] : []), @@ -1519,6 +1557,7 @@ function AddSigningDevice() { isAddInheritanceKey={isAddInheritanceKey} isAddEmergencyKey={isAddEmergencyKey} hasInitialTimelock={hasInitialTimelock} + initialTimelockDuration={initialTimelockDuration} currentBlockHeight={currentBlockHeight} onGoBack={onGoBack} vaultKeys={vaultKeys} diff --git a/src/screens/Vault/VaultMigrationController.tsx b/src/screens/Vault/VaultMigrationController.tsx index 66736912d3..d0ea0f63d7 100644 --- a/src/screens/Vault/VaultMigrationController.tsx +++ b/src/screens/Vault/VaultMigrationController.tsx @@ -305,9 +305,33 @@ function VaultMigrationController({ // The getCurrentTimeForLock and getTimelockDuration control whether // a vault created will use UNIX timestamp or block height based timelocks. - const getCurrentTimeForLock = () => { + const getCurrentTimeForLock = async () => { if (activeVault && isVaultUsingBlockHeightTimelock(activeVault)) { - return currentBlockHeight; + let currentSyncedBlockHeight = currentBlockHeight; + if ( + !Number.isSafeInteger(currentSyncedBlockHeight) || + currentSyncedBlockHeight <= 0 || + currentSyncedBlockHeight >= 500000000 + ) { + try { + currentSyncedBlockHeight = (await WalletUtilities.fetchCurrentBlockHeight()) + .currentBlockHeight; + } catch { + throw new Error( + 'Failed to fetch current chain data, please check your connection and try again' + ); + } + } + if ( + !Number.isSafeInteger(currentSyncedBlockHeight) || + currentSyncedBlockHeight <= 0 || + currentSyncedBlockHeight >= 500000000 + ) { + throw new Error( + 'Failed to fetch current chain data, please check your connection and try again' + ); + } + return currentSyncedBlockHeight; } return Math.floor(Date.now() / 1000); }; @@ -383,23 +407,7 @@ function VaultMigrationController({ ); const multisigScriptType = MultisigScriptType.MINISCRIPT_MULTISIG; - // let currentSyncedBlockHeight = currentBlockHeight; - // if (!currentSyncedBlockHeight) { - // try { - // currentSyncedBlockHeight = (await WalletUtilities.fetchCurrentBlockHeight()) - // .currentBlockHeight; - // } catch (err) { - // console.log('Failed to re-fetch current block height: ' + err); - // } - // if (!currentSyncedBlockHeight) { - // showToast( - // 'Failed to fetch current chain data, please check your connection and try again', - // - // ); - // setCreating(false); - // return; - // } - // } + const currentTimeForLock = await getCurrentTimeForLock(); const inheritanceSignerWithTimelocks = []; const emergencySignerWithTimelocks = []; @@ -413,7 +421,7 @@ function VaultMigrationController({ } inheritanceSignerWithTimelocks.push({ signer: key, - timelock: getCurrentTimeForLock() + initialTimelock + timelock, + timelock: currentTimeForLock + initialTimelock + timelock, }); } } @@ -427,7 +435,7 @@ function VaultMigrationController({ } emergencySignerWithTimelocks.push({ signer: key, - timelock: getCurrentTimeForLock() + initialTimelock + timelock, + timelock: currentTimeForLock + initialTimelock + timelock, }); } } @@ -437,7 +445,7 @@ function VaultMigrationController({ inheritanceSignerWithTimelocks, emergencySignerWithTimelocks, vaultInfo.vaultScheme, - initialTimelock ? getCurrentTimeForLock() + initialTimelock : 0 + initialTimelock ? currentTimeForLock + initialTimelock : 0 ); if (!miniscriptElements) { diff --git a/src/services/backup/image.ts b/src/services/backup/image.ts index 0a9446967b..f4e7ca668a 100644 --- a/src/services/backup/image.ts +++ b/src/services/backup/image.ts @@ -65,6 +65,41 @@ export function recoveryContent(kind: keyof BackupImage, record: any) { return { ...result, specs }; } +function vaultSchemeIdentity(scheme: any) { + const miniscript = scheme?.miniscriptScheme; + const elements = miniscript?.miniscriptElements; + if (!elements) return scheme; + const keyIdentity = (key: any) => ({ + ...key, + uniqueKeyIdentifier: key.uniqueKeyIdentifier ?? null, + }); + // Realm defaults optional key identifiers to null and does not persist the + // compiler's phase weights. Compare the compiled policy/script unchanged; + // only then can these non-persisted weights be excluded from key identity. + const hasCompiledPolicy = !!miniscript.miniscript && !!miniscript.miniscriptPolicy; + return { + ...scheme, + miniscriptScheme: { + ...miniscript, + miniscriptElements: { + ...elements, + keysInfo: elements.keysInfo?.map(keyIdentity), + phases: elements.phases?.map((phase: any) => { + const normalized = { + ...phase, + paths: phase.paths?.map((path: any) => ({ + ...path, + keys: path.keys?.map(keyIdentity), + })), + }; + if (hasCompiledPolicy) delete normalized.probability; + return normalized; + }), + }, + }, + }; +} + function identity(kind: keyof BackupImage, record: any) { if (kind === 'wallets') return { @@ -81,14 +116,26 @@ function identity(kind: keyof BackupImage, record: any) { if (kind === 'vaults') return { networkType: record.networkType, - scheme: record.scheme, + scheme: vaultSchemeIdentity(record.scheme), signers: record.signers, scriptType: record.scriptType, }; if (kind === 'signers') return { masterFingerprint: record.masterFingerprint, - signerXpubs: record.signerXpubs, + // Realm adds empty script-type lists when a newly added signer is saved. + // Incremental backups can contain the pre-persistence form. Empty lists + // do not change key identity; populated lists and private keys still do. + signerXpubs: Object.fromEntries( + Object.entries(record.signerXpubs || {}) + .filter(([, keys]) => !Array.isArray(keys) || keys.length > 0) + .map(([type, keys]) => [ + type, + Array.isArray(keys) + ? keys.map((key) => ({ ...key, xpriv: key.xpriv ?? null })) + : keys, + ]) + ), networkType: record.networkType, type: record.type, }; diff --git a/src/services/backup/repair.ts b/src/services/backup/repair.ts index 160ab288cb..25b543c7a1 100644 --- a/src/services/backup/repair.ts +++ b/src/services/backup/repair.ts @@ -167,6 +167,7 @@ export function inspectBackup( const local = await captureBackupImage(assertCurrent); assertCurrent(); let expectedRevision: string; + let needsVaultRepair = false; const read = async () => { const response = await boundedBackupPost( `${config.RELAY}getBackupSnapshot`, @@ -177,10 +178,50 @@ export function inspectBackup( if (!/^[a-f0-9]{64}$/.test(response.data?.revision)) throw new Error('Backup snapshot revision unavailable'); expectedRevision = response.data.revision; - return decodeImage(key, response.data, appId, assertCurrent); + const unavailable = response.data.unavailableVaultIds ?? []; + if (!Array.isArray(unavailable) || new Set(unavailable).size !== unavailable.length) + throw new Error('Invalid unavailable backup records'); + const references = response.data.appImage?.vaults; + if ( + unavailable.length && + (!Array.isArray(references) || + new Set(references).size !== references.length || + unavailable.some( + (id) => + typeof id !== 'string' || + !id || + !references.includes(id) || + response.data.allVaultImages?.some((record) => record.vaultId === id) + )) + ) + throw new Error('Invalid unavailable backup references'); + // A legacy shared-wallet image may have been overwritten by another + // participant. The relay withholds that participant's ciphertext. Only + // this explicit backup check may compare the remaining records; clean + // restore still rejects the incomplete reference list. + const availableResponse = unavailable.length + ? { + ...response.data, + appImage: { + ...response.data.appImage, + vaults: references.filter((id) => !unavailable.includes(id)), + }, + } + : response.data; + const decoded = await decodeImage(key, availableResponse, appId, assertCurrent); + needsVaultRepair = + unavailable.length > 0 || + response.data.allVaultImages.some( + (record) => + typeof record.isArchived === 'boolean' && + record.isArchived !== !!decoded.vaults[record.vaultId]?.archived + ); + return decoded; }; const remote = await read(); - const comparison = await compareImages(local, remote, assertCurrent); + const contentComparison = await compareImages(local, remote, assertCurrent); + const comparison = + contentComparison === 'matched' && needsVaultRepair ? 'different' : contentComparison; assertCurrent(); if (comparison === 'conflict') { notify('conflict'); @@ -216,7 +257,11 @@ export function inspectBackup( // A lost response is not proof the upload failed. Always read back. } notify('verifying'); - if ((await compareImages(local, await read(), assertCurrent)) !== 'matched') + const verifiedRemote = await read(); + if ( + needsVaultRepair || + (await compareImages(local, verifiedRemote, assertCurrent)) !== 'matched' + ) throw new Error('Backup not verified'); } if ( diff --git a/src/store/sagas/bhr.ts b/src/store/sagas/bhr.ts index c60ec711eb..206aaceb2d 100644 --- a/src/store/sagas/bhr.ts +++ b/src/store/sagas/bhr.ts @@ -1,7 +1,7 @@ import { buffers, END, eventChannel } from 'redux-saga'; import { inspectBackup, RepairPhase } from 'src/services/backup/repair'; import { prepareRecoveryImage } from 'src/services/backup/restore'; -import { BackupImage } from 'src/services/backup/image'; +import { BackupImage, pauseBackup } from 'src/services/backup/image'; import { markBackupMutation } from 'src/services/backup/transport'; import * as bip39 from 'bip39'; import { Wallet } from 'src/services/wallets/interfaces/wallet'; @@ -189,16 +189,6 @@ export function* updateVaultImageWorker({ JSON.stringify(sanitizeVaultSignersForSeedKeyBackup(vault)) ); - if (isUpdate) { - const response = yield call(Relay.updateVaultImage, { - isUpdate, - appId: id, - vaultId: vault.id, - vault: vaultEncrypted, - }); - return response; - } - const signersData: Array<{ signerId: string; xfpHash: string; @@ -211,6 +201,18 @@ export function* updateVaultImageWorker({ }); } + if (isUpdate) { + const response = yield call(Relay.updateVaultImage, { + isUpdate, + signersData, + appId: id, + vaultId: vault.id, + vault: vaultEncrypted, + isArchived: !!vault.archived, + }); + return response; + } + // TODO to be removed const subscriptionStrings = JSON.stringify(subscription); @@ -220,6 +222,7 @@ export function* updateVaultImageWorker({ vaultId: vault.id, signersData, vault: vaultEncrypted, + isArchived: !!vault.archived, subscription: subscriptionStrings, ...(archiveVaultId && { archiveVaultId }), }); @@ -705,6 +708,9 @@ function* writeRecoveredObject(schema: RealmSchema, record: any) { // throwing. Never count that record as recovered or report partial success. const written = yield call(dbManager.createObject, schema, record); if (written !== true) throw new Error('Recovery data unavailable'); + // Realm writes complete synchronously. Break the saga's synchronous effect + // chain between records so a large restore cannot exhaust the JS stack. + yield call(pauseBackup); } function* healthCheckSatutsUpdateWorker({ diff --git a/tests/recovery/restoreIntegrity.test.cjs b/tests/recovery/restoreIntegrity.test.cjs index dc2b4f6025..8ff08e3c1e 100644 --- a/tests/recovery/restoreIntegrity.test.cjs +++ b/tests/recovery/restoreIntegrity.test.cjs @@ -64,6 +64,31 @@ function recoveryFixture() { const completed = (f) => f.actions.some((a) => a.type === 'setAppCreated' && a.payload === true); const errors = (f) => f.actions.filter((a) => a.type === 'setAppImageError' && a.payload); +test( + 'hundreds of synchronous Realm writes complete recovery without stalling', + { timeout: 15000 }, + async () => { + const f = recoveryFixture(); + const key = encryption.generateEncryptionKey(f.app.primarySeed); + const labels = Array.from({ length: 600 }, (_, index) => ({ + id: `label-${index}`, + label: `Saved label ${index}`, + ref: `tx-${index}`, + type: 'TXN', + })); + f.response.labels = labels.map((label) => ({ + id: `encrypted-${label.id}`, + content: encryption.encrypt(key, JSON.stringify(label)), + })); + f.remote.labels = f.response.labels.map((label) => label.id); + await f.restore(); + assert.deepEqual(errors(f), []); + assert.equal(completed(f), true); + assert.deepEqual(plain(f.collections.Tags), labels); + assert.equal(f.actions.at(-1).type, 'appImagerecoveryRetry'); + } +); + test('clean recovery recreates keys, BTC/USDT, archived vault, labels and custom nodes', async () => { const f = recoveryFixture(); await f.restore(); diff --git a/tests/recovery/sagaHarness.cjs b/tests/recovery/sagaHarness.cjs index 3a378a08d9..ab82a1d9c4 100644 --- a/tests/recovery/sagaHarness.cjs +++ b/tests/recovery/sagaHarness.cjs @@ -118,6 +118,7 @@ function fixture(options = {}) { ...enums, ...account, prepareRecoveryImage, + pauseBackup: image.pauseBackup, console: { log() {}, error() {} }, Buffer, _: require('lodash'), diff --git a/tests/recovery/sharedVaultRepair.test.cjs b/tests/recovery/sharedVaultRepair.test.cjs new file mode 100644 index 0000000000..7b9027b846 --- /dev/null +++ b/tests/recovery/sharedVaultRepair.test.cjs @@ -0,0 +1,96 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { encryption, image, harness, wallet, loadModule } = require('./helpers.cjs'); +const { prepareRecoveryImage } = loadModule('src/services/backup/restore.ts', { './image': image }); +const clone = value => JSON.parse(JSON.stringify(value)); +function fixture({ unavailable = ['shared'], leaveUnavailable = false } = {}) { + const state = { + appImage: { appId:'disposable', wallets:{}, signers:{}, nodes:[], vaults:['shared'], labels:[] }, + allVaultImages:[], labels:[], unavailableVaultIds:unavailable, revision:'a'.repeat(64), + }; + let uploads=0; + const f=harness({ adapter:async (endpoint,payload) => { + if(endpoint==='getBackupSnapshot') return {data:clone(state)}; + assert.equal(endpoint,'repairAppBackup'); + assert.equal(payload.expectedRevision,state.revision); + assert.equal(payload.replaceCurrentState,true); + uploads++; + Object.assign(state.appImage, {wallets:payload.walletObject,signers:payload.signersObject, + nodes:payload.nodes,vaults:Object.keys(payload.vaultObject),labels:payload.labels.map(v=>v.id)}); + state.allVaultImages=Object.values(payload.vaultObject); + state.labels=payload.labels; + if (!leaveUnavailable) state.unavailableVaultIds=[]; + state.revision='b'.repeat(64); + return {data:{updated:true}}; + }}); + f.local.Vault.push({...wallet('shared'),signers:[],scheme:{m:1,n:1},archived:false}); + const key=encryption.generateEncryptionKey(f.app.primarySeed); + return {f,state,key,uploads:()=>uploads}; +} +test('unavailable collaborative ciphertext requires user action and cannot be clean-restored',async()=>{ + const {f,state,key,uploads}=fixture(); + assert.equal(await f.run(),'different'); + assert.equal(uploads(),0); + assert.deepEqual(f.calls,['getBackupSnapshot']); + await assert.rejects(prepareRecoveryImage(key,f.app.id,state.appImage,state.allVaultImages,state.labels)); +}); +test('explicit local resubmission replaces missing account copy and verifies clean recovery',async()=>{ + const {f,state,key,uploads}=fixture(); + assert.equal(await f.run(true),'verified'); + assert.equal(uploads(),1); + assert.deepEqual(state.unavailableVaultIds,[]); + const recovered=await prepareRecoveryImage(key,f.app.id,state.appImage,state.allVaultImages,state.labels); + assert.deepEqual(clone(recovered.vaults.shared),f.local.Vault[0]); + assert.deepEqual(f.calls,['getBackupSnapshot','repairAppBackup','getBackupSnapshot']); +}); +test('missing server-only vault cannot look matched; explicit current-state replacement removes it',async()=>{ + const {f,state,uploads}=fixture(); f.local.Vault.length=0; + assert.equal(await f.run(),'different'); assert.equal(uploads(),0); + assert.equal(await f.run(true),'verified'); + assert.deepEqual(state.appImage.vaults,[]); assert.equal(uploads(),1); +}); +for(const problem of ['identity','ahead address counter']) test(`available ${problem} conflict still blocks missing-copy repair`,async()=>{ + const {f,state,key,uploads}=fixture(); + f.local.Wallet.push(wallet('other')); const remote=wallet('other'); + if(problem==='identity') remote.specs.xpub='another-key'; + else remote.specs.nextFreeAddressIndex=2; + state.appImage.wallets.other=encryption.encrypt(key,JSON.stringify(remote)); + assert.equal(await f.run(true),'conflict'); assert.equal(uploads(),0); +}); +for(const unavailable of [['not-referenced'],['shared','shared'],[null],'shared']) test(`malformed missing-copy metadata cannot authorize an upload: ${JSON.stringify(unavailable)}`,async()=>{ + const {f,uploads}=fixture({unavailable}); + assert.equal(await f.run(true),'unverified'); assert.equal(uploads(),0); +}); +test('an acknowledged upload that still has unavailable vaults is never verified',async()=>{ + const {f,uploads}=fixture({leaveUnavailable:true}); + assert.equal(await f.run(true),'unverified'); assert.equal(uploads(),1); +}); +test('archive metadata mismatch is read-only until explicit backup and must match after readback',async()=>{ + const {f,state,key,uploads}=fixture({unavailable:[]}); + f.local.Vault[0].archived=true; + state.allVaultImages=[{vaultId:'shared',vault:encryption.encrypt(key,JSON.stringify(f.local.Vault[0])),isArchived:false}]; + assert.equal(await f.run(),'different'); assert.equal(uploads(),0); + assert.equal(await f.run(true),'verified'); assert.equal(uploads(),1); + assert.equal(state.allVaultImages[0].isArchived,true); +}); + +for(const archived of [true,false]) test(`existing-wallet update carries signer maps and archive state: archived=${archived}`,async()=>{ + const {fixture:sagaFixture,enums,signer}=require('./sagaHarness.cjs'); + const f=sagaFixture(); + const device=signer('AABBCCDD',enums.NetworkType.MAINNET,enums.SignerType.LEDGER,0); + device.id=f.scope.getKeyUID(device); + f.collections.Signer.push(device); + const key={masterFingerprint:device.masterFingerprint,...device.signerXpubs[enums.XpubTypes.P2WPKH][0]}; + const vault={id:'reinstated',networkType:enums.NetworkType.MAINNET,signers:[key],scheme:{m:1,n:1},archived}; + let uploaded; + f.scope.Relay.updateVaultImage=async payload=>{uploaded=payload;return {updated:true};}; + await f.run('updateVaultImageWorker',{payload:{vault,isUpdate:true}}); + assert.equal(uploaded.appId,f.app.id); + assert.equal(uploaded.isArchived,archived); + assert.equal(uploaded.signersData.length,1); + assert.equal(uploaded.signersData[0].signerId,f.scope.getKeyUID(key)); + assert.equal(uploaded.signersData[0].xfpHash,encryption.hash256(key.masterFingerprint)); + const restored=JSON.parse(encryption.decrypt(encryption.generateEncryptionKey(f.app.primarySeed),uploaded.vault)); + assert.equal(restored.archived,uploaded.isArchived); + assert.equal(restored.signers[0].masterFingerprint,key.masterFingerprint); +}); diff --git a/tests/recovery/signerPersistence.test.cjs b/tests/recovery/signerPersistence.test.cjs new file mode 100644 index 0000000000..6924c4b385 --- /dev/null +++ b/tests/recovery/signerPersistence.test.cjs @@ -0,0 +1,37 @@ +const assert = require('node:assert/strict'); +const { test } = require('node:test'); +const { loadModule, image, makeImage } = require('./helpers.cjs'); +const { RealmSchema } = loadModule('src/storage/realm/enum.ts'); +const XpubTypes = Object.fromEntries(['AMF', 'P2PKH', 'P2SH-P2WPKH', 'P2SH-P2WSH', 'P2TR', 'P2WPKH', 'P2WSH'].map(type => [type, type])); +const schemas = loadModule('src/storage/realm/schema/vault.ts', { + '../enum': { RealmSchema }, 'src/services/wallets/enums': { XpubTypes }, +}); +// Use the real storage schema defaults without requiring a native Realm binary +// in CI. The native validation additionally checks an actual Realm round trip. +const emptyScriptLists = Object.fromEntries(Object.keys(schemas.SignerXpubsSchema.properties).map(type => [type, []])); +const signer = { masterFingerprint: '12345678', type: 'MOBILE_KEY', networkType: 'TESTNET', signerXpubs: { + P2WSH: [{ xpub: 'disposable-xpub', derivationPath: "m/48'/1'/0'/2'" }], +}}; +function pair() { + const local = makeImage(), remote = makeImage(); + remote.signers.key = structuredClone(signer); + local.signers.key = { ...structuredClone(signer), signerXpubs: { ...emptyScriptLists, P2WSH: [{ ...signer.signerXpubs.P2WSH[0], xpriv: null }] } }; + return { local, remote }; +} +test('Realm empty script lists and absent optional private key do not block backup repair', async () => { + const { local, remote } = pair(); + assert.equal(await image.compareImages(local, remote), 'different'); + assert.equal(await image.compareImages(local, structuredClone(local)), 'matched'); +}); +for (const field of ['xpub', 'derivationPath', 'xpriv']) { + test(`a changed signer ${field} remains a conflict`, async () => { + const { local, remote } = pair(); + local.signers.key.signerXpubs.P2WSH[0][field] = 'different-key-material'; + assert.equal(await image.compareImages(local, remote), 'conflict'); + }); +} +test('a populated script group must not be discarded as a Realm default', async () => { + const { local, remote } = pair(); + local.signers.key.signerXpubs.P2TR = [{ xpub: 'another-xpub', derivationPath: "m/86'/1'/0'" }]; + assert.equal(await image.compareImages(local, remote), 'conflict'); +}); diff --git a/tests/recovery/vaultPersistence.test.cjs b/tests/recovery/vaultPersistence.test.cjs new file mode 100644 index 0000000000..e0956f7529 --- /dev/null +++ b/tests/recovery/vaultPersistence.test.cjs @@ -0,0 +1,49 @@ +const assert = require('node:assert/strict'); +const { test } = require('node:test'); +const { image, loadModule, makeImage } = require('./helpers.cjs'); +const { RealmSchema } = loadModule('src/storage/realm/enum.ts'); +const schemas = loadModule('src/storage/realm/schema/vault.ts', { + '../enum': { RealmSchema }, 'src/services/wallets/enums': { XpubTypes: {} }, +}); +function pair() { + assert.equal(schemas.MiniscriptKeyInfoSchema.properties.uniqueKeyIdentifier, 'string?'); + assert.equal(schemas.MiniscriptPhaseSchema.properties.probability, undefined); + const key = { identifier: 'K1', descriptor: 'disposable-descriptor' }; + const remote = makeImage(), local = makeImage(); + remote.vaults.vault = { id: 'vault', networkType: 'TESTNET', scriptType: 'P2WSH', signers: [], + scheme: { m: 1, n: 1, miniscriptScheme: { + usedMiniscriptTypes: ['TIMELOCKED'], miniscriptPolicy: 'and(after(155000),pk(K1))', + miniscript: 'and_v(v:pk(K1),after(155000))', + miniscriptElements: { keysInfo: [key], phases: [{ id: 1, timelock: 155000, + probability: 99, requiredPaths: 1, paths: [{ id: 1, threshold: 1, keys: [{ ...key, uniqueKeyIdentifier: 'K1<0;1>' }] }] }] }, + } }, specs: {} }; + local.vaults.vault = structuredClone(remote.vaults.vault); + const elements = local.vaults.vault.scheme.miniscriptScheme.miniscriptElements; + elements.keysInfo[0].uniqueKeyIdentifier = null; + delete elements.phases[0].probability; + return { local, remote }; +} +test('new enhanced vault remains repairable after Realm normalizes policy metadata', async () => { + const { local, remote } = pair(); + assert.equal(await image.compareImages(local, remote), 'different'); + assert.equal(await image.compareImages(local, structuredClone(local)), 'matched'); +}); +for (const [name, mutate] of [ + ['primary timelock', s => { s.miniscriptElements.phases[0].timelock = 0; }], + ['key descriptor', s => { s.miniscriptElements.keysInfo[0].descriptor = 'changed'; }], + ['path key identifier', s => { s.miniscriptElements.phases[0].paths[0].keys[0].uniqueKeyIdentifier = 'K2<0;1>'; }], + ['compiled policy', s => { s.miniscriptPolicy = 'pk(K1)'; }], + ['compiled script', s => { s.miniscript = 'pk(K1)'; }], +]) { + test(`changed ${name} still blocks automatic replacement`, async () => { + const { local, remote } = pair(); + mutate(local.vaults.vault.scheme.miniscriptScheme); + assert.equal(await image.compareImages(local, remote), 'conflict'); + }); +} +test('phase weights remain significant when no compiled policy is available', async () => { + const { local, remote } = pair(); + delete local.vaults.vault.scheme.miniscriptScheme.miniscriptPolicy; + delete remote.vaults.vault.scheme.miniscriptScheme.miniscriptPolicy; + assert.equal(await image.compareImages(local, remote), 'conflict'); +}); diff --git a/tests/services/addReserveTimelockBoundary.test.ts b/tests/services/addReserveTimelockBoundary.test.ts new file mode 100644 index 0000000000..27baf07150 --- /dev/null +++ b/tests/services/addReserveTimelockBoundary.test.ts @@ -0,0 +1,561 @@ +import fs from 'fs'; +import path from 'path'; +import vm from 'vm'; +import ts from 'typescript'; +import idx from 'idx'; +import { resolveInitialTimelock } from 'src/services/wallets/operations/miniscript/initialTimelock'; +import { + MiniscriptTypes, + MultisigScriptType, + NetworkType, + VaultType, +} from 'src/services/wallets/enums'; +import * as durations from 'src/screens/Vault/constants'; +import { + ENHANCED_VAULT_TIMELOCKS_BLOCK_HEIGHT_MAINNET, + ENHANCED_VAULT_TIMELOCKS_BLOCK_HEIGHT_TESTNET, + ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_MAINNET, + ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_TESTNET, + INHERITANCE_KEY_IDENTIFIER, + EMERGENCY_KEY_IDENTIFIER, + generateEnhancedVaultElements, +} from 'src/services/wallets/operations/miniscript/default/EnhancedVault'; +import { generateMiniscriptPolicy } from 'src/services/wallets/operations/miniscript/policy-generator'; +import { generateMiniscript } from 'src/services/wallets/operations/miniscript/miniscript'; + +jest.mock('src/utils/utilities', () => ({ getKeyUID: (s) => s.masterFingerprint })); +jest.mock('src/utils/service-utilities/utils', () => ({ + getDerivationPath: (p) => p.replace('m/', ''), +})); + +// Evaluate the actual TSX expressions and controller/factory functions. This +// exercises the screen boundary without rendering native UI or using wallet data. +function readSource(relativePath: string) { + return ts.createSourceFile( + relativePath, + fs.readFileSync(path.join(process.cwd(), relativePath), 'utf8'), + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX + ); +} + +function variableExpression(source: ts.SourceFile, name: string) { + let expression: ts.Expression; + function visit(node: ts.Node) { + if (ts.isVariableDeclaration(node) && node.name.getText(source) === name) { + expression = node.initializer; + } + ts.forEachChild(node, visit); + } + visit(source); + if (!expression) throw new Error(`Missing production variable ${name}`); + return expression; +} + +function execute(expression: ts.Expression, source: ts.SourceFile, scope: any) { + vm.runInNewContext( + ts.transpileModule(`result = (${expression.getText(source)});`, { + fileName: 'screen-boundary.tsx', + compilerOptions: { target: ts.ScriptTarget.ES2019, jsx: ts.JsxEmit.React }, + }).outputText, + scope + ); + return scope.result; +} + +function migrationProps(source: ts.SourceFile, scope: any) { + let component: ts.JsxOpeningLikeElement; + function visit(node: ts.Node) { + if ( + (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) && + node.tagName.getText(source) === 'VaultMigrationController' + ) { + component = node; + } + ts.forEachChild(node, visit); + } + visit(source); + if (!component) throw new Error('Missing production VaultMigrationController'); + const props: any = {}; + for (const attribute of component.attributes.properties) { + if (!ts.isJsxAttribute(attribute)) continue; + const name = attribute.name.getText(source); + if ( + !['miniscriptTypes', 'initialTimelockDuration', 'inheritanceKeys', 'emergencyKeys'].includes( + name + ) + ) + continue; + if (!attribute.initializer || !ts.isJsxExpression(attribute.initializer)) continue; + props[name] = execute(attribute.initializer.expression, source, scope); + } + return props; +} + +function proceedCallback(source: ts.SourceFile, scope: any) { + let expression: ts.Expression; + function visit(node: ts.Node) { + if (ts.isJsxAttribute(node) && node.name.getText(source) === 'primaryCallback') { + if (node.initializer && ts.isJsxExpression(node.initializer)) { + expression = node.initializer.expression; + } + } + ts.forEachChild(node, visit); + } + visit(source); + if (!expression) throw new Error('Missing production primaryCallback'); + return execute(expression, source, scope); +} + +const reserveSource = readSource('src/screens/Vault/AddReserveKey.tsx'); +const emergencySource = readSource('src/screens/Vault/AddEmergencyKey.tsx'); +const controllerSource = readSource('src/screens/Vault/VaultMigrationController.tsx'); +const factorySource = readSource('src/services/wallets/factories/VaultFactory.ts'); +const mk = (masterFingerprint: string) => ({ + masterFingerprint, + derivationPath: "m/48'/0'/0'/2'", + xpub: `xpub${masterFingerprint}`, + account: 0, +}); + +function screenScope(hasInitialTimelock: boolean, initialTimelockDuration: any) { + return { + MiniscriptTypes, + hasInitialTimelock, + initialTimelockDuration, + selectedSigner: [mk('DDDDDDDD')], + selectedOption: { label: durations.MONTHS_12 }, + inheritanceKeys: [{ key: mk('DDDDDDDD'), duration: durations.MONTHS_12 }], + }; +} + +function controllerFixture(network: NetworkType, blockHeight: boolean) { + const base = blockHeight ? 950000 : 1767225600; + const scope: any = { + ...durations, + resolveInitialTimelock, + MiniscriptTypes, + VaultType, + NetworkType, + MultisigScriptType, + ENHANCED_VAULT_TIMELOCKS_BLOCK_HEIGHT_MAINNET, + ENHANCED_VAULT_TIMELOCKS_BLOCK_HEIGHT_TESTNET, + ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_MAINNET, + ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_TESTNET, + generateEnhancedVaultElements: jest.fn(generateEnhancedVaultElements), + generateMiniscriptPolicy, + generateMiniscript, + bitcoinNetworkType: network, + currentBlockHeight: base, + activeVault: { + scheme: { miniscriptScheme: { miniscriptElements: { timelocks: [base] } } }, + }, + Date: { now: () => base * 1000 }, + WalletUtilities: { + fetchCurrentBlockHeight: jest.fn().mockRejectedValue(new Error('Disposable offline fixture')), + }, + idx, + getKeyUID: (key) => key.masterFingerprint, + showToast: jest.fn(), + ErrorText: { invalidDuration: 'Invalid duration' }, + React: { createElement: () => null }, + ToastErrorIcon: () => null, + }; + for (const name of ['isVaultUsingBlockHeightTimelock', 'generateMiniscriptScheme']) { + scope[name] = execute(variableExpression(factorySource, name), factorySource, scope); + } + for (const name of ['getCurrentTimeForLock', 'getTimelockDuration', 'prepareMiniscriptScheme']) { + scope[name] = execute(variableExpression(controllerSource, name), controllerSource, scope); + } + const table = blockHeight + ? network === NetworkType.MAINNET + ? ENHANCED_VAULT_TIMELOCKS_BLOCK_HEIGHT_MAINNET + : ENHANCED_VAULT_TIMELOCKS_BLOCK_HEIGHT_TESTNET + : network === NetworkType.MAINNET + ? ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_MAINNET + : ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_TESTNET; + const info: any = { + vaultType: VaultType.MINISCRIPT, + vaultScheme: { m: 2, n: 3 }, + vaultSigners: [mk('AAAAAAAA'), mk('BBBBBBBB'), mk('CCCCCCCC')], + }; + return { scope, info, base, table }; +} + +function migrationCaller(scope: any, info: any, props: any) { + scope.activeVault.id = 'disposable'; + Object.assign(scope, { + vaultType: VaultType.MINISCRIPT, + scheme: info.vaultScheme, + vaultKeys: info.vaultSigners, + name: 'Disposable fixture', + description: '', + miniscriptTypes: props.miniscriptTypes, + inheritanceKeys: props.inheritanceKeys, + emergencyKeys: props.emergencyKeys, + initialTimelockDuration: props.initialTimelockDuration, + allVaults: [], + archivedVaults: [], + vaultAlreadyExists: jest.fn(() => false), + dispatch: jest.fn(), + migrateVault: jest.fn((newVaultInfo, vaultId) => ({ + type: 'DISPOSABLE_MIGRATION_FIXTURE', + newVaultInfo, + vaultId, + })), + addNewVault: jest.fn(), + generateVaultId: jest.fn(), + setGeneratedVaultId: jest.fn(), + setSavedGeneratedVaultId: jest.fn(), + setCreating: jest.fn(), + captureError: jest.fn(), + }); + return execute(variableExpression(controllerSource, 'initiateNewVault'), controllerSource, scope); +} + +const invalidHeights = [null, undefined, 0, -1, NaN, 950000.5, '950000', 500000000]; +const chainDataError = + 'Failed to fetch current chain data, please check your connection and try again'; + +describe('Actual block-height replacement refuses missing or invalid chain data', () => { + test.each(invalidHeights)( + 'preparation rejects invalid supplied and fetched height %s before policy construction', + async (height) => { + const props = migrationProps(reserveSource, screenScope(true, durations.MONTHS_6)); + const { scope, info } = controllerFixture(NetworkType.MAINNET, true); + scope.currentBlockHeight = height; + scope.WalletUtilities.fetchCurrentBlockHeight.mockResolvedValue({ + currentBlockHeight: height, + }); + await expect( + scope.prepareMiniscriptScheme( + info, + props.miniscriptTypes, + props.inheritanceKeys, + props.emergencyKeys, + props.initialTimelockDuration + ) + ).rejects.toThrow(chainDataError); + expect(scope.WalletUtilities.fetchCurrentBlockHeight).toHaveBeenCalledTimes(1); + expect(scope.generateEnhancedVaultElements).not.toHaveBeenCalled(); + expect(info).not.toHaveProperty('miniscriptElements'); + expect(info.vaultScheme).toEqual({ m: 2, n: 3 }); + } + ); + + test.each(invalidHeights)( + 'actual migration caller does not dispatch for current height %s', + async (height) => { + const props = migrationProps(reserveSource, screenScope(true, durations.MONTHS_6)); + const { scope, info } = controllerFixture(NetworkType.MAINNET, true); + scope.currentBlockHeight = height; + const initiate = migrationCaller(scope, info, props); + await initiate(); + expect(scope.WalletUtilities.fetchCurrentBlockHeight).toHaveBeenCalledTimes(1); + expect(scope.dispatch).not.toHaveBeenCalled(); + expect(scope.migrateVault).not.toHaveBeenCalled(); + expect(scope.addNewVault).not.toHaveBeenCalled(); + expect(scope.vaultAlreadyExists).not.toHaveBeenCalled(); + expect(scope.generateEnhancedVaultElements).not.toHaveBeenCalled(); + expect(scope.scheme).toEqual({ m: 2, n: 3 }); + expect(scope.setCreating).toHaveBeenCalledWith(false); + expect(scope.showToast).toHaveBeenCalledWith( + `Failed to prepare enhanced vault: ${chainDataError}`, + null + ); + expect(scope.captureError).toHaveBeenCalledTimes(1); + } + ); + + test.each(invalidHeights)( + 'timestamp wallet timing is unaffected by irrelevant height %s', + async (height) => { + const props = migrationProps(reserveSource, screenScope(true, durations.MONTHS_6)); + const { scope, info, base, table } = controllerFixture(NetworkType.MAINNET, false); + scope.currentBlockHeight = height; + await scope.prepareMiniscriptScheme( + info, + props.miniscriptTypes, + props.inheritanceKeys, + props.emergencyKeys, + props.initialTimelockDuration + ); + expect( + info.vaultScheme.miniscriptScheme.miniscriptElements.phases.map((phase) => phase.timelock) + ).toEqual([base + table.MONTHS_6, base + table.MONTHS_6 + table.MONTHS_12]); + expect(scope.WalletUtilities.fetchCurrentBlockHeight).not.toHaveBeenCalled(); + } + ); + + test('the same migration caller recovers after reconnecting and uses one fetched phase anchor', async () => { + const props = migrationProps(emergencySource, { + ...screenScope(true, durations.MONTHS_6), + selectedSigner: [mk('EEEEEEEE')], + selectedOption: { label: durations.MONTHS_36 }, + }); + const { scope, info, table } = controllerFixture(NetworkType.MAINNET, true); + const fetchedHeight = 975000; + scope.currentBlockHeight = null; + const fetchHeight = scope.WalletUtilities.fetchCurrentBlockHeight; + fetchHeight + .mockRejectedValueOnce(new Error('Disposable offline fixture')) + .mockResolvedValueOnce({ currentBlockHeight: fetchedHeight }); + const initiate = migrationCaller(scope, info, props); + + await initiate(); + expect(scope.dispatch).not.toHaveBeenCalled(); + expect(scope.generateEnhancedVaultElements).not.toHaveBeenCalled(); + expect(scope.scheme).toEqual({ m: 2, n: 3 }); + expect(scope.showToast).toHaveBeenCalledWith( + `Failed to prepare enhanced vault: ${chainDataError}`, + null + ); + expect(scope.setCreating).toHaveBeenCalledWith(false); + + // Repeat the same closure; no screen remount or prop/state change repairs it. + await initiate(); + expect(fetchHeight).toHaveBeenCalledTimes(2); + expect(scope.currentBlockHeight).toBeNull(); + expect(scope.generateEnhancedVaultElements).toHaveBeenCalledTimes(1); + expect(scope.migrateVault).toHaveBeenCalledTimes(1); + expect(scope.dispatch).toHaveBeenCalledTimes(1); + expect(scope.addNewVault).not.toHaveBeenCalled(); + const [replacement, vaultId] = scope.migrateVault.mock.calls[0]; + expect(vaultId).toBe('disposable'); + expect(scope.dispatch).toHaveBeenCalledWith({ + type: 'DISPOSABLE_MIGRATION_FIXTURE', + newVaultInfo: replacement, + vaultId, + }); + const expected = [ + fetchedHeight + table.MONTHS_6, + fetchedHeight + table.MONTHS_6 + table.MONTHS_12, + fetchedHeight + table.MONTHS_6 + table.MONTHS_36, + ]; + const replacementScheme = replacement.vaultScheme.miniscriptScheme; + expect(replacementScheme.miniscriptElements.phases.map((phase) => phase.timelock)).toEqual( + expected + ); + for (const timelock of expected) + expect(replacementScheme.miniscriptPolicy).toContain(`after(${timelock})`); + expect(replacementScheme.usedMiniscriptTypes).toEqual([ + MiniscriptTypes.TIMELOCKED, + MiniscriptTypes.INHERITANCE, + MiniscriptTypes.EMERGENCY, + ]); + expect(scope.captureError).toHaveBeenCalledTimes(1); + }); +}); + +describe('AddReserveKey production migration boundary', () => { + test.each([undefined, null, '', 0, NaN, -1, 'invalid'])( + 'retains required TIMELOCKED and rejects missing/invalid duration %s', + async (duration) => { + const props = migrationProps(reserveSource, screenScope(true, duration)); + expect(props.miniscriptTypes).toContain(MiniscriptTypes.TIMELOCKED); + const { scope, info } = controllerFixture(NetworkType.MAINNET, false); + await expect( + scope.prepareMiniscriptScheme( + info, + props.miniscriptTypes, + props.inheritanceKeys, + props.emergencyKeys, + props.initialTimelockDuration + ) + ).rejects.toThrow('initial timelock duration'); + expect(info).not.toHaveProperty('miniscriptElements'); + expect(info.vaultScheme).not.toHaveProperty('miniscriptScheme'); + } + ); + + test.each([ + ['mainnet timestamp', NetworkType.MAINNET, false], + ['testnet timestamp', NetworkType.TESTNET, false], + ['mainnet height', NetworkType.MAINNET, true], + ['testnet height', NetworkType.TESTNET, true], + ])( + 'preserves primary and inheritance timing through actual policy generation (%s)', + async (_name, network: NetworkType, blockHeight: boolean) => { + const props = migrationProps(reserveSource, screenScope(true, durations.MONTHS_6)); + const { scope, info, base, table } = controllerFixture(network, blockHeight); + await scope.prepareMiniscriptScheme( + info, + props.miniscriptTypes, + props.inheritanceKeys, + props.emergencyKeys, + props.initialTimelockDuration + ); + const scheme = info.vaultScheme.miniscriptScheme; + const expected = [base + table.MONTHS_6, base + table.MONTHS_6 + table.MONTHS_12]; + expect(scheme.miniscriptElements.phases.map((phase) => phase.timelock)).toEqual(expected); + for (const timelock of expected) + expect(scheme.miniscriptPolicy).toContain(`after(${timelock})`); + expect(scheme.usedMiniscriptTypes).toContain(MiniscriptTypes.TIMELOCKED); + } + ); + + test('preserves primary, inheritance and emergency timing across both add-key screens', async () => { + const navigate = jest.fn(); + proceedCallback(reserveSource, { + ...screenScope(true, durations.MONTHS_6), + navigation: { navigate }, + isAddEmergencyKey: true, + isAddInheritanceKey: true, + vaultKeys: [mk('AAAAAAAA'), mk('BBBBBBBB'), mk('CCCCCCCC')], + vaultId: 'disposable', + scheme: { m: 2, n: 3 }, + name: 'Disposable fixture', + description: '', + currentBlockHeight: 950000, + route: { params: { selectedSigners: [] } }, + keyToRotate: mk('FFFFFFFF'), + setCreating: jest.fn(), + VaultType, + })(); + expect(navigate.mock.calls[0][0]).toBe('AddEmergencyKey'); + const nextParams = navigate.mock.calls[0][1]; + expect(nextParams.hasInitialTimelock).toBe(true); + expect(nextParams.initialTimelockDuration).toBe(durations.MONTHS_6); + const props = migrationProps(emergencySource, { + ...nextParams, + MiniscriptTypes, + selectedSigner: [mk('EEEEEEEE')], + selectedOption: { label: durations.MONTHS_36 }, + }); + const { scope, info, base, table } = controllerFixture(NetworkType.MAINNET, false); + await scope.prepareMiniscriptScheme( + info, + props.miniscriptTypes, + props.inheritanceKeys, + props.emergencyKeys, + props.initialTimelockDuration + ); + const scheme = info.vaultScheme.miniscriptScheme; + const expected = [ + base + table.MONTHS_6, + base + table.MONTHS_6 + table.MONTHS_12, + base + table.MONTHS_6 + table.MONTHS_36, + ]; + expect(scheme.miniscriptElements.phases.map((phase) => phase.timelock)).toEqual(expected); + for (const timelock of expected) + expect(scheme.miniscriptPolicy).toContain(`after(${timelock})`); + }); + + test.each([undefined, null, '', 0])( + 'accepts a legitimate no-initial-lock wallet (%s)', + async (duration) => { + const props = migrationProps(reserveSource, screenScope(false, duration)); + expect(props.miniscriptTypes).not.toContain(MiniscriptTypes.TIMELOCKED); + const { scope, info, base, table } = controllerFixture(NetworkType.MAINNET, false); + await scope.prepareMiniscriptScheme( + info, + props.miniscriptTypes, + props.inheritanceKeys, + props.emergencyKeys, + props.initialTimelockDuration + ); + expect( + info.vaultScheme.miniscriptScheme.miniscriptElements.phases.map((phase) => phase.timelock) + ).toEqual([0, base + table.MONTHS_12]); + } + ); +}); + +describe('Add-key screens forward initial duration to AddSigningDevice', () => { + test.each([ + ['AddReserveKey', reserveSource], + ['AddEmergencyKey', emergencySource], + ])( + '%s passes the independent flag and exact selected duration', + (_name, source: ts.SourceFile) => { + const push = jest.fn(); + const scope: any = { + ...screenScope(true, durations.MONTHS_6), + navigation: { push }, + ADDRESERVEKEY: 'AddReserveKey', + ADDEMERGENCYKEY: 'AddEmergencyKey', + vaultKeys: [mk('AAAAAAAA'), mk('BBBBBBBB'), mk('CCCCCCCC')], + route: { params: { selectedSigners: [] } }, + scheme: { m: 2, n: 3 }, + isAddInheritanceKey: true, + isAddEmergencyKey: true, + currentBlockHeight: 950000, + setSelectedSigner: jest.fn(), + }; + const useCallback = variableExpression(source, 'userKeyCallback'); + if (!ts.isCallExpression(useCallback)) throw new Error('Expected production useCallback'); + const callback = execute(useCallback.arguments[0], source, scope); + callback(); + expect(push).toHaveBeenCalledTimes(1); + expect(push.mock.calls[0][0]).toBe('AddSigningDevice'); + expect(push.mock.calls[0][1].hasInitialTimelock).toBe(true); + expect(push.mock.calls[0][1].initialTimelockDuration).toBe(durations.MONTHS_6); + } + ); +}); + +describe('Add-key screens preserve fallback roles while replacing a primary key', () => { + test.each([ + ['AddReserveKey', reserveSource, 'DDDDDDDD'], + ['AddEmergencyKey', emergencySource, 'EEEEEEEE'], + ])( + '%s preloads the existing fallback for a primary rotation', + (_name, source: ts.SourceFile, fingerprint: string) => { + const setSelectedSigner = jest.fn(); + const scope: any = { + selectedSigner: null, + keyToRotate: mk('AAAAAAAA'), + activeVault: { + id: 'disposable', + signers: ['AAAAAAAA', 'BBBBBBBB', 'CCCCCCCC', 'DDDDDDDD', 'EEEEEEEE'].map(mk), + scheme: { + miniscriptScheme: { + miniscriptElements: { + signerFingerprints: { + K1: 'AAAAAAAA', + K2: 'BBBBBBBB', + K3: 'CCCCCCCC', + IK1: 'DDDDDDDD', + EK1: 'EEEEEEEE', + }, + }, + }, + }, + }, + INHERITANCE_KEY_IDENTIFIER, + EMERGENCY_KEY_IDENTIFIER, + getKeyUID: (key) => key.masterFingerprint, + setSelectedSigner, + }; + let expression: ts.Expression; + function visit(node: ts.Node) { + if ( + ts.isCallExpression(node) && + node.expression.getText(source) === 'useEffect' && + node.arguments[0].getText(source).includes('setSelectedSigner(') + ) { + expression = node.arguments[0]; + } + ts.forEachChild(node, visit); + } + visit(source); + if (!expression) throw new Error('Missing production fallback preload effect'); + const effect = execute(expression, source, scope); + effect(); + expect(setSelectedSigner).toHaveBeenCalledWith([mk(fingerprint)]); + + // Replacing the fallback itself must still require choosing its replacement. + setSelectedSigner.mockClear(); + scope.keyToRotate = mk(fingerprint); + effect(); + expect(setSelectedSigner).not.toHaveBeenCalled(); + + // Re-rendering must not overwrite an explicit user selection. + scope.keyToRotate = mk('AAAAAAAA'); + scope.selectedSigner = [mk('FFFFFFFF')]; + effect(); + expect(setSelectedSigner).not.toHaveBeenCalled(); + } + ); +}); diff --git a/tests/services/addSigningDeviceTimelock.test.ts b/tests/services/addSigningDeviceTimelock.test.ts new file mode 100644 index 0000000000..dc658c1f18 --- /dev/null +++ b/tests/services/addSigningDeviceTimelock.test.ts @@ -0,0 +1,450 @@ +import fs from 'fs'; +import path from 'path'; +import vm from 'vm'; +import ts from 'typescript'; +import { MiniscriptTypes, VaultType, XpubTypes } from 'src/services/wallets/enums'; +import { resolveInitialTimelock } from 'src/services/wallets/operations/miniscript/initialTimelock'; + +// Run the production screen's route bindings, controller props and button callback. +// Native rendering, Realm persistence and funded migration remain separate acceptance work. +function sourceFile(name: string, override?: string) { + return ts.createSourceFile( + name, + fs.readFileSync(override || path.join(process.cwd(), `src/screens/Vault/${name}`), 'utf8'), + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX + ); +} + +const signingSource = sourceFile('AddSigningDevice.tsx', process.env.R02_ADD_SIGNING_DEVICE_SOURCE); +const detailsSource = sourceFile( + 'SigningDeviceDetails.tsx', + process.env.R02_SIGNING_DEVICE_DETAILS_SOURCE +); + +function findNode(source: ts.SourceFile, predicate: (node: ts.Node) => boolean): ts.Node { + let result: ts.Node; + function visit(node: ts.Node) { + if (!result && predicate(node)) result = node; + if (!result) ts.forEachChild(node, visit); + } + visit(source); + return result; +} + +function execute(code: string, scope: any = {}) { + vm.runInNewContext( + ts.transpileModule(code, { + fileName: 'screen-contract.tsx', + compilerOptions: { target: ts.ScriptTarget.ES2019, jsx: ts.JsxEmit.React }, + }).outputText, + scope + ); + return scope; +} + +function expressionValue(source: ts.SourceFile, node: ts.Expression, scope: any) { + expect(node).toBeDefined(); + return execute(`result = (${node.getText(source)});`, scope).result; +} + +function componentAttribute(component: string, attribute: string): ts.Expression { + const element = findNode( + signingSource, + (node) => + (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) && + node.tagName.getText(signingSource) === component + ) as ts.JsxOpeningElement | ts.JsxSelfClosingElement; + const prop = element.attributes.properties.find( + (node) => ts.isJsxAttribute(node) && node.name.getText(signingSource) === attribute + ) as ts.JsxAttribute; + expect(prop).toBeDefined(); + return (prop.initializer as ts.JsxExpression).expression; +} + +function requirementFromStoredWallet( + types: MiniscriptTypes[], + routeFlag?: boolean, + newScheme = false +) { + const declaration = findNode( + signingSource, + (node) => + ts.isVariableDeclaration(node) && node.name.getText(signingSource) === 'hasInitialTimelock' + ) as ts.VariableDeclaration; + expect(declaration).toBeDefined(); + return expressionValue(signingSource, declaration.initializer, { + isNewSchemeFlow: newScheme, + hasInitialTimelockParam: routeFlag, + activeVault: { scheme: { miniscriptScheme: { usedMiniscriptTypes: types } } }, + MiniscriptTypes, + }); +} + +function footerFixture(overrides: any = {}) { + const footer = findNode( + signingSource, + (node) => ts.isFunctionDeclaration(node) && node.name?.text === 'Footer' + ) as ts.FunctionDeclaration; + const navigation = { navigate: jest.fn(), dispatch: jest.fn(), goBack: jest.fn() }; + const setCreating = jest.fn(); + const scope: any = { + React: { createElement: (type, props, ...children) => ({ type, props, children }) }, + Box: 'Box', + Buttons: 'Buttons', + styles: { bottomContainer: {} }, + useNavigation: () => navigation, + useContext: () => ({ translations: { common: { proceed: 'Proceed', confirm: 'Confirm' } } }), + LocalizationContext: {}, + getKeyUID: (key) => key.id, + CommonActions: { navigate: (name, params) => ({ name, params }) }, + INHERITANCE_KEY_IDENTIFIER: 'IK', + EMERGENCY_KEY_IDENTIFIER: 'EK', + }; + execute(`${footer.getText(signingSource)}; result = Footer;`, scope); + const keyToRotate = { id: 'old-primary' }; + const props = { + areSignersValid: true, + colorMode: 'light', + setCreating, + isCollaborativeFlow: false, + isAssistedWalletFlow: false, + hasInitialTimelock: true, + initialTimelockDuration: undefined, + isReserveKeyFlow: false, + isEmergencyKeyFlow: false, + isAddInheritanceKey: false, + isAddEmergencyKey: false, + currentBlockHeight: 100000, + vaultKeys: [{ id: 'new-primary', masterFingerprint: 'AAAAAAAA' }], + selectedSigners: new Map([['new-primary', true]]), + signers: [{ id: 'new-primary' }], + name: 'Disposable fixture', + description: '', + vaultId: 'fixture-wallet', + scheme: { m: 1, n: 1 }, + vaultType: 'MINISCRIPT', + keyToRotate, + activeVault: { + scheme: { miniscriptScheme: { miniscriptElements: { signerFingerprints: {} } } }, + }, + ...overrides, + }; + const element = scope.result(props); + const button = element.children.find((child) => child?.type === 'Buttons'); + expect(button).toBeDefined(); + button.props.primaryCallback(); + return { navigation, setCreating, keyToRotate }; +} + +describe('AddSigningDevice initial timelock contract', () => { + test.each(['3 months', '6 months', '9 months', '12 months'])( + 'reads the selected duration %s from the real route binding', + (duration) => { + const binding = findNode( + signingSource, + (node) => + ts.isVariableDeclaration(node) && + ts.isObjectBindingPattern(node.name) && + node.initializer?.getText(signingSource) === 'route.params' + ) as ts.VariableDeclaration; + const scope = execute( + `const ${binding.getText( + signingSource + )}; result = typeof initialTimelockDuration === 'undefined' ? undefined : initialTimelockDuration;`, + { route: { params: { initialTimelockDuration: duration } } } + ); + expect(scope.result).toBe(duration); + } + ); + + test.each([undefined, false, true])( + 'retains the stored TIMELOCKED requirement when route flag is %s', + (routeFlag) => { + expect(requirementFromStoredWallet([MiniscriptTypes.TIMELOCKED], routeFlag)).toBe(true); + } + ); + + test('respects an explicit new-scheme choice to remove the initial lock', () => { + expect(requirementFromStoredWallet([MiniscriptTypes.TIMELOCKED], false, true)).toBe(false); + }); + + test.each(['VaultMigrationController', 'Footer'])( + 'passes the exact selected duration to %s', + (component) => { + const duration = expressionValue( + signingSource, + componentAttribute(component, 'initialTimelockDuration'), + { + initialTimelockDuration: '9 months', + } + ); + expect(duration).toBe('9 months'); + } + ); + + test.each([undefined, null, '', 0])( + 'keeps the controller requirement independent from invalid duration %s', + (initialTimelockDuration) => { + const hasInitialTimelock = requirementFromStoredWallet([MiniscriptTypes.TIMELOCKED]); + const types = expressionValue( + signingSource, + componentAttribute('VaultMigrationController', 'miniscriptTypes'), + { + hasInitialTimelock, + isAddInheritanceKey: true, + isAddEmergencyKey: true, + MiniscriptTypes, + } + ); + const duration = expressionValue( + signingSource, + componentAttribute('VaultMigrationController', 'initialTimelockDuration'), + { + initialTimelockDuration, + } + ); + expect(types).toContain(MiniscriptTypes.TIMELOCKED); + expect(() => resolveInitialTimelock(types, duration, () => 6)).toThrow('initial timelock'); + } + ); + + test('routes replacement without a duration through the existing timelock selection', () => { + const { navigation, setCreating, keyToRotate } = footerFixture(); + expect(setCreating).not.toHaveBeenCalled(); + expect(navigation.dispatch).toHaveBeenCalledWith( + expect.objectContaining({ + name: 'SelectInitialTimelock', + params: expect.objectContaining({ hasInitialTimelock: true, keyToRotate }), + }) + ); + }); + + test.each([ + ['AddReserveKey', { isAddInheritanceKey: true }], + ['AddEmergencyKey', { isAddEmergencyKey: true }], + ])('forwards an explicit duration and replacement identity to %s', (name, overrides) => { + const { navigation, keyToRotate } = footerFixture({ + initialTimelockDuration: '6 months', + ...overrides, + }); + expect(navigation.dispatch).toHaveBeenCalledWith( + expect.objectContaining({ + name, + params: expect.objectContaining({ + hasInitialTimelock: true, + initialTimelockDuration: '6 months', + keyToRotate, + }), + }) + ); + }); + + test('forwards an explicit duration to final confirmation for a new wallet', () => { + const { navigation } = footerFixture({ + initialTimelockDuration: '12 months', + keyToRotate: undefined, + }); + expect(navigation.navigate).toHaveBeenCalledWith( + 'ConfirmWalletDetails', + expect.objectContaining({ hasInitialTimelock: true, initialTimelockDuration: '12 months' }) + ); + }); + + test('uses an explicit duration for primary-key replacement without reselection', () => { + const { navigation, setCreating } = footerFixture({ initialTimelockDuration: '6 months' }); + expect(setCreating).toHaveBeenCalledWith(true); + expect(navigation.dispatch).not.toHaveBeenCalled(); + }); + + test('preserves ordinary untimelocked key replacement', () => { + const { navigation, setCreating } = footerFixture({ hasInitialTimelock: false }); + expect(setCreating).toHaveBeenCalledWith(true); + expect(navigation.dispatch).not.toHaveBeenCalled(); + }); +}); + +describe('Existing primary Change Key navigation', () => { + test('requires duration selection from stored metadata when the unchanged caller omits it', () => { + const action = findNode( + detailsSource, + (node) => + ts.isObjectLiteralExpression(node) && + node.properties.some( + (prop) => + ts.isPropertyAssignment(prop) && + prop.name.getText(detailsSource) === 'text' && + prop.initializer.getText(detailsSource) === 'vaultText.changeKey' + ) + ) as ts.ObjectLiteralExpression; + const callback = ( + action.properties.find( + (prop) => ts.isPropertyAssignment(prop) && prop.name.getText(detailsSource) === 'onPress' + ) as ts.PropertyAssignment + ).initializer; + const activeVault = { + presentationData: { name: 'Disposable fixture', description: '' }, + scheme: { miniscriptScheme: { usedMiniscriptTypes: [MiniscriptTypes.TIMELOCKED] } }, + }; + const vaultKey = { id: 'old-primary' }; + const entryNavigation = { dispatch: jest.fn() }; + const onPress = expressionValue(detailsSource, callback, { + activeVault, + vaultKey, + vaultId: 'fixture-wallet', + isInheritanceKey: false, + isEmergencyKey: false, + navigation: entryNavigation, + CommonActions: { navigate: (action) => action }, + }); + onPress(); + const entry = entryNavigation.dispatch.mock.calls[0][0]; + expect(entry).toMatchObject({ name: 'AddSigningDevice', params: { keyToRotate: vaultKey } }); + expect(entry.params.hasInitialTimelock).toBeUndefined(); + expect(entry.params.initialTimelockDuration).toBeUndefined(); + const hasInitialTimelock = requirementFromStoredWallet( + activeVault.scheme.miniscriptScheme.usedMiniscriptTypes, + entry.params.hasInitialTimelock + ); + expect(hasInitialTimelock).toBe(true); + const { navigation, setCreating } = footerFixture({ + ...entry.params, + hasInitialTimelock, + initialTimelockDuration: entry.params.initialTimelockDuration, + }); + expect(setCreating).not.toHaveBeenCalled(); + expect(navigation.dispatch).toHaveBeenCalledWith( + expect.objectContaining({ + name: 'SelectInitialTimelock', + params: expect.objectContaining({ hasInitialTimelock: true, keyToRotate: vaultKey }), + }) + ); + expect(navigation.dispatch.mock.calls[0][0].params.initialTimelockDuration).toBeUndefined(); + }); +}); + +describe('AddSigningDevice existing primary-key selection', () => { + function selectionFixture(type: VaultType, n = 3, keyToRotate?: string) { + const declaration = findNode( + signingSource, + (node) => + ts.isVariableDeclaration(node) && node.name.getText(signingSource) === 'setInitialKeys' + ) as ts.VariableDeclaration; + const keys = ['K1', 'K2', 'K3', 'IK1', 'EK1'].map((id) => ({ id, masterFingerprint: id })); + const signerMap = Object.fromEntries( + keys.map((key) => [ + key.id, + { + ...key, + signerXpubs: { + [XpubTypes.P2WSH]: [{}], + [XpubTypes.P2WPKH]: [{}], + [XpubTypes.AMF]: [{}], + }, + }, + ]) + ); + const scope = { + getKeyUID: (key) => key.id, + VaultType, + MiniscriptTypes, + XpubTypes, + isSignerValidForScheme: () => ({ isValid: true }), + WalletUtilities: { getKeyForScheme: (_isMultisig, signer) => ({ id: signer.id }) }, + }; + const setInitialKeys = expressionValue(signingSource, declaration.initializer, scope); + const setVaultKeys = jest.fn(); + const setSelectedSigners = jest.fn(); + const activeVault = { + type, + signers: keys, + scheme: { + miniscriptScheme: { + usedMiniscriptTypes: [ + MiniscriptTypes.TIMELOCKED, + MiniscriptTypes.INHERITANCE, + MiniscriptTypes.EMERGENCY, + ], + miniscriptElements: { + signerFingerprints: Object.fromEntries( + keys.map((key) => [key.id, key.masterFingerprint]) + ), + }, + }, + }, + }; + setInitialKeys( + activeVault, + type, + { m: 2, n }, + signerMap, + setVaultKeys, + setSelectedSigners, + new Map(), + keys.find((key) => key.id === keyToRotate) + ); + return { + vaultKeys: setVaultKeys.mock.calls[0][0], + selected: setSelectedSigners.mock.calls[0][0] as Map, + }; + } + + test('leaves the replacement slot free and excludes IK/EK from primary preselection', () => { + const { vaultKeys, selected } = selectionFixture(VaultType.MINISCRIPT, 3, 'K1'); + expect(vaultKeys).toEqual([{ id: 'K2' }, { id: 'K3' }]); + expect(Array.from(selected.keys())).toEqual(['K2', 'K3']); + expect(selected.size).toBeLessThan(3); + }); + + test('respects the chosen primary count when changing a scheme', () => { + const { vaultKeys, selected } = selectionFixture(VaultType.MINISCRIPT, 1, 'K1'); + expect(vaultKeys).toEqual([{ id: 'K2' }]); + expect(Array.from(selected.keys())).toEqual(['K2']); + }); + + test('preserves a fresh new-scheme selection without a rotation target', () => { + const { vaultKeys, selected } = selectionFixture(VaultType.MINISCRIPT); + expect(vaultKeys).toEqual([]); + expect(selected.size).toBe(0); + }); + + test('preserves ordinary wallet preselection', () => { + const { vaultKeys, selected } = selectionFixture(VaultType.DEFAULT, 3, 'K1'); + expect(vaultKeys).toEqual([{ id: 'K2' }, { id: 'K3' }, { id: 'IK1' }]); + expect(Array.from(selected.keys())).toEqual(['K2', 'K3', 'IK1']); + }); +}); + +describe('primary selection validation with retained fallback keys', () => { + const intelSource = ts.createSourceFile('useSignerIntel.tsx', fs.readFileSync( + path.join(process.cwd(), 'src/hooks/useSignerIntel.tsx'), 'utf8' + ), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const declaration = (name: string) => findNode(intelSource, node => + ts.isVariableDeclaration(node) && node.name.getText(intelSource) === name + ) as ts.VariableDeclaration; + function validate(n: number, selectedCount: number, types: MiniscriptTypes[]) { + const keys = Array.from({ length: selectedCount }, (_, i) => ({ id: `new-${i}`, xfp: `new-${i}` })); + const selectedSigners = new Map(keys.map(key => [key.id, true])); + const scope = execute(`const areSignersSame = ${declaration('areSignersSame').initializer.getText(intelSource)}; + const useSignerIntel = ${declaration('useSignerIntel').initializer.getText(intelSource)}; + result = useSignerIntel(input);`, { + useSignerMap: () => ({ signerMap: Object.fromEntries(keys.map(key => [key.id, { type: 'MY_KEEPER' }])) }), + usePlan: () => ({ plan: 'L1' }), SubscriptionTier: { L1: 'L1' }, + useContext: () => ({ translations: { signer: {} } }), LocalizationContext: {}, + isSignerAMF: () => false, getKeyUID: key => key.id, + SignerType: { POLICY_SERVER: 'POLICY_SERVER' }, getSignerNameFromType: () => 'Mobile Key', + input: { scheme: { m: 1, n, miniscriptScheme: { usedMiniscriptTypes: types } }, + vaultKeys: keys, selectedSigners, existingKeys: [{ xfp: 'old-primary' }, { xfp: 'retained-inheritance' }] }, + }); + return scope.result.areSignersValid; + } + test.each([ + [1, 1, true], [1, 0, false], [1, 2, false], [3, 3, true], [3, 2, false], [3, 4, false], + ])('requires exactly %i primary keys when %i are selected', (n, selected, valid) => { + expect(validate(n, selected, [MiniscriptTypes.TIMELOCKED, MiniscriptTypes.INHERITANCE])).toBe(valid); + }); + test('Emergency Key also does not increase the primary quorum count', () => { + expect(validate(1, 1, [MiniscriptTypes.TIMELOCKED, MiniscriptTypes.INHERITANCE, MiniscriptTypes.EMERGENCY])).toBe(true); + }); +}); From 5bd4dc6421658cd3dfb03900decfcfff4ff15e35 Mon Sep 17 00:00:00 2001 From: Anant Date: Tue, 6 Oct 2026 19:06:07 +0530 Subject: [PATCH 08/19] Use live Keeper channel and guard mobile release builds --- android/fastlane/Fastfile | 1 + ios/fastlane/Fastfile | 1 + scripts/verify-channel-config.cjs | 20 ++++++++++++++++++++ src/utils/service-utilities/config.ts | 2 +- 4 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 scripts/verify-channel-config.cjs diff --git a/android/fastlane/Fastfile b/android/fastlane/Fastfile index cfc909f0db..9ff016ca39 100644 --- a/android/fastlane/Fastfile +++ b/android/fastlane/Fastfile @@ -52,6 +52,7 @@ platform :android do sh("node", File.expand_path("../../scripts/release-version.cjs", __dir__), "release-check") production_env = File.expand_path("../../.env.production", __dir__) UI.user_error!("Missing reviewed .env.production") unless File.file?(production_env) + sh("node", File.expand_path("../../scripts/verify-channel-config.cjs", __dir__), production_env) ENV['ENVFILE'] = production_env store_password = ENV["STORE_PASSWORD"] key_password = ENV["KEY_PASSWORD"] diff --git a/ios/fastlane/Fastfile b/ios/fastlane/Fastfile index b231891c82..a3dfa9739b 100644 --- a/ios/fastlane/Fastfile +++ b/ios/fastlane/Fastfile @@ -107,6 +107,7 @@ platform :ios do sh("node", File.expand_path("../../scripts/release-version.cjs", __dir__), "release-check") production_env = File.expand_path("../../.env.production", __dir__) UI.user_error!("Missing reviewed .env.production") unless File.file?(production_env) + sh("node", File.expand_path("../../scripts/verify-channel-config.cjs", __dir__), production_env) ENV['ENVFILE'] = production_env get_certificates( # Create or get certificate, and install it diff --git a/scripts/verify-channel-config.cjs b/scripts/verify-channel-config.cjs new file mode 100644 index 0000000000..18ecc31734 --- /dev/null +++ b/scripts/verify-channel-config.cjs @@ -0,0 +1,20 @@ +const fs = require('fs'); + +const expected = 'https://channel.bitcoinkeeper.app/'; +const envFile = process.argv[2]; + +if (!envFile || !fs.existsSync(envFile)) { + throw new Error('Production environment file is missing'); +} + +const matches = fs.readFileSync(envFile, 'utf8') + .split(/\r?\n/) + .map(line => line.match(/^\s*(?:export\s+)?CHANNEL_URL\s*=\s*(.*?)\s*$/)) + .filter(Boolean) + .map(match => match[1].replace(/^['"]|['"]$/g, '')); + +if (matches.length !== 1 || matches[0] !== expected) { + throw new Error(`Production CHANNEL_URL must be ${expected}`); +} + +console.log('Production channel URL verified'); diff --git a/src/utils/service-utilities/config.ts b/src/utils/service-utilities/config.ts index 5344d501b9..999bbc3ae7 100644 --- a/src/utils/service-utilities/config.ts +++ b/src/utils/service-utilities/config.ts @@ -23,7 +23,7 @@ const DEFAULT_CONFIG = { HEXA_ID_MAINNET: 'b01623f1065ba45d68b516efe2873f59bfc9b9b2d8b194f94f989d87d711830a', SENTRY_DNS: 'https://25289533edf7432994f58edeaf6541dc@o1388909.ingest.sentry.io/6711631', ENVIRONMENT: APP_STAGE.DEVELOPMENT, - CHANNEL_URL: 'https://keeper-channel-dev-8d01fa5233d0.herokuapp.com/', + CHANNEL_URL: 'http://localhost:4002/', LETS_EXCHANGE_AFFILIATE_ID: 'G0BiaS34U81NR3ra', }; From cc1ac7ecfbd8ce6016799236e893bb354c927485 Mon Sep 17 00:00:00 2001 From: Anant Date: Tue, 6 Oct 2026 19:40:13 +0530 Subject: [PATCH 09/19] Verify packaged native pairing channel before release --- scripts/verify-release-artifact.py | 37 +++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/scripts/verify-release-artifact.py b/scripts/verify-release-artifact.py index 0de412db51..13e3a94dc1 100644 --- a/scripts/verify-release-artifact.py +++ b/scripts/verify-release-artifact.py @@ -19,6 +19,8 @@ import xml.etree.ElementTree as ET ANDROID_NS = "{http://schemas.android.com/apk/res/android}" +LIVE_CHANNEL = "https://channel.bitcoinkeeper.app/" +RETIRED_CHANNELS = ("https://keeper-channel.herokuapp.com/", "https://keeper-dev-channel.herokuapp.com/") def require_equal(actual, expected, label): @@ -37,6 +39,34 @@ def verify_features(bundle): raise ValueError("Required packaged feature markers absent: " + ", ".join(missing)) +def verify_channel(archive, suffix, info=None, app_prefix=None): + if suffix == ".ipa": + executable = info.get("CFBundleExecutable") + if not executable or "/" in executable: + raise ValueError("Cannot identify main iOS executable for channel verification") + members = [app_prefix + "/" + executable] + elif suffix == ".aab": + members = [name for name in archive.namelist() + if name.startswith("base/") and (name.endswith(".dex") or name == "base/resources.pb")] + else: + members = [name for name in archive.namelist() + if re.fullmatch(r"classes\d*\.dex", name) or name == "resources.arsc"] + if not members: + raise ValueError("No native release payload available for channel verification") + expected = LIVE_CHANNEL.encode() + retired = [url.encode() for url in RETIRED_CHANNELS] + found_live = False + found_retired = False + for member in members: + data = archive.read(member) + found_live |= expected in data + found_retired |= any(url in data for url in retired) + if found_retired: + raise ValueError("Packaged native configuration contains a retired pairing channel") + if not found_live: + raise ValueError("Live pairing channel absent from packaged native configuration") + + def output(command): result = subprocess.run(command, capture_output=True, text=True) if result.returncode: @@ -54,7 +84,9 @@ def inspect(path, manifest): info = plistlib.loads(archive.read(names[0])) app_id, version, build = (info.get(k) for k in ("CFBundleIdentifier", "CFBundleShortVersionString", "CFBundleVersion")) platform = "ios" - bundle = archive.read(names[0].rsplit("/", 1)[0] + "/main.jsbundle") + app_prefix = names[0].rsplit("/", 1)[0] + bundle = archive.read(app_prefix + "/main.jsbundle") + verify_channel(archive, suffix, info=info, app_prefix=app_prefix) elif suffix == ".apk": text = output([os.environ.get("AAPT", "aapt"), "dump", "badging", str(path)]) match = re.search(r"package: name='([^']+)' versionCode='([^']+)' versionName='([^']+)'", text) @@ -63,6 +95,7 @@ def inspect(path, manifest): app_id, build, version = match.groups() platform = "android" bundle = archive.read("assets/index.android.bundle") + verify_channel(archive, suffix) elif suffix == ".aab": jar = os.environ.get("BUNDLETOOL_JAR") if not jar or not Path(jar).is_file(): @@ -72,6 +105,7 @@ def inspect(path, manifest): app_id, build, version = root.get("package"), root.get(ANDROID_NS + "versionCode"), root.get(ANDROID_NS + "versionName") platform = "android" bundle = archive.read("base/assets/index.android.bundle") + verify_channel(archive, suffix) else: raise ValueError("Expected an IPA, APK or AAB") expected_id = {"ios": "io.hexawallet.keeper", "android": "io.hexawallet.bitcoinkeeper"}[platform] @@ -82,6 +116,7 @@ def inspect(path, manifest): result = {"artifact": path.name, "applicationId": app_id, "version": version, "build": str(build), "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "bundleSha256": hashlib.sha256(bundle).hexdigest(), "featureMarkers": "present", + "channelUrl": "verified", "signing": "separate verification required"} if suffix == ".apk": certs = output([os.environ.get("APKSIGNER", "apksigner"), "verify", "--print-certs", str(path)]) From 859429f7b99b5e30423a018cc5bf7cb57020be23 Mon Sep 17 00:00:00 2001 From: Anant Date: Tue, 6 Oct 2026 19:42:52 +0530 Subject: [PATCH 10/19] Prepare 2.6.3 pairing channel hotfix versions --- android/app/build.gradle | 4 ++-- ios/hexa_keeper.xcodeproj/project.pbxproj | 16 ++++++++-------- package.json | 2 +- release/version.json | 22 +++++++++++----------- 4 files changed, 22 insertions(+), 22 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index eebb1acfe2..b73b4caad3 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -98,8 +98,8 @@ android { applicationId "io.hexawallet.keeper" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 625 - versionName "2.6.2" + versionCode 626 + versionName "2.6.3" missingDimensionStrategy 'react-native-camera', 'general' missingDimensionStrategy 'store', 'play' multiDexEnabled true diff --git a/ios/hexa_keeper.xcodeproj/project.pbxproj b/ios/hexa_keeper.xcodeproj/project.pbxproj index 52aa23ef44..c90117ddd7 100644 --- a/ios/hexa_keeper.xcodeproj/project.pbxproj +++ b/ios/hexa_keeper.xcodeproj/project.pbxproj @@ -748,7 +748,7 @@ CODE_SIGN_ENTITLEMENTS = hexa_keeper/hexa_keeper.entitlements; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 618; + CURRENT_PROJECT_VERSION = 619; DEVELOPMENT_TEAM = Y5TCB759QL; ENABLE_BITCODE = NO; HEADER_SEARCH_PATHS = ( @@ -849,7 +849,7 @@ "$(inherited)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.6.2; + MARKETING_VERSION = 2.6.3; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -876,7 +876,7 @@ CODE_SIGN_IDENTITY = "Apple Development"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 618; + CURRENT_PROJECT_VERSION = 619; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; HEADER_SEARCH_PATHS = ( @@ -977,7 +977,7 @@ "$(inherited)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.6.2; + MARKETING_VERSION = 2.6.3; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1147,7 +1147,7 @@ CODE_SIGN_IDENTITY = "Apple Development"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 618; + CURRENT_PROJECT_VERSION = 619; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; ENABLE_BITCODE = NO; @@ -1250,7 +1250,7 @@ "$(PROJECT_DIR)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.6.2; + MARKETING_VERSION = 2.6.3; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1278,7 +1278,7 @@ CODE_SIGN_ENTITLEMENTS = hexa_keeper_dev.entitlements; CODE_SIGN_IDENTITY = "Apple Distribution"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; - CURRENT_PROJECT_VERSION = 618; + CURRENT_PROJECT_VERSION = 619; DEVELOPMENT_TEAM = Y5TCB759QL; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; HEADER_SEARCH_PATHS = ( @@ -1380,7 +1380,7 @@ "$(PROJECT_DIR)", "\"$(SRCROOT)\"", ); - MARKETING_VERSION = 2.6.2; + MARKETING_VERSION = 2.6.3; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", diff --git a/package.json b/package.json index dc78f187da..ad0eeb2c1e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hexa_keeper", - "version": "2.6.2", + "version": "2.6.3", "private": true, "scripts": { "ios": "npx react-native run-ios --scheme=hexa_keeper_dev --simulator 'iPhone 16' ", diff --git a/release/version.json b/release/version.json index 553cacad87..57bc77e469 100644 --- a/release/version.json +++ b/release/version.json @@ -1,21 +1,21 @@ { - "version": "2.6.2", - "androidVersionCode": 625, - "iosBuildNumber": 618, + "version": "2.6.3", + "androidVersionCode": 626, + "iosBuildNumber": 619, "baselines": { "android": { "applicationId": "io.hexawallet.bitcoinkeeper", - "verifiedAt": "2026-10-05T10:04:03Z", - "highestUploadedBuild": 624, - "highestMarketingVersion": "2.5.17", - "productionRelease": "624 (2.5.17)" + "verifiedAt": "2026-10-06T14:11:41Z", + "highestUploadedBuild": 625, + "highestMarketingVersion": "2.6.2", + "productionRelease": "625 (2.6.2)" }, "ios": { "applicationId": "io.hexawallet.keeper", - "verifiedAt": "2026-10-05T10:04:36Z", - "highestUploadedBuild": 617, - "highestMarketingVersion": "2.5.17", - "productionRelease": "617 (2.5.17)" + "verifiedAt": "2026-10-06T14:12:22Z", + "highestUploadedBuild": 618, + "highestMarketingVersion": "2.6.2", + "productionRelease": "618 (2.6.2)" } } } From 872cbc4b16ddcb0a8f3b5b1d7ebcde28e06ed096 Mon Sep 17 00:00:00 2001 From: Anant Date: Tue, 6 Oct 2026 20:11:52 +0530 Subject: [PATCH 11/19] Use aapt2 for release APK metadata verification --- scripts/verify-release-artifact.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/scripts/verify-release-artifact.py b/scripts/verify-release-artifact.py index 13e3a94dc1..16ebaf120b 100644 --- a/scripts/verify-release-artifact.py +++ b/scripts/verify-release-artifact.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Inspect packaged release metadata and required feature markers without dumping secrets. -APK: Android SDK aapt and apksigner are required. +APK: Android SDK aapt2 and apksigner are required. AAB: BUNDLETOOL_JAR and Java are required. IPA: Python standard library; signing is verified separately by codesign/export evidence. This verifier supplements device tests; bytecode markers do not prove feature behavior. @@ -74,6 +74,18 @@ def output(command): return result.stdout +def android_tool(name, override): + if os.environ.get(override): + return os.environ[override] + for variable in ("ANDROID_HOME", "ANDROID_SDK_ROOT"): + sdk = os.environ.get(variable) + if sdk: + candidates = sorted((Path(sdk) / "build-tools").glob("*/" + name), reverse=True) + if candidates: + return str(candidates[0]) + return name + + def inspect(path, manifest): suffix = path.suffix.lower() with zipfile.ZipFile(path) as archive: @@ -88,7 +100,7 @@ def inspect(path, manifest): bundle = archive.read(app_prefix + "/main.jsbundle") verify_channel(archive, suffix, info=info, app_prefix=app_prefix) elif suffix == ".apk": - text = output([os.environ.get("AAPT", "aapt"), "dump", "badging", str(path)]) + text = output([android_tool("aapt2", "AAPT2"), "dump", "badging", str(path)]) match = re.search(r"package: name='([^']+)' versionCode='([^']+)' versionName='([^']+)'", text) if not match: raise ValueError("Cannot read APK package/version metadata") @@ -119,7 +131,7 @@ def inspect(path, manifest): "channelUrl": "verified", "signing": "separate verification required"} if suffix == ".apk": - certs = output([os.environ.get("APKSIGNER", "apksigner"), "verify", "--print-certs", str(path)]) + certs = output([android_tool("apksigner", "APKSIGNER"), "verify", "--print-certs", str(path)]) expected = os.environ.get("KEEPER_ANDROID_CERT_SHA256", "").lower().replace(":", "") if not re.fullmatch(r"[0-9a-f]{64}", expected): raise ValueError("Set KEEPER_ANDROID_CERT_SHA256 to the independently verified release certificate") From 84476d7b17cbd34b0859023052b0d49407e05984 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Wed, 7 Oct 2026 02:31:08 +0530 Subject: [PATCH 12/19] ci: test release/2.6.3 pull requests Enable the release branch test trigger and repair the inert recovery provenance fixture exposed by that run. No production app code changes. --- .github/workflows/test.yml | 2 ++ tests/store/versionHistory.test.ts | 1 + 2 files changed, 3 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a81eab2bb5..dbff68d1af 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,11 +6,13 @@ on: - sprint - dev - main + - release/2.6.3 pull_request: branches: - sprint - dev - main + - release/2.6.3 jobs: test: diff --git a/tests/store/versionHistory.test.ts b/tests/store/versionHistory.test.ts index 2343a8c9db..8526829fc8 100644 --- a/tests/store/versionHistory.test.ts +++ b/tests/store/versionHistory.test.ts @@ -122,6 +122,7 @@ function recoveryFixture(backupVersion: string) { BackupType: { SEED: 'SEED' }, EntityKind: { USDT_WALLET: 'USDT_WALLET' }, BackupAction: { SEED_BACKUP_CONFIRMED: 'confirmed' }, + pauseBackup: () => {}, NetworkType: { MAINNET: 'MAINNET', TESTNET: 'TESTNET' }, uaiType: {}, moment: () => ({ unix: () => 1 }), From d3e0b0484741fd7ea533d7285af4e678f61d6c9b Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 17:16:48 +0530 Subject: [PATCH 13/19] Address Copilot review findings in R3 baseline backmerge --- .github/workflows/test.yml | 6 ++++++ release/README.md | 10 +++++----- scripts/release-version.cjs | 4 +++- scripts/release-version.test.cjs | 7 +++++++ scripts/test_release_artifact.py | 5 ++++- src/store/sagas/upgrade.ts | 14 +++++++++----- tests/store/versionHistory.test.ts | 31 +++++++++++++++++++++--------- 7 files changed, 56 insertions(+), 21 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index dbff68d1af..7b53c20ffd 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -32,3 +32,9 @@ jobs: - name: Run tests run: npm run test + + - name: Run recovery regression tests + run: npm run test:recovery + + - name: Run release and packaged-artifact tests + run: npm run test:release diff --git a/release/README.md b/release/README.md index 4e484e0251..3b9db966fb 100644 --- a/release/README.md +++ b/release/README.md @@ -1,17 +1,17 @@ # Release version verification -**Current milestone:** R02 / 2.6.2: faster entry after local authentication, Assisted Server Backup current-state correctness, narrow timelock prevention, and the selected cloud credential follow-ups. Keep private advisory details, credentials and fixtures out of public release material. +**Current source intent:** 2.6.3 is the pairing-channel hotfix baseline. R3 is a separate internal work bucket; this manifest does not declare an R3 mobile delivery. Keep private advisory details, credentials and fixtures out of public release material. -`version.json` selects 2.6.2, Android 625 and iOS 618. Authenticated store checks on 5 October 2026 found highest uploaded Android code 624 and iOS build 617, both at 2.5.17. Refresh these baselines before upload. Development builds and local relay validation are separate from reviewed production builds, deployment and store submission. R02 is not released. +`version.json` selects 2.6.3, Android 626 and iOS 619. Its recorded authenticated store baselines on 6 October 2026 are Android 625 and iOS 618, both at 2.6.2. Refresh these baselines before upload. Development builds and local relay validation are separate from reviewed production builds, deployment and store submission. -For R02, the owner accepts real-phone upgrade, Face ID and camera feedback after release. Do not require Developer Mode or physical-device connections to finish preparation. Record simulator, automated and funded testnet evidence accurately; they do not establish physical or hardware-signer acceptance. Already-affected-wallet assessment and consented repair are scheduled for R04 / 2.6.3; R03 is the backend open-source milestone. +The owner will perform real-phone and other manual live checks after release. Do not require Developer Mode or physical-device connections to finish preparation. Record simulator, automated and disposable testnet evidence accurately; they do not establish physical or hardware-signer acceptance. 1. Read all uploaded builds and release tracks for Android package `io.hexawallet.bitcoinkeeper`, and uploaded iOS builds for `io.hexawallet.keeper`. Preserve the timestamp and evidence outside the repository. Refresh before upload; preflight accepts evidence at most 24 hours old. 2. Update the manifest with the highest known marketing version and highest uploaded build per platform. Select one greater marketing version for both stores and greater platform build counters. Check unpublished App Store version records as well. 3. Run `npm run version:apply` to synchronize package.json, Android versionName/versionCode and both Keeper iOS targets. Both Info.plist files must reference `$(CURRENT_PROJECT_VERSION)` and `$(MARKETING_VERSION)`; hardcoded values are rejected. Review the diff, then run `npm run version:check` and `npm run test:release`. 4. Reconcile release source with the published versions, prepare a clean release checkout and set `KEEPER_RELEASE_COMMIT` to its complete verified commit SHA. Run `npm run release:preflight`. The manifest cannot contain its own commit SHA. 5. Build from a reviewed production configuration and existing signing identities. Check extracted IPA, APK and AAB metadata against the manifest, verify signing fingerprints and record checksums. A source preflight does not verify the resulting binaries. -6. Test the signed builds before public submission; record the R02 physical-device deferral above separately. +6. Run all feasible automated, simulator/emulator and disposable checks before public submission; record the owner's post-release manual checks separately. Both existing Fastlane `live` lanes run preflight before building and consume `.env.production` without downloading over `.env`. They no longer increment production build numbers. Android notifications require explicit `KEEPER_NOTIFY_SLACK=1`. @@ -23,7 +23,7 @@ Run `python3 scripts/verify-release-artifact.py /absolute/path/to/build.ipa` (or The verifier checks the production application ID, marketing version, native counter, and bundled Ask Keeper / Dust route and data markers, then emits artifact and bundle SHA-256 hashes. Marker presence supplements device testing; it does not prove behavior or source provenance. Compiler-generated component names are unsuitable markers because release optimization removes them. -For Android, set `AAPT` and `APKSIGNER` to SDK build-tool paths (or put them on PATH), `BUNDLETOOL_JAR` to an installed bundletool jar, and `KEEPER_ANDROID_CERT_SHA256` to the certificate fingerprint independently verified from the established public APK. The verifier checks the APK signature and certificate. IPA code signing/provisioning and AAB signing still require separate verification before distribution. The seven packaged-artifact regression tests run with `npm run test:release` alongside the source-version tests; Python 3 is required. +For Android, set `AAPT2` and `APKSIGNER` to SDK build-tool paths (or put them on PATH), `BUNDLETOOL_JAR` to an installed bundletool jar, and `KEEPER_ANDROID_CERT_SHA256` to the certificate fingerprint independently verified from the established public APK. The verifier checks the APK signature and certificate. IPA code signing/provisioning and AAB signing still require separate verification before distribution. The seven packaged-artifact regression tests run with `npm run test:release` alongside the source-version tests; Python 3 is required. The normal public APK channel is the repository's GitHub Releases. Publish the APK together with `SHA256SUM.asc` and `KEEPER_DETACHED_SIGN.sign` using the established PGP identity, as documented in the root README. Do not replace release signing keys to work around missing access. diff --git a/scripts/release-version.cjs b/scripts/release-version.cjs index c1ba39d0b6..de30abd6da 100644 --- a/scripts/release-version.cjs +++ b/scripts/release-version.cjs @@ -140,7 +140,9 @@ function main() { ios: iosConfigurations(sources.ios).map(({ id, version, build }) => ({ id, version, build })) }, null, 2)); return; } - const errors = validateIntent(manifest); + // Store evidence must be fresh for publication, not for draft edits or + // checking that the source and manifest still agree. + const errors = validateIntent(manifest, { requireEvidence: command === 'release-check' }); if (errors.length) throw new Error(errors.join('\n')); if (command === 'apply') { const updated = applyVersions(manifest, sources); diff --git a/scripts/release-version.test.cjs b/scripts/release-version.test.cjs index ca3387c611..c34db5dee9 100644 --- a/scripts/release-version.test.cjs +++ b/scripts/release-version.test.cjs @@ -46,6 +46,13 @@ test('rejects stale and future-dated evidence', () => { assert.ok(validateIntent(m, { now }).some((e) => e.includes('refresh authenticated store baseline'))); } }); + +test('draft validation permits stale evidence while publication validation rejects it', () => { + const m = intent(); + m.baselines.android.verifiedAt = '2026-09-20T00:00:00Z'; + assert.deepEqual(validateIntent(m, { now, requireEvidence: false }), []); + assert.ok(validateIntent(m, { now, requireEvidence: true }).some((e) => e.includes('refresh authenticated store baseline'))); +}); test('rejects the similarly named non-production Play package', () => { const m = intent(); m.baselines.android.applicationId = 'io.hexawallet.keeper'; assert.ok(validateIntent(m, { now }).some((e) => e.includes('wrong production application ID'))); diff --git a/scripts/test_release_artifact.py b/scripts/test_release_artifact.py index d105e52dff..ae6ee89670 100644 --- a/scripts/test_release_artifact.py +++ b/scripts/test_release_artifact.py @@ -26,9 +26,10 @@ def ipa(self, *, app_id="io.hexawallet.keeper", version="2.5.15", build="615", b with zipfile.ZipFile(path, "w") as archive: archive.writestr("Payload/Keeper.app/Info.plist", plistlib.dumps({ "CFBundleIdentifier": app_id, "CFBundleShortVersionString": version, - "CFBundleVersion": build, + "CFBundleVersion": build, "CFBundleExecutable": "Keeper", }, fmt=plistlib.FMT_BINARY)) archive.writestr("Payload/Keeper.app/main.jsbundle", bundle) + archive.writestr("Payload/Keeper.app/Keeper", artifact.LIVE_CHANNEL.encode()) return path def test_candidate_metadata_and_hashes(self): @@ -63,6 +64,7 @@ def test_apk_must_match_independent_signing_identity(self): path = Path(self.directory.name) / "Keeper.apk" with zipfile.ZipFile(path, "w") as archive: archive.writestr("assets/index.android.bundle", FEATURES) + archive.writestr("classes.dex", artifact.LIVE_CHANNEL.encode()) metadata = "package: name='io.hexawallet.bitcoinkeeper' versionCode='622' versionName='2.5.15'" for actual, should_pass in [("a" * 64, True), ("b" * 64, False)]: with self.subTest(actual=actual), patch.dict(os.environ, {"KEEPER_ANDROID_CERT_SHA256": "a" * 64}), \ @@ -77,6 +79,7 @@ def test_aab_reads_base_manifest_and_bundle(self): path = Path(self.directory.name) / "Keeper.aab" with zipfile.ZipFile(path, "w") as archive: archive.writestr("base/assets/index.android.bundle", FEATURES) + archive.writestr("base/classes.dex", artifact.LIVE_CHANNEL.encode()) xml = '' with patch.dict(os.environ, {"BUNDLETOOL_JAR": str(path)}), patch.object(artifact, "output", return_value=xml): self.assertEqual(artifact.inspect(path, MANIFEST)["build"], "622") diff --git a/src/store/sagas/upgrade.ts b/src/store/sagas/upgrade.ts index e7dd01185f..1c8772e532 100644 --- a/src/store/sagas/upgrade.ts +++ b/src/store/sagas/upgrade.ts @@ -97,11 +97,15 @@ export function* updateVersionHistoryWorker({ appId: app.id, version: newVersion, }); - yield call(dbManager.createObject, RealmSchema.VersionHistory, { - version: `${newVersion}(${DeviceInfo.getBuildNumber()})`, - date: new Date().toString(), - title: isRecovery ? 'Recovered Wallet' : `Upgraded from ${previousVersion} to ${newVersion}`, - }); + // recoverApp already records the single "Recovered Wallet" entry. Keep the + // image/version and notification updates here without writing it twice. + if (!isRecovery) { + yield call(dbManager.createObject, RealmSchema.VersionHistory, { + version: `${newVersion}(${DeviceInfo.getBuildNumber()})`, + date: new Date().toString(), + title: `Upgraded from ${previousVersion} to ${newVersion}`, + }); + } const firebaseApp = getApp(); const messagingInstance = getMessaging(firebaseApp); unsubscribeFromTopic(messagingInstance, getReleaseTopic(previousVersion)); diff --git a/tests/store/versionHistory.test.ts b/tests/store/versionHistory.test.ts index 8526829fc8..677ae3bb72 100644 --- a/tests/store/versionHistory.test.ts +++ b/tests/store/versionHistory.test.ts @@ -47,15 +47,28 @@ function writeHistory(action) { return write.payload.args[1]; } +function recoverWithoutDuplicateHistory(action) { + const worker = updateVersionHistoryWorker(action); + expect(worker.next().value).toEqual(call(dbManager.getObjectByIndex, RealmSchema.KeeperApp)); + expect(worker.next({ id: 'test-app' } as any).value).toEqual( + call(Relay.updateAppImage, { appId: 'test-app', version: newVersion }) + ); + expect(worker.next({} as any).done).toBe(true); +} + describe('Version History retains recovery provenance through required upgrades', () => { - test.each([true, false])('upgrade passes recovery=%s to the history writer', (isRecovery) => { + test.each([true, false])('upgrade handles recovery=%s without duplicate history', (isRecovery) => { const upgrade = applyUpgradeSequence({ previousVersion, newVersion, isRecovery }); expect(upgrade.next().value).toEqual(put(setAppVersion(newVersion))); const history = upgrade.next().value as any; expect(history).toEqual(put(updateVersionHistory(previousVersion, newVersion, isRecovery))); - const record = writeHistory(history.payload.action); - expect(record.version).toBe('2.5.16(624)'); - expect(record.title).toBe(isRecovery ? 'Recovered Wallet' : 'Upgraded from 2.5.15 to 2.5.16'); + if (isRecovery) { + recoverWithoutDuplicateHistory(history.payload.action); + } else { + const record = writeHistory(history.payload.action); + expect(record.version).toBe('2.5.16(624)'); + expect(record.title).toBe('Upgraded from 2.5.15 to 2.5.16'); + } expect(upgrade.next().done).toBe(true); }); @@ -89,7 +102,7 @@ function recoveryFixture(backupVersion: string) { ts.isFunctionDeclaration(node) && ['getAppImageWorker', 'recoverApp', 'writeRecoveredObject'].includes(node.name?.text) ); - const writes = new Map(); + const writes = []; const recoveryUpgrades = []; const errors = []; const scope: any = { @@ -142,7 +155,7 @@ function recoveryFixture(backupVersion: string) { addSigningDeviceWorker: () => {}, dbManager: { createObject: (schema, record) => { - if (schema === RealmSchema.VersionHistory) writes.set(record.version, record); + if (schema === RealmSchema.VersionHistory) writes.push(record); return true; }, createObjectBulk: () => {}, @@ -218,8 +231,8 @@ function recoveryFixture(backupVersion: string) { const action = effect.payload.action; if (action.type === 'setAppImageError' && action.payload) errors.push(action.payload); if (action.type === 'UPDATE_VERSION_HISTORY') { - const record = writeHistory(action); - writes.set(record.version, record); + if (action.payload.isRecovery) recoverWithoutDuplicateHistory(action); + else writes.push(writeHistory(action)); } } result = generator.next(response); @@ -235,7 +248,7 @@ test.each(['2.5.15', '2.5.16'])( (backupVersion) => { const { writes, recoveryUpgrades, errors } = recoveryFixture(backupVersion); expect(errors).toEqual([]); - expect([...writes.values()]).toEqual([ + expect(writes).toEqual([ expect.objectContaining({ version: '2.5.16(624)', title: 'Recovered Wallet', From 5ab398397a8e353d94879065932ca3c146973803 Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 17:21:05 +0530 Subject: [PATCH 14/19] Check backup freshness after wallet sync completes --- src/store/sagaActions/wallets.ts | 6 +++-- src/store/sagas/login.ts | 12 +--------- src/store/sagas/wallets.ts | 31 +++++++++++++++++++++---- tests/recovery/backupFreshness.test.cjs | 27 +++++++++++++++++++++ tests/recovery/sagaHarness.cjs | 10 +++++++- 5 files changed, 68 insertions(+), 18 deletions(-) diff --git a/src/store/sagaActions/wallets.ts b/src/store/sagaActions/wallets.ts index 0508d24152..b9078e1e3e 100644 --- a/src/store/sagaActions/wallets.ts +++ b/src/store/sagaActions/wallets.ts @@ -29,13 +29,15 @@ export const getTestcoins = (testWallet: Wallet) => ({ export const autoSyncWallets = ( syncAll?: boolean, hardRefresh?: boolean, - addNotifications?: boolean + addNotifications?: boolean, + backupCheckAppId?: string ) => ({ type: AUTO_SYNC_WALLETS, payload: { syncAll, hardRefresh, addNotifications, + backupCheckAppId, }, }); @@ -145,4 +147,4 @@ export const generateNewAddress = (wallet: Wallet | Vault) => ({ export const updateVaultSignersXpriv = (signers: Signer[]) => ({ type: UPDATED_VAULT_SIGNERS_XPRIV, signers, -}); \ No newline at end of file +}); diff --git a/src/store/sagas/login.ts b/src/store/sagas/login.ts index 35028a9bc8..93465bf271 100644 --- a/src/store/sagas/login.ts +++ b/src/store/sagas/login.ts @@ -51,7 +51,6 @@ import { createWatcher } from '../utilities'; import { fetchExchangeRates } from '../sagaActions/send_and_receive'; import { setLoginMethod } from '../reducers/settings'; import { setSubscription } from 'src/store/sagaActions/settings'; -import { checkBackupFreshness } from '../sagaActions/bhr'; import { uaiChecks } from '../sagaActions/uai'; import { applyUpgradeSequence } from './upgrade'; import { resetSyncing } from '../reducers/wallets'; @@ -228,7 +227,7 @@ function* credentialsAuthWorker({ payload }) { // Wallet/node refresh runs through its watcher after local unlock. // Waiting for network work here can hold the success modal for 15s. yield put(resetSyncing()); - yield put(autoSyncWallets(false, false, true)); + yield put(autoSyncWallets(false, false, true, id)); yield put( uaiChecks([ @@ -241,15 +240,6 @@ function* credentialsAuthWorker({ payload }) { ]) ); - const { - pendingAllBackup, - automaticCloudBackup, - backupRepairCompletedByAppId = {}, - } = yield select((state: RootState) => state.bhr); - // Check without uploading; a mismatch requires Back Up Now. - if (automaticCloudBackup && (pendingAllBackup || !backupRepairCompletedByAppId[id])) { - yield put(checkBackupFreshness()); - } if (!allAccounts.length) { // upgraded app yield put(addAccount(appId)); diff --git a/src/store/sagas/wallets.ts b/src/store/sagas/wallets.ts index d212e033db..cd3d786253 100644 --- a/src/store/sagas/wallets.ts +++ b/src/store/sagas/wallets.ts @@ -71,6 +71,7 @@ import { } from 'src/utils/utilities'; import { COLLABORATIVE_SCHEME } from 'src/screens/SigningDevices/SetupCollaborativeWallet'; import { RootState } from '../store'; +import { checkBackupFreshness } from '../sagaActions/bhr'; import { initiateVaultMigration, @@ -633,7 +634,7 @@ function* refreshWalletsWorker({ }); try { - if (!wallets || wallets.length === 0) return; + if (!wallets || wallets.length === 0) return true; if (!ELECTRUM_CLIENT.isClientConnected) { ElectrumClient.resetCurrentPeerIndex(); @@ -882,6 +883,7 @@ function* refreshWalletsWorker({ yield put(setPendingDustToast(synchedWallet.id)); } } // end for (synchedWalletWithUTXOs) + return true; } catch (err) { if ([ELECTRUM_NOT_CONNECTED_ERR, ELECTRUM_NOT_CONNECTED_ERR_TOR].includes(err?.message)) { yield put( @@ -897,6 +899,7 @@ function* refreshWalletsWorker({ ); captureError(err); } + return false; } finally { yield put(setSyncing({ wallets, isSyncing: false })); } @@ -907,9 +910,14 @@ export const refreshWalletsWatcher = createWatcher(refreshWalletsWorker, REFRESH export function* autoWalletsSyncWorker({ payload, }: { - payload: { syncAll?: boolean; hardRefresh?: boolean; addNotifications?: boolean }; + payload: { + syncAll?: boolean; + hardRefresh?: boolean; + addNotifications?: boolean; + backupCheckAppId?: string; + }; }) { - const { syncAll, hardRefresh, addNotifications } = payload; + const { syncAll, hardRefresh, addNotifications, backupCheckAppId } = payload; const wallets: Wallet[] = yield call(dbManager.getObjectByIndex, RealmSchema.Wallet, null, true); const vaults: Vault[] = yield call(dbManager.getObjectByIndex, RealmSchema.Vault, null, true); const { bitcoinNetworkType } = yield select((state: RootState) => state.settings); @@ -923,8 +931,9 @@ export function* autoWalletsSyncWorker({ } walletsToSync = walletsToSync.filter((wallet) => wallet.networkType === bitcoinNetworkType); + let refreshSucceeded = true; if (walletsToSync.length) { - yield call(refreshWalletsWorker, { + refreshSucceeded = yield call(refreshWalletsWorker, { payload: { wallets: walletsToSync, options: { @@ -934,6 +943,20 @@ export function* autoWalletsSyncWorker({ }, }); } + // Check backup freshness only after the refreshed wallet specs are persisted. + // A failed refresh or account switch must not verify a stale snapshot. + if (backupCheckAppId && refreshSucceeded) { + const { appId } = yield select((state: RootState) => state.storage); + const { automaticCloudBackup, pendingAllBackup, backupRepairCompletedByAppId = {} } = + yield select((state: RootState) => state.bhr); + if ( + appId === backupCheckAppId && + automaticCloudBackup && + (pendingAllBackup || !backupRepairCompletedByAppId[appId]) + ) { + yield put(checkBackupFreshness()); + } + } } export const autoWalletsSyncWatcher = createWatcher(autoWalletsSyncWorker, AUTO_SYNC_WALLETS); diff --git a/tests/recovery/backupFreshness.test.cjs b/tests/recovery/backupFreshness.test.cjs index 03ff4b9ab2..e03ad47b90 100644 --- a/tests/recovery/backupFreshness.test.cjs +++ b/tests/recovery/backupFreshness.test.cjs @@ -3,6 +3,33 @@ const assert = require('node:assert/strict'); const { fixture, enums, encryption, wallet, loadModule } = require('./sagaHarness.cjs'); const { NetworkType, WalletType } = enums; +test('login backup inspection waits for wallet refresh to finish', async () => { + let finishSync; + const syncGate = new Promise((resolve) => { finishSync = resolve; }); + const f = fixture({ bhr: { pendingAllBackup: true }, syncGate }); + f.collections.Wallet.push(wallet('pending', NetworkType.MAINNET)); + const running = f.run('autoWalletsSyncWorker', { + payload: { syncAll: false, hardRefresh: false, addNotifications: true, backupCheckAppId: f.app.id }, + }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(f.calls.map(([type]) => type), ['sync']); + assert.equal(f.actions.some((action) => action.type === 'checkBackupFreshness'), false); + finishSync(); + await running; + assert.equal(f.actions.filter((action) => action.type === 'checkBackupFreshness').length, 1); +}); + +test('failed refresh and account switch do not verify backup freshness', async () => { + for (const option of ['syncFails', 'switchAppDuringSync']) { + const f = fixture({ bhr: { pendingAllBackup: true }, [option]: true }); + f.collections.Wallet.push(wallet('pending', NetworkType.MAINNET)); + await f.run('autoWalletsSyncWorker', { + payload: { backupCheckAppId: f.app.id }, + }); + assert.equal(f.actions.some((action) => action.type === 'checkBackupFreshness'), false); + } +}); + for (const network of [NetworkType.MAINNET, NetworkType.TESTNET]) { test(`wallet added after initial backup survives encrypted restore: ${network}`, async () => { const f = fixture(); diff --git a/tests/recovery/sagaHarness.cjs b/tests/recovery/sagaHarness.cjs index ab82a1d9c4..37cc5412d7 100644 --- a/tests/recovery/sagaHarness.cjs +++ b/tests/recovery/sagaHarness.cjs @@ -77,6 +77,7 @@ const signer = (fingerprint, networkType, type = enums.SignerType.COLDCARD, acco function fixture(options = {}) { const appId = require('crypto').createHash('sha256').update(Buffer.from('ab'.repeat(32), 'hex')).digest('hex'); const state = { + storage: { appId }, bhr: { automaticCloudBackup: true, pendingAllBackup: false, @@ -213,6 +214,12 @@ function fixture(options = {}) { semver: require('semver'), setupRecoveryKeySigningKey: () => signer('RECOVERY', NetworkType.MAINNET, enums.SignerType.SEED_WORDS), applyUpgradeSequence: () => {}, + refreshWalletsWorker: async () => { + calls.push(['sync']); + if (options.syncGate) await options.syncGate; + if (options.switchAppDuringSync) state.storage.appId = 'another-app'; + return options.syncFails !== true; + }, }; const names = [ 'setBackupRepairCompleted', @@ -235,6 +242,7 @@ function fixture(options = {}) { 'setAppId', 'setAppCreated', 'autoSyncWallets', + 'checkBackupFreshness', 'uaiChecks', 'loadConciergeUser', 'loadConciergeTickets', @@ -264,7 +272,7 @@ function fixture(options = {}) { functions('src/store/sagas/wallets.ts', [ 'addNewWalletsWorker', 'addSigningDeviceWorker', 'mergeSimilarKeysWorker', 'updateVaultSignerXprivWorker', 'updateSignerDetailsWorker', - 'updateKeyDetailsWorker', + 'updateKeyDetailsWorker', 'autoWalletsSyncWorker', ]); vm.runInNewContext( ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ES2020 } }).outputText, From 197feb399458fa71d1ea7286219e46ec34861c79 Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 23:26:39 +0530 Subject: [PATCH 15/19] fix: serialize signer migration and reject failed refresh writes --- src/services/backend/Relay.ts | 2 +- src/store/sagas/wallets.ts | 16 ++- tests/recovery/backupFreshness.test.cjs | 81 +++++++++++++- tests/recovery/fingerprintTransport.test.cjs | 110 +++++++++++++++++++ 4 files changed, 198 insertions(+), 11 deletions(-) create mode 100644 tests/recovery/fingerprintTransport.test.cjs diff --git a/src/services/backend/Relay.ts b/src/services/backend/Relay.ts index d9a33502ad..9bcdcb3fe4 100644 --- a/src/services/backend/Relay.ts +++ b/src/services/backend/Relay.ts @@ -142,7 +142,7 @@ export default class Relay { err?: string; }> => { try { - const res = await RestClient.post(`${RELAY}migrateXfps`, { appId, signerChanges }); + const res = await backupPost(`${RELAY}migrateXfps`, { appId, signerChanges }); const data = res.data || res.json; return data; } catch (err) { diff --git a/src/store/sagas/wallets.ts b/src/store/sagas/wallets.ts index cd3d786253..839c894ca3 100644 --- a/src/store/sagas/wallets.ts +++ b/src/store/sagas/wallets.ts @@ -869,15 +869,13 @@ function* refreshWalletsWorker({ } // Write updated specs (with spendability) back to Realm - if (synchedWallet.entityKind === EntityKind.VAULT) { - yield call(dbManager.updateObjectById, RealmSchema.Vault, synchedWallet.id, { - specs: synchedWallet.specs, - }); - } else { - yield call(dbManager.updateObjectById, RealmSchema.Wallet, synchedWallet.id, { - specs: synchedWallet.specs, - }); - } + const persisted = yield call( + dbManager.updateObjectById, + synchedWallet.entityKind === EntityKind.VAULT ? RealmSchema.Vault : RealmSchema.Wallet, + synchedWallet.id, + { specs: synchedWallet.specs } + ); + if (!persisted) throw new Error('Failed to persist refreshed wallet'); if (options.addNotifications && newDustUTXOs.length > 0) { yield put(setPendingDustToast(synchedWallet.id)); diff --git a/tests/recovery/backupFreshness.test.cjs b/tests/recovery/backupFreshness.test.cjs index e03ad47b90..4676654e7c 100644 --- a/tests/recovery/backupFreshness.test.cjs +++ b/tests/recovery/backupFreshness.test.cjs @@ -1,8 +1,87 @@ const { test } = require('node:test'); const assert = require('node:assert/strict'); -const { fixture, enums, encryption, wallet, loadModule } = require('./sagaHarness.cjs'); +const vm = require('node:vm'); +const ts = require('typescript'); +const { fixture, enums, encryption, wallet, loadModule, functions } = require('./sagaHarness.cjs'); const { NetworkType, WalletType } = enums; +function refreshFixture(kind, rejectWrite = false) { + const f = fixture({ bhr: { pendingAllBackup: true } }); + const original = { + ...wallet('refresh-persistence', NetworkType.MAINNET), + entityKind: kind === 'Vault' ? enums.EntityKind.VAULT : enums.EntityKind.WALLET, + specs: { + receivingAddress: 'before-refresh', + confirmedUTXOs: [], unconfirmedUTXOs: [], transactions: [], + addresses: { external: {}, internal: {} }, + }, + }; + f.collections[kind].push(original); + f.scope.getJSONFromRealmObject = (value) => JSON.parse(JSON.stringify(value)); + f.scope.ELECTRUM_CLIENT = { isClientConnected: true }; + f.scope.WalletUtilities.getNetworkByType = () => ({}); + f.scope.WalletOperations = { syncWalletsViaElectrumClient: async () => { + const synced = f.scope.getJSONFromRealmObject(original); + synced.specs.receivingAddress = 'after-refresh'; + synced.specs.hasNewUpdates = true; + return { synchedWallets: [{ synchedWallet: synced, newUTXOs: [] }] }; + } }; + f.scope.classifyDustByAddress = () => ({ + taintedAddresses: new Set(), initialTaintAddresses: new Set(), dustSpendTxids: new Set(), + }); + f.scope.setSyncing = (payload) => ({ type: 'setSyncing', payload }); + f.scope.setElectrumNotConnectedErr = (payload) => ({ type: 'setElectrumNotConnectedErr', payload }); + f.scope.ELECTRUM_NOT_CONNECTED_ERR = 'offline'; + f.scope.ELECTRUM_NOT_CONNECTED_ERR_TOR = 'tor-offline'; + f.errors = []; + f.scope.captureError = (error) => f.errors.push(error); + const persist = f.scope.dbManager.updateObjectById; + f.writes = []; + f.scope.dbManager.updateObjectById = (schema, id, patch) => { + f.writes.push(schema); + return rejectWrite ? false : persist(schema, id, patch); + }; + vm.runInNewContext(ts.transpileModule( + functions('src/store/sagas/wallets.ts', ['refreshWalletsWorker']), + { compilerOptions: { target: ts.ScriptTarget.ES2020 } } + ).outputText, f.scope); + return f; +} + +for (const kind of ['Wallet', 'Vault']) { + test(`${kind}: rejected refresh persistence returns failure and clears syncing`, async () => { + const f = refreshFixture(kind, true); + assert.equal(await f.run('refreshWalletsWorker', { + payload: { wallets: f.collections[kind], options: { hardRefresh: true } }, + }), false); + assert.deepEqual(f.writes, [kind]); + assert.equal(f.collections[kind][0].specs.receivingAddress, 'before-refresh'); + assert.deepEqual(f.actions.filter((action) => action.type === 'setSyncing') + .map((action) => action.payload.isSyncing), [true, false]); + assert.equal(f.errors.length, 1); + assert.ok(f.actions.some((action) => action.type === 'setElectrumNotConnectedErr' && + action.payload.includes('Failed to persist refreshed wallet'))); + }); + + test(`${kind}: login never inspects stale specs after rejected refresh persistence`, async () => { + const f = refreshFixture(kind, true); + await f.run('autoWalletsSyncWorker', { payload: { backupCheckAppId: f.app.id } }); + assert.deepEqual(f.writes, [kind]); + assert.equal(f.collections[kind][0].specs.receivingAddress, 'before-refresh'); + assert.equal(f.actions.some((action) => action.type === 'checkBackupFreshness'), false); + assert.equal(f.state.bhr.pendingAllBackup, true); + }); + + test(`${kind}: login inspects backup only after successful refresh persistence`, async () => { + const f = refreshFixture(kind); + await f.run('autoWalletsSyncWorker', { payload: { backupCheckAppId: f.app.id } }); + assert.deepEqual(f.writes, [kind]); + assert.equal(f.collections[kind][0].specs.receivingAddress, 'after-refresh'); + assert.equal(f.actions.filter((action) => action.type === 'checkBackupFreshness').length, 1); + assert.equal(f.errors.length, 0); + }); +} + test('login backup inspection waits for wallet refresh to finish', async () => { let finishSync; const syncGate = new Promise((resolve) => { finishSync = resolve; }); diff --git a/tests/recovery/fingerprintTransport.test.cjs b/tests/recovery/fingerprintTransport.test.cjs new file mode 100644 index 0000000000..8b971e26c0 --- /dev/null +++ b/tests/recovery/fingerprintTransport.test.cjs @@ -0,0 +1,110 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const crypto = require('node:crypto'); +const { loadModule, harness, wallet } = require('./helpers.cjs'); + +const signerChanges = [{ + oldSignerId: 'fixture-old', newSignerId: 'fixture-new', newSignerDetails: 'fixture-ciphertext', +}]; + +function relay(transport, rest = { post: () => assert.fail('Migration bypassed backup transport') }, errors = []) { + return loadModule('src/services/backend/Relay.ts', { + '../backup/transport': transport, + '../rest/RestClient': rest, + '../sentry': { captureError: (error) => errors.push(error) }, + 'src/services/wallets/enums': {}, + 'src/utils/service-utilities/config': { RELAY: 'fixture/' }, + 'react-native': { Platform: { OS: 'fixture' } }, + }).default; +} + +for (const repair of [false, true]) { + test(`fingerprint migration waits for ${repair ? 'repair readback' : 'inspection'} and invalidates its completion`, async (t) => { + let armed = false, reads = 0, release, entered; + const readGate = new Promise((resolve) => { release = resolve; }); + const readStarted = new Promise((resolve) => { entered = resolve; }); + t.after(() => release()); + let f; + let vaults = [], labels = []; + const revision = () => crypto.createHash('sha256') + .update(JSON.stringify({ remote: f.remote, vaults, labels })).digest('hex'); + f = harness({ + post: async ({ path }) => { + if (armed && path.endsWith('getBackupSnapshot') && ++reads === (repair ? 2 : 1)) { + entered(); + await readGate; + } + }, + adapter: (path, payload, config) => { + assert.ok(config.signal, 'Every backup request must use bounded transport'); + if (path === 'getBackupSnapshot') return { data: { + appImage: f.remote, allVaultImages: vaults, labels, revision: revision(), + } }; + if (path === 'migrateXfps') { + assert.equal(payload.appId, f.app.id); + assert.deepEqual(JSON.parse(JSON.stringify(payload.signerChanges)), signerChanges); + return { data: { updated: true } }; + } + assert.equal(path, 'repairAppBackup'); + assert.equal(payload.expectedRevision, revision()); + f.remote.wallets = { ...payload.walletObject }; + f.remote.signers = { ...payload.signersObject }; + f.remote.nodes = payload.nodes; + vaults = Object.values(payload.vaultObject); + labels = payload.labels; + f.remote.vaults = vaults.map((record) => record.vaultId); + f.remote.labels = labels.map((record) => record.id); + return { data: { updated: true } }; + }, + }); + f.local.Wallet.push(wallet()); + assert.equal(await f.run(true), 'verified'); + if (repair) f.local.Wallet[0].presentationData.name = 'Updated fixture wallet'; + f.calls.length = 0; + f.phases.length = 0; + armed = true; + const checking = f.run(repair); + await readStarted; + const previousRevision = f.transport.backupRevision(f.app.id); + const migration = relay(f.transport).migrateXfp(f.app.id, signerChanges); + const completed = Promise.allSettled([checking, migration]); + const requestedRevision = f.transport.backupRevision(f.app.id); + const migrationStartedDuringCheck = f.calls.includes('migrateXfps'); + release(); + const [checked, migrated] = await completed; + assert.equal(requestedRevision, previousRevision + 1); + assert.equal(migrationStartedDuringCheck, false); + assert.equal(checked.status, 'fulfilled'); + assert.equal(checked.value, 'unverified'); + assert.equal(f.phases.includes('verified'), false); + assert.equal(migrated.status, 'fulfilled'); + assert.equal(migrated.value.updated, true); + assert.deepEqual(f.calls, repair + ? ['getBackupSnapshot', 'repairAppBackup', 'getBackupSnapshot', 'migrateXfps'] + : ['getBackupSnapshot', 'migrateXfps']); + }); +} + +test('migration rejection and transport failure preserve responses, invalidate checks, and release the queue', async () => { + let fail = false; + const errors = []; + const rest = { post: async (_path, _body, _headers, config) => { + assert.ok(config.signal); + if (fail) throw Error('fixture request body must stay redacted'); + return { json: { updated: false, err: 'fixture-rejection' } }; + } }; + const transport = loadModule('src/services/backup/transport.ts', { '../rest/RestClient': rest }); + const service = relay(transport, rest, errors); + assert.deepEqual(JSON.parse(JSON.stringify(await service.migrateXfp('fixture-account', signerChanges))), + { updated: false, err: 'fixture-rejection' }); + assert.equal(transport.backupRevision('fixture-account'), 1); + fail = true; + await assert.rejects(service.migrateXfp('fixture-account', signerChanges), + /^Error: Failed to do migrate the xfp$/); + assert.equal(errors.length, 1); + assert.equal(errors[0].message, 'Backup request could not be completed'); + assert.equal(transport.backupRevision('fixture-account'), 2); + fail = false; + assert.equal((await service.migrateXfp('fixture-account', signerChanges)).updated, false); + assert.equal(transport.backupRevision('fixture-account'), 3); +}); From eb26eace8134a3101ae13a89566cd162baa546fc Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 23:26:39 +0530 Subject: [PATCH 16/19] fix: retain backup progress until shared inspections settle --- src/store/sagas/bhr.ts | 32 +++++++---- tests/recovery/sagaState.test.cjs | 90 +++++++++++++++++++++++++++++-- 2 files changed, 107 insertions(+), 15 deletions(-) diff --git a/src/store/sagas/bhr.ts b/src/store/sagas/bhr.ts index 206aaceb2d..ba417ac0e4 100644 --- a/src/store/sagas/bhr.ts +++ b/src/store/sagas/bhr.ts @@ -978,18 +978,24 @@ export const deleteAppImageEntityWatcher = createWatcher( DELETE_APP_IMAGE_ENTITY ); +const backupInspectionOwners = new Map(); + function* runBackupInspection(repair: boolean) { const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp); - yield put(setBackupRepairRunning({ appId: id, running: true })); + backupInspectionOwners.set(id, (backupInspectionOwners.get(id) ?? 0) + 1); let finalPhase: RepairPhase = 'unverified'; - const updates = eventChannel((emit) => { - inspectBackup(id, repair, (phase) => emit(phase)).then( - () => emit(END), - () => emit(END) - ); - return () => {}; - }, buffers.expanding()); + let inspection: Promise | undefined; + let updates: ReturnType> | undefined; try { + yield put(setBackupRepairRunning({ appId: id, running: true })); + updates = eventChannel((emit) => { + inspection = inspectBackup(id, repair, (phase) => emit(phase)); + inspection.then( + () => emit(END), + () => emit(END) + ); + return () => {}; + }, buffers.expanding()); while (true) { const phase = yield takeMaybe(updates); if (phase === END) break; @@ -1024,8 +1030,14 @@ function* runBackupInspection(repair: boolean) { } return finalPhase === 'verified'; } finally { - updates.close(); - yield put(setBackupRepairRunning({ appId: id, running: false })); + updates?.close(); + // Cancellation closes this listener, but does not stop its shared operation. + // Keep ownership until that operation settles, including a queued repair. + if (inspection) yield call(() => inspection.catch(() => undefined)); + const remaining = (backupInspectionOwners.get(id) ?? 1) - 1; + if (remaining) backupInspectionOwners.set(id, remaining); + else backupInspectionOwners.delete(id); + yield put(setBackupRepairRunning({ appId: id, running: remaining > 0 })); } } diff --git a/tests/recovery/sagaState.test.cjs b/tests/recovery/sagaState.test.cjs index 9285b375c1..b1dba4af81 100644 --- a/tests/recovery/sagaState.test.cjs +++ b/tests/recovery/sagaState.test.cjs @@ -12,20 +12,100 @@ const bhr = loadModule('src/store/reducers/bhr.ts', { 'src/storage': { reduxStorage:{} }, 'redux-persist': { persistReducer: (_config,reducer) => reducer }, }); -function runInspection(f, repair) { +function inspectionRunner(f) { const filename = 'src/store/sagas/bhr.ts'; const source = ts.createSourceFile(filename,fs.readFileSync(path.join(__dirname,'../..',filename),'utf8'),ts.ScriptTarget.Latest,true); - const code = source.statements.filter(n => ts.isFunctionDeclaration(n) && n.name?.text === 'runBackupInspection').map(n => n.getText(source)).join('\n'); - const scope = { ...saga, ...effects, ...bhr, inspectBackup:f.repair.inspectBackup, + const code = source.statements.filter(n => + (ts.isFunctionDeclaration(n) && n.name?.text === 'runBackupInspection') || + (ts.isVariableStatement(n) && n.declarationList.declarations.some(d => d.name?.text === 'backupInspectionOwners')) + ).map(n => n.getText(source)).join('\n'); + const operations = []; + const scope = { ...saga, ...effects, ...bhr, inspectBackup:(...args) => { + const operation = f.repair.inspectBackup(...args); + operations.push(operation); + return operation; + }, RealmSchema:{KeeperApp:'KeeperApp',UAI:'UAI'}, dbManager:{ getObjectByIndex:()=>f.app, getObjectByField:()=>[] }, uaiType:{SERVER_BACKUP_FAILURE:'failure'}, uaiActionedWorker:()=>{}, addToUaiStackWorker:()=>{}, }; vm.runInNewContext(ts.transpileModule(code,{ compilerOptions:{ target:ts.ScriptTarget.ES2020 }}).outputText,scope); let state = bhr.default(undefined,{type:'init'}); const actions = []; - const task = saga.runSaga({getState:()=>({bhr:state}),dispatch:action=>{ actions.push(action); state=bhr.default(state,action); }},scope.runBackupInspection,repair).toPromise(); - return {task,get state(){ return state; }, actions}; + return { + start(repair) { + const sagaTask = saga.runSaga({getState:()=>({bhr:state}),dispatch:action=>{ actions.push(action); state=bhr.default(state,action); }},scope.runBackupInspection,repair); + return {task:sagaTask.toPromise(),sagaTask,settled:()=>Promise.all(operations),get state(){ return state; },actions}; + }, + }; } +const runInspection = (f, repair) => inspectionRunner(f).start(repair); + +const gate = () => { + let release; + const promise = new Promise(resolve => { release = resolve; }); + return {promise,release}; +}; + +test('queued repair keeps actions disabled after the read-only wrapper finishes', async (t) => { + const read = gate(), readStarted = gate(), upload = gate(), uploadStarted = gate(); + t.after(() => { read.release(); upload.release(); }); + let firstRead = true; + const f = harness({post:async ({path}) => { + if (path.endsWith('getBackupSnapshot') && firstRead) { + firstRead = false; readStarted.release(); await read.promise; + } + if (path.endsWith('repairAppBackup')) { uploadStarted.release(); await upload.promise; } + }}); + f.local.Wallet.push(wallet()); + const runner = inspectionRunner(f); + const check = runner.start(false); + await readStarted.promise; + const repair = runner.start(true); + read.release(); + assert.equal(await check.task, false); + await uploadStarted.promise; + assert.equal(repair.state.backupRepairRunningByAppId.disposable, true); + assert.equal(repair.actions.some(a => a.type === 'bhr/setBackupRepairRunning' && !a.payload.running), false); + upload.release(); + assert.equal(await repair.task, true); + assert.equal(repair.state.backupRepairRunningByAppId.disposable, false); +}); + +test('cancelling a coalesced wrapper does not clear another running repair', async (t) => { + const upload = gate(), uploadStarted = gate(); + t.after(() => upload.release()); + const f = harness({post:async ({path}) => { + if (path.endsWith('repairAppBackup')) { uploadStarted.release(); await upload.promise; } + }}); + f.local.Wallet.push(wallet()); + const runner = inspectionRunner(f), first = runner.start(true); + await uploadStarted.promise; + const second = runner.start(true); + first.sagaTask.cancel(); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(second.state.backupRepairRunningByAppId.disposable, true); + upload.release(); + await first.task; + assert.equal(await second.task, true); + assert.equal(second.state.backupRepairRunningByAppId.disposable, false); + assert.equal(f.calls.filter(path => path === 'repairAppBackup').length, 1); +}); + +test('cancellation retains progress until its non-cancellable inspection actually settles', async (t) => { + const read = gate(), readStarted = gate(); + t.after(() => read.release()); + const f = harness({post:async () => { readStarted.release(); await read.promise; }}); + const run = runInspection(f, false); + await readStarted.promise; + run.sagaTask.cancel(); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(run.state.backupRepairRunningByAppId.disposable, true); + read.release(); + await run.task; + await run.settled(); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(run.state.backupRepairRunningByAppId.disposable, false); +}); test('only verified readback sets durable per-account completion and clears pending', async () => { const f = harness(); f.local.Wallet.push(wallet()); const run=runInspection(f,true); From 27943db4afda7b5cdf3d66b821bb46df2f1497dc Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 23:26:39 +0530 Subject: [PATCH 17/19] ci: check release consistency on actual checkout --- .github/workflows/test.yml | 3 +++ openspec/changes/fix-release-version-consistency/design.md | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 900273c88c..8a5680c736 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -60,5 +60,8 @@ jobs: - name: Run recovery regression tests run: npm run test:recovery + - name: Verify checked-out release version consistency + run: npm run version:check + - name: Run release and packaged-artifact tests run: npm run test:release diff --git a/openspec/changes/fix-release-version-consistency/design.md b/openspec/changes/fix-release-version-consistency/design.md index f8df1e8d18..2862d15f90 100644 --- a/openspec/changes/fix-release-version-consistency/design.md +++ b/openspec/changes/fix-release-version-consistency/design.md @@ -41,6 +41,6 @@ DESIGN.md reviewed: no UI change, so existing typography, colors, components and ## Open Questions -- Candidate selected: 2.5.15, Android 622, iOS 615. Refresh store baselines before upload. +- This baseline records 2.6.3, Android 626, iOS 619, matching `release/version.json` and the release guide. R3 is an internal work bucket; any subsequent app delivery needs refreshed store baselines and new version intent before building or uploading. - Canonical release source after reconciling iOS and Android published-build provenance. - Public APK channel is GitHub Releases with SHA256SUM.asc and KEEPER_DETACHED_SIGN.sign. Existing local keystore certificate matches public APK 2.5.13; PGP signing access remains to be resolved. From 8d3e06855472ef65a8026b535fd2e2f033482bcb Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 23:46:45 +0530 Subject: [PATCH 18/19] test(backup): verify fresh inspection after fingerprint migration --- tests/recovery/fingerprintTransport.test.cjs | 49 +++++++++++++++----- 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/tests/recovery/fingerprintTransport.test.cjs b/tests/recovery/fingerprintTransport.test.cjs index 8b971e26c0..bb5daab124 100644 --- a/tests/recovery/fingerprintTransport.test.cjs +++ b/tests/recovery/fingerprintTransport.test.cjs @@ -21,6 +21,7 @@ function relay(transport, rest = { post: () => assert.fail('Migration bypassed b for (const repair of [false, true]) { test(`fingerprint migration waits for ${repair ? 'repair readback' : 'inspection'} and invalidates its completion`, async (t) => { let armed = false, reads = 0, release, entered; + const events = []; const readGate = new Promise((resolve) => { release = resolve; }); const readStarted = new Promise((resolve) => { entered = resolve; }); t.after(() => release()); @@ -30,19 +31,26 @@ for (const repair of [false, true]) { .update(JSON.stringify({ remote: f.remote, vaults, labels })).digest('hex'); f = harness({ post: async ({ path }) => { - if (armed && path.endsWith('getBackupSnapshot') && ++reads === (repair ? 2 : 1)) { - entered(); - await readGate; + if (armed && path.endsWith('getBackupSnapshot')) { + events.push(`snapshot-request:${++reads}`); + if (reads === (repair ? 2 : 1)) { + entered(); + await readGate; + } } }, adapter: (path, payload, config) => { assert.ok(config.signal, 'Every backup request must use bounded transport'); - if (path === 'getBackupSnapshot') return { data: { - appImage: f.remote, allVaultImages: vaults, labels, revision: revision(), - } }; + if (path === 'getBackupSnapshot') { + if (armed) events.push(`snapshot-response:${reads}`); + return { data: { + appImage: f.remote, allVaultImages: vaults, labels, revision: revision(), + } }; + } if (path === 'migrateXfps') { assert.equal(payload.appId, f.app.id); assert.deepEqual(JSON.parse(JSON.stringify(payload.signerChanges)), signerChanges); + events.push('migration-acknowledged'); return { data: { updated: true } }; } assert.equal(path, 'repairAppBackup'); @@ -63,7 +71,10 @@ for (const repair of [false, true]) { f.calls.length = 0; f.phases.length = 0; armed = true; - const checking = f.run(repair); + const checking = f.repair.inspectBackup(f.app.id, repair, (phase) => { + f.phases.push(phase); + events.push(`phase:${phase}`); + }); await readStarted; const previousRevision = f.transport.backupRevision(f.app.id); const migration = relay(f.transport).migrateXfp(f.app.id, signerChanges); @@ -75,13 +86,27 @@ for (const repair of [false, true]) { assert.equal(requestedRevision, previousRevision + 1); assert.equal(migrationStartedDuringCheck, false); assert.equal(checked.status, 'fulfilled'); - assert.equal(checked.value, 'unverified'); - assert.equal(f.phases.includes('verified'), false); assert.equal(migrated.status, 'fulfilled'); assert.equal(migrated.value.updated, true); - assert.deepEqual(f.calls, repair - ? ['getBackupSnapshot', 'repairAppBackup', 'getBackupSnapshot', 'migrateXfps'] - : ['getBackupSnapshot', 'migrateXfps']); + if (!repair && checked.value === 'verified') { + // A read-only retry may verify a new snapshot after queued writes drain. + // The invalidated first attempt must never publish verified completion. + assert.deepEqual(f.calls, ['getBackupSnapshot', 'migrateXfps', 'getBackupSnapshot']); + assert.equal(reads, 2); + assert.equal(f.phases.filter((phase) => phase === 'verified').length, 1); + const acknowledged = events.indexOf('migration-acknowledged'); + const freshRequest = events.indexOf('snapshot-request:2'); + const freshResponse = events.indexOf('snapshot-response:2'); + const verified = events.indexOf('phase:verified'); + assert.ok(acknowledged >= 0 && freshRequest > acknowledged); + assert.ok(freshResponse > freshRequest && verified > freshResponse); + } else { + assert.equal(checked.value, 'unverified'); + assert.equal(f.phases.includes('verified'), false); + assert.deepEqual(f.calls, repair + ? ['getBackupSnapshot', 'repairAppBackup', 'getBackupSnapshot', 'migrateXfps'] + : ['getBackupSnapshot', 'migrateXfps']); + } }); } From fee03fab6557595e3180b6fb895becf3a6f85815 Mon Sep 17 00:00:00 2001 From: Anant Date: Wed, 7 Oct 2026 23:47:50 +0530 Subject: [PATCH 19/19] test(backup): require read completion before migration acknowledgement --- tests/recovery/fingerprintTransport.test.cjs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/recovery/fingerprintTransport.test.cjs b/tests/recovery/fingerprintTransport.test.cjs index bb5daab124..4e035df3ba 100644 --- a/tests/recovery/fingerprintTransport.test.cjs +++ b/tests/recovery/fingerprintTransport.test.cjs @@ -88,13 +88,16 @@ for (const repair of [false, true]) { assert.equal(checked.status, 'fulfilled'); assert.equal(migrated.status, 'fulfilled'); assert.equal(migrated.value.updated, true); + const heldResponse = events.indexOf(`snapshot-response:${repair ? 2 : 1}`); + const acknowledged = events.indexOf('migration-acknowledged'); + assert.ok(heldResponse >= 0 && acknowledged > heldResponse, + 'Fingerprint migration must wait for the held backup response'); if (!repair && checked.value === 'verified') { // A read-only retry may verify a new snapshot after queued writes drain. // The invalidated first attempt must never publish verified completion. assert.deepEqual(f.calls, ['getBackupSnapshot', 'migrateXfps', 'getBackupSnapshot']); assert.equal(reads, 2); assert.equal(f.phases.filter((phase) => phase === 'verified').length, 1); - const acknowledged = events.indexOf('migration-acknowledged'); const freshRequest = events.indexOf('snapshot-request:2'); const freshResponse = events.indexOf('snapshot-response:2'); const verified = events.indexOf('phase:verified');