diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 0000000000..baadc36f3e
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1,2 @@
+# Request the three developers for all changes; one approval is required.
+* @ben-kaufman @cakesoft-utkarsh @Parsh
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 0000000000..91cd9f43e4
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,35 @@
+## Problem and change
+
+
+
+Issue:
+OpenSpec change / archived proposal:
+Target branch:
+
+## Test results
+
+
+
+| Check / scenario | Platform | Passed / failed / blocked / not run | Evidence or reason |
+| --- | --- | --- | --- |
+| | | | |
+
+## Review considerations
+
+
+
+- [ ] The diff excludes local secrets, wallet data and generated build/dependency files.
+- [ ] Test failures and untested behavior are recorded above.
+- [ ] The issue/spec and implementation describe the same scope.
+
+Keeper maintainers own security review, acceptance, merging and official releases.
+Passing checks does not constitute approval.
+
+## Signoff
+
+- Copilot review findings:
+- Developer approval:
+- Product owner signoff:
diff --git a/.github/workflows/android-diagnostic-build.yml b/.github/workflows/android-diagnostic-build.yml
new file mode 100644
index 0000000000..9ebe30f1f8
--- /dev/null
+++ b/.github/workflows/android-diagnostic-build.yml
@@ -0,0 +1,153 @@
+name: Android diagnostic build
+
+on:
+ pull_request:
+ branches:
+ - 'release/**'
+ - sprint
+ - dev
+ - main
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: android-diagnostic-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ build:
+ # Hosted feature acceptance owns PR native scheduling. Retain explicit package diagnostics only.
+ if: github.event_name == 'workflow_dispatch'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 90
+
+ steps:
+ - name: Check out source
+ uses: actions/checkout@v4
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ persist-credentials: false
+
+ - name: Set up Node
+ uses: actions/setup-node@v4
+ with:
+ node-version: 22.23.3
+
+ - name: Set up Java
+ uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: '17.0.19'
+
+ - name: Set up Android SDK tools
+ uses: android-actions/setup-android@v4
+ with:
+ packages: ''
+
+ - name: Install Android build packages
+ run: sdkmanager 'platforms;android-36' 'build-tools;35.0.0' 'ndk;27.0.12077973' 'ndk;27.1.12297006' 'cmake;3.22.1'
+
+ - name: Install JavaScript dependencies without the iOS setup hook
+ run: |
+ npm install --global yarn@1.22.22
+ yarn install --frozen-lockfile --ignore-scripts --non-interactive
+ ./node_modules/.bin/patch-package
+ ./node_modules/.bin/rn-nodeify --install buffer,events,process,stream,inherits,path,assert,crypto --hack --yarn
+
+ - name: Create diagnostic configuration
+ run: |
+ cat > "$RUNNER_TEMP/keeper-diagnostic.env" <<'EOF'
+ CHANNEL_URL=https://channel.bitcoinkeeper.app/
+ ENVIRONMENT=PRODUCTION
+ HEXA_ID_MAINNET=0000000000000000000000000000000000000000000000000000000000000000
+ HEXA_ID_TESTNET=0000000000000000000000000000000000000000000000000000000000000000
+ RELAY=https://example.invalid/
+ SIGNING_SERVER_MAINNET=https://example.invalid/
+ SIGNING_SERVER_TESTNET=https://example.invalid/
+ EOF
+ node scripts/verify-channel-config.cjs "$RUNNER_TEMP/keeper-diagnostic.env"
+ printf 'sdk.dir=%s\n' "$ANDROID_SDK_ROOT" > android/local.properties
+
+ - name: Verify pinned Android inputs
+ env:
+ SOURCE_COMMIT: ${{ github.event.pull_request.head.sha || github.sha }}
+ run: |
+ python3 -B reproducibility/verify-android-inputs.py \
+ --source-commit "$SOURCE_COMMIT" \
+ --env-file "$RUNNER_TEMP/keeper-diagnostic.env" \
+ --android-sdk-root "$ANDROID_SDK_ROOT"
+
+ - name: Confirm Gradle rejects a retired mobile credential
+ run: |
+ cp "$RUNNER_TEMP/keeper-diagnostic.env" "$RUNNER_TEMP/keeper-rejected.env"
+ printf 'GASFREE_API_KEY=diagnostic-only\n' >> "$RUNNER_TEMP/keeper-rejected.env"
+ if (cd android && ENVFILE="$RUNNER_TEMP/keeper-rejected.env" ./gradlew :app:help --no-daemon --console=plain > "$RUNNER_TEMP/rejected-build.log" 2>&1); then
+ echo 'Gradle accepted a retired mobile credential' >&2
+ exit 1
+ fi
+ if ! grep -q 'Retired API credentials must not be included in an Android build' "$RUNNER_TEMP/rejected-build.log"; then
+ tail -80 "$RUNNER_TEMP/rejected-build.log"
+ exit 1
+ fi
+
+ - name: Build APK and AAB with the public debug key
+ env:
+ STORE_PASSWORD: android
+ KEY_ALIAS: androiddebugkey
+ KEY_PASSWORD: android
+ run: |
+ export ENVFILE="$RUNNER_TEMP/keeper-diagnostic.env"
+ export KEEPER_ANDROID_KEYSTORE="$GITHUB_WORKSPACE/android/app/debug.keystore"
+ cd android
+ ./gradlew :app:assembleProductionRelease :app:bundleProductionRelease --no-daemon --console=plain
+
+ - name: Check diagnostic artifacts
+ run: |
+ apk=android/app/build/outputs/apk/production/release/app-production-release.apk
+ aab=android/app/build/outputs/bundle/productionRelease/app-production-release.aab
+ test -s "$apk"
+ test -s "$aab"
+ "$ANDROID_SDK_ROOT/build-tools/35.0.0/apksigner" verify "$apk"
+ badging=$("$ANDROID_SDK_ROOT/build-tools/35.0.0/aapt2" dump badging "$apk")
+ version=$(node -p 'require("./release/version.json").version')
+ version_code=$(node -p 'require("./release/version.json").androidVersionCode')
+ grep -Fq "package: name='io.hexawallet.bitcoinkeeper' versionCode='$version_code' versionName='$version'" <<< "$badging"
+ if ! jarsigner -verify -verbose -certs "$aab" > "$RUNNER_TEMP/aab-signature.log" 2>&1; then
+ tail -80 "$RUNNER_TEMP/aab-signature.log"
+ exit 1
+ fi
+ if ! grep -Fxq 'jar verified.' "$RUNNER_TEMP/aab-signature.log" || grep -Fq '? = unsigned entry' "$RUNNER_TEMP/aab-signature.log"; then
+ tail -80 "$RUNNER_TEMP/aab-signature.log"
+ echo 'AAB is unsigned or contains unsigned entries' >&2
+ exit 1
+ fi
+ unzip -tq "$apk" >/dev/null
+ unzip -tq "$aab" >/dev/null
+ sha256sum "$apk" "$aab"
+ echo 'Diagnostic APK/AAB built with placeholder config and debug signing; no reproducibility verdict.'
+
+ - name: Stage diagnostic APK and provenance
+ env:
+ SOURCE_COMMIT: ${{ github.event.pull_request.head.sha || github.sha }}
+ run: |
+ apk=android/app/build/outputs/apk/production/release/app-production-release.apk
+ artifact_dir="$RUNNER_TEMP/android-diagnostic-apk"
+ mkdir -p "$artifact_dir"
+ cp "$apk" "$artifact_dir/keeper-diagnostic-production-release.apk"
+ {
+ printf 'source_commit=%s\n' "$SOURCE_COMMIT"
+ printf 'workflow_run_id=%s\n' "$GITHUB_RUN_ID"
+ printf 'apk_sha256=%s\n' "$(sha256sum "$artifact_dir/keeper-diagnostic-production-release.apk" | cut -d ' ' -f1)"
+ printf 'configuration=placeholder\nsigning=public-debug-key\npurpose=package-inspection-only\n'
+ } > "$artifact_dir/provenance.txt"
+
+ - name: Upload diagnostic APK for inspection
+ uses: actions/upload-artifact@v4
+ with:
+ name: android-diagnostic-apk-${{ github.event.pull_request.head.sha || github.sha }}
+ path: ${{ runner.temp }}/android-diagnostic-apk/
+ if-no-files-found: error
+ retention-days: 7
+ compression-level: 0
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index a9dbb36c04..645d24fbd7 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -6,11 +6,14 @@ on:
- sprint
- dev
- main
+ - release/2.6.4
pull_request:
branches:
- sprint
+ - codex/r3-release-baseline-to-sprint
- dev
- main
+ - release/2.6.4
permissions:
actions: read
diff --git a/.github/workflows/keeper-protected-release-plan.yml b/.github/workflows/keeper-protected-release-plan.yml
new file mode 100644
index 0000000000..e14b026625
--- /dev/null
+++ b/.github/workflows/keeper-protected-release-plan.yml
@@ -0,0 +1,100 @@
+name: Protected release preparation (no signing or upload)
+
+on:
+ workflow_dispatch:
+ inputs:
+ source_sha:
+ description: Full reviewed immutable candidate commit
+ required: true
+ release_ref:
+ description: Protected release/version branch at that exact commit
+ required: true
+ operation:
+ description: Operation to prepare; this workflow cannot execute it
+ type: choice
+ options: [ios-signed-build, android-signed-build, testflight-upload, play-internal-upload]
+ required: true
+ version:
+ description: Exact marketing version
+ required: true
+ build:
+ description: Exact platform build counter
+ required: true
+ artifact_sha256:
+ description: Artifact digest for upload preparation; pending for signed-build preparation
+ required: true
+ default: pending
+ approval_comment_id:
+ description: Existing owner approval comment ID with exact scope and expiry
+ required: true
+
+permissions:
+ contents: read
+ actions: read
+ checks: read
+ statuses: read
+ issues: read
+
+concurrency:
+ group: keeper-protected-release-preparation
+ cancel-in-progress: false
+
+jobs:
+ authorize:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ outputs:
+ environment: ${{ steps.plan.outputs.environment }}
+ steps:
+ - name: Checkout installed trusted driver
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.sha }}
+ path: driver
+ persist-credentials: false
+ - name: Use the reviewed Node runtime
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
+ with:
+ node-version: '22.23.3'
+ - name: Validate request before candidate checkout
+ env:
+ KEEPER_SOURCE_SHA: ${{ inputs.source_sha }}
+ KEEPER_RELEASE_REF: ${{ inputs.release_ref }}
+ KEEPER_OPERATION: ${{ inputs.operation }}
+ KEEPER_VERSION: ${{ inputs.version }}
+ KEEPER_BUILD: ${{ inputs.build }}
+ KEEPER_ARTIFACT_SHA256: ${{ inputs.artifact_sha256 }}
+ KEEPER_APPROVAL_COMMENT_ID: ${{ inputs.approval_comment_id }}
+ run: |
+ node -e "require('./driver/scripts/protected-release-plan.cjs').requestFromEnvironment(process.env)" 2>/dev/null || { echo 'Invalid preparation request'; exit 1; }
+ - name: Read candidate files without executing candidate scripts
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ inputs.source_sha }}
+ path: candidate
+ persist-credentials: false
+ - name: Check exact source, owner receipt and protected setup
+ id: plan
+ env:
+ GH_TOKEN: ${{ github.token }}
+ KEEPER_CANDIDATE_PATH: candidate
+ KEEPER_SOURCE_SHA: ${{ inputs.source_sha }}
+ KEEPER_RELEASE_REF: ${{ inputs.release_ref }}
+ KEEPER_OPERATION: ${{ inputs.operation }}
+ KEEPER_VERSION: ${{ inputs.version }}
+ KEEPER_BUILD: ${{ inputs.build }}
+ KEEPER_ARTIFACT_SHA256: ${{ inputs.artifact_sha256 }}
+ KEEPER_APPROVAL_COMMENT_ID: ${{ inputs.approval_comment_id }}
+ run: node driver/scripts/protected-release-plan.cjs
+
+ protected-plan:
+ needs: authorize
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ environment: ${{ needs.authorize.outputs.environment }}
+ permissions: {}
+ steps:
+ - name: Record preparation boundary
+ run: |
+ echo 'Protected authorization plan prepared. Signing and upload workers are NOT IMPLEMENTED.'
+ echo 'Artifact bytes/signatures remain unverified. No release action is permitted or executed here.'
diff --git a/.github/workflows/keeper-protected-release-workers.yml b/.github/workflows/keeper-protected-release-workers.yml
new file mode 100644
index 0000000000..18c99ece51
--- /dev/null
+++ b/.github/workflows/keeper-protected-release-workers.yml
@@ -0,0 +1,182 @@
+name: Protected release workers (explicit approval only)
+
+on:
+ workflow_dispatch:
+ inputs:
+ request_json:
+ description: Exact reviewed non-secret request JSON; see release/cloud/README.md
+ required: true
+ type: string
+
+permissions:
+ contents: read
+ actions: read
+ checks: read
+ statuses: read
+ issues: read
+
+concurrency:
+ group: keeper-protected-release-workers
+ cancel-in-progress: false
+
+jobs:
+ plan:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ outputs:
+ source_sha: ${{ steps.request.outputs.source_sha }}
+ operation: ${{ steps.request.outputs.operation }}
+ platform: ${{ steps.request.outputs.platform }}
+ environment: ${{ steps.plan.outputs.environment }}
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.sha }}
+ path: driver
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
+ with:
+ node-version: '22.23.3'
+ - name: Reject untrusted/malformed requests before candidate checkout
+ id: request
+ env:
+ KEEPER_RELEASE_REQUEST_JSON: ${{ inputs.request_json }}
+ run: node driver/scripts/protected-release-worker.cjs request
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ steps.request.outputs.source_sha }}
+ path: candidate
+ persist-credentials: false
+ - name: Verify exact source, approval and protected environment exist
+ id: plan
+ env:
+ KEEPER_RELEASE_REQUEST_JSON: ${{ inputs.request_json }}
+ KEEPER_CANDIDATE_PATH: candidate
+ GH_TOKEN: ${{ github.token }}
+ run: node driver/scripts/protected-release-worker.cjs plan
+
+ approved-operation:
+ needs: plan
+ runs-on: ${{ needs.plan.outputs.platform == 'ios' && 'macos-15' || 'ubuntu-24.04' }}
+ timeout-minutes: 100
+ environment: ${{ needs.plan.outputs.environment }}
+ env:
+ KEEPER_RELEASE_REQUEST_JSON: ${{ inputs.request_json }}
+ KEEPER_CANDIDATE_PATH: ${{ github.workspace }}/candidate
+ KEEPER_EXPECTED_CERT_SHA256: ${{ vars.KEEPER_RELEASE_CERT_SHA256 }}
+ KEEPER_EXPECTED_CONFIG_SHA256: ${{ vars.KEEPER_PRODUCTION_CONFIG_SHA256 }}
+ KEEPER_IOS_TEAM_ID: ${{ vars.KEEPER_IOS_TEAM_ID }}
+ KEEPER_IOS_PROFILE_UUID: ${{ vars.KEEPER_IOS_PROFILE_UUID }}
+ FASTLANE_SKIP_UPDATE_CHECK: '1'
+ FASTLANE_OPT_OUT_USAGE: '1'
+ LANG: en_US.UTF-8
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.sha }}
+ path: driver
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
+ with:
+ node-version: '22.23.3'
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ needs.plan.outputs.source_sha }}
+ path: candidate
+ persist-credentials: false
+ - name: Revalidate AFTER protected environment approval, before credentials
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: node driver/scripts/protected-release-worker.cjs revalidate
+ - uses: ruby/setup-ruby@675dd7ba1b06c8786a1480d89c384f5620a42647 # v1.281.0
+ with:
+ ruby-version: '3.3.8'
+ - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5
+ with:
+ distribution: temurin
+ java-version: '17'
+ - name: Install frozen trusted uploader/Pod dependencies without credentials
+ working-directory: driver
+ env:
+ BUNDLE_DEPLOYMENT: 'true'
+ BUNDLE_FROZEN: 'true'
+ BUNDLE_PATH: ${{ runner.temp }}/keeper-gems
+ run: |
+ bundle install --jobs 4
+ echo "BUNDLE_GEMFILE=$GITHUB_WORKSPACE/driver/Gemfile" >> "$GITHUB_ENV"
+ echo "BUNDLE_PATH=$RUNNER_TEMP/keeper-gems" >> "$GITHUB_ENV"
+ echo "KEEPER_PACKAGE_OVERLAY_PATH=$RUNNER_TEMP/keeper-nodeify-overlay.json" >> "$GITHUB_ENV"
+ - name: Reject incompatible frozen iOS toolchain without credentials
+ if: needs.plan.outputs.operation == 'ios-signed-build'
+ run: python3 driver/scripts/cloud_release_worker.py ruby-lock-check candidate unused
+ - name: Install pinned bundletool without credentials
+ if: needs.plan.outputs.platform == 'android'
+ run: |
+ curl --fail --location --silent --show-error https://github.com/google/bundletool/releases/download/1.18.1/bundletool-all-1.18.1.jar --output "$RUNNER_TEMP/keeper-bundletool.jar"
+ echo "675786493983787ffa11550bdb7c0715679a44e1643f3ff980a529e9c822595c $RUNNER_TEMP/keeper-bundletool.jar" | sha256sum --check --status
+ echo "BUNDLETOOL_JAR=$RUNNER_TEMP/keeper-bundletool.jar" >> "$GITHUB_ENV"
+ - uses: android-actions/setup-android@be39fa834029ff78f1a44aa3bb0819b8fc2bd8fd # v4
+ if: needs.plan.outputs.operation == 'android-signed-build'
+ with:
+ cmdline-tools-version: '13114758'
+ packages: platform-tools
+ log-accepted-android-sdk-licenses: false
+ - name: Install reviewed Android build inputs without credentials
+ if: needs.plan.outputs.operation == 'android-signed-build'
+ run: sdkmanager 'platforms;android-36' 'build-tools;35.0.0' 'ndk;27.1.12297006' 'cmake;3.22.1'
+ - name: Prepare canonical native dependencies without credentials
+ if: endsWith(needs.plan.outputs.operation, '-signed-build')
+ working-directory: candidate
+ run: |
+ python3 -c "import shutil; assert shutil.disk_usage('.').free >= 16 * 1024**3, 'Insufficient native build disk reserve'"
+ npm install --global yarn@1.22.22 --ignore-scripts
+ yarn install --frozen-lockfile --ignore-scripts --non-interactive
+ node_modules/.bin/patch-package --error-on-fail
+ node .github/native/nodeify.cjs
+ git diff --exit-code HEAD -- yarn.lock ios/Podfile.lock
+ python3 ../driver/scripts/cloud_release_worker.py overlay . "$KEEPER_PACKAGE_OVERLAY_PATH"
+ - name: Prepare frozen iOS dependencies without credentials
+ if: needs.plan.outputs.operation == 'ios-signed-build'
+ working-directory: candidate/ios
+ env:
+ DEVELOPER_DIR: /Applications/Xcode_16.4.app/Contents/Developer
+ run: |
+ test -d "$DEVELOPER_DIR"
+ bundle exec pod install --deployment
+ git diff --exit-code HEAD -- Podfile.lock
+ echo "DEVELOPER_DIR=$DEVELOPER_DIR" >> "$GITHUB_ENV"
+ - name: Refresh authorization immediately before loading operation credentials
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: node driver/scripts/protected-release-worker.cjs revalidate
+ - name: Execute only the approved signed build, with no upload credentials
+ if: endsWith(needs.plan.outputs.operation, '-signed-build')
+ id: sign
+ env:
+ GH_TOKEN: ${{ github.token }}
+ KEEPER_PRODUCTION_CONFIG_BASE64: ${{ secrets.KEEPER_PRODUCTION_CONFIG_BASE64 }}
+ KEEPER_IOS_P12_BASE64: ${{ needs.plan.outputs.platform == 'ios' && secrets.KEEPER_IOS_P12_BASE64 || '' }}
+ KEEPER_IOS_P12_PASSWORD: ${{ needs.plan.outputs.platform == 'ios' && secrets.KEEPER_IOS_P12_PASSWORD || '' }}
+ KEEPER_IOS_PROFILE_BASE64: ${{ needs.plan.outputs.platform == 'ios' && secrets.KEEPER_IOS_PROFILE_BASE64 || '' }}
+ KEEPER_ANDROID_KEYSTORE_BASE64: ${{ needs.plan.outputs.platform == 'android' && secrets.KEEPER_ANDROID_KEYSTORE_BASE64 || '' }}
+ STORE_PASSWORD: ${{ needs.plan.outputs.platform == 'android' && secrets.STORE_PASSWORD || '' }}
+ KEY_PASSWORD: ${{ needs.plan.outputs.platform == 'android' && secrets.KEY_PASSWORD || '' }}
+ KEY_ALIAS: ${{ needs.plan.outputs.platform == 'android' && secrets.KEY_ALIAS || '' }}
+ run: node driver/scripts/protected-release-worker.cjs execute
+ - name: Execute only the approved immutable upload, with no signing credentials
+ if: endsWith(needs.plan.outputs.operation, '-upload')
+ id: upload
+ env:
+ GH_TOKEN: ${{ github.token }}
+ KEEPER_ASC_KEY_ID: ${{ needs.plan.outputs.platform == 'ios' && secrets.KEEPER_ASC_KEY_ID || '' }}
+ KEEPER_ASC_ISSUER_ID: ${{ needs.plan.outputs.platform == 'ios' && secrets.KEEPER_ASC_ISSUER_ID || '' }}
+ KEEPER_ASC_KEY_BASE64: ${{ needs.plan.outputs.platform == 'ios' && secrets.KEEPER_ASC_KEY_BASE64 || '' }}
+ KEEPER_PLAY_SERVICE_ACCOUNT: ${{ needs.plan.outputs.platform == 'android' && secrets.KEEPER_PLAY_SERVICE_ACCOUNT || '' }}
+ run: node driver/scripts/protected-release-worker.cjs execute
+ - name: Retain only the explicitly approved signed artifact or upload receipt
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ with:
+ name: keeper-approved-release-${{ github.run_id }}-${{ github.run_attempt }}
+ path: ${{ steps.sign.outputs.artifact_dir || steps.upload.outputs.artifact_dir }}
+ if-no-files-found: error
+ retention-days: 14
diff --git a/.github/workflows/keeper-release-preparation-contracts.yml b/.github/workflows/keeper-release-preparation-contracts.yml
new file mode 100644
index 0000000000..f0d8425a0f
--- /dev/null
+++ b/.github/workflows/keeper-release-preparation-contracts.yml
@@ -0,0 +1,48 @@
+name: Protected release preparation contracts
+
+on:
+ pull_request:
+ paths:
+ - '.github/workflows/keeper-protected-release-plan.yml'
+ - '.github/workflows/keeper-release-preparation-contracts.yml'
+ - '.github/workflows/keeper-protected-release-workers.yml'
+ - 'scripts/protected-release-plan*'
+ - 'scripts/protected-release-worker*'
+ - 'scripts/cloud_release_inventory.py'
+ - 'scripts/test_cloud_release_inventory.py'
+ - 'scripts/cloud_release_worker.py'
+ - 'scripts/test_cloud_release_worker.py'
+ - 'scripts/release-version.cjs'
+ - 'scripts/test_cloud_upload_adapters.rb'
+ - 'release/cloud/**'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: keeper-release-preparation-contracts-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ contracts:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
+ with:
+ node-version: '22.23.3'
+ - uses: ruby/setup-ruby@675dd7ba1b06c8786a1480d89c384f5620a42647 # v1.281.0
+ with:
+ ruby-version: '3.3.8'
+ - name: Offline gate and inventory contracts
+ run: |
+ node --test scripts/protected-release-plan.test.cjs scripts/protected-release-worker.test.cjs scripts/release-version.test.cjs scripts/verify-channel-config.test.cjs
+ python3 -B -m unittest discover -s scripts -p 'test_cloud_release_inventory.py'
+ python3 -B -m unittest discover -s scripts -p 'test_release_artifact.py'
+ python3 -B -m unittest discover -s scripts -p 'test_cloud_release_worker.py'
+ ruby scripts/test_cloud_upload_adapters.rb
diff --git a/.github/workflows/keeper-ruby-lock-contracts.yml b/.github/workflows/keeper-ruby-lock-contracts.yml
new file mode 100644
index 0000000000..24f7346620
--- /dev/null
+++ b/.github/workflows/keeper-ruby-lock-contracts.yml
@@ -0,0 +1,52 @@
+name: Frozen cloud Ruby toolchain
+
+on:
+ pull_request:
+ paths:
+ - 'Gemfile'
+ - 'Gemfile.lock'
+ - 'ios/Podfile.lock'
+ - 'package.json'
+ - 'yarn.lock'
+ - 'scripts/check_cloud_release_inputs.py'
+ - 'scripts/cloud_release_worker.py'
+ - 'scripts/test_cloud_release_worker.py'
+ - '.github/workflows/keeper-ruby-lock-contracts.yml'
+ - 'release/cloud/Fastfile'
+ - 'scripts/test_cloud_upload_adapters.rb'
+ - 'scripts/test_cloud_upload_fastlane.rb'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: keeper-ruby-lock-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ frozen-runtime:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ persist-credentials: false
+ - uses: ruby/setup-ruby@675dd7ba1b06c8786a1480d89c384f5620a42647 # v1.281.0
+ with:
+ ruby-version: '3.3.8'
+ - name: Install/load only the frozen toolchain; no native build or provider access
+ env:
+ BUNDLE_PATH: ${{ runner.temp }}/keeper-ruby-gems
+ BUNDLE_FROZEN: 'true'
+ run: |
+ python3 -B scripts/check_cloud_release_inputs.py --root .
+ python3 -B -m unittest discover -s scripts -p 'test_cloud_release_worker.py'
+ bundle install --jobs 4 --retry 1
+ bundle check
+ bundle exec ruby -e 'require "cocoapods"; require "xcodeproj"; require "rexml/document"; abort unless Pod::VERSION == "1.16.2" && Xcodeproj::VERSION == "1.27.0"; puts "Frozen CocoaPods/Xcodeproj load PASS"'
+ bundle exec ruby -rxcodeproj -e 'p = Xcodeproj::Project.open("ios/hexa_keeper.xcodeproj"); abort unless p.targets.any? { |t| t.name == "hexa_keeper" }; puts "Existing Xcode project parse PASS"'
+ ruby scripts/test_fastlane_build_only.rb
+ bundle exec ruby scripts/test_cloud_upload_fastlane.rb
+ git diff --exit-code HEAD -- Gemfile Gemfile.lock package.json yarn.lock ios/Podfile.lock
diff --git a/.github/workflows/public-backend.yml b/.github/workflows/public-backend.yml
new file mode 100644
index 0000000000..9212bdce78
--- /dev/null
+++ b/.github/workflows/public-backend.yml
@@ -0,0 +1,59 @@
+name: Public backend setup
+
+on:
+ push:
+ branches: [sprint, main]
+ paths:
+ - 'dev/local-backend/**'
+ - '.github/workflows/public-backend.yml'
+ pull_request:
+ branches: [sprint, main]
+ paths:
+ - 'dev/local-backend/**'
+ - '.github/workflows/public-backend.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: public-backend-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ signing:
+ name: Public SigningServer adapter
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: '22'
+ - run: ./dev/local-backend/dev prepare-signing
+ - run: npm ci --ignore-scripts
+ working-directory: dev/local-backend/.sources/signing
+ - run: npm run compile
+ working-directory: dev/local-backend/.sources/signing
+ - run: npm test
+ working-directory: dev/local-backend/.sources/signing
+
+ backend:
+ name: Local backend and bootstrap
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
+ with:
+ python-version: '3.9'
+ - run: python3 -B -m unittest discover -s dev/local-backend -p 'test_*.py'
+ - run: ./dev/local-backend/dev up
+ - run: ./dev/local-backend/verify-local.sh --persistence --boundaries
+ - name: Stop containers and retain volumes
+ if: always()
+ run: ./dev/local-backend/dev stop
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 5d6104f0ae..cf7f29ae26 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -6,11 +6,16 @@ on:
- sprint
- dev
- main
+ - release/2.6.3
+ - release/2.6.4
pull_request:
branches:
- sprint
+ - codex/r3-release-baseline-to-sprint
- dev
- main
+ - release/2.6.3
+ - release/2.6.4
permissions:
contents: read
@@ -22,15 +27,27 @@ jobs:
steps:
- name: Checkout code
- uses: actions/checkout@v7
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
- name: Set up Node.js
- uses: actions/setup-node@v7
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
- node-version: '22'
+ node-version: '22.23.3'
+ # Root prepare invokes CocoaPods and writes a Mac SDK path; setup.sh can
+ # mask the pod failure. Keep JavaScript CI installation explicit on Linux.
- name: Install dependencies
- run: yarn install --ignore-scripts
+ run: |
+ npm install --global yarn@1.22.22 --ignore-scripts
+ yarn install --frozen-lockfile --ignore-scripts --non-interactive
+
+ - name: Apply repository dependency patches
+ run: node_modules/.bin/patch-package --error-on-fail
+
+ - name: Verify dependency inputs remain unchanged
+ run: git diff --exit-code HEAD -- package.json yarn.lock ios/Podfile.lock
- name: Run lint
run: npm run lint
@@ -42,15 +59,123 @@ jobs:
steps:
- name: Checkout code
- uses: actions/checkout@v7
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
- name: Set up Node.js
- uses: actions/setup-node@v7
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
- node-version: '22'
+ node-version: '22.23.3'
+ # Match the explicit JavaScript setup used by the lint job.
- name: Install dependencies
- run: yarn install
+ run: |
+ npm install --global yarn@1.22.22 --ignore-scripts
+ yarn install --frozen-lockfile --ignore-scripts --non-interactive
+
+ - name: Apply repository dependency patches
+ run: node_modules/.bin/patch-package --error-on-fail
+
+ - name: Verify dependency inputs remain unchanged
+ run: git diff --exit-code HEAD -- package.json yarn.lock ios/Podfile.lock
+
+ - name: Set up Ruby for build-only release lane regressions
+ uses: ruby/setup-ruby@v1
+ with:
+ ruby-version: '3.3.8'
+
+ - name: Check USDT pause and retired build inputs
+ run: |
+ node --test tests/services/usdtPause.test.cjs tests/recovery/usdtBackup.test.cjs \
+ scripts/verify-channel-config.test.cjs ios/scripts/verify-retired-env.test.cjs
- name: Run tests
run: npm run test
+
+ # Frozen installation intentionally skips lifecycle scripts. The released
+ # recovery suite includes genuine encrypted Realm transaction tests.
+ - name: Install the Realm N-API binding for recovery tests
+ working-directory: node_modules/realm
+ run: ../.bin/prebuild-install --runtime napi --target 6
+
+ - 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
+
+ - name: Test Android 16 KB static inspection
+ run: python3 -B -m unittest scripts/test_check_android_16kb.py
+
+ - name: Test Android reproducibility tools
+ run: python3 -B -m unittest scripts/test_compare_android_apks.py reproducibility/test_verify_android_inputs.py
+
+ automatic-backup-genuine:
+ name: Automatic backup native Realm and Relay
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+ env:
+ KEEPER_RELAY_FIXTURE_MODULE: ${{ github.workspace }}/.ci-relay/tests/support/automaticBackupHttpFixture.cjs
+ BACKUP_TEST_MONGO_URL: mongodb://127.0.0.1:27058
+ REALM_DISABLE_ANALYTICS: '1'
+
+ steps:
+ - name: Checkout Keeper source
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
+
+ - name: Checkout pinned paired Relay fixture
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ repository: KeeperCommunity/Relay
+ ref: 838049e537e07eb646a2a0393eb969fba43d0739
+ path: .ci-relay
+ persist-credentials: false
+
+ - name: Set up Node 22
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: '22'
+
+ - name: Install Keeper dependencies without native app setup
+ run: |
+ yarn install --frozen-lockfile --ignore-scripts
+ yarn patch-package
+
+ - name: Install the real Realm N-API binding
+ working-directory: node_modules/realm
+ run: ../.bin/prebuild-install --runtime napi --target 6
+
+ - name: Install paired Relay dependencies
+ working-directory: .ci-relay
+ run: yarn install --frozen-lockfile --non-interactive --ignore-scripts
+
+ - name: Start disposable loopback Mongo replica set
+ shell: bash
+ run: |
+ set -euo pipefail
+ docker run --detach --name keeper-backup-mongo \
+ --publish 127.0.0.1:27058:27058 \
+ mongo:7.0@sha256:9854f7139445d766a9523571d6f047530c45547460ffcf8259eb2bf4264632ca \
+ mongod --replSet keeperQA --bind_ip_all --port 27058
+ for attempt in {1..30}; do
+ if docker exec keeper-backup-mongo mongosh --port 27058 --quiet --eval \
+ 'try { rs.status(); } catch (e) { if (e.code !== 94) throw e; rs.initiate({_id: "keeperQA", members: [{_id: 0, host: "127.0.0.1:27058"}]}); } quit(db.hello().isWritablePrimary ? 0 : 1)'; then
+ exit 0
+ fi
+ sleep 2
+ done
+ docker logs keeper-backup-mongo
+ exit 1
+
+ - name: Run genuine automatic backup source matrix
+ run: npm run test:automatic-backup-genuine
+
+ - name: Remove disposable Mongo container
+ if: always()
+ run: docker rm --force keeper-backup-mongo || true
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000000..d7cec89098
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,128 @@
+# Contributing to Bitcoin Keeper
+
+Contributions are welcome through forks and pull requests. Keeper
+maintainers are responsible for code and security review, assessing privacy risks,
+deciding whether to accept changes, and controlling merges and public releases.
+Passing automated checks or submitting a working build does not constitute approval.
+
+## Set up a local workspace
+
+Fork this repository on GitHub and clone your fork for contributions. You do not
+need write access to the Keeper repository or production credentials. Follow the
+[local development guide](dev/local-backend/README.md) for tool versions, Docker
+backend setup, Android Studio/Xcode builds and troubleshooting. Docker runs the
+backend; native SDKs and the mobile app run on your host.
+
+The [SigningServer source](https://github.com/KeeperCommunity/SigningServer) is
+public and can be cloned, installed, built, tested and contributed to on its own.
+The full Docker app/backend setup uses the public
+[Relay](https://github.com/KeeperCommunity/Relay) and SigningServer sources;
+it requires no repository invitation. Optional private development resources
+follow a separate [access process](dev/local-backend/ACCESS.md). Access approval
+is separate from acceptance of contributed code.
+
+The guide's [capability table](dev/local-backend/README.md#what-works-locally) lists
+supported local flows and unavailable integrations. The
+[verification record](dev/local-backend/VERIFICATION.md) distinguishes tested
+behavior from failures and untested platforms. Start with disposable testnet
+wallets. Store accounts, release signing keys and production backend access are
+not prerequisites for contributing.
+
+## Develop a focused change
+
+1. Find an existing issue or describe the problem in a new issue. For a suspected
+ vulnerability, use the private process in [SECURITY.md](SECURITY.md) instead.
+2. Create a branch in your fork. Use the base branch associated with the issue;
+ if none is specified, use the repository's default development branch,
+ `sprint`. Do not assume a release tag includes every unreleased feature.
+3. Capture the change's scope and acceptance criteria using the repository's
+ OpenSpec workflow. The CLI is included in the locked development dependencies:
+
+ ```sh
+ yarn openspec new change your-change-name
+ yarn openspec status --change your-change-name
+ yarn openspec instructions proposal --change your-change-name
+ ```
+
+ Follow the artifact instructions for proposal, specs, design and tasks. Read
+ [OpenSpec configuration](openspec/config.yaml); for UI changes, also read
+ [DESIGN.md](DESIGN.md). The repository's
+ [change-engineer workflow](.github/agents/change-engineer.agent.md) describes
+ planning, implementation and archiving. Respect any explicit repository-owner
+ restrictions on committing, pushing or publishing when using coding agents.
+4. Implement the agreed scope, reuse existing components and keep unrelated
+ formatting, dependency upgrades, feature reconciliation and version bumps out
+ of the change. Maintainers coordinate version numbers and the
+ [Android](android/fastlane/README.md) and [iOS](ios/fastlane/README.md) release
+ workflows separately from local development.
+
+`sprint` is the shared integration branch. Maintainers may use a temporary
+release branch while a specific app version is stabilized. Carry fixes made on
+that branch back into `sprint` so the shared development line stays current;
+then follow the reviewed `dev` to `main` release promotion used by the project.
+
+For backend development, bootstrap creates ignored checkouts under
+`dev/local-backend/.sources/`. Save backend work in a branch/patch and submit it to
+the appropriate backend repository; an app PR does not include those ignored
+edits. Changes to packaged adapters must update the corresponding SHA-256 entries
+in `sources.lock.json` and be verified from freshly prepared sources. Do not
+package a generated checkout, database or signing volume in a PR.
+
+## Test and report the result
+
+Run checks relevant to the changed behavior. These commands run from the app root:
+
+| Change | Checks |
+| --- | --- |
+| App logic | `yarn test --runInBand` (or the relevant Jest test paths) and `yarn lint` |
+| User flow or native code | Build the affected development app and exercise the acceptance scenarios; use/update relevant Maestro flows under `flows/` |
+| Local backend/bootstrap | `python3 -B -m unittest discover -s dev/local-backend -p 'test_*.py'` and `./dev/local-backend/dev verify` |
+| Persistence or isolation | `./dev/local-backend/verify-local.sh --persistence --boundaries` on a disposable, otherwise idle Compose project |
+| OpenSpec | `yarn openspec validate your-change-name --strict` |
+
+Shared mobile changes should be checked on both Android and iOS. If a platform,
+hardware device or integration is unavailable, say so; maintainers decide what
+additional testing is required before acceptance. A local backend smoke test does
+not validate recovery, transaction signing or every mobile feature.
+
+Report the commands, commit, platform/device, actual results and relevant redacted
+evidence. Keep **passed**, **failed/blocked** and **not run** separate. Describe
+existing failures rather than hiding them or reporting an unexecuted check as a
+pass. Screenshots can support manual verification but do not turn a failed
+automated assertion into a passing automated test.
+
+## Submit and review
+
+Open a pull request from your fork and complete the supplied template. Link the
+issue and OpenSpec artifacts, explain the behavior change and provide the test
+results. Review the diff before submission: exclude local environment files,
+generated dependencies, databases, keys, wallet backups and signing credentials.
+Use [SECURITY.md](SECURITY.md) for private vulnerability details.
+
+Keeper maintainers review correctness, product fit, security/privacy, dependencies
+and test evidence. They may request revisions or additional tests, and decide
+whether a change is accepted. Only authorized maintainers merge and release
+official builds. Contributors do not need release permissions to participate.
+
+Copilot code review is requested automatically for pull requests targeting
+`sprint`. Read its actual comments and check each claim against the changed code
+and relevant tests. Fix valid findings or explain why a comment does not apply
+before requesting final human review. One developer approval remains the code
+review gate. GitHub requests Ben, Utkarsh, and Parsh when a PR is ready for review;
+any one can provide that approval. For changes to product behavior,
+UX, or copy, the product owner
+records separate product signoff in the PR discussion. A PR author's product
+signoff does not count as GitHub's required developer approval.
+
+Some existing CI checks use maintainer-managed services or secrets. If a check is
+unavailable on a fork PR, report it in the PR so maintainers can arrange review;
+do not request production secrets or treat an unavailable check as passing.
+This document defines review responsibilities; it does not claim that GitHub
+branch protection or approval rules have been configured or verified.
+
+GitHub runs app tests and separate public backend/bootstrap checks. The existing Electrum/wallet integration
+tests use public testnet nodes and fee services; an internet connection is needed.
+Coverage, where generated, measures the configured Electrum/wallet source
+directories, not every app screen. SonarCloud analysis on the development branch
+is deferred; passing tests are not a security analysis pass. See [CI notes](dev/local-backend/CI.md)
+for the branch-specific checks, deferred analysis work and evidence limits.
diff --git a/Gemfile b/Gemfile
index 18850d8fac..e9acfb67c1 100644
--- a/Gemfile
+++ b/Gemfile
@@ -2,10 +2,10 @@ source 'https://rubygems.org'
# You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
ruby '>= 2.6.10'
# Exclude problematic versions of cocoapods and activesupport that causes build failures.
-gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1'
+gem 'cocoapods', '1.16.2'
gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0'
gem "fastlane", "~> 2.225.0"
-gem 'xcodeproj', '< 1.26.0'
+gem 'xcodeproj', '1.27.0'
gem 'concurrent-ruby', '< 1.3.4'
diff --git a/Gemfile.lock b/Gemfile.lock
index 1dabd56760..4437d10ee3 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -42,10 +42,10 @@ GEM
base64 (0.2.0)
bigdecimal (3.1.6)
claide (1.1.0)
- cocoapods (1.15.2)
+ cocoapods (1.16.2)
addressable (~> 2.8)
claide (>= 1.0.2, < 2.0)
- cocoapods-core (= 1.15.2)
+ cocoapods-core (= 1.16.2)
cocoapods-deintegrate (>= 1.0.3, < 2.0)
cocoapods-downloader (>= 2.1, < 3.0)
cocoapods-plugins (>= 1.0.0, < 2.0)
@@ -59,8 +59,8 @@ GEM
molinillo (~> 0.8.0)
nap (~> 1.0)
ruby-macho (>= 2.3.0, < 3.0)
- xcodeproj (>= 1.23.0, < 2.0)
- cocoapods-core (1.15.2)
+ xcodeproj (>= 1.27.0, < 2.0)
+ cocoapods-core (1.16.2)
activesupport (>= 5.0, < 8)
addressable (~> 2.8)
algoliasearch (~> 1.0)
@@ -226,7 +226,7 @@ GEM
multi_json (1.15.0)
multipart-post (2.4.1)
mutex_m (0.2.0)
- nanaimo (0.3.0)
+ nanaimo (0.4.0)
nap (1.1.0)
naturally (2.2.1)
netrc (0.11.0)
@@ -241,7 +241,7 @@ GEM
trailblazer-option (>= 0.1.1, < 0.2.0)
uber (< 0.2.0)
retriable (3.1.2)
- rexml (3.2.6)
+ rexml (3.4.4)
rouge (2.0.7)
ruby-macho (2.5.1)
ruby2_keywords (0.0.5)
@@ -271,13 +271,13 @@ GEM
uber (0.1.0)
unicode-display_width (2.6.0)
word_wrap (1.0.0)
- xcodeproj (1.24.0)
+ xcodeproj (1.27.0)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
- nanaimo (~> 0.3.0)
- rexml (~> 3.2.4)
+ nanaimo (~> 0.4.0)
+ rexml (>= 3.3.6, < 4.0)
xcpretty (0.3.0)
rouge (~> 2.0.7)
xcpretty-travis-formatter (1.0.1)
@@ -288,11 +288,14 @@ PLATFORMS
ruby
DEPENDENCIES
- cocoapods (>= 1.11.3)
+ activesupport (>= 6.1.7.5, != 7.1.0)
+ cocoapods (= 1.16.2)
+ concurrent-ruby (< 1.3.4)
fastlane (~> 2.225.0)
+ xcodeproj (= 1.27.0)
RUBY VERSION
ruby 3.3.0p0
BUNDLED WITH
- 2.5.6
+ 2.5.22
diff --git a/Readme.md b/Readme.md
index 3f1f9d298a..0db9aef789 100644
--- a/Readme.md
+++ b/Readme.md
@@ -55,11 +55,23 @@ Refer to platform-specific documentation for detailed setup requirements.
cd bitcoin-keeper
```
3. Install the project dependencies using Yarn:
- The prepare scripts will automatically install pods and nodify crypto-related packages for react-native
+ The prepare script configures the crypto-related React Native packages.
+ CocoaPods is an explicit iOS setup step; follow [CONTRIBUTING.md](CONTRIBUTING.md)
+ after dependency installation.
```shell
yarn install
```
+## Contributing and local backends
+
+See [CONTRIBUTING.md](CONTRIBUTING.md) for the contribution process and
+[the local development guide](dev/local-backend/README.md) for a reproducible
+backend setup using public [Relay](https://github.com/KeeperCommunity/Relay)
+and [SigningServer](https://github.com/KeeperCommunity/SigningServer) sources.
+The local stack uses disposable testnet fixtures and needs no production
+credentials. Keep native app builds on your host; the backend runs in Docker.
+Report suspected vulnerabilities through [private reporting](SECURITY.md).
+
## Build and Run
### Varients
diff --git a/android/app/build.gradle b/android/app/build.gradle
index e8ead00b0a..8c6fc44d1c 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -2,6 +2,13 @@ apply plugin: "com.android.application"
apply plugin: "com.facebook.react"
apply plugin: 'com.google.gms.google-services'
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
+// react-native-config embeds every selected env key, even when JavaScript does not use it.
+// Check the resolved env map so direct Gradle builds cannot package retired credentials.
+def retiredCredentialKeys = ['GASFREE_API_KEY', 'GASFREE_API_SECRET',
+ 'LETS_EXCHANGE_API_KEY'].collectMany { [it, "RN_${it}"] }
+if (retiredCredentialKeys.any { project.ext.env.containsKey(it) }) {
+ throw new GradleException('Retired API credentials must not be included in an Android build')
+}
apply plugin: 'kotlin-android'
/**
@@ -98,8 +105,8 @@ android {
applicationId "io.hexawallet.keeper"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
- versionCode 621
- versionName "2.3.15"
+ versionCode 627
+ versionName "2.6.4"
missingDimensionStrategy 'react-native-camera', 'general'
missingDimensionStrategy 'store', 'play'
multiDexEnabled true
@@ -115,12 +122,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 +140,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
@@ -161,6 +170,15 @@ android {
}
dependencies {
+ // Portal's transitive JNA 5.14.0 has an 8 KB RELRO boundary even though
+ // its LOAD segments are 64 KB aligned. Keep classes and JNI on one AAR.
+ // 5.18.1 retains the 5.17 native fix and fixes the subsequent UniFFI
+ // Structure deadlock/concurrency regressions (JNA #1681 and #1686).
+ implementation('net.java.dev.jna:jna:5.18.1@aar') {
+ version { strictly '5.18.1' }
+ because 'Portal requires 16 KB JNA natives and the UniFFI Structure fixes'
+ }
+
// The version of react-native is set by the React Native Gradle Plugin
implementation project(':react-native-iap')
implementation 'com.google.mlkit:barcode-scanning:17.3.0'
diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml
index 594604506c..fdb0c092e5 100644
--- a/android/app/src/debug/AndroidManifest.xml
+++ b/android/app/src/debug/AndroidManifest.xml
@@ -52,15 +52,6 @@
-
-
-
-
-
-
-
-
-
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index de838aa93e..1b21a28af9 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -60,9 +60,19 @@
-
+
+
+
+
+
+
+
+
+
+
+
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/android/fastlane/Fastfile b/android/fastlane/Fastfile
index 6765414875..6bfaee660d 100644
--- a/android/fastlane/Fastfile
+++ b/android/fastlane/Fastfile
@@ -15,6 +15,54 @@
default_platform(:android)
+def build_verified_production_android_artifacts!
+ 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"]
+ key_alias = ENV["KEY_ALIAS"]
+ 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 must return the artifact path for this invocation.
+ Actions.lane_context.delete(SharedValues::GRADLE_AAB_OUTPUT_PATH)
+ gradle(
+ task: 'bundle',
+ build_type: 'productionRelease',
+ print_command: false,
+ properties: {
+ "android.injected.signing.store.file" => releaseFilePath,
+ "android.injected.signing.store.password" => store_password,
+ "android.injected.signing.key.alias" => key_alias,
+ "android.injected.signing.key.password" => key_password,
+ }
+ )
+ 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.strip.empty?
+ Actions.lane_context.delete(SharedValues::GRADLE_APK_OUTPUT_PATH)
+ gradle(
+ task: 'assemble',
+ build_type: 'productionRelease',
+ print_command: false,
+ properties: {
+ "android.injected.signing.store.file" => releaseFilePath,
+ "android.injected.signing.store.password" => store_password,
+ "android.injected.signing.key.alias" => key_alias,
+ "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.strip.empty?
+ verifier = File.expand_path("../../scripts/verify-release-artifact.py", __dir__)
+ sh("python3", verifier, aab_path)
+ sh("python3", verifier, apk_path)
+ { aab: aab_path, apk: apk_path }
+end
+
platform :android do
desc "Push a new dev build to Slack"
lane :dev do
@@ -47,45 +95,17 @@ platform :android do
)
end
- desc "Push a new live build to Slack and internal track on Play Store"
+ desc "Build and verify production AAB and APK without uploading or notifying Slack"
+ lane :build_only do
+ build_verified_production_android_artifacts!
+ end
+
+ 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}'"
- )
- 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()
- gradle(task: 'clean')
- gradle(
- task: 'bundle',
- build_type: 'productionRelease',
- print_command: false,
- properties: {
- "android.injected.signing.store.file" => releaseFilePath,
- "android.injected.signing.store.password" => store_password,
- "android.injected.signing.key.alias" => key_alias,
- "android.injected.signing.key.password" => key_password,
- }
- )
+ artifacts = build_verified_production_android_artifacts!
upload_to_play_store(
- track: 'internal'
- )
- gradle(
- task: 'assemble',
- build_type: 'productionRelease',
- print_command: false,
- properties: {
- "android.injected.signing.store.file" => releaseFilePath,
- "android.injected.signing.store.password" => store_password,
- "android.injected.signing.key.alias" => key_alias,
- "android.injected.signing.key.password" => key_password,
- }
+ track: 'internal',
+ aab: artifacts[:aab]
)
end
end
@@ -93,15 +113,21 @@ 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 lane.to_s.split.last != 'build_only' && 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 lane.to_s.split.last != 'build_only' && 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/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties
index d4081da476..a54add3199 100644
--- a/android/gradle/wrapper/gradle-wrapper.properties
+++ b/android/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
+distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
diff --git a/appcenter-pre-build.sh b/appcenter-pre-build.sh
index 6adc321a73..3705a26b9a 100644
--- a/appcenter-pre-build.sh
+++ b/appcenter-pre-build.sh
@@ -1,8 +1,19 @@
#!/usr/bin/env bash
# Creates an .env from ENV variables for use with react-native-config
+set -eu
+
+if [ -n "${RN_GASFREE_API_KEY+x}" ] || [ -n "${RN_GASFREE_API_SECRET+x}" ] || [ -n "${RN_LETS_EXCHANGE_API_KEY+x}" ]; then
+ printf "Retired API credentials must not be included in a mobile build\n" >&2
+ exit 1
+fi
+
ENV_WHITELIST=${ENV_WHITELIST:-"^RN_"}
printf "Creating an .env file with the following whitelist:\n"
printf "%s\n" $ENV_WHITELIST
set | egrep -e $ENV_WHITELIST | sed 's/^RN_//g' > .env
-printf "\n.env created with contents:\n\n"
-cat .env
\ No newline at end of file
+if grep -Eq '^(RN_)?(GASFREE_API_(KEY|SECRET)|LETS_EXCHANGE_API_KEY)=' .env; then
+ rm .env
+ printf "Retired API credentials must not be included in a mobile build\n" >&2
+ exit 1
+fi
+printf ".env created\n"
diff --git a/dev/local-backend/.env.example b/dev/local-backend/.env.example
new file mode 100644
index 0000000000..ed62df3b1f
--- /dev/null
+++ b/dev/local-backend/.env.example
@@ -0,0 +1,5 @@
+# Copy to .env only when changing the defaults. No secrets required.
+COMPOSE_PROJECT_NAME=keeper-contributor
+KEEPER_RELAY_PORT=3000
+KEEPER_CHANNEL_PORT=4002
+KEEPER_SIGNING_PORT=3003
diff --git a/dev/local-backend/.gitignore b/dev/local-backend/.gitignore
new file mode 100644
index 0000000000..53a25a248d
--- /dev/null
+++ b/dev/local-backend/.gitignore
@@ -0,0 +1,3 @@
+.sources/
+.env
+__pycache__/
diff --git a/dev/local-backend/ACCESS.md b/dev/local-backend/ACCESS.md
new file mode 100644
index 0000000000..d9012a6548
--- /dev/null
+++ b/dev/local-backend/ACCESS.md
@@ -0,0 +1,24 @@
+# Optional private development resources
+
+The public [app](https://github.com/KeeperCommunity/bitcoin-keeper),
+[Relay](https://github.com/KeeperCommunity/Relay), and
+[SigningServer](https://github.com/KeeperCommunity/SigningServer) can be cloned,
+built, tested and contributed to without a Keeper invitation. The local Docker
+setup in [README.md](README.md) uses only those public repositories and
+disposable development identities. Production credentials are never needed.
+
+Some assigned work may need separate private repositories, provider dashboards,
+or test infrastructure. Ask the Keeper maintainer coordinating that work in your
+existing private conversation. Include your GitHub username, task and the exact
+resource needed. Do not post credentials or private access requests in a public
+issue. If you do not have a maintainer contact, use the
+[community contact](../../Readme.md#community) to reach one privately.
+
+Maintainers review the work and grant only the needed permissions after checking
+that the resource is ready to share. Approval covers the development access, not
+every local command or proposed code change. Record invitation acceptance and
+setup success in the internal development backlog. A contributor must use their
+own GitHub identity; maintainers must not share personal tokens.
+
+Security reports follow [SECURITY.md](../../SECURITY.md). Code acceptance,
+merges, production access and releases remain separate maintainer decisions.
diff --git a/dev/local-backend/CI.md b/dev/local-backend/CI.md
new file mode 100644
index 0000000000..66064cccd7
--- /dev/null
+++ b/dev/local-backend/CI.md
@@ -0,0 +1,54 @@
+# Contributor checks and analysis
+
+## Public backend CI
+
+The app's local backend workflow pins the public
+[Relay](https://github.com/KeeperCommunity/Relay) and
+[SigningServer](https://github.com/KeeperCommunity/SigningServer). It requires no
+private repository token or production credential. The default branch runs
+`Public backend setup` for the packaged adapter, bootstrap and disposable API
+checks. Earlier Linux backend runs failed while fetching the private Relay;
+those historical runs do not establish the result for this public pin.
+Code acceptance and releases remain maintainer decisions.
+
+## Active checks
+
+The default branch's existing `Run Tests` workflow runs app tests. The new
+`Public backend setup` workflow runs a separate public SigningServer adapter
+fetch/install/compile/test job and full local backend bootstrap, API,
+persistence and network-boundary checks. Neither job uses hosted credentials.
+Pull requests are checked against their proposed merge with the target branch.
+The development branch's `Contributor checks` workflow additionally publishes
+app test coverage; its results are tracked with PR #7014.
+
+Where generated, Jest's LCOV measures only the
+Electrum/wallet directories listed in `jest.config.js`; this is not whole-app
+coverage. Test success is evidence about the exercised cases, not a security
+clearance. Maintainers retain security review and acceptance responsibility.
+
+## SonarCloud deferred on 26 September 2026
+
+The project owner chose to defer SonarCloud on the development branch. That job
+was removed from its active workflow; app tests and an LCOV artifact remain there. `sonar-project.properties` is
+retained for future restoration, including the report path and quality-gate wait
+setting. No analysis or quality-gate pass is claimed, and no threshold has been
+lowered. GitHub protection settings were not changed; if a required Sonar status
+blocks merging, a maintainer must reconcile that setting with this decision.
+
+Before deferral, PR #7014's original and updated scanners failed while retrieving
+the pull request, before analysis. Public project metadata lists the repository
+as `bithyve/bitcoin-keeper`, while this PR lives in
+`KeeperCommunity/bitcoin-keeper`. This suggests a stale binding; an administrator
+needs to verify the exact access/configuration problem when analysis is restored.
+
+Deferred follow-up: inspect the project's Repository binding and GitHub app
+access, confirm project/organization keys and the secret, restore a pinned scanner
+that consumes LCOV and waits for its quality gate, then review the actual result.
+Keep analyzer credentials away from fork code. See Sonar's
+[repository binding instructions](https://docs.sonarsource.com/sonarqube-cloud/managing-your-projects/administering-your-projects/changing-binding).
+
+The last existing `sprint` analysis (17 September, commit `1adf4f663`) reported a
+failed quality gate: 0% new-code coverage, reliability rating C, 5.1% duplication
+and 0% reviewed security hotspots, using a September 2024 previous-version
+baseline. These are historical findings, not this PR's analysis. Deferral does
+not resolve them or replace Keeper's review.
diff --git a/dev/local-backend/HANDOFF.md b/dev/local-backend/HANDOFF.md
new file mode 100644
index 0000000000..8d2fe447e2
--- /dev/null
+++ b/dev/local-backend/HANDOFF.md
@@ -0,0 +1,61 @@
+# Independent contributor setup check
+
+Use this full-stack checklist with the public Relay and SigningServer sources.
+SigningServer-only work can follow
+[its independent setup](README.md#signingserver-without-relay-access). A maintainer's working Mac does not establish that the guide works
+on another developer's machine. This check does not authorize code acceptance or
+an official release.
+
+## Start clean
+
+1. Use an anonymous fresh app clone at the exact commit
+ supplied by the maintainer. Record `git rev-parse HEAD`. Do not copy another
+ developer's `.env`, databases, signing volume, account credentials or key files.
+2. Follow [README.md](README.md) for the toolchain and a
+ running Docker engine. If other Keeper projects are running, choose a distinct
+ Compose project and three unused ports as documented there.
+3. Run `./dev/local-backend/dev up`. It must prepare the pinned sources, start the
+ services and pass the local API checks without production credentials.
+4. Run `./dev/local-backend/verify-local.sh --persistence --boundaries` while no
+ other test is using this project's services. It recreates this project's
+ containers while retaining its volumes. Both persistence and rejection of
+ mainnet/hosted database settings must pass.
+5. Run `python3 -B -m unittest discover -s dev/local-backend -p 'test_*.py'`.
+6. Follow the native development build instructions for the platforms available
+ on this machine. iOS requires a Mac and Xcode. Record unavailable platforms as
+ untested, not passed.
+7. In the development app, create only a disposable local test fixture, complete
+ passcode/onboarding, reach Mobile Wallet and More Options, then relaunch and
+ unlock. Confirm that the app uses the local environment. Do not import a real
+ wallet or move real funds for this check.
+8. Stop the selected stack with `./dev/local-backend/dev stop`. Retain the volumes
+ for follow-up unless you intentionally choose to discard this test fixture.
+
+## Send the result privately to the coordinating maintainer
+
+Copy this summary into the existing private conversation. Maintainers keep it in
+the internal development backlog, not a new public administrative issue.
+
+```text
+App commit:
+Backend revisions (from dev/local-backend/sources.lock.json):
+Host OS and architecture:
+Docker/Compose, Node/Yarn, Python, Java and Xcode versions as applicable:
+Fresh clone and new project/volumes: yes/no (explain reused state)
+
+PASS:
+FAIL or BLOCKED (exact step and sanitized error):
+NOT TESTED:
+Guide corrections or undocumented steps needed:
+Native platform(s), simulator/emulator and onboarding/relaunch result:
+```
+
+Do not attach recovery words, private keys, authentication tokens, receipts,
+databases, captured emails or unreviewed full logs. Report security findings via
+[SECURITY.md](../../SECURITY.md). Ordinary reproducible user-facing defects can
+have public product issues after removing private details.
+
+Passing this checklist proves only the listed local setup and smoke checks.
+Purchases, push delivery, scheduled inheritance, hardware wallets, transaction
+signing and recovery correctness require their own acceptance evidence; see the
+[capability table](README.md#what-works-locally) and [verification record](VERIFICATION.md).
diff --git a/dev/local-backend/README.md b/dev/local-backend/README.md
new file mode 100644
index 0000000000..07d2fb2f5e
--- /dev/null
+++ b/dev/local-backend/README.md
@@ -0,0 +1,177 @@
+# Contributor development environment
+
+Run MongoDB, Keeper relay/channel and the testnet signing backend in Docker. Run Metro, Android Studio and Xcode on your host. Hosted development services have been retired; this setup needs no production backend or release credentials.
+
+For choosing a change, OpenSpec, test reporting and submitting a pull request, see
+[Contributing](../../CONTRIBUTING.md). Keeper maintainers own security review,
+acceptance, merges and official releases.
+
+## Prerequisites
+
+Both [Relay](https://github.com/KeeperCommunity/Relay) and
+[SigningServer](https://github.com/KeeperCommunity/SigningServer) are public.
+The full local Docker stack uses pinned revisions of these clean public sources
+and needs no repository invitation or production credentials. Optional private
+development resources have a separate [access process](ACCESS.md).
+
+- Git, Python 3.9+, Docker Engine with Compose v2.20+ (or a newer Compose release). On macOS use Docker Desktop or Colima; Linux can use Docker Engine. Start the engine before setup. Reserve about 3–4 GB for Docker and run native builds sequentially on a 16 GB Mac.
+- Anonymous GitHub access to both public backends. First setup downloads sources, container images and dependencies. Subsequent starts can reuse them.
+- Mobile: Node 20.19.4+ (Node 22 is a suitable supported baseline), Yarn Classic 1.22.22. Use the committed `yarn.lock`.
+- Android: Android Studio, JDK 17, SDK platform 36, build tools 35.0.0, NDK 27.1.12297006, CMake 3.22.1 and platform tools. Set `JAVA_HOME` and `ANDROID_HOME`. These versions come from this app's Gradle files.
+- iOS: macOS, Xcode with an iOS simulator runtime, Ruby 3.3.0 (`.ruby-version`) and Bundler. Use the root `Gemfile.lock` and `ios/Podfile.lock`.
+
+Earlier native validation on this Mac used Apple Silicon, Xcode 26.4, Node 25.9.0, Yarn 1.22.22, JDK 17 and Ruby 3.3.0. App tests also passed in GitHub Linux CI on Node 22. Full contributor setup on Intel Macs, Linux and Windows/WSL still needs independent verification; iOS builds require macOS. See [verification](VERIFICATION.md) for actual results and limitations.
+
+Native tool installation: [React Native 0.83 environment guide](https://reactnative.dev/docs/0.83/set-up-your-environment). Follow the repo-specific Android versions above when they differ from that guide.
+
+## First start
+
+Clone the public default branch:
+
+```sh
+git clone https://github.com/KeeperCommunity/bitcoin-keeper.git
+cd bitcoin-keeper
+```
+
+`dev up` fetches only public backend sources.
+
+From this app checkout's root:
+
+```sh
+./dev/local-backend/dev doctor
+./dev/local-backend/dev up
+./dev/local-backend/dev env
+yarn install --frozen-lockfile --non-interactive
+```
+
+`up` fetches the exact backend Git revisions, applies the local development adapters, builds containers, waits for readiness and runs real disposable API checks. `env` creates `.env.local` with restrictive permissions; it refuses to overwrite an existing different configuration. Existing `.env` and production files are not used or modified.
+
+## SigningServer without Relay access
+
+For SigningServer changes that do not need the mobile app or Relay, use the
+[public repository's instructions](https://github.com/KeeperCommunity/SigningServer#install-and-verify):
+
+```sh
+git clone https://github.com/KeeperCommunity/SigningServer.git
+cd SigningServer
+npm ci --ignore-scripts
+npm run compile
+npm test
+```
+
+Use Node 22 and report the exact tested commit. The server's unit tests use
+disposable local fixtures; they do not establish full app/backend integration or
+live signing behavior. To check this app's local adapter against its pinned
+public source, run `./dev/local-backend/dev prepare-signing` from the app clone.
+That command checks the adapter digests and applies it under ignored
+`.sources/signing/` without fetching Relay or starting Docker. Submit upstream
+SigningServer changes to its own repository. Full `dev up`, API checks and native
+app setup use the public Relay source.
+
+The JavaScript install hook only installs the repo's Node compatibility shims. Native dependencies are separate explicit steps below. It no longer runs CocoaPods on Android-only machines or rewrites `android/local.properties` with a Mac-specific path.
+
+If default ports 3000/4002/3003 are occupied, copy `dev/local-backend/.env.example` to `dev/local-backend/.env`, set distinct ports and a unique project name, then run the commands above. Port 8081 is reserved for Metro and cannot be assigned to a backend service. Use the same settings for every invocation. Multiple copies using the same Compose project name share containers and volumes; give each independent environment a unique name. `.env.local` must match those ports. Commands work from any directory except the native/Yarn commands, which assume the app root.
+
+## Android
+
+Create and boot an emulator through Android Studio. Use an ARM64 image on Apple Silicon, x86_64 on Intel/Linux. Use `adb devices` to select its serial. In one terminal at the app root:
+
+```sh
+yarn start
+```
+
+In another terminal:
+
+```sh
+./dev/local-backend/dev android-forward --serial YOUR_SERIAL
+ENVFILE=.env.local ./android/gradlew -p android app:assembleDevelopmentDebug -PreactNativeArchitectures=arm64-v8a --max-workers=2
+adb -s YOUR_SERIAL install -r android/app/build/outputs/apk/development/debug/app-development-debug.apk
+adb -s YOUR_SERIAL shell am start -n io.hexawallet.keeper.development/io.hexawallet.keeper.MainActivityDefault
+```
+
+Use `-PreactNativeArchitectures=x86_64` for an x86_64 emulator. `ANDROID_HOME` lets Gradle locate the SDK without a machine-specific committed `local.properties`. Android debug signing uses the disposable debug keystore already in the repository. No release signing key is needed.
+
+Keep `localhost` in `.env.local`: the app's Android cleartext policy allows it. `android-forward` connects the selected device to Metro and the configured backend ports; rerun after restarting the device. A physical Android device can use the same USB forwarding, but physical-device validation is a separate step.
+
+## iOS
+
+Select Ruby 3.3.0 with your Ruby manager, then from the app root:
+
+```sh
+bundle install
+(cd ios && BUNDLE_GEMFILE="$PWD/../Gemfile" RCT_NEW_ARCH_ENABLED=1 bundle exec pod install)
+xcrun simctl list devices available
+```
+
+Use the root Gemfile explicitly; the `ios` directory has a different Gemfile. CocoaPods may refresh checkout-path-dependent Hermes podspec checksums on initial installation; review any lockfile diff and do not treat dependency version changes as routine setup.
+
+For exact-source validation, use `pod install --deployment` and report a checksum mismatch as blocked instead of changing the lock incidentally. Before building, check for the shared `/tmp/envfile` selector: react-native-config gives it precedence over `ENVFILE`. Preserve any existing selector, coordinate with other builds, and proceed only when the effective file is this checkout's `.env.local`. Do not print configuration contents or delete another build's selector.
+
+Start `yarn start` in a separate terminal. You can inspect the workspace in Xcode (`ios/hexa_keeper.xcworkspace`, scheme `hexa_keeper_dev`). Use the command below for local builds so `ENVFILE` reaches every native build phase; simply clicking Run with the default scheme settings does not select `.env.local`:
+
+```sh
+ENVFILE=.env.local xcodebuild -workspace ios/hexa_keeper.xcworkspace -scheme hexa_keeper_dev -configuration Debug -destination 'platform=iOS Simulator,id=YOUR_SIMULATOR_UDID' -derivedDataPath ios/build/local-dev build
+xcrun simctl boot YOUR_SIMULATOR_UDID
+xcrun simctl install YOUR_SIMULATOR_UDID ios/build/local-dev/Build/Products/Debug-iphonesimulator/hexa_keeper_dev.app
+xcrun simctl launch YOUR_SIMULATOR_UDID io.hexawallet.hexakeeper.dev
+```
+
+Skip `simctl boot` if already booted. Keep simulator signing enabled so the app retains required entitlements. Store publishing/signing is separate from contributor development; see the release documentation.
+
+## Daily use and verification
+
+```sh
+./dev/local-backend/dev status
+./dev/local-backend/dev verify
+./dev/local-backend/dev logs
+./dev/local-backend/dev stop
+```
+
+`stop` removes containers but retains both named volumes. A later `up` restores the environment. To check persistence and configuration boundaries explicitly:
+
+```sh
+./dev/local-backend/verify-local.sh --persistence --boundaries
+```
+
+This recreates only the selected Compose project's containers, retains its volumes, and compares the same app record, revisioned backup and testnet signing public key. It verifies backup snapshot reads, transactional repair and rejection of stale revisions, and checks startup rejection of mainnet and hosted databases. Run when no other test is using that project. Ordinary `verify` does not restart containers. Every verify run adds a disposable app/signer fixture and synthetic encrypted backup records to the local database; no testnet coins are needed and no transaction is sent. Tokens and private keys are not printed.
+
+For native smoke testing: launch the development app, complete onboarding with a disposable wallet, unlock, open Wallets and More Options, and select testnet before testing network functionality. An API smoke pass does not prove wallet backup/recovery or a real signing transaction.
+
+## What works locally
+
+| Capability | Scope |
+| --- | --- |
+| Mongo, relay app records | Local persistence and API create/read checks |
+| Channel | Socket.IO connection handshake |
+| Server Key | V3 testnet setup, public-key derivation, valid/invalid 2FA and persistence |
+| Email | Captured inside signing volume at `/local-data/outbox.jsonl`; never delivered |
+| Push, purchases, Ask Keeper AI, faucet, price feeds | Unavailable; relay reports unsupported routes explicitly |
+| Scheduled signing / inheritance jobs | Disabled; timer-dependent flows are not covered |
+| Blockchain / Electrum | Separate mobile internet connection; not provided by this stack |
+| Legacy V2 Server Key | Not supported by this acceptance check; a V2 setup probe terminated the pinned upstream process (see verification notes) |
+
+The relay health field `signing: false` describes the relay, not the separate signing service. Use each service's health endpoint. No production service deployment is performed.
+
+## Sources, data and network boundaries
+
+`sources.lock.json` pins both public backend revisions and all local adapter SHA-256 checksums. Relay's public source includes local mode; its local Dockerfile adapter pins the Node base image. The Node, Mongo and nginx base images are pinned by digest. Backend dependency installs use frozen Yarn / npm lockfiles; OS packages in the relay build still use Debian repositories, so this is a reproducible development workflow, not a bit-for-bit reproducible image build.
+
+`adapters/signing/` contains the local-mode modifications for the pinned public SigningServer source; `adapters/relay/` pins its local build image. `.sources/` is generated and ignored. Bootstrap never overwrites an existing checkout; reruns preserve local backend edits. After editing a backend, rerun `up` to rebuild. To change pins/adapters, save your backend edits and move the generated checkout aside first. Do not deploy the development adapters to production.
+
+Only the gateway publishes host ports, all on `127.0.0.1`. Mongo, relay and signing share an internal network with no external egress; the gateway also has a host-access network. Compose waits on service health, following [Docker's startup ordering](https://docs.docker.com/compose/how-tos/startup-order/). Build-time dependency downloads still use the internet. Mobile native integrations are outside Docker; this is not a fully offline mobile mode.
+
+Mongo starts as the single-member `keeper-local` replica set required by the backup API's transactions. Its idempotent health check initializes a new local volume and waits for a writable primary. Existing local data volumes are retained; a standalone Mongo server cannot exercise transactional backup repair.
+
+Signing identities are randomly generated per signing volume and stored with restricted permissions. Use disposable test wallets. Keep the Mongo and signing volumes together: deleting signing keys invalidates their stored Server Key records. There is deliberately no automatic reset/delete command. `docker compose down --volumes` is destructive and not part of normal setup. Do not distribute databases, keys, email captures, `.env` files or native signing credentials with the source.
+
+## Troubleshooting
+
+- Docker unavailable: start Docker Desktop or Colima, then rerun `doctor`.
+- Backend source fetch failure: check the public pinned revision and network connection; no application secret is needed.
+- Stale source/adapter marker: save edits and move the relevant `.sources/relay` or `.sources/signing` directory aside. Bootstrap refuses to overwrite it.
+- Health succeeds but a feature fails: consult the capability table; cloud integrations are not restored by local startup.
+- App cannot reach local services: check `.env.local`, rebuild with `ENVFILE=.env.local`, and rerun Android port forwarding. Changing an env file requires a native rebuild.
+- Xcode reports a missing Node executable: inspect the ignored `ios/.xcode.env.local`; CocoaPods may have cached a version-specific path removed by a Node upgrade. Update its `NODE_BINARY` to your current executable and rebuild.
+- If several Metro servers are running, select the one for this checkout on each device. Android emulator defaults can bypass USB forwarding via `10.0.2.2`; set its debug server host to `localhost:8081` when using `adb reverse`.
+- iOS pod install fails under system Ruby: select the repo's Ruby version and root Bundler environment. Do not run an unrelated globally installed CocoaPods.
+- Memory pressure: build iOS and Android sequentially, limit Gradle workers, and shut down unused simulators without erasing their data.
diff --git a/dev/local-backend/VERIFICATION.md b/dev/local-backend/VERIFICATION.md
new file mode 100644
index 0000000000..a22f83ad33
--- /dev/null
+++ b/dev/local-backend/VERIFICATION.md
@@ -0,0 +1,303 @@
+# Contributor setup verification
+
+## R4 public Relay repin — 9 October 2026
+
+The current source lock pins public Relay
+`fb93c887631a6f567155a88f8e93d566f9d32a53` and public SigningServer
+`3cc7728c27328e7b0358d1f91a32d8d13feba90a`. Compared with the previous
+Relay pin, the follow-up changes signer lookup cleanup and its regression tests;
+it does not change the mobile backup request or response shape or the app's local
+Dockerfile adapter. Relay's exact-head build, disposable backup tests and source
+scans passed in [PR #3](https://github.com/KeeperCommunity/Relay/pull/3).
+
+In the existing anonymous app checkout, with an isolated HOME, disabled
+system/global Git configuration and interactive credential prompts,
+`dev prepare` fetched the new Relay commit and applied the unchanged adapter.
+It preserved the prepared public
+SigningServer checkout. All 11 bootstrap fixtures and Compose configuration
+validation passed. No local Docker build or native app run was repeated for this
+new pin. The earlier full-stack acceptance in
+[app PR #7030](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7030)
+used the previous Relay pin and is historical evidence for that revision.
+
+## Sprint contributor package — 7 October 2026
+
+That sprint contributor package pinned public Relay
+`4c54e28738815546718775dbbdb39f0342c1b646` and public SigningServer
+`3cc7728c27328e7b0358d1f91a32d8d13feba90a`, with local adapter checksums in
+`sources.lock.json`. These are newer revisions than the earlier sprint PR #7014
+and main PR #7026. The source locks include Relay snapshot/repair and revision
+guards, compatible SigningServer dependency fixes, and digest-pinned image adapters.
+
+At app commit `19e079ae4486dacf1f79bf5e527384e608872977`, the
+[public-backend CI](https://github.com/KeeperCommunity/bitcoin-keeper/actions/runs/37627727798)
+passed both the SigningServer adapter and full local backend/bootstrap jobs.
+Those checks used these backend pins and exercised local snapshot/repair,
+A → B → A revisions, stale-repair rejection and persistence. Subsequent contributor
+changes have their own PR check results. Native app builds must be assessed
+against the selected app branch and platform separately.
+
+All dated sections below are historical evidence for the exact revisions named
+in those sections. They do not verify the 9 October source lock or attribute
+earlier private-source failures to the current public backend.
+
+## Public Relay transition — 7 October 2026
+
+- Clean-history [Relay](https://github.com/KeeperCommunity/Relay) is public at
+ `3e1a01bd2fd5381d8546229922c431ce50bedad4`; the legacy credential-bearing
+ Relay repository remains private. GitHub private vulnerability reporting is
+ enabled on the public repository.
+- An anonymous Relay clone at that exact commit passed a frozen Node 22 install,
+ compilation, 104 tests across nine suites with disposable MongoDB, current
+ source and full-history secret scans, and the runtime dependency audit. A
+ separate local Compose run served ready/local health, persisted a synthetic
+ app record and returned 503 for an unavailable hosted integration. Its
+ disposable containers and volumes were removed.
+- Sprint PR #7014's public Relay pin and public SigningServer pin were fetched with
+ Git credential helpers disabled. Six bootstrap regression tests passed. The
+ isolated full stack passed health, Socket.IO, unsupported-route behavior,
+ synthetic app record create/read, and V3 testnet signer authorization and
+ valid/invalid 2FA. No production credentials or funded wallets were used.
+- The optional persistence/boundary rerun stopped during Docker network
+ recreation with an engine input/output error after the host filled its disk.
+ That rerun is **not passed**. Free space was recovered, but no further Docker
+ build is being run while concurrent mobile QA uses the machine. CI on the
+ updated app commit and an independent developer/machine remain pending.
+- No new native mobile build, physical-device check, hosted provider delivery,
+ real signing transaction, or production deployment is claimed by this
+ contributor source-pin change.
+
+## Public SigningServer follow-up — 6 October 2026
+
+- The pinned SigningServer source is now the public
+ `KeeperCommunity/SigningServer` revision
+ `b82dc4f4a8f75676b70b12545d59c7906556a92b`. Its local adapter checksum
+ check and patch application pass. With Node 22, the adapted source passes
+ `npm ci --ignore-scripts`, `npm run compile` and `npm test` (2 suites, 108 tests).
+ The new independent GitHub SigningServer adapter job passes those same steps.
+- SigningServer's previously cancelled current-source readiness job was rerun at
+ its public head: current-source and history scans both pass on the rerun.
+ Its own public test workflow also passes. Dependency review remains open;
+ successful source scans and tests are not security acceptance.
+- A separate anonymous app checkout at app commit
+ `41e482ec97ebffb0beff43ed807b1205fb26ed8e` used an empty home and package
+ cache, disabled Git credential helpers and prompts, and copied no backend
+ source or environment files. `dev prepare` stopped at private Relay as expected.
+ `dev prepare-signing` fetched the public pin and applied its adapter without
+ Relay. `dev env` created a local-only file with mode `0600`; six bootstrap
+ regression tests passed. No full Docker stack or native build was possible
+ without Relay access.
+- A separate anonymous SigningServer clone, with an initially empty package
+ cache and no Git credentials, passed `npm ci --ignore-scripts`,
+ `npm run compile` and `npm test` (2 suites, 108 tests). The local anonymous app
+ Yarn install was stopped before completion when this Mac had about 1.5 GB free;
+ no local anonymous app JavaScript install or Jest pass is claimed. On the same
+ app commit, GitHub Linux CI passed frozen Yarn install, 17 Jest suites / 183
+ tests, strict active OpenSpec validation and LCOV upload. Its full backend job
+ passed bootstrap tests but failed fetching private Relay; later API/persistence
+ checks were skipped. These CI results do not establish an independent
+ full-stack checkout or native app acceptance.
+- Relay remains private and its publication is deferred. Safe CI Relay access,
+ independent full-stack setup, remaining dependency/security review and
+ maintainer acceptance remain open. No production deployment or credential
+ change was part of this follow-up.
+
+## Earlier evidence — 26–28 September 2026
+
+## Contributor handoff follow-up — 28 September 2026
+
+- Removed the public contributor-access issue template. Access instructions now
+ use private intake/internal tracking, matching the owner's policy. Added
+ `HANDOFF.md` for independent-machine setup and separate pass/fail/untested reports.
+- Five bootstrap regression tests, ten local documentation links and diff
+ whitespace checks: PASS.
+- Restarted this Mac's existing Colima profile and ran the documented `dev up`
+ against the same pinned sources, existing disposable project/volumes and build
+ caches. Health, Socket.IO, explicit unsupported-route failure, app create/read
+ and V3 testnet authorization/2FA: PASS.
+- `verify-local.sh --persistence --boundaries`: PASS, including retained app and
+ signing identity after recreation and rejection of mainnet/hosted databases.
+ This rerun is not a fresh-machine, native UI or transaction-signing test.
+- Published baseline app head `434cd7c405d8723b3c21c7ce6e82745b9b254517`, GitHub
+ run `36240719417`: app tests/coverage PASS; backend bootstrap unit tests PASS;
+ backend startup FAIL and subsequent integration checks SKIPPED. CI access is
+ still unresolved; these CI results apply to that baseline, not a later head.
+- Independent-machine verification, supported mobile Server Key acceptance,
+ backend readiness acceptance and safe CI source access remain open. No new
+ native build, full UI automation, provider-purchase or security-clearance pass
+ is claimed by this follow-up.
+
+## Readiness before private access
+
+The owner requires the same repository hygiene before private contributor access
+as before public publication. Backend cleanup is published in private draft PRs.
+This app now pins those updated revisions and its refreshed adapters have passed
+a fresh Docker setup on this Mac. Broader backend access still awaits history
+hygiene, credential handling, remaining dependency/security review and acceptance.
+Detailed findings remain private.
+
+## Fresh backend readiness integration
+
+This earlier private-backend readiness run used private Relay and SigningServer
+revisions, separate from the current public source pins. New app worktree, newly
+fetched backend sources and new Docker volumes; host image/package caches and
+existing GitHub read access reused. Project `keeper-readiness-proof` used ports
+23000/24002/23003, preserving other development projects.
+
+- Source fetch, adapter checksums/application and container builds: PASS.
+- All four service health checks, Socket.IO handshake, explicit unsupported-route
+ response and persisted app record create/read: PASS.
+- V3 testnet Server Key setup, authorization and valid/invalid 2FA: PASS.
+- Container recreation preserves the same app record and derived signer public
+ key: PASS. Mainnet/hosted database startup rejection: PASS.
+- Five bootstrap regression tests: PASS. Both backend test jobs and
+ current-source scans pass in their own CI;
+ their history scans remain failing, tracked privately.
+- Updated native development builds: iOS PASS after replacing a stale local
+ Node path; Android PASS after selecting the installed JDK 17 (976 tasks, 58
+ executed, 918 cached). Both builds embed the isolated 23000/24002/23003 backend
+ configuration. Native app source is the previously verified sprint integration;
+ this follow-up changes only backend pins/adapters and documentation.
+- Relay container compilation initially failed from memory exhaustion. Importing
+ only the existing Android Publisher v3 client reduced measured local compiler
+ memory to about 422 MB; the final image builds successfully with a 1 GB Node
+ heap. This retains the same provider API/library version.
+- Final image startup/API/V3/2FA and persistence/configuration-boundary checks:
+ PASS. The earlier iOS onboarding record survives recreation. No actual store
+ purchase, signing transaction or backup/recovery correctness test is claimed.
+- Native local smoke: iOS passcode/onboarding, Mobile Wallet and More Options
+ PASS using Maestro steps plus screenshot inspection. Initial Start New selector
+ failed despite the visible control; a visually guided tap continued the flow.
+ Relaunch/unlock after final backend restart PASS after handling the notification
+ prompt and repeated introductory/recovery-backup reminders; More Options assertion
+ passed. The original uninterrupted automation flows remain recorded as failures.
+- Android: disposable emulator user 10 preserves the prior user's app data. Fresh
+ passcode/onboarding, Mobile Wallet and More Options PASS using ADB assertions
+ plus a visually guided Next tap. The first attempt used the wrong Metro; after
+ selecting the matching checkout and resetting only this new user's disposable
+ fixture, the relay created the native app record with HTTP 200. UIAutomator could
+ not reach idle during the animated Next screen; that original assertion timed
+ out, while visual navigation and subsequent assertions passed. An earlier
+ attempt also overlapped the deliberate backend restart and was retried.
+- Native app records are confirmed in local MongoDB. This is onboarding/connectivity
+ evidence, not real signing, recovery, purchase or cloud-integration acceptance.
+- Full Linux Docker CI still lacks private-source access. Independent-machine
+ setup and Keeper security acceptance remain pending. These commits are draft
+ review inputs and are not an approval to deploy production backends.
+
+## Access policy and analysis update
+
+The owner chose approved contributor access and deferred SonarCloud on 26
+September. [Access instructions](ACCESS.md) and a GitHub request template now
+cover profile/context review, approved resource grants and setup confirmation.
+Local edits need no individual approval. No invitations or CI credentials were
+provisioned by this documentation change. SonarCloud is removed from active CI;
+its earlier failures below remain historical evidence, not a passing analysis.
+App tests and coverage remain active; private-source access still blocks backend
+CI. Independent contributor setup remains pending.
+
+This documentation/workflow update passed YAML and issue-template parsing,
+21 local documentation link checks, all five bootstrap tests and strict validation
+of both active OpenSpec changes. Native builds were not repeated for this update;
+the existing build results below apply to the unchanged app/native code.
+
+## Integration onto sprint
+
+The current PR is being integrated onto `sprint` commit `1adf4f663`; the release
+baseline results below are historical and are not a substitute for these checks.
+Fresh worktree and node_modules, host SDKs/caches reused:
+
+- Frozen Yarn installation: PASS.
+- Jest: 17 suites / 183 tests PASS; process exits normally after adding test-only
+ Electrum/HTTP teardown. LCOV is generated (coverage scope is the existing
+ Electrum/wallet directories).
+- Five bootstrap regression tests (including denied source access) and both active
+ OpenSpec changes: PASS.
+- Broad validation of all legacy OpenSpec specs: 17 pre-existing specs failed;
+ CI validates active changes, not these legacy documents.
+- Ruby lockfile constraints synchronized with Gemfile without gem version changes.
+- Initial CocoaPods install failed because `sprint` locked openiap 1.2.22 while
+ its existing react-native-iap 16.5.0 requires 3.4.0. Targeted `pod update openiap`
+ aligned NitroIap/NitroModules/openiap with existing JavaScript dependencies;
+ 142 pods installed successfully. The updated lockfile is part of this PR.
+- Fresh backend API, V3 authorization/2FA, persistence and configuration boundary
+ checks: PASS using this Mac's existing backend source access.
+- Android development build: PASS (976 tasks, 5m20s). Install over the disposable
+ development app, local backend configuration and testnet passcode-screen launch:
+ PASS. Fresh signed iOS Debug simulator build: PASS (142 pods). Simulator install and
+ launch to the passcode screen: PASS by screenshot inspection. These launch
+ checks are not complete onboarding, recovery or transaction tests.
+- GitHub Linux app job: PASS, 17 suites / 183 tests, active OpenSpec validation and
+ LCOV artifact upload. Measured line coverage is 57.37% (1451/2529) within the
+ existing configured source scope; no 80% coverage claim is made.
+- GitHub Linux bootstrap unit tests: PASS. Docker startup: FAIL during source
+ fetch because both backend repositories were private at the time and CI lacked
+ access. Current full-stack CI still requires private Relay access. This is not
+ a passing full-stack setup check.
+- SonarCloud: both the original and updated scanner failed before analysis; repository binding
+ still points at the old organization. See [CI notes](CI.md). No analysis pass
+ or security clearance is claimed.
+
+This integration preserves `sprint`'s app version fields; the separate 2.5.15
+release-version work is not imported or reverted by this contributor PR.
+
+## Test environment
+
+Fresh HTTPS clone of the published app tag `v2.5.15` (`e79e16b572d6e3472ac94500bf812d937bd89135`), plus this contributor setup change. New app dependency directories and newly fetched backend checkouts; no copied backend env files, databases or signing keys. Existing host SDKs, package caches and container image caches were reused.
+
+Apple Silicon Mac, macOS 26.6.2, Xcode 26.4/iOS 26.4 simulator, Node 25.9.0, Yarn 1.22.22, Python 3.9, Ruby 3.3.0/CocoaPods 1.15.2, JDK 17.0.19. Docker Engine 29.5.2/Compose 5.5.1 on Colima. Independent Compose project `keeper-contributor-clean`, newly generated volumes, loopback ports 13000/14002/13003. Existing developer/release services and data were preserved.
+
+## Results
+
+| Check | Result |
+| --- | --- |
+| Fetch pinned sources and verify/apply packaged adapters | PASS, both backends fetched from GitHub |
+| Advertised `dev up`, including API checks | PASS after correcting the smoke fixture to use current V3 Server Key APIs |
+| Mongo, relay, signing, gateway readiness | PASS |
+| Socket.IO polling handshake | PASS |
+| Relay create/read persisted app record | PASS |
+| Unsupported relay integration | PASS, explicit HTTP 503 |
+| V3 testnet Server Key setup and public-key format | PASS |
+| Invalid authorization, valid 2FA, invalid 2FA | PASS |
+| Container removal/recreation with retained volumes | PASS, same app record and derived signing public key |
+| Mainnet and hosted Mongo configuration rejection | PASS for relay and signing |
+| Actual container network/port inspection | PASS, backend network internal, no database port published, gateway bound only to loopback |
+| Rerun setup, existing env preservation, adapter tampering, unknown checkout preservation, duplicate ports | PASS, four regression tests plus real repeated bootstrap |
+| Fresh mobile Yarn install on the historical v2.5.15 acceptance tag | PASS with frozen mode at that source state. The source PR's `sprint` lock had unmatched lint-plugin selectors; the R4 combined candidate includes a corrected lock and uses frozen install, which passed in hosted diagnostic CI. |
+| Fresh CocoaPods installation | PASS, 142 pods; see path-dependent checksum note below |
+| Fresh Android `assembleDevelopmentDebug` | PASS, 976 tasks executed, 5m17s |
+| Android installed local configuration | PASS, development environment and alternate local backend ports verified in generated BuildConfig |
+| Android fresh install, passcode creation, onboarding, Mobile Wallet and More Options | PASS via ADB UI assertions and observed emulator controls |
+| Android local app record creation | PASS, HTTP 200 and database record confirmation |
+| Android Maestro driver | UNAVAILABLE, gRPC connection failed twice before flow execution; no Maestro pass claimed |
+| Fresh iOS development simulator build | PASS, signed Debug simulator app from fresh Pods/derived data |
+| iOS simulator launch, passcode creation/unlock and local relay connection | PASS, dev app launched; local app record created (two native app records total) |
+| iOS onboarding through Wallets | PASS by simulator screenshot inspection; Maestro text assertion failed despite the visible Mobile Wallet tile |
+| iOS More Options | PASS, simulator navigation and screenshot inspected |
+| Node/Mongo/nginx pinned image manifests | PASS, each includes Linux amd64 and arm64 |
+| Existing release version consistency | PASS, unchanged 2.5.15 / Android 622 / iOS 615 |
+
+Native apps use a separate Metro process on port 8082 during this acceptance run, preserving the existing developer's Metro on 8081. Android's dev-server host is set to localhost with device port 8081 forwarded to host 8082. Ordinary single-checkout instructions use port 8081.
+
+## Findings and limits
+
+- The pinned relay and signing backends acknowledge creation before their save callbacks complete. The check polls for record visibility for up to five seconds before dependent reads; it does not hide a rejected verification token or an unexpected response.
+- An exploratory legacy V2 Server Key setup returned success and then terminated its signing process. Its source uses a structured verifier schema but writes a string. This is an observed limitation of the pinned backend, not a verified production incident. Current app acceptance uses V3. Legacy V2 workflows remain outside the supported acceptance scope; this packaging change does not repair wallet/signing business logic.
+- Initial CocoaPods `--deployment` failed because the Hermes podspec embeds an absolute `HERMES_CLI_PATH`. A normal locked `pod install` refreshed only that podspec checksum to the new checkout path. Comparing old/new podspec JSON confirmed the path is the only difference. No dependency version changed. This generated lockfile difference is not part of the contributor source change.
+- Initial iOS UI scripts hit modal timing/selector failures, and one automated unlock was rejected. Retrying the same fixture PIN with waits succeeded. The XCUITest driver also needed a simulator restart after a failed connection; app data was preserved. The Mobile Wallet tile and Start New card were visible in screenshots when text assertions could not find them. These are recorded as automation limitations, not passes of the original complete flows; visual checks are explicitly distinguished from automated assertions.
+- React Native/third-party dependencies emit existing peer-dependency, export-resolution and native deprecation warnings. Build success is not a claim that those upstream warnings are resolved.
+- This proves a fresh checkout on this Mac, not a second physical machine. Intel/Linux/Windows, physical devices, cloud integrations, hardware wallets, real Server Key transactions, recovery correctness and scheduled inheritance flows remain unverified here. Recovery T-060 and store/source reconciliation are separate tasks.
+- Backend image digests and source pins constrain inputs; package caches and Debian package repositories prevent claiming a bit-identical image build.
+
+## Reproduce checks
+
+The earlier contributor OpenSpec change is not included in this checkout. Its
+validation is not a reproducible acceptance check for this source package.
+
+```sh
+./dev/local-backend/dev up
+./dev/local-backend/verify-local.sh --persistence --boundaries
+python3 -B -m unittest discover -s dev/local-backend -p test_keeper.py
+```
+
+The acceptance logs and emulator fixtures remain on the maintainer's machine outside the source package. Do not include local databases, generated signing identities, recovery material or captured emails in a source review or handoff archive.
diff --git a/dev/local-backend/adapters/relay/files/Dockerfile.local b/dev/local-backend/adapters/relay/files/Dockerfile.local
new file mode 100644
index 0000000000..285e1e8e18
--- /dev/null
+++ b/dev/local-backend/adapters/relay/files/Dockerfile.local
@@ -0,0 +1,12 @@
+FROM node:22-bookworm-slim@sha256:43ac6c60b8f89723f746e8a92ce91abd5017e627ce1ddfe4238355d3a30b772c
+WORKDIR /app
+RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates python3 make g++ && rm -rf /var/lib/apt/lists/*
+COPY package.json yarn.lock ./
+RUN yarn install --frozen-lockfile --non-interactive --ignore-scripts
+COPY tsconfig.json ./
+COPY src ./src
+COPY public ./public
+RUN yarn compile
+ENV NODE_ENV=development
+USER node
+CMD ["node", "dist/index.js"]
diff --git a/dev/local-backend/adapters/signing/files/.dockerignore b/dev/local-backend/adapters/signing/files/.dockerignore
new file mode 100644
index 0000000000..e8b30bfc29
--- /dev/null
+++ b/dev/local-backend/adapters/signing/files/.dockerignore
@@ -0,0 +1,9 @@
+.git
+.env*
+node_modules
+dist
+**/*.pem
+**/*.p12
+**/*.key
+logfile.log
+coverage
diff --git a/dev/local-backend/adapters/signing/files/Dockerfile.local b/dev/local-backend/adapters/signing/files/Dockerfile.local
new file mode 100644
index 0000000000..f14a93fd88
--- /dev/null
+++ b/dev/local-backend/adapters/signing/files/Dockerfile.local
@@ -0,0 +1,11 @@
+FROM node:22-bookworm-slim@sha256:43ac6c60b8f89723f746e8a92ce91abd5017e627ce1ddfe4238355d3a30b772c
+WORKDIR /app
+COPY package.json package-lock.json ./
+RUN npm ci --ignore-scripts
+COPY tsconfig.json ./
+COPY src ./src
+COPY scripts/local-entry.cjs ./scripts/local-entry.cjs
+RUN npm run compile && mkdir /local-data && chown node:node /local-data /app
+ENV NODE_ENV=development
+USER node
+CMD ["node", "scripts/local-entry.cjs"]
diff --git a/dev/local-backend/adapters/signing/files/scripts/local-entry.cjs b/dev/local-backend/adapters/signing/files/scripts/local-entry.cjs
new file mode 100644
index 0000000000..2795934ca9
--- /dev/null
+++ b/dev/local-backend/adapters/signing/files/scripts/local-entry.cjs
@@ -0,0 +1,14 @@
+// Local test keys are created once per Docker volume. Never print their values.
+const fs = require('node:fs');
+const crypto = require('node:crypto');
+const bip39 = require('bip39');
+if (process.env.LOCAL_DEV !== 'true' || process.env.ENVIRONMENT !== 'TEST') throw new Error('Local entry requires LOCAL_DEV and TEST');
+const file = '/local-data/secrets.json';
+if (!fs.existsSync(file)) {
+ const rsa = crypto.generateKeyPairSync('rsa', { modulusLength: 2048,
+ privateKeyEncoding: { type: 'pkcs1', format: 'pem' }, publicKeyEncoding: { type: 'spki', format: 'pem' } });
+ const secrets = { 'local-rsa-private': rsa.privateKey, 'local-rsa-public': rsa.publicKey };
+ for (const id of ['local-signer-v2', 'local-signer-v3', 'local-inheritance-v2', 'local-inheritance-v3']) secrets[id] = bip39.generateMnemonic(256);
+ fs.writeFileSync(file, JSON.stringify(secrets), { mode: 0o600, flag: 'wx' });
+}
+require('../dist/index.js');
diff --git a/dev/local-backend/adapters/signing/files/src/config.ts b/dev/local-backend/adapters/signing/files/src/config.ts
new file mode 100644
index 0000000000..1df0526542
--- /dev/null
+++ b/dev/local-backend/adapters/signing/files/src/config.ts
@@ -0,0 +1,100 @@
+import * as bitcoinJS from "bitcoinjs-lib";
+import dotenv from "dotenv";
+import { fetchSecrets } from "./utilities/secretManager";
+import { logger } from "./utilities/logger"
+import { WalletCredsVersion } from "./interfaces/wallet";
+
+const result = dotenv.config();
+
+if (result.error && process.env.LOCAL_DEV !== "true") {
+ throw result.error;
+}
+
+export enum SERVER_TYPE {
+ MAIN = "MAIN",
+ TEST = "TEST"
+}
+
+export enum DATABASE_TYPE {
+ DEV = "DEV",
+ PROD = "PROD"
+}
+
+class Config {
+ public LOCAL_DEV = process.env.LOCAL_DEV === "true";
+ public ENVIRONMENT: string = process.env.ENVIRONMENT;
+ public PORT: string = process.env.PORT || "3003";
+ public NETWORK: bitcoinJS.Network;
+ public HEXA_ID = process.env.HEXA_ID
+ public RELAY = process.env.RELAY
+
+ public INHERITANCE_KEY_REQUEST_THRESHOLD: number; // 30days(prod) / 5 mins(dev)
+ public INHERITANCE_KEY_REQUEST_TTL: number; // 3x of request threshold duration
+ public ADMIN_KEY: string = process.env.BIT_ADMIN_KEY;
+ public VERSION: string = process.env.VERSION;
+
+ public MAILER_CONFIG = {
+ SES_REGION: process.env.SES_REGION,
+ SOURCE_EMAIL: process.env.SES_SOURCE_EMAIL,
+ ACCESS_KEY_ID: process.env.SES_ACCESS_KEY_ID,
+ SECRET_ACCESS_KEY: process.env.SES_SECRET_ACCESS_KEY,
+ }
+
+ public DB_MODE = process.env.DB_MODE;
+ public DATABASE_NAME_V2: string = process.env.DATABASE_NAME_V2;
+ public DATABASE_SECRET_IDENTIFIER_V2: string = process.env.DATABASE_SECRET_IDENTIFIER_V2;
+ public PROJECT_ID: string = process.env.PROJECT_ID;
+ public MIN_POLICY_UPDATE_DELAY: number;
+
+ public MNEMONIC_IDENTIFIERS = {
+ [WalletCredsVersion.V2]: process.env.MNEMONIC_IDENTIFIER_V2,
+ [WalletCredsVersion.V3]: process.env.MNEMONIC_IDENTIFIER_V3,
+ };
+
+ public INHERITANCE_MNEMONIC_IDENTIFIERS = {
+ [WalletCredsVersion.V2]: process.env.INHERITANCE_MNEMONIC_IDENTIFIER_V2,
+ [WalletCredsVersion.V3]: process.env.INHERITANCE_MNEMONIC_IDENTIFIER_V3,
+ };
+
+ public RSA_PRV_KEY_IDENTIFIER: string = process.env.RSA_PRV_KEY_IDENTIFIER;
+ public RSA_PUB_KEY_IDENTIFIER: string = process.env.RSA_PUB_KEY_IDENTIFIER;
+ public RSA_PRV_KEY: string;
+ public RSA_PUB_KEY: string;
+
+ constructor() {
+ if (this.LOCAL_DEV) {
+ const db = new URL(process.env.LOCAL_DATABASE_URL || "");
+ if (this.ENVIRONMENT !== "TEST" || this.DB_MODE !== "DEV" ||
+ db.protocol !== "mongodb:" || !["mongo", "localhost", "127.0.0.1"].includes(db.hostname) ||
+ db.username || db.password || db.pathname !== "/keeper_signing_local") {
+ throw new Error("Local signing requires TEST, DEV and the isolated local database");
+ }
+ if (this.HEXA_ID !== "keeper-local-only") throw new Error("Local signing requires its own application credential");
+ }
+ this.configureNetwork();
+ }
+
+ public configureNetwork = () => {
+ if (this.ENVIRONMENT === SERVER_TYPE.MAIN) {
+ this.NETWORK = bitcoinJS.networks.bitcoin;
+ this.INHERITANCE_KEY_REQUEST_THRESHOLD = 2592000000 // 30 days in milliseconds
+ this.MIN_POLICY_UPDATE_DELAY = 1 * 7 * 24 * 60 * 60 * 1000 // 1 week in milliseconds
+ } else if (this.ENVIRONMENT === SERVER_TYPE.TEST) {
+ this.NETWORK = bitcoinJS.networks.testnet;
+ this.INHERITANCE_KEY_REQUEST_THRESHOLD = 300000 // 5 mins in milliseconds
+ this.MIN_POLICY_UPDATE_DELAY = 1 * 60 * 60 * 1000 // 1 hour in milliseconds
+ } else {
+ throw new Error("Please specify an apt environment(MAIN||TEST)");
+ }
+ this.INHERITANCE_KEY_REQUEST_TTL = (this.INHERITANCE_KEY_REQUEST_THRESHOLD / 1000) * 3
+ };
+
+ public initRSAKeys = async () => {
+ const [privResponse, pubResponse] = await fetchSecrets([this.RSA_PRV_KEY_IDENTIFIER, this.RSA_PUB_KEY_IDENTIFIER]);
+ this.RSA_PRV_KEY = privResponse[this.RSA_PRV_KEY_IDENTIFIER]
+ this.RSA_PUB_KEY = pubResponse[this.RSA_PUB_KEY_IDENTIFIER]
+ logger.info('RSA keys have been initialized')
+ }
+}
+
+export default new Config();
diff --git a/dev/local-backend/adapters/signing/local.patch b/dev/local-backend/adapters/signing/local.patch
new file mode 100644
index 0000000000..d13580b53a
--- /dev/null
+++ b/dev/local-backend/adapters/signing/local.patch
@@ -0,0 +1,132 @@
+diff --git a/src/databases/dbV2.ts b/src/databases/dbV2.ts
+index dc661dc..31b47a9 100644
+--- a/src/databases/dbV2.ts
++++ b/src/databases/dbV2.ts
+@@ -269,6 +269,13 @@ class DatabaseV2 {
+ }
+
+ public initializeConnection = async () => {
++ if (config.LOCAL_DEV) {
++ this.connection = mongoose.createConnection(process.env.LOCAL_DATABASE_URL, {
++ dbName: "keeper_signing_local", autoIndex: true,
++ });
++ await this.connection.asPromise();
++ return;
++ }
+ const [response] = await fetchSecrets(
+ [config.DATABASE_SECRET_IDENTIFIER_V2],
+ true
+@@ -288,6 +295,8 @@ class DatabaseV2 {
+ });
+ };
+
++ public isReady = () => this.connection?.readyState === 1;
++
+ public getSignerV2Model = (): mongoose.Model => {
+ return this.connection.model("Signer", this.signerV2);
+ };
+diff --git a/src/index.ts b/src/index.ts
+index 7e3a325..bee0b07 100644
+--- a/src/index.ts
++++ b/src/index.ts
+@@ -3,6 +3,7 @@ import express, { Express } from "express";
+ import morgan from "morgan";
+
+ import config from "./config";
++import dbV2 from "./databases/dbV2";
+ import { logger, unhandledLogger} from "./utilities/logger"
+ import { initializeCrons } from "./utilities/crons";
+ import { initializeRoutes } from "./routes/router";
+@@ -14,7 +15,7 @@ class SigningServer {
+ this.app = express();
+ this.configure();
+ this.invoke();
+- initializeCrons();
++ if (!config.LOCAL_DEV) initializeCrons();
+ config.initRSAKeys();
+ }
+
+@@ -24,6 +25,13 @@ class SigningServer {
+ this.app.use(morgan("combined", { stream: { write: message => logger.info(message.trim()) } }));
+ this.app.use(bodyParser.json());
+ this.app.use(bodyParser.urlencoded({ extended: true }));
++ if (config.LOCAL_DEV) {
++ this.app.get("/health", (_req, res) => {
++ const ready = dbV2.isReady() && !!config.RSA_PUB_KEY;
++ res.status(ready ? 200 : 503).json({ ready, mode: "local", network: "TESTNET",
++ capabilities: { signing: ready, emailDelivery: false, pushDelivery: false, scheduledJobs: false } });
++ });
++ }
+ this.app.use(initializeRoutes(this.app));
+ }
+
+diff --git a/src/services/mailing/mailer.ts b/src/services/mailing/mailer.ts
+index 9ab6b1d..3995234 100644
+--- a/src/services/mailing/mailer.ts
++++ b/src/services/mailing/mailer.ts
+@@ -1,5 +1,6 @@
+ import config from "../../config";
+ import moment from "moment";
++import { appendFileSync } from "fs";
+ import AWS from "aws-sdk";
+ import { EMAIL_TEMPLATES } from "./templates";
+
+@@ -65,7 +66,7 @@ const fetchEmailContentByType = (
+ )
+ .replace(
+ "{{server_url}}",
+- config.ENVIRONMENT === "MAIN"
++ config.LOCAL_DEV ? "http://localhost:3003" : config.ENVIRONMENT === "MAIN"
+ ? "https://sign.bithyve.com"
+ : "https://dev-sign.bithyve.com"
+ )
+@@ -109,5 +110,9 @@ export const sendEmails = (
+ },
+ },
+ };
++ if (config.LOCAL_DEV) {
++ appendFileSync("/local-data/outbox.jsonl", JSON.stringify({ capturedAt: new Date().toISOString(), ...params }) + "\n", { mode: 0o600 });
++ return Promise.resolve({ MessageId: "local-captured-not-delivered" });
++ }
+ return AWS_SES.sendEmail(params).promise();
+ };
+diff --git a/src/services/notifications/pushNotification.ts b/src/services/notifications/pushNotification.ts
+index 87e9d5c..477681d 100644
+--- a/src/services/notifications/pushNotification.ts
++++ b/src/services/notifications/pushNotification.ts
+@@ -85,6 +85,7 @@ export const pushIKNotification = async (
+ requestAutoApprovesIn?: number;
+ }
+ ) => {
++ if (config.LOCAL_DEV) { logger.info("Local mode: push delivery disabled"); return; }
+ try {
+ const requestData = {
+ FCMs,
+@@ -118,6 +119,7 @@ export const pushServerKeyNotification = async (
+ signedTx?: string;
+ }
+ ) => {
++ if (config.LOCAL_DEV) { logger.info("Local mode: push delivery disabled"); return; }
+ try {
+ let title;
+ let body;
+diff --git a/src/utilities/secretManager.ts b/src/utilities/secretManager.ts
+index e6bfd49..3b3b732 100644
+--- a/src/utilities/secretManager.ts
++++ b/src/utilities/secretManager.ts
+@@ -1,7 +1,15 @@
+ import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
+ import config from '../config';
++import { readFileSync } from 'fs';
+
+ export const fetchSecrets = async (secretIdentifiers: string[], shouldParse: Boolean = false) => {
++ if (config.LOCAL_DEV) {
++ const secrets = JSON.parse(readFileSync("/local-data/secrets.json", "utf8"));
++ return secretIdentifiers.map(identifier => {
++ if (!Object.prototype.hasOwnProperty.call(secrets, identifier)) throw new Error("Unknown local secret identifier");
++ return { [identifier]: shouldParse ? JSON.parse(secrets[identifier]) : secrets[identifier] };
++ });
++ }
+ const client = new SecretManagerServiceClient();
+ const projectId = config.PROJECT_ID;
+
diff --git a/dev/local-backend/app.env.local.example b/dev/local-backend/app.env.local.example
new file mode 100644
index 0000000000..0121ab915d
--- /dev/null
+++ b/dev/local-backend/app.env.local.example
@@ -0,0 +1,10 @@
+# Disposable local development only. Copy to app repo .env.local.
+ENVIRONMENT=DEVELOPMENT
+RELAY=http://localhost:3000/
+CHANNEL_URL=http://localhost:4002/
+SIGNING_SERVER_TESTNET=http://localhost:3003/
+SIGNING_SERVER_MAINNET=http://localhost:3003/mainnet-disabled/
+HEXA_ID_TESTNET=keeper-local-only
+HEXA_ID_MAINNET=keeper-local-mainnet-disabled
+ENC_KEY_STORAGE_IDENTIFIER=KEEPER-LOCAL-DEV
+SENTRY_DNS=http://local@localhost:3000/1
diff --git a/dev/local-backend/compose.yaml b/dev/local-backend/compose.yaml
new file mode 100644
index 0000000000..be79d65d3a
--- /dev/null
+++ b/dev/local-backend/compose.yaml
@@ -0,0 +1,99 @@
+name: ${COMPOSE_PROJECT_NAME:-keeper-contributor}
+services:
+ mongo:
+ image: mongo:7.0@sha256:9854f7139445d766a9523571d6f047530c45547460ffcf8259eb2bf4264632ca
+ command: [mongod, --replSet, keeper-local, --bind_ip_all]
+ volumes:
+ - mongo-data:/data/db
+ networks: [local-only]
+ healthcheck:
+ test: [CMD, mongosh, --quiet, --eval, "try { rs.status(); } catch (e) { if (e.code !== 94) throw e; rs.initiate({_id: 'keeper-local', members: [{_id: 0, host: 'mongo:27017'}]}); } quit(db.hello().isWritablePrimary ? 0 : 1)"]
+ interval: 5s
+ timeout: 5s
+ retries: 20
+ relay:
+ build:
+ context: ./.sources/relay
+ dockerfile: Dockerfile.local
+ environment:
+ LOCAL_DEV: "true"
+ ENVIRONMENT: DEVELOPMENT
+ BITCOIN_NETWORK: TESTNET
+ VERSION: local-development
+ DATABASE_URL: mongodb://mongo:27017/keeper_local?replicaSet=keeper-local
+ PORT: "3000"
+ WS_PORT: "4002"
+ HEXA_ID: keeper-local-only
+ ADMIN_KEY: keeper-local-admin-only
+ CHANNEL_URL: http://relay:4002/
+ FAUCET_MNEMONIC: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
+ networks: [local-only]
+ depends_on:
+ mongo:
+ condition: service_healthy
+ healthcheck:
+ test: [CMD, node, -e, "fetch('http://localhost:3000/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
+ interval: 5s
+ timeout: 5s
+ retries: 20
+ signing:
+ build:
+ context: ./.sources/signing
+ dockerfile: Dockerfile.local
+ environment:
+ LOCAL_DEV: "true"
+ ENVIRONMENT: TEST
+ DB_MODE: DEV
+ PORT: "3003"
+ VERSION: local-development
+ HEXA_ID: keeper-local-only
+ BIT_ADMIN_KEY: keeper-local-admin-only
+ LOCAL_DATABASE_URL: mongodb://mongo:27017/keeper_signing_local?replicaSet=keeper-local
+ RELAY: http://relay:3000/
+ MNEMONIC_IDENTIFIER_V2: local-signer-v2
+ MNEMONIC_IDENTIFIER_V3: local-signer-v3
+ INHERITANCE_MNEMONIC_IDENTIFIER_V2: local-inheritance-v2
+ INHERITANCE_MNEMONIC_IDENTIFIER_V3: local-inheritance-v3
+ RSA_PRV_KEY_IDENTIFIER: local-rsa-private
+ RSA_PUB_KEY_IDENTIFIER: local-rsa-public
+ SES_REGION: us-east-1
+ SES_SOURCE_EMAIL: local@example.invalid
+ volumes:
+ - signing-data:/local-data
+ networks: [local-only]
+ depends_on:
+ mongo:
+ condition: service_healthy
+ healthcheck:
+ test: [CMD, node, -e, "fetch('http://localhost:3003/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
+ interval: 5s
+ timeout: 5s
+ retries: 20
+ gateway:
+ healthcheck:
+ test: [CMD-SHELL, "wget -q -O /dev/null http://127.0.0.1:3000/health && wget -q -O /dev/null http://127.0.0.1:3003/health"]
+ interval: 5s
+ timeout: 5s
+ retries: 20
+ image: nginx:1.28-alpine@sha256:a8b39bd9cf0f83869a2162827a0caf6137ddf759d50a171451b335cecc87d236
+ volumes:
+ - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
+ ports:
+ - "127.0.0.1:${KEEPER_RELAY_PORT:-3000}:3000"
+ - "127.0.0.1:${KEEPER_CHANNEL_PORT:-4002}:4002"
+ - "127.0.0.1:${KEEPER_SIGNING_PORT:-3003}:3003"
+ networks: [local-only, host-access]
+ depends_on:
+ relay:
+ condition: service_healthy
+ restart: true
+ signing:
+ condition: service_healthy
+ restart: true
+networks:
+ local-only:
+ internal: true
+ host-access:
+volumes:
+ mongo-data:
+ signing-data:
diff --git a/dev/local-backend/dev b/dev/local-backend/dev
new file mode 100755
index 0000000000..52a7cab783
--- /dev/null
+++ b/dev/local-backend/dev
@@ -0,0 +1,3 @@
+#!/bin/sh
+set -eu
+exec python3 "$(dirname "$0")/keeper.py" "$@"
diff --git a/dev/local-backend/keeper.py b/dev/local-backend/keeper.py
new file mode 100644
index 0000000000..fbb93a8dca
--- /dev/null
+++ b/dev/local-backend/keeper.py
@@ -0,0 +1,192 @@
+#!/usr/bin/env python3
+"""Contributor setup using only Python's standard library, Git and Compose."""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+HERE = Path(__file__).resolve().parent
+APP = HERE.parent.parent
+
+
+def run(args, **kwargs):
+ return subprocess.run([str(a) for a in args], check=True, **kwargs)
+
+
+def output(args, **kwargs):
+ return subprocess.check_output([str(a) for a in args], text=True, **kwargs).strip()
+
+
+def settings():
+ values = {}
+ envfile = HERE / '.env'
+ if envfile.exists():
+ for line in envfile.read_text().splitlines():
+ if line.strip() and not line.lstrip().startswith('#'):
+ key, sep, value = line.partition('=')
+ if not sep:
+ raise ValueError('Use KEY=value lines in dev/local-backend/.env')
+ values[key.strip()] = value.strip()
+ defaults = {'COMPOSE_PROJECT_NAME': 'keeper-contributor',
+ 'KEEPER_RELAY_PORT': '3000', 'KEEPER_CHANNEL_PORT': '4002',
+ 'KEEPER_SIGNING_PORT': '3003'}
+ for key, default in defaults.items():
+ values[key] = os.environ.get(key, values.get(key, default))
+ if not re.fullmatch(r'[a-z0-9][a-z0-9_-]*', values['COMPOSE_PROJECT_NAME']):
+ raise ValueError('COMPOSE_PROJECT_NAME must contain lowercase letters, digits, _ or -')
+ ports = [int(values[k]) for k in defaults if k.endswith('_PORT')]
+ if 8081 in ports:
+ raise ValueError('Port 8081 is reserved for Metro; choose another backend port')
+ if len(set(ports)) != 3 or any(p < 1024 or p > 65535 for p in ports):
+ raise ValueError('Choose three distinct ports between 1024 and 65535')
+ return {k: values[k] for k in defaults}
+
+
+def compose(*args, **kwargs):
+ env = dict(os.environ, **settings())
+ return run(['docker', 'compose', '--env-file', HERE / '.env.example',
+ '-f', HERE / 'compose.yaml', *args], env=env, **kwargs)
+
+
+def prepare(only=None):
+ lock = json.loads((HERE / 'sources.lock.json').read_text())
+ sources = HERE / '.sources'
+ sources.mkdir(exist_ok=True)
+ for name, spec in lock.items():
+ if only is not None and name != only:
+ continue
+ adapter = HERE / 'adapters' / name
+ adapter_files = [path for path in adapter.rglob('*') if path.is_file() or path.is_symlink()]
+ if any(path.is_symlink() for path in adapter_files):
+ raise ValueError(f'{name}: adapter symlinks are not allowed')
+ actual_assets = {path.relative_to(adapter).as_posix() for path in adapter_files}
+ if actual_assets != set(spec['assets']):
+ raise ValueError(f'{name}: adapter file set does not match source lock')
+ for asset, digest in spec['assets'].items():
+ if hashlib.sha256((adapter / asset).read_bytes()).hexdigest() != digest:
+ raise ValueError(f'{name}: adapter checksum mismatch: {asset}')
+ fingerprint = hashlib.sha256(json.dumps(spec, sort_keys=True).encode()).hexdigest()
+ target = sources / name
+ marker = target / '.keeper-source.json'
+ if target.exists():
+ if not marker.exists() or json.loads(marker.read_text()) != spec:
+ raise ValueError(f'{target}: existing checkout does not match this setup. '
+ 'Move it aside after saving your edits, then retry; it was not overwritten.')
+ if output(['git', '-C', target, 'rev-parse', 'HEAD']) != spec['revision']:
+ raise ValueError(f'{target}: HEAD changed; save your work and move this checkout aside.')
+ print(f'{name}: already prepared; preserving local backend edits ({fingerprint[:12]})')
+ continue
+ with tempfile.TemporaryDirectory(prefix=f'.{name}-', dir=sources) as temp:
+ checkout = Path(temp) / 'checkout'
+ run(['git', 'init', '--quiet', checkout])
+ run(['git', '-C', checkout, 'remote', 'add', 'origin', spec['url']])
+ print(f'{name}: fetching {spec["revision"]}', flush=True)
+ try:
+ run(['git', '-C', checkout, 'fetch', '--quiet', '--depth=1', 'origin', spec['revision']])
+ except subprocess.CalledProcessError as error:
+ raise ValueError(f'{name}: cannot fetch the pinned public backend revision. '
+ 'Check the revision and network connection. '
+ 'No existing checkout was replaced.') from error
+ run(['git', '-C', checkout, 'checkout', '--quiet', '--detach', spec['revision']])
+ if spec['assets']:
+ if (adapter / 'local.patch').exists():
+ run(['git', '-C', checkout, 'apply', '--check', adapter / 'local.patch'])
+ run(['git', '-C', checkout, 'apply', adapter / 'local.patch'])
+ for asset in (adapter / 'files').rglob('*'):
+ if asset.is_file():
+ dest = checkout / asset.relative_to(adapter / 'files')
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(asset, dest)
+ (checkout / '.keeper-source.json').write_text(json.dumps(spec, indent=2) + '\n')
+ checkout.rename(target)
+
+
+def app_env():
+ config = settings()
+ template = (HERE / 'app.env.local.example').read_text()
+ ports = {'3000': config['KEEPER_RELAY_PORT'],
+ '4002': config['KEEPER_CHANNEL_PORT'],
+ '3003': config['KEEPER_SIGNING_PORT']}
+ template = re.sub(r':(3000|4002|3003)/', lambda match: f':{ports[match.group(1)]}/', template)
+ dest = APP / '.env.local'
+ if dest.exists():
+ if dest.read_text() != template:
+ raise ValueError('.env.local already exists with different settings. Compare it with '
+ 'dev/local-backend/app.env.local.example; no file was overwritten.')
+ print('.env.local already matches this setup')
+ return
+ fd = os.open(dest, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(fd, 'w') as stream:
+ stream.write(template)
+ print('Created .env.local (local test settings only)')
+
+
+def doctor():
+ failed = False
+ for label, args in [('Git', ['git', '--version']), ('Docker Engine', ['docker', 'info', '--format', '{{.ServerVersion}}']),
+ ('Docker Compose', ['docker', 'compose', 'version']), ('Node', ['node', '--version']),
+ ('Yarn', ['yarn', '--version'])]:
+ try:
+ print(f'{label}: {output(args, stderr=subprocess.DEVNULL)}')
+ except (OSError, subprocess.CalledProcessError):
+ print(f'MISSING: {label}')
+ failed = True
+ print('Python:', sys.version.split()[0])
+ print('Android SDK:', os.environ.get('ANDROID_HOME', 'set ANDROID_HOME before Android builds'))
+ print('JAVA_HOME:', os.environ.get('JAVA_HOME', 'set JAVA_HOME to JDK 17 before Android builds'))
+ if sys.platform == 'darwin':
+ for label, args in [('Xcode', ['xcodebuild', '-version']), ('Ruby', ['ruby', '--version']),
+ ('Bundler', ['bundle', '--version'])]:
+ try:
+ print(f'{label}: {output(args, stderr=subprocess.DEVNULL)}')
+ except (OSError, subprocess.CalledProcessError):
+ print(f'MISSING for iOS: {label}')
+ print('See README.md for required native tool versions; this checks availability, not native builds.')
+ if failed:
+ raise ValueError('Install/start the missing prerequisites and rerun doctor.')
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('command', choices=['doctor', 'prepare', 'prepare-signing', 'up', 'stop', 'status', 'logs', 'verify', 'env', 'android-forward'])
+ parser.add_argument('--serial', help='Android emulator/device serial for android-forward')
+ args = parser.parse_args()
+ if args.command == 'doctor':
+ doctor()
+ elif args.command == 'prepare':
+ prepare()
+ elif args.command == 'prepare-signing':
+ prepare(only='signing')
+ elif args.command == 'up':
+ prepare()
+ compose('up', '-d', '--build', '--wait', '--wait-timeout', '180')
+ run([sys.executable, HERE / 'verify.py'])
+ elif args.command == 'stop':
+ compose('down') # Retain both databases and signing keys. No implicit data reset.
+ elif args.command == 'status':
+ compose('ps')
+ elif args.command == 'logs':
+ compose('logs', '--tail', '100')
+ elif args.command == 'verify':
+ run([sys.executable, HERE / 'verify.py'])
+ elif args.command == 'env':
+ app_env()
+ elif args.command == 'android-forward':
+ if not args.serial:
+ parser.error('android-forward requires --serial; use adb devices to choose one')
+ for port in ['8081'] + [v for k, v in settings().items() if k.endswith('_PORT')]:
+ run(['adb', '-s', args.serial, 'reverse', f'tcp:{port}', f'tcp:{port}'])
+
+
+if __name__ == '__main__':
+ try:
+ main()
+ except (OSError, ValueError, subprocess.CalledProcessError) as error:
+ print(f'Setup failed: {error}', file=sys.stderr)
+ sys.exit(1)
diff --git a/dev/local-backend/nginx.conf b/dev/local-backend/nginx.conf
new file mode 100644
index 0000000000..bcd9481514
--- /dev/null
+++ b/dev/local-backend/nginx.conf
@@ -0,0 +1,22 @@
+server {
+ listen 3000;
+ client_max_body_size 50m;
+ location / {
+ proxy_pass http://relay:3000;
+ }
+}
+server {
+ listen 4002;
+ location / {
+ proxy_pass http://relay:4002;
+ proxy_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection "upgrade";
+ }
+}
+server {
+ listen 3003;
+ location / {
+ proxy_pass http://signing:3003;
+ }
+}
diff --git a/dev/local-backend/sources.lock.json b/dev/local-backend/sources.lock.json
new file mode 100644
index 0000000000..4d5d02b531
--- /dev/null
+++ b/dev/local-backend/sources.lock.json
@@ -0,0 +1,20 @@
+{
+ "relay": {
+ "url": "https://github.com/KeeperCommunity/Relay.git",
+ "revision": "ee935359f22ff7932ea0a62e9084d4b49801f4aa",
+ "assets": {
+ "files/Dockerfile.local": "6dde6c692430b1a91a10cdd82e6f1562023cc5974ffd4d4f58fe57fa1994407a"
+ }
+ },
+ "signing": {
+ "url": "https://github.com/KeeperCommunity/SigningServer.git",
+ "revision": "3cc7728c27328e7b0358d1f91a32d8d13feba90a",
+ "assets": {
+ "files/.dockerignore": "78d9a1e03c57cfc1c7fb79ff2335aa2393bb075d0ac4a23feae81371728190be",
+ "files/Dockerfile.local": "04a0bfca3903eb1363f8804b7c181424747c949aed543a89fe7a02316ccafa3d",
+ "files/scripts/local-entry.cjs": "7e0d39965fd8d4a880ab68b5ff9e7b75595c33cbdb106bb5ec0b42d505b1827b",
+ "files/src/config.ts": "606fdeb4717e98ab95e5a6918a0c8a8b9b3427697d27bba263b9ec566a91438e",
+ "local.patch": "a592f37900215a5f013a0d349983f7a1d937206fbf1670c07fc9a37e457d743f"
+ }
+ }
+}
diff --git a/dev/local-backend/test_keeper.py b/dev/local-backend/test_keeper.py
new file mode 100644
index 0000000000..b5bc059b51
--- /dev/null
+++ b/dev/local-backend/test_keeper.py
@@ -0,0 +1,146 @@
+"""Regression checks for setup operations that must preserve developer work."""
+import hashlib
+import json
+import subprocess
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import patch
+
+import keeper
+import verify
+
+
+class PreserveDeveloperWork(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.app = Path(self.temp.name)
+ self.here = self.app / 'dev/local-backend'
+ self.here.mkdir(parents=True)
+ self.contexts = [patch.object(keeper, 'HERE', self.here), patch.object(keeper, 'APP', self.app),
+ patch.dict('os.environ', {}, clear=True)]
+ for context in self.contexts:
+ context.start()
+ self.addCleanup(context.stop)
+
+ def test_environment_is_exclusive_and_preserves_production(self):
+ (self.here / 'app.env.local.example').write_text('RELAY=http://localhost:3000/\n')
+ production = self.app / '.env.production'
+ production.write_text('existing-production-sentinel\n')
+ keeper.app_env()
+ self.assertEqual((self.app / '.env.local').stat().st_mode & 0o777, 0o600)
+ keeper.app_env() # Same configuration is repeatable.
+ (self.app / '.env.local').write_text('developer-settings\n')
+ with self.assertRaisesRegex(ValueError, 'already exists'):
+ keeper.app_env()
+ self.assertEqual((self.app / '.env.local').read_text(), 'developer-settings\n')
+ self.assertEqual(production.read_text(), 'existing-production-sentinel\n')
+
+ def test_swapped_ports_do_not_rewrite_each_other(self):
+ (self.here / 'app.env.local.example').write_text(
+ 'RELAY=http://localhost:3000/\nCHANNEL=http://localhost:4002/\n'
+ 'SIGNING=http://localhost:3003/\n')
+ (self.here / '.env').write_text('KEEPER_RELAY_PORT=4002\nKEEPER_CHANNEL_PORT=3000\n')
+ keeper.app_env()
+ self.assertEqual((self.app / '.env.local').read_text(),
+ 'RELAY=http://localhost:4002/\nCHANNEL=http://localhost:3000/\n'
+ 'SIGNING=http://localhost:3003/\n')
+
+ def test_adapter_tampering_is_rejected_before_fetch(self):
+ adapter = self.here / 'adapters/relay'
+ adapter.mkdir(parents=True)
+ (adapter / 'local.patch').write_text('changed')
+ (self.here / 'sources.lock.json').write_text(json.dumps({'relay': {
+ 'assets': {'local.patch': hashlib.sha256(b'original').hexdigest()}}}))
+ with patch.object(keeper, 'run') as command:
+ with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
+ keeper.prepare()
+ command.assert_not_called()
+
+ def test_unlisted_adapter_file_is_rejected_before_fetch(self):
+ adapter = self.here / 'adapters/relay/files'
+ adapter.mkdir(parents=True)
+ (adapter / 'unlisted.js').write_text('unexpected')
+ (self.here / 'sources.lock.json').write_text(json.dumps({'relay': {'assets': {}}}))
+ with patch.object(keeper, 'run') as command:
+ with self.assertRaisesRegex(ValueError, 'file set does not match'):
+ keeper.prepare()
+ command.assert_not_called()
+
+ def test_adapter_symlinks_are_rejected_before_fetch_even_when_listed(self):
+ adapter = self.here / 'adapters/relay/files'
+ adapter.mkdir(parents=True)
+ target = self.app / 'outside-adapter.js'
+ target.write_text('fixture')
+ (adapter / 'link.js').symlink_to(target)
+ for assets in ({}, {'files/link.js': hashlib.sha256(b'fixture').hexdigest()}):
+ with self.subTest(listed=bool(assets)):
+ (self.here / 'sources.lock.json').write_text(json.dumps({
+ 'relay': {'assets': assets}}))
+ with patch.object(keeper, 'run') as command:
+ with self.assertRaisesRegex(ValueError, 'symlinks are not allowed'):
+ keeper.prepare()
+ command.assert_not_called()
+
+ def test_unknown_existing_checkout_is_not_overwritten(self):
+ source = self.here / '.sources/relay'
+ source.mkdir(parents=True)
+ edit = source / 'my-work.ts'
+ edit.write_text('keep this')
+ (self.here / 'sources.lock.json').write_text(json.dumps({'relay': {'assets': {}}}))
+ with patch.object(keeper, 'run') as command:
+ with self.assertRaisesRegex(ValueError, 'not overwritten'):
+ keeper.prepare()
+ command.assert_not_called()
+ self.assertEqual(edit.read_text(), 'keep this')
+
+ def test_port_collision_is_rejected(self):
+ (self.here / '.env').write_text('KEEPER_RELAY_PORT=3003\n')
+ with self.assertRaisesRegex(ValueError, 'distinct ports'):
+ keeper.settings()
+
+ def test_metro_port_is_reserved_for_each_backend_service(self):
+ for service in ('RELAY', 'CHANNEL', 'SIGNING'):
+ with self.subTest(service=service):
+ (self.here / '.env').write_text(f'KEEPER_{service}_PORT=8081\n')
+ with self.assertRaisesRegex(ValueError, 'reserved for Metro'):
+ keeper.settings()
+
+ def test_invalid_two_fa_requires_the_pinned_token_failure(self):
+ with patch.object(verify, 'request', return_value={
+ 'err': 'Validation failed: verification token is either invalid or has expired'}):
+ verify.verify_invalid_two_fa('3003', {'id': 'disposable-signer'})
+ for unrelated in ({'err': 'Unauthorized request'}, {'err': 'Invalid request schema'},
+ {'valid': False}, {'valid': True}):
+ with self.subTest(response=unrelated):
+ with patch.object(verify, 'request', return_value=unrelated):
+ with self.assertRaisesRegex(RuntimeError, 'unrelated error'):
+ verify.verify_invalid_two_fa('3003', {'id': 'disposable-signer'})
+
+ def test_fetch_failure_explains_public_revision_and_cleans_temporary_checkout(self):
+ (self.here / 'sources.lock.json').write_text(json.dumps({'relay': {
+ 'assets': {}, 'url': 'https://github.com/example/private-backend.git',
+ 'revision': 'a' * 40}}))
+ with patch.object(keeper, 'run', side_effect=[
+ None, None, subprocess.CalledProcessError(128, ['git', 'fetch'])]):
+ with self.assertRaisesRegex(ValueError, 'pinned public backend revision'):
+ keeper.prepare()
+ self.assertEqual(list((self.here / '.sources').iterdir()), [])
+
+ def test_signing_prepare_does_not_fetch_relay(self):
+ (self.here / 'sources.lock.json').write_text(json.dumps({
+ 'relay': {'assets': {}, 'url': 'https://github.com/example/private-relay.git', 'revision': 'a' * 40},
+ 'signing': {'assets': {}, 'url': 'https://github.com/example/public-signing.git', 'revision': 'b' * 40},
+ }))
+ with patch.object(keeper, 'run', side_effect=[
+ None, None, subprocess.CalledProcessError(128, ['git', 'fetch'])]) as command:
+ with self.assertRaisesRegex(ValueError, 'pinned public backend revision'):
+ keeper.prepare(only='signing')
+ self.assertEqual(command.call_count, 3)
+ self.assertIn('https://github.com/example/public-signing.git', command.call_args_list[1].args[0])
+ self.assertEqual(list((self.here / '.sources').iterdir()), [])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/dev/local-backend/verify-local.sh b/dev/local-backend/verify-local.sh
new file mode 100755
index 0000000000..04dc216dfb
--- /dev/null
+++ b/dev/local-backend/verify-local.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+set -eu
+exec python3 "$(dirname "$0")/verify.py" "$@"
diff --git a/dev/local-backend/verify.py b/dev/local-backend/verify.py
new file mode 100644
index 0000000000..00922ffea3
--- /dev/null
+++ b/dev/local-backend/verify.py
@@ -0,0 +1,206 @@
+#!/usr/bin/env python3
+"""Exercise disposable local fixtures, never a hosted backend or real wallet."""
+import argparse
+import base64
+import hashlib
+import hmac
+import json
+import re
+import struct
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+import uuid
+
+from keeper import compose, settings
+
+
+def require(condition, description):
+ if not condition:
+ raise RuntimeError(description)
+
+
+class NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, *args, **kwargs):
+ raise RuntimeError('Local check refused an HTTP redirect')
+
+
+def request(port, path, data=None, expected=200):
+ req = urllib.request.Request(f'http://127.0.0.1:{port}{path}',
+ data=None if data is None else json.dumps(data).encode(),
+ headers={'Content-Type': 'application/json', 'appversion': '2.5.15',
+ 'os': 'ANDROID', 'HEXA-ID': 'keeper-local-only'})
+ try:
+ response = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()).open(req, timeout=20)
+ except urllib.error.HTTPError as error:
+ response = error
+ with response:
+ statuses = expected if isinstance(expected, tuple) else (expected,)
+ require(response.code in statuses, f'{path}: expected HTTP {expected}, got {response.code}')
+ body = response.read().decode()
+ return body if path.startswith('/socket.io/') else json.loads(body)
+
+
+def token(secret):
+ key = base64.b32decode(secret + '=' * (-len(secret) % 8))
+ digest = hmac.new(key, struct.pack('>Q', int(time.time()) // 30), hashlib.sha1).digest()
+ offset = digest[-1] & 15
+ return str((struct.unpack('>I', digest[offset:offset + 4])[0] & 0x7fffffff) % 1000000).zfill(6)
+
+
+def health(relay, signing):
+ for port in (relay, signing):
+ result = request(port, '/health')
+ require(result.get('ready') is True and result.get('mode') == 'local' and
+ result.get('network') == 'TESTNET', 'Expected healthy local TESTNET service')
+ require(result['capabilities']['pushDelivery'] is False, 'Push must be disabled')
+ require(request(signing, '/health')['capabilities']['scheduledJobs'] is False, 'Scheduled jobs must be disabled')
+ print('PASS local/testnet health and disabled cloud capabilities')
+
+
+def boundaries():
+ cases = [('relay', 'BITCOIN_NETWORK=MAINNET', 'LOCAL_DEV requires'),
+ ('relay', 'DATABASE_URL=mongodb://example.invalid/keeper_local', 'LOCAL_DEV requires'),
+ ('signing', 'ENVIRONMENT=MAIN', 'Local signing requires'),
+ ('signing', 'LOCAL_DATABASE_URL=mongodb://example.invalid/keeper_signing_local', 'Local signing requires')]
+ for service, override, message in cases:
+ try:
+ compose('run', '--rm', '--no-deps', '-e', override, service, 'node', '-e',
+ "require('./dist/config')", capture_output=True, text=True)
+ except subprocess.CalledProcessError as error:
+ require(message in error.stdout + error.stderr, f'{service}: failed for an unexpected reason')
+ else:
+ raise RuntimeError(f'{service}: unsafe configuration was accepted')
+ print('PASS mainnet and hosted database configuration rejected')
+
+
+def backup_roundtrip(relay, fixture):
+ snapshot = request(relay, '/getBackupSnapshot', {'appId': fixture})
+ require(snapshot.get('exists') is True and
+ re.fullmatch(r'[a-f0-9]{64}', snapshot.get('revision', '')),
+ 'Created app backup snapshot unavailable')
+ replacement = {'appId': fixture, 'publicId': fixture, 'version': '2.6.3',
+ 'expectedRevision': snapshot['revision'],
+ 'walletObject': {'qa': 'synthetic-encrypted-wallet'},
+ 'signersObject': {}, 'vaultObject': {}, 'nodes': [], 'labels': []}
+ result = request(relay, '/repairAppBackup', replacement)
+ require(result.get('updated') is True, 'Revisioned backup repair failed')
+ repaired = request(relay, '/getBackupSnapshot', {'appId': fixture})
+ require(repaired.get('revision') != snapshot['revision'] and
+ repaired.get('appImage', {}).get('wallets', {}).get('qa') ==
+ replacement['walletObject']['qa'], 'Backup repair did not persist its image')
+ stale = dict(replacement, walletObject={'qa': 'stale-replacement-must-not-persist'})
+ result = request(relay, '/repairAppBackup', stale, expected=409)
+ require(result.get('updated') is False and result.get('error') == 'BACKUP_CHANGED',
+ 'Stale backup revision was accepted')
+ require(request(relay, '/getBackupSnapshot', {'appId': fixture}) == repaired,
+ 'Rejected stale repair changed the backup')
+ print('PASS revisioned backup create/read and stale-revision preservation')
+ changed = dict(replacement, expectedRevision=repaired['revision'],
+ walletObject={'qa': 'second-synthetic-encrypted-wallet'})
+ require(request(relay, '/repairAppBackup', changed).get('updated') is True,
+ 'Second disposable backup image was not saved')
+ second = request(relay, '/getBackupSnapshot', {'appId': fixture})
+ restored = dict(replacement, expectedRevision=second['revision'])
+ require(request(relay, '/repairAppBackup', restored).get('updated') is True,
+ 'Restoring disposable backup content failed')
+ final = request(relay, '/getBackupSnapshot', {'appId': fixture})
+ require(len({repaired['revision'], second['revision'], final['revision']}) == 3 and
+ final['appImage']['wallets'] == repaired['appImage']['wallets'],
+ 'A backup revision repeated after its content changed and returned')
+ obsolete = dict(changed, expectedRevision=repaired['revision'])
+ require(request(relay, '/repairAppBackup', obsolete, expected=409).get('error') ==
+ 'BACKUP_CHANGED', 'An obsolete revision was accepted after content returned')
+ require(request(relay, '/getBackupSnapshot', {'appId': fixture}) == final,
+ 'Rejected obsolete repair changed the restored backup')
+ print('PASS restored content retains a new revision and rejects obsolete repairs')
+ return final
+
+
+def verify_invalid_two_fa(signing, auth):
+ rejected = request(signing, '/v3/validateSingerSetup',
+ dict(auth, verificationToken='abcdef'), expected=400)
+ require(rejected.get('err') ==
+ 'Validation failed: verification token is either invalid or has expired',
+ 'Invalid 2FA check returned an unrelated error')
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--persistence', action='store_true', help='Recreate this Compose stack, retaining volumes, and recheck fixtures')
+ parser.add_argument('--boundaries', action='store_true', help='Check startup rejection of mainnet and external databases')
+ args = parser.parse_args()
+ config = settings()
+ relay, channel, signing = (config[f'KEEPER_{key}_PORT'] for key in ('RELAY', 'CHANNEL', 'SIGNING'))
+ health(relay, signing) # Must pass before any mutations.
+ handshake = request(channel, '/socket.io/?EIO=4&transport=polling')
+ require(handshake.startswith('0') and json.loads(handshake[1:]).get('sid'), 'Socket.IO handshake failed')
+ print('PASS Socket.IO handshake')
+ unavailable = request(relay, '/local-unavailable-probe', {}, expected=503)
+ require(unavailable.get('error') == 'LOCAL_INTEGRATION_UNAVAILABLE', 'Unavailable route silently succeeded')
+ print('PASS unsupported integration fails explicitly')
+ fixture = 'contributor-smoke-' + uuid.uuid4().hex
+ created = request(relay, '/createNewApp', {'publicId': fixture, 'appID': fixture})
+ require(created.get('created') is True, 'App record creation failed')
+ # Existing relay acknowledges creation before its app save callback completes.
+ # Poll the non-throwing subscription endpoint before retrieving the app image.
+ for attempt in range(20):
+ subscription = request(relay, '/getSubscriptionDetails', {'id': fixture, 'appID': fixture})
+ if subscription.get('currentSubscription'):
+ break
+ time.sleep(0.25)
+ else:
+ raise RuntimeError('Created app did not become readable within 5 seconds')
+ app = request(relay, '/getAppImage', {'appId': fixture})
+ require(app.get('appImage', {}).get('appId') == fixture and
+ app['appImage'].get('publicId') == fixture and app['appImage'].get('_id'),
+ 'Persisted app record round trip failed')
+ print('PASS relay app record create/read')
+ backup = backup_roundtrip(relay, fixture)
+ app = request(relay, '/getAppImage', {'appId': fixture})
+ rejected = request(signing, '/v3/setupSigner', {'HEXA_ID': 'invalid'}, expected=400)
+ require(rejected.get('err') == 'Unauthorized request', 'Signing authorization failed')
+ result = request(signing, '/v3/setupSigner', {'HEXA_ID': 'keeper-local-only', 'policy': {'verification': {'method': 'TWO_FA'},
+ 'restrictions': {'none': True, 'maxTransactionAmount': None, 'timeWindow': None},
+ 'signingDelay': None}})
+ require(result.get('setupSuccessful') is True, 'Signer setup failed')
+ data = result['setupData']
+ require(data['bhXpub'].startswith('tpub'), 'Signer must use testnet public key')
+ secret = data['verification']['verifier'] # Disposable fixture; never print or write to source.
+ auth = {'HEXA_ID': 'keeper-local-only', 'id': data['id'], 'verificationToken': token(secret)}
+ # Pinned backend uses a save callback here too; wait only for record visibility.
+ for attempt in range(20):
+ result = request(signing, '/v3/validateSingerSetup', auth, expected=(200, 400))
+ if result.get('valid') is True:
+ break
+ require(result.get('err', '').startswith('Singer not found'), 'Valid 2FA token rejected')
+ time.sleep(0.25)
+ auth['verificationToken'] = token(secret)
+ else:
+ raise RuntimeError('Created signer did not become readable within 5 seconds')
+ verify_invalid_two_fa(signing, auth)
+ print('PASS testnet signer setup, authorization and valid/invalid 2FA')
+ if args.persistence:
+ compose('down')
+ compose('up', '-d', '--wait', '--wait-timeout', '180')
+ health(relay, signing)
+ require(request(relay, '/getAppImage', {'appId': fixture}) == app, 'App data changed after recreation')
+ require(request(relay, '/getBackupSnapshot', {'appId': fixture}) == backup,
+ 'Revisioned backup changed after recreation')
+ auth['verificationToken'] = token(secret)
+ restored = request(signing, '/v3/fetchSignerSetup', auth)
+ require(restored.get('valid') is True and restored.get('xpub') == data['bhXpub'], 'Signing identity changed after recreation')
+ print('PASS database and signing identity persist after container recreation')
+ if args.boundaries:
+ boundaries()
+ print('Local backend checks passed. Disposable records retained in this project\'s local volumes.')
+
+
+if __name__ == '__main__':
+ try:
+ main()
+ except Exception as error:
+ print(f'FAIL: {error}', file=sys.stderr)
+ sys.exit(1)
diff --git a/docs/7066-protected-backup-correction.md b/docs/7066-protected-backup-correction.md
new file mode 100644
index 0000000000..8de4b3b9e5
--- /dev/null
+++ b/docs/7066-protected-backup-correction.md
@@ -0,0 +1,246 @@
+# Protected-backup and Version History follow-up — #7066 / #7067
+
+## Source and scope
+
+This patch uses the owner-designated completed R5 implementation source
+`77b72da29ac5f2cdf3f51c9a0e9f3fd1c2af7238` from [PR #7058](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7058).
+Live records checked on 22 October 2026 show an open draft with `NEEDS_LOCAL`,
+not a publicly released 2.6.5. There is no 2.6.5 GitHub tag/release. The source
+still declares 2.6.4 (Android 627, iOS 620); this patch assigns no version.
+Store publication/availability has not been independently checked. The owner
+reports the App Store showing 2.6.4 after updating, while Keeper's Version History
+still ends at 2.6.3. The actual running binary/build is not established by that
+historical row or by the store listing alone.
+Its ancestry includes released R4 source
+`1d8a86a7462d935cbd0e28b857934b5718c152fc` and `sprint`
+`def0d6a90c80287edb4f58ae272cbfc340f00d73`.
+
+Work runs in the selected **Bitcoin Keeper** managed environment, in a separate
+worktree and `codex/7066-protected-backup-correction` branch. Explicit fetch
+successfully obtained the R5 commit missing from the previous stale attempt.
+Live searches found no other #7066 PR/implementation. R5 and the original
+checkout remain unchanged. The PR targets `sprint` per AGENTS.md and links a
+patch-only comparison from the exact R5 SHA.
+
+The provisional code/test estimate was 5k–10k changed tokens; the first backup
+patch measured approximately 12.1k, including workflow/privacy regressions and
+the supplemental current-backend witness. The owner subsequently authorized the
+stale Version History correction in the same follow-up (called the "5.1 patch"
+in the conversation). The revised estimate is approximately 16k–17k code/test
+tokens. This is a scope label, not a new app release version. No legacy all-copy
+purge, protocol redesign, release change, or parked investigation is included.
+
+## Evidence and limits
+
+The [current Relay production receipt](https://github.com/KeeperCommunity/bitcoin-keeper-relay/pull/158#issuecomment-6321195858)
+reports selected source `29597b27eeeb299205bf7d0555db0a90c38cc4be` and 14 hosted
+protocol checks passing on 21 October after correcting a storage-readiness
+probe. The current app and Relay v3 signing, namespace, projection, revision,
+generation, epoch and tombstone contracts agree on inspection. The hosted
+checks used a fresh synthetic namespace; they do not establish this upgraded
+iPhone's backup state. No production operation is performed for this patch.
+
+An enabled never-enrolled installation has only a read-only Check Again action
+on the baseline status screen. Repeated reads leave that state unchanged and
+cannot finish enrollment. Existing accounts can retain automatic-backup consent
+while their legacy encrypted copy has never been enrolled into v3. The backend
+intentionally does not adopt a legacy copy as a protected backup. The patch
+exposes Back Up Now through the existing explicit repair path, preserving its
+account/session, consent, conflict, upload acknowledgement and complete readback
+guards. Check Again still never enrolls or uploads. Disabled/deleted/conflicting
+states do not silently repair or recreate a protected copy.
+
+The same action is available for the generic unverified state. This is a direct
+retry route; it is not evidence that every unverified state was permanently
+stuck. For example, after a committed enrollment with a lost reply, a later
+read can report different, where the baseline already offered backup. The
+failing-before UI controls specifically cover enabled never-enrolled and
+unverified states; the supplemental service witness separates those schedules.
+
+An authenticated, validated never-enrolled result is absence of a protected
+namespace, not evidence of deletion. Delete remains non-success in that case;
+the UI explains the absence instead of showing the generic uncertain-deletion
+message. It neither creates a namespace to delete nor deletes legacy copies.
+Authorization, network, invalid/incomplete readback and uncertain mutation
+results remain failures.
+
+The screenshot's generic unverified state does not establish which request
+failed. The original phone's cause and corrected behavior remain **unconfirmed**.
+The user can reveal the latest bounded diagnostic on the status screen: fixed
+operation/stage/category, HTTP error status when available, elapsed milliseconds,
+and app version/build. This result exists only in memory for the selected account
+session and is cleared on account changes/new operations. It never displays or
+persists caught errors, request/response bodies, headers, identifiers, ciphertext
+or recovery contents. Do not request raw logs to fill the remaining evidence gap.
+
+## Owner-added Version History correction
+
+The app's history list reads local Realm records; it is separate from both the
+App Store listing and the running binary's native version/build. Source diagnosis
+found a shared Redux version controlling account-specific upgrades, an unguarded
+last-row access, and a comparison of only the last build number. Those conditions
+can skip a selected account's upgrade, fail on missing history, or leave a stale
+marketing-version row when build numbers match. They are reproducible source
+defects, not confirmation of the original phone's precise cause.
+
+Use the selected account's valid persisted version for migration decisions,
+retaining the legacy fallback only when that account version is absent. That
+fallback cannot establish a current account or justify an observation by itself.
+Compare
+the complete native version/build tuple when reconciling history. A missing
+current row can be recorded as a current installation observation only after a
+successful upgrade or when that account is already current. Preserve existing
+recovery/installation rows and dates; do not fabricate a successful transition
+after a failed migration or grant backup verification. Account/session ownership
+and atomic migration rollback remain required.
+
+The Version History screen separately labels the running native version/build
+as **Installed app version**. Historical rows are retained as historical evidence,
+including when they disagree with the running version. The store listing must
+never supply a fabricated installed version.
+
+Native acceptance for this addition:
+
+- Upgrade a disposable 2.6.3 account and verify the installed native version/build,
+ account version and history entry after normal unlock. Repeat with another
+ account that has already advanced the shared version value.
+- Test empty/stale history, the same build across different marketing versions,
+ build-only changes, repeated cold launches, and an existing Recovered Wallet
+ record. No duplicates, invented upgrade dates, or overwritten recovery labels.
+- Inject a failed local migration and switch A → B → A during the operation.
+ Failure must not append a success/observation row for the attempted upgrade or
+ write another account/session. Backup consent/readback semantics stay intact.
+- Check the installed-version label and history on iOS/Android at small width and
+ larger text. On the owner's phone, only normal navigation/reopen/unlock and
+ reading version/build are permitted; no reset, reinstall or recovery operation.
+
+## Targeted native acceptance
+
+Run on the exact final PR head, with the actual compatible backend selected and
+recorded. Use disposable accounts and installations for every destructive step.
+Record IOS, ANDROID and HARDWARE results separately, including build/backend
+identity and any step not run. JavaScript, Linux Realm and fixture results do
+not constitute native or original-phone acceptance.
+
+1. Create an older-account fixture with synthetic recovery contents and legacy
+ encrypted server copies. Retain saved automatic-backup consent when upgrading
+ through 2.6.4 to the patch; use the native app's persisted storage. Include
+ wallets, keys, a vault, node and label/metadata as applicable. Check the fresh
+ account separately as a control.
+2. Interrupt an enrollment/upload or use the demonstrated failing path. Confirm
+ enabled and unverified are distinct facts. Check Again only reads. Back Up Now
+ explicitly retries through the guarded repair, then requires an acknowledged
+ upload plus authenticated complete matching readback. An uncertain reply must
+ not claim Verified. A remote recovery conflict must preserve both copies.
+3. Reopen/cold launch the same account and recheck. Make an ordinary backup-relevant
+ metadata change, confirm it reaches the protected copy, and recheck again.
+4. Recover the disposable protected backup into a separate disposable installation.
+ Verify complete expected recovery contents and restored consent remaining off
+ until the established explicit choice. Never restore over the owner's phone.
+5. Turn off automatic backup. Confirm no copy was deleted and status checking
+ remains read-only. Separately re-enable and verify backup, then delete the
+ disposable protected copy. Require fresh confirmed tombstone/readback, auto
+ off, and unchanged local recovery contents. Fresh-read the deleted state and
+ explicitly recreate; deleted protected records must not resurrect. Older
+ read-only encrypted copies may remain.
+6. Check missing enrollment, authorization failure, interrupted request and
+ malformed/incomplete readback. No error may become Verified/Deleted. Repeat
+ while switching A → B → A; stale work and diagnostics must not bind to the new
+ account/session. Revoke consent while backup runs and check the result.
+7. On iOS and Android, check More, backup status and the affected enable/delete
+ dialogs in light/dark themes, small width (320–360 logical pixels) and larger
+ system text. Both long actions must wrap, remain fully readable and tappable;
+ the explanatory copy must be complete. Scroll through persistent feedback
+ without obscuring bottom navigation. Check retained-copy notice spacing,
+ progress/disabled actions, diagnostic show/hide and accessibility labels.
+
+## Original working iPhone — non-destructive only
+
+Before an approved corrected build is available, capture only version/build from
+About and, if available, the user-initiated fixed diagnostic from a normal Check
+Again. Share only the bounded fields listed above, never screenshots containing
+account details or raw logs. After the approved build/backend pair is available,
+use normal Back Up Now and Check Again, then reopen/recheck. The owner must confirm
+that successful verification persists. Do not reset, uninstall, restore over,
+delete a backup, or export private recovery data on that phone as a diagnostic.
+
+Keep #7066 open until disposable native acceptance and original-phone confirmation
+are complete. No merge, signing, distribution, deployment or publication is
+authorized by this patch or by a passing Cloud check.
+
+## Reproduce the supplemental upgrade witness
+
+Use Node 22.23.3+, frozen app dependencies with repository patches, the genuine
+Realm 12.15.0 Linux/macOS N-API binding, a clean separately obtained Relay checkout
+at `29597b27eeeb299205bf7d0555db0a90c38cc4be` with frozen dependencies and
+`npm ci --ignore-scripts --prefix tests/proof-tools`, and a disposable loopback
+Mongo replica set on port 27038. The wrapper verifies exact source hashes and
+driver versions; it leaves the historical proof runner/pins unchanged.
+
+```sh
+KEEPER_PROTECTED_RELAY_CHECKOUT=/absolute/path/to/current-relay \
+BACKUP_TEST_MONGO_URL=mongodb://127.0.0.1:27038 \
+node scripts/run-protected-upgrade-regression.cjs
+```
+
+The witness uses actual persisted Redux consent, encrypted native Realm, signed
+HTTP, current Relay and disposable Mongo: old legacy account → cold rehydration
+and upgrade → never-enrolled read/delete non-success → interrupted enrollment
+reply → read-only recheck → explicit repair and complete comparison → disable
+retains copies → protected deletion/tombstone → explicit recreation. It checks
+that legacy and local recovery contents survive. It is a host integration proof,
+not native app or original-phone acceptance.
+
+In this Cloud environment execution is **BLOCKED**: the native Realm binding is
+absent and `prebuild-install --runtime napi --target 6` received proxy CONNECT
+403 from `static.realm.io`. No cached binding or official GitHub release asset
+was available. No network-policy bypass, mock substitute, or passing upgrade
+proof is claimed. Syntax and exact-current-source admission/wrong-head rejection
+were checked. Native acceptance must complete this witness and the matrix above.
+
+## Actual Cloud checks
+
+Node 22.23.3 / Yarn 1.22.22; frozen install and all six repository patches PASS.
+Package, lockfile, Pod inputs and version consistency remain unchanged.
+
+| Check | Actual result |
+| --- | --- |
+| `npm run test -- --runInBand --coverage=false` | PASS after history addition: 49 suites, 553 tests, zero skips/failures |
+| `node --test tests/recovery/backupDiagnostic.test.cjs tests/recovery/transport.test.cjs tests/recovery/repair.test.cjs` | PASS: 70 tests, zero skips/failures |
+| UI interaction suite | PASS: 12; exact-baseline controls FAIL 2 assertions, 10 deliberately deselected (enabled never-enrolled and unverified backup action absent) |
+| Diagnostic baseline controls | FAIL: all 9 before; PASS: all 9 after; these establish diagnostic coverage, not the phone's request cause |
+| `npm run test:recovery` | FAIL after history addition: 492 pass, one test-file load failure (493 total), zero skips; missing Realm binding prevents the 10 encrypted-Realm scenarios from loading |
+| History reconciliation and upgrade/login tests | PASS: 27 Node cases (13 new); Version History Jest PASS: 9; exact-before controls FAIL: 4 actual-login cases and one actual-migration preservation case |
+| Installed-version header | PASS: 2 UI regressions; both FAIL before; native version/history disagreement tested in both directions without rewriting rows |
+| Supplemental current-backend upgrade witness | BLOCKED by missing Realm native binding; no passing upgraded-account integration claim |
+| Current Relay protected/legacy protocol tests on disposable Mongo | PASS: 45; readiness tests PASS: 7; backend only, not upgraded-app acceptance |
+| Whole ESLint | FAIL: 4450 errors / 882 warnings; R5 baseline 4451 / 882, first patch 4450 / 882; normalized zero added by the history addition |
+| Whole TypeScript | FAIL: 943 diagnostics; exact baseline 943; normalized zero added/removed |
+| Focused backup service ESLint | PASS: zero errors/warnings |
+| CI USDT/retired-configuration guard command | FAIL: 30 pass / 11 fail, all 11 require unavailable Ruby |
+| `npm run test:release` | FAIL at Ruby stage (exit 127); preceding Node 28 and Python 7 tests PASS |
+| Local-validation/protected-runner contract tests | PASS: 14 |
+| Android static/reproducibility Python tools | PASS: 31 |
+| Version, JSON parsing, new proof/runner syntax, whitespace | PASS |
+| iOS / Android app build, simulator/emulator, physical phone | NOT RUN; required exact-head native handoff remains NEEDS_LOCAL |
+
+The current-backend command, run in its separate exact checkout, was:
+
+```sh
+KEEPER_APP_SOURCE=/absolute/path/to/keeper-patch \
+BACKUP_TEST_MONGO_URL=mongodb://127.0.0.1:27038 \
+node --test tests/protectedBackup.test.cjs tests/legacyBackupReadOnly.test.cjs
+```
+
+The task-owned disposable Mongo container is stopped; its data/evidence are
+retained. Passing backend checks do not replace the blocked upgraded-account
+witness. Existing formatting/lint/type failures are reported, not waived. No
+independent cryptographic certification or release clearance is claimed.
+
+The history before-controls use isolated source
+`3c5f8d8ace5c211ed78264b1a460c4e06e060ceb` (before the owner-added history
+correction). The current-backend 45+7 results and release/tooling results were
+executed for that first patch and retained as prior evidence; they were not
+rerun after the history-only addition. Current full Jest/recovery, lint/type,
+version/input and targeted history checks are reported separately above. IOS,
+ANDROID, HARDWARE and the original phone still require exact-head acceptance.
diff --git a/docs/r5-cloud-administrator-setup.md b/docs/r5-cloud-administrator-setup.md
new file mode 100644
index 0000000000..c3c270283f
--- /dev/null
+++ b/docs/r5-cloud-administrator-setup.md
@@ -0,0 +1,174 @@
+# Cloud release administrator and custodian setup
+
+This is a reviewable setup specification, **not authorization to apply it or run
+release workers**. No setup, credential change, signing, upload, merge or
+deployment is performed by this document. Use hosted Cloud infrastructure and an
+existing authorized custodian; no personal Mac or keychain export is required.
+The [operator handoff](r5-protected-release-handoff.md) retains the package ledger
+and native/provenance blockers.
+
+The latest successful read-only inventory on 22 October 2026 returned only
+`copilot`, `Env` and `keeper-claude-review`. Both proposed release environments
+were absent. Earlier secret-name and variable-name API reads returned HTTP403;
+custody and credential readiness are **UNKNOWN**, not proven absent. The managed
+task has no configured release credentials. Neither an environment name nor a
+secret name proves a usable signing/store identity.
+
+## Administrator specification
+
+After separately approved administration, configure exactly
+`keeper-release-ios` and `keeper-release-android` in
+`KeeperCommunity/bitcoin-keeper`. The current
+[gate](../scripts/protected-release-plan.cjs) requires the following metadata for
+each environment:
+
+```json
+{
+ "can_admins_bypass": false,
+ "protection_rules": [
+ {
+ "type": "required_reviewers",
+ "prevent_self_review": true,
+ "reviewers": [""]
+ }
+ ],
+ "deployment_branch_policy": {
+ "protected_branches": true,
+ "custom_branch_policies": false
+ }
+}
+```
+
+This is a shape specification, not a GitHub API write payload. Use actual approved
+reviewer IDs and verify that the requester cannot approve their own deployment.
+The gate expects exactly one required-reviewers rule with at least one reviewer.
+Custom branch-name rules alone fail this gate. Protected-branches-only permits
+protected branches as a class; it does not prove exact-source authorization.
+The driver additionally requires `refs/heads/sprint`, its current protected SHA,
+and a protected `release/` ref at the requested source. Signed-build
+source must equal the installed canonical driver SHA. Keep those code checks.
+
+Install source only through separately approved review/merge. Read back the
+effective rules for `sprint` and the intended `release/` ref, including
+actor/bypass scope and force-push/deletion controls. Require `Tests` and
+`keeper/local-validation` for `sprint` as AGENTS.md specifies; retain the actual
+security/native requirements and applicable review policy. A reported check is
+not protected enforcement. Record a secret-free negative-control plan proving
+wrong ref/source, absent independent review, self review, and bypass attempts
+cannot reach a credential-bearing step. Perform that plan only under its own
+approved infrastructure-testing scope. Do not weaken rules to make a test pass.
+
+The canonical producer #7084 additionally reads the nonsecret Actions variable
+`KEEPER_CANONICAL_NATIVE_DRIVER_SHA`; its value must be the full reviewed current
+protected canonical driver SHA and the selected source must equal it. The
+workflow has no environment, so provide this separately approved pin at a scope
+visible to that workflow and verify its live read-only API visibility rather than
+assuming environment variables supply it. Successor
+[#7095](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7095),
+`effd9175c00ebbdbaf616813a3ecfa6886bbbf45`, fixes the candidate's default-token
+Variables-read incompatibility. Its separate installation requirement is the
+repository secret **`KEEPER_CANONICAL_PIN_READ_TOKEN`**: a finite-expiry fine-grained
+PAT with resource owner KeeperCommunity, selected repository only `bitcoin-keeper`,
+**Variables: Read-only** (`actions_variables=read`) plus automatic Metadata read.
+Obtain organization approval if required; no broad classic PAT or write/admin
+rights. Require a live GET200 of the exact named variable/reviewed SHA under that
+identity. The default token remains for the other read endpoints; no cached pin
+or default-token fallback is acceptable. Explicit reusable alias
+`canonical_pin_read_token` is step-scoped and removed before subprocesses. During
+later authorized rotation revoke the old PAT; replacing the stored secret does
+not revoke an already running token. This identity is not provisioned/live-tested
+here. Review/adopt #7095 separately; it is not installed or included in this
+reconciliation branch. Pin/credential creation or update is not authorized here.
+The #7085 consumer is not an authorization integration. Keep B1's
+private origin capability unminted and all authorization flags false until
+genuine canonical evidence, security linkage and enforcement are established.
+
+## Exact protected names and operation scope
+
+These names come from the current
+[workflow](../.github/workflows/keeper-protected-release-workers.yml) and
+[adapter README](../release/cloud/README.md). Provisioning or copying values is
+outside this task. Record the custodian and approved scope privately; place no
+values, private files or key material in issues, PRs, requests, logs or artifacts.
+
+| Environment | Kind | Exact names | Used only for |
+| --- | --- | --- | --- |
+| Both | Variable | `KEEPER_RELEASE_CERT_SHA256`, `KEEPER_PRODUCTION_CONFIG_SHA256` | Independent lowercase SHA256 identity/config pins; also bound to owner receipt |
+| Both | Secret | `KEEPER_PRODUCTION_CONFIG_BASE64` | Signed build's reviewed client-safe dotenv bytes; no signing/store/server secret embedded |
+| iOS | Variable | `KEEPER_IOS_TEAM_ID`, `KEEPER_IOS_PROFILE_UUID` | Existing production team/profile binding |
+| iOS | Secret | `KEEPER_IOS_P12_BASE64`, `KEEPER_IOS_P12_PASSWORD`, `KEEPER_IOS_PROFILE_BASE64` | `ios-signed-build` only |
+| Android | Secret | `KEEPER_ANDROID_KEYSTORE_BASE64`, `STORE_PASSWORD`, `KEY_PASSWORD`, `KEY_ALIAS` | `android-signed-build` only |
+| iOS | Secret | `KEEPER_ASC_KEY_ID`, `KEEPER_ASC_ISSUER_ID`, `KEEPER_ASC_KEY_BASE64` | `testflight-upload` only |
+| Android | Secret | `KEEPER_PLAY_SERVICE_ACCOUNT` | `play-internal-upload` only |
+
+Signing steps must not load upload credentials; upload steps must not load
+signing credentials. Keep the existing step-scoped references, credential-free
+frozen dependency setup, and fresh revalidation after environment review,
+immediately before secret loading and at adapter entry. Do not use repository or
+organization secret fallbacks to bypass an absent/protected environment.
+
+## Custodian metadata acceptance
+
+Use existing vault inventories, public certificates/profile metadata and
+authorized read-only store consoles/API reports. This task does not authorize
+credential retrieval, private-key export, provider login, certificate issuance,
+key rotation, provisioning changes or an upload to test access. Redact account
+emails, subject names and unrelated organization details from public evidence.
+
+| Boundary | Safe metadata to verify and record | Current result |
+| --- | --- | --- |
+| iOS distribution identity | Independent SHA256 of public certificate DER, distribution type, team and expiry/revocation state; custodian confirms matching existing private-key custody without exporting it | UNKNOWN |
+| iOS profile | Existing UUID/team, app identifier `TEAM.io.hexawallet.keeper`, App Store distribution type, certificate inclusion, entitlement compatibility, `get-task-allow:false`, no provisioned-device list or enterprise all-device flag; certificate/profile valid beyond the intended operation plus two hours | UNKNOWN |
+| Android upload identity | Independent SHA256 of public upload certificate DER, expiry, custodian-confirmed existing authorized keystore/alias custody; match Play Console's **upload** certificate and separately record App Signing certificate continuity | UNKNOWN |
+| App Store Connect | Existing app/bundle `io.hexawallet.keeper`, approved team/issuer/key identity and least-privileged app access, active agreements, complete fresh uploaded version/build history including processing/nonpublic builds | UNKNOWN |
+| Google Play | Existing package `io.hexawallet.bitcoinkeeper`, approved service-account app/internal-track rights, required API access/agreements, complete fresh version-code/track history including drafts | UNKNOWN |
+| Production configuration | Owner-reviewed allowlisted client configuration and independent exact-byte SHA256; no private values in public evidence; full built-binary config readback remains a separate unverified acceptance item | UNKNOWN |
+
+Fingerprint pins must come from independent approved metadata, not solely from
+the artifact being checked. Secret existence, successful SDK authentication or a
+listed role alone does not prove app/channel authorization or signing readiness.
+Current source inputs are 2.6.4 / iOS620 / Android627. Historical store baselines
+in `release/version.json` are not fresh store acceptance or allocation of new
+counters. The current gate requires fresh complete store/version evidence.
+
+For later operation approval, the owner receipt must bind the exact source and
+driver SHA, operation, version/build, artifact/certificate/config digest, expiry
+and the 14-day GitHub Actions artifact audience. Signed artifacts in this public
+repository can be accessible to authenticated public-repository readers. If that
+audience is not approved, a separately reviewed private transport is required.
+Do not generate an approval on the owner's behalf.
+
+## Safe readback and durable result
+
+The following GET commands project metadata only. Run with already authorized
+Cloud identity and inherited proxy/CA settings. Do not print auth configuration,
+tokens, environment dumps or secret files. Treat403/404 as unavailable evidence;
+a403 never establishes absence.
+
+```sh
+gh api repos/KeeperCommunity/bitcoin-keeper/environments --paginate \
+ --jq '{total_count,environments:[.environments[]|{name,can_admins_bypass,protection_rules,deployment_branch_policy}]}'
+gh api repos/KeeperCommunity/bitcoin-keeper/environments/keeper-release-ios \
+ --jq '{name,can_admins_bypass,protection_rules,deployment_branch_policy}'
+gh api repos/KeeperCommunity/bitcoin-keeper/environments/keeper-release-android \
+ --jq '{name,can_admins_bypass,protection_rules,deployment_branch_policy}'
+gh api repos/KeeperCommunity/bitcoin-keeper/environments/keeper-release-ios/secrets --paginate \
+ --jq '{total_count,secrets:[.secrets[]|{name,created_at,updated_at}]}'
+gh api repos/KeeperCommunity/bitcoin-keeper/environments/keeper-release-android/secrets --paginate \
+ --jq '{total_count,secrets:[.secrets[]|{name,created_at,updated_at}]}'
+```
+
+Variable collection endpoints also return nonsecret **values**. If an approved
+administrator uses them, project only `name`, `created_at` and `updated_at` before
+any output/storage; never retain the raw response or emit the production config.
+Use the existing inventory helper for environment metadata with
+`execution_allowed:false`. Its collection-level restriction summary does not
+verify `can_admins_bypass`, exact allowed source or functioning review enforcement.
+
+Record a bounded readiness receipt: UTC observation time; exact source/driver
+SHA; API route and successful/unavailable outcome; effective rule/reviewer
+metadata; expected name presence only; custodian-owned identity/expiry/app/channel
+checks; store-history freshness; unresolved blockers; and `execution_allowed:
+false`. Actual signing/store operations, hosted cleanup, artifact readback and
+physical/native acceptance remain **NOT RUN / NOT VERIFIED**. Continue with the
+cloud-only operator handoff; never convert this setup receipt into authorization.
diff --git a/docs/r5-cloud-release-readiness.md b/docs/r5-cloud-release-readiness.md
new file mode 100644
index 0000000000..8ae61635be
--- /dev/null
+++ b/docs/r5-cloud-release-readiness.md
@@ -0,0 +1,117 @@
+# R5 protected cloud release preparation
+
+This is the separate Phase B preparation package for [#7061](https://github.com/KeeperCommunity/bitcoin-keeper/issues/7061), following [#7065](https://github.com/KeeperCommunity/bitcoin-keeper/issues/7065). It does not install or execute signing or distribution. **Hosted signing/distribution: NOT IMPLEMENTED / NOT VERIFIED.** The personal Mac is not a prerequisite in the proposed route. Existing app, native acceptance, exact-head gate and physical-device requirements remain separate.
+
+Source inspected: R5 core `77b72da29ac5f2cdf3f51c9a0e9f3fd1c2af7238` and 5.1 `c1c4b803039b61b940373c4dc9d08473cf25e042`, containing released R4 `1d8a86a7462d935cbd0e28b857934b5718c152fc`. This package does not establish whether 5.2 is complete or integrated. App inputs are still 2.6.4 / Android627 / iOS620; no R5 version/build counters are assigned here. Work-package names 5.1 and 5.2 are not versions.
+
+## Verified inventory, 22 October 2026
+
+| Existing source/capability | Evidence and consequence |
+| --- | --- |
+| iOS `build_only` | Calls `get_certificates`, `get_provisioning_profile`, project provisioning and `build_app`; this is a **signed build**, requiring approval before invocation. It is not a safe unsigned preflight. |
+| iOS `live` / `dev` | Invoke TestFlight upload. `dev` also downloads environment configuration and increments a build number. Do not use either as a native test command. |
+| Android `build_only` | Builds signed production AAB/APK using keystore/password inputs and verifies resulting artifact versions. Requires signing approval. |
+| Android `live` | Calls `upload_to_play_store` for the internal track after its build. Internal upload is distribution and requires separate explicit approval. |
+| Android release signing block | Reads keystore/password/alias from environment. No literal production password/alias was found in the inspected release block. Android public debug credentials remain separate. This bounded review is not proof that every historical credential is safe or current. |
+| Protected GitHub environments | Read-only environment API returned `copilot`, `Env`, `keeper-claude-review`. No dedicated iOS/Android release environment was present. No environments or rules were changed. |
+| Secret/variable inventory | Repository secret-name and variable-name API reads returned HTTP403. Contents were never requested. Existing values, owners, scope and usability are **UNKNOWN**, not proven absent. Managed task runtime reports no configured secrets/identities; that does not describe store or repository credentials. |
+| Reviewer route | `keeper-claude-review` exists with a branch policy. This does not prove Claude is enabled, paid capacity approved, review executed or findings resolved. Existing independent/Claude review requirement remains open; no paid request was initiated. |
+
+The read-only helper can refresh bounded source/configuration evidence without reading keys or secret values:
+
+```sh
+python3 scripts/cloud_release_inventory.py --root .
+gh api repos/KeeperCommunity/bitcoin-keeper/environments > /tmp/keeper-environments.json
+python3 scripts/cloud_release_inventory.py --root . --environment-metadata /tmp/keeper-environments.json
+python3 -B -m unittest discover -s scripts -p 'test_cloud_release_inventory.py'
+```
+
+The helper never invokes Fastlane, builds, signs, logs in, uploads, changes configuration or grants permission. Its JSON always has `execution_allowed: false`; a named environment and a reviewer rule cannot prove exact source restriction, credential custody or functioning enforcement. Missing environment metadata stays UNKNOWN. Literal-credential findings include only field/line, never values; investigate any finding through [private vulnerability reporting](../SECURITY.md). This is a narrow source inventory, not a secret scanner or release gate.
+
+## Prepared reusable authorization workflow
+
+The candidate [protected preparation workflow](../.github/workflows/keeper-protected-release-plan.yml) implements manual dispatch, a secret-free trusted-driver authorization job, and a protected environment review boundary. It is **not installed on sprint and was not dispatched**. It has no signing or upload command and passes no production secrets to either job.
+
+The executable [gate](../scripts/protected-release-plan.cjs) requires all of:
+
+- Execution from the current protected `sprint` driver commit; no PR/mutable driver acceptance.
+- An exact immutable candidate SHA at the current protected `release/` head; candidate files are read as data and no candidate script executes.
+- Fresh authenticated-store baseline metadata and consistent package, Android and iOS versions/builds using the existing release-version validator.
+- A current writer-authorized release-owner (`antuz123`) approval comment binding driver SHA, candidate SHA, version/build, specific operation and artifact digest (or `pending` for build preparation), expiring within24hours. An approval for one operation cannot authorize another.
+- The matching protected release environment already configured with independent reviewers, prevented self review, no administrative bypass, and protected-branch restriction. An absent/unreadable environment blocks before the environment job; no implicit unprotected environment is created by a successful path.
+- Exact-head `Tests`, `CodeQL` and `keeper/local-validation` success, with no failed/skipped/in-progress/wrong-SHA check, and complete bounded check evidence. These fixed required names need confirmation against the final installed acceptance route; an unmatched name fails closed.
+
+**Security correction: authorization planning is disabled fail-closed until trusted CI origin is implemented and verified.** A check/status name or bot/app creator alone does not prove the installed workflow ran; same-repository PR workflows may produce misleading status names. The collector currently cannot mint the module-private verified-origin capability, so even otherwise complete synthetic or name-matching evidence cannot produce an authorization plan. No plan or release operation is claimed verified. A separately reviewed exact-canonical/selected-route attestation must bind genuine workflow/run/attempt/source evidence before this boundary can be enabled. Existing failed/security/native checks remain intact; no PR pass transfers to a merge SHA.
+
+The final protected job records the preparation boundary only. Its result always reports `execution_allowed: false`, `release_worker_implemented: false` and `artifact_bytes_and_signature_verified: false`. The artifact approval digest is bound to the request; this preparation package does not download/verify actual release bytes or signatures. Environment selection and shape-valid metadata alone never produce a release pass.
+
+**Future execution workers must revalidate after the protected environment approval**, immediately before any signing or upload: refresh driver/source ref identity, exact-head check and review state, approval author/scope/expiry, fresh store/version baseline, and the actual immutable artifact bytes/digest/signature/provenance. A source movement, new failure, expired/revoked approval or artifact mismatch while waiting blocks execution. The earlier preparation result cannot serve as final execution authorization, and a successful environment review cannot bypass this fresh validation. Artifact verification must use trusted driver code and must not run artifact-provided code.
+
+The owner approval receipt has this exact form (use actual reviewed identities; no receipt is created or requested by this package):
+
+```text
+## Keeper protected release approval
+State: APPROVED
+Source commit:
+Version:
+Build:
+Operation:
+Artifact SHA256: <64-character digest, or pending for signed-build preparation>
+Workflow commit:
+Expires at:
+```
+
+This template is not owner approval. Do not post it on the owner's behalf. Tests use synthetic receipts and perform no remote action. Run the offline contracts with `node --test scripts/protected-release-plan.test.cjs`.
+
+## Remaining execution worker implementation
+
+Implement the actual Phase B signing/artifact/distribution workers in a further separate PR, estimated 5k–10k changed code/test tokens plus platform integration fixes. Trim/split if it approaches 20k or adds another substantial capability. Native acceptance belongs to Phase A. No workflow that can reach signing or stores is installed by this preparation package.
+
+1. A reusable manual release driver, installed on reviewed trusted source, accepts an immutable full source SHA, the approved operation/channel, version/build tuple, and exact evidence/artifact identities. Its initial job has read-only repository permissions and no signing/store secrets. Resolve and compare the source against the reviewed candidate; reject PR merge refs, mutable refs, wrong repositories, stale head/evidence, missing required tests/security/review, and changed inputs. Verify that the workflow driver itself is the installed trusted revision. Do not accept a PR-authored JSON assertion as trusted CI evidence.
+2. Build/test with development/disposable configuration first on hosted macOS/Xcode and Linux Android runners, one native build at a time. Retain source/tree/input identities, exact test run/attempt, platform/tool versions and artifact hashes. Rerun candidate acceptance when source changes. An infrastructure smoke cannot satisfy R5 feature acceptance.
+3. Proposed environments `keeper-release-ios` and `keeper-release-android` restrict deployment source to explicitly reviewed release refs, require an independent named approver, prevent self approval and review administrative bypass policy. Configure least-privileged secrets only after a credential custodian and owner approve provisioning. Test rejection of wrong source and absent approval without secrets before testing signing. Environment creation or selection alone does not establish enforcement.
+4. Sign only after owner approval naming source, version/build, platform and operation. Prefer separate short-lived signing workers with narrowly scoped credentials and transient keychain/keystore storage. Do not run unreviewed PR/dependency scripts with production secrets. Current `build_only` lanes need adaptation and actual hosted verification; iOS automatic certificate/profile acquisition must not create or rotate material implicitly. Preserve Android upload-key and signing-certificate continuity. Do not regenerate keys.
+5. Verify signed artifacts before any upload: source/build manifest, application ID, version/build, SHA256, iOS signing team/profile/entitlements and Android certificate/signature/16KB evidence. Retain provenance and safe receipts. Secret files, recovery data and unredacted native logs must never enter public artifacts or caches. Clean transient signing material as part of the same job, including failure paths, without deleting unrelated caches or owner artifacts.
+6. Upload the verified immutable artifact only after a separate approval for TestFlight or Play internal. An upload worker uses least-privileged channel-specific credentials and the approved artifact digest; it never rebuilds from a moving branch. Compare the returned store-selected version/build/artifact receipt. No production rollout, review submission or public release follows automatically. Each remains a separate explicitly approved operation.
+
+This is a concrete proposed boundary, not proven remote signing capability. Required native/security failures remain blocking; physical-device results must come from actual testers/devices tied to the distributed artifact. No personal Mac session is needed for build, certificate custody service, store API or tester installation in this route.
+
+## One-time setup and custody inventory
+
+All entries below need a named maintainer/custodian and evidence of actual readiness. Do not place values in PRs, task sheets, job inputs or this document.
+
+| Capability | Required input/setup | Observed state / next action |
+| --- | --- | --- |
+| Trusted release source/driver | Approved release ref policy, protected environments, independent approval, exact-SHA evidence/check enforcement | Dedicated environments absent at read; authorization workflow is a candidate, uninstalled/unrun; execution workers unimplemented. Review/approve separate worker PR and administrative rules. No shared-branch promotion authorized. |
+| Apple signing | Existing authorized signing certificate/private-key custody, matching profile and team/entitlements; approve hosted secret/signing-service scope | UNKNOWN. Existing Fastlane acquisition is not proof of authorized custody. Provision through authorized custodian; do not copy a personal keychain or create a new certificate by default. |
+| Apple upload | App Store Connect identity/API key with app/channel privileges, existing app identity and agreements | UNKNOWN. API upload authorization is distinct from code signing. Inventory and test via approved operation; no interactive owner-Mac dependency. |
+| Android signing | Existing upload keystore/service and alias, `STORE_PASSWORD`, `KEY_PASSWORD`, `KEEPER_ANDROID_KEYSTORE`; verify expected certificate fingerprint | UNKNOWN. Current code consumes these names; existence/current validity is unverified. Preserve existing-user update continuity. Play App Signing key is distinct from upload key. |
+| Play internal upload | Existing app/package, least-privileged approved service account, selected internal track/testers, current store counters | UNKNOWN. Existing Appfile refers to a JSON file; no file contents inspected. Move custody into reviewed protected storage only with authorization. |
+| Production app configuration | Reviewed exact allowlist of client-safe fields, production service identities/channel and successful version/config guards | UNKNOWN for R5 signed candidate. `react-native-config` embeds supplied fields: never place server/signing/upload secrets there. Preserve the existing retired-credential rejection. |
+| Artifact retention/provenance | Approved safe retention, authenticated checksums/signature receipts and trusted artifact transport | Source helpers exist; full signed hosted chain NOT VERIFIED. Do not transfer a pass between SHAs. |
+| Physical acceptance | Named trusted testers, actual supported phones/signers, firmware/artifact identity and results | NOT RUN by this package. Emulator biometric simulation cannot establish physical biometrics/NFC/USB/camera/signers. |
+| Independent and Claude review | Applicable approved review route, authorized capacity, exact-source report and finding resolution | Required; execution/approval NOT VERIFIED. No paid usage requested. Preserve inherited security findings and failed checks. |
+
+Before signing, refresh authenticated complete Apple/Play uploaded-build baselines using the existing release-version tooling; do not infer the next counters from current source. Preserve approval and channel receipts separately from native acceptance. No merge, signing, upload, distribution, deployment or publication was performed in this package.
+
+## PHP security research and exposure assessment
+
+The DigitalOcean bulletin itself has not been provided/located; its date alone cannot identify a vulnerability or Keeper exposure. Independent official upstream research did identify two current critical PHP advisories published 21 October 2026:
+
+- [CVE-2026-109618 / GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w), “RCE via OOM corruption”.
+- [CVE-2026-109619 / GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp), “RCE via stale global state”.
+
+Both official advisories list patched branch versions **8.2.35, 8.3.36, 8.4.27, 8.5.12**. The [official 8.5.12 release](https://github.com/php/php-src/releases/tag/php-8.5.12) describes unauthenticated RCE, no complete mitigation and strongly encourages affected PHP8.5 users to update. [Tagged NEWS](https://github.com/php/php-src/blob/php-8.5.12/NEWS) records both fixes; [8.2.35 NEWS](https://github.com/php/php-src/blob/php-8.2.35/NEWS) confirms the backport. This identifies relevant upstream research, **not the missing bulletin's exact contents or an impact determination**.
+
+Read-only complete Git tree and dependency-manifest inspection found:
+
+| Public source audited | Exact source | PHP/Composer evidence |
+| --- | --- | --- |
+| R5 app | `c1c4b803039b61b940373c4dc9d08473cf25e042` | 0 tracked PHP files, 0 Composer manifests; React Native/JS/TS source. No PHP-named direct dependency. |
+| Website | `ddba13bd289e8899b16a6f653cf5c1ea66be6243` | Complete tree193 files; 0 PHP/Composer; React/Vite/Express package manifest. |
+| Public SigningServer | `130d74b5336c40901933d4882db745f0cca811f1` | Complete tree62 files; 0 PHP/Composer; Express/TypeScript package manifest. |
+| Public Relay | `1a6b9ff19c82633a15939ff4e74ccd47d535e534` | Complete tree87 files; 0 PHP/Composer; Node22/Express/TypeScript package manifest. |
+
+Authorized private-service source was also inspected read-only; no PHP/Composer source was observed there. Private paths/source details remain outside this public document. A source tree does not inventory deployed hosts, OS packages, reverse proxies, images, control panels, unrelated WordPress/PHP endpoints or provider-managed runtime. **Keeper exposure remains NOT ESTABLISHED; deployed runtime inventory is UNKNOWN.** No live probing, production account operation, exploit test or configuration change was performed.
+
+Next research step: use existing authorized read-only operator inventory to map relevant deployed assets/images and any installed PHP versions/SAPIs to these advisories; obtain the actual bulletin for correlation. Communicate the evidence and uncertainties to the owner privately. Do not infer “not affected” from JavaScript manifests. R5 owns research/exposure investigation and owner communication only; any resulting PHP remediation and verification is assigned to R6 by the latest scope decision. Confirmed urgent exposure must be brought to the owner promptly without silently implementing or publishing a change.
diff --git a/docs/r5-cloud-ruby-locks.md b/docs/r5-cloud-ruby-locks.md
new file mode 100644
index 0000000000..16a460c861
--- /dev/null
+++ b/docs/r5-cloud-ruby-locks.md
@@ -0,0 +1,34 @@
+# Frozen Ruby compatibility for hosted release workers
+
+This small package resolves the concrete CocoaPods/Xcodeproj mismatch identified while reviewing Phase B2. It pins CocoaPods/core1.16.2 and Xcodeproj1.27.0, matching the selected hosted Xcode16.4 route. The resolver changes only the required Nanaimo0.4.0/REXML3.4.4 closure and records Bundler2.5.22, the resolver supplied by the verified portable Ruby3.3.8 toolchain. Fastlane remains2.225.0; FFI/Ethon/Typhoeus and all unrelated selected gems remain unchanged. No signing/store lane runs during installation or contracts.
+
+Resolution used Bundler conservative update; temporary resolver constraints held unrelated shared dependencies at their original selected versions and were removed before the final local resolution. Actual frozen installation completed for118gems on Ruby3.3.8, `bundle check` passed, and CocoaPods1.16.2/Xcodeproj1.27.0/REXML3.4.4 loaded successfully. Initial local attempts failed on missing development headers and portable linker paths; those failures were resolved with SHA256-authenticated Debian Ruby3.3.8-2 development headers from the existing verified APT snapshot and a task-local portable rbconfig/linker shim. Shared tool configuration and credentials were not changed. This setup is not required on standard hosted ruby/setup-ruby runners.
+
+The inherited root Podfile.lock records CocoaPods1.15.2. The separately reviewed adopted native foundation owns the1.16.2 Podfile.lock; pair these inputs during integration. This package **does not edit/regenerate Podfile.lock or claim a successful CocoaPods install/native build**. The release worker rejects mismatched pairs before credentials. Actual frozen Pod installation/build still requires exact combined hosted validation. Historical `.ruby-version`/lock Ruby3.3.0 metadata is unchanged; the existing >=2.6.10 constraint accepts the explicitly selected/tested hosted Ruby3.3.8 runtime.
+
+The added secret-free contract workflow installs frozen Ruby dependencies, checks their selected versions, parses the existing Xcode project and runs fake Fastlane contracts. It does not invoke CocoaPods installation, xcodebuild, Gradle, signing or a provider upload. No production configuration, keychain, API credential, Mac or release operation was used. Dependency resolution/load is not independent security review or proof of production signing compatibility; preserve unrelated dependency/security findings.
+
+## Isolated reconciliation after #7086
+
+The historical mismatch above is preserved on #7078/#7080/#7086. The separate
+`codex/r5-cloud-release-reconciliation` branch copies exactly `package.json`,
+`yarn.lock` and `ios/Podfile.lock` from native candidate #7082
+`3eb92fc8a622a3e09926d49f47243c163e32d009`, retaining #7078's Gemfile/lock.
+The copied native tuple pins Nitro0.36.5 and CocoaPods1.16.2; no lock was
+regenerated. This preparation branch does not contain all later native app
+changes and is not the full combined app candidate.
+
+`python3 -B scripts/check_cloud_release_inputs.py --root .` now checks the same
+fail-closed Ruby compatibility boundary used by the iOS worker, plus exact
+Nitro agreement across manifest, Yarn resolution and Pod lock. It emits only
+input hashes and preparation flags; alignment is not frozen installation or
+native acceptance. Negative controls preserve rejection of the old mismatch and
+reject drift in each Nitro input without modifying files. The frozen Ruby
+workflow runs this check and those controls when any paired input changes.
+
+Actual frozen118-gem installation/check/load/project parse passed again on this
+reconciled tuple under task-local Ruby3.3.8/Bundler2.5.22. Full combined-source
+`pod install --deployment`, app builds and feature acceptance remain with the
+native owner, in one coordinated hosted window. See the
+[operator handoff](r5-protected-release-handoff.md) for exact source hashes and
+the [administrator/custodian specification](r5-cloud-administrator-setup.md).
diff --git a/docs/r5-cloud-worker-core.md b/docs/r5-cloud-worker-core.md
new file mode 100644
index 0000000000..1adb54b9cd
--- /dev/null
+++ b/docs/r5-cloud-worker-core.md
@@ -0,0 +1,16 @@
+# Protected cloud worker core — Phase B2
+
+This separate core package extends #7072's preparation. It supplies executable future authorization/platform adapters and offline contracts; **no worker workflow entry point or upload Fastfile is installed by this core package alone**. The separate Phase B3 package supplies that orchestration/uploader layer. No signed build, signing credential operation, release workflow dispatch, upload or provider API call was performed while preparing either package.
+
+The trusted driver requires installed canonical source for signing, protected exact source/version/build evidence, fresh exact-owner receipts, pinned certificate/config/artifact identities and post-environment revalidation. Only exact current-run/current-attempt worker checks are excluded to prevent self-deadlock; unrelated failed/pending/security/native checks remain blocking. Native setup admits only a source/hash-bound nodeify mapping overlay, including staged-change protection. Platform adapters verify signatures and metadata, use transient credentials and fail before a success receipt if iOS keychain/profile cleanup fails. Upload producer lineage, payload digest, ZIP traversal/duplicate/symlink rejection and separate operation receipts are included in the contracts.
+
+Actual operation remains **NOT EXECUTED / NOT VERIFIED**. Prerequisites include approved protected environment enforcement/custody, independent security/Claude review, complete exact-canonical native evidence, compatible reviewed frozen native/Ruby inputs, and the separate orchestration layer. Current inherited CocoaPods/xcodeproj locks are explicitly rejected before credentials; no lock regeneration or credential provisioning occurred. A normal PR merge creates a new source SHA: PR-head native passes must never be transferred to canonical source. A separately reviewed exact-canonical attestation route is required before signing can become operational.
+
+The adapters intentionally fail closed if the Phase B3 standalone uploader/installed Phase A helper is absent. They never fall back to legacy dev/live/auto-certificate lanes or to the personal Mac. `protected-release-plan.cjs` remains preparation-only when invoked directly; actual future execution requires the separate protected worker driver. Production configuration/signing/upload material must never be supplied to host tests.
+
+Validation commands (synthetic/fake actions only):
+
+```sh
+node --test scripts/protected-release-plan.test.cjs scripts/protected-release-worker.test.cjs
+python3 -B -m unittest discover -s scripts -p 'test_cloud_release_worker.py'
+```
diff --git a/docs/r5-protected-release-handoff.md b/docs/r5-protected-release-handoff.md
new file mode 100644
index 0000000000..ccb326c5c7
--- /dev/null
+++ b/docs/r5-protected-release-handoff.md
@@ -0,0 +1,237 @@
+# Protected cloud release preparation handoff
+
+This document reconciles the separately reviewable non-app packages. They are
+prepared source candidates, **not installed or operational release capability**.
+No signing, keychain, provider, upload, distribution, release or deployment
+operation has been performed. The primary R5 candidate and all producer branches
+remain unchanged. Work-package labels 5.1/5.2 are not app versions.
+
+## Preserved source checkpoints
+
+| Package | Draft PR / exact commit | Current state and next action |
+| --- | --- | --- |
+| Inventory, authorization preparation and research | [#7072](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7072), `f2fc0cb557f0e5303335dadc9e98152640795e6c` | Preparation complete. Its original estimate and NOT IMPLEMENTED worker state are historical package scope; later packages below supply inert worker candidates. Preserve its source/research evidence. |
+| Origin guard | [#7074](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7074), `76150f455978c1a565f2c670774672bc18789877` | Deliberately disabled. The module-private origin marker is never minted by the collector; caller JSON/status names cannot authorize. Keep disabled pending separately reviewed integration. |
+| Platform worker core | [#7076](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7076), `e195de31ffc38ec54fcee9c43f74e610139d3844` | Implemented future adapters, not executed. Review together with orchestration and the paired canonical native foundation. |
+| Frozen Ruby inputs | [#7078](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7078), `1241256d465d25f2ea2bb4c4e75fccb608ff276e` | Actual frozen118-gem install/load/project parse previously passed. CocoaPods1.16.2/Xcodeproj1.27.0 must be paired with the reviewed native foundation's Podfile.lock; inherited worker-base lock1.15.2 fails before credentials. No native pass follows from dependency loading. |
+| Manual orchestration and upload adapters | [#7080](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7080), `c1e0e6df99eb762d62e31e9d71afa2cb97958bc5` | Prepared, deliberately inoperable through B1. The small follow-up containing this handoff corrects TestFlight processing-path metadata writes; review its patch separately from this preserved producer. |
+| Upload-only successor | [#7086](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7086), `36df64be4ccafc287c0ac07fb911d7e3a1c4711c` | Preserved and included in the isolated reconciliation. Pinned Pilot fake-boundary regression proves the corrected adapter stops before processing/distribution. No provider operation performed. |
+| Canonical native producer | [#7084](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7084), `29a73faaf4312f3536db9aad1d5b6795042aef7d` | Uninstalled/unexecuted. Five parent obligations remain NOT IMPLEMENTED; only blocked readiness can be emitted until genuine complete coverage exists. Read-only capacity admission is not an atomic lock shared with legacy routes. |
+| Read-only trusted-origin consumer | [#7085](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7085), `a1e167cab4e8485bb84418cadfb2313cbcedb644` | Separate and unintegrated. Proofs retain authorization_eligible:false, release_authorized:false and execution_allowed:false. Official security-analysis/run linkage is unverified after analysis API403. Never use this object to mint B1 authorization. |
+| Strict installed-byte consumer successor | [#7087](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7087), `546d77261d02c0633e45b2c62df8f8e5580620c0` | Implements root/all-five/Retry/key proof schema, equality and built-binary binding missing from #7085. Separate, not included here; review/adoption and genuine exact-canonical receipt acceptance pending. All authorization flags remain false. |
+| Canonical live-pin identity successor | [#7095](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7095), `effd9175c00ebbdbaf616813a3ecfa6886bbbf45` | Fixes default-token Variables-read incompatibility in its candidate. Separate uninstalled repository-selected Variables-read identity/setup and live preflight remain required; no fallback or release capability. |
+
+Each linked PR retains its patch-only comparison. Do not squash these packages
+into an expanded app implementation PR or transfer their checks to another SHA.
+The orchestrator's existing stack totals multiple substantial features; each
+future substantial delta must remain separately bounded, with a new estimate
+and a split before approximately20k changed code/test tokens.
+
+## Final source review and actual checks
+
+Independent review of orchestration c1e0 and its pinned Fastlane2.225.0 source
+found one additional functional discrepancy: waiting for TestFlight processing
+reaches `update_beta_app_meta` before `skip_submission` is honored. The follow-up
+sets `skip_waiting_for_build_processing:true` with no changelog. Actual library
+control-flow tests stub login, package construction and Transporter; the corrected
+options stop after one fake upload, while the previous waiting flag reaches the
+processing/distribution path. No store or network operation is exercised.
+
+At preserved c1e0, independent local rerun passed Node22.23.3 contracts67,
+Python contracts24, Ruby3.3.8 fake adapter tests3runs/16assertions and actionlint
+for3workflows. These are source/fake contracts, not native/signing/store tests.
+Initial reviewer invocations used a nonexistent artifact-test filename and
+workflow path; corrected invocations passed without source changes. They are
+review-command errors, not application regressions. Follow-up exact-head results
+are recorded in its PR, rather than attributed to c1e0.
+
+Source review also confirmed that transient cleanup, staged-source/recorded
+nodeify overlays, signed payload digests and independent operation credentials
+remain bounded. Actual hosted cleanup on failure/cancellation or runner loss,
+full embedded production-config readback, provider-selected build identities and
+processing remain **NOT VERIFIED**. Current upload receipts correctly record
+command completion only and storeProcessingVerified:false.
+
+Review follows the latest owner instructions and [#7034](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7034).
+Signing/workflow/security changes require adequate Balanced coverage; record
+reviewer route, exact SHA/base, findings and disposition. This independent cloud
+agent review is source evidence, not a formal GitHub approval or completed
+Copilot/Claude provider review. Claude is unavailable/uninstalled; no new paid
+activation/retry is authorized. Human developer review is conditional, not a
+blanket gate. Preserve substantive security findings and actual required checks.
+
+## Observed one-time setup, without credential values
+
+Read-only environment collection at **2026-10-22 18:23:58 UTC** returned exactly
+`copilot`, `Env` and `keeper-claude-review`. Neither `keeper-release-ios` nor
+`keeper-release-android` exists in that response. Earlier secret-name/variable-name
+reads returned403: custody, value existence, ownership, scope and usability remain
+UNKNOWN, not absent. No secret value was requested and no setup was changed.
+
+| Setup boundary | Remaining evidence/action, requiring separately authorized administration or operation |
+| --- | --- |
+| Protected source and driver | Approved installation on protected sprint, reviewed exact canonical source and release ref, current nonsecret driver pin. No merge/promotion/pin/configuration change has occurred. |
+| Protected environments | Create/configure only after approval: independent reviewers, prevented self approval, administrative bypass disabled and exact protected-source restriction; prove actual rejection before loading credentials. Environment selection alone proves nothing. |
+| Apple signing | Authorized custodian for existing distribution identity/profile, matching team/app/entitlements and independently verified fingerprint; no personal Mac/keychain export, implicit certificate creation or rotation. |
+| Android signing | Authorized existing upload keystore/alias/password custody and independently verified upload-certificate continuity; distinguish Play App Signing identity. |
+| Store API custody | Approved least-privileged App Store Connect and Play app/channel identities, current agreements and authenticated complete version/build baselines. Names are listed in release/cloud/README.md; no values enter source, requests or logs. |
+| Production app configuration | Reviewed client-safe allowlist and exact digest, no signing/upload/server secret embedded. Input digest/source checks do not establish full binary configuration readback. |
+| Artifact audience | Separate owner receipt must acknowledge signed binaries accessible to authenticated readers of this public repository for14days. If that audience is not approved, a private reviewed artifact transport is still required. |
+| Hosted capacity and trust access | Verify macOS/Xcode/Android readiness, safe caches/disk, one native build at a time and read-only variable/Actions/check/artifact/analysis permissions. Coordinate legacy routes; do not cancel active work. |
+| Native, backend and physical acceptance | Complete exact-candidate software matrix and paired backend evidence remain separate from these source packages; actual devices/testers are required for physical results. |
+
+## Remaining implementation deltas before any authorization integration
+
+1. Bind official CodeQL security analysis to the selected installed run/attempt
+ using a genuinely authorized read-only API route. Current403 and separate
+ failed security outcomes are not a success. Keep authorization false while
+ linkage is incomplete.
+2. Reconcile installed selected-route evidence with the legacy all-checks/name
+ predicate without accepting unrelated skips, pending/failed checks or another
+ SHA. Retain exact owner/environment/version/config/certificate/artifact gates.
+3. Original #7085 omitted root/per-scenario installed-byte binding from #7083.
+ Separate successor [#7087](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7087)
+ now implements strict platform proof schema, built-byte binding and equality
+ across all five samples/Retry/key receipts, rejecting missing/false/malformed/
+ mismatched proofs. Review/adopt that candidate and obtain genuine hosted
+ receipts; do not implement a competing copy or claim it is installed. All
+ authorization flags remain false and the canonical matrix remains incomplete.
+4. Complete the parent native feature/performance matrix in its own app/acceptance
+ packages, then obtain genuine exact-canonical receipts after approved
+ installation. Do not replace missing cases with helper/startup evidence.
+5. Before calling signing/distribution verified, separately authorize hosted
+ disposable/approved-channel trials and verify actual transient cleanup,
+ embedded config/signature compatibility, artifact transport and provider
+ build/readback receipts. This document does not authorize those operations.
+
+The provenance integration and installed-byte binding are estimated separately
+at roughly6k–12k changed code/test tokens before live validation; security API
+availability and final native schema may change that estimate. Provider receipt
+and configuration readback would be another bounded estimated3k–6k delta if
+assigned, with actual hosted acceptance separate. No infrastructure absence is
+treated as release approval or grounds to weaken a gate.
+
+## Resumed dependency preparation and metadata evidence
+
+Work continues in isolated `codex/r5-cloud-release-reconciliation`, based on
+#7080 plus #7086. All producer refs and the native candidate are preserved.
+Only the three dependency files below are copied from #7082
+`3eb92fc8a622a3e09926d49f47243c163e32d009`; later native app code is not imported.
+The Gem inputs remain byte-identical to reviewed #7078. No resolver regenerated
+any lock and no authorization code was enabled.
+
+| Input | Origin | SHA256 |
+| --- | --- | --- |
+| Gemfile | #7078 | `5ab2f41eef4d9b3cd84f939f099d0d58cd3fceddb2d4b7815f83eb9b146dd6b4` |
+| Gemfile.lock | #7078 | `e62ce3f1729da11bfdbbbb1665b90c72516352ffaa14606507ff6ce2367b78b1` |
+| package.json | #7082 | `0497b2aaeb76372a6f21721f28ebd42ec2877155a090580b23ace2e017fab6a8` |
+| yarn.lock | #7082 | `60ef283fd7cfb1ac0a940216864d7a779e8449fd245c213d3148b92b97435b7b` |
+| ios/Podfile.lock | #7082 | `b72b31df28a9dececdab9781d5d96785b2081e63cc1d7475941ecfbc624777b3` |
+
+The selected tuple is CocoaPods1.16.2/Xcodeproj1.27.0/Nitro0.36.5. The existing
+worker rejection is retained, extended to reject manifest/Yarn/Pod Nitro drift,
+and exposed through a read-only hash report. It does not confer authorization.
+
+Fresh safe GitHub metadata readback during this resume, approximately
+**2026-10-22 18:28–18:31 UTC**, establishes:
+
+- Complete environment collection: total_count3, exactly `copilot`, `Env`,
+ `keeper-claude-review`; both dedicated release environments absent.
+- Current `sprint` source `def0d6a90c80287edb4f58ae272cbfc340f00d73`,
+ protected:true. Active ruleset24908211 targets `refs/heads/sprint`, has no
+ bypass actors, blocks deletion/non-fast-forward changes, and requires
+ `Tests` and `keeper/local-validation`, both bound to integration15368.
+ Its approval count is0 and strict status policy false; no stronger developer
+ approval/up-to-date-source enforcement is inferred. Other security/native
+ requirements and effective release-ref protection still need proof.
+- Classic branch-protection read, repository secret-name read and variable-name
+ read each return403. Custody/pin visibility and classic policy remain UNKNOWN.
+ No value was printed or retained. The managed task has no configured release
+ credentials; no authorized store/vault metadata route is available here.
+- Native run39824790868, attempt1, exact #7082 source above: iOS job119985112961
+ failed `Check disposable iOS driver readiness` after immutable dependency
+ setup; app build/probes skipped. Android job119991169863 was still running
+ after its development build at that observation. No native acceptance is
+ claimed or transferred.
+
+Later refresh at approximately **18:35 UTC** found new #7087/#7095 candidates
+above and native diagnostic successor [#7094](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7094)
+`ffb2131e4e4478e6befc93c9124941fcff4abb31`. #7094 records attempt1 Android's
+natural FAILURE after installed-APK byte comparison: initial Create a passcode
+assertion failed; later feature/performance cases did not run. Its iOS setup-only
+diagnostic owns the next investigation, without an established root cause or
+dependency correction. The original run39824790868 has meanwhile advanced to
+attempt2/in_progress (iOS job120011570058) under its owner's work. This task
+neither initiated nor cancelled/retried it. Coordinate that owner and #7094;
+never infer an idle native window from the earlier observation.
+
+Signing certificate/profile/upload-key continuity, team/app/store API identity,
+roles, expiry/revocation, agreements and fresh complete store histories remain
+**UNKNOWN / NOT VERIFIED**. Source app identifiers and secret names cannot prove
+those facts. The [exact administrator/custodian specification](r5-cloud-administrator-setup.md)
+lists the safe metadata needed, exact protected names and rejection requirements.
+This task prepares that setup; it does not apply it.
+
+## Reusable cloud-only operator handoff
+
+```text
+Resume isolated protected release preparation; no operation authorization.
+Read AGENTS.md, the newest preparation PR/head and this handoff. Preserve every
+producer/shared branch, the native owner's source and all retained failures.
+Use a new worktree/branch; do not depend on /tmp tools from an earlier session.
+
+1. Refresh #7082 and successors, #7078/#7086 and #7084/#7085 exact heads, active
+ native runs/current attempts, complete environment collection and effective
+ protected rules. Record full SHAs, observation time and API limitations.
+ Keep one named native owner and one reserved hosted native window. Wait for
+ existing runs to finish naturally; do not cancel or dispatch a competing run.
+2. Agree with the native owner on ONE new immutable combined-source checkpoint:
+ their current reviewed full app/native foundation plus reviewed Ruby/Gem
+ inputs and any explicitly adopted preparation corrections. Do not replace a
+ newer app manifest with this preparation branch's older complete app tree.
+ Verify the five dependency hashes/provenance; if the owner advances any input,
+ review that delta and record a new tuple instead of regenerating locks.
+3. On that combined source, run the read-only input checker and negative/fake
+ contracts, then frozen Yarn --ignore-scripts and BUNDLE_FROZEN=true bundle
+ install/check/load. Preserve exact input bytes. The native owner alone then
+ schedules hosted macOS15/Xcode16.4 frozen pod install --deployment (no update),
+ no-signing iOS and disposable Android acceptance within that owner's already
+ authorized route. This task does not dispatch or extend that permission. If
+ any route signs artifacts, resolve its separate scope before invoking it.
+ Require all
+ applicable feature/storage/restore/multi-account/recovery, five raw full-app
+ timings, Retry/key UI and strict installed-byte evidence. Failed/skipped or
+ incomplete cases remain blocked. No personal Mac or platform waiver.
+4. Coordinate #7084/#7085 installation separately from native execution. Keep
+ B1's private marker unminted and all authorization flags false. Require current
+ protected sprint = installed driver = reviewed canonical pin/source, genuine
+ exact-canonical latest-run/current-attempt Actions App/job/check-suite/check
+ identities, original bounded artifact ZIP/digest bytes, complete parent matrix
+ and production source hashes. PR-head checks cannot transfer to canonical SHA.
+ Enforce the strict installed-byte schema including per-scenario identity.
+ Review/adopt #7087's existing binding implementation and #7095's explicit
+ Variables-reader fix; provision/live-test the latter only under separately
+ approved administration.
+ Producer permits1MiB ZIP/512KiB JSON; consumer permits128KiB/64KiB and stronger
+ raw observations. Obtain actual acceptance by BOTH without relaxing limits.
+ Resolve official CodeQL security outcome AND analysis-to-run linkage; Actions
+ workflow success and a403 analysis API are insufficient. Fix/review selected
+ route/legacy-check reconciliation; neither successor is installed by this task.
+5. Have administrator/custodian complete the separately authorized specification
+ and supply only secret-free metadata/readback. Verify environment reviewers,
+ prevented self review, can_admins_bypass:false, protected-branches-only policy,
+ exact source/ref controls and actual credential-free rejection tests. Verify
+ independent certificate/profile/upload-key/store app/channel identities and
+ fresh full histories; never infer readiness from name presence or status text.
+6. Update a durable exact-head PR handoff with commands and real pass/fail/
+ blocked/not-run results, run IDs/attempts and artifact digests, remaining setup,
+ named ownership and execution_allowed:false. No owner receipt is fabricated.
+ No signing, upload, credential/configuration change, deployment, merge or
+ release operation follows from preparation. A later operation needs its own
+ explicit source/environment/channel/artifact approval after all gates exist.
+```
+
+Exact-head test results and native-owner coordination links belong in the new
+preparation PR, so a later operator can distinguish this static procedure from
+live acceptance. Offline/fake checks never supply canonical native/security or
+signing/store evidence.
diff --git a/docs/r5-support-copy-draft.md b/docs/r5-support-copy-draft.md
new file mode 100644
index 0000000000..c9161e8816
--- /dev/null
+++ b/docs/r5-support-copy-draft.md
@@ -0,0 +1,28 @@
+# R5 support and release copy — unsent draft
+
+For owner review after the combined candidate passes its required acceptance. This draft is not published, sent, or a statement that R5 is released. Verify final 5.2 scope, source, versions, channels and exact acceptance before using it. 5.1/5.2 are internal work-package labels; source still identifies 2.6.4. Do not claim native, physical or backend acceptance from source completion alone.
+
+## Proposed release-note text
+
+Keeper's next stability update improves safe key deletion and startup recovery, with clearer backup actions and Version History. Review the final release source and acceptance record before describing these as shipped improvements.
+
+- Key deletion is easier to find and checks current wallet references before removing a key, including retained wallet data. Follow the in-app warning and retain the recovery material you need.
+- Startup and first-wallet setup give clearer retry behavior when required local credentials or connectivity are unavailable. No timing claim is included until the exact candidate's raw measurements are reviewed.
+- Assisted Server Backup has clearer status, an explicit Back Up Now repair path where eligible, read-only Check Again, and readable results. Automatic backup consent, a successful protected backup, and deletion of an existing protected copy are distinct states.
+- Version History distinguishes the installed app version from historical entries. A “Current installation observed” entry records the app observed on that account; it does not invent a store update or a successful migration.
+
+Add or amend the 5.2 paragraph only from its authoritative completed handoff. Do not describe an unknown package identity or unfinished feature as complete.
+
+## Ask Keeper / website help proposed changes
+
+**Checking a backup:** Check Again reads the current protected-backup state. It does not create a backup. An eligible account with automatic backup enabled may use Back Up Now to attempt the explicit repair/upload; wait for its acknowledged result. A conflict, deleted namespace, failure or uncertain result must not be described as a verified new backup.
+
+**Deleting a backup:** Turning automatic backup off stops automatic uploads; it does not itself delete a saved protected copy. Deleting a protected backup applies to that protected copy and is not a promise to erase every legacy copy. A never-enrolled account has no protected copy to delete and is not enrolled merely to perform deletion. Keep the Recovery Key safe.
+
+**Version History:** Installed app version comes from the running native app. Historical records remain historical. The store listing is separate evidence; it must not replace the installed version or manufacture a past update date. The owner-confirmed 2.6.4 installation with stale 2.6.3 history is already accepted evidence; do not ask the owner to recheck that version.
+
+**Support diagnostics:** Share only the bounded operation/stage/category, HTTP status if shown, elapsed time and app version/build through the approved support route. Do not request raw logs, Recovery Keys, PINs, headers, bodies, account identifiers or signing material. Do not request a reset, reinstall, restore-over or backup deletion on the working phone to investigate the old report.
+
+**Emergency Key wording:** Only use the reviewed wording included in the final candidate. Do not expand key-role terminology or advertise a new reset/recovery capability. Hardware/biometric behavior needs actual device evidence; simulator results must be labelled accurately.
+
+Publication remains owner controlled. Update public release notes, website and Ask Keeper together only when required for the actual accepted deliverable, after the final channel/version/source evidence and explicit publication approval. No communications were sent by this package.
diff --git a/docs/r5/R4-RECONCILIATION.md b/docs/r5/R4-RECONCILIATION.md
new file mode 100644
index 0000000000..41e7715afa
--- /dev/null
+++ b/docs/r5/R4-RECONCILIATION.md
@@ -0,0 +1,130 @@
+# R5 reconciliation against released R4 / 2.6.4
+
+The owner explicitly confirmed on 22 October 2026 that 2.6.4 is live on the app
+stores. That confirmation resolves the earlier stale-record discrepancy; GitHub
+PR/tag status and regional store caches are not prerequisites for R5 work.
+
+## Baseline and history
+
+Released artifact source: `1d8a86a7462d935cbd0e28b857934b5718c152fc` (R4 / 2.6.4,
+iOS620, Android627). The recorded signed-artifact/source checkpoint identifies
+this exact source. The source is now an ancestor of the isolated R5 branch through
+reconciliation commit `a8947c867562b6148f328289069785b18053b944`.
+The earlier R5 head5954 and its history are also preserved. No R4/sprint/other
+workstream ref was changed, no force push occurred and no GitHub PR was merged.
+
+The single yarn.lock conflict was resolved to the **exact released R4 lockfile**.
+That file already includes both missing ESLint selectors repaired earlier in R5,
+so retaining the obsolete R5 resolution would have been incorrect. package.json,
+yarn.lock, Podfile.lock, Android/iOS native inputs, version metadata and existing
+backup/backend/store/worker modules remain byte-identical to the released source.
+
+The PR remains based on sprint per repository guidance. Until released history is
+carried to sprint by its owner, its ordinary diff includes inherited R4 history.
+Review R5's own scope as `git diff 1d8a86a...` (the PR handoff links that
+range). This inherited history is not new R5 scope or permission to merge R4.
+
+## Combined-source changes and findings
+
+- R4's local transaction checks **all retained Vault signer references** before
+ deleting a Signer. R5 retains that guard, its current-reference UI checks,
+ archived retention, protected-key exclusions and one-use passcode intent.
+- R4 stamps action origin at dispatch. Eleven new screen regressions demonstrated
+ that an earlier R5 confirmation could reach that boundary after an account
+ switch or A → B → A round trip. Selection/confirmation now compare their original
+ app/session with current Redux and Realm ownership. Delete/archive actions carry
+ the original app/session explicitly, preventing dispatch-time rebinding. These
+ tests use production transport-session tracking, identity and action creators;
+ native UI, Realm access and the Redux state getter are modeled boundaries.
+- R5's Keys entry uses the released navigation dispatch pattern; this removes the
+ TypeScript overload mismatch exposed by integration. No shared PIN/navigation
+ implementation, transaction formatting or timelock calculation changed.
+- Six additional startup regressions reproduced token completion and delayed
+ navigation crossing an A → B → A session change. The existing effects/timers
+ now retain their originating session, including a retained Next callback.
+ Setup and notification workers are unchanged; native persistence remains unrun.
+- Emergency reset uses its Emergency-specific helper; Inheritance retains its
+ own helper. Native display checks remain open.
+- Existing R5 frozen JavaScript CI preparation is retained. Its recovery lane now
+ explicitly installs the released Realm N-API binary, and existing Ruby setup
+ precedes all Ruby-dependent guards. No dependency version or workflow gate was
+ changed. The existing public-v2 genuine backend fixture remains baseline debt;
+ no protocol, readiness, pin, backend deployment or scanner waiver was introduced.
+
+Repository OpenSpec planning artifacts for this reconciliation were committed with
+the baseline integration before the new ownership guard was implemented. DESIGN.md
+was reviewed; existing components, layout, theme and critical controls are retained.
+
+## Executed Cloud checks
+
+Node22.23.3 / Yarn1.22.22:
+
+- Frozen install PASS; all six explicit dependency patches PASS. Released
+ package/lock/Pod/native/version input-immutability checks PASS.
+- Final full Jest **47 suites /538 tests PASS**, zero failures/skips, including
+ the released loopback Electrum fixtures. Final R5-focused run **5 suites /106
+ tests PASS**, including 53 deletion and 20 first-use screen cases.
+- New guard controls before implementation: **11 assertion failures**, with the
+ other42 deletion tests deliberately deselected (not execution passes). All53
+ deletion tests pass after the fix. Real account-round-trip session tracking is
+ used; this does not prove actual native authentication/Realm provenance.
+- Startup session controls before implementation: **6 assertion failures /14
+ passes**. All 20 pass after the fix, including original-session navigation and
+ the existing retry, duplicate-attempt and unmount cases.
+- Full recovery **480/480 PASS**, zero skips. Initial execution had470 passes and
+ one file-load failure because the Realm N-API binary was absent. The exact
+ released binary was installed with prebuild-install; the10 encrypted Realm
+ cases then passed and the complete recovery rerun passed. These are Linux Realm
+ tests, not iOS/Android app-native acceptance.
+- Gate contracts **11/11 PASS**. Static Android16KB/reproducibility checks **31 PASS**.
+ Version consistency, JSON/YAML/prerequisite ordering, formatting, OpenSpec strict
+ validation and diff checks PASS.
+- Release-tool Node **28 PASS** and Python **7 PASS**. Local Ruby is unavailable:
+ the combined release command stops at Ruby. A related guard run recorded30 PASS
+ and11 failures from its missing Ruby runner; those failures are preserved and
+ not reported as app regressions or passes. Hosted CI now sets up the existing
+ Ruby3.3.8 prerequisite before these unchanged checks.
+- Focused lint remains **FAIL82 errors/25 warnings**, versus85/25 on released R4
+ for the same six modules/dependencies; normalized0 added,3 removed.
+- Whole TypeScript remains **FAIL943 diagnostics**, versus944 on released R4 with
+ the same dependencies; normalized0 added,1 removed. The transient new navigation
+ overload finding was fixed before this comparison. Neither check is clean.
+
+The exact final SHA and hosted checks are recorded in the PR handoff. A full
+app-native build/install/UI, performance measurement or physical-device result
+must not be inferred from any JavaScript or Linux Realm result.
+The R5-only changed code/test estimate is approximately 18.1k tokens using changed
+characters/4, at the upper edge of the original 13k–18k estimate. Scope remains two
+substantial features; no additional investigation fix or infrastructure is added.
+
+## Finite native handoff
+
+Use the final PR head, reuse compatible released-R4 caches and preserve all data.
+Cloud development remains primary; optional Linux setup is not a prerequisite.
+The separate hosted-native infrastructure PR is not imported as another R5 feature.
+Where that approved route is available, run its exact-head development startup
+build/smoke; use the Mac only for remaining platform/feature/device checks.
+
+Before any Mac work, read its actual local guidance, measure free disk and use the
+larger actual build forecast (approximately6GiB is only a planning floor), one
+native build at a time. Never delete other worktrees, simulators/AVD users,
+wallets/databases, caches, artifacts or evidence without approval.
+
+1. IOS and ANDROID: new development artifacts from the exact head; cold/warm/resume,
+ theme/network/Tor, credential error/retry, deep-link/auth and small display cases.
+2. Disposable account only: unused visible/hidden key cancellation/deletion, active/
+ hidden/canary/multi-wallet blocks, archived retention, new references during
+ confirmation and same-key account/session changes (including A → B → A). Preserve
+ real wallets; test against an approved disposable fixture, not production data.
+3. Setup offline/failure/repeated Retry/Next, success/relaunch and persistent wallet
+ counts; measure at least five raw first-wallet/startup samples with exact build,
+ device/OS/network configuration. Do not substitute the animation duration or
+ unit-test wall time for native performance.
+4. Bounded #7055 More→Wallets and #6991 device timezone/DST/history/details checks;
+ no speculative patch. Verify Emergency/Inheritance helper and shipped Assisted
+ Server Backup copy. Owner-parked #7056/#7057 remain excluded.
+5. HARDWARE: actual physical PIN/biometric/device scenarios remain explicit. R4's
+ physical deferral is not an R5 pass or automatically transferable scope decision.
+
+No PR merge, signing, store action, deployment or release is authorized by passing
+these checks. R5 remains a draft with unrun native acceptance and review visible.
diff --git a/docs/r5/STARTUP-INVESTIGATION.md b/docs/r5/STARTUP-INVESTIGATION.md
new file mode 100644
index 0000000000..54353806aa
--- /dev/null
+++ b/docs/r5/STARTUP-INVESTIGATION.md
@@ -0,0 +1,139 @@
+# R5 startup and bounded investigations — 21 October 2026
+
+Development evidence only. The owner confirms R4/2.6.4 is live; R5 is now
+reconciled to its recorded source1d8a86a. Earlier unmerged/pending descriptions
+below retain their original investigation scope. No native acceptance,
+release-readiness, issue closure or performance improvement is claimed here.
+
+## Newer work checked before editing
+
+Continued from PR #7058 head `625435ac26af0304670c993a639626b1117699ba`, preserving
+its deletion/privacy, setup lifecycle and CI/lock work. `AGENTS.md` is unchanged.
+R4 #7045 was an open draft at `1d8a86a7462d935cbd0e28b857934b5718c152fc`.
+Its Splash, NewKeeperApp and secure-store modules are identical to the original
+sprint versions. This permits independent source changes without importing R4.
+R4's changed Login, Home/navigation, transaction views and backup/backend paths
+remained untouched during that independent checkpoint. Reconciliation with the
+owner-confirmed released source is now complete; see R4-RECONCILIATION.md.
+
+Other open work includes native-validation #7060, cloud-release #7062, bootstrap
+#7063, lock-selector #7064, PIN fixes #7052/#7053, reproducibility #7043 and the
+Assisted Multisig preview #7041. No commits were imported from these branches;
+no branch/ref, workflow, native configuration or dependency input in them was
+changed. No optional Linux setup or Mac connection was awaited or started.
+
+## #7046: confirmed JavaScript startup defects
+
+1. The credential read formerly started only after the 3,000 ms animation
+ callback. Tests failed 9/10 against the previous Splash implementation.
+ Startup now starts that read after its existing default-network/theme/Tor
+ initialization, independently of animation completion. It still waits for
+ credentials before choosing Login/CreatePin and discards stale completions.
+ PersistGate wraps the app before Navigator, so Redux rehydration already
+ precedes Splash; this change does not remove that hydration gate.
+2. `hasPin()` caught native Keychain/JSON failures and returned false. Two real
+ secure-store boundary tests reproduced this conflating an unreadable store
+ with an empty store. Startup now explicitly requests error propagation with
+ `hasPin({ throwOnError: true })`; default behavior is preserved for legacy
+ callers. A generic Retry dialog contains no underlying error or credential
+ material. Repeated Retry callbacks cannot start parallel reads. No Keychain
+ write, account-selection rule or authentication-policy change was made.
+3. Three setup navigation tests reproduced unmounts leaving the 3-second
+ recreated-app and 500 ms Next timers active, and rapid Next taps scheduling
+ multiple replacements. Cleanup and a one-use pending timer fix those cases.
+ A fourth test reproduced a retained Next callback scheduling after unmount;
+ its screen-lifetime guard now rejects it. The delays themselves are unchanged.
+4. `flows/login.yaml` now checks Proceed is visible but disabled at zero/three
+ digits, enabled at four, and disabled after the inline incorrect-PIN error.
+ It no longer expects a Retry modal on the first incorrect PIN. The existing
+ disposable fixture PIN remains 1111; the flow accepts old-sprint Next or R4's
+ direct advance and then requires Home. It is a native test specification,
+ YAML-parsed here but NOT executed with Maestro. Shared PIN code was not edited.
+5. After release reconciliation, six new tests reproduced pending setup/FCM tokens
+ and navigation timers crossing an A → B → A account-session change. Existing
+ effect lifetime checks now also require their captured production session;
+ Next retains its rendered session before scheduling and when the timer fires.
+ All 20 first-use screen cases pass. These tests use the real session counter
+ with explicit account-transition fixtures; workers and account schemas are
+ unchanged. They do not prove native account-switch persistence or performance.
+
+The screen tests replace native Keychain, navigation, animation and UI boundaries;
+they are not cold-start, warm-start, resume, deep-link or native persistence proof.
+The credential tests execute the actual secure-store function with synthetic
+Keychain results and synthetic account identifiers, without writing any storage.
+
+## #6813: first-wallet timing
+
+Source trace: Start/Retry waits for Firebase token retrieval (rejection falls back
+to tokenless setup), then dispatches setup. The setup worker can derive seed/BIP85
+material, call Relay registration, persist the app/account, create the default
+wallet and Recovery Key signer, then set appCreated. R4 changes some downstream
+wallet/backup behavior. No stage has been established as the runtime bottleneck.
+Do not introduce a notification timeout, weaken wallet setup or change worker
+idempotency from this source trace.
+
+Native measurement recipe, on disposable state after R4 reconciliation:
+
+- Record exact source/build/APK hash, OS/API/ABI, screen/display/font settings,
+ network/Tor state, cold/warm/resume mode and free disk. Reuse the same build
+ mode/device for before/after comparison.
+- Record raw monotonic durations for launch to usable PIN, PIN to usable Home,
+ and Start to completed first wallet. Separate Firebase, worker dispatch,
+ registration response and wallet persistence stages using test instrumentation
+ without logging credentials, seeds, account identifiers or private payloads.
+- At least five samples per cold/warm condition; retain every sample and report
+ median/range rather than attributing the configured animation duration to actual
+ wall-clock performance. Test offline/retry/relaunch and count persisted wallets
+ before/after; JavaScript appCreated simulation cannot prove no duplicates.
+
+No measured native durations or performance percentage is available in this Cloud
+workspace. Java/Jest wall times must not be substituted for app performance.
+
+## #7055: More → Wallets exits to launcher
+
+Bounded read-only trace: MenuFooter calls Home's option-change callback; Home
+selects the Wallets content. Neither path invokes BackHandler.exitApp, navigation
+back/reset, or an Android activity-finish call for this tap. R4 adds tab test IDs
+and changes Home/Ask navigation, so it remains the required baseline. Native
+MainActivity/AppState/task transitions and the report's multiuser history are not
+modeled by these JavaScript tests. No root cause is confirmed and no navigation
+behavior was patched. This does not dismiss the preserved Android 17 failure.
+
+Next reproduction should use an ordinary single-user install plus separate fresh
+state on supported Android versions, then the reported backup opt-in/Delete
+sequence. Verify Wallets/Keys/Ask/More, cold launch and account changes; preserve
+wallets, labels, task/window state, logcat and absence of unintended backup reupload.
+Use existing disposable fixtures only; retain the failed user/artifacts. Do not
+reopen owner-parked #7056/#7057 or infer an R4 test waiver.
+
+## #6991: local transaction times
+
+Bitcoin transaction conversion stores UTC strings from epoch seconds; list rows
+and transaction details call local Moment formatting. R4 changes the row module
+but retains that formatter. The new test renders the actual current production
+TransactionElement with those UTC strings, using synthetic confirmed, pending
+and cached records, and checks the transaction object is unchanged.
+
+Four separate Node/Jest processes tested UTC, Asia/Kolkata, America/New_York and
+Europe/London: 18 assertions each, 72 total. Vectors cover fractional offsets,
+previous-day rollover, spring DST changes and New York's repeated autumn hour.
+All passed. Existing display punctuation/hour-format conventions were preserved.
+This establishes local formatting in Node for the tested rows, not Android/Hermes,
+actual history/details, device-timezone changes while running, or cached-source
+integrity. No timezone fix was confirmed, so no timestamp/formatter code changed.
+Native reproduction remains open and bounded to the approved scope.
+
+## Execution limits and next native route
+
+Cloud has Java and approximately 24 GiB free at preflight, but no adb, emulator
+or Maestro on PATH. No Android/iOS build, install, native UI or physical-device
+check ran. The hosted-native PRs are separate unmerged infrastructure work, not a
+reason to block this source/test work or to import their implementation here.
+Use the approved Cloud native route when available; use a Mac only for remaining
+platform/device checks it actually needs. Do not interrupt R4's Mac work.
+
+For any later native handoff: verify the exact R5 head after R4 reconciliation;
+check disk (approximately 6 GiB planning minimum, more if required), one native
+build at a time, reuse compatible caches and preserve worktrees, AVD users,
+simulators, wallet data, artifacts and evidence. No deletion/cleanup without
+approval. IOS, ANDROID and HARDWARE acceptance remain outstanding.
diff --git a/docs/r5/WORKSTREAM.md b/docs/r5/WORKSTREAM.md
new file mode 100644
index 0000000000..a1b3bdd1d1
--- /dev/null
+++ b/docs/r5/WORKSTREAM.md
@@ -0,0 +1,311 @@
+# R5 Cloud workstream
+
+Status: development draft reconciled to owner-confirmed live R4 / 2.6.4 source
+`1d8a86a7462d935cbd0e28b857934b5718c152fc`. No R5 app version/date assigned.
+The earlier pending-baseline records below are historical and superseded by the
+22 October owner confirmation and completed reconciliation.
+
+## Authority and budget
+
+Owner request and Master Task List, Backlog row 245 (15 October 2026 scope reset),
+plus rows 7, 8, 23, 76, 231 and 263. The owner's 22 October confirmation that R4
+2.6.4 is live authorizes reconciliation with its recorded released source on R5
+only. Historical instructions to wait for R4 are superseded. PR base is `sprint`;
+do not modify R4 or other workstream branches.
+
+Pre-implementation changed code/test estimate (not model context or runtime cost):
+
+| Area | Tokens | Complexity | Regression risk |
+| --- | ---: | --- | --- |
+| Safe discoverable key deletion #7006 | 6k–8k | Substantial feature 1 | High: signing material and wallet references |
+| Android startup/first use #7046, measured #6813 | 5k–7k | Substantial feature 2 | Medium: initialization, authentication, retries |
+| Bounded #7055/#6991 and confirmed minor corrections | 2k–3k | Small investigations only | Medium until reproduced |
+| Total | 13k–18k | Two substantial areas | Security review and native acceptance required |
+
+Warn and propose a smaller split before exceeding approximately 20k changed
+code/test tokens or adding a third substantial feature. Investigations do not
+implicitly authorize architectural fixes.
+
+Excluded: Receive QR (R7); broad components, terminology and touch targets (R8);
+global text scaling and Ask Keeper reply delivery (Soon); #6917 guided setup (R10);
+#7056 second backup POST and #7057 restored-fixture follow-up (Later).
+
+## Baseline and overlap
+
+The initial checkpoint inspected R4 PR #7045 at
+`4927ad549dd1d610d9eb84c6d9a37ed0a6f33a29`. A read-only recheck on 18 October
+2026 found it still an unmerged draft at
+`be89c34473bb6aab253b98325f1fe746ca391c6f`. R4 changes the backup/deletion backend,
+Login/CreatePin, Home/navigation, ResetEmergencyKey/ResetInheritanceKey, transaction
+views and Android native configuration. Leave those dependencies alone now.
+R4, Reproducibility, Bitkey/Assisted Multisig and Claude-review branches are not
+implementation sources for this workstream and must not be modified.
+
+The three initial R5 UI modules are byte-identical between both inspected R4
+heads and sprint. No R4 implementation was imported. Initial independent changes:
+
+- Keys tab links to Manage Keys; visible eligible keys offer Delete without Hide.
+- Read the full Vault collection rather than the network/canary-filtered display
+ hook for active-reference protection. Recheck after passcode entry. Preserve
+ Recovery Key/Policy Server exclusions, hidden-key authentication, cancellation
+ and archived-reference retention. No backend deletion or backup changes.
+- Remove the duplicate setup-error modal; clear the previous error on Retry so a
+ subsequent failed attempt can report its error again.
+
+This is an initial source checkpoint, not completed R5 or native acceptance.
+Backend atomic reference enforcement and account/session changes need reconciliation
+with the released R4 implementation before deletion can be release-ready.
+
+## Original bounded worklist (current results below)
+
+1. Reconcile with the released R4 source; rerun deletion tests and inspect every
+ delete/archive caller and storage/backup boundary. Include references across
+ normal, hidden, archived and canary wallets and signer identity variants.
+2. #7046: profile Android cold/warm/resume time to usable PIN/home; remove artificial
+ splash wait while preserving theme/network/Tor/auth/deep links. Do not substitute
+ the animation's configured 3000 ms for measured startup performance.
+3. Exercise setup failure/offline/retry with one dialog/one attempt, success,
+ relaunch and no duplicate wallet. Correct Maestro login to visible/disabled
+ Proceed only after the R4 shipped PIN baseline is available (sprint is older).
+4. #6813: time first-wallet creation on disposable state, preserve build/device,
+ sample count and raw durations. Diagnose only measured bottlenecks.
+5. #7055: supported single-user Android plus controlled clean state; Wallets → More
+ → Wallets after backup opt-in/Delete, cold launch and account changes. Preserve
+ logcat/task evidence. Existing report does not establish an app root cause.
+ No navigation patch without confirmed narrow cause.
+6. #6991: inspect source timestamps, wallet list/history/details, pending/confirmed/
+ cached data, timezone changes and DST on actual R4-derived build. Current source
+ uses local Moment/Date formatting; source inspection alone does not prove or
+ disprove the Android report. No speculative timezone patch.
+7. Verify shipped #7007 rapid PIN/delete, lock/unlock and biometric behavior;
+ do not redo shipped fixes. Verify Emergency/Inheritance helper text and Assisted
+ Server Backup copy against what R4 actually ships, then make copy-only fixes.
+
+## Later Local resource plan
+
+No Mac is needed for Cloud source development. R4 is released and reconciliation
+is complete. For later native work, use a separate safe checkout,
+check available disk (approximately 6 GiB minimum planning threshold; require more
+if the selected build needs it), run one native build at a time and reuse safe
+compatible caches/artifacts. Preserve every existing worktree, simulator, AVD user,
+wallet/database, artifact and evidence file. Never clean/delete them without owner
+approval. Recheck free space during builds and stop safely if capacity is inadequate.
+
+Native matrix: iOS and Android for shared UI; physical PIN/biometric verification;
+unused visible/hidden key delete and cancellation; active/hidden/canary/multi-wallet
+blocks; archived retention; reference added during passcode; Recovery/Policy Server
+exclusions; offline/retry/resume; small screens/light/dark/large display settings.
+No native result is implied by a unit test. No merge, signing or publication authority.
+
+## Cloud validation, initial checkpoint
+
+- `yarn install --frozen-lockfile --ignore-scripts`: FAILED, existing sprint
+ manifest/lockfile mismatch. `corepack yarn install --pure-lockfile --ignore-scripts`:
+ PASSED, no tracked manifest/lockfile changes. Nested git dependency preparation
+ still ran its package builds. This fallback is not reproducibility evidence.
+- `node_modules/.bin/jest tests/screens/DeleteKeys.test.tsx tests/screens/NewKeeperApp.test.tsx tests/components/Button.test.tsx tests/components/UTXOFooter.test.tsx --runInBand --coverage=false`:
+ PASS, 4 suites / 22 tests. New screen tests are 13 cases; use mocked native,
+ storage, signer-identity and dispatch boundaries. They do not prove actual
+ Realm transactions, native passcode storage, hardware or backup behavior.
+- Initial test harness run: FAILED module resolution for dynamically registered
+ mocks (0 tests executed). Corrected mock paths; final command above passes.
+- Focused ESLint on the three touched UI modules: FAIL, 29 errors / 17 warnings.
+ Read-only stdin comparison with origin/sprint finds identical error/warning
+ counts and rule/message findings (line numbers in two inherited shadow warnings
+ moved). Tests are ignored by the repository ESLint configuration. No claim of
+ repository-wide lint or type-check success.
+- `git diff --check`: PASS. Localization JSON parsing: PASS.
+- Security-focused executed coverage: reference blocking, reference added during
+ passcode entry, cancellation, archived retention, Policy Server and Recovery Key
+ exclusions, hidden-key concealment and repeat confirmation. Backend/session race
+ enforcement and true signer identity integration remain unverified.
+- Native iOS/Android builds, emulator/simulator, physical biometrics/signers,
+ startup/first-wallet timing, CodeQL and full repository test suite: NOT RUN in
+ this checkpoint. No Android SDK/adb was available in this Cloud workspace.
+
+Next: after R4 release, reconcile this draft with its exact baseline and rerun
+these tests; review backend reference enforcement before expanding deletion use.
+Then complete the bounded startup work and actual performance/native matrix.
+Do not claim R5 completion, close issues, merge or release this checkpoint.
+
+## Independent Cloud follow-up — 18 October 2026
+
+The owner authorized continued independent Cloud implementation and automated
+testing while R4 and its Mac remain untouched. This follow-up stays on the R5
+draft; it changes no backend, account/session, shared PIN, native, production
+configuration, version/counter or contributor-pin inputs.
+
+Deletion review reproduced replayed and cancelled passcode callbacks dispatching
+deletion, plus callbacks reading detached active/archived-reference snapshots.
+Each deletion selection now has a one-use intent, consumed synchronously and
+cancelled when its confirmation closes or its screen loses focus. Confirmation
+reads the live Vault collection, blocking active references and retaining keys
+needed by archived wallets. The screen still does not supply backend atomicity
+or shared authentication/account-session provenance.
+
+The full safety query must include concealed and canary references, but those
+records must not disclose wallet names, descriptions or counts in a deletion
+warning. Only the selected key identity is retained; every render reads current
+references again, including newly added references and changes to visibility.
+The warning uses a generic message whenever details are concealed or unavailable,
+and leaving the screen clears it. Tests exercise both callback lifetime and the actual production
+signer-identity helper; native Realm, presentation and dispatch remain replaced
+at the test boundary.
+
+Setup review reproduced late Firebase-token completion dispatching setup or a
+token update after the screen unmounted. Effect-owned guards suppress those late
+Redux actions. The tests now use the real login reducer and setup action with a
+small test-owned Redux store, covering repeated error/Retry/success, rapid presses,
+pending/rejected tokens and successful remount. They simulate `appCreated`; they
+do not prove native wallet creation, wallet-worker success, persistent storage or
+backend idempotency. No arbitrary notification timeout or navigation fix was added.
+
+### Reproducible JavaScript preparation
+
+The unchanged R5 frozen installation failure was reproduced first. The repair
+adds only the two missing root ESLint selectors, preserving all 2,299 existing
+selectors and their version/resolution/integrity/dependency fields. Manifest,
+Pod lock, Nitro/Hermes and native inputs stay unchanged.
+
+Node 22.23.3 and Yarn 1.22.22 frozen installation with root lifecycle scripts
+disabled then passed; all six explicit dependency patches passed. Yarn still
+prepares the pinned Git dependencies while packaging them, so this is not a claim
+that no dependency build scripts execute. The existing IAP/Nitro peer mismatch
+is retained and is not a native-build pass.
+
+Both existing CI jobs now use verified immutable action pins, exact Node/Yarn,
+frozen installation, fail-closed patch application and manifest/lock immutability
+checks. Checkout credentials are not persisted. This avoids invoking the normal
+Mac-specific root prepare script on Linux; that script can mask a CocoaPods
+failure because it lacks `set -e`. Required `Tests`, the local-validation gate,
+and inherited tolerated lint behavior are unchanged.
+
+### Executed follow-up validation
+
+- Frozen JavaScript install: PASS (250.09 seconds), after the original frozen
+ failure and minimal selector repair. All six dependency patches: PASS.
+- Combined offline Jest: **16 suites / 181 tests PASS**, zero failures/skips.
+ This includes **42 deletion** and **9 setup-lifecycle** cases. Command:
+ `node_modules/.bin/jest --runInBand --coverage=false --testPathIgnorePatterns '/tests/services/(client|wallet|vault)\.test\.ts$'`.
+ The three existing live-Electrum integration suites were not run locally;
+ the existing CI `npm run test` command still runs the complete suite.
+- Accepted regression controls: the original deletion code failed 12/30 cases;
+ subsequent lifecycle checks failed 2/32 and live-warning checks failed 10/42
+ before their fixes. Original setup code failed 3/9 lifecycle cases. These
+ were assertion failures after successful test setup, not native results.
+- Existing merge-gate contracts: **11/11 PASS**. Actionlint 1.7.7, workflow
+ YAML/shell checks, localization JSON and `git diff --check`: PASS.
+- Focused ESLint: **FAIL 29 errors / 17 warnings**, exactly the original R5
+ diagnostic multiset after ignoring positions, including embedded upper-scope
+ line/column references. No new lint findings; this is not a clean lint pass.
+- Whole TypeScript: **FAIL 1,013 diagnostics**, versus 1,014 at the original R5
+ checkpoint with the same installed dependencies. Normalizing positions and
+ linked dependency paths finds zero added/one removed diagnostic. The removed
+ diagnostic was the existing Vault JSON conversion assignment in DeleteKeys.
+- Independent review: the two additional visible-to-hidden/canary warning probes
+ failed before the live-warning repair and passed afterward. No additional
+ blocker was found in this bounded source/test/workflow follow-up.
+
+The final draft handoff records the exact tested head and hosted CI results.
+The initial failures above remain part of this checkpoint's history. No native
+iOS/Android, physical-device, startup/first-wallet performance, real-backend or
+retained-data continuity result follows from these JavaScript tests. Finish the
+R4-baseline reconciliation before the affected native matrix. No Mac access,
+private-data transfer, merge, signing or release occurred.
+
+## Cloud continuation — 21 October 2026
+
+Continued from the latest #7058 head `625435ac26af0304670c993a639626b1117699ba`
+after checking current guidance, the approved sheet rows, R4 and overlapping PRs.
+The [startup investigation](STARTUP-INVESTIGATION.md) records the confirmed fixes,
+source traces and limits. No optional Linux setup or Mac session was required.
+
+Independent implementation now includes starting the credential read without the
+fixed splash-animation gate, explicit error propagation for startup-only Keychain
+reads, one generic Retry action, stale-read protection, and setup navigation-timer
+cleanup/repeat protection. The legacy login flow's visibility/disabled-state and
+first-error assumptions are corrected as an unexecuted native test specification.
+No R4 code/ref, shared PIN, navigation, wallet worker, backup/backend, native
+configuration, dependency, CI or version/counter input changed in this follow-up.
+
+New regression controls before fixes: Splash 9 failures/10; actual secure-store
+boundary 2 failures/5; setup navigation 3 new failures/12, then a retained-callback
+failure/13. These are executed JavaScript assertion failures, not native results.
+All final focused cases pass. The expanded offline run passes 19 suites/218 tests,
+with the same three live-Electrum integration suites excluded. Four process-level
+timezone runs pass 18 cases each (72 total); no Android timezone defect or
+navigation root cause is established. Neither received a speculative patch.
+
+Focused ESLint on Splash, NewKeeperApp and secure-store still FAILS with 26 errors
+and 11 warnings, versus 28/11 on the previous R5 head with the same dependencies;
+no added findings after position normalization. Whole TypeScript still FAILS:
+1,018 diagnostics versus 1,019 on previous head625435 with these same installed
+dependencies, zero added/one removed after normalizing positions and linked paths.
+These counts differ from the previous worker's 1,013 and do not supersede its
+separately scoped evidence. Gate contracts 11/11, test formatting, YAML/JSON and
+diff checks PASS. A transient new noImplicitReturns diagnostic in timer cleanup
+was corrected before the final comparison. No clean whole-lint/typecheck claim.
+
+R5 remains two substantial features and within its 13k–18k estimate: a rough
+changed-source/test character count divided by four is about 15k tokens. This is
+an estimate, not tokenizer usage. Stop/propose a split before approximately 20k
+or a third feature. Native startup/first-wallet timings, offline wallet-worker
+idempotency/persistence, real Realm/authentication, #7055/#6991 native reproduction,
+PIN/biometrics and R4-shipped copy reconciliation remain open. Reconcile against
+R4's eventual released baseline and rerun affected checks before native acceptance.
+
+## R4 reconciliation preflight — 22 October 2026
+
+The owner reported R4 released and authorized moving forward. Current repository
+and regional store evidence still identify open/draft #7045 source1d8a86a with
+held store review, unchanged sprint and no2.6.4 tag; exact baseline clarification
+is pending. The [reconciliation preflight](R4-RECONCILIATION.md) records a read-only
+merge preview (one yarn.lock conflict), transactional deletion/account-binding
+review and **31/31 passing R4 unit cases** in a detached, unchanged audit worktree.
+This is not an integrated R5/native pass. No R4 branch or R5 ancestry was changed.
+
+The approved narrow Emergency Key helper correction is independently applied to
+R5: a dedicated EN/ES helper now names Emergency Key, while Inheritance Key keeps
+its original helper. No timelock or recovery calculation changed. JSON/diff PASS;
+existing ResetEmergencyKey ESLint FAIL39/1 with zero added findings. Native copy
+checks remain open. Previous R5 head98c4 hosted Tests and CodeQL are now SUCCESS;
+job-log download was unavailable, so no new hosted suite count or clean-lint claim.
+
+
+## Released-baseline reconciliation completed — 22 October 2026
+
+The owner's explicit confirmation that R4/2.6.4 is live resolves the earlier
+metadata discrepancy. No further release/tag/source confirmation is being awaited.
+Released source1d8a86a is now an ancestor of R5 through commit a8947c867; previous
+R5 history remains intact. R4/sprint/other workstream refs and all released native,
+dependency, backend/store/worker/version inputs remain unchanged. The one lock
+conflict resolves to R4's exact lock, which already includes the two R5 selectors.
+
+The [current reconciliation and finite native plan](R4-RECONCILIATION.md) records
+final full Jest 47/538 PASS, R5 focused 106 PASS, recovery 480/480 PASS (including 10 real
+Linux Realm cases after installing its missing N-API prerequisite), gate11 PASS,
+static31 PASS and Node/Python release-tool28/7 PASS. Local Ruby checks remain
+unavailable/failed-prerequisite, not passed; hosted CI explicitly installs Ruby
+before them. Lint82/25 and TypeScript943 remain inherited failures with no added
+normalized diagnostics versus released R4. Native app/UI/performance/physical
+acceptance has NOT RUN here.
+
+Reconciliation also confirmed and fixed eleven stale-origin UI cases: key-delete
+selection and confirmation now retain the original account/session, verify current
+Redux/Realm ownership, and carry that origin into R4's existing middleware/worker.
+No R4 reference/session guard was weakened. New tests execute real session-counter,
+identity and action-creator logic with modeled screen/storage boundaries. The
+Keys entry's dispatch form was adapted to the released navigation types.
+
+Six additional startup session-crossing regressions failed before the narrow
+effect/timer guards and now pass with the existing cases (20 first-use screen
+tests). Pending token callbacks, recreated-app timers and retained Next callbacks
+cannot act after an A → B → A round trip. No setup worker or backup policy changed.
+
+The R5-only changed source/test estimate is approximately 18.1k tokens (rough
+characters/4), at the upper edge of the approved two-feature 13k–18k target. Hold
+scope here. Review against the
+released source rather than counting R4's inherited history as new R5 work. Do not
+silently add hosted-native infrastructure, extra backend work or a third feature.
+No optional Linux setup or Mac session was awaited. Next is the exact-head finite
+native acceptance/performance plan and required review; no PR merge or release.
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/flows/login.yaml b/flows/login.yaml
index 603b55dd51..858c1525d3 100644
--- a/flows/login.yaml
+++ b/flows/login.yaml
@@ -1,32 +1,56 @@
+# Disposable English-language fixture only: PIN 1111, biometric login disabled,
+# no prior failed attempts, app already created. Never run against a real wallet.
appId: io.hexawallet.keeper
---
- extendedWaitUntil:
visible: 'Enter your passcode'
timeout: 20000
-- assertNotVisible: 'Proceed'
+- assertVisible:
+ id: 'btn_primaryText'
+ text: 'Proceed'
+ enabled: false
- tapOn: '1'
- tapOn: '2'
- tapOn: '3'
+- assertVisible:
+ id: 'btn_primaryText'
+ text: 'Proceed'
+ enabled: false
- tapOn: '7'
-- assertVisible: 'Proceed'
+- assertVisible:
+ id: 'btn_primaryText'
+ text: 'Proceed'
+ enabled: true
- tapOn: 'Proceed'
-- waitForAnimationToEnd:
- timeout: 5000
-- assertVisible: 'Incorrect password'
-- assertNotVisible: 'Proceed'
-- assertVisible: 'Retry'
-- tapOn: 'Retry'
+- extendedWaitUntil:
+ visible: 'Incorrect Passcode, Try Again!'
+ timeout: 15000
+- assertVisible:
+ id: 'btn_primaryText'
+ text: 'Proceed'
+ enabled: false
+# A single incorrect PIN shows an inline error, not a Retry modal.
- tapOn: '1'
- tapOn: '1'
- tapOn: '1'
- tapOn: '1'
-- assertVisible: 'Proceed'
+- assertVisible:
+ id: 'btn_primaryText'
+ text: 'Proceed'
+ enabled: true
- tapOn: 'Proceed'
- waitForAnimationToEnd:
timeout: 5000
+# The older sprint login has a security-tip Next action; R4 advances directly.
- extendedWaitUntil:
- visible: 'Next'
+ visible: 'Next|Wallets'
+ timeout: 30000
+- runFlow:
+ when:
+ visible: 'Next'
+ commands:
+ - tapOn: 'Next'
+- extendedWaitUntil:
+ visible:
+ id: 'text_home_current_plan'
timeout: 30000
-- tapOn: 'Next'
-- waitForAnimationToEnd:
- timeout: 2000
diff --git a/index.js b/index.js
index e352be378e..c02e93f03c 100644
--- a/index.js
+++ b/index.js
@@ -7,6 +7,7 @@ global.atob = decode;
import 'react-native-reanimated';
import 'react-native-gesture-handler';
import './shim';
+import './src/services/backup/encoding';
import { AppRegistry, Text as NativeText } from 'react-native';
import 'react-native-get-random-values';
import { Text, Input } from '@gluestack-ui/themed-native-base';
diff --git a/ios/Podfile b/ios/Podfile
index b0e96375f5..bbda6b4095 100644
--- a/ios/Podfile
+++ b/ios/Podfile
@@ -86,6 +86,17 @@ post_install do |installer|
# :ccache_enabled => true
)
+ # react-native-config logs and embeds every key from its selected .env file.
+ # Run the guard in that pod's own phase before its code generator starts.
+ config_target = installer.pods_project.targets.find { |target| target.name == 'react-native-config' }
+ config_codegen = config_target&.shell_script_build_phases&.find { |phase| phase.name == '[CP-User] Config codegen' }
+ raise 'react-native-config codegen phase not found; release credential guard cannot be installed' unless config_codegen
+
+ config_codegen.shell_script = <<~SCRIPT + config_codegen.shell_script
+ set -e
+ ruby "${PODS_ROOT}/../scripts/verify-retired-env.rb" "${PODS_TARGET_SRCROOT}/ios/ReactNativeConfig" "${SRCROOT}/../.."
+ SCRIPT
+
# fixes release issue with xCode 16, bitcode is stripped by default.
bitcode_strip_path = `xcrun --find bitcode_strip`.chop!
def strip_bitcode_from_framework(bitcode_strip_path, framework_relative_path)
diff --git a/ios/Podfile.lock b/ios/Podfile.lock
index 85cbf1ecf8..7fa62b9bbc 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.36.5):
- 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
@@ -3986,17 +3986,17 @@ SPEC CHECKSUMS:
glog: 5683914934d5b6e4240e497e0f4a3b42d1854183
GoogleDataTransport: aae35b7ea0c09004c3797d53c8c41f66f219d6a7
GoogleUtilities: 00c88b9a86066ef77f0da2fab05f65d7768ed8e1
- hermes-engine: 4ec27e7c84ed7950da6e65008539685455d8bef4
- HtmlToPdf: 6a9c28f54ec810d1d120a698a9b3c83e2bdb1672
+ hermes-engine: 06d1c4969de42f925f6614a3c2e049b3a000331d
+ 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: 5115360c2954442d8a6a4fafe836f7a5458815df
+ 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
+PODFILE CHECKSUM: 79b67f9496d66b3a6a618591c809ed441d1032f6
COCOAPODS: 1.16.2
diff --git a/ios/fastlane/Fastfile b/ios/fastlane/Fastfile
index 7147a897aa..29d1c67ee1 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
@@ -58,6 +54,60 @@ def upload_build_to_testflight!
upload_to_testflight(options)
end
+def verify_envfile_selector!(production_env, selector = "/tmp/envfile")
+ return unless File.exist?(selector)
+
+ if File.read(selector).strip != production_env
+ UI.user_error!("/tmp/envfile would override the reviewed .env.production")
+ end
+end
+
+def build_verified_production_ipa!
+ 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)
+ verify_envfile_selector!(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)
+ )
+
+ get_provisioning_profile( # Create or get provisioning profile
+ output_path: "./builds", # Download provisioning profile in the build folder
+ filename: "Keeper_Distribution.mobileprovision" # Rename the local provisioning profile
+ )
+
+ update_project_provisioning( # Set the project provisioning profile (related in Xcode to the General > Signing Release section)
+ xcodeproj: "hexa_keeper.xcodeproj",
+ target_filter: "hexa_keeper", # Name of your project
+ profile: "./builds/Keeper_Distribution.mobileprovision",
+ build_configuration: "Release"
+ )
+
+ update_project_team( # Set the right team on your project
+ teamid: CredentialsManager::AppfileConfig.try_fetch_value(:team_id)
+ )
+
+ app_identifier = resolved_app_identifier!
+
+ # Only accept an artifact path produced by this invocation.
+ Actions.lane_context.delete(SharedValues::IPA_OUTPUT_PATH)
+ build_app(workspace: "hexa_keeper.xcworkspace", scheme: "hexa_keeper", clean: true,
+ export_method: "app-store",
+ export_options: {
+ provisioningProfiles: {
+ app_identifier => app_identifier + " AppStore" # Value of this parameter is the name of the Provisioning Profile. By default, it will be "{bundleId} AppStore"
+ }
+ },
+ build_path: "./builds",
+ output_directory: "./builds")
+ ipa_path = resolved_ipa_path!
+ sh("python3", File.expand_path("../../scripts/verify-release-artifact.py", __dir__), ipa_path)
+ ipa_path
+end
+
platform :ios do
desc "Push a new dev build to TestFlight"
lane :dev do
@@ -106,48 +156,14 @@ platform :ios do
upload_build_to_testflight!
end
+ desc "Build and verify production IPA without uploading"
+ lane :build_only do
+ build_verified_production_ipa!
+ end
+
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")
-
- 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)
- )
-
- get_provisioning_profile( # Create or get provisioning profile
- output_path: "./builds", # Download provisioning profile in the build folder
- filename: "Keeper_Distribution.mobileprovision" # Rename the local provisioning profile
- )
-
- update_project_provisioning( # Set the project provisioning profile (related in Xcode to the General > Signing Release section)
- xcodeproj: "hexa_keeper.xcodeproj",
- target_filter: "hexa_keeper", # Name of your project
- profile: "./builds/Keeper_Distribution.mobileprovision",
- build_configuration: "Release"
- )
-
- update_project_team( # Set the right team on your project
- teamid: CredentialsManager::AppfileConfig.try_fetch_value(:team_id)
- )
-
- app_identifier = resolved_app_identifier!
-
- build_app(workspace: "hexa_keeper.xcworkspace", scheme: "hexa_keeper", clean: true,
- export_method: "app-store",
- export_options: {
- provisioningProfiles: {
- app_identifier => app_identifier + " AppStore" # Value of this parameter is the name of the Provisioning Profile. By default, it will be "{bundleId} AppStore"
- }
- },
- build_path: "./builds",
- output_directory: "./builds")
+ build_verified_production_ipa!
upload_build_to_testflight!
end
end
diff --git a/ios/hexa_keeper.xcodeproj/project.pbxproj b/ios/hexa_keeper.xcodeproj/project.pbxproj
index 7f0b8da754..1f8616b945 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 = 620;
DEVELOPMENT_TEAM = Y5TCB759QL;
ENABLE_BITCODE = NO;
HEADER_SEARCH_PATHS = (
@@ -849,7 +849,7 @@
"$(inherited)",
"\"$(SRCROOT)\"",
);
- MARKETING_VERSION = 2.5.14;
+ MARKETING_VERSION = 2.6.4;
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 = 620;
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.6.4;
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 = 620;
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.6.4;
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 = 620;
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.6.4;
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)ITSAppUsesNonExemptEncryptionLSApplicationQueriesSchemes
diff --git a/ios/hexa_keeper/hexa_keeper.entitlements b/ios/hexa_keeper/hexa_keeper.entitlements
index 2fba371611..176fe58afc 100644
--- a/ios/hexa_keeper/hexa_keeper.entitlements
+++ b/ios/hexa_keeper/hexa_keeper.entitlements
@@ -6,7 +6,8 @@
developmentcom.apple.developer.associated-domains
- applinks:bitcoinkeeper.app/app/prod
+ applinks:www.bitcoinkeeper.app
+ applinks:bitcoinkeeper.appcom.apple.developer.icloud-container-identifiers
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)ITSAppUsesNonExemptEncryptionLSApplicationQueriesSchemes
diff --git a/ios/hexa_keeper_dev.entitlements b/ios/hexa_keeper_dev.entitlements
index bda8e1cf34..212d9955d9 100644
--- a/ios/hexa_keeper_dev.entitlements
+++ b/ios/hexa_keeper_dev.entitlements
@@ -6,7 +6,8 @@
developmentcom.apple.developer.associated-domains
- applinks:bitcoinkeeper.app/app/dev
+ applinks:www.bitcoinkeeper.app
+ applinks:bitcoinkeeper.appcom.apple.developer.icloud-container-identifiers
diff --git a/ios/scripts/verify-retired-env.rb b/ios/scripts/verify-retired-env.rb
new file mode 100644
index 0000000000..ff11a414fc
--- /dev/null
+++ b/ios/scripts/verify-retired-env.rb
@@ -0,0 +1,28 @@
+#!/usr/bin/env ruby
+# frozen_string_literal: true
+
+# Use react-native-config's own reader so this checks the same ENVFILE,
+# /tmp/envfile override, and .env fallback that its code generator will use.
+reader_directory, environment_root, selector_path = ARGV
+abort('Missing react-native-config environment inputs') unless reader_directory && environment_root
+selector_path ||= '/tmp/envfile'
+
+# react-native-config prefers the shared selector over ENVFILE. Recheck it in
+# the pod codegen phase, after the release lane's earlier preflight check.
+if File.basename(ENV['ENVFILE'].to_s) == '.env.production'
+ production_env = File.expand_path(ENV['ENVFILE'])
+ abort('Reviewed production environment is missing during iOS codegen') unless File.file?(production_env)
+ if File.exist?(selector_path) && File.read(selector_path).strip != production_env
+ abort('iOS codegen environment differs from the reviewed .env.production')
+ end
+end
+
+retired_names = %w[GASFREE_API_KEY GASFREE_API_SECRET LETS_EXCHANGE_API_KEY]
+retired_names += retired_names.map { |name| "RN_#{name}" }
+failure = 'Retired API credentials must not be included in an iOS build'
+
+abort(failure) if retired_names.any? { |name| ENV.key?(name) }
+
+require File.join(reader_directory, 'ReadDotEnv')
+dotenv, = read_dot_env(environment_root)
+abort(failure) if retired_names.any? { |name| dotenv.key?(name) }
diff --git a/ios/scripts/verify-retired-env.test.cjs b/ios/scripts/verify-retired-env.test.cjs
new file mode 100644
index 0000000000..4e496e11e0
--- /dev/null
+++ b/ios/scripts/verify-retired-env.test.cjs
@@ -0,0 +1,100 @@
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const verifier = path.join(__dirname, 'verify-retired-env.rb');
+const reader = process.env.KEEPER_TEST_RN_CONFIG_READER ||
+ path.join(__dirname, '..', '..', 'node_modules', 'react-native-config', 'ios', 'ReactNativeConfig');
+const secret = 'synthetic-secret-not-for-output';
+const retiredNames = ['GASFREE_API_KEY', 'GASFREE_API_SECRET', 'LETS_EXCHANGE_API_KEY'];
+retiredNames.push(...retiredNames.map(name => `RN_${name}`));
+
+function verify(contents, additionalEnv = {}) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-ios-env-'));
+ try {
+ const envFile = path.join(directory, '.env.test');
+ fs.writeFileSync(envFile, contents);
+ return spawnSync('ruby', [verifier, reader, directory], {
+ cwd: directory,
+ env: { PATH: process.env.PATH, ENVFILE: envFile, ...additionalEnv },
+ encoding: 'utf8',
+ });
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+}
+
+test('iOS pod guard accepts config without retired credentials', () => {
+ assert.ok(fs.existsSync(reader), 'Install react-native-config before running this test');
+ const result = verify('CHANNEL_URL=https://channel.bitcoinkeeper.app/\n');
+ assert.equal(result.status, 0, result.stderr);
+});
+
+for (const name of retiredNames) {
+ test(`iOS pod guard rejects ${name} in selected ENVFILE before logging its value`,
+ () => {
+ const result = verify(`CHANNEL_URL=https://channel.bitcoinkeeper.app/\n${name}=${secret}\n`);
+ assert.notEqual(result.status, 0);
+ assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/);
+ });
+}
+
+test('iOS pod guard rejects exported retired credentials', () => {
+ const result = verify(`export GASFREE_API_KEY=${secret}\n`);
+ assert.notEqual(result.status, 0);
+ assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/);
+});
+
+test('iOS pod guard rejects a retired process variable before logging its value',
+ () => {
+ const result = verify('CHANNEL_URL=https://channel.bitcoinkeeper.app/\n', {
+ RN_GASFREE_API_SECRET: secret,
+ });
+ assert.notEqual(result.status, 0);
+ assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/);
+ });
+
+test('iOS production codegen rejects a conflicting envfile selector', () => {
+ assert.ok(fs.existsSync(reader), 'Install react-native-config before running this test');
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-ios-production-env-'));
+ try {
+ const production = path.join(directory, '.env.production');
+ const selector = path.join(directory, 'envfile-selector');
+ fs.writeFileSync(production, 'CHANNEL_URL=https://channel.bitcoinkeeper.app/\n');
+ fs.writeFileSync(selector, path.join(directory, 'unreviewed.env'));
+ const result = spawnSync('ruby', [verifier, reader, directory, selector], {
+ cwd: directory,
+ env: { PATH: process.env.PATH, ENVFILE: production },
+ encoding: 'utf8',
+ });
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /environment differs from the reviewed/);
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+test('iOS production codegen accepts matching or absent envfile selector', () => {
+ assert.ok(fs.existsSync(reader), 'Install react-native-config before running this test');
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-ios-production-env-'));
+ try {
+ const production = path.join(directory, '.env.production');
+ const selector = path.join(directory, 'envfile-selector');
+ fs.writeFileSync(production, 'CHANNEL_URL=https://channel.bitcoinkeeper.app/\n');
+ for (const selectorContents of [null, production]) {
+ if (selectorContents === null) fs.rmSync(selector, { force: true });
+ else fs.writeFileSync(selector, selectorContents);
+ const result = spawnSync('ruby', [verifier, reader, directory, selector], {
+ cwd: directory,
+ env: { PATH: process.env.PATH, ENVFILE: production },
+ encoding: 'utf8',
+ });
+ assert.equal(result.status, 0, result.stderr);
+ }
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
diff --git a/jest.config.js b/jest.config.js
index d473261bc7..e2bee4d73c 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -4,7 +4,7 @@ module.exports = {
setupFiles: ['./node_modules/react-native-gesture-handler/jestSetup.js'],
setupFilesAfterEnv: ['./test-setup.js'],
transformIgnorePatterns: [
- 'node_modules/(?!(jest-)?@?react-native|@react-navigation|@react-native-community|redux-persist|@realm)',
+ 'node_modules/(?!(jest-)?@?react-native|@react-navigation|@react-native-community|redux-persist|@realm|@noble/(curves|hashes)|@scure/(bip32|bip39|base)|@exodus/bytes)',
],
collectCoverage: true,
coverageDirectory: 'coverage',
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..244040a94b
--- /dev/null
+++ b/openspec/changes/fix-ask-tab-navigation/design.md
@@ -0,0 +1,48 @@
+## 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.
+
+## 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.
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/openspec/changes/fix-recovery-backup-freshness/automatic-write-readiness.md b/openspec/changes/fix-recovery-backup-freshness/automatic-write-readiness.md
new file mode 100644
index 0000000000..911b9cba12
--- /dev/null
+++ b/openspec/changes/fix-recovery-backup-freshness/automatic-write-readiness.md
@@ -0,0 +1,43 @@
+> Current R4 contract: [protected backup integration](protected-backup-integration.md) supersedes the historical v2 protocol and whole-copy Delete language below. Prior checked source/fixture boxes are SHA-scoped historical evidence, not protected-v3, native, hosted or release acceptance. Delete now applies only to the new protected copy; older encrypted copies remain read-only. All-copy erasure is outside approved R4 scope, unimplemented and unscheduled.
+
+# Automatic Assisted Backup writes: implementation gates
+
+R4 requirements reconciled 13 October 2026 from audit starting app head `b160656218dc6065ad12af9db220c974255bfc23`. The original plan reviewed Keeper `0550ac9ffa938a079816ae4ed58bc970324c3e08` and Relay PR #4 `82ee3b10708a56d220170505d1bb7e3bc8429e77`; those are historical inputs, not the final proof source.
+
+The owner requires the automatic-backup fix and disposable proof in R4. Critical native IOS/ANDROID backup checks also precede release; explicitly physical-only follow-up may be recorded separately. The implemented committed-payload/session proof has observed host Realm/transactional HTTP evidence in [automatic-write-validation.md](automatic-write-validation.md) and [October evidence](evidence/automatic-backup-source-proof-2026-10-13.md). `AUTOMATIC_BACKUP_SOURCE_READY=true` permits only development loopback testing while `AUTOMATIC_BACKUP_RELAY_ROLLOUT_READY=false` keeps hosted writes fenced. This record authorizes no production enablement, merge or Relay deployment.
+
+## Why the audit-baseline intent cannot authorize a write
+
+At the audit starting source, `BackupWriteIntent` recorded the selected account session and a previously verified Relay revision. It did not identify the local recovery state represented by an encrypted payload or deletion. `backupPost` therefore rejected all seven operations before network. That was required at the baseline: some producers encrypted action data before Realm persistence, Realm could change while an action waited, and one action could emit several Relay writes with the same captured base revision. A valid server compare-and-swap protects against another server writer; it does not prove that the client is sending its present local recovery data. These historical observations are superseded for the final implementation by the source/proof result matrix.
+
+The baseline central Realm observer invalidates backup verification **before** each relevant write. It has no post-commit token and can fire for several field writes in one logical action. The baseline transport's `queuedMutationRevisions` is never populated, so it cannot provide a queue completion proof. A pre-send comparison of a prepared ciphertext against the current Realm image is necessary but still insufficient for operations deliberately sent before local persistence.
+
+## Implemented transaction model
+
+1. Give each logical local recovery operation an account-scoped operation ID and a commit result. A successful commit captures a monotonic recovery generation after all related Realm writes; failed or partial writes stay pending and never authorize upload. For pre-persistence producers, stage data locally and queue the cloud mutation only after this commit. Do not make server success a prerequisite for saving a new wallet, signer, vault or deletion.
+2. Capture the originating `appId`, account session, verified base revision/epoch and operation ID before async work. Never substitute a newly verified base for an older action. On A→B→A, reject old queued work even if A is selected again. An already sent request has an uncertain outcome and requires readback.
+3. At the head of the per-account queue, re-read the fresh local recovery image and prove the proposed operation's decrypted payload or deletion target against that image and its committed generation. Verify the selected account, backup consent, encryption key ownership, and the originally captured session immediately before sending. An operation-specific failed proof ends in pending/unverified without network.
+4. Read or retain a validated protected-v3 namespace snapshot, complete raw projection checksum and original revision/generation/authEpoch tuple. The original Keeper App/provider identity remains separate. No legacy endpoint fallback. Apply each proposed operation to the remote snapshot in memory and reject an effect that removes remote-only recovery records or changes key identity without an explicit user decision. The Relay must atomically enforce original `expectedRevision`, `expectedGeneration` and `authEpoch`, returning a positive acknowledgement with its own advancing `newRevision`, `newGeneration` and correct `authEpoch`.
+5. A multi-record logical operation should use one Relay transaction carrying all its effects. When protected mutations are sequential, each step must validate its own current local proof and use the preceding acknowledgement’s complete revision/generation/epoch tuple. Partial success remains pending. Never call the whole backup verified on an intermediate response.
+6. After the last acknowledged write, read back and decrypt the complete Relay image. Only a match with a newly captured local image at the same committed generation may set verified. A local write during comparison invalidates the claim. The existing atomic Redux verification commit remains the final UI gate.
+7. On 409, old Relay/404, malformed acknowledgement, timeout, lost response, network error, failed local commit, changed session or changed local generation, stop the chain. Do not retry prepared ciphertext or send later fanout members. Keep pending and run a read-only check. A lost response may have committed on the server; its result must be learned from readback before any fresh write.
+
+## Operation-specific proof at the queue head
+
+| Relay operation | Local proof before send | Historical audit-baseline producer complication |
+| --- | --- | --- |
+| `updateAppImage` | Decrypt each wallet/USDT/signer ciphertext with the active account seed; map IDs, sanitized signer records and recoverable fields must equal the committed Realm records. `replaceNodes` requires the exact current normalized node set; app metadata must come from the current KeeperApp. | New wallet and signer creation call backup before Realm insertion. Node and version paths use different timing. Action payloads may be stale. |
+| `migrateXfps` | Old exact KeyUID must be absent in committed Realm; new exact KeyUID and decrypted sanitized signer must match Realm. Verify all affected vault signer references, and prove the old map entry exists in the validated Relay snapshot. | The baseline worker updated a live signer before building the request. It previously sent bare fingerprints while Relay maps use KeyUIDs; the baseline narrow fix still left automatic transport disabled. |
+| `deleteAppImageEntity` | Every wallet/USDT/signer ID must be absent after a successful local commit and present in the expected Relay snapshot. Deleting a signer must not make a retained vault unrecoverable. | Baseline BTC wallet and signer deletion called Relay before Realm deletion; USDT deletion did so directly. Reordering required durable pending state and truthful result/UI handling. |
+| `deleteVaults` | Each ID must be absent after local commit; other participant/shared-vault references must remain owned and recoverable. | Vault deletion also calls Relay before local deletion. A remote success followed by local failure can leave a mismatched backup. |
+| `updateVaultImage` | Decrypt the vault; its ID, sanitized signers, policy, archive state and `signersData` must match the committed Realm Vault plus persisted VaultSigner registrations. | Creation and metadata edit can call Relay before persistence. Registration changes can fan out to several vault writes; migration creates and archives two vaults. |
+| `modifyLabels` | Decrypt each added label and verify the account-derived hashed ID and current Realm tag. Every deleted hashed ID must map to a tag absent after local commit. Reconcile add/delete overlap and account ownership. | Imports, upgrades and transaction-label workers can emit multi-label fanouts; a delayed file callback carries older intent. |
+| `deleteBackup` | Require explicit Delete protected backup for the same selected account/session and original protected namespace/revision/generation/epoch. Preserve local records and consent until positive scoped acknowledgement plus complete tombstone readback. Older encrypted copies remain read-only; an uncertain reply never means Delete succeeded. | This is a destructive exception to the local-image comparison: the user intentionally removes the remote copy while keeping Realm. It needs its own opt-out state and separate tests. |
+
+## Test matrix and remaining enablement gates
+
+Run each of the seven operations against disposable Realm and transactional Relay fixtures, with real encryption/decryption and the production saga/transport entry points. For each operation, verify: matching committed payload/target reaches the protected mutation route once; stale payload after a local mutation sends nothing; A→B→A sends nothing; a server 409/old route 404/malformed response leaves pending and does not fall back; timeout or lost acknowledgement sends no next item and readback cannot create false verified. Exercise both matching and remote-only/conflicting snapshots.
+
+Add focused multi-write fixtures for (a) creating and archiving a vault, (b) one VaultSigner registration affecting several vaults, and (c) label import plus deletion. Make the first Relay write succeed and the next fail; assert local data survives, the remaining prepared writes do not run, and neither a saga nor Redux reports verified. Assert a local mutation injected just before the final verification commit leaves the backup pending. Pair these tests with native iOS/Android create, edit, delete, relaunch and clean Recovery Key restore on the exact app SHA, plus exact protected-protocol HTTP tests against a disposable replica set.
+
+The host source matrix now supports development loopback testing. Preserve the hosted rollout fence until transaction topology, compatible running Relay artifacts and protection from old/legacy writers are reviewed under separately authorized rollout. A source pass is not deployment evidence. A future source change must never turn an endpoint name or revision string alone into a freshness proof. The current result matrix identifies which source/fixture cases actually ran and keeps native app relaunch, critical IOS/ANDROID and release checks open independently of host results.
diff --git a/openspec/changes/fix-recovery-backup-freshness/automatic-write-validation.md b/openspec/changes/fix-recovery-backup-freshness/automatic-write-validation.md
new file mode 100644
index 0000000000..cb308ad06d
--- /dev/null
+++ b/openspec/changes/fix-recovery-backup-freshness/automatic-write-validation.md
@@ -0,0 +1,105 @@
+> Current R4 contract: [protected backup integration](protected-backup-integration.md) supersedes the historical v2 protocol and whole-copy Delete language below. Prior checked source/fixture boxes are SHA-scoped historical evidence, not protected-v3, native, hosted or release acceptance. Delete now applies only to the new protected copy; older encrypted copies remain read-only. All-copy erasure is outside approved R4 scope, unimplemented and unscheduled.
+
+# R4 automatic Assisted Backup: result matrix
+
+Updated 13 October 2026 from observed source/disposable evidence. Historical September logs remain unchanged in [validation.md](validation.md). The [sanitized October proof record](evidence/automatic-backup-source-proof-2026-10-13.md) records commands, source identities, counts and coverage boundaries. The table below retains the original Cloud source-proof result; a later exact-head Codex Local report on PR #7045 records native results and any new app SHA.
+
+Automatic-backup implementation and disposable proof are mandatory R4 work. Critical IOS/ANDROID backup acceptance also precedes release. Host-native Realm means the real Node Realm SDK, not an iOS/Android app launch. Physical-device-only follow-up cannot waive critical simulator/emulator safety checks.
+
+The [15 October exact-698 Local report](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045#issuecomment-6178691569) supersedes the historical native NOT RUN cells only for its explicitly tested subset. It records a strict-16-KB Android startup FAIL. The [targeted supplier correction and new-head retest](../../../release/r4-android-16kb.md) do not constitute native acceptance or R4 readiness. Android C8/#7056 remains owner-parked and failed; this continuation must not restart that separate fix/retest cycle. Both hosted-backup readiness constants and the approved contributor manifest are unchanged.
+
+## Source and result record
+
+| Field | Current record |
+| --- | --- |
+| Audit starting app source | b160656218dc6065ad12af9db220c974255bfc23; historical |
+| Final tested code commit before documentation | 3cc9368ca2f3b2149db5743a5f9d230aa516d6a0; includes persisted-proof expiration, current-proof status projection and seven new genuine cases |
+| Original tested Relay fixture commit | b600416e5ba7325927d7d2871cff7776f4e593fe; runner requires clean tracked source. Native Android later exposed an incomplete repair readback on this fixture |
+| Current paired disposable Relay source | 838049e537e07eb646a2a0393eb969fba43d0739 in draft Relay #4 fixes subscription metadata on an existing AppImage during explicit revisioned repair. Focused route regression RED 0/1 on b600 and GREEN 1/1 on 838; full HTTP 58/58, backup suite 120/120 and Relay TypeScript PASS. This is loopback evidence, not deployed Relay readiness or final exact-SHA app signoff |
+| Runtime and topology | Node 22.23.3, actual Realm 12.15.0, Linux host, disposable loopback keeperQA Mongo replica set on port 27058; no hosted credentials |
+| Combined genuine fixture command/result | `npm run test:automatic-backup-genuine`: PASS 260/260, 0 failures/skips, 208.779 seconds, clean frozen-Yarn run terminal recorded 2026-10-13 05:26 UTC; core 213 + producers 46 + restore 1 |
+| Recovery unit command/result | `npm run test:recovery`: 443/443 PASS, 0 failures/skips, 52.156 seconds at 3cc9368ca2f3b2149db5743a5f9d230aa516d6a0 |
+| Clean encrypted Recovery Key restore | PASS: actual recovery saga, real key derivation/AES, blank encrypted Realm and real HTTP reads; complete image, all signer fields and normalized nodes checked |
+| Source/hosted flags | AUTOMATIC_BACKUP_SOURCE_READY=true for DEVELOPMENT loopback only; AUTOMATIC_BACKUP_RELAY_ROLLOUT_READY=false; hosted rollout remains false |
+| IOS / ANDROID exact-source result | NOT RUN / NOT RUN; NEEDS_LOCAL |
+| Review and current-head CI | Independent agent fixture review completed; external final-source review remains open. Prior head 2071 hosted Tests 38348159148 and CodeQL 115134694738 succeeded; current final-head combined CI awaits the post-documentation push. Source #7042 at 163cc own-head checks succeeded with runtime d280 unchanged; prior failures remain in [October evidence](evidence/automatic-backup-source-proof-2026-10-13.md) |
+| Current Jest | 42 suites / 432 tests PASS, 37.9 seconds at 3cc9368ca2f3b2149db5743a5f9d230aa516d6a0 |
+| Type/lint boundary | Recorded focused six core module lint/format PASS. Prior 2071 hosted whole lint CLI FAIL: 5353 problems, 4467 errors, 886 warnings, tolerated by the green job. Whole-project tsc FAIL with 945 inherited diagnostics versus 957 at baseline bb66cea459fbb00ec33c5c4ebd601d07c0d7c125; zero added normalized diagnostics, not a clean typecheck |
+| Current release preflight | FAIL: 2026-10-13 04:11 UTC command found iOS store history older than 24 hours; refresh required before release |
+| Production running artifact/topology/authorization | NOT VERIFIED; no deployment, merge or publication authorized |
+
+Use PASS, FAIL, BLOCKED or NOT RUN with provenance. The source SHA precedes this documentation commit; the final PR handoff must separately name the actual post-push head SHA. Earlier October results at efa6 (253 genuine) and 0f375 (430 recovery), and the earlier 41-suite/393-test Jest report, remain as the prior checkpoint in the linked evidence. No real seed, private key, account identifier, label content, plaintext backup or credentials are included in the evidence.
+
+## Common cases required for every operation
+
+| Case | Required assertion |
+| --- | --- |
+| C1 committed match | Real local commit precedes cloud send; operation ID, originating account/session, generation, decrypted payload/target and original verified base are valid. Exactly one intended v2 effect reaches the production transport/HTTP path. Local results survive cloud failure. |
+| C2 uncommitted/stale state | Failed/partial local commit, stale generation/payload, wrong encryption owner or missing operation proof sends no mutation. No pre-persistence upload or newly verified base is substituted. |
+| C3 account session | A→B→A before send performs no old-session mutation; change after send remains uncertain/pending for A without using B's key/data or changing B's status. |
+| C4 remote conflicts | Apply the proposed effect against the validated remote snapshot; remote-only records and immutable identity conflicts are preserved without automatic overwrite/deletion. |
+| C5 consent | Disabled/unconsented accounts send zero automatic mutations. The separately explicit whole-backup opt-out preserves its consent choice until positive acknowledgement. |
+| C6 competing writer | A real revision race/409 stops the chain and leaves pending; no refreshed base authorizes an old payload. |
+| C7 old/malformed protocol | 404/unsupported v2, malformed snapshot or acknowledgement, false/missing preconditionApplied, and invalid/missing newRevision fail closed with no legacy fallback. |
+| C8 timeout/lost acknowledgement | Read back uncertain server state before fresh work; do not replay ciphertext or send later fanout members. Matching content alone does not complete the interrupted originating operation. |
+| C9 complete readback | Final decrypted server image includes all recovery records/references and matches freshly captured local state at the same committed generation/session. Corruption, partial response or missing references cannot produce verified. |
+| C10 final commit race/restart | Inject a local mutation immediately before Redux verification commit: pending persists and verified is rejected. Restart keeps committed local data and pending state; it does not replay prepared payloads. |
+
+## Seven-operation host matrix
+
+The genuine matrix uses actual production snapshot/commit/automatic/transport code, real AES, production schemas and encrypted native Realm, extracted production Redux middleware/store observers, and real HTTP into the pinned transactional Relay. Common negatives include stale generation, queued A→B→A, remote-only/key conflict, failed commit, copied/missing proof, unsupported/malformed protocol, timeout/lost ACK, incomplete/wrong-key readback and closed/reopened Realm. The additional after-send A→B→A and inter-member native-write schedules passed 8/8 at fixture commit 7b1ad70ba9e2aa1a2778b375f36e776bdd26a5ad, before source commit efa6f89ebf7140f738f03ce8a7218a2a1e7f9bc2 enabled development loopback testing. The combined final runner result is recorded separately.
+
+Most operation mutation callbacks in the core matrix are constructed directly over the production commit API. Separate producer files exercise actual wallet/vault, signer/registration, label, version-upgrade and existing-USDT functions. Seven additional cases exercise real Redux Persist reconciliation in both BHR/legacy-root orders and the actual UI AST declaration projection over native Realm/HTTP proof. This does not attest rendered React Native UI, native MMKV, UI navigation or native app relaunch. USDT new-wallet creation/import remains paused; tested USDT records are existing retained records only.
+
+| Operation | Observed production proof | Host result / evidence |
+| --- | --- | --- |
+| updateAppImage | Committed wallet/signer records, node exact-set replacement and app/version metadata; stale action ciphertext rejected | PASS existing core/producer cases; added held-ACK schedules PASS; [October proof](evidence/automatic-backup-source-proof-2026-10-13.md) |
+| migrateXfps | Exact old/new KeyUID and committed sanitized signer, live/archive vault references and registration/policy continuity | PASS existing core + signer producer 9; added held-ACK schedules PASS; [October proof](evidence/automatic-backup-source-proof-2026-10-13.md) |
+| deleteAppImageEntity | Committed local BTC/USDT/signer absence with validated expected remote target and retained recovery content | PASS existing core + existing-USDT producer 11; added held-ACK schedules PASS; [October proof](evidence/automatic-backup-source-proof-2026-10-13.md) |
+| deleteVaults | Exact committed local absence and preserved retained/server-only recovery records | PASS existing core; added held-ACK schedules PASS; [October proof](evidence/automatic-backup-source-proof-2026-10-13.md) |
+| updateVaultImage | Committed vault/policy/archive/signersData and shared registrations; real create/archive and correction fanouts | PASS existing core + wallet 8 + signer 9; added held-ACK schedules PASS; [October proof](evidence/automatic-backup-source-proof-2026-10-13.md) |
+| modifyLabels | Committed tags, exact account-derived hash/ciphertext, grouped send/change labels and import rollback | PASS existing core + label 9 + upgrade 9; added held-ACK schedules PASS; [October proof](evidence/automatic-backup-source-proof-2026-10-13.md) |
+| deleteBackup | Fresh explicit same-session opt-out, positive ACK, complete empty readback, retained local records and protected consent completion | PASS existing core including newer-choice/reentrant completion guards; added held-ACK schedules PASS; [October proof](evidence/automatic-backup-source-proof-2026-10-13.md) |
+
+## Logical fanout and producer proof
+
+| Scenario | Result / observed boundary |
+| --- | --- |
+| New vault plus archived predecessor | PASS real wallet producer migration; both local effects precede HTTP, archive sends before new vault, success readback and second-CAS rejection tested |
+| Shared registration | PASS real persisted VaultSigner registration fans out to active/archive vaults; complete readback required; second CAS rejection leaves pending |
+| Label import plus deletion / grouped send labels | PASS actual label producers, real tags/AES/HTTP; invalid late import rolls back atomically; 409/404/malformed/lost response preserves local data |
+| First fanout member succeeds, next fails | PASS second-member 409 schedules for create/archive, shared registration and label fanouts. Signer/upgrade lost-first-reply schedules stop later effects. This does not claim every fault was injected at every position |
+| Native local mutation between fanout members | PASS added actual native-write schedule after first real CAS while its ACK is held: the next prepared member sends nothing, local data survives and pending remains |
+| New verification cannot authorize old/cloned intent | PASS immutable original-base/captured intent/operation tests, queued stale generation and no-original-baseline producer cases |
+| Local-first creation/edit/deletion | PASS observed actual wallet/vault/signer/label/upgrade/existing-USDT producers; failures retain truthful committed local results and pending backup |
+| Disabled/unconsented account | PASS no-original-baseline/consent-off host cases and unit coverage; no inherited consent or upload. Fresh explicit whole-backup opt-out while consent already off is separately tested |
+| Complete encrypted restore | PASS actual Recovery Key worker into blank Realm; BTC MAINNET/TESTNET, existing DEFAULT/IMPORTED USDT, keys, active/archive vaults, registrations, labels and nodes |
+| Final verification race | PASS native write immediately before actual Redux verification dispatch leaves pending; copied/uncommitted proof cannot bypass it |
+| Account change after send | PASS added after-send A→B→A for all seven operations, with a distinct B seed/account/publicId and independently verified B backup; old A completion leaves B state, native data and remote backup unchanged |
+| Realm close/reopen | PASS stale queued proof rejects the reopened handle; this is not native app/process restart or MMKV evidence |
+| Persisted host rehydration / current-proof display | PASS six actual Redux Persist boot/consent/durability cases and one actual UI AST declaration projection case over native Realm/HTTP. Saved Verified/interrupted/completed status expires to unverified/pending; consent, confirmation, local records and existing negative findings survive. Canonical consent wins both read orders and subscriber prefixes; only confirmed absence permits fallback, errors deny it, and late raw legacy fallback preserves continued nested writes. No replay or upload; only fresh complete readback restores proof |
+| Persisted app interruption/relaunch and background behavior | NOT RUN; mandatory IOS/ANDROID Local checks |
+| Transactional HTTP contract | PASS actual paired route/service/Mongoose transaction path and disposable source contract checks; hosted artifact parity, topology, limits and old-writer fleet rollout remain unverified |
+
+## Mandatory critical native acceptance
+
+Both platforms must test the final source with disposable accounts/data and a compatible fixture backend. Do not replace the owner's installed app or mutate real wallets for this matrix. Use native build/launch plus simulator/emulator flows; unit mocks and a historical simulator compile do not substitute for launch/flow evidence.
+
+| Native scenario | IOS result + evidence | ANDROID result + evidence |
+| --- | --- | --- |
+| Build and launch exact source; identify native package/version and backend source | NOT RUN | NOT RUN |
+| Cold launch with saved Verified/interrupted state, nested/legacy consent precedence and durable MMKV: unverified/pending until fresh complete readback; no replay, preserved local data/choices/confirmation | NOT RUN | NOT RUN |
+| Opted-in automatic create/edit/delete after initial backup; local data survives forced cloud failure and relaunch | NOT RUN | NOT RUN |
+| Complete server readback and clean Recovery Key restore of newly produced committed dataset | NOT RUN | NOT RUN |
+| Legacy encrypted snapshot upgrade plus absent/stale/transport/server/decryption failure; no false missing/empty/verified or unsolicited replacement | NOT RUN | NOT RUN |
+| Account/consent switch including A→B→A while connectivity/queue/readback waits; no cross-account upload, key selection, persistence or status change | NOT RUN | NOT RUN |
+| Local mutation during upload/readback/final completion; truthful pending and no stale verified | NOT RUN | NOT RUN |
+| Interrupted/uncertain write, relaunch and manual read-only reconciliation; no ciphertext replay or spinner trap | NOT RUN | NOT RUN |
+| Interrupted clean recovery preserves truthful incomplete result; correct Recovery Key retries unavailable/corrupt backup without incorrect-words/empty-success feedback | NOT RUN | NOT RUN |
+| Registration-only repair and immutable key/policy conflict, with all affected vaults included in verified readback | NOT RUN | NOT RUN |
+
+Native performance/layout and hardware/physical-only results remain separately described in [nfr-review.md](nfr-review.md) and the final Local handoff. Any accepted physical-only follow-up must name the exact unperformed scenario and its authority; it must not relabel required critical native safety checks as optional. Store/signing/deployment/merge approval remains separate from test results.
+
+## Durable evidence and handoff
+
+The October proof record is sanitized durable evidence; September files remain unchanged. After the final Cloud push, the AGENTS.md Codex local handoff must name the actual current PR head and required IOS, ANDROID and relevant HARDWARE checks. Each native row requires exact-head Local results; new code commits invalidate prior signoff. Source/disposable passes do not authorize hosted rollout, merge, signing, store submission or publication.
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..7879706444
--- /dev/null
+++ b/openspec/changes/fix-recovery-backup-freshness/design.md
@@ -0,0 +1,57 @@
+> Current R4 contract: [protected backup integration](protected-backup-integration.md) supersedes the historical v2 protocol and whole-copy Delete language below. Prior checked source/fixture boxes are SHA-scoped historical evidence, not protected-v3, native, hosted or release acceptance. Delete now applies only to the new protected copy; older encrypted copies remain read-only. All-copy erasure is outside approved R4 scope, unimplemented and unscheduled.
+
+# Design
+
+This is the R4 contract reconciled on 13 October 2026 from audit starting app head b160656218dc6065ad12af9db220c974255bfc23. The implemented source and observed host Realm/transactional HTTP proof are recorded in [the result matrix](automatic-write-validation.md) and [October evidence](evidence/automatic-backup-source-proof-2026-10-13.md). Source readiness permits development loopback testing; hosted Relay rollout remains disabled. The September native/fixture results in [validation](validation.md) remain historical.
+
+## Entry points, consent and user flow
+
+Reuse More → Backup and Recovery → Assisted Server Backup, AssistedBackupStatus and the existing notification. Login may schedule a read-only comparison for an opted-in pending/unverified account after essential startup/sync work, without awaiting its network result. Account-scoped opt-in never transfers to another account. A legacy global flag is migrated only with evidence of the consenting account.
+
+The status screen keeps real checking, preparing, uploading and verifying stages, slow-operation explanation and an immediate Back action. Leaving does not imply rollback or continued background execution. Durable per-account pending/unverified state survives restart; active spinner state is transient. Different content offers explicit Back Up Now; a failed check reports an unavailable/unverified result, not missing data or permission to replace it. Recovery Key physical confirmation and verified server content are distinct states.
+
+## Local transaction and operation identity
+
+Each logical recovery operation captures the originating app/account, selected-account session, operation ID and originally verified remote revision/epoch before asynchronous work. Local changes are saved first. After all related Realm writes succeed, the operation obtains an account-scoped monotonic committed recovery generation. Pre-write invalidation alone is not a commit token. Failed/partial writes never authorize a cloud mutation or success; retain any local data and a pending result for reconciliation.
+
+New wallets, signers, vaults, node changes and deletions must not depend on server acceptance to persist locally. Producers previously sending encrypted data before Realm insertion/deletion are reordered. If work is interrupted after the local commit, the data and durable pending status survive; restart reconstructs fresh work only after reading local/remote state, not by replaying old ciphertext.
+
+An A→B→A transition invalidates the original A session, even if the same account ID returns. No worker substitutes another account's seed, destination or persistence context. A fresh check cannot retroactively grant an older action a new base revision or committed-generation token.
+
+## Queue-head proof and recovery comparison
+
+The per-account queue covers automatic app/vault/label/deletion mutations and explicit inspection/repair through final readback. Different accounts remain isolated. Each automatic effect must be proved at the queue head using fresh committed local recovery data, account/session, consent, encryption-key ownership, operation ID and generation. Stale action payloads, failed commit, generation/session change or missing intent leave pending without network.
+
+image.ts compares canonical decrypted recovery data with deterministic ordering. Ignore rebuildable chain/balance/sync/receiving-address caches and live connection flags. Retain keys, derivation, address counters, manual UTXO spendability overrides by outpoint, signer/vault policy, archive state, labels, nodes and user metadata. Include both BTC networks, USDT, signers and all referenced vault/label records. Sanitize secrets with existing helpers; checking does not mutate Realm.
+
+Prove additions/updates by decrypting the proposed record and matching its exact ID and recoverable fields with the committed record. Prove deletion by committed local absence and presence in the validated remote snapshot; retained vaults must remain recoverable. migrateXfps uses exact KeyUID map entries, not bare fingerprints, and validates affected vault signer references. Labels use account-derived hashed IDs and current tag content. Whole-backup deletion is a separate explicit same-session opt-out operation; preserve the user's consent choice until a positive acknowledgement, complete empty readback and final current-session/current-consent-epoch commit. A newer off-to-on choice cannot be overwritten by the older deletion completion.
+
+Apply the proposed operation to the validated remote snapshot in memory before send. Reject removal of remote-only recovery records or immutable key/derivation/network/script/policy conflicts without explicit reconciliation. An invalid/partial/decryption-failed response is unavailable, never empty. Repairable registration metadata is distinct from immutable identity and must be preserved and propagated to every affected vault with readback.
+
+## Revisioned server contract and logical fanout
+
+Read getBackupSnapshot through the validated v2 protocol, including a valid 64-character revision and required capabilities. Automatic and explicit repair writes use revisionedBackupMutation; an explicit repair identifies operation repairAppBackup. Never fall back to legacy full replacement or an old incremental route after 404, 409 or protocol failure.
+
+The Relay must atomically compare expectedRevision and apply all effects, preserving recovery records and rejecting ownership/reference/identity conflicts. A valid acknowledgement requires updated: true, preconditionApplied: true and a valid newRevision. Capability advertisement alone is not proof that a particular mutation used a precondition.
+
+Prefer one revisioned transaction for a logical fanout, including new+archived vault migration, registration affecting several vaults, and label import/deletion. If the existing route is used sequentially, every member revalidates its committed local proof and uses the preceding acknowledged newRevision; do not reuse one captured base for all members. Partial success is pending, with local data retained. A failed/uncertain member stops later prepared members. Intermediate responses never mark the whole backup verified.
+
+A request timeout/lost response may have committed on the server. Do not replay its ciphertext or assume a failed server write. Read back before deciding on any fresh write. The originating operation remains pending without a valid acknowledgement; a later independent read-only check may establish a new verified baseline only after complete content, current generation/session and protocol checks. It must not report the interrupted producer or fanout as completed.
+
+## Complete readback and atomic UI completion
+
+After the last acknowledged effect, read back and decrypt the complete server image, validating all referenced records. Compare it with a newly captured local image at the same committed generation. Recheck the originating account/session, consent, generation and operation at the final Redux verification commit. A concurrent local mutation, incomplete response, missing record or immutable conflict invalidates completion. Only this atomic final transition may set verified or clear durable pending state.
+
+BHR defines persisted per-account verification/repair state separately from transient running state. Nullish defaults protect older persisted state. Account switching cannot clear another account's pending flag or grant its backup consent. Interrupted state returns to pending/unverified until a fresh read-only comparison completes. The host fixture uses real reducers and extracted production store hooks/origin middleware; it does not prove MMKV persistence or native app relaunch. Those checks remain in the required IOS/ANDROID matrix. No Realm schema migration is authorized by this document.
+
+## NFR and restore boundaries
+
+Existing engineering bounds are a 30-second no-progress transport abort and a ten-minute overall deadline. Genuine upload/download byte progress resets the stall timer; repeated equal byte counts do not. They remain provisional until native/deployed request-limit checks pass. Error reporting excludes Axios bodies/headers and private recovery material.
+
+Crypto yields between 16 KiB chunks while retaining the existing OpenSSL format. Record/aggregate limits reject oversized data without truncation or verified success. Realm extraction, JSON, Base64 and UTF-8 still contain synchronous work; desktop timing is not native frame-time or memory acceptance. Preserve [the NFR review](nfr-review.md) as historical benchmarks and an open measurement plan.
+
+Recovery predecodes the complete image and validates referenced vault/label identity before persistence. Failed local persistence or a derived Recovery Key identity mismatch prevents success; no failed records are skipped. Local restoration currently has sequential writes, so interruption may leave partial local records without completing recovery. Exact-head disposable and native clean/retry/interruption restore checks are mandatory before release. A correct Recovery Key with unavailable/corrupt backup receives retry feedback, not an incorrect-words error.
+
+## Release gates
+
+The automatic fix, all seven operation proofs, fanout/failure/readback matrix and critical iOS/Android backup tests are required R4 work, not a post-release waiver. Physical-device-only checks may be separately reported after release when authorized. Old-client/fenced-writer behavior needs exact-source disposable replica-set/HTTP proof; production transaction topology, running artifact, request limits and legacy-writer drain/rollout remain separately gated by operator access and explicit authorization. Source readiness is not deployed-service evidence.
diff --git a/openspec/changes/fix-recovery-backup-freshness/evidence/automatic-backup-source-proof-2026-10-13.md b/openspec/changes/fix-recovery-backup-freshness/evidence/automatic-backup-source-proof-2026-10-13.md
new file mode 100644
index 0000000000..97406bb7c8
--- /dev/null
+++ b/openspec/changes/fix-recovery-backup-freshness/evidence/automatic-backup-source-proof-2026-10-13.md
@@ -0,0 +1,62 @@
+# R4 automatic backup source/disposable proof — 13 October 2026
+
+This is a sanitized result summary. It contains source identities, commands, counts and test boundaries only. It contains no backup content, real account/wallet identifiers, labels, seed material, private keys or credentials. Existing September logs are preserved unchanged.
+
+## Source identity and enablement boundary
+
+- Final tested app code commit before this documentation commit: `3cc9368ca2f3b2149db5743a5f9d230aa516d6a0`. This includes persisted BHR proof expiration before reconciliation, current-proof UI status projection and seven added genuine cases, in addition to the earlier frozen-Yarn and utility fixes.
+- Paired Relay: `b600416e5ba7325927d7d2871cff7776f4e593fe`. The app runner requires this exact clean tracked checkout and the expected fixture path.
+- Final flags: `AUTOMATIC_BACKUP_SOURCE_READY=true` permits DEVELOPMENT loopback testing only; `AUTOMATIC_BACKUP_RELAY_ROLLOUT_READY=false` remains unchanged. Development source readiness does not enable hosted writes.
+- The final PR Local handoff must separately record the exact post-push head SHA. This evidence file cannot name its own future commit or confer release approval.
+
+## Genuine host Realm and transactional HTTP matrix
+
+Command: `npm run test:automatic-backup-genuine`, with Node 22.23.3 on Linux, actual Realm 12.15.0, `KEEPER_RELAY_FIXTURE_MODULE` pointing to the pinned Relay's `tests/support/automaticBackupHttpFixture.cjs`, and `BACKUP_TEST_MONGO_URL=mongodb://127.0.0.1:27058`. The runner refuses a missing/different/dirty tracked Relay, missing required matrix, unavailable native binding, unsupported Node or non-loopback/credentialed Mongo. A missing prerequisite fails; it is not skipped or replaced by a unit adapter.
+
+Final combined command outcome/time: **PASS 260/260, 0 failures, 0 skips**, exit 0, 208.779 seconds; clean frozen-Yarn run terminal log recorded 2026-10-13 05:26 UTC on the exact app/Relay sources above. Earlier combined seven-file run passed 245/245 with zero skips. Eight added direct schedules passed 8/8 with zero skips, 30.469 seconds, observed 2026-10-13 04:08 UTC at fixture commit 7b1ad70ba9e2aa1a2778b375f36e776bdd26a5ad: one native local change after the first actual CAS while its ACK is held, and after-send A→B→A for each of the seven operations. Each B account uses a distinct seed/appId/publicId and real verified B baseline; old A completion preserves B UI/native/remote state. The final seven-file combined run includes all eight schedules at the enabled code SHA.
+
+| File / scope | Observed result |
+| --- | --- |
+| automaticWriteRealmRelay.integration.cjs — all seven operations and shared queue/proof gates | 213/213 PASS, including held-ACK schedules plus seven rehydration/current-proof projection cases |
+| automaticRecoveryRestore.integration.cjs — whole Recovery Key restore | 1/1 PASS; strengthened whole-image/all-signers/normalized-nodes comparison also reran 1/1 PASS |
+| automaticLabelProducers.integration.cjs — actual label import/edit/send/manual-coin producers | 9/9 PASS |
+| automaticUpgradeProducer.integration.cjs — actual launch upgrade/version/health/label fanout | 9/9 PASS |
+| automaticWalletProducer.integration.cjs — actual wallet/vault creation, rename and migration | 8/8 PASS |
+| automaticUSDTProducer.integration.cjs — existing DEFAULT/IMPORTED metadata/deletion, cache and paused creation | 11/11 PASS |
+| automaticSignerProducer.integration.cjs — actual correction/registration/live/archive fanout | 9/9 PASS |
+
+The fixture loads actual production Realm wrappers and schemas, snapshot/sanitization/AES, backup automatic coordinator/transport, real Redux reducers, extracted production account-origin middleware and store observers. The paired server runs real HTTP through extracted production routes, production services and Mongoose transactions in a disposable keeperQA replica set. Protocol fault interception is explicit: malformed/old/missing/false ACK, 404, 409, lost or delayed reply and corrupt readback. Negative tests assert zero unauthorized effects or stopped fanout, retained local data, and pending/unverified status. They never manufacture an operation receipt, generation or baseline.
+
+Core mutation callbacks are often built directly over the production commit API; the five producer suites and selected BHR cases additionally execute actual source functions. Host platform/device-info, MMKV persistence adapter, unused RSA and notification helpers are disclosed host boundaries. The seven new cases comprise six actual Redux Persist boot/consent/durability cases and one actual UI AST declaration projection case over native Realm/HTTP proof. They assert saved Verified/interrupted/completed flags become unverified/pending without changing consent, physical confirmation or local records; existing negative findings survive. Canonical nested opt-out wins both read orders and every subscriber prefix; legacy fallback requires confirmed absence, a read error denies it, and absence-first legacy fallback retains live persistence metadata so later consent/pending changes really flush. Rehydration sends no Relay read, repair or write and grants no usable write intent. A fresh complete encrypted HTTP inspection alone restores current proof, and a new post-inspection operation alone may upload. The display checks project actual source declarations; no rendered React Native UI, native MMKV, full app boot, UI navigation or physical signing is attested.
+
+Clean restoration uses real BIP39/BIP32/BIP85/AES and actual getAppImageWorker/recoverApp/writeRecoveredObject into a blank encrypted Realm, reading from the actual HTTP Relay. The dataset includes BTC MAINNET and TESTNET, retained DEFAULT and IMPORTED USDT key/address/history metadata, Recovery Key and other signer data, active/archived vaults, registrations, labels and both-network nodes. Whole recovery-image comparison, complete signer fields and normalized nodes are asserted. Initial database opening is a real dbManager call, outside the native passcode/UI flow. No new USDT setup/import, provider transfer or consent opt-in is enabled by this test.
+
+## Other Cloud checks
+
+| Check | Actual outcome / boundary |
+| --- | --- |
+| Recovery suite: `npm run test:recovery` | 443/443 PASS, zero failures/skips, 52.156 seconds, exit 0 on app source 3cc9368ca2f3b2149db5743a5f9d230aa516d6a0. Producer unit adapters are distinguished from genuine integration files; actual native Realm wrapper regressions are included |
+| Realm commit/invalidation/open-session focused suite | 20/20 PASS, including ten actual-native atomic commit/rollback/observer cases |
+| Root Jest | 42 suites / 432 tests PASS, exit 0, 37.9 seconds on 3cc9368ca2f3b2149db5743a5f9d230aa516d6a0 |
+| Release tooling | Coordinator reports Node 28 PASS, Python 7 PASS and Ruby 21 runs / 117 assertions PASS; these are tooling tests, not signing/store validation |
+| Local validation gate tests | Coordinator reports 11/11 PASS; gate test code passing does not supply an actual Local validation comment |
+| Focused six core backup modules lint/format | Recorded PASS; distinguished from whole-repository lint |
+| Whole-repository lint CLI | Prior 2071 hosted run actually FAILED with 5353 problems: 4467 errors and 886 warnings. The job tolerated this failure and completed green; neither job status nor focused checks is a clean whole-lint pass |
+| Whole-project TypeScript | FAIL: coordinator reports 945 inherited diagnostics versus 957 at baseline bb66cea459fbb00ec33c5c4ebd601d07c0d7c125, zero added normalized diagnostics. No clean whole-project typecheck is claimed |
+| Current release preflight | FAIL: observed 2026-10-13 04:11 UTC, iOS store history older than 24 hours; no release-readiness pass is inferred from tooling tests |
+| Source-specific CI | Source #7042 at 163cccb831f824b3daacc05199421683abdaf1ad passed hosted Tests/CodeQL: 341 Jest, 210 recovery, 12 JavaScript + 7 Python release checks and version 2.6.3. Changes are test-only fixtures/AES assertion/CI trigger; runtime d280 unchanged. Prior 74df and 28c7 failures remain source-specific history below; these results are not combined R4 or native signoff |
+| Independent agent fixture review | PASS architecture/evidence review after strengthening missing full-signers/nodes restore assertions; no external final-source developer signoff implied |
+
+## Preserved earlier October checkpoints
+
+The earlier source checkpoint remains evidence for its own tested source: genuine 253/253, zero failures/skips, 162.1566 seconds at app efa6f89ebf7140f738f03ce8a7218a2a1e7f9bc2 and the same pinned Relay, terminal recorded 2026-10-13 04:12 UTC. Earlier recovery 430/430, zero failures/skips, 47.9 seconds was run on 0f37506a58e6bf44061dd6788b20e5fa095a10c6 after the c308aa405 session guards. The coordinator's earlier Jest report was 41 suites / 393 tests PASS. These are historical October results, superseded for the current source by the refreshed counts above; no result is retroactively transferred to a new SHA. September evidence files are unchanged.
+
+The later a243b53b5682a276eb88851c3d34379c0908fedd source checkpoint passed genuine 253/253, zero failures/skips, 195.046 seconds at 04:40 UTC; recovery 434/434 in 67.140 seconds and Jest 42 suites / 432 tests in 72.836 seconds. Hosted combined head 2071acbdcc572de9988d41f894b7356618bc14be then passed Tests run 38348159148 (genuine 253 with zero skips, recovery 434, Jest 42/432) and CodeQL check 115134694738 SUCCESS. Its whole lint CLI nevertheless failed with the 5353 problems stated above. That checkpoint preceded the rehydrated-Verified proof fix and cannot prove the new source or native cold launch.
+
+Source #7042 history is separate: trigger correction 74df55446d8645ebfac05405fce81fa43446acd9 had separate CodeQL/Analyze SUCCESS but Tests run 38347397038 failed 34/35 Jest suites, 333/340 tests (seven unchanged live-network Electrum failures); recovery/version/release were skipped. The intervening 28c7 test-fixture attempt also remained a failed source-PR checkpoint. Final test-only 163cccb831f824b3daacc05199421683abdaf1ad corrected fixtures/AES assertion/trigger and passed its own hosted checks with runtime d280 unchanged. It is source-specific version 2.6.3 evidence, not the combined R4 app's final-head checks. Subsequent current-head CI outcomes are recorded externally on the PR after the final documentation push.
+
+## Open gates
+
+IOS and ANDROID exact-source build/launch, automatic create/edit/delete/relaunch and complete Recovery Key restore safety matrix: **NOT RUN / NEEDS_LOCAL**. Host SDK close/reopen is not proof of process restart, persisted MMKV pending state, background execution, UI layout, enlarged text, memory or native 1/10/50-wallet profiling. Physical-only follow-up needs a separately recorded owner decision; it cannot waive critical native checks.
+
+Hosted running Relay source parity, transaction topology, request limits, old/legacy-writer fleet rollout and production authorization remain unverified. Final current-head CI/external developer review, store histories/counters, signed artifact identity, merge/signing/submission/deployment/publication approval remain open. This source/disposable proof does not authorize any such operation and stays independent of Reproducibility, Bitkey/Recoverable Wallet and unrelated R4 deliverables.
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..9a5a603f21
--- /dev/null
+++ b/openspec/changes/fix-recovery-backup-freshness/nfr-review.md
@@ -0,0 +1,54 @@
+# Backup comparison and repair: NFR review
+
+Reviewed 29 September 2026; evidence boundary clarified 13 October 2026. This file preserves the historical check → prompt → update → verify audit and measurements. Statements below about implemented safeguards, completed native runs or infrastructure describe that historical candidate; they are not exact-head R4 automatic-write acceptance. See [design.md](design.md), [validation.md](validation.md) and [the current automatic-write matrix](automatic-write-validation.md) for current requirements/results. No approved numerical backup performance budgets were found in the product sources or OpenSpec documents searched at the historical review. The thresholds below remain proposed engineering targets, subject to native validation.
+
+## Current source evidence and unrun native measurements
+
+The October source/fixture results are linked in [the result matrix](automatic-write-validation.md) and [the sanitized proof record](evidence/automatic-backup-source-proof-2026-10-13.md). Host Realm/HTTP failure, timeout and readback tests exercise production cancellation and truthful pending state; they do not measure React Native frame time, memory, accessibility or background persistence. Required IOS/ANDROID safety flows and native 1/10/50-wallet profiles, including enlarged text and large/single-record workloads, remain NOT RUN. Development loopback readiness does not approve hosted limits, running artifacts, store submission or release.
+
+## Historical original observed gaps
+
+- `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.
+
+## Historical native acceptance matrix
+
+**Historically completed, September source only:** native small-fixture upgrade and clean recovery on Android/iOS, Android repair/readback, iOS backend failure/retry. These development/simulator results do not validate the final R4 automatic pipeline.
+
+**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.
+
+## Historical 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..9c55ef90b6
--- /dev/null
+++ b/openspec/changes/fix-recovery-backup-freshness/proposal.md
@@ -0,0 +1,27 @@
+# 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. Permanent loss of wallet keys or funds was not established. Later source review found that a previously verified Relay revision and selected account alone cannot prove that a prepared automatic mutation represents committed local recovery data.
+
+## R4 / 2.6.4 scope
+
+The automatic-backup fix and disposable proof are mandatory R4 work. Critical native iOS/Android backup acceptance also precedes release; physical-device-only follow-up may be recorded separately after release when authorized. Green tests for an earlier repair candidate do not satisfy the automatic-write gate.
+
+- Persist each wallet, signer, vault, label, node or deletion locally before queuing its automatic cloud effect. A cloud failure must retain the committed local result and a truthful pending backup status; server success is not a prerequisite for local creation or deletion.
+- Bind each operation to the originating account/session, committed recovery generation and operation ID, plus its originally captured verified remote base. Reject stale work, including A→B→A, rather than substituting new account data or a newer verification for an older action.
+- At the per-account queue head, prove the decrypted payload or deletion target against fresh committed local recovery data. Preserve remote-only records and immutable key/policy identity absent an explicit user decision.
+- Use the revisioned v2 Relay contract with atomic compare-and-swap. Prefer one transaction for a logical multi-record operation; any sequential fanout must use each acknowledged new revision, revalidate local proof and stop on the first uncertain/failed step.
+- Keep the whole backup pending until complete decrypted readback matches fresh local recovery data at the same committed generation and the final atomic verification commit succeeds. A response, intermediate fanout success or content-only readback after a lost acknowledgement does not complete the originating operation.
+- Keep upgrade/login checks read-only. Historical mismatch repair remains explicit in Notifications and More → Backup and Recovery → Assisted Server Backup. Transport/decryption failure is never an empty backup or permission to replace it.
+- Preserve per-account consent and status, bounded truthful progress, data format, Recovery Key confirmation and failure feedback. Never truncate recovery records or put private material in diagnostics.
+
+## Status and evidence boundary
+
+Audit starting source: b160656218dc6065ad12af9db220c974255bfc23, 13 October 2026. At that baseline, backupPost rejects automatic mutations before network because end-to-end committed-payload proof is missing. Automatic transport may be enabled only after implementation and the required disposable matrix pass; an endpoint name or valid revision is insufficient.
+
+The source now saves logical local operations atomically and proves their committed generation, account/session/consent and payload before revisioned writes and complete readback. The recorded host Realm/transactional HTTP tests support development loopback testing: `AUTOMATIC_BACKUP_SOURCE_READY=true`. `AUTOMATIC_BACKUP_RELAY_ROLLOUT_READY=false` keeps hosted writes fenced. This is source/disposable readiness, with the precise tested cases and remaining gaps recorded in [the current result matrix](automatic-write-validation.md) and [October evidence](evidence/automatic-backup-source-proof-2026-10-13.md).
+
+See [design](design.md), [implementation tasks](tasks.md) and [automatic write readiness](automatic-write-readiness.md). [Validation](validation.md) preserves September results unchanged as historical evidence; they are not exact-head R4 signoff.
+
+Current-source independent review, critical native checks, compatible Relay source/deployment evidence and release approval remain separate gates. No merge, production action or publication is authorized by this proposal. Existing backups missing data still need a device that holds it; this work does not reconstruct arbitrarily missing wallets.
diff --git a/openspec/changes/fix-recovery-backup-freshness/protected-backup-integration.md b/openspec/changes/fix-recovery-backup-freshness/protected-backup-integration.md
new file mode 100644
index 0000000000..b23a274f19
--- /dev/null
+++ b/openspec/changes/fix-recovery-backup-freshness/protected-backup-integration.md
@@ -0,0 +1,37 @@
+# Current R4 protected-backup contract
+
+This supersedes older v2 and whole-copy Delete requirements for the owner's approved R4 scope. It does not mark the release complete. Exact source checks and native instructions belong to the newest PR #7045 handoff and the accompanying release evidence.
+
+## Identity and authorization
+
+The Recovery Key derives a separate self-certifying `bk3_` namespace using BIP39 seed bytes, HKDF-SHA256 and hardened BIP32 child0. The isolated supported signing implementation must not use the old wallet signing adapter. Verify that mnemonic, canonical lowercase stored seed and original Keeper App ID agree before enrollment or writing. Preserve all existing wallet, encryption and BIP85 derivations.
+
+The original Keeper App ID continues to own Realm, accounts, provider and billing identity. A backup namespace never replaces it, adopts a legacy account or grants a subscription. Authenticate requests using the fixed ES256K JWS profile, exact body bytes, audience/path/namespace and bounded freshness. Reads and enrollment cannot reset generation, epoch or tombstones.
+
+## Writes and complete verification
+
+All seven automatic operations and explicit full repair use protected v3 transport. Retain the original committed-local receipt, account session, consent epoch, fingerprint and namespace/revision/remote-generation/auth-epoch tuple before asynchronous work. Sequential fanout advances only through each member's own positive acknowledgement. No retry/rebase of uncertain ciphertext, observer uploads or substitution of a newly verified base.
+
+Validate the raw complete projection and its checksum before identity adaptation. Decrypt every recovery record; verify strict protected wallet-map IDs, encrypted label IDs, vault scheme/archive/signer references and complete scoped maps, plus recovery metadata. Only fresh matching local evidence and final synchronous Redux admission can report Verified. The projection checksum is public consistency data, not ownership proof or a server signature.
+
+Status reads do not enroll or write. Compiled client availability is ON for the owner-directed store-review and intended 2.6.4 build; explicit opt-in or repair can enroll only within its original source/session/consent scope and unchanged authority proof. Backend readiness remains UNKNOWN; public release is HELD until actual readiness and separate owner release approval. Initial absence, enrolled-empty, tombstone, authorization/decryption/protocol/network failure and previously-known namespace conflict stay distinct.
+
+## Delete, disable and recovery
+
+Delete means **Delete protected backup**, including a protected copy created after upgrade. Confirm the scoped acknowledgement, advancing generation/epoch and complete empty tombstone readback before reporting success or disabling consent. Preserve local wallets/keys/Recovery Key, original account/billing identity, server identity/fences/generation and retained older encrypted copies. Disclose that older copies may remain read-only even after upgrading. All-copy erasure is separately unimplemented and unscheduled; no cleanup action is offered.
+
+Turning off automatic updates keeps existing copies and is not Delete. Persisted deletion hints are not fresh verification authority. A lost response remains unconfirmed.
+
+Clean recovery checks the authenticated protected namespace first. Never automatically fall back after absence, tombstone, errors or a known-namespace conflict. A separately selected **Recover an older copy** reads retained legacy data with provenance and a missing-newer-changes warning. Decode and validate the full selected image before the first local write; never report partial/conflicted/unavailable recovery as complete.
+
+A recovery request remains bound to its original request serial as well as account session through asynchronous decrypt/derivation and every consent, Redux and Realm write. Newer discovery cancels the old recovery task and called child generators; cancellation must not emit stale retry or completion. A superseded protected or older-copy request cannot mutate local data or consent.
+
+After validation, revoke target-account automatic-backup consent and expire old queued/opt-in scope before any restore write or producer. This applies even when saved consent was true for a not-yet-selected account. Neither recovery source silently enables or uploads the recovered copy; a later explicit opt-in is separate.
+
+## Acceptance and remaining gates
+
+Historical v2 proof stays historical. Preserve the public fixture/runtime pins and their existing guard; the separately identified exact-private genuine lane must prove current authority/transport/production consumers against real encrypted Realm and transactional loopback Mongo. Unit transport mocks, V8 bundle execution and Hermes bytecode compilation have narrower meanings than that lane or native UI acceptance.
+
+Compiled client availability admits hosted automatic transport, protected Delete and manual repair for store review and the intended app build, with per-account consent and original authority checks unchanged. Actual backend source/runtime/audience/provisioning/index/transaction/drain/ingress/read protection and compatible rollback readiness remain UNKNOWN; app availability and source tests do not establish deployment. Public release remains HELD until actual backend readiness, current-source review and separate owner release approval. Upgrading old writers requires actual per-platform availability and an approved denial interval; old binaries cannot be promised an upgrade prompt or truthful rejection UI.
+
+Exact-new-SHA IOS and ANDROID builds/install/launch and critical recovery/backup acceptance remain required. HARDWARE stays explicit; only an exact-SHA physical-only owner decision can defer eligible unrun physical checks. No failed critical check, store/artifact/review/channel gate or release approval is waived. Parked C8/navigation work and independence from Reproducibility/Bitkey remain unchanged.
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..ed49d4bdc7
--- /dev/null
+++ b/openspec/changes/fix-recovery-backup-freshness/specs/assisted-server-backup/spec.md
@@ -0,0 +1,152 @@
+> Current R4 contract: [protected backup integration](../../protected-backup-integration.md) supersedes the historical v2 protocol and whole-copy Delete language below. Prior checked source/fixture boxes are SHA-scoped historical evidence, not protected-v3, native, hosted or release acceptance. Delete now applies only to the new protected copy; older encrypted copies remain read-only. All-copy erasure is outside approved R4 scope, unimplemented and unscheduled.
+
+## MODIFIED Requirements
+
+### Requirement: Enabled Assisted Server Backup includes committed subsequent mutations
+The app SHALL automatically back up enabled recovery-relevant changes only after their successful local commit and operation-specific freshness proof. Pending historical repair SHALL NOT discard the local operation, grant consent or substitute for write proof. Server acceptance SHALL NOT be required to preserve local creation, edit or deletion.
+
+#### Scenario: A wallet is created after the initial backup
+- **WHEN** an opted-in account creates a Bitcoin wallet on either network after its initial backup
+- **THEN** save the wallet locally before queuing its cloud effect
+- **AND** capture the committed recovery generation and originating operation/account/session
+- **AND** prove its encrypted recovery content against fresh committed local data at queue head before a revisioned write
+- **AND** retain the wallet and pending backup state if proof or cloud transport fails
+
+#### Scenario: A local operation fails or commits only partially
+- **WHEN** related local writes fail or have not all committed
+- **THEN** do not authorize a prepared automatic cloud mutation
+- **AND** retain pending/unverified status without reporting the backup or partial operation complete
+
+#### Scenario: Backup is disabled or another account did not consent
+- **WHEN** local recovery data changes for a disabled or unconsented account
+- **THEN** send no automatic backup mutation
+- **AND** preserve local data and the other accounts' choices
+
+## ADDED Requirements
+
+### Requirement: Automatic intent proves committed payload and originating session
+Every automatic write SHALL bind its operation ID, committed local recovery generation, originating app/account session and originally captured verified remote revision/epoch. At queue head the app SHALL recheck consent, key ownership and current local recovery content. A revision string alone SHALL NOT authorize a write.
+
+#### Scenario: Local data changes while an action waits
+- **WHEN** a queued payload no longer represents its committed local generation or records
+- **THEN** reject it before network and keep backup pending
+- **AND** do not retry its ciphertext or silently grant it a newly verified base
+
+#### Scenario: The user switches A to B and back to A
+- **WHEN** work captured in the first A session resumes after A→B→A
+- **THEN** reject the old session before mutation or verified-state commit
+- **AND** never select B's encryption key, destination or local persistence for A
+
+#### Scenario: Deletion and identity migration
+- **WHEN** a committed deletion or signer-map migration is queued
+- **THEN** prove exact local absence/new identity and expected remote target
+- **AND** preserve retained vault recoverability and validate exact KeyUID map entries and affected references
+
+### Requirement: Revisioned mutations preserve complete remote recovery content
+The app SHALL validate the v2 snapshot and use an atomic expectedRevision precondition through revisionedBackupMutation. A positive acknowledgement SHALL include updated: true, preconditionApplied: true and a valid newRevision. The app SHALL NOT fall back to old incremental or full replacement endpoints after protocol, conflict or transport failure.
+
+#### Scenario: Remote-only or immutable conflicting content exists
+- **WHEN** the proposed effect would remove remote-only recovery records or change immutable key, derivation, network, script or policy identity without an explicit user decision
+- **THEN** preserve the remote backup and report conflict without sending that effect
+
+#### Scenario: Another server writer wins
+- **WHEN** the expected revision is stale or the Relay returns 409
+- **THEN** stop the originating operation, preserve local data and leave backup pending
+- **AND** re-read before preparing any new write
+
+#### Scenario: The server is old or its response is malformed
+- **WHEN** the v2 route returns 404 or acknowledgement/capability/revision validation fails
+- **THEN** send no legacy fallback and show pending/unverified feedback
+
+### Requirement: Logical fanout never completes on an intermediate response
+A logical multi-record operation SHALL use one atomic revisioned transaction or a serialized sequence that revalidates current local proof and uses each preceding acknowledged newRevision. The whole backup SHALL remain pending until every required effect and final readback complete.
+
+#### Scenario: Registration affects several vaults
+- **WHEN** a persisted VaultSigner registration must update multiple vault images
+- **THEN** preserve and propagate the committed registration metadata to every affected vault
+- **AND** verify complete readback rather than marking success after the first update
+
+#### Scenario: A later fanout member fails
+- **WHEN** a prior member succeeds but a later member fails or loses its acknowledgement
+- **THEN** stop all remaining prepared members, retain local results and keep pending
+- **AND** do not replay the prepared fanout or claim rollback/verified success
+
+### Requirement: Upgrade repair requires comparison and user action
+The app SHALL compare local recovery content with a complete decrypted server snapshot for an opted-in unverified account. Retrieval, validation or decryption errors SHALL NOT be interpreted as mismatch or empty backup.
+
+#### Scenario: Old backup omits local data
+- **WHEN** comparison detects recovery data present locally but missing remotely
+- **THEN** show a mismatch and Back Up Now through the existing backup area
+- **AND** do not replace the backup until the user explicitly starts repair
+
+#### Scenario: Backups match
+- **WHEN** complete canonical content matches fresh local recovery data and current account/session/generation/protocol checks pass
+- **THEN** mark that account verified without an upload
+
+### Requirement: Completion means complete verified recovery content
+After all acknowledged effects the app SHALL read back, decrypt and validate the complete backup, compare fresh local content at the same committed generation, and atomically recheck ownership/session/consent/generation before setting verified. A server acknowledgement alone SHALL NOT complete backup.
+
+#### Scenario: An acknowledgement is lost
+- **WHEN** a write fails after it may have committed on the server
+- **THEN** stop the operation and read back within bounded limits without replaying its ciphertext
+- **AND** do not mark that originating write or fanout complete from a content-only match
+- **AND** allow a later independent read-only reconciliation to establish a fresh baseline only after all current checks pass
+
+#### Scenario: A local mutation arrives before final completion
+- **WHEN** local recovery data changes during upload, readback or immediately before the Redux verification commit
+- **THEN** reject the completion claim and retain pending until a fresh comparison includes committed data
+
+#### Scenario: The app restarts or changes accounts
+- **WHEN** an operation is interrupted or its selected account/session changes
+- **THEN** preserve pending/unverified state for the original account without clearing another account
+- **AND** reconstruct fresh work after restart rather than replaying a prepared old payload
+
+### Requirement: Whole-backup deletion uses explicit same-account consent
+deleteBackup SHALL require an explicit opt-out for the same selected account/session and validated remote revision. It SHALL preserve the user's consent choice until a positive revisioned acknowledgement, complete empty readback and a current-session/current-consent-epoch final commit, and treat lost responses as uncertain.
+
+#### Scenario: Remote deletion acknowledgement is lost
+- **WHEN** explicit opt-out may have deleted the backup but no valid acknowledgement arrived
+- **THEN** do not claim deletion or consent-change success
+- **AND** preserve local recovery data and reconcile by readback before another deletion attempt
+
+#### Scenario: A newer consent choice arrives before deletion completes
+- **WHEN** the user makes a newer off-to-on choice while an older deletion is awaiting its reply or final completion
+- **THEN** reject the older consent completion and preserve the newer selected choice
+- **AND** retain pending/unverified state without claiming the older operation completed
+
+### Requirement: Repair has bounded accessible progress
+The repair screen SHALL expose truthful checking, preparing, uploading and verifying stages, slow-operation explanation after ten seconds and Back throughout. It SHALL NOT claim background execution or rollback. Stalled transport SHALL abort, repeated repair requests SHALL coalesce, and oversized records SHALL fail without truncation.
+
+#### Scenario: Transfer stops progressing
+- **WHEN** upload/download bytes do not advance for thirty seconds
+- **THEN** abort transport and retain pending/unverified status with manual checking available
+- **AND** repeated equal progress values do not reset the stall clock
+
+#### Scenario: The user leaves progress
+- **WHEN** Back is selected during repair
+- **THEN** keep navigation available and let status be revisited in Assisted Server Backup
+- **AND** preserve truthful durable state if the OS interrupts the operation
+
+### Requirement: Failed server backup is not shown as success
+Existing backup screens SHALL NOT enable Assisted Server Backup or display success following backup failure. Recovery Key confirmation SHALL remain a separate state.
+
+#### Scenario: Server backup fails after Recovery Key confirmation
+- **WHEN** the Recovery Key is confirmed but server verification fails
+- **THEN** retain physical confirmation and show backup-not-verified feedback without falsely enabling backup
+
+### Requirement: R4 includes current disposable and critical native proof
+The automatic-backup fix SHALL pass the current all-seven-operation disposable matrix, fanout/uncertain-response/final-readback safety proof and critical native IOS and ANDROID backup acceptance before release. Historical repair fixtures or native runs SHALL NOT substitute for exact-source automatic-write proof.
+
+#### Scenario: Only an older repair or desktop fixture passed
+- **WHEN** evidence does not exercise the final automatic producers, committed-generation/session proof and compatible transactional Relay
+- **THEN** leave the automatic-backup gate open and identify required exact-source checks
+
+#### Scenario: Physical-device-only tests are unavailable
+- **WHEN** an explicitly physical-only check cannot run before release
+- **THEN** record that separate follow-up honestly
+- **AND** do not defer required disposable or critical simulator/emulator backup create/edit/delete/relaunch/readback/restore checks
+
+#### Scenario: A clean Recovery Key restore is tested
+- **WHEN** disposable backup content produced by the current automatic pipeline is restored on IOS or ANDROID
+- **THEN** verify all intended wallets/networks, keys, active/archived vaults, registrations, labels and nodes
+- **AND** fail truthfully on missing/corrupt/unavailable data or interrupted local persistence rather than accepting an empty/partial restore
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..dfb8e7aa18
--- /dev/null
+++ b/openspec/changes/fix-recovery-backup-freshness/tasks.md
@@ -0,0 +1,51 @@
+> Current R4 contract: [protected backup integration](protected-backup-integration.md) supersedes the historical v2 protocol and whole-copy Delete language below. Prior checked source/fixture boxes are SHA-scoped historical evidence, not protected-v3, native, hosted or release acceptance. Delete now applies only to the new protected copy; older encrypted copies remain read-only. All-copy erasure is outside approved R4 scope, unimplemented and unscheduled.
+
+# R4 automatic Assisted Backup tasks
+
+Reconciled 13 October 2026 at audit starting app source b160656218dc6065ad12af9db220c974255bfc23, then updated from observed October source and disposable proof. The earlier checked checklist described a September candidate, including pre-persistence writes; it did not prove today's automatic-write contract. Historical results remain in [validation](validation.md) and unchanged evidence files. Current completion refers to [the result matrix](automatic-write-validation.md) and [sanitized October evidence](evidence/automatic-backup-source-proof-2026-10-13.md), not native or hosted release readiness.
+
+## Local-first implementation
+
+- [x] Give each logical recovery operation an originating account/session, operation ID and monotonic generation captured after all related local writes commit.
+- [x] Reorder wallet/signer/vault creation, edits and deletions so local persistence precedes cloud effects; cloud failure preserves local results and the reducer pending-state contract. Verify actual persisted restart behavior in the native matrix below.
+- [x] Prove all seven operation payloads/deletion targets against fresh committed Realm data at queue head with real decrypt/identity validation.
+- [x] Reject stale generation, failed/partial commit, wrong owner/key/consent and queued A→B→A without network or later substitution of a newer verified base.
+- [x] Cover account-bound node/version writes, exact-KeyUID migration, USDT direct deletion, delayed import callbacks and shared registration propagation in the recorded source/producer cases.
+- [x] Handle explicit whole-backup opt-out separately; retain the user's choice until acknowledged empty readback and current consent/session completion, and reconcile lost responses.
+
+## Server sequencing and verification
+
+- [x] Validate v2 snapshot/capabilities and preserve remote-only/conflicting recovery content before automatic send.
+- [x] Enforce atomic expectedRevision with positive precondition acknowledgement and valid newRevision; prohibit legacy fallback.
+- [x] Use a serialized acknowledged revision chain, revalidating local proof for each member.
+- [x] Stop on 409/404/protocol/network/timeout/lost response; do not replay prepared ciphertext or claim intermediate success. The matrix states which multi-member fault schedules actually ran.
+- [x] Complete and decrypt server readback, then compare fresh local data at the same committed generation and account/session.
+- [x] Make the final Redux verified transition reject a local mutation injected immediately before completion.
+- [ ] Verify persisted pending state across actual native app interruption/restart; SDK Realm close/reopen and reducer tests do not substitute for this.
+
+## Mandatory R4 disposable proof
+
+- [x] Exercise each of seven production transport operations with real encryption and disposable Realm + transactional Relay fixtures, with separate actual saga/hook producer coverage.
+- [x] Record valid committed write once, stale data/commit rejection, queued and after-send A→B→A, remote-only/conflicting snapshot, 409/old-route 404/malformed acknowledgement, timeout/lost response and complete readback outcomes per operation.
+- [x] Prove vault creation+archive, multi-vault registration and label add/delete fanouts, including successful first member then failure and no later prepared send. Direct native mutation after first actual CAS/held ACK also stops the remaining effects.
+- [x] Prove disabled/unconsented accounts send zero writes and successful local create/edit/delete survives cloud failure in the observed producer cases.
+- [x] Prove clean Recovery Key restoration from the disposable encrypted backup, validating all intended records and key/policy/registration identity.
+- [x] Run revisioned Relay HTTP/transaction source tests against a disposable replica set, including old-writer fences and competing writers. Deployed source/topology and fleet rollout remain open.
+- [x] Link exact app/backend SHA, commands, fixture provenance, pass/fail/blocked counts and sanitized evidence in the current matrix; prior logs are not replacements.
+
+## Mandatory critical native backup acceptance
+
+- [ ] IOS: exact-source native build/launch; opted-in automatic create/edit/delete, relaunch persistence, check/readback and clean disposable Recovery Key restore.
+- [ ] ANDROID: the same exact-source create/edit/delete, relaunch, readback and clean restore checks.
+- [ ] Both platforms: legacy snapshot upgrade, failed/stale/absent check truthfulness, account/consent switching and A→B→A, interrupted/uncertain write/retry, no false verified/empty restore or automatic replacement.
+- [ ] Both platforms: local mutation during pending upload/final readback remains pending; interrupted recovery never claims complete; record platform-specific outcomes rather than assuming parity.
+- [ ] Record physical-device-only follow-up separately when unavailable; do not use it to defer required fixtures or critical simulator/emulator checks.
+
+## Remaining delivery and NFR gates
+
+- [ ] Independent final-source developer review and current-head CI, with inherited lint/type failures disclosed.
+- [ ] Native small-width/enlarged-text, large/single-record frame time, memory, throughput and slow/background cases; distinguish mandatory critical safety failures from explicitly accepted physical-only follow-up.
+- [ ] Verify deployed request limits and transaction topology, compatible running Relay artifact and old-writer drain/rollout under existing operator authorization.
+- [ ] Refresh store histories/counters and source/artifact manifest; obtain intended merge/signing/submission/deployment/release approval separately.
+
+Checked items describe observed source/disposable proof only. Every unchecked native, infrastructure, review/CI or release task remains open. Reproducibility, Bitkey/Recoverable Wallet and unrelated R4 code stay independent.
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..b45454ca06
--- /dev/null
+++ b/openspec/changes/fix-recovery-backup-freshness/validation.md
@@ -0,0 +1,50 @@
+> Current R4 contract: [protected backup integration](protected-backup-integration.md) supersedes the historical v2 protocol and whole-copy Delete language below. Prior checked source/fixture boxes are SHA-scoped historical evidence, not protected-v3, native, hosted or release acceptance. Delete now applies only to the new protected copy; older encrypted copies remain read-only. All-copy erasure is outside approved R4 scope, unimplemented and unscheduled.
+
+# R4 recovery validation — current gates and historical evidence
+
+## Current automatic-write status — 13 October 2026
+
+Audit starting app source: `b160656218dc6065ad12af9db220c974255bfc23`. The automatic fix and disposable proof are mandatory R4 requirements; critical native iOS/Android backup acceptance also precedes release. Physical-device-only follow-up does not waive the fixture/native safety checks.
+
+Current exact-source results live in [automatic-write-validation.md](automatic-write-validation.md), with a sanitized [October source-proof record](evidence/automatic-backup-source-proof-2026-10-13.md). Source local-first generation/session/payload proof and disposable host Realm/HTTP outcomes are now recorded; required IOS/ANDROID native backup acceptance and hosted deployment remain open. The source flag permits development loopback testing only; hosted rollout remains fenced. See [tasks](tasks.md) for evidence-backed completion and remaining gates.
+
+The baseline automatic transport fails closed before network until end-to-end local commit/generation, originating-session/payload proof, revisioned fanout and final complete readback are implemented and proved. Earlier success of manual repair or a pre-persistence automatic writer does not establish readiness for this contract. A lost write acknowledgement leaves its originating operation pending; a content-only match is not an acknowledged write or fanout completion.
+
+## Historical recovery candidate — 29 September 2026
+
+The material below preserves prior recorded results and their original source/artifact boundaries. It has not been rerun in this reconciliation. References to local uncommitted source, earlier versions/counters, native completion or remaining gates describe that September candidate, not the final R4 source. In particular, older tests requiring upload before local commit are superseded by the local-first model; their logs remain unchanged as provenance.
+
+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/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..2862d15f90
--- /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
+
+- 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.
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/changes/reconcile-r5-release-baseline/.openspec.yaml b/openspec/changes/reconcile-r5-release-baseline/.openspec.yaml
new file mode 100644
index 0000000000..7cc41bb519
--- /dev/null
+++ b/openspec/changes/reconcile-r5-release-baseline/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-10-22
diff --git a/openspec/changes/reconcile-r5-release-baseline/design.md b/openspec/changes/reconcile-r5-release-baseline/design.md
new file mode 100644
index 0000000000..67a52b6894
--- /dev/null
+++ b/openspec/changes/reconcile-r5-release-baseline/design.md
@@ -0,0 +1,52 @@
+## Context
+
+R4's middleware stamps app/session authority at dispatch and its deletion worker
+checks retained Vault references inside the local transaction. R5's earlier UI
+confirmation predates that dispatch boundary; its origin must survive an account
+switch, including A → B → A. The owner-confirmed release baseline is 1d8a86a.
+
+## Goals / Non-Goals
+
+Preserve R4 and R5 history and all released backend/native/dependency inputs;
+reject stale deletion confirmations without weakening reference, archived-key or
+passcode guards. No schema/MMKV/store-shape change or Persist migration/version
+bump; no PSBT, amount, UTXO or hardware interaction.
+
+## Decisions
+
+The DeleteKeys screen will capture the rendered storage appId and backup account
+session with its one-use intent. Selection and confirmation compare that origin
+against current Redux storage, current Realm KeeperApp and session before reading
+references or dispatching. Delete/archive actions carry the original app/session
+so R4 middleware cannot silently bind them to a different account. Existing
+wallet sagas and transactional guards remain unchanged.
+
+Affected R5 files: src/screens/SigningDevices/DeleteKeys.tsx,
+tests/screens/DeleteKeys.test.tsx, src/screens/Home/components/Keys/ManageKeys.tsx
+(typed navigation dispatch adaptation), docs/r5/R4-RECONCILIATION.md,
+docs/r5/WORKSTREAM.md, and this OpenSpec change. The baseline integration also
+combines the existing R5 CI workflow and explicitly installs its Realm N-API
+prerequisite before recovery tests; package.json/yarn.lock/Podfile.lock and native
+inputs remain exact R4 bytes. No new UI component: reuse KeyCard, KeeperModal and
+PasscodeVerify and existing theme tokens per DESIGN.md. Its implementation
+checklist is satisfied without changing layout, text scale or critical controls.
+
+Redux storage.appId is read; existing DELETE/ARCHIVE_SIGINING_DEVICE workers and
+backup origin middleware consume the unchanged action fields. UI screens and
+flows/login.yaml retain the existing native checkpoints; document the finite
+account-switch/deletion Maestro scenarios instead of scripting destructive actions
+against arbitrary users. Native execution remains an explicit follow-up.
+
+## Risks / Trade-offs
+
+Separate model tests do not prove real Realm/auth provenance or native account
+switches. Run original R5 tests against the combined tree, add stale-origin
+regressions, rerun existing R4 deletion/session checks and disclose every unrun
+native/genuine fixture. The inherited public-v2 Relay fixture mismatch is baseline
+debt; no backend/protocol/pin workaround belongs in this reconciliation.
+
+Existing NewKeeperApp effects/timers also capture the production transport session.
+Their active predicates combine effect lifetime and session equality. Tests use
+the real counter with explicit account-transition fixtures; setup workers and
+account/credential schemas remain unchanged. Affected files additionally include
+src/screens/NewKeeperAppScreen/NewKeeperAppScreen.tsx and its existing screen test.
diff --git a/openspec/changes/reconcile-r5-release-baseline/proposal.md b/openspec/changes/reconcile-r5-release-baseline/proposal.md
new file mode 100644
index 0000000000..77c8117169
--- /dev/null
+++ b/openspec/changes/reconcile-r5-release-baseline/proposal.md
@@ -0,0 +1,42 @@
+## Why
+
+The owner confirms R4 / 2.6.4 is live. R5 must use its recorded artifact source
+1d8a86a as the baseline and retain its transactional deletion protections while
+completing the already-approved bounded key-deletion/startup work.
+
+## What Changes
+
+- Integrate the released R4 source into the isolated R5 branch, preserving R5
+ history, R4 refs and the exact released dependency/native/configuration inputs.
+- Bind a key-deletion confirmation to its originating account/session so a late
+ passcode callback cannot be rebound by dispatch-time middleware.
+- Rerun affected automated checks and record finite native acceptance still needed.
+
+## Capabilities
+
+### New Capabilities
+
+- `r5-account-bound-key-deletion`: confirmation ownership across account/session changes.
+
+### Modified Capabilities
+
+None; released R4 backend requirements are preserved.
+
+## Impact
+
+Both mainnet and testnet. Signer, Vault and account/session ownership are affected;
+no amount/UTXO, hardware transport, subscription tier, schema or key-material
+change. Reuse existing DeleteKeys/KeyCard/KeeperModal/passcode components. Existing
+flows/login.yaml remains the startup specification; account-switch/deletion native
+checkpoints will be documented without deleting real wallets or contacting providers.
+The R5 delta remains within the two-feature, approximately 13k–18k token estimate.
+
+## Non-goals
+
+No R4 branch modification or PR merge, release, backend/protocol change, dependency
+upgrade, Receive QR, shared-component rewrite, scaling, Ask Keeper delivery,
+private-data transfer or optional Linux setup.
+
+The same existing startup feature must retain its account session across pending
+notification tokens and delayed navigation; this is callback ownership, not a
+third feature or a change to backend account creation.
diff --git a/openspec/changes/reconcile-r5-release-baseline/specs/r5-account-bound-key-deletion/spec.md b/openspec/changes/reconcile-r5-release-baseline/specs/r5-account-bound-key-deletion/spec.md
new file mode 100644
index 0000000000..c5de22bebc
--- /dev/null
+++ b/openspec/changes/reconcile-r5-release-baseline/specs/r5-account-bound-key-deletion/spec.md
@@ -0,0 +1,49 @@
+## ADDED Requirements
+
+### Requirement: Key deletion confirmation retains account ownership
+
+DeleteKeys SHALL authorize deletion or archived retention of a Signer only in the
+same KeeperApp account/session in which its current one-use confirmation began.
+All active Vault references remain blocking. No satoshi amount or UTXO changes.
+
+#### Scenario: Current account deletes an unused key
+- **GIVEN** an unused visible Signer selected in account A and its current session
+- **WHEN** its passcode confirmation succeeds and A/Realm/session still match
+- **THEN** one delete action carries that original app/session; the Delete CTA is
+ discoverable without Hide and R4's transaction performs its own reference check
+
+#### Scenario: Old confirmation survives an account round trip
+- **GIVEN** a Signer confirmation from A, followed by A → B → A without a rerender
+- **WHEN** the earlier passcode callback completes
+- **THEN** no delete/archive action is dispatched and the old confirmation closes
+
+#### Scenario: Realm and Redux disagree
+- **GIVEN** Redux names A while the current Realm KeeperApp belongs to B or is unreadable
+- **WHEN** a key selection or confirmation is attempted
+- **THEN** no delete/archive action is dispatched; native UI SHALL not report success
+
+#### Scenario: A retained callback tries a newer account's key card
+- **GIVEN** a key-card callback captured in A before account/session changed
+- **WHEN** it is invoked after the transition
+- **THEN** it cannot open a new actionable deletion confirmation in the new account
+
+#### Scenario: Referenced and archived keys remain protected offline
+- **GIVEN** a Signer with a live active or archived Vault reference and unavailable network
+- **WHEN** its current account confirms a deletion attempt
+- **THEN** active references block it and archived references retain the Signer;
+ cancellation and repeated callbacks cannot produce a second destructive action
+
+### Requirement: First-use callbacks retain their account session
+
+Existing setup and notification callbacks SHALL not dispatch or navigate after
+their original account session changes, even if the screen remains mounted.
+
+#### Scenario: Token completes after an account round trip
+- **GIVEN** setup or its post-success token update pending in session A
+- **WHEN** the account changes A → B → A and the token resolves or rejects
+- **THEN** no old setup/token action is dispatched into the new session
+
+#### Scenario: Delayed navigation belongs to an old session
+- **GIVEN** a recreated-app or Next navigation timer scheduled in session A
+- **WHEN** the account session changes before the delay ends
+- **THEN** it does not navigate over the current account's screen
diff --git a/openspec/changes/reconcile-r5-release-baseline/tasks.md b/openspec/changes/reconcile-r5-release-baseline/tasks.md
new file mode 100644
index 0000000000..a08bdf3051
--- /dev/null
+++ b/openspec/changes/reconcile-r5-release-baseline/tasks.md
@@ -0,0 +1,27 @@
+## 1. UI Components
+- [x] 1.1 Preserve existing components, confirmation/cancel/privacy and helper copy against released source.
+
+## 2. Business Logic / Hooks
+- [x] 2.1 Capture and validate deletion origin before selection/confirmation, including A → B → A.
+
+## 3. Store (Slice + Saga)
+- [x] 3.1 Carry original app/session on delete/archive actions; retain R4 workers/middleware unchanged.
+
+## 4. Storage
+- [x] 4.1 Verify no schema/MMKV/store-shape change; no Redux Persist migration bump needed.
+
+## 5. Tests
+- [x] 5.1 Add stale account/session/Realm confirmation and retained-card regressions, with failing controls.
+- [x] 5.2 Run frozen setup/patches, affected Jest/recovery/security/quality and baseline comparison.
+- [x] 5.3 Record exact baseline, R5-only diff, results and unresolved native/genuine gaps.
+
+## 6. E2E Flows (Maestro)
+- [x] 6.1 Preserve login flow, document finite deletion/account-switch/native measurements.
+- [ ] 6.2 Execute relevant IOS/ANDROID/HARDWARE scenarios when available; retain NOT RUN otherwise.
+
+Native task6.2 remains NOT RUN; no archive or acceptance claim. Ruby-dependent
+local checks remain unavailable and are explicitly retained in the validation report.
+
+## 7. Existing startup callback ownership
+- [x] 7.1 Reproduce pending-token/delayed-navigation account-session crossings (6 assertion failures /14 passes).
+- [x] 7.2 Guard effects/timers by their captured session and rerun focused/full Jest (20 startup, 106 focused, 538 full PASS).
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 d192ee46fa..a5bb6e05a5 100644
--- a/package.json
+++ b/package.json
@@ -1,12 +1,17 @@
{
"name": "hexa_keeper",
- "version": "2.5.13",
+ "version": "2.6.4",
"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 scripts/verify-channel-config.test.cjs && python3 -B -m unittest discover -s scripts -p 'test_release_artifact.py' && ruby scripts/test_fastlane_build_only.rb",
+ "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",
@@ -14,7 +19,7 @@
"androidDevelopmentDebug": "ENVFILE=.env react-native run-android --mode=developmentDebug --appIdSuffix=development",
"androidDevelopmentRelease": "ENVFILE=.env react-native run-android --mode=developmentRelease --appIdSuffix=development",
"androidProductionDebug": "ENVFILE=.env react-native run-android --mode=productionDebug",
- "androidProductionRelease": "ENVFILE=.env react-native run-android --mode=productionRelease",
+ "androidProductionRelease": "node scripts/verify-channel-config.cjs .env.production && ENVFILE=.env.production react-native run-android --mode=productionRelease",
"uninstall ios": "xcrun simctl uninstall booted io.hexawallet.keeper",
"uninstall ios:dev": "xcrun simctl uninstall booted io.hexawallet.hexakeeper.dev",
"uninstall android": "adb uninstall io.hexawallet.bitcoinkeeper",
@@ -23,7 +28,10 @@
"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",
+ "test:automatic-backup-genuine": "node scripts/run-automatic-backup-genuine.cjs",
+ "test:protected-backup-genuine": "node scripts/run-protected-backup-genuine.cjs"
},
"dependencies": {
"@bitcoinerlab/miniscript": "1.4.0",
@@ -98,7 +106,7 @@
"react-native-mmkv": "4.3.0",
"react-native-modal": "^13.0.1",
"react-native-nfc-manager": "3.16.0",
- "react-native-nitro-modules": "0.35.4",
+ "react-native-nitro-modules": "0.36.5",
"react-native-pdf": "7.0.4",
"react-native-qrcode-svg": "6.3.2",
"react-native-randombytes": "3.6.1",
@@ -128,7 +136,12 @@
"stream": "0.0.2",
"stream-browserify": "1.0.0",
"tronweb": "6.0.3",
- "url": "0.10.1"
+ "url": "0.10.1",
+ "@exodus/bytes": "1.16.0",
+ "@scure/bip32": "2.4.0",
+ "@scure/bip39": "2.4.0",
+ "@noble/curves": "2.4.0",
+ "@noble/hashes": "2.4.0"
},
"devDependencies": {
"@babel/core": "7.26.0",
diff --git a/patches/react-native+0.83.9.patch b/patches/react-native+0.83.9.patch
index 6eeb009e8a..a0957763e8 100644
--- a/patches/react-native+0.83.9.patch
+++ b/patches/react-native+0.83.9.patch
@@ -117,3 +117,12 @@ index 2ee2c50..6fbfe6f 100644
[subviews insertObject:subview atIndex:atIndex];
}
+diff --git a/node_modules/react-native/sdks/hermes-engine/hermes-engine.podspec b/node_modules/react-native/sdks/hermes-engine/hermes-engine.podspec
+index fb99142..3f5cbb6 100644
+--- a/node_modules/react-native/sdks/hermes-engine/hermes-engine.podspec
++++ b/node_modules/react-native/sdks/hermes-engine/hermes-engine.podspec
+@@ -78,3 +78,3 @@ Pod::Spec.new do |spec|
+ spec.user_target_xcconfig = {
+- 'HERMES_CLI_PATH' => "#{hermes_compiler_path}/hermesc/osx-bin/hermesc"
++ 'HERMES_CLI_PATH' => '${PODS_ROOT}/../../node_modules/hermes-compiler/hermesc/osx-bin/hermesc'
+ }
diff --git a/release/README.md b/release/README.md
new file mode 100644
index 0000000000..7500d40554
--- /dev/null
+++ b/release/README.md
@@ -0,0 +1,64 @@
+# Release version verification
+
+**Current source intent:** this R4 candidate stages 2.6.4 on the 2.6.3 pairing-channel hotfix baseline. The candidate is still under review. Keep private advisory details, credentials and fixtures out of public release material.
+
+`version.json` provisionally selects 2.6.4, Android 627 and iOS 620. Its recorded authenticated store baselines on 6 October 2026 are Android 625 and iOS 618, both at 2.6.2. Refresh these baselines and confirm the counters before signing or upload. Development builds and local relay validation are separate from reviewed production builds, deployment and store submission.
+
+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. Run all feasible automated, simulator/emulator and disposable checks before public submission; record the owner's post-release manual checks separately.
+
+Both Fastlane `build_only` and `live` lanes run the same preflight, production build and artifact verification logic and consume `.env.production` without downloading over `.env`. They do not increment production build numbers. `build_only` never uploads and never notifies Slack, including on failures and when `KEEPER_NOTIFY_SLACK=1` is set. Android `live` notifications still 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.
+
+## Build-only production preparation
+
+The following commands are for a future **owner-approved production build**. `build_only` still obtains signing assets and creates signed production artifacts using the existing identities. Approval must name the intended commit, platform and production environment before these commands run. Simulator/emulator validation in the Codex Local handoff is separate and does not authorize signing, building production artifacts, upload or distribution.
+
+Refresh authenticated store evidence, review `.env.production` and provide the existing signing credentials first. Start each platform in its own clean, isolated checkout at the approved commit so one platform's signing/provisioning changes cannot affect the other platform's clean-source preflight. In each checkout, set `KEEPER_RELEASE_COMMIT` to that full verified commit and run `npm run release:preflight` before its command:
+
+```sh
+# In the approved iOS checkout (requires the approved Mac/signing setup):
+export KEEPER_RELEASE_COMMIT="$(git rev-parse HEAD)"
+npm run release:preflight
+(cd ios && ENVFILE=.env.production bundle exec fastlane build_only --env production)
+```
+
+```sh
+# In the approved Android checkout (requires the established release keystore):
+export KEEPER_RELEASE_COMMIT="$(git rev-parse HEAD)"
+npm run release:preflight
+(cd android && ENVFILE=.env.production bundle exec fastlane build_only --env production)
+```
+
+Record the generated IPA or AAB/APK paths, verifier output and checksums. The lanes require fresh artifact paths from their current build actions; a prior lane-context path cannot satisfy a missing output. Review signing/provisioning changes without committing credentials. Separate IPA/AAB signing verification and all distribution channels still need their own checks and approval. Do not use `live` for build-only preparation because it uploads.
+
+`ruby scripts/test_fastlane_build_only.rb` executes the real lane bodies and success/error hooks with fake actions in disposable fixtures. It checks preflight/config/artifact failures, rejection of old artifact paths, and absence of upload/Slack calls for `build_only`, while retaining `live` upload behavior. It needs Ruby 3.3 with the bundled Minitest gem; it never invokes Fastlane, native build tools, signing, stores or Slack. Run it through `npm run test:release` with the source and packaged-artifact regression suites.
+
+## Packaged artifact checks
+
+Run `python3 scripts/verify-release-artifact.py /absolute/path/to/build.ipa` (or `.apk` / `.aab`). Both production lanes run this; `live` does so before uploading. Android builds both artifacts and verifies them before its first upload. Both platforms clear prior artifact paths before their build actions and require the current build's output; the iOS lane 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 `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.
+
+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
+
+- Post-release 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.
+- 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/cloud/Fastfile b/release/cloud/Fastfile
new file mode 100644
index 0000000000..a538c5f65e
--- /dev/null
+++ b/release/cloud/Fastfile
@@ -0,0 +1,35 @@
+# Loaded from a disposable directory with no legacy Appfile or callbacks.
+# This adapter uploads only already verified bytes; it never builds/signs.
+default_platform(:ios)
+
+def verified_artifact!(operation, suffix)
+ UI.user_error!("Wrong approved operation") unless ENV['KEEPER_RELEASE_OPERATION'] == operation
+ path = ENV['KEEPER_VERIFIED_ARTIFACT'].to_s
+ UI.user_error!("Missing verified artifact") unless File.file?(path) && File.extname(path) == suffix
+ path
+end
+
+platform :ios do
+ lane :approved_upload do
+ artifact = verified_artifact!('testflight-upload', '.ipa')
+ %w[KEEPER_ASC_KEY_ID KEEPER_ASC_ISSUER_ID KEEPER_ASC_KEY_BASE64].each do |name|
+ UI.user_error!("Missing approved App Store Connect credential") if ENV[name].to_s.empty?
+ end
+ key = app_store_connect_api_key(key_id: ENV['KEEPER_ASC_KEY_ID'], issuer_id: ENV['KEEPER_ASC_ISSUER_ID'],
+ key_content: ENV['KEEPER_ASC_KEY_BASE64'], is_key_content_base64: true, in_house: false)
+ upload_to_testflight(ipa: artifact, app_identifier: 'io.hexawallet.keeper', api_key: key,
+ skip_submission: true, distribute_external: false, notify_external_testers: false,
+ skip_waiting_for_build_processing: true)
+ end
+end
+
+platform :android do
+ lane :approved_upload do
+ artifact = verified_artifact!('play-internal-upload', '.aab')
+ UI.user_error!("Missing approved Play credential") if ENV['KEEPER_PLAY_SERVICE_ACCOUNT'].to_s.empty?
+ upload_to_play_store(aab: artifact, package_name: 'io.hexawallet.bitcoinkeeper',
+ json_key_data: ENV['KEEPER_PLAY_SERVICE_ACCOUNT'], track: 'internal', release_status: 'draft',
+ skip_upload_metadata: true, skip_upload_images: true, skip_upload_screenshots: true,
+ changes_not_sent_for_review: true)
+ end
+end
diff --git a/release/cloud/README.md b/release/cloud/README.md
new file mode 100644
index 0000000000..dbd7bb2a91
--- /dev/null
+++ b/release/cloud/README.md
@@ -0,0 +1,110 @@
+# Protected release orchestration — Phase B3 candidate
+
+These are **implemented future worker candidates, NOT EXECUTED / NOT VERIFIED**. They combine separately reviewable preparation #7072, fail-closed origin guard #7074, worker core #7076 and frozen Ruby inputs #7078. Those producer checkpoints and the primary R5 native candidate are unchanged. No workflow was dispatched, credentials provisioned, signed app built, store contacted, binary uploaded, deployment made or paid setup initiated to prepare this package. Host contracts use synthetic data and fake actions only. Do not treat those contracts as successful remote signing/distribution.
+
+The [manual workflow](../../.github/workflows/keeper-protected-release-workers.yml) has four explicit operations. Each invocation performs exactly one:
+
+| Operation | Adapter behavior | Deliberately separate next decision |
+| --- | --- | --- |
+| `ios-signed-build` | Build/export one manually provisioned production IPA with an existing pinned certificate/profile; verify native metadata, app ID/version/build, signature, team/profile/entitlements and certificate. Retain only IPA and signed-build receipt. | TestFlight upload needs its own exact-artifact owner receipt and environment approval. |
+| `android-signed-build` | Build one production AAB using the existing approved upload keystore, with environment-only signing inputs; verify metadata/version/channel and strict JAR signature against the pinned certificate. Retain only AAB and signed-build receipt. | Play internal upload needs its own exact-artifact owner receipt and environment approval. No APK/sideload/publication route is added. |
+| `testflight-upload` | Download the exact approved successful canonical signing-run artifact, reject substituted bytes/receipt/provenance, recheck IPA identity/signature, then upload without external distribution or submission. | Physical testing, store-selected build/processing evidence and any further distribution/submission/publication are separate. |
+| `play-internal-upload` | Verify the exact successful canonical signing-run artifact and AAB signature, then upload to **internal draft**, skipping metadata/images/screenshots and automatic review submission. | This is not an approved production rollout or proof of tester delivery. Store-selected build/review and later rollout require separate evidence/approval. |
+
+The standalone [Fastfile](Fastfile) is loaded in a disposable directory without legacy Appfiles, callbacks, Slack or dev/live lanes. It only uploads already verified artifacts. Existing source guards (`release-version.cjs`, `verify-channel-config.cjs`, `verify-release-artifact.py`) are reused. Existing Android signing configuration is consumed only after its release block passes the bounded literal-credential check. Existing iOS automatic certificate/profile acquisition is replaced with pre-provisioned manual signing; no material is created, rotated or fetched from a personal keychain.
+
+TestFlight stops after the binary upload command: `skip_waiting_for_build_processing:true` and no changelog return before pinned Fastlane2.225.0 enters its processing/distribution path. `skip_submission:true` alone is insufficient because that path updates beta metadata first. Processing and store-selected build verification remain separate, unperformed steps. A regression executes the pinned library with fake login/package/transporter boundaries and proves the previous waiting flag reaches that path.
+
+## Trust, approval and fresh validation
+
+The installed driver must run from the **current protected sprint SHA**. A signed build additionally requires candidate SHA = driver SHA, so PR or uninstalled release-branch code cannot execute with production signing material. A protected `release/` ref must point to that exact source. An upload may use an older reviewed protected source, but candidate files are read only as data; only the current installed driver/uploader code executes.
+
+**Authorization is currently disabled.** The shared gate cannot mint its module-private trusted-origin marker from API JSON, status names, actor names or a claimed successful workflow. Every live authorization therefore fails closed with `TRUSTED_CI_ORIGIN_NOT_VERIFIED`. The separately prepared canonical native producer and trusted-origin consumer must be reviewed and installed before that boundary can change. No worker operation has run.
+
+Before the environment job, the intended shared gate requires authentic exact successful Tests/CodeQL/native evidence, fresh store/build baselines, consistent native versions, current owner write permission and an exact expiring approval. The current legacy all-checks predicate also rejects skipped/in-progress/wrong-SHA checks; selected-route skips are not native credit. The independent producer/consumer package must reconcile genuine selected-route evidence with that predicate without transferring PR-head passes. Absent dedicated environments, unknown administrative bypass policy, missing independent reviewers or unverified protected-branch restriction all block. Current check names must be reconciled with the installed Phase A route; a name mismatch fails closed.
+
+The worker's own in-progress authorization/operation checks are excluded only after proving their exact current Actions run, current attempt, trusted workflow path/repository/driver SHA, job check IDs/names and check-suite ID. Complete bounded pagination is required before filtering. Unrelated pending/failed checks, other attempts and required independent checks remain blocking; the preparation workflow is not accepted as native or security evidence.
+
+After independent environment approval, the worker repeats those read-only checks **before any operation credentials are referenced**. Dependency setup runs without production credentials and without caches. It then repeats the checks immediately before the step-scoped signing/upload secrets, and again at entry to execution. Uploads repeat live authorization after artifact download. The request/receipt also binds independently approved certificate and production-config SHA256 values, matched against protected environment variables. A received preparation plan cannot authorize execution. Signing and upload are not chained.
+
+Approvals must remain valid for at least two hours at adapter entry; jobs time out after100minutes. Profiles/certificates also need at least two hours of validity. An expired, revoked, moved or newly failing candidate is rejected by fresh checks. No approval is generated or posted on behalf of the owner.
+
+## Exact manual request and owner receipt
+
+The single `request_json` dispatch input contains only these ten string fields (no credentials or configuration values):
+
+```json
+{
+ "source_sha": "<40 lowercase hex>",
+ "release_ref": "release/",
+ "operation": "ios-signed-build",
+ "version": "",
+ "build": "",
+ "artifact_sha256": "pending",
+ "approval_comment_id": "",
+ "certificate_sha256": "<64 lowercase hex independently verified fingerprint>",
+ "config_sha256": "<64 lowercase hex approved client-config digest>",
+ "artifact_id": "none"
+}
+```
+
+For an upload, select its upload operation, supply the actual app-file SHA256 and the successful signing run's numeric GitHub artifact ID. The owner receipt has the exact #7072 approval fields, plus these lines between `Workflow commit` and `Expires at`:
+
+```text
+Signing identity SHA256:
+Production config SHA256:
+Artifact storage: GitHub Actions public-repository readers (14 days)
+```
+
+**Artifact retention is explicitly part of this future approval.** Signed binaries stored as Actions artifacts in this public repository can be accessible to authenticated readers of the public repository; do not treat them as a private beta channel. If that audience is not approved, do not use this worker: implement/review a private artifact transport first. Upload receipts contain no binary; signed-build artifacts contain only the approved IPA/AAB and bounded receipt. Native logs, `.env.production`, profiles, private keys, keychains, service-account JSON and API key content are never retained as artifacts.
+
+The receipt binds operation, source/driver SHA, marketing version/platform build, artifact/certificate/config digests, run/attempt, approval comment/expiry and source artifact lineage. `storeUploaded` means only that the upload adapter command completed. `storeProcessingVerified` remains false: it does not establish a store-selected build, external distribution, review submission, public release or readiness. Verify those separately before further action.
+
+## One-time protected setup — not performed
+
+Use separately approved administrator/custodian setup; never put credential values in a PR, dispatch request, task sheet or command log. #7072's HTTP403 secret-name reads do not prove credentials absent. No personal Mac is required; use an existing approved credential vault/custodian or signing service, not an automatic export/copy of the owner's keychain.
+
+| Scope | Required names/conditions |
+| --- | --- |
+| Both protected environments | Existing `keeper-release-ios` / `keeper-release-android`; independent required reviewers, prevented self approval, administrative bypass disabled, protected-branch restriction. Confirm actual rejection/enforcement before any secret-enabled trial. |
+| Both environments' variables | `KEEPER_RELEASE_CERT_SHA256`, `KEEPER_PRODUCTION_CONFIG_SHA256`: independently verified64-character lowercase digests, also bound to owner receipt. No certificate fingerprint is guessed from the artifact alone. |
+| Signed builds' shared secret | `KEEPER_PRODUCTION_CONFIG_BASE64`: exact owner-reviewed client-safe dotenv bytes. The adapter requires its approved digest, rejects unknown/duplicate keys and reuses production channel/service guards. Known client keys are allowlisted; secret signing/upload/server credentials are not permitted in this embedded configuration. |
+| iOS signing secrets | `KEEPER_IOS_P12_BASE64`, `KEEPER_IOS_P12_PASSWORD`, `KEEPER_IOS_PROFILE_BASE64`: existing approved distribution identity/profile, not a new certificate. Protected variables `KEEPER_IOS_TEAM_ID` and `KEEPER_IOS_PROFILE_UUID` must match actual production app/team/profile and pinned certificate. |
+| Android signing secrets | `KEEPER_ANDROID_KEYSTORE_BASE64`, `STORE_PASSWORD`, `KEY_PASSWORD`, `KEY_ALIAS`: existing authorized upload identity. Verify continuity independently; the Play App Signing certificate and upload certificate are distinct. AAB-only output avoids claiming that an upload-key APK is suitable for existing sideload users. |
+| TestFlight upload secrets | `KEEPER_ASC_KEY_ID`, `KEEPER_ASC_ISSUER_ID`, `KEEPER_ASC_KEY_BASE64`: least-privileged approved App Store Connect API identity with intended app/channel access. These are not loaded during signing. |
+| Play internal upload secret | `KEEPER_PLAY_SERVICE_ACCOUNT`: least-privileged approved JSON API identity for the existing app/internal draft upload. It is not loaded during signing. |
+
+Dependencies must already be reviewed/installed on canonical source: Phase A's `.github/native/nodeify.cjs`, frozen Yarn/Pod/Gem inputs and compatible native source. Missing helper/lock inputs fail rather than invent a dependency workaround. No production-secrets caches are used. The workflow uses hosted macOS15/Xcode16.4/Ruby3.3.8/Node22.23.3 and Linux/Java17/SDK36/build-tools35/NDK27.1.12297006; these are reviewed development-route pins, **not new proof of production signing compatibility**. At least16GiB free disk is required; the worker serializes its own operations and must be scheduled in an exclusive native-build window alongside other release work.
+
+**Exact-canonical native proof remains a separate readiness dependency.** A normal merge/squash creates a new canonical SHA, while current hosted native/keeper-local evidence is scoped to a PR head. The signing worker refuses to inherit those passes. Install/review an exact-canonical native attestation entry point and produce its genuine required checks on the protected canonical SHA before this worker can operate. Ordinary merge alone does not make signing ready; this package does not weaken source trust, manufacture status or execute post-merge release operations.
+
+Nodeify's three module-mapping fields (`browser`, `react-native`, `browserify`) are a recorded build overlay, not a source promotion. A trusted setup step records canonical source SHA and before/after package hashes; all other manifest fields and tracked source, including staged changes, must match HEAD. The same exact overlay is rechecked before native execution and before receipts. The canonical clean driver still runs the ordinary release-version preflight. Separate Ruby package #7078 pins CocoaPods1.16.2/Xcodeproj1.27.0 and completed an actual frozen118-gem install/load/project parse under portable Ruby3.3.8. This orchestration inherits those reviewed inputs, while its inherited base Podfile.lock still records CocoaPods1.15.2. Pair the adopted native foundation’s reviewed CocoaPods1.16.2 Podfile.lock during future integration; the worker rejects a mismatch before credentials. No Podfile lock is silently regenerated here, and actual combined hosted frozen Pod/native acceptance remains required.
+
+Bundletool1.18.1 is pinned to observed SHA256 `675786493983787ffa11550bdb7c0715679a44e1643f3ff980a529e9c822595c`,32,505,571bytes downloaded through official GitHub release HTTPS during preparation. Upstream release metadata supplied no digest. This is an observed source pin, not independently publisher-authenticated proof; independent review of that tool/input remains required before approving actual execution.
+
+Private signing files use exclusive0600 files in a0700 temporary directory. iOS uses a transient unlocked keychain, explicit manual provisioning and signing identity; its previous profile/search-list state is restored and its keychain deleted in failure/success cleanup. The candidate dotenv is created exclusively and removed only when this worker created it. Raw build/provider output is captured privately and discarded; public failure evidence contains only fixed stage categories. No unrelated files/caches/worktrees are deleted.
+
+Keychain restoration/deletion each has a bounded30second check. An otherwise successful build fails before any success receipt when cleanup fails; if the build already failed, its primary stage is preserved and cleanup failure is additionally reported. Fake-action controls exercise both cleanup failures and the combined primary/cleanup failure. No real keychain was created or modified by these tests.
+
+## Validation and remaining acceptance
+
+Run only the fake-action contracts for review:
+
+```sh
+node --test scripts/protected-release-plan.test.cjs scripts/protected-release-worker.test.cjs
+python3 -B -m unittest discover -s scripts -p 'test_cloud_release_worker.py'
+ruby scripts/test_cloud_upload_adapters.rb
+bundle exec ruby scripts/test_cloud_upload_fastlane.rb
+```
+
+Actual protected-rule enforcement, certificate/profile compatibility, hosted signed build, signature/provenance, upload/provider receipt and artifact transport remain **NOT RUN / NOT VERIFIED**. Apply the latest owner instructions and [conditional review policy #7034](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7034): this signing/workflow package needs adequate Balanced review; record the actual route, exact-source coverage and findings. Claude is unavailable/uninstalled for this task and no fresh paid activation is authorized; do not invent a completed provider review or a blanket human-review requirement. Approved capacity/custody setup and a later explicitly authorized disposable/approved-channel trial must exercise failure cleanup and exact artifacts before capability is called verified. No physical-device or native feature acceptance is established by this package. No production rollout/submission/publication workflow is included. See the [current package handoff](../../docs/r5-protected-release-handoff.md) for cross-package dependencies and observed setup.
+
+The later isolated dependency reconciliation pairs #7078's Ruby inputs with
+#7082's reviewed Pod/Nitro inputs, without changing either producer. The old
+mismatch described above remains a historical failure on the producer heads.
+Run `python3 -B scripts/check_cloud_release_inputs.py --root .` for a read-only
+alignment report on any proposed assembled source; never update locks to make
+the check pass. Alignment does not install missing native helpers or transfer
+native acceptance from #7082. Follow the current package handoff and
+[exact administrator/custodian specification](../../docs/r5-cloud-administrator-setup.md)
+before any separately approved installation. Authorization remains disabled.
diff --git a/release/evidence/r4-android-16kb-suppliers-2026-10-15.json b/release/evidence/r4-android-16kb-suppliers-2026-10-15.json
new file mode 100644
index 0000000000..854f6aeedf
--- /dev/null
+++ b/release/evidence/r4-android-16kb-suppliers-2026-10-15.json
@@ -0,0 +1,1212 @@
+{
+ "schema": 1,
+ "inspection_date": "2026-10-15",
+ "source_baseline": "698078e1765d1e0728145f0ef6def05195192b30",
+ "page_size": 16384,
+ "scope": [
+ "Read-only inspection of supplier AAR bytes; no native build, simulator or runtime test.",
+ "13 AARs and 50 inspected 64-bit entries include debug/release variants, repeated shared libraries and both old/new JNA. This is NOT an inventory of 50 retained APK libraries.",
+ "The Mac-local developmentDebug APK SHA256 8d73e790f9b47766c92e927d7fe8425ad4967cfe44607cf35312cbb87e469af8 was unavailable in Cloud. Its reported 49/59 raw RELRO-end flags cannot be enumerated or classified here.",
+ "The JNA 5.14.0 x86_64 supplier entry fails static checks but the app explicitly excludes lib/x86_64/libjnidispatch.so. The arm64 entry remains a declared production input.",
+ "AAR ZIP offsets are not final APK ZIP proof. Source-built adapters, final APK packaging and Android strict-16KB runtime remain separate checks.",
+ "An unaligned raw RELRO end alone does not imply Android 17 strict-mode rejection when RELRO covers its complete matching LOAD."
+ ],
+ "references": {
+ "guide": "https://developer.android.com/guide/practices/page-sizes",
+ "bionic_revision": "06356e41c5ed7b12220b24c05ba4fdb873b126a7",
+ "bionic_check_program_header_alignment": "https://android.googlesource.com/platform/bionic/+/06356e41c5ed7b12220b24c05ba4fdb873b126a7/linker/linker_phdr.cpp#557",
+ "bionic_fix_min_align": "https://android.googlesource.com/platform/bionic/+/06356e41c5ed7b12220b24c05ba4fdb873b126a7/linker/linker_phdr_16kib_compat.cpp#445"
+ },
+ "checker": "scripts/check-android-16kb.py",
+ "checker_unit_tests": {
+ "command": "python3 -B -m unittest discover -s scripts -p 'test_check_android_16kb.py'",
+ "passed": 20,
+ "failed": 0
+ },
+ "summary": {
+ "aar_count": 13,
+ "inspected_64bit_entries": 50,
+ "passing_entries": 48,
+ "failing_entries": 2
+ },
+ "artifacts": [
+ {
+ "coordinate": "com.facebook.fbjni:fbjni:0.7.0",
+ "url": "https://repo.maven.apache.org/maven2/com/facebook/fbjni/fbjni/0.7.0/fbjni-0.7.0.aar",
+ "sha256": "7e319ae110ac5e5ef18904170aea5c3e753e915d196699d7fd39d36c8e1dfe36",
+ "static_status": "PASS",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libc++_shared.so",
+ "sha256": "3e852764502d06e0cf1080d532ae7c608b7649d946a3a9d7e84e3d4b7d683214",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 1282800,
+ "memsz": 40208,
+ "end": 1323008,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/arm64-v8a/libfbjni.so",
+ "sha256": "a9e35ba55d3f956920281f519385f8a72475ee24819799cb08375fdd4cce2b22",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 187536,
+ "memsz": 4976,
+ "end": 192512,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libc++_shared.so",
+ "sha256": "0a2c7afa35b183fdd5a3cb20e2080ad54cbea06c2a4f0bc8f122cb7d1e9e0b9f",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 1242192,
+ "memsz": 39856,
+ "end": 1282048,
+ "end_mod_16384": 4096,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libfbjni.so",
+ "sha256": "a51410366a0394e05bc04052cfb237c70dcf7d4d53a56e1d00a041436cb0b653",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 183504,
+ "memsz": 4912,
+ "end": 188416,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ }
+ ]
+ },
+ {
+ "coordinate": "com.facebook.hermes:hermes-android:0.14.1:debug",
+ "url": "https://repo.maven.apache.org/maven2/com/facebook/hermes/hermes-android/0.14.1/hermes-android-0.14.1-debug.aar",
+ "sha256": "f2cf4d13e7de78baec93b1c29aa2a0dbf4774af96c57e2c858890e809eed2869",
+ "static_status": "PASS",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libhermesvm.so",
+ "sha256": "02430039489a47f7aacb9e1c505d3af8d6c04d8c453a94d8bc39f5e8bae4c448",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 3668576,
+ "memsz": 58784,
+ "end": 3727360,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libhermesvm.so",
+ "sha256": "67f80125c7cf0f02b146b1d5f7cd23fc23c15877ec18a3c0c6468974b63e0883",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 4019584,
+ "memsz": 60032,
+ "end": 4079616,
+ "end_mod_16384": 0,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ }
+ ],
+ "module_metadata": {
+ "url": "https://repo.maven.apache.org/maven2/com/facebook/hermes/hermes-android/0.14.1/hermes-android-0.14.1.module",
+ "downloaded_size_and_sha256_match": true
+ }
+ },
+ {
+ "coordinate": "com.facebook.hermes:hermes-android:0.14.1:release",
+ "url": "https://repo.maven.apache.org/maven2/com/facebook/hermes/hermes-android/0.14.1/hermes-android-0.14.1-release.aar",
+ "sha256": "b4e57b503718697db4677aac75c2aaec1d3bb4cfda50ab9935c80da08072c63e",
+ "static_status": "PASS",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libhermesvm.so",
+ "sha256": "eb5a852e438dd9efcf85076abd89c7c38372e9b3b7ee85cd40915dabf6593d85",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 2121616,
+ "memsz": 36976,
+ "end": 2158592,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libhermesvm.so",
+ "sha256": "002bec5ba8cee35b4799f6ab4881efe19962088d53fc9e0dcedb552a86a4b524",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 2207936,
+ "memsz": 36672,
+ "end": 2244608,
+ "end_mod_16384": 0,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ }
+ ],
+ "module_metadata": {
+ "url": "https://repo.maven.apache.org/maven2/com/facebook/hermes/hermes-android/0.14.1/hermes-android-0.14.1.module",
+ "downloaded_size_and_sha256_match": true
+ }
+ },
+ {
+ "coordinate": "io.legere:pdfiumandroid:1.0.32",
+ "url": "https://repo.maven.apache.org/maven2/io/legere/pdfiumandroid/1.0.32/pdfiumandroid-1.0.32.aar",
+ "sha256": "561759462d8071ad16d54f0b83ebdc4daa6e63cd8b0833a6516dcebeaa848f3a",
+ "static_status": "PASS",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libpdfium.so",
+ "sha256": "e3ad7644b9dd203f27e0650d5a1af0a2a73548fad9fe608c209fbd55888d3643",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 4724160,
+ "memsz": 51776,
+ "end": 4775936,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/arm64-v8a/libpdfiumandroid.so",
+ "sha256": "be53f7f812f9ab94b09c694db79b30170c9af9937387be945733424e654b776c",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 425184,
+ "memsz": 21280,
+ "end": 446464,
+ "end_mod_16384": 4096,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libpdfium.so",
+ "sha256": "4f48d1c92fd74a2e5758c98034036393d5b5f12f5eab39175979894976725869",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 4895424,
+ "memsz": 77120,
+ "end": 4972544,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libpdfiumandroid.so",
+ "sha256": "ab5666f50f7fab63a0981fc977fc11e1738399540a950a69482261b4c1f80a49",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 411760,
+ "memsz": 22416,
+ "end": 434176,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ }
+ ]
+ },
+ {
+ "coordinate": "com.facebook.react:react-android:0.83.9:debug",
+ "url": "https://repo.maven.apache.org/maven2/com/facebook/react/react-android/0.83.9/react-android-0.83.9-debug.aar",
+ "sha256": "e8a7e428e5369a541e1eb267b703fb53d84c5be5b2ab32a0d5f8f30dc745e5cc",
+ "static_status": "PASS",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libc++_shared.so",
+ "sha256": "3e852764502d06e0cf1080d532ae7c608b7649d946a3a9d7e84e3d4b7d683214",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 1282800,
+ "memsz": 40208,
+ "end": 1323008,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/arm64-v8a/libfbjni.so",
+ "sha256": "a9e35ba55d3f956920281f519385f8a72475ee24819799cb08375fdd4cce2b22",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 187536,
+ "memsz": 4976,
+ "end": 192512,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/arm64-v8a/libhermestooling.so",
+ "sha256": "f691a1cc4e8e85340ab92f5c5a692a9f5566e9278454b352da097fdf9b59689b",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 719472,
+ "memsz": 17808,
+ "end": 737280,
+ "end_mod_16384": 0,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/arm64-v8a/libjsi.so",
+ "sha256": "3b8cc60472b8e1a0d84df444c8bd4a7b1954fb3470c4c34fbac3615e847ed715",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 919312,
+ "memsz": 18672,
+ "end": 937984,
+ "end_mod_16384": 4096,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/arm64-v8a/libreactnative.so",
+ "sha256": "22f599e15b3dd932d82677b2abeb6845c08668e751ee3425e3fbe68db673cfa3",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 19971840,
+ "memsz": 303360,
+ "end": 20275200,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libc++_shared.so",
+ "sha256": "0a2c7afa35b183fdd5a3cb20e2080ad54cbea06c2a4f0bc8f122cb7d1e9e0b9f",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 1242192,
+ "memsz": 39856,
+ "end": 1282048,
+ "end_mod_16384": 4096,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libfbjni.so",
+ "sha256": "a51410366a0394e05bc04052cfb237c70dcf7d4d53a56e1d00a041436cb0b653",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 183504,
+ "memsz": 4912,
+ "end": 188416,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libhermestooling.so",
+ "sha256": "6b774fe4a5fa31943d7399737da7299e7dd65696d81bc964c3522c26b4a138ce",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 680592,
+ "memsz": 15728,
+ "end": 696320,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libjsi.so",
+ "sha256": "68767a1866fb857c75739e59a3a29c83809229649c7cc14716d3841d53c9afe5",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 907328,
+ "memsz": 18368,
+ "end": 925696,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libreactnative.so",
+ "sha256": "29e5981ab51238dab700cd84e15279619e5a05581eee52880f35cc2db790ef5e",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 19327536,
+ "memsz": 300496,
+ "end": 19628032,
+ "end_mod_16384": 0,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ }
+ ],
+ "module_metadata": {
+ "url": "https://repo.maven.apache.org/maven2/com/facebook/react/react-android/0.83.9/react-android-0.83.9.module",
+ "downloaded_size_and_sha256_match": true
+ }
+ },
+ {
+ "coordinate": "com.facebook.react:react-android:0.83.9:release",
+ "url": "https://repo.maven.apache.org/maven2/com/facebook/react/react-android/0.83.9/react-android-0.83.9-release.aar",
+ "sha256": "a511f9e013cd27bcd7bacb3d825fc681f7778cb11bd14f76e0c24388aee70eeb",
+ "static_status": "PASS",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libc++_shared.so",
+ "sha256": "3e852764502d06e0cf1080d532ae7c608b7649d946a3a9d7e84e3d4b7d683214",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 1282800,
+ "memsz": 40208,
+ "end": 1323008,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/arm64-v8a/libfbjni.so",
+ "sha256": "a9e35ba55d3f956920281f519385f8a72475ee24819799cb08375fdd4cce2b22",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 187536,
+ "memsz": 4976,
+ "end": 192512,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/arm64-v8a/libhermestooling.so",
+ "sha256": "fd2e39f4e3a968a868445e01ae3294e779f1e7c3838103b5e667b06ab865b387",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 146896,
+ "memsz": 8752,
+ "end": 155648,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/arm64-v8a/libjsi.so",
+ "sha256": "8122d5fe2ecfd84772c7b9abedb40cb79175608c7deaf68c25c5d398bc3fda2b",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 400688,
+ "memsz": 13008,
+ "end": 413696,
+ "end_mod_16384": 4096,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/arm64-v8a/libreactnative.so",
+ "sha256": "a0da6ff20683f8bee87861f2683a6fcda8a86fe0fdc22112668c5ab123265f57",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 6173632,
+ "memsz": 150592,
+ "end": 6324224,
+ "end_mod_16384": 0,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libc++_shared.so",
+ "sha256": "0a2c7afa35b183fdd5a3cb20e2080ad54cbea06c2a4f0bc8f122cb7d1e9e0b9f",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 1242192,
+ "memsz": 39856,
+ "end": 1282048,
+ "end_mod_16384": 4096,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libfbjni.so",
+ "sha256": "a51410366a0394e05bc04052cfb237c70dcf7d4d53a56e1d00a041436cb0b653",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 183504,
+ "memsz": 4912,
+ "end": 188416,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libhermestooling.so",
+ "sha256": "ca834ac984a34cbcd14381f4fc63287af58495ec0bf3f3466976e1c0fc96e5ec",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 143584,
+ "memsz": 7968,
+ "end": 151552,
+ "end_mod_16384": 4096,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libjsi.so",
+ "sha256": "d728958aa4ea58816c557ea0ae5b87e44983a5b056e27b6a3ddc2413c9e52bc1",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 407808,
+ "memsz": 9984,
+ "end": 417792,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libreactnative.so",
+ "sha256": "458499dfe2014ba2b9bd7555aabf28b9d3d5b6825330376362720863f6e3c974",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 6288496,
+ "memsz": 150416,
+ "end": 6438912,
+ "end_mod_16384": 0,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ }
+ ],
+ "module_metadata": {
+ "url": "https://repo.maven.apache.org/maven2/com/facebook/react/react-android/0.83.9/react-android-0.83.9.module",
+ "downloaded_size_and_sha256_match": true
+ }
+ },
+ {
+ "coordinate": "io.sentry:sentry-native-ndk:0.13.3",
+ "url": "https://repo.maven.apache.org/maven2/io/sentry/sentry-native-ndk/0.13.3/sentry-native-ndk-0.13.3.aar",
+ "sha256": "f09e7dd432b99e0b9c782eeec5c90887171b3ff5065134bc246ff217f7698c32",
+ "static_status": "PASS",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libsentry-android.so",
+ "sha256": "0cc45445f6f545256be5102a39fae3c482d40970b8b3f6cffb8e0f00a3e1172e",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 31392,
+ "memsz": 1376,
+ "end": 32768,
+ "end_mod_16384": 0,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/arm64-v8a/libsentry.so",
+ "sha256": "7ba1fe9acd50e7f6ff980aae31ea06123e99e3e4b4c6dbadd1314cdfaca1b4f9",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 731344,
+ "memsz": 26416,
+ "end": 757760,
+ "end_mod_16384": 4096,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libsentry-android.so",
+ "sha256": "747747abea1312a76a61eabe673b185556c6467e6d02facefefc7ee645483b8f",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 30896,
+ "memsz": 1872,
+ "end": 32768,
+ "end_mod_16384": 0,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libsentry.so",
+ "sha256": "a388dbf74c684603c02730bb90ea2ac4db7df5048334874a6d9c7f5beedf6dd8",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 717696,
+ "memsz": 23680,
+ "end": 741376,
+ "end_mod_16384": 4096,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ }
+ ]
+ },
+ {
+ "coordinate": "com.google.mlkit:barcode-scanning:17.3.0",
+ "url": "https://dl.google.com/dl/android/maven2/com/google/mlkit/barcode-scanning/17.3.0/barcode-scanning-17.3.0.aar",
+ "sha256": "64c5cf48bb94b6c54f2c785c660640a7d167aff6ad72bc2c920706dc4187b79a",
+ "static_status": "PASS",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libbarhopper_v3.so",
+ "sha256": "ec09597e9eb3aee0eb55ae3366da0d4ba416f5aa35a1af0b3811f50ff46743a1",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 4866048,
+ "memsz": 49152,
+ "end": 4915200,
+ "end_mod_16384": 0,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libbarhopper_v3.so",
+ "sha256": "6c5deea87d962af008fd48c3229db13ab68eef2e9feeccb2df5b33a920c0579a",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 5832704,
+ "memsz": 45056,
+ "end": 5877760,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ }
+ ]
+ },
+ {
+ "coordinate": "androidx.camera:camera-core:1.5.0-alpha03",
+ "url": "https://dl.google.com/dl/android/maven2/androidx/camera/camera-core/1.5.0-alpha03/camera-core-1.5.0-alpha03.aar",
+ "sha256": "c07ef5ee196ae35a4d3d77babae6197460929b38970c9ca7d3acc61e85986198",
+ "static_status": "PASS",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libimage_processing_util_jni.so",
+ "sha256": "067d083e0c4de78aac6ae431df298947020990fe3f5ae743b5bd418d0d144b46",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 42912,
+ "memsz": 2144,
+ "end": 45056,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libimage_processing_util_jni.so",
+ "sha256": "352fa6662094b3a3e3ad60893219cb889180c452c74ffab8025720e0bef4c6db",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 59728,
+ "memsz": 1712,
+ "end": 61440,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ }
+ ]
+ },
+ {
+ "coordinate": "io.github.zhongwuzw:mmkv:2.4.0",
+ "url": "https://repo.maven.apache.org/maven2/io/github/zhongwuzw/mmkv/2.4.0/mmkv-2.4.0.aar",
+ "sha256": "f1f40d7460d689aa3768bb51c38de917ab4cd5946928db371f1be1aaa5997e82",
+ "static_status": "PASS",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libc++_shared.so",
+ "sha256": "ad74bf43eb1fd576518168f664ad16a74e00eeda9595875c33dd87f6dd197869",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 1243288,
+ "memsz": 42856,
+ "end": 1286144,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/arm64-v8a/libmmkv.so",
+ "sha256": "7e63e305547b410717b12ea6c15aacd7c59610b4b6ebcb1796fe18929fedc2a5",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 366336,
+ "memsz": 6400,
+ "end": 372736,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libc++_shared.so",
+ "sha256": "294e0ce4e88589103952c57c9484f917c26509d66170bc86d07d48f0fc879de4",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 1219776,
+ "memsz": 41792,
+ "end": 1261568,
+ "end_mod_16384": 0,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libmmkv.so",
+ "sha256": "4f646fce28adccac88af7a4179f6928503337c196c7f52c1a15afbff222c4f5a",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 368576,
+ "memsz": 4160,
+ "end": 372736,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ }
+ ]
+ },
+ {
+ "coordinate": "libportal-react-native@2ff681b0b725009768acadb35b2731fb1a402fa3:android/libs/libportal-android-0.3.4-SNAPSHOT.aar",
+ "url": "https://github.com/bithyve/libportal-react-native/blob/2ff681b0b725009768acadb35b2731fb1a402fa3/android/libs/libportal-android-0.3.4-SNAPSHOT.aar",
+ "sha256": "f12252c9ca9c8dc2fa58e44841e5b340e95072dae2c9ae1e21d79a23e060c1fa",
+ "static_status": "PASS",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libportal.so",
+ "sha256": "7c1e474e03dfdc71bea0aeaa8afca22bb357ac23df99136ed73453ed4e1d677d",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 2415072,
+ "memsz": 50720,
+ "end": 2465792,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libportal.so",
+ "sha256": "dbc6a0afeffe068209495005ce9d010f39b3cd47f6e33a8a9b4a901b7616d4fc",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 2700800,
+ "memsz": 55808,
+ "end": 2756608,
+ "end_mod_16384": 4096,
+ "whole_matching_load_exemption": true
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ }
+ ]
+ },
+ {
+ "coordinate": "net.java.dev.jna:jna:5.14.0@aar",
+ "url": "https://repo.maven.apache.org/maven2/net/java/dev/jna/jna/5.14.0/jna-5.14.0.aar",
+ "sha256": "81a8b9afc65f9d6b205338c25908af8de0ff8411a00985104c9d83fffdfab380",
+ "static_status": "FAIL",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libjnidispatch.so",
+ "sha256": "3730ce014f7a6807ae74af78c3b9f5a3cba1f5886316b3d3858493df923efe96",
+ "load_min_p_align": 65536,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 220064,
+ "memsz": 1120,
+ "end": 221184,
+ "end_mod_16384": 8192,
+ "whole_matching_load_exemption": false
+ }
+ ],
+ "android17_effective_program_alignment": 8192,
+ "android17_load_page_overlap": false,
+ "static_status": "FAIL",
+ "failures": [
+ "Android 17 effective program alignment is 8192",
+ "nonaligned RELRO end has no whole-LOAD exemption"
+ ]
+ },
+ {
+ "entry": "jni/x86_64/libjnidispatch.so",
+ "sha256": "a6d3997d3cfc0dba1b00fd2943b41e7395741e88336ed6f6237b594c94083eea",
+ "load_min_p_align": 4096,
+ "load_alignment_pass": false,
+ "load_16kb_congruence_pass": false,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 109312,
+ "memsz": 1280,
+ "end": 110592,
+ "end_mod_16384": 12288,
+ "whole_matching_load_exemption": false
+ }
+ ],
+ "android17_effective_program_alignment": 4096,
+ "android17_load_page_overlap": false,
+ "static_status": "FAIL",
+ "failures": [
+ "LOAD p_align is not a power of two of at least 16384",
+ "LOAD virtual/file offsets are not congruent",
+ "Android 17 effective program alignment is 4096",
+ "nonaligned RELRO end has no whole-LOAD exemption"
+ ]
+ }
+ ]
+ },
+ {
+ "coordinate": "net.java.dev.jna:jna:5.18.1@aar",
+ "url": "https://repo.maven.apache.org/maven2/net/java/dev/jna/jna/5.18.1/jna-5.18.1.aar",
+ "sha256": "7f053e3ec99e14dd71259c82c1c8a02738d64a13c31226b2acc170f3060951e0",
+ "static_status": "PASS",
+ "libraries": [
+ {
+ "entry": "jni/arm64-v8a/libjnidispatch.so",
+ "sha256": "abc26e994517bcaa3309acdb0a27373864086c7569c89d3087b8626fada9ef06",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 179096,
+ "memsz": 1128,
+ "end": 180224,
+ "end_mod_16384": 0,
+ "whole_matching_load_exemption": false
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ },
+ {
+ "entry": "jni/x86_64/libjnidispatch.so",
+ "sha256": "3809247e9b804a05ed8377b87d545cf5b5e97f960f75e725bc8497b40260e417",
+ "load_min_p_align": 16384,
+ "load_alignment_pass": true,
+ "load_16kb_congruence_pass": true,
+ "load_declared_congruence_pass": true,
+ "relro": [
+ {
+ "vaddr": 129792,
+ "memsz": 1280,
+ "end": 131072,
+ "end_mod_16384": 0,
+ "whole_matching_load_exemption": false
+ }
+ ],
+ "android17_effective_program_alignment": 16384,
+ "android17_load_page_overlap": false,
+ "static_status": "PASS",
+ "failures": []
+ }
+ ]
+ }
+ ]
+}
diff --git a/release/r4-android-16kb.md b/release/r4-android-16kb.md
new file mode 100644
index 0000000000..27255363af
--- /dev/null
+++ b/release/r4-android-16kb.md
@@ -0,0 +1,236 @@
+# R4 Android 16 KB supplier correction and Local retest
+
+15 October 2026. State: **NEEDS_LOCAL / NOT RELEASE-READY**. This is a targeted
+continuation of [#7045](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045),
+preserving `698078e1765d1e0728145f0ef6def05195192b30`. The newest PR **Codex local
+handoff** names the full final SHA; this file cannot contain its own eventual SHA.
+Read [AGENTS.md](../AGENTS.md), the [complete native handoff](r4-automatic-backup-local-handoff.md)
+and [backup matrix](../openspec/changes/fix-recovery-backup-freshness/automatic-write-validation.md).
+
+## Failure and supplier identity
+
+The [retained exact-698 Local report](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045#issuecomment-6178691569)
+records developmentDebug 2.6.4(627), package `io.hexawallet.keeper.development`, APK
+SHA256 `8d73e790f9b47766c92e927d7fe8425ad4967cfe44607cf35312cbb87e469af8`.
+A genuinely fresh Android17/API37 arm64 emulator reported `PAGE_SIZE=16384`.
+Default launch reached Create Passcode and initialized MMKV files. After enabling
+the official strict properties on that new emulator only, relaunch aborted:
+
+```text
+lib/arm64-v8a/libjnidispatch.so program alignment (8192) cannot be smaller than system page size (16384)
+Fatal signal 6 (SIGABRT)
+```
+
+The failing library's LOAD `p_align=0x10000` and STORED ZIP data offset `48709632`
+both pass their respective alignment checks. Its GNU_RELRO end is `0x36000`,
+with remainder `0x2000` modulo 16 KB. This is not a failed LOAD or ZIP check.
+
+Cloud downloaded official Maven Central AARs and reproduced the reported library
+identity without accessing any Mac-local artifact:
+
+| Bytes | SHA256 |
+| --- | --- |
+| [Official JNA 5.14.0 AAR](https://repo.maven.apache.org/maven2/net/java/dev/jna/jna/5.14.0/jna-5.14.0.aar) | `81a8b9afc65f9d6b205338c25908af8de0ff8411a00985104c9d83fffdfab380` |
+| Its raw arm64 library, 168176 bytes | `3730ce014f7a6807ae74af78c3b9f5a3cba1f5886316b3d3858493df923efe96` |
+| Same library after LLVM 19.1.7 `llvm-strip --strip-unneeded`, 157720 bytes | `fe9c603f2a7a5d19197b87f275d6e0afb975f997a57ff4f8ca801cb8c5e7b731` |
+| [Selected JNA 5.18.1 AAR](https://repo.maven.apache.org/maven2/net/java/dev/jna/jna/5.18.1/jna-5.18.1.aar) | `7f053e3ec99e14dd71259c82c1c8a02738d64a13c31226b2acc170f3060951e0` |
+| Selected raw arm64 library | `abc26e994517bcaa3309acdb0a27373864086c7569c89d3087b8626fada9ef06` |
+
+Maven's published SHA1 sidecars independently matched 5.14.0 and 5.18.1 downloads
+(`17b4b6c99bdc5586644d7f97fca4dd84d8889fb0` and
+`8e93d068c4eab70ada4c79e010198a112aa3c581`). Local separately reproduced the
+same 5.14.0 packaged hash with its trusted NDK27.1 strip tool. The new supplier
+arm64 library has LOAD alignment `0x4000` and RELRO end `0x2c000`, remainder zero.
+LLVM 19.1.7 stripping of the new arm64 library yields
+`ddfc6c965bbe366615c000ec1f06552ddf0bb2b4f9d921d0bff8c75b3cb2ca4c`;
+verify the actual build transformation rather than assuming this future APK hash.
+
+## Narrow dependency change
+
+The pinned [Portal bridge](https://github.com/bithyve/libportal-react-native/blob/2ff681b0b725009768acadb35b2731fb1a402fa3/android/build.gradle#L99)
+declares `implementation "net.java.dev.jna:jna:5.14.0@aar"` without a debug-only
+condition. Its Git pin is unchanged in `package.json` and `yarn.lock`. The app
+retains arm64 for both flavors and excludes only x86_64 `libjnidispatch.so`.
+This establishes production dependency/packaging input risk. It does not prove
+the contents or behavior of an unbuilt signed production AAB or generated split.
+
+An app-level strict `implementation('net.java.dev.jna:jna:5.18.1@aar')` selects
+one matched Java/native artifact for every app variant. No Portal source, native
+library exclusion, compatibility switch, app-wide linker flag or readiness gate
+is changed. A version conflict fails resolution instead of silently selecting
+another version.
+
+The version is based on upstream fixes and actual binaries:
+
+| JNA | arm64 LOAD alignment | arm64 RELRO end | Result |
+| --- | --- | --- | --- |
+| 5.14.0 / 5.15.0 | 0x10000 | 0x36000 | FAIL, effective program alignment 8192 |
+| 5.16.0 | 0x4000 | 0x2a000 | FAIL, effective program alignment 8192 |
+| 5.17.0 | 0x4000 | 0x2c000 | First fixed native binary |
+| 5.18.0 / 5.18.1 / 5.19.0 / 5.19.1 | 0x4000 | 0x2c000 | Same fixed arm64 native bytes |
+
+[JNA #1654](https://github.com/java-native-access/jna/pull/1654), commit
+`5305913155092d793f806f51f3c3e0e85869c4da`, adds `common-page-size=16384`, rebuilds
+natives and advances native ABI 7.0.3 to 7.0.4. Replacing only the `.so` would
+break the matched supplier relationship. 5.18.0 fixes the Structure constructor
+deadlock introduced in 5.16 ([#1681](https://github.com/java-native-access/jna/issues/1681));
+5.18.1 fixes the concurrent `sortFields` race reported by Android UniFFI
+([#1686](https://github.com/java-native-access/jna/issues/1686)). Portal uses
+concurrent UniFFI calls and nested JNA Structures. Thus 5.18.1 is the minimum
+selected line including those relevant managed fixes, rather than the earliest
+native-only fix. These races were not reproduced in Keeper. Static classfile
+inspection found all 19 explicit Portal JNA member references in the selected
+classes, with matching names/descriptors; this is not runtime compatibility proof.
+
+A resolution-only Gradle 8.14.3 project with the actual Portal declaration and
+the app's strict declaration passed three tasks: original 5.14.0 baseline,
+single 5.18.1 AAR on app compile/runtime paths with the transitive 5.14 request
+upgraded, and rejection of an incompatible strict 5.19.1 request. The resolved
+5.18.1 AAR matches the supplier SHA above. This harness is not an actual AGP
+developmentDebug or productionRelease dependency graph; those remain Local checks.
+
+## Static inspection scope
+
+The [official Android guide](https://developer.android.com/guide/practices/page-sizes)
+requires ELF, RELRO, packaging and runtime checks separately, and rebuilding or
+reimporting affected prebuilts. Repository linker flags cannot change a supplier
+prebuilt. The checker models the public Android17 bionic revision
+[`06356e41c5ed7b12220b24c05ba4fdb873b126a7`](https://android.googlesource.com/platform/bionic/+/06356e41c5ed7b12220b24c05ba4fdb873b126a7/linker/linker_phdr_16kib_compat.cpp).
+For a RELRO that exactly prefixes but does not cover its entire LOAD, that helper
+uses the lowest set bit of its end: `lowbit(0x36000)=8192`. This matches the
+observed diagnostic. The exact emulator linker revision was not inspected.
+
+The earlier 49/59 nonaligned RELRO ends are retained as a raw observation, not
+49 demonstrated strict-mode crashes. A whole-LOAD RELRO is exempt in the
+checked Android17 helper. The pinned Portal library has that layout on both
+64-bit ABIs and passes the computed program-alignment/overlap checks; its raw
+end remainder alone does not justify rebuilding or removing Portal.
+
+`scripts/check-android-16kb.py` separately records each supplied library's SHA,
+LOAD alignment/congruence, raw RELRO end, whole-LOAD exception, Android17
+effective alignment/LOAD-page overlap and actual APK local-header data offset.
+AAR ZIP offsets are not APK evidence. Compressed APK entries report
+`NOT_PROVEN` because extraction/manifest behavior is not established. Its PASS
+means only the supplied static checks passed, never that Android ran the app.
+
+The [supplier inventory](evidence/r4-android-16kb-suppliers-2026-10-15.json)
+records 50 64-bit entries across 13 explicitly downloaded AAR inputs, including
+both old/fixed JNA and duplicate debug/release shared runtimes. This is not a
+count of retained APK libraries. The 48 entries outside old JNA pass these static
+checks. Old JNA arm64 fails effective8192; old JNA x86_64 also fails LOAD4KB but
+that ABI's JNA is already excluded by this app. The other inspected inputs are:
+
+| Supplier input | Inspected 64-bit entries | Static result |
+| --- | --- | --- |
+| React Android0.83.9 debug + release | 10 + 10 | PASS |
+| Hermes Android0.14.1 debug + release | 2 + 2 | PASS |
+| fbjni0.7.0 | 4 | PASS |
+| pdfiumandroid1.0.32 | 4 | PASS |
+| Sentry native0.13.3 | 4 | PASS |
+| Pinned Portal0.3.4-SNAPSHOT | 2 | PASS, whole-LOAD exception |
+| MMKV2.4.0 | 4 | PASS |
+| MLKit barcode17.3.0 | 2 | PASS |
+| CameraX1.5.0-alpha03 image processing | 2 | PASS |
+
+These are supplier-byte observations. Actual resolved graph selection,
+`libc++_shared.so` pick-first identity and source-linked Realm/RN/autolinked
+outputs must be inventoried from the rebuilt APK. A static source archive or
+repository linker option cannot establish their final ELF layout.
+
+Cloud cannot access the Mac's retained APK or full 59-library scan. Downloading
+the existing hosted diagnostic APK was blocked at the signed artifact host with
+HTTP403. That older artifact is production-flavor/public-debug-key/placeholder
+configuration and is not the reported development APK or a signed production
+release. Therefore exact-APK supplier mapping and all packaged/source-linked
+libraries remain required; a supplier sample is not a complete APK inventory.
+
+## Actual Cloud checks
+
+- Checker regression suite: PASS 20/20, including failing JNA-style RELRO prefix,
+ corrected prefix, whole-LOAD exception, overlapping LOAD pages, malformed ELF,
+ APK local-header offsets, duplicate entries and compressed-entry uncertainty.
+- Genuine Node22.23.3/native Realm/transactional loopback Relay matrix: PASS
+ 263/263, zero skips, paired Relay `838049e537e07eb646a2a0393eb969fba43d0739`.
+- Recovery: PASS 448/448, zero skips. Jest: PASS 42 suites / 432 tests.
+- Release rules: PASS 28 Node and 7 Python tests. Ruby fake-action regressions:
+ NOT RUN here, `ruby` unavailable; the combined release command exited127.
+- Version consistency: PASS 2.6.4 / Android627 / iOS620, still provisional.
+- Release preflight: FAIL; both authenticated store baselines exceed24hours.
+- Full TypeScript/lint: NOT RUN for this Android-only dependency change. The
+ prior inherited failures remain failures, not new clean results.
+- Actual AGP variant graphs, new native build, install, launch, MMKV/Realm,
+ Portal/wallet/backup smoke, physical hardware and production AAB/splits:
+ **NOT RUN in Cloud**. No Android SDK or interactive emulator is installed here.
+
+The tests above used this source change with the unchanged package/Yarn inputs
+and existing dependency caches; the final commit adds this evidence/handoff.
+Neither hosted-backup gate nor approved contributor pins changed. The manifest
+SHA256 remains `2706b8a1c250c93d4098384201cba0188c667777b8fa2d2fdc5267380e0ccfcc`.
+
+## Exact-head Local continuation
+
+1. Resolve the newest PR handoff and verify its full SHA equals the live head,
+ using the safe isolated setup in the complete handoff. Preserve all owner
+ apps/data and old test artifacts. Keep Relay `838049e537e07eb646a2a0393eb969fba43d0739`
+ separate from the approved contributor stack. No paid/real provider calls.
+2. With the source's JDK17/SDK36/NDK27.1 toolchain and disposable `.env.local`,
+ capture `:app:dependencyInsight --dependency net.java.dev.jna:jna` for
+ `--configuration developmentDebugRuntimeClasspath`,
+ `developmentDebugCompileClasspath` and `productionReleaseRuntimeClasspath`.
+ Inspect `:libportal-react-native:dependencies` as well. Production graph
+ inspection is read-only, not permission to build/sign a production artifact.
+ Verify one matched 5.18.1 AAR; retain any standalone Portal compile5.14 edge
+ separately from the app's final compile/runtime selection.
+3. Build **developmentDebug only** from the exact SHA with the disposable debug
+ certificate, for arm64. Record package/version/certificate/APK SHA and SDK/NDK.
+ Scan the actual APK and the resolved AAR, including every retained64-bit
+ library. Preserve JSON and failed results; do not filter the scan to JNA.
+
+ ```bash
+ python3 -B -m unittest scripts/test_check_android_16kb.py
+ python3 scripts/check-android-16kb.py /actual/resolved/jna-5.18.1.aar
+ python3 scripts/check-android-16kb.py /actual/new-development.apk > /private/evidence/new-apk-16kb.json
+ "$ANDROID_SDK_ROOT/build-tools/35.0.0/zipalign" -c -P 16 -v 4 /actual/new-development.apk
+ ```
+
+ Attribute every `.so` to resolved Maven/local AAR or actual source-linked
+ output, particularly `libc++_shared.so` selected by `pickFirst`. Reconcile the
+ earlier59-entry scan and distinguish raw RELRO remainders from strict failures.
+ Verify JNA supplier-to-merged/stripped-to-APK byte identity using the actual
+ NDK strip transformation. No LOAD-only or AAR-only compatibility claim.
+4. Use a **new disposable arm64 Android17/API37 16KB AVD only**. Prove serial/AVD,
+ ABI and `adb shell getconf PAGE_SIZE` =16384. Following official guidance,
+ set and read back `bionic.linker.16kb.app_compat.enabled=fatal` and
+ `pm.16kb.app_compat.disabled=true` on that AVD, before the strict install/launch
+ sequence. Never alter the owner's device properties or enable compatibility
+ to obtain a pass. Record actual install, force-stop/cold-launch and native
+ logs: no SIGABRT, linker alignment error, Java/native mismatch or swallowed
+ Portal initialization error. Portal SDK construction is eager; reaching PIN
+ alone is not full Portal acceptance. Also retain a normal4KB launch regression.
+5. On the strict16KB runtime, actually exercise disposable PIN/onboarding,
+ native MMKV creation/cold persistence, encrypted Realm create/read/reopen,
+ wallet/vault/import/export and paired-loopback backup opt-in, complete
+ readback, automatic local-first mutation, recovery and relevant relaunch
+ regressions. Record Portal constructor/native dispatch and available safe
+ Portal UI/cancellation separately from unavailable NFC/card signing. Keep
+ Android C8/#7056 **parked and failed**; do not restart its fix/retest cycle.
+6. Required local checks remain **IOS, ANDROID, HARDWARE**. Rerun relevant iOS
+ Debug simulator/PIN/Realm/wallet/backup smoke against the new exact SHA and
+ continue other feasible existing native requirements. Do not claim an old
+ artifact validates the new SHA. Hardware/NFC/USB tests are NOT RUN unless
+ actually performed; a new exact-SHA owner scope decision is needed for any
+ physical-only deferral. A locked Mac may permit command-line preparation,
+ but unperformed build/install/launch/UI checks remain BLOCKED/NOT RUN.
+7. Post an exact-SHA **Codex local validation** comment with hashes, per-library
+ static results, strict-property/page-size proof, actual native outcomes and
+ every failed/blocked/unrun category. Preserve the698 LOCAL_FAILED evidence.
+
+Android C8 remains a separate known failure. Human review, current Local
+acceptance, production backend all-instance/index/transaction/old-writer rollout
+proof, fresh store histories and separate Desktop/website deliverables remain
+open. Both backup gates and approved contributor manifest stay unchanged.
+No merge, deployment, index creation, release signing, AAB/split construction,
+upload, publication, customer message or real transaction is authorized here.
+Production AAB/split identity and strict runtime verification require a separate
+owner-approved artifact stage. R4 stays independent of Reproducibility and
+Bitkey Wallet; this source correction is not release readiness.
diff --git a/release/r4-automatic-backup-local-handoff.md b/release/r4-automatic-backup-local-handoff.md
new file mode 100644
index 0000000000..bcc10561d0
--- /dev/null
+++ b/release/r4-automatic-backup-local-handoff.md
@@ -0,0 +1,288 @@
+# R4 / 2.6.4 automatic backup: Codex Local handoff
+
+**Current protected-v3 continuation:** follow [the protected-backup app handoff](r4-protected-backup-app.md) and the newest exact-SHA PR comment. Its guarded private backend7693/loopback27038 setup supersedes the public-v2 commands below for the current app. The historical public838 results remain preserved; they do not validate v3. Do not run this document’s old v2 setup as current protected-backup acceptance.
+
+State: **NEEDS_LOCAL**. PR [#7045](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045), branch `codex/r4-264-combined-candidate`, base `sprint`. The exact final SHA is recorded in the newest **Codex local handoff** on that PR. The setup below verifies that handoff against the live head before selecting it; this repository document cannot contain its own eventual commit SHA.
+
+**Node-bootstrap continuation:** follow the [managed producer and original-order Local retest](r4-node-bootstrap-backup.md). This supersedes the narrower queue-only retest below: use one new incremental artifact per platform and test initial Verified→ordinary detail bootstrap→automatic complete Verified→ordinary rename→complete readback/cold persistence. Preserve9a19 native controls and its original bootstrap failure separately; all remaining R4 gaps and restrictions stay open.
+
+**Queue-admission continuation:** follow the [narrow fix and focused Local retest](r4-backup-queue-admission.md). The only changed app module is backup inspection queue admission; native/dependency/configuration inputs are unchanged from17e0. Use incremental builds and one focused ordinary-rename/native smoke retest on both platforms. Preserve17e0 failures and independent test results; do not repeat unrelated large matrices or infer a uniquely proved native cause. The prior full R4 gaps remain tracked, C8/#7056 stays parked, and any further failure must be reported without another speculative fix loop.
+
+**15 October Android continuation:** read the [16 KB supplier proof and targeted retest](r4-android-16kb.md) and retain the [698078 Local failure](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045#issuecomment-6178691569). The new JNA selection requires a new development build and actual strict-16-KB launch; no native result transfers to this head. Android C8 / [#7056](https://github.com/KeeperCommunity/bitcoin-keeper/issues/7056) remains owner-parked with its observed FAIL: do not restart that bug's fix/retest cycle. Other required native and release blockers remain open. Production AAB/generated-split construction, signing, upload and runtime verification are a separate owner-approved artifact stage.
+
+Paired disposable Relay: **`838049e537e07eb646a2a0393eb969fba43d0739`**, draft [Relay #4](https://github.com/KeeperCommunity/Relay/pull/4). The originally requested `b600416e5ba7325927d7d2871cff7776f4e593fe` was tested: native Android opt-in reached a real repair write but failed complete readback because `createNewApp` had precreated an AppImage without subscription and repair wrote that field only on insert. The successor sets subscription on existing AppImages during explicit revisioned repair, after the transaction's revision and conflict checks. It is a loopback test dependency, not a deployed-service assertion. The approved contributor manifest in `dev/local-backend/sources.lock.json` remains Relay `ee935359f22ff7932ea0a62e9084d4b49801f4aa` and SigningServer `3cc7728c27328e7b0358d1f91a32d8d13feba90a`; do not replace those pins or overwrite generated contributor checkouts to prepare this test.
+
+`AUTOMATIC_BACKUP_SOURCE_READY` is true after genuine disposable proof and independent fixture review. It permits development loopback validation with an explicit port. `AUTOMATIC_BACKUP_RELAY_ROLLOUT_READY` remains false until the separately authorized deployed fleet, transactions/indexes, v2 route and old-writer drainage are verified. The Node fixture permits its explicit loopback test target. Hosted writes remain fenced. Do not change either gate to make a test pass. Current source and results are recorded in [the proof matrix](../openspec/changes/fix-recovery-backup-freshness/automatic-write-validation.md).
+
+The historical [Local report](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045#issuecomment-6128906958) at `b160656218dc6065ad12af9db220c974255bfc23` is **LOCAL_FAILED**. Its unsigned iOS simulator compile and Android development build passed; install, launch and UI scenarios were not run because the Mac was locked. Seven automatic writes remained disabled and opted-in deletions remained blocked. Its physical deferral and earlier native evidence do not validate a newer SHA. No current app native pass is claimed by this document.
+
+The combined source also retains the bracketed iOS import and shared PIN keypad changes assembled at `bb66cea459fbb00ec33c5c4ebd601d07c0d7c125` from [#7051](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7051) and [#7052](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7052). Their contributor reports used local dependency-lock changes outside those PRs. Validate the final combined dependency set and native behavior again; Jest rendering does not prove Fabric keypad visibility.
+
+## Copy into Codex Local
+
+```text
+Validate Keeper PR #7045 on the exact Head commit in its newest Codex local handoff.
+
+For the Android 16 KB continuation, also follow release/r4-android-16kb.md.
+Keep Android C8/#7056 parked; retain its observed FAIL without a fix/retest cycle.
+
+Read the latest PR description, newest Codex local handoff, AGENTS.md and
+release/r4-automatic-backup-local-handoff.md at the final head. Read the complete
+automatic-write-validation.md matrix. Recheck the live PR head; if it differs,
+report the mismatch and obtain the current handoff rather than testing stale code.
+
+Preserve every existing checkout, installed owner app, wallet and database. Use
+new isolated checkouts, simulator/emulator state and disposable test accounts.
+Use paired public Relay 838049e537e07eb646a2a0393eb969fba43d0739 separately from
+the approved contributor bootstrap. Do not edit its source or replace the
+approved sources.lock.json pins. Save exact source identities and private logs.
+
+Run the Node 22 genuine native-Realm/transactional-Relay runner and all seven
+operations through C1-C10, complete producer/fanout and clean Recovery Key
+restore cases. Missing native bindings, a skipped matrix or substituted mocks
+are BLOCKED/FAIL, never PASS. Run relevant regression/release checks.
+
+On the exact final app source, build unsigned iOS simulator and development
+Android artifacts, then actually install, launch and exercise disposable UI
+flows on BOTH platforms. Complete the critical backup/account/recovery matrix;
+retain bracketed iOS BSMS/TXT import, keypad/cooldown, PIN/Proceed, Testnet
+tutorial/faucet-to-visible-balance, modal, inheritance/timelock and profiling
+checks below. Source-unit evidence does not replace native launch/UI results.
+
+Required local checks: IOS, ANDROID, HARDWARE. Read #7050's integrated policy in
+AGENTS.md. Only the release owner's new exact-SHA OWNER_DEFERRED_PHYSICAL comment
+can defer unrun physical HARDWARE checks; old b160 decisions do not carry over.
+IOS and ANDROID cannot be deferred. A known critical failure cannot be deferred.
+
+Post a new exact-SHA Codex local validation report with actual pass/fail/not-run
+outcomes, versions/artifact hashes, private-log locations and open blockers.
+LOCAL_PASSED covers only the stated tested subset, never deferred devices.
+Do not merge, deploy, modify production records/indexes, sign a release, upload
+to stores, publish artifacts/releases, or use real funded MAINNET wallets. Keep R4 separate
+from Reproducibility and Bitkey Wallet. Continue feasible checks if one prerequisite
+is blocked, but do not waive a critical or required platform result.
+```
+
+## Safe exact-source setup
+
+Select the existing Node **22** toolchain; use Yarn Classic **1.22.22**. Do not overwrite global tool configuration or existing Node/Realm installations. These commands create private temporary directories and fresh detached checkouts. Run them in Bash and retain the printed workspace path for follow-up. GitHub CLI must have read access; a missing or mismatched exact-head handoff fails before checkout.
+
+```bash
+set -euo pipefail
+umask 077
+keeper_app_sha=$(gh pr view 7045 --repo KeeperCommunity/bitcoin-keeper --json headRefOid |
+ python3 -c 'import json,sys; print(json.load(sys.stdin)["headRefOid"])')
+keeper_handoff_sha=$(gh api --paginate --slurp \
+ 'repos/KeeperCommunity/bitcoin-keeper/issues/7045/comments?per_page=100' |
+ python3 -c 'import json,re,sys; pages=json.load(sys.stdin); comments=[c for page in pages for c in page]; handoffs=[c["body"] for c in comments if c.get("body", "").startswith("## Codex local handoff")]; assert handoffs, "Missing Codex local handoff"; matches=re.findall(r"(?m)^Head commit:\s*([0-9a-f]{40})\s*$", handoffs[-1]); assert matches, "Missing handoff SHA"; print(matches[-1])')
+test "$keeper_app_sha" = "$keeper_handoff_sha" || {
+ printf 'Live PR head and newest Codex local handoff differ.\n' >&2
+ exit 1
+}
+keeper_relay_sha=838049e537e07eb646a2a0393eb969fba43d0739
+test "${#keeper_app_sha}" -eq 40
+test "$(node -p 'process.versions.node.split(".")[0]')" = 22
+keeper_qa_root=$(mktemp -d "${TMPDIR:-/tmp}/keeper-r4-local.XXXXXX")
+keeper_app_dir="$keeper_qa_root/app"
+keeper_relay_dir="$keeper_qa_root/relay"
+keeper_evidence_dir="$keeper_qa_root/evidence"
+mkdir -p "$keeper_evidence_dir"
+printf 'Isolated R4 workspace: %s\n' "$keeper_qa_root"
+
+git clone --filter=blob:none --no-checkout https://github.com/KeeperCommunity/bitcoin-keeper.git "$keeper_app_dir"
+git -C "$keeper_app_dir" fetch origin refs/pull/7045/head
+test "$(git -C "$keeper_app_dir" rev-parse FETCH_HEAD)" = "$keeper_app_sha"
+git -C "$keeper_app_dir" checkout --detach "$keeper_app_sha"
+git clone --filter=blob:none --no-checkout https://github.com/KeeperCommunity/Relay.git "$keeper_relay_dir"
+git -C "$keeper_relay_dir" checkout --detach "$keeper_relay_sha"
+git -C "$keeper_app_dir" diff --quiet HEAD
+git -C "$keeper_relay_dir" diff --quiet HEAD
+
+cd "$keeper_app_dir"
+yarn install --frozen-lockfile --ignore-scripts
+yarn patch-package
+./node_modules/.bin/rn-nodeify --install buffer,events,process,stream,inherits,path,assert,crypto --hack --yarn
+(cd node_modules/realm && ../.bin/prebuild-install --runtime napi --target 6)
+(cd "$keeper_relay_dir" && yarn install --frozen-lockfile --non-interactive --ignore-scripts)
+export REALM_DISABLE_ANALYTICS=1
+export KEEPER_RELAY_FIXTURE_MODULE="$keeper_relay_dir/tests/support/automaticBackupHttpFixture.cjs"
+export BACKUP_TEST_MONGO_URL=mongodb://127.0.0.1:27058
+```
+
+Confirm Docker uses the local Mac Docker Desktop/Colima engine. Port **27058** must be free; do not stop somebody else's service to claim it. The runner rejects a different port, credentials, non-loopback Mongo, an incorrect Relay SHA or tracked Relay changes. A native Realm write/read probe must really pass; do not substitute the Jest Realm mock.
+
+```bash
+docker info --format '{{.ServerVersion}}'
+if lsof -nP -iTCP:27058 -sTCP:LISTEN; then
+ printf 'Port 27058 is occupied; coordinate an isolated fixture first.\n' >&2
+ exit 1
+fi
+keeper_mongo_name="keeper-r4-local-mongo-$$"
+docker run --detach --rm --name "$keeper_mongo_name" \
+ --publish 127.0.0.1:27058:27058 \
+ mongo:7.0@sha256:9854f7139445d766a9523571d6f047530c45547460ffcf8259eb2bf4264632ca \
+ mongod --replSet keeperQA --bind_ip_all --port 27058
+keeper_mongo_ready=false
+for keeper_attempt in $(seq 1 30); do
+ if docker exec "$keeper_mongo_name" mongosh --port 27058 --quiet --eval \
+ 'try { rs.status(); } catch (e) { if (e.code !== 94) throw e; rs.initiate({_id:"keeperQA",members:[{_id:0,host:"127.0.0.1:27058"}]}); } quit(db.hello().isWritablePrimary ? 0 : 1)'; then
+ keeper_mongo_ready=true
+ break
+ fi
+ sleep 2
+done
+test "$keeper_mongo_ready" = true
+npm run test:automatic-backup-genuine 2>&1 | tee "$keeper_evidence_dir/genuine-matrix.log"
+KEEPER_APP_SOURCE="$keeper_app_dir" yarn --cwd "$keeper_relay_dir" test:automatic-http \
+ 2>&1 | tee "$keeper_evidence_dir/relay-http.log"
+npm run test:recovery 2>&1 | tee "$keeper_evidence_dir/recovery.log"
+npm test -- --runInBand 2>&1 | tee "$keeper_evidence_dir/jest.log"
+npm run test:release 2>&1 | tee "$keeper_evidence_dir/release-rules.log"
+npm run version:check 2>&1 | tee "$keeper_evidence_dir/version.log"
+git diff --check
+# Stop ONLY the disposable container created by this session when finished.
+docker stop "$keeper_mongo_name"
+```
+
+Retain failures and counts even if a command stops the sequence; run independent feasible checks separately afterward. Do not report unexecuted later commands as passing. A repository-wide TypeScript failure must retain its actual diagnostics/status; historical inherited diagnostics are not a passing typecheck. The same genuine source runner and prerequisite steps are defined in `.github/workflows/test.yml` and `scripts/run-automatic-backup-genuine.cjs`. Verify their Relay pin agrees with this document before running. Keep private logs locally and publish only redacted categories, counts, hashes and source/run identities.
+
+## Required operation and failure coverage
+
+Use the complete [matrix](../openspec/changes/fix-recovery-backup-freshness/automatic-write-validation.md). Record a result and evidence for every operation: `updateAppImage`, `migrateXfps`, `deleteAppImageEntity`, `deleteVaults`, `updateVaultImage`, `modifyLabels`, and `deleteBackup`. Their production producers, native Realm commits, real AES, Redux/store guards, HTTP handlers and Mongo transactions must be exercised together. A transport-only unit fixture is supplemental.
+
+| Case | Required result |
+| --- | --- |
+| C1 committed match | Local commit and original branded account/session/base/generation precede one intended v2 effect; ciphertext/IDs or deletion target match committed Realm. |
+| C2 uncommitted/stale state | Failed/partial/raw/unmanaged commit, stale local state, wrong key, copied origin/receipt or missing proof sends nothing; local data survives. |
+| C3 account session | A→B→A and closed/reopened Realm reject old work. Old A's aborted work leaves A pending and clears its stale baseline without changing B. |
+| C4 remote conflicts | Remote-only records and immutable wallet/signer/vault key or policy conflicts survive; no automatic overwrite or removal. Fingerprint correction cannot change unrelated keys, script, policy or network. |
+| C5 consent | No automatic write for an unconsented account. Explicit whole-backup opt-out is same-account and deliberate; a newer consent choice invalidates old deletion work. Consent changes only after acknowledged complete deletion. |
+| C6 competing writer | A real peer transaction/409 stops the chain; no fresh revision is borrowed for old ciphertext. |
+| C7 old/malformed protocol | 404, unavailable/partial references, wrong metadata, malformed JSON, false/missing `updated`/`preconditionApplied`, missing/invalid/unchanged `newRevision` stop with no legacy write fallback. |
+| C8 timeout/lost acknowledgement | Real post-commit timeout/lost reply remains uncertain/pending; no replay or next prepared member. Matching readback alone does not acknowledge the interrupted operation. |
+| C9 complete readback | Full decrypt/reference/metadata comparison at the same generation/session precedes verified. Wrong-key, incomplete or corrupted content cannot pass. A retained empty generation tombstone confirms deletion but never represents a verified backup. |
+| C10 final commit race/restart | Inject a genuine local mutation just before final Redux commit: no false verified. Relaunch preserves committed data/pending state and does not replay prepared work. |
+
+Include complete create/archive, multi-vault registration, label import/deletion and whole-upgrade producer batches. For each fanout, let the first real transaction commit and make the next fail, lose its reply or receive malformed acknowledgement; remaining prepared effects must not run. Verify genuine late-field rollback, local-first creation/edit/deletion without an original verified baseline, and final complete restore of BTC MAINNET/TESTNET wallets, existing USDT recovery metadata, keys, active/archived vaults, registrations, labels and nodes. New USDT/GasFree setup and transactional flows remain paused.
+
+## Native local services without changing the approved manifest
+
+Read [contributor setup](../dev/local-backend/README.md), [verification boundaries](../dev/local-backend/VERIFICATION.md) and the paired Relay README. Use unique Compose projects and only disposable data. The approved contributor bootstrap is useful for toolchain, onboarding and existing public services, but its `ee935359` Relay does not establish positive v2 automatic-write acceptance.
+
+From the isolated app checkout, prepare its approved stack and `.env.local` normally. These examples use free default ports; check all ports and choose unused contributor ports/settings as documented before starting anything. Keep the same settings for every invocation.
+
+```bash
+cd "$keeper_app_dir"
+export COMPOSE_PROJECT_NAME="keeper-r4-contributor-$$"
+./dev/local-backend/dev doctor
+./dev/local-backend/dev up
+./dev/local-backend/dev env
+./dev/local-backend/dev verify
+./dev/local-backend/dev stop
+# stop retains this project's named volumes. Never use down --volumes.
+./dev/local-backend/dev prepare-signing
+export SIGNING_SOURCE_DIR="$keeper_app_dir/dev/local-backend/.sources/signing"
+keeper_pair_project="keeper-r4-paired-$$"
+docker compose -p "$keeper_pair_project" \
+ -f "$keeper_relay_dir/compose.local.yaml" \
+ -f "$keeper_relay_dir/compose.local-with-signing.yaml" config --quiet
+docker compose -p "$keeper_pair_project" \
+ -f "$keeper_relay_dir/compose.local.yaml" \
+ -f "$keeper_relay_dir/compose.local-with-signing.yaml" up --build -d --wait
+curl --fail http://127.0.0.1:3000/health
+curl --fail http://127.0.0.1:3003/health
+```
+
+The signing overlay requires Compose **2.24.4+**. Record paired Relay source/container identities and effective local endpoints; this separate stack supports actual onboarding/channel/read/v2 routes, rather than only the runner's ephemeral HTTP handlers. Use the approved local SigningServer adapter for its existing testnet capability; this does not authorize new Assisted Multisig work. Ensure `.env.local` matches the paired gateway ports before building. Do not print its contents, copy hosted configuration, modify approved source locks/adapters or point this fixture at a hosted backend. Stop only this paired project with the same files/project name and `down` without `--volumes` after testing; retain its disposable volumes for diagnosis.
+
+## Required iOS and Android builds, launch and UI
+
+Build sequentially to limit memory pressure. Record available disk/RAM, Node/Yarn/Ruby/Bundler/Xcode/SDK/JDK versions, simulator/emulator identifiers and exact source SHA. Use fresh QA device state through normal simulator/emulator creation, not by erasing an existing owner device. Run Metro from this checkout with `yarn start` in a separate terminal.
+
+For iOS, select Ruby **3.3.0**, the root Gemfile and the actual available simulator UDID. Before building, inspect the shared `/tmp/envfile` selector without printing configuration: coordinate if it selects another build, and do not delete somebody else's selector. Use deployment CocoaPods installation; a lockfile/checksum mismatch is BLOCKED, not permission to rewrite locks.
+
+```bash
+cd "$keeper_app_dir"
+bundle install
+(cd ios && BUNDLE_GEMFILE="$keeper_app_dir/Gemfile" RCT_NEW_ARCH_ENABLED=1 bundle exec pod install --deployment)
+xcrun simctl list devices available
+keeper_ios_udid=YOUR_DISPOSABLE_SIMULATOR_UDID
+ENVFILE=.env.local xcodebuild -workspace ios/hexa_keeper.xcworkspace \
+ -scheme hexa_keeper_dev -configuration Debug -sdk iphonesimulator \
+ -destination "platform=iOS Simulator,id=$keeper_ios_udid" \
+ -derivedDataPath ios/build/r4-local -jobs 2 CODE_SIGNING_ALLOWED=NO build \
+ 2>&1 | tee "$keeper_evidence_dir/ios-build.log"
+xcrun simctl boot "$keeper_ios_udid" # Skip if already booted.
+xcrun simctl bootstatus "$keeper_ios_udid" -b
+xcrun simctl install "$keeper_ios_udid" ios/build/r4-local/Build/Products/Debug-iphonesimulator/hexa_keeper_dev.app
+xcrun simctl launch "$keeper_ios_udid" io.hexawallet.hexakeeper.dev
+```
+
+An unsigned compile is not functional entitlement evidence. The unsigned app may launch but Keychain can reject PIN storage with OSStatus -34018; a passcode screen alone does not establish onboarding or Realm persistence. Inspect the effective signed entitlements and actual PIN/Realm outcome. If signing or launch blocks this flow, record the exact action and error; use the contributor README's simulator-only Debug build with its normal local development signing if available without distribution credentials. A manually re-signed bundle may itself fail simulator launch policy. Record each artifact and which one actually launched. This is not production/release signing, and it does not turn an unsigned or nonfunctional launch into native acceptance.
+
+For Android, select a disposable emulator serial and its architecture. Use JDK **17**, SDK **36**, build tools **35.0.0**, NDK **27.1.12297006** and CMake **3.22.1** as required by this source. The development artifact uses the checked-in disposable debug certificate, not a production signing key.
+
+```bash
+cd "$keeper_app_dir"
+adb devices
+keeper_android_serial=YOUR_DISPOSABLE_EMULATOR_SERIAL
+keeper_android_arch=arm64-v8a # Use x86_64 for an x86_64 emulator.
+./dev/local-backend/dev android-forward --serial "$keeper_android_serial"
+ENVFILE=.env.local ./android/gradlew -p android app:assembleDevelopmentDebug \
+ -PreactNativeArchitectures="$keeper_android_arch" --max-workers=2 --no-daemon \
+ 2>&1 | tee "$keeper_evidence_dir/android-build.log"
+keeper_android_apk=android/app/build/outputs/apk/development/debug/app-development-debug.apk
+shasum -a 256 "$keeper_android_apk"
+adb -s "$keeper_android_serial" install -r "$keeper_android_apk"
+adb -s "$keeper_android_serial" shell am start -W \
+ -n io.hexawallet.keeper.development/io.hexawallet.keeper.MainActivityDefault
+```
+
+Verify actual app/package IDs, version/counters, APK signature/alignment and launched identities; do not guess them from filenames. The current provisional counters are 2.6.4 / Android 627 / iOS 620. Store-history refresh and signed production artifact reconciliation remain separate release work. The development Android package is `io.hexawallet.keeper.development`; verify website association files against the actual package/certificate, rather than assuming a `bitcoinkeeper.development` entry matches it.
+
+On **both** platforms, record each scenario separately:
+
+1. Fresh disposable onboarding, PIN create/unlock/cooldown, always-visible disabled Proceed/queued presentation and account setup. Cold launch/unlock without pressing a key must retain every keypad digit; disabled cooldown must reject input, retain all digits, expire normally and then accept input. Exercise PIN creation and another shared-keypad consumer without shortening cooldown in production code.
+2. Opt in per account, create/edit/delete wallets, signers and vaults locally, archive and register them, edit/import/delete labels, change nodes and version-related recovery state, then relaunch. Check actual local persistence, pending/verified presentation, failure-stage/retry copy and complete native clean Recovery Key restore into a **different disposable Realm**, through the production restore worker. Never restore over the owner's existing app/database. After a verified backup, terminate and cold-launch the disposable app with the next snapshot delayed or unavailable. Open backup status immediately: saved verification and interrupted phases must be unverified/pending before a fresh complete read establishes current proof. Consent and committed local records must survive; no prepared ciphertext may replay. Repeat after a failed partial fanout and A→B→A: a historical phase must not display Verified after its session proof expires. With disposable native storage, cover canonical nested opt-out versus stale root opt-in in both read orders, hold the canonical read and check intermediate states, distinguish confirmed absence from read error, and restore an older root BHR record without nested persistence metadata. Then change consent/pending state and cold-launch again to prove subsequent writes persist. Record native MMKV persistence and actual process restart separately from host Redux-persist rehydration and source-expression tests.
+ For the normal Manage Wallets Hide → Delete path, confirm an opted-in BTC wallet or vault Hide commits locally and receives its own revisioned mutation and complete readback before Delete is offered. While Hide is pending or its response is lost, the local hidden state remains, Delete stays unavailable and no stale deletion is sent. After verified Hide, PIN-confirmed Delete must remove the exact remote entity with another complete readback. Consent-off local deletion follows its separate no-write rule.
+3. Repeat C1–C10 through feasible real UI paths with the paired v2 service: interruptions/large payloads, 409/old route/malformed/lost reply, local mutation during verification, A→B→A, consent change during deletion, missing/orphaned/legacy encrypted references and multi-write partial success. Confirm server-only records and immutable identities survive. A successful Delete Backup retains local data, acknowledges empty readback, clears only the intended consent and never displays a verified backup.
+4. On iOS, import identical harmless bracketed/unbracketed TXT files and valid `[Test]_backup.bsms` / `Test_backup.bsms` from the same Files provider. Both BSMS files must reach identical configuration review; stop before duplicate creation. Test filenames with spaces/literal percent escapes and cancellation. Smoke Android's unchanged content-URI path on a native file picker.
+5. Fresh-install Testnet tutorial → Receive Test Sats → visible wallet balance **without restarting**, including retry/slow response and displayed-account ownership. Local mode intentionally lacks a faucet/AI provider: a 503 or mocked unit result is not positive end-to-end evidence. Use an independently approved disposable Testnet-provider QA configuration when available; otherwise record the scenario's actual BLOCKED/NOT RUN status and explicit owner follow-up, without waiving critical backup or required platform checks.
+6. Modal/navigation states for new wallet configuration, backup consent/check/failure, vault registration, file picker, QR readiness/retry and network/node switching. Verify disabled/proceed controls, error dismissal, keyboard/dismiss/reopen and account handover while delayed operations resolve. Simulator camera/USB/NFC limitations must be explicit.
+7. Wallet/Vault/Archived Wallet refresh, sequential label persistence, node failover/custom-node separation, deep-link cold/warm start, Ask Keeper retry/late response and existing USDT read-only balance/address/history/export. New USDT/GasFree setup, transfers and GasFree actions remain paused. Correct association hosting/certificates and available provider access are separate dependencies; record inaccessible cases rather than reporting UI-source tests as a provider pass.
+8. Follow [inheritance validation](r4-inheritance-validation.md): same public test seed with/without passphrase, actual primary/inheritance identities, six-month selection, exported descriptor and fixed absolute activation. Mainnet means 180 days; new Testnet fixtures use the documented accelerated delay. Activity/later deposits must not reset it. Keep affected-wallet assessment and any funded repair separate; unavailable preserved assessor source is still a blocker, not a guessed safety verdict.
+9. Profile realistic small/large encrypted backup checks, local-generation capture and UI interaction on both native runtimes. Record sizes/counts, wall time, responsiveness/cancellation, memory peaks and stall/deadline behavior. Do not truncate records or weaken size/timeout/identity guards to obtain a pass. Historical benchmarks and fast loopback HTTP tests are not native profiling acceptance.
+
+Do not sign or broadcast user transactions, touch funded MAINNET wallets, or use real recovery/private material. Physical phones, camera scanning, NFC/USB and hardware signer address/policy/PSBT round trips stay explicitly tracked for the owner's approved physical follow-up; simulator screenshots and fabricated device results cannot satisfy them.
+
+## Exact-head owner scope and Local report
+
+Read [AGENTS.md](../AGENTS.md), including merged [#7050](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7050). Keep `IOS, ANDROID, HARDWARE` in the final Cloud handoff. The release-owner account **antuz123**, with current write access, must record a **new** scope comment for the exact final SHA to defer unrun physical checks. A new commit invalidates both previous Local sign-off and the old deferral. Do not post as a different account or infer a fresh GitHub decision from the old b160 comment.
+
+```text
+## Codex local scope decision
+State: OWNER_DEFERRED_PHYSICAL
+PR: #7045
+Head commit:
+Deferred local checks: HARDWARE
+Reason: The release owner directs unrun physical phone, camera, NFC/USB and hardware-signer checks to post-release testing because those devices are unavailable for this Local run. IOS and ANDROID and known critical failures are not deferred.
+Post-release follow-up: The owner will test the installed released iOS/Android builds on physical phones and available signers, including QR, address verification, vault policy and PSBT round trips, and report exact build/device outcomes on #7045 or the release record.
+```
+
+This scope decision authorizes no release action and cannot turn a failed physical check into PASS. Run all feasible automated/native checks first. Unavailable noncritical scenarios may be recorded individually as `NOT RUN / POST-RELEASE` only with explicit reason and owner follow-up; neither that label nor the physical decision waives required IOS/ANDROID or a critical backup/key/funds/recipient/policy failure.
+
+After testing, post a new report preserving the earlier `LOCAL_FAILED` evidence:
+
+```text
+## Codex local validation
+State: LOCAL_PASSED | LOCAL_FAILED | BLOCKED
+Tested commit:
+iOS build/simulator: PASS/FAIL/NOT RUN — exact commands, installed artifact identity, actual launch and critical UI/recovery outcomes; private log locations.
+Android build/emulator: PASS/FAIL/NOT RUN — exact commands, package/version/counter, debug certificate/hash/alignment, actual launch and critical UI/recovery outcomes; private log locations.
+Real devices/signers: NOT RUN / OWNER-DEFERRED PHYSICAL only if the exact-SHA owner decision exists; name its URL and every deferred scenario. Otherwise report actual results or BLOCKED.
+Other checks: Exact app/Relay SHA; genuine native Realm/HTTP runner and per-operation C1-C10/producer/restore results; recovery/Jest/release/version/typecheck outcomes; hashes and redacted evidence.
+Open issues / next action: Every failed, blocked or NOT RUN scenario, reason and owner follow-up. State whether critical software, unsigned native launch/flows, store histories, independent reviews and hosted Relay rollout remain open.
+Release readiness: ready for review / NOT READY — LOCAL_PASSED does not authorize release, signing, deployment, upload or publication.
+```
+
+Use `LOCAL_PASSED` only after required iOS **and** Android checks actually pass and the physical requirement is either performed or covered by the accepted exact-SHA owner decision. Keep `Real devices/signers` beginning with `NOT RUN` or `DEFERRED` for deferred physical execution. If a critical scenario fails, retain `LOCAL_FAILED`; if a required prerequisite/check cannot run, use `BLOCKED`. Link the report and return the PR URL and actual state to the coordinator. Do not merge, deploy, sign a release, submit to stores or publish any artifact.
diff --git a/release/r4-backup-queue-admission.md b/release/r4-backup-queue-admission.md
new file mode 100644
index 0000000000..3815b55de5
--- /dev/null
+++ b/release/r4-backup-queue-admission.md
@@ -0,0 +1,170 @@
+# R4 backup inspection queue admission
+
+15 October 2026. **NEEDS_LOCAL / NOT RELEASE-READY**. PR
+[#7045](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045); the newest
+Codex local handoff names the actual final SHA. This document cannot contain
+its own eventual commit SHA.
+
+## Preserved evidence and narrow change
+
+The [17e0 investigation](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045#issuecomment-6183834923)
+preserves the original native rename failure, three diagnostic outcomes and
+separate required-behavior **0/1 RED** regression, with portable fixture code.
+Its app source is `17e0d9b9e3daf39359b762baa99b899f20b95f96`; the unchanged
+paired disposable Relay is `838049e537e07eb646a2a0393eb969fba43d0739`.
+The three diagnostic cases passed by establishing a successful completed rename,
+the inspection-overlap defect, and a missing-original-baseline uncertainty
+control. Those are not three backup acceptance passes.
+
+`inspectBackup` previously expired the verified baseline before joining the
+account queue. A later read-only inspection could therefore change the epoch
+of an earlier current writer while that writer awaited its snapshot, CAS or
+readback. Its original proof then failed closed, preserving local data and
+pending state. The fix moves that invalidation into **every admitted `runOnce`
+callback**, immediately after the captured-session stale return and before
+`inspectOnce`. A coalesced caller does not acquire another admission. A retry
+does acquire an admission and expires that admission's baseline, using the same
+deadline. Stale A→B→A work returns before touching the new session's baseline.
+
+No original intent is rebased. Session/consent, runtime brands, Realm identity,
+generation/fingerprint, original revision/CAS, single-use ciphertext and complete
+readback checks are unchanged. Hosted writes remain fenced. The source gate
+stays true for approved development loopback; the rollout gate stays false.
+
+This confirms a source ordering defect, **not the unique cause of the native
+17e0 failure**. The modal normally closes after its upload attempt settles.
+The reported Save→Home interval and later Status visit do not prove overlap;
+concurrent/background inspection timing or missing dispatch-time authority
+remains unestablished. Preserve the original local rename/unchanged remote
+revision/pending evidence and the measured14.170s host/guest clock offset.
+Later Local evidence at17e0 records one explicit **Back Up Now → conflict /
+Backup needs review**, with unchanged remote revision fingerprint
+`bfc41e774d5b0a53` (1wallet/2signers, no vaults/labels), and matching selected
+account/live Realm/store. This is a separate actual **FAIL**, not covered or
+resolved by the ordering fix. The conservative `replacementWouldDiscardRecovery`
+guard compares recovery content, including presentation changes; safe field-level
+differences are still being assessed read-only. No manual retry, override or
+change to that guard is authorized in this cycle.
+
+## Cloud proof and boundaries
+
+The focused genuine matrix is
+`tests/recovery/automaticInspectionQueue.integration.cjs`. It uses actual
+encrypted Realm and production transaction/schema/crypto/producer/inspection/
+store statements, with real HTTP to the paired transactional Relay. The
+Node22 full genuine runner discovers this matrix in addition to the seven
+existing matrices and requires a native Realm write/read prerequisite.
+
+Required coverage includes writer-first checks requested before admission and
+during original snapshot/CAS/readback; inspection-first later work and missing
+original authority staying local-preserved/pending; old-session queued
+inspection not erasing a fresh-session baseline; per-admission retry invalidation,
+shared deadline and coalescing. Controlled HTTP schedules and any host clock or
+public baseline-registration seams are disclosed in the tests. They do not
+constitute native navigation/dispatch/MMKV or simulator/emulator execution.
+
+The final PR handoff records exact commands, counts, skips and review results.
+Historical17e0 results remain SHA-scoped. No source fixture pass is an iOS or
+Android build/install/launch pass.
+
+The focused file passed **12/12, zero skipped** on Node22.23.3 with real
+Realm12.15.0 and paired Relay838049. The first focused run was11/12: its retry
+test's deliberate thrown snapshot callback re-entered the fixture response
+handler and produced an HTML error instead of the intended setup read. Only
+that test was corrected to hold a genuine HTTP reply until the actual client
+abort; the source patch did not change. The final retry case compresses transport
+abort timers to1000ms, delegates actual HTTP, and asserts the same unmodified
+inspection deadline across attempts. No host inspection clock is replaced.
+
+The stale-session/retry cases deliberately exercise the public baseline
+registration boundary. A real HTTP snapshot must strictly decrypt, match the
+full native Realm image and app metadata, with stable session/Realm handle/
+fingerprint, before recording it. This is not a claim that a nested queued
+native inspection can run while its own account queue is held. The stale-session
+test also uses the preserved fresh baseline for a real subsequent rename CAS.
+Independent read-only source/test review found no authority rebase or guard/gate
+change. The completed Cloud results for this implementation are:
+
+| Check | Actual outcome |
+| --- | --- |
+| `npm run test:automatic-backup-genuine`, Node22.23.3/native Realm12.15.0/paired Relay838049 | PASS275/275, zero skipped/cancelled;168791.623271ms; native write/read prerequisite passed |
+| New `automaticInspectionQueue.integration.cjs` alone | PASS12/12, zero skipped/cancelled;10982.202962ms |
+| Preserved required-behavior case, changing only its fixture import to this source | GREEN1/1, zero skipped; original17e0 RED0/1 remains preserved separately |
+| `npm run test:recovery` | PASS448/448, zero skipped;42324.276752ms |
+| `npm test -- --runInBand --coverage=false` | PASS42suites/432tests;46.243s |
+| Release rule components | PASS28Node +7Python +21Ruby/117assertions, zero failures/skips; Ruby3.3.8 ran offline in a read-only source container, not Fastlane actions |
+| `npm run version:check` | PASS2.6.4 / Android627 / iOS620; counters remain provisional |
+| `eslint src/services/backup/repair.ts`, diff and changed handoff links | PASS |
+| Whole-project TypeScript/ESLint | NOT RUN here; historical inherited failures are not new clean results |
+| New-head native build/install/launch, MMKV/Realm/UI, hardware | NOT RUN in Cloud; NEEDS_LOCAL |
+
+The tests used the exact minimal source patch with the unchanged dependency
+caches; the final commit adds the recorded evidence/handoff. The genuine runner
+used the pinned disposable Mongo7.0 image and source identities documented in
+the complete Local handoff. Ruby used
+`ruby@sha256:307aed56240959e9cd3fcc10740ae8d0e6c461e9b42efc076100d4f8126b87b9`
+with `--network none --read-only`, a read-only source mount and tmpfs/tmp.
+None of these checks signs, builds or publishes a production release. Final
+push/hosted-CI status and full source SHA are recorded in the fresh PR handoff.
+
+## Focused Codex Local continuation
+
+Read the newest exact-head PR handoff, [AGENTS.md](../AGENTS.md), this document
+and the preserved17e0 investigation before selecting a clean isolated checkout.
+Check the live head again. Preserve existing owner apps, QA accounts/databases,
+failed artifacts/logs and ongoing independent17e0 checks; do not reset or clean
+their worktrees or overwrite failed evidence.
+
+The only changed app module is `src/services/backup/repair.ts`. Native/build
+inputs remain byte-identical to17e0: `android/`, `ios/`, `package.json`,
+`yarn.lock`, `patches/`, JNA5.18.1/Portal pins and exclusions, build versions,
+tracked configuration code/templates and approved contributor manifest. Backup transport,
+automatic-write implementation/guards and both readiness constants are unchanged.
+Use existing matching dependencies, CocoaPods/Gradle/native caches for incremental
+builds; do not rewrite locks or reinstall unrelated inputs to obtain a pass.
+Actual new-artifact install and launch are still required.
+
+Required local checks remain **IOS, ANDROID, HARDWARE**. The focused retest is:
+
+1. Build from the actual new SHA: Android **developmentDebug only** and iOS
+ simulator **Debug**, using the established disposable loopback configuration
+ and paired Relay838049. Use the existing functional simulator development
+ signing if required for Keychain; no release signing or production artifact.
+ Ensure Metro or the packaged JS comes from this exact checkout. Record source,
+ package/bundle ID, version/counter, artifact SHA/certificate and launched device.
+2. Actually install/launch both artifacts. Preserve the17e0 strict16KB/normal4KB
+ and iOS compile evidence as historical, not new-head passes. On the disposable
+ strict16KB arm64 Android17/API37 AVD, confirm PAGE_SIZE16384 and the established
+ fatal/true properties; do not enable compatibility. Do targeted native
+ Portal initialization/MMKV/Realm/PIN/wallet smoke. Native inputs are unchanged;
+ do not repeat unrelated large static/provider/hardware matrices for this patch.
+ Verify the new artifact's identity and continued strict launch rather than
+ transferring the old artifact's result.
+3. In a separate disposable QA account/dataset on each platform, establish a
+ complete Verified backup, perform ordinary BTC Mobile Wallet rename, and
+ observe local persistence plus the intended revisioned write/readback. Open
+ AssistedBackupStatus for a fresh check; require the new name remotely and
+ Verified at the current local generation. Include one controlled overlapping
+ read-only check if the existing approved fixture/operator can schedule it,
+ recording the actual sequence. Do not add broad app instrumentation.
+4. Cold-launch/unlock and confirm the renamed local wallet and truthful pending/
+ fresh-verification behavior, without replaying old ciphertext. Keep the
+ original17e0 failed account/artifact/evidence intact. Missing baseline,
+ concurrent local change or another failure must remain pending rather than
+ borrowing a new baseline. Preserve the separate17e0 manual conflict; do not
+ press manual repair again or override it to hide a failed result. This patch
+ does not claim to fix that conflict.
+5. Post actual per-platform results for the new SHA, retaining all unresolved
+ R4/native/release categories separately. A known native failure is not waived
+ by Cloud proof. If another failure remains, preserve it and report; **do not
+ start another speculative source fix/rebuild loop** under this handoff.
+
+Keep Android C8/#7056 owner-parked and failed; this patch does not retest, resolve
+or waive it. Physical-only deferral still requires the owner's new exact-SHA
+scope decision; retain HARDWARE and actual NOT RUN boundaries. Existing source
+reviews, full native acceptance gaps, hosted backend fleet/index/transaction/
+old-writer rollout, current store/config/production artifact evidence and separate
+Desktop/website deliverables remain open. No merge, deployment/index mutation,
+release signing, production AAB/split construction, upload/publication, customer
+message, transaction broadcast or new real/paid provider call is authorized.
+R4 remains independent of Reproducibility and Bitkey Wallet.
diff --git a/release/r4-inheritance-validation.md b/release/r4-inheritance-validation.md
new file mode 100644
index 0000000000..284fb78858
--- /dev/null
+++ b/release/r4-inheritance-validation.md
@@ -0,0 +1,99 @@
+# R4 inheritance and affected timelock validation
+
+This checklist belongs to the R4 / 2.6.4 candidate in PR #7045. Read its latest Codex local handoff for the exact tested source SHA. Native and hardware acceptance remain open. The copy below is conditional on the documented acceptance and approved release; it does not authorize publishing or customer communication.
+
+## Row 249: existing decaying-passphrase setup
+
+The live tracker requires the same BIP39 words **with** a passphrase as the primary key and **without** a passphrase as the Inheritance Key in a 1-of-1 Miniscript wallet, with six-month activation. This is an existing inheritance-policy configuration, not a new passphrase-recovery engine.
+
+### What the source supports
+
+- `AddNewWallet.tsx` offers Single-key, then Enhanced Security Options → Inheritance Key. Enhanced option selection checks `usePlan().isOnL3Above`; the Inheritance Planning education entry checks `isOnL2Above`. In the current candidate **usePlan hardcodes L3**, as does useSubscriptionLevel, so both checks are presently true regardless of stored subscription. These source conditions do not establish actual store/product entitlement or require a purchase in this candidate. Observe the final build and confirm intended product availability before publishing customer steps; no entitlement logic was changed by this subtask.
+- The primary AddSigningDevice step routes to AddReserveKey when inheritance is selected. AddReserveKey supports one inheritance signer and offers 6, 12, 18, …, 60 months; the default is **12 months**, so the user must explicitly choose **6 months**.
+- `VaultMigrationController.tsx` computes one fixed activation lock: creation time + optional initial Wallet Timelock duration + selected inheritance delay. New wallets use a UNIX timestamp from `Date.now()`; re-vaulting an existing block-height policy preserves the block-height unit. Policy compilation uses `after(...)`, not a per-UTXO `older(...)` delay. Consensus timestamp maturity uses chain median time, so wall-clock presentation is not a guarantee of spend finality.
+- Mainnet MONTHS_6 means a fixed **180 days**, rather than six calendar months. Testnet's identically labelled option is accelerated to **60 minutes** for new timestamp wallets; the legacy height fixture is **6 blocks**. Testnet acceptance must inspect the actual descriptor and must not mistake its accelerated duration for mainnet behavior.
+- A 1-of-1 wallet has the primary key available before inheritance activation (unless a separate initial Wallet Timelock is deliberately enabled), and adds a distinct one-key Inheritance path at the fixed activation. The original primary path remains available afterward. For other quorum sizes, an Inheritance Key joins the quorum; generic copy must not promise that it alone spends every wallet.
+- `generateSeedWordsKey` and the software seed-key setup derive from words without a passphrase; there is no in-app passphrase field in that path. The passphrase-protected primary key must be derived/exported by a suitable external signer, with its fingerprint/xpub checked against the chosen passphrase. Keeper cannot infer that two xpubs came from the same words.
+- The source Miniscript allowlist includes MY_KEEPER, TAPSIGNER, SATOCHIP, BITBOX02, COLDCARD, JADE, KRUX, LEDGER, SPECTER, SEED_WORDS, KEEPER and POLICY_SERVER. This is a selection allowlist, not hardware/firmware proof. The fixture passphrase string `TREZOR` is a public BIP39 test value; it does not establish Trezor compatibility (TREZOR is absent from that allowlist).
+- Receiving funds, spending funds, generating more addresses, opening Keeper or entering a passphrase does **not** restart activation. Later deposits to the same wallet descriptor retain its existing fixed date. Resetting uses an explicit new wallet version and fund transfer, with network fees and signer availability; old addresses keep the old policy.
+- Wallet Settings → Wallet configuration file offers QR/file/PDF export; it contains the actual policy and is needed alongside the appropriate seed/passphrase recovery material. Wallet Settings has a separate Resetting Inheritance Key → re-vault flow. That flow must not be presented as an automatic inactivity reset.
+
+### Targeted source changes in this continuation
+
+AddReserveKey now uses a separate English/Spanish inheritance disclosure explaining the fixed activation, inclusion of any Wallet Timelock, non-resetting deposits/spends, and the need to re-vault and transfer funds to reset. The shared Emergency Key copy remains unchanged. The existing disposable policy test additionally checks that only the passphrase primary is available before activation, the seed-only path has threshold one after activation, and generating addresses/reading availability does not change the descriptor.
+
+An additional concrete UI finding: the Inheritance Planning CTA passes `params.isAddInheritanceKeyFromParams`, while AddNewWallet previously read `route.isAddInheritanceKeyFromParams`. The scoped fix reads it from the existing `route.params` binding. The regression executes the actual CTA navigation expression, actual route binding and actual React state initializer; it covers the entry, ordinary creation without params, and retained inheritance policy. The main Create Wallet path still requires explicit Enhanced Security selection. Record the final fix SHA and validate this alternative entry separately.
+
+### Cloud checks in this continuation
+
+- `npm test -- --runInBand tests/services/passphraseDecayPolicy.test.ts tests/services/inheritanceEntryRoute.test.ts tests/services/initialTimelock.test.ts tests/services/addReserveTimelockBoundary.test.ts tests/services/addSigningDeviceTimelock.test.ts tests/services/resetTimelockBoundary.test.ts tests/services/resetTimelockRoute.test.ts`: **7/7 suites, 118/118 tests passed**. After refining the route read through its existing destructuring, the two directly changed suites were rerun: **2/2 suites, 6/6 tests passed**.
+- Test-file Prettier, English/Spanish JSON parsing and disclosure-key presence, and `git diff --check`: **passed**.
+- Scoped screen ESLint: **fails with existing screen debt**. Before/after isolated source comparison: AddNewWallet 27→26 errors, unchanged 15 warnings; AddReserveKey unchanged 33 errors/2 warnings. Config ignores test files. No newly introduced screen lint diagnostic; the obsolete root-route property diagnostic disappears. Full JSON Prettier check also fails the existing localization formatting; no whole-file reformat was applied.
+- React best-practices review applied to the two narrow TSX edits: no new hooks, async work, components or subscriptions. Native accessibility/text-layout acceptance remains open for the longer disclosure.
+- No simulator/emulator, physical signer, fund transfer, customer wallet assessment, production action, customer reply or release was performed by this audit.
+
+### Exact UI steps to validate before customer use
+
+These steps are source-derived and remain **draft** until observed on the final iOS and Android builds with a supported signer/firmware:
+
+1. Use a disposable Testnet account and a signer capable of the generated Miniscript policy. Prepare the same public test seed with a test passphrase and with no passphrase as two distinct signer identities. Import/export the appropriate P2WSH/multisig xpubs and origins; record fingerprints. Do not use real recovery material in screenshots or logs.
+2. From Home's wallet area, open the add-wallet control → **Create Wallet** → **Single-key**. Open **Enhanced Security Options**, select **Inheritance Key**, leave **Emergency Key** and **Wallet Timelock** off for this specific setup, then **Save Changes** and **Proceed**. Record whether the final build allows selection; if an actual product gate appears, stop rather than bypassing it. Do not infer paid-plan requirements from the current candidate's hardcoded L3 helper.
+3. On key selection, choose the key derived with the passphrase as the sole primary key, then **Proceed**. Do not substitute Keeper's passphrase-free seed-key import for that primary.
+4. On **Add Inheritance Key**, add/select the key derived from the same words without the passphrase. Check that its fingerprint/xpub is distinct from the primary. Select **6 months** explicitly; confirm that the fixed-date disclosure is visible and readable, then **Confirm**.
+5. Name the wallet and use **Create Your Wallet**. Open its **Wallet Settings** → **Wallet configuration file** and save the disposable descriptor/config. Confirm the primary role is the passphrase key, the inheritance role is the no-passphrase key, and the policy has exactly the expected fixed fallback `after(...)` lock. Confirm no unintended initial primary timelock was introduced.
+6. Complete the signing/receive tests below before moving this wording out of draft. For a mainnet customer, include the 180-day duration, fixed-date limitation, supported firmware and recovery/config requirement; do not claim generic passphrase import or unrestricted signer support.
+
+### Local acceptance checklist (IOS, ANDROID, HARDWARE)
+
+Record the final full app SHA, app bundle/package/version/build, OS/device, signer model/firmware, and pass/fail/not run per row. Use disposable Testnet funds only.
+
+| Scenario | Expected evidence |
+| --- | --- |
+| UI and entitlement | Main Create Wallet path above works; English/Spanish disclosure wraps fully on a small screen and large font size; the 6-month choice is deliberate; disabled/unsupported signers explain the limitation. |
+| Inheritance Planning entry | “Create vault with Inheritance Key” reaches creation with inheritance preselected after the scoped route-param fix. Record final availability/product gating; the current helper hardcodes L3 and does not prove subscription enforcement. |
+| Two identities from the same seed | Passphrase and no-passphrase fingerprint/xpub differ; primary and inheritance roles match the imported origins. No stored field or heuristic is treated as proof of common seed words. |
+| Descriptor and receive addresses | Two receive addresses plus change branch share one fixed fallback lock. Mainnet read-only policy inspection shows 180 days; Testnet actual descriptor shows its accelerated duration. Export/reimport preserves exact policy and origins. |
+| Before activation | Supported hardware successfully signs the primary Testnet path. The no-passphrase key must not produce a currently spendable fallback before the descriptor lock matures. A signature or finalized future-dated PSBT alone is not maturity evidence; verify policy and chain finality in disposable fixtures. |
+| After activation | Once chain median time or height is beyond the descriptor's lock, the no-passphrase key alone signs/finalizes a disposable fallback transaction; original primary still works. Record the maturity source and lock value. |
+| No reset on use | Receive before and after activation; make a primary spend before activation; refresh/restart. Descriptor and fallback lock remain identical. A later deposit does not acquire a new six-month clock. |
+| Recovery | On a separate disposable install, restore from exported wallet configuration with the required signer/seed material. Verify addresses and lock unchanged. Do not overwrite an owner's installed app or wallet data. |
+| Re-vault limits | Do not initiate on a real wallet. If authorized for a disposable fixture, separately verify new policy/schedule, explicit transfer/fees, cancel/retry/restart and old-address continuity. Activation remains absolute; re-vaulting is a separate manual operation. |
+
+Pending validation: exact UI, native builds/launch, hardware signing and fallback maturity, restore, and final release availability. Source fixture checks alone do not establish these.
+
+### Conditional release and requester copy
+
+Use only after the final build passes relevant acceptance and is actually released through an owner-approved channel. Confirm precise signer/firmware steps from Local before sending. No message or social post is sent by this Cloud continuation.
+
+**Release note draft:** “Support for a decaying-passphrase inheritance setup: configure a 1-of-1 Miniscript wallet with the passphrase-protected key as primary and the same seed without its passphrase as the Inheritance Key. The six-month option is a fixed 180-day activation delay on mainnet; activity and later deposits do not restart it. Requires compatible signers and the wallet configuration for recovery.”
+
+**Social draft:** “A decaying-passphrase inheritance setup is supported in Keeper 2.6.4 with compatible Miniscript signers. Its activation is fixed when the wallet is created: sending, receiving or using the wallet does not restart the delay. See the validated setup and recovery instructions before funding.” Add an actual published documentation/release link only when one exists.
+
+**Requester reply draft:** “Your same-seed, with-passphrase / without-passphrase setup has been validated in Keeper 2.6.4 using [actual device/firmware and platforms]. Choose Single-key → Enhanced Security Options → Inheritance Key; use the with-passphrase key as primary, the no-passphrase key as Inheritance Key, and select 6 months. On mainnet this is a fixed 180-day delay from wallet creation, not a new six-month timer for each deposit or after activity. Keep the exported wallet configuration and your recovery material. To start a new delay you must explicitly re-vault and transfer funds, including the network fee. [Published release/instructions link].” Replace placeholders only with actual acceptance/release evidence; do not send before then.
+
+## Row 252: affected Wallet Timelock assessment
+
+The preserved artifact named by the live tracker is `outputs/r02-timelock-preserved-before-scope-trim-2026-10-02` (earlier pure read-only assessor plus 34 tests). It is **not present in this Cloud workspace or active candidate**. Preserve this missing dependency by name; do not silently replace it with a fresh detector that guesses prior intent. Existing `initialTimelock.test.ts` creates affected/intended disposable policies and compares them; it is not a stored-wallet assessor or repair implementation.
+
+Current source boundary:
+
+- `resolveInitialTimelock` rejects malformed or absent selection when TIMELOCKED is required. Current screen/controller tests cover route propagation and generated initial/fallback schedule. These guard future creation and re-vaulting; they do not repair already funded scripts.
+- VaultDetails' timelock presentation and VaultSettings' reset entry use retained `usedMiniscriptTypes.TIMELOCKED` and stored timelock arrays. They do not compare the actual compiled primary spending path with independent original-lock intent.
+- A retained TIMELOCKED marker with an unlocked primary path can signal a contradiction. When the intent marker is absent, an unlocked primary may be entirely legitimate; inference from inheritance/emergency locks alone cannot recover an original initial-lock duration.
+- Existing Resetting Wallet Timelock or Resetting Inheritance Key flows create a new policy/version and transfer funds. They do not rewrite an already funded Bitcoin output script. Their existence is not row 252 assessment acceptance.
+
+### Safe assessor port requirements, once preserved source is available
+
+1. Recover the preserved source/tests without overwriting any work, identify original provenance and exact commit/artifact hash, review its assumptions, and port it as a separate read-only deliverable.
+2. Accept only stored compiled primary-path evidence plus independent intent evidence (trusted original creation selection/config/owner-confirmed record). Inspect all supported primary spending alternatives and units; metadata alone is insufficient. Never serialize seed/private material or identifiable wallet data to shared logs.
+3. Report at least affected / no demonstrated contradiction / unknown with evidence and explicit unknown reason. Absence of evidence must remain unknown, rather than a guessed duration or safety verdict. A matching policy is “not affected by this omission,” not a general wallet-security assessment.
+4. Cover retained TIMELOCKED+unlocked primary, omitted metadata but independently attested intent, legitimate no-initial-lock inheritance, timestamp/height policies, contradictory descriptors vs phase metadata, malformed/unsupported policy, multiple primary paths, partial key/origin state and no independent intent. Reuse/extend the preserved 34 tests and record exact final results.
+5. Prove inspection leaves wallet, backup, server, UTXO and navigation state unchanged; no sign/sweep/registration/upload side effects. Keep any proposed repair separate and inactive.
+
+### Later funded-repair acceptance (explicit owner consent required)
+
+Any repair needs a new wallet script and signed migration/sweep. Before a funded operation, privately review original intent, corrected primary lock and inheritance/emergency schedule, signer/recovery readiness, exact amount/fee and destination; get explicit owner consent. Do not guess the original duration, auto-migrate, shorten fallback schedules or treat a reset button as consent to security-policy repair.
+
+Disposable repair acceptance must include fee display and consent, cancel without mutation, retry without duplicate sweep, restart/resume, partial/failed transfer, already-locked current wallet behavior, existing archived-wallet visibility/sync, old address receiving after migration, finding and recovering any remaining old-address UTXOs, configuration/recovery continuity and account isolation. Real-wallet repair is outside #7045 authorization.
+
+Remaining row 252 blockers: preserved assessor/source and tests unavailable; independent per-wallet initial-lock intent evidence; separate assessor implementation/review; native read-only acceptance; and any later explicitly consented repair design/validation. No user wallet is assessed or repaired by this audit.
diff --git a/release/r4-node-bootstrap-backup.md b/release/r4-node-bootstrap-backup.md
new file mode 100644
index 0000000000..6b3d43c20b
--- /dev/null
+++ b/release/r4-node-bootstrap-backup.md
@@ -0,0 +1,202 @@
+# R4 managed default-node backup producer
+
+15 October 2026. **NEEDS_LOCAL / NOT RELEASE-READY**. The newest
+[PR #7045](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045)
+**Codex local handoff** names the exact final SHA and actual check results.
+
+## Failure and preserved controls
+
+Local tested `9a19c6a2a4b4b71d6ffb0d6a5b9776f12a7dbf1d` with paired disposable
+Relay `838049e537e07eb646a2a0393eb969fba43d0739`. The strict16KB Android17/API37
+APK was `7331408887f5d755b439d0d350a49defbef3fdb6698c4bd1c6c89bb46b98acd0`.
+After explicit opt-in and complete Verified readback (one wallet, two signers,
+no nodes), simply opening Mobile Wallet details saved two canonical Testnet
+nodes. Local revision became1, queued stayed0; fresh Status said Needs Updating.
+Remote fingerprint stayed `d34ef089ca58d3f8`, with no nodes. All common recovery
+content and metadata matched; only two additive nodes differed. No injected
+fault or manual repair preceded this capture.
+
+A first manual Back Up Now safely added only nodes and verified at
+`64ab05c5d321d550`. A separate healthy-baseline ordinary rename then passed at
+`69bc52bb10af357c`: actual native decrypted full image/metadata matched Realm,
+with only `presentationData.name` changed. Cold PIN, MMKV, Realm and fresh
+Status also passed. These controls do not pass the original bootstrap order
+and are not results for the new source.
+
+The earlier17e0 rename failure and [queue-admission evidence](r4-backup-queue-admission.md)
+remain intact; its exact native cause was never uniquely proved. Its explicit
+renamed-wallet repair conflict is expected conservative preservation behavior:
+name differs, signers/metadata match, and additive nodes are not the discard
+trigger. This producer does not change that guard or add a manual override.
+
+## Actual caller and bounded change
+
+`HomeWallet` opens Mobile Wallet details with `autoRefresh:true`. Refresh reaches
+`connectToNodeWorker`; its initial/default and one-time fallback additions used
+bare Realm helpers. Observers correctly expired verification but did not upload.
+The unchanged9a19 actual-caller regression reproduced persisted defaults with
+**zero CAS writes**, where one acknowledged exact-set write was required:
+**RED0/1, zero skipped**. A prior Mongo-not-primary setup failure is separate.
+
+The new producer retains original account/session/Realm and branded authority
+before yielding, appends only missing node IDs in one managed transaction, then
+starts the existing `updateAppImageWorker(updateNodes:true)` with its genuine
+receipt. Dispatch stamps `CONNECT_TO_NODE`; direct callers propagate original
+authority, including its absence. The exact-set payload includes all persisted
+recoverable nodes, custom nodes and both networks. Existing IDs/fields survive;
+a completed fallback migration does not resurrect a later explicit deletion.
+No-op reconnects do not commit/upload. Missing/stale authority preserves local
+nodes and remains pending without acquiring a fresh baseline after persistence.
+
+The backup child is detached with `spawn`, retaining immutable receipt/origin;
+the existing helper contains backup failures and all proof/CAS/readback guards
+still apply. Electrum and its refresh/faucet/send callers do not wait for the
+Relay deadline. Real native Realm connection-flag writes are exercised around
+the background backup: `isConnected` is normalized out of recovery content.
+Observers never upload. There is no new ciphertext replay or authority refresh.
+
+`tests/recovery/automaticNodeBootstrap.integration.cjs` uses the production
+network module, origin middleware/store observers, encrypted native Realm,
+crypto and real HTTP/CAS/readback on clean Relay838049. Public Electrum
+connectivity is stubbed; provider/fee actions are not serviced. It does not
+render WalletDetails, exercise MMKV, or prove native UI/public-provider flows.
+The exact commands/results, initial failures, TypeScript comparison and
+independent safety review are recorded in the newest handoff.
+
+## Reproducible proof and actual boundaries
+
+The accepted RED ran before any app source edit with this exact command (the
+new integration file then contained only its first test):
+
+```bash
+KEEPER_RELAY_FIXTURE_MODULE=/workspace/dependencies/Relay-r4-16kb-fixture/tests/support/automaticBackupHttpFixture.cjs \
+ /workspace/dependencies/tools/node_modules/node/bin/node --test tests/recovery/automaticNodeBootstrap.integration.cjs
+```
+
+It failed `The actual network caller must enqueue its committed node image`,
+expected1/actual0, after actual defaults and migration flags were saved.
+Unchanged9a19 `src/store/sagas/network.ts` SHA256:
+`744c69af7633e8ac4333b535c76f50dc76e34e2eae4b469d7c85826c86e8700e`.
+Accepted RED log SHA256:
+`8cbeec9e557cc4f6e8343b91113ad929cf950060c844201e8c2993c165d301b7`.
+The committed first test plus optional network-slice fixture support provide
+portable source, rather than requiring a Cloud-local log path. To reproduce
+the failure, copy those two test files from this final commit into a separate
+9a19 checkout with the same prerequisites and run only the first named test;
+the later safety cases are for the fixed source. A filtered reproduction will
+report the other cases skipped; the original single-test RED had zero skips.
+
+The first focused GREEN ran19/19. The twentieth case separately passed1/1
+after correcting its setup to close the existing Realm before reopening the
+same account. The original attempt opened a second cached same-path wrapper,
+then encountered a closed-Realm setup error. That lifecycle boundary is
+preserved as an initial fixture failure, not fixed or claimed to be a Mac/app
+reproduction. An earlier cross-VM empty-object assertion was normalized to
+plain data before accepting RED; no production source was changed for it.
+
+The final native toolchain is Linux x64, Node22.23.3, Realm12.15.0; the actual
+`realm/prebuilds/node/realm.node` SHA256 is
+`f9873520422ba77488708a7ef760b189117782a9b13ae1f5c963a68041965934`.
+The runner requires and passes an actual native write/read before discovering
+the matrices. Mongo7.0 uses the pinned disposable image
+`mongo:7.0@sha256:9854f7139445d766a9523571d6f047530c45547460ffcf8259eb2bf4264632ca`,
+replica set `keeperQA`, loopback port27058; clean Relay838049 stays unchanged.
+
+```bash
+export REALM_DISABLE_ANALYTICS=1
+export KEEPER_RELAY_FIXTURE_MODULE=/path/to/clean/Relay/tests/support/automaticBackupHttpFixture.cjs
+export BACKUP_TEST_MONGO_URL=mongodb://127.0.0.1:27058
+npm run test:automatic-backup-genuine
+npm run test:recovery
+npm test -- --runInBand --coverage=false
+node --test scripts/release-version.test.cjs scripts/verify-channel-config.test.cjs
+python3 -B -m unittest discover -s scripts -p 'test_release_artifact.py'
+ruby scripts/test_fastlane_build_only.rb
+npm run version:check
+node_modules/.bin/eslint src/store/sagas/network.ts
+node_modules/.bin/tsc --noEmit --pretty false
+```
+
+Ruby3.3.8 ran offline with read-only source, tmpfs/tmp and image
+`ruby@sha256:307aed56240959e9cd3fcc10740ae8d0e6c461e9b42efc076100d4f8126b87b9`;
+these are rule tests, not actual Fastlane build/sign/upload actions.
+TypeScript **fails** with944 diagnostics on both unchanged9a19 and final source,
+with zero additions/removals after normalizing source locations and symlink
+dependency paths while retaining diagnostic code/message/path/multiplicity.
+Thus no new action/origin/producer typing diagnostic was added; this is not a
+clean whole-project typecheck. All-four-module ESLint still **fails** with
+12 inherited errors/17warnings in wallets/send; normalized findings add zero.
+The network module is clean (previously2errors/2warnings); store.ts is clean.
+Whole-project ESLint and native build/UI/MMKV/hardware are NOT RUN in Cloud.
+
+| Final Cloud check | Actual result |
+| --- | --- |
+| `npm run test:automatic-backup-genuine` | PASS295/295, zero failures/skips/cancellations;213482.007654ms; native prerequisite passed; new producer20 + prior275 |
+| Focused new fixture before full run | PASS19/19, then added Realm-handle case1/1 separately; all20 subsequently passed in the full runner |
+| `npm run test:recovery` | PASS448/448, zero skips/cancellations;53687.300236ms |
+| `npm test -- --runInBand --coverage=false` | PASS42suites/432tests;58.513s; focused connection Jest3/3 also passed |
+| Release rule components | PASS28Node +7Python +21Ruby/117assertions, zero failures/skips |
+| `npm run version:check` | PASS2.6.4 / Android627 / iOS620; counters remain provisional |
+| Network ESLint / diff / changed handoff links | PASS; broader inherited lint and TypeScript failures remain as disclosed above |
+| Independent read-only production/test safety review | No blocking findings; no reviewer edits or claimed independent native execution |
+| Current-head native install/launch/UI/MMKV/hardware | NOT RUN in Cloud; NEEDS_LOCAL |
+
+The final handoff records the full pushed SHA, hosted checks and actual Android
+diagnostic cancellation stage. Cloud test passes do not imply current-head
+hosted CI or native acceptance, backend rollout, signed-artifact identity or
+release approval. Prior17e0/9a19 native results remain separately SHA-scoped.
+
+## Exact-source Codex Local continuation
+
+Required local checks: **IOS, ANDROID, HARDWARE**. Read the newest exact-head
+handoff, [AGENTS.md](../AGENTS.md), this document and the
+[full R4 handoff](r4-automatic-backup-local-handoff.md). Recheck the live SHA.
+Preserve ongoing9a19 tests, owner apps/data and original failed artifacts;
+advance only a separate clean checkout after this stage closes. Use disposable
+Relay838049 without changing contributor pins or either readiness constant.
+
+1. Incrementally build new **Android developmentDebug** and **iOS simulator
+ Debug** artifacts from the exact new SHA, retaining matching native caches,
+ dependencies and locks. Actually install/launch; record source/JS checkout,
+ artifact hash, package/bundle, version/counter, device and backend. On strict
+ arm64 Android17/API37 confirm PAGE_SIZE16384 and established fatal/true
+ properties; do not enable compatibility mode. Old16KB/4KB/static/iOS results
+ remain scoped to their original artifacts and SHAs.
+2. On **each platform**, reproduce the original order with a fresh disposable
+ account: consentOFF, no persisted nodes; explicit opt-in to complete Verified
+ readback with one wallet/two signers/no nodes; then ordinary Wallets→Mobile
+ Wallet detail (`autoRefresh:true`) **before any editor/rename/Save**. Require
+ local canonical nodes and automatic current Verified with an acknowledged
+ next revision and complete image/metadata readback. Do not bridge this step
+ with manual Back Up Now.
+3. From that automatic healthy baseline, perform one harmless ordinary rename.
+ Require local persistence, acknowledged next revision, native decrypted full
+ image/metadata matching current Realm and only the intended name delta.
+ Fresh Status must be Verified. Reopen details/reconnect and confirm cache
+ flags do not enqueue another recovery write. Cold launch/PIN unlock; check
+ MMKV consent, nodes, renamed wallet and truthful proof without replay.
+4. Retain relevant PIN/keypad, Portal initialization, MMKV/encrypted Realm,
+ wallet/backup/recovery base smoke on both platforms. Preserve independently
+ incomplete R4 categories; do not repeat unrelated large native/provider
+ matrices solely for this TypeScript patch. Physical signer/camera/NFC/USB,
+ public-provider and real-device claims require actual execution separately.
+5. Post actual per-platform results for the exact SHA. If another failure
+ remains, preserve sequence/local/remote evidence and artifacts and report;
+ do not begin another speculative fix/rebuild loop under this handoff.
+
+Only app files `src/store/sagas/network.ts`, `wallets.ts`, `send_and_receive.ts`
+and `src/store/store.ts` change. Native/build inputs (`android/`, `ios/`), package
+and Yarn locks, patches, JNA/Portal pins, version counters, tracked configuration,
+contributor manifest, automatic transport/guards and readiness constants remain
+byte-identical to9a19. New native acceptance is still required. Old physical
+deferral does not transfer: only a new owner exact-SHA decision can defer unrun
+HARDWARE, never IOS/ANDROID or an observed failure.
+
+R4 remains blocked on current-head native acceptance, outstanding scope/review,
+owner-parked failed Android C8/#7056, separate backend source/fleet/index/
+transaction/old-writer proof and authorized rollout, fresh store/version/config
+inputs and the separately authorized production artifact stage, plus separate
+Desktop/website deliverables. Do not merge, deploy, create indexes, sign release
+builds, construct production AAB/splits, upload, submit, publish, call real/paid
+providers, message customers or broadcast transactions. Keep R4 independent of
+Reproducibility and Bitkey Wallet.
diff --git a/release/r4-protected-backup-app.md b/release/r4-protected-backup-app.md
new file mode 100644
index 0000000000..1f85adac75
--- /dev/null
+++ b/release/r4-protected-backup-app.md
@@ -0,0 +1,111 @@
+# R4 / 2.6.4 protected-backup app handoff
+
+State: **NEEDS_LOCAL; R4 remains BLOCKED.** Use the full app SHA in the newest **Codex local handoff** on [PR #7045](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045), verify it equals the live PR head, and preserve every earlier result under its original SHA. This document cannot name its own eventual commit. The current v3 instructions here supersede the historical public-v2 fixture commands in [the earlier handoff](r4-automatic-backup-local-handoff.md).
+
+## Owner-directed store-review availability
+
+`AUTOMATIC_BACKUP_HOSTED_AVAILABLE` and `PROTECTED_BACKUP_HOSTED_AVAILABLE` enable the intended protected-backup paths in the app. These are app availability controls, not evidence of deployed backend readiness. Per-account consent remains default off and restored off; original authority, session, local-generation, CAS and complete-readback checks still apply. Failed or uncertain server responses cannot report Verified or confirmed Delete.
+
+The owner authorized production artifact preparation/signing and App Store/Play review submission, with public release held. Actual backend readiness remains unverified, and production deployment is not authorized by this app change. The accepted `be89c34473bb6aab253b98325f1fe746ca391c6f` owner-reduced native subset and exact-SHA physical deferral remain evidence for that head only. New-source verification should cover this admission change and final artifacts, without reopening deferred native campaigns.
+
+## Superseded recovery request correction
+
+The03e proof did not cover a newer recovery discovery arriving during the old restore's record decryption in the **same account session**. Genuine protected and explicit-older schedules reproduced local account/consent changes. The corrected worker carries an identity-only request checkpoint through decode, post-derivation and every guarded Realm write, alongside the existing original/selected account-session checks. Each recovery Redux dispatch checks current request/session. Only GET_APP_IMAGE uses `takeLatest`; it cancels called wallet/signer/upgrade generators, and cancelled workers cannot emit retry cleanup. This does not change generic watchers, account authority or parked navigation behavior. Source RED/GREEN, fixture precondition failures and actual watcher/child cancellation evidence belong to the newest exact-head receipt.
+
+CodeQL's03e analysis completed but its separate security aggregate **failed** (one Critical SSRF/one High sanitizer alert) on synthetic merge784b915c27060afabc340248b459541a754fe5f4. The test-only proxy now chooses three literal loopback URLs without constructing a destination from request input; genuine raw-target rejection tests verify it. Independent review supports a false-positive classification for the unchanged ASM warning: text remains local and only its numeric element count reaches fee sizing, with no HTML sink. No alert was dismissed. A new source scan and its actual result stay separate from this classification.
+
+## Scope and identity
+
+Production entry points are the protected authority/transport, existing automatic-write producer/queue and repair/status paths, confirmed Delete worker, and typed Recovery Key discovery/restore. Authority is derived separately from the Recovery Key with the supported signing profile; it does not turn legacy decryption or an old account identifier into proof of ownership. Existing Keeper app identity, wallet/key derivation, encrypted payload format, provider/billing identity and local-first recovery records stay separate. Missing/stale account, session, consent, committed-generation, original-base, fingerprint, CAS or final-readback proof remains fail-closed.
+
+Hosted app availability is enabled; backend readiness remains **unverified**. Read-only status never enrolls or enables automatic backup. Delete removes **only the new protected copy**, preserves local wallets/Recovery Key and records its confirmed tombstone. Older encrypted copies may remain read-only. A lost/malformed/uncertain Delete reply is not success; preserve local data and check status rather than retrying uncertain ciphertext. Turning off automatic backup keeps copies. Re-enrollment after Delete is an explicit new-copy action, with no automatic legacy fallback.
+
+Recovery checks the protected namespace first. Absent, empty, deleted and read/auth/network errors are distinct typed results; errors do not select legacy recovery. Only the deliberate **Recover an older copy** choice permits that read. Complete validation precedes recovery success, whose provenance must match the selected source and current account. Partial/unavailable recovery is not full success. Restore leaves automatic-backup consent **off**; enabling the protected copy is a separate explicit action. EN and reachable ES disclose the retained-copy scope.
+
+## Dependency and source preservation
+
+Exactly five direct JS dependencies were added: `@exodus/bytes@1.16.0`, `@scure/bip32@2.4.0`, `@scure/bip39@2.4.0`, `@noble/curves@2.4.0`, and `@noble/hashes@2.4.0`. Yarn adds six selectors, including nested `@scure/base@2.4.0`; all 2,274 original selectors and old direct pins are unchanged. Existing QR resolution remains `@scure/base@1.1.9`; existing wallet crypto remains independent. The JS entry adds only the encoding initializer, which installs TextEncoder only when absent. The Android input receipt changes only its matching yarn-lock hash.
+
+Android/iOS inputs, patches, native dependencies, JNA/Portal, Metro/Babel/shim, fixed configuration and the approved contributor `dev/local-backend/sources.lock.json` remain unchanged from `4927ad549dd1d610d9eb84c6d9a37ed0a6f33a29`. This is source preservation, not transfer of old native acceptance to the new SHA.
+
+## Cloud and disposable checks
+
+Use Node **22.23.3** or a later supported 22.x patch and frozen Yarn Classic **1.22.22** dependencies. Keep the separate private backend checkout at **`7693ce4bfffcadb5fb71d6478a8befc8e533a844`**, clean and obtained with authorized private read access. The opt-in runner checks that commit, fixed nonsecret input hashes, Mongoose 5.13.20/driver 3.7.4, genuine encrypted native Realm commit/reopen, and a credential-free disposable loopback replica at port **27038**. Never point it at hosted services or import/start the full backend/provider service graph.
+
+```sh
+KEEPER_PROTECTED_RELAY_CHECKOUT=/absolute/path/to/reviewed-private-backend \
+BACKUP_TEST_MONGO_URL=mongodb://127.0.0.1:27038 \
+yarn test:protected-backup-genuine
+node --test tests/recovery/protected-authority.test.mjs
+node tests/recovery/protected-authority.metro.cjs
+node --test tests/recovery/protectedRecoverySource.test.cjs tests/recovery/recoveryErrorFeedback.test.cjs scripts/run-protected-backup-genuine.test.cjs
+```
+
+The private genuine lane exercises actual production saga/store/crypto, encrypted Realm and transactional backend HTTP/readback. It is separate from the public Relay **`838049e537e07eb646a2a0393eb969fba43d0739`** v2 lane. Public/fork CI cannot obtain the private fixture automatically; public838 results do not validate this v3 protocol. Do not replace contributor pins, vendor private backend source into the app, or skip the private proof and report success.
+
+The signer command runs actual installed production crypto/vector/interoperability checks. The focused Metro command resolves mobile/default encoding and authority sources, executes its bundle in Node V8 and compiles Hermes bytecode; it does **not** execute Hermes or the full native App. The unit command is a narrow recovery/guard lane, not the entire acceptance matrix. Missing native bindings, skipped genuine proof and substituted algorithm mocks remain failures or blockers.
+
+Source-bound construction results retained before the final commit: signer13/13, focused corrected genuine5/5, Jest42 suites/432 tests, release Node28/Python7/Ruby21 (117 assertions), all with zero skips. The newest PR receipt records the final frozen38 genuine cases and whole480 recovery outcome separately. Existing diagnostic failures are retained: initial Jest430/432, recovery473/480; later recovery478/480 (two missing AST bindings, both affected files subsequently36/36). A genuine vault-map alteration was RED0/1 then GREEN1/1 after complete projection validation; a genuine new-vault producer was RED0/1 then GREEN in the focused5/5 after including its scheme.
+
+Expanded runtime lint has13 errors/2 warnings both at the4927 baseline and current source, with zero added/removed normalized findings; UI comparison36/21 versus38/21 adds none. Whole-project TypeScript remains failing with944 diagnostics on each tree. Seven raw TS2339 message renderings differ only in abbreviated inferred locale types; the same missing properties remain. Normalization adds/removes zero diagnostics. This is baseline comparison, not a clean typecheck or lint pass. New source support, advisory and Metro receipts are in `tests/recovery/protected-authority-evidence.json`; the independent engineering review is not professional crypto certification.
+
+The final exact-head comment supplies all commands, case classifications, source hashes, stable-input manifests, compressed log retrieval and actual final outcomes. Native IOS/ANDROID/HARDWARE, Hermes runtime and full-app startup are NOT RUN in Cloud.
+
+Do not convert earlier source-bound or native results into final-head passes. The newest PR comment must record exact commands, full app/backend identities, actual counts/failures/skips and log hashes.
+
+## Codex Local: bounded current-source acceptance
+
+Required local checks: **IOS, ANDROID, HARDWARE**. Keep the owner's [minimal native batch](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045#issuecomment-6185462332) and all remaining R4 gates. C8/[#7056](https://github.com/KeeperCommunity/bitcoin-keeper/issues/7056) and navigation work remain parked; no new fix/rebuild loop is authorized by this document. Old strict16KB/4KB/iOS results stay SHA-scoped. Only a fresh exact-SHA owner decision can defer eligible unrun physical checks; required platform failures cannot be waived.
+
+### Disposable native transport preparation
+
+The public contributor stack does not supply v3. Obtain the exact private backend separately and retain the approved public source manifest. In the app checkout use the same environment as the genuine runner, with a task-owned credential-free `keeperQA` replica on loopback27038 and frozen dependencies/native Realm. Run this **proposed, not native-executed in Cloud** long-lived command from the final app checkout:
+
+```sh
+KEEPER_PROTECTED_RELAY_CHECKOUT=/absolute/path/to/reviewed-private-backend \
+BACKUP_TEST_MONGO_URL=mongodb://127.0.0.1:27038 \
+node <<'NODE'
+const assert = require('node:assert/strict');
+const { checkedBackend, supportedNode, disposableMongoUrl } = require('./scripts/run-protected-backup-genuine.cjs');
+assert.ok(supportedNode(process.versions.node));
+checkedBackend(process.env.KEEPER_PROTECTED_RELAY_CHECKOUT);
+process.env.BACKUP_TEST_MONGO_URL = disposableMongoUrl(process.env.BACKUP_TEST_MONGO_URL);
+(async () => {
+ const { createProtectedServer } = require('./tests/recovery/protectedWriteRealmRelay.fixture.cjs');
+ const fixture = await createProtectedServer();
+ console.log(JSON.stringify({ relay: fixture.url, audience: fixture.audience,
+ database: fixture.backend.database, backend: '7693ce4bfffcadb5fb71d6478a8befc8e533a844' }));
+ let closing = false;
+ const close = async () => {
+ if (closing) return;
+ closing = true;
+ await fixture.close();
+ };
+ process.once('SIGINT', () => { close().catch(() => { process.exitCode = 1; }); });
+ process.once('SIGTERM', () => { close().catch(() => { process.exitCode = 1; }); });
+})().catch(() => { console.error('Disposable protected fixture startup failed'); process.exitCode = 1; });
+NODE
+```
+
+This uses actual private v3 router/services plus the two exact legacy read declarations, inert provider traps and a distinct disposable database. No full backend/bootstrap/config/credentials are loaded. It binds an ephemeral loopback port; do not run the full matrix concurrently against its single-process fixture. The fixture close operation drops **only its owned disposable database**; keep a diagnosed failure process/database alive until evidence is retained. Container volumes and all existing databases remain protected. Nothing here authorizes a hosted call.
+
+In a separate **uncommitted local QA environment file**, set `ENVIRONMENT=DEVELOPMENT` and `RELAY` to the printed exact `http://127.0.0.1:/` including trailing slash. Keep the existing reviewed local channel/SigningServer/test-only values; never print/copy hosted configuration. `src/utils/service-utilities/config.ts` consumes this field. The explicit-port development loopback exception remains available for disposable verification independently of hosted app availability. Other protected targets require HTTPS. For Android use `adb -s reverse tcp: tcp:`; iOS simulator uses host loopback. Record the exact QA env-file hash/path and actual ENVFILE/native configuration selection, without exporting values.
+
+**Boundary:** this fixture serves backups, not onboarding/channel/provider APIs. The app has one RELAY origin and no per-v3 override. Prepare a disposable consent-OFF account through the already reviewed local onboarding stack, then switch that QA configuration to this backup-only server for the exact-source native build/test; preserve the account's original identity and local records. It cannot establish full fresh onboarding against a composed v3 service. If an end-to-end onboarding gateway is needed, a fixed reviewed local-only forwarding composition remains required: do not silently invent it, start a private full service/provider graph, or claim this standalone launcher implements it. Clean protected restore is exercised from the app's recovery path, with real native success still to be established. Explicit older-copy native recovery additionally requires deliberately seeded disposable legacy ciphertext; do not point at retained customer copies. The actual encrypted fixture seeds/readback and failure injection are in `protectedWriteRealmRelay.proof.cjs` and `.fixture.cjs`; native hooks do not inherit those Node proof passes.
+
+Build, install and launch the actual current development artifact on both platforms, then preserve artifact hashes and test:
+
+- Fresh explicit opt-in → complete protected Verified; ordinary wallet-detail default-node bootstrap → automatic complete Verified → ordinary rename → full decrypted image/metadata readback. Test the original order, including a fresh account, rather than repairing the baseline first.
+- Consent off/status without enrollment, current-account/session isolation, complete protected restore and deliberate older-copy restore; no legacy fallback on tombstone, empty/absent protected data, or errors. Available records must be complete before success; restore must keep consent off.
+- Scoped Delete confirmed versus uncertain result, cold tombstone discovery and explicit recreate; older-copy warning/provenance and EN/ES enable/disable/status/recovery notices. Preserve local recovery data throughout.
+- Cold PIN/MMKV/encrypted Realm persistence, relevant wallet/base smoke and Portal behavior. Android must actually launch with strict 16KB settings and exercise real Hermes/crypto initialization; retain normal4KB and iOS acceptance separately as requested in the minimal batch.
+
+Record unrun hardware interactions as NOT RUN, with the actual exact-SHA owner scope decision if applicable. Report any new failure without speculating that an earlier fix uniquely explains it.
+
+## Storage and authorization boundaries
+
+The latest supplied Mac report is **16 October 15:30:40 UTC**, **50.9437 GiB free**. The proposed Stage B estimate is **47 GiB**, leaving arithmetic margin **3.9437 GiB**; this is a dated report, not current capacity or a fit decision. The storage helper still exited **2**: embedded-worktree fingerprint/source bindings and a non-null fit assessment remain required. Preserve all protected source/evidence/caches/devices/wallets/volumes. No cleanup was authorized.
+
+Before any heavy checkout/install/fixture/native resumption and at closeout, follow available `AGENTS.override.md`, `keeper-local-memory.md` and `dev-environment/release-runbook.md`; run `python3 dev-environment/release-storage.py assess --context ` with the fresh complete remaining-peak/retry budget. Receipts expire after 30 minutes. Resolve the capacity/fit/source-binding gaps before heavy work; no timer/background cleanup.
+
+Backend promotion/deployment/index/transaction/CAS/writer and ingress/protection evidence, exact-head local acceptance, store/channel/version/artifact approvals and physical follow-up remain separate open gates. The owner separately authorized Local production build/signing and store review submission, with public release held. This source change does not authorize merge, production deployment/index/data/admin write, public release/APK publication, provider calls or real transactions. Keep R4 independent of Reproducibility and Bitkey Wallet.
diff --git a/release/version.json b/release/version.json
new file mode 100644
index 0000000000..2ee660a4d4
--- /dev/null
+++ b/release/version.json
@@ -0,0 +1,21 @@
+{
+ "version": "2.6.4",
+ "androidVersionCode": 627,
+ "iosBuildNumber": 620,
+ "baselines": {
+ "android": {
+ "applicationId": "io.hexawallet.bitcoinkeeper",
+ "verifiedAt": "2026-10-21T08:57:54Z",
+ "highestUploadedBuild": 626,
+ "highestMarketingVersion": "2.6.3",
+ "productionRelease": "626 (2.6.3)"
+ },
+ "ios": {
+ "applicationId": "io.hexawallet.keeper",
+ "verifiedAt": "2026-10-21T08:26:48Z",
+ "highestUploadedBuild": 619,
+ "highestMarketingVersion": "2.6.3",
+ "productionRelease": "619 (2.6.3)"
+ }
+ }
+}
diff --git a/reproducibility/README.md b/reproducibility/README.md
new file mode 100644
index 0000000000..e40baa5341
--- /dev/null
+++ b/reproducibility/README.md
@@ -0,0 +1,181 @@
+# Android reproducibility status
+
+This directory records the inputs needed to compare a Bitcoin Keeper Android
+release with a build from its public source. The comparison tool in
+[`scripts/compare-android-apks.py`](../scripts/compare-android-apks.py) is an
+inspection aid. It is **not** a WalletScrutiny build script, and this repository
+does not yet establish a reproducibility verdict for v2.6.3.
+
+The [Android diagnostic build workflow](../.github/workflows/android-diagnostic-build.yml)
+is set up to compile an APK and AAB from the combined draft with the live public
+channel URL and `ENVIRONMENT=PRODUCTION`, dummy service endpoints and IDs, and
+the checked-in debug key. It verifies the exact PR source and pinned Android
+inputs before Gradle, and checks that Gradle rejects a retired GasFree
+credential. A successful run verifies that the draft compiles in a clean CI
+checkout; its outputs cannot be compared to a production release for a
+reproducibility verdict. After validation, the workflow keeps only the debug
+APK and its source/hash provenance as a seven-day CI artifact for package
+inspection. Placeholder Relay settings block fresh account setup, so this
+artifact alone does not enable native pairing smoke. Pairing QA needs a
+separately reviewed disposable configuration or seeded account. The CI artifact
+is not a signed production release.
+
+## v2.6.3 reference and measured result
+
+The public source tag is [`v2.6.3`](https://github.com/KeeperCommunity/bitcoin-keeper/releases/tag/v2.6.3),
+commit `872cbc4b16ddcb0a8f3b5b1d7ebcde28e06ed096`. The GitHub release APK
+`Bitcoin_Keeper_v2.6.3.apk` has SHA-256
+`a20d934ebd80ece779d3c171c7906bb4aff010337989ec1b826cab55c50eba46`.
+Its package is `io.hexawallet.bitcoinkeeper`, version `2.6.3`, version code
+`626`.
+
+An isolated build of that tag with a placeholder production configuration and
+the checked-in debug signing key produced a valid 2.6.3 APK. Its SHA-256 was
+`cc4102251a11cbbfa104808adc4906a3a0e3b2efd9a14ab0785d66f5c9d5143b`.
+Comparing uncompressed APK entries found **1,424 matching payload entries and
+192 differences**: one manifest, one baseline profile, one Hermes bundle, five
+DEX files, 56 native libraries, and 128 resources. The placeholder
+configuration and different build environment can affect these files. This is
+a diagnostic mismatch, not evidence that the published binary was built from
+different source. The measured result and remaining work are tracked in
+[#6097](https://github.com/KeeperCommunity/bitcoin-keeper/issues/6097).
+
+For an SDK 33, arm64-v8a, xxhdpi, English-only profile, the four official
+Play-generated APKs were also retrieved and verified. All 42 corresponding
+code entries (six DEX files, Hermes, and 35 arm64 libraries) match the GitHub
+release APK byte for byte. This establishes published-channel code parity for
+that profile, not a rebuild from public source. A rebuilt AAB and split-set
+comparison are still needed.
+
+| Play split | SHA-256 |
+| --- | --- |
+| SDK 29+ base | `e384b966359aa4937bf4353316ddda471adf1e17f6bb08fe53f9945e8ea9bc1d` |
+| arm64-v8a | `11740257e813455501301d5dc0f9870dc476e15947d912523e051d9a3400ab8c` |
+| xxhdpi | `da3b93b89e98cff52bbea6c593fc26193139d53f400139ebd44ac51118f08195` |
+| English | `a5cae92f6e9c2d725bcf8fc3ebcfb397573fda38e1413dde7e40c395430f0a73` |
+
+## Compare two APKs
+
+Run with Python 3 and no extra packages:
+
+```sh
+python3 scripts/compare-android-apks.py published.apk rebuilt.apk > comparison.json
+```
+
+Exit code 0 means all **uncompressed ZIP file entries** match after the narrow
+signing exceptions below. Exit code 1 means at least one payload difference;
+exit code 2 means invalid input. JSON includes whole-APK SHA-256 hashes, entry
+counts, and every changed, added, or removed file path. ZIP directory records,
+compression, entry order, and APK v2/v3 signing blocks are outside this payload
+comparison. The tool assumes its inputs are APKs; verify their signatures,
+package names, and versions separately.
+
+The only exempt entries are root-level JAR/v1 signature material
+(`META-INF/MANIFEST.MF`, `META-INF/*.SF`, `*.RSA`, `*.DSA`, `*.EC`) and Play's
+root `stamp-cert-sha256`. Their differences still appear in
+`ignored_signing_entries`. DEX, Hermes, native libraries, manifests, resource
+tables and files, baseline profiles, other assets, and other `META-INF` files
+remain comparison-critical. A payload match does not authenticate either
+signer or prove that the APK came from the claimed source.
+
+Synthetic tests cover signing exceptions, each payload category, added and
+removed files, duplicate ZIP paths, and CLI exit codes:
+
+```sh
+python3 -m unittest scripts/test_compare_android_apks.py
+```
+
+Compare one APK with one APK. Google Play delivers APKs generated from an AAB;
+a Play base split cannot be equated with a standalone GitHub APK. Play
+verification needs the complete delivered split set and corresponding splits
+from a rebuilt AAB, with transformations examined separately.
+
+## Inputs needed for an independent build
+
+The tagged production lane requires an ignored `.env.production`. Its exact
+v2.6.3 contents are not public. Names-only inspection of the published APK
+found 13 environment-derived fields in `BuildConfig`. `react-native-config`
+embeds supplied environment values in Android build outputs, including fields
+outside the app's TypeScript configuration object. Placeholder values cannot
+support an exact payload verdict. Some fields appear credential-bearing and
+require owner security review before public build inputs are released; do not
+commit an unchecked production environment file.
+
+The source pins Gradle wrapper 8.14.3, Android Gradle Plugin 8.8.0, Android
+SDK/target 36, Build Tools 35.0.0, NDK 27.1.12297006, and React Native
+0.83.9. The locked Realm dependency requests CMake 3.22.1. The dependency
+tree is recorded in `yarn.lock` and checked-in `patch-package` patches. The
+successful diagnostic used Node
+22.23.3, Yarn 1.22.22, and JDK 17.0.19; these are measured diagnostic inputs,
+not a claim about the publisher's complete toolchain. A third-party recipe
+still needs a digest-pinned Linux container image, exact JDK/Node/Yarn and SDK
+package checksums, a fixed checkout and dependency layout, and verified build
+commands. The Gradle wrapper now has a distribution checksum pin, but the
+Android project has no dependency lock or verification metadata. The published
+Hermes bundle contains a Node 25.9.0
+literal injected by `rn-nodeify` and a path through a sibling
+`keeper-release-2.5.15/node_modules` directory. These historical build inputs
+must be investigated; copying them into a future release recipe would not by
+itself reproduce v2.6.3. Realm and Screens also have native executable/data
+differences in the placeholder rebuild.
+
+For the Android-only path, the diagnostic installed JavaScript packages with
+`yarn install --frozen-lockfile --ignore-scripts`, then ran the checked-in
+`patch-package` patches and the Android `rn-nodeify` step before invoking
+`./gradlew :app:assembleProductionRelease`. The root `setup.sh` cannot serve
+as a Linux build recipe unchanged: it runs iOS CocoaPods and writes a macOS SDK
+path. A future container recipe needs a Linux `local.properties`, the verified
+production environment input, and a disposable signing identity. It should
+also run `:app:bundleProductionRelease` for Play split comparisons. These
+commands describe the diagnostic path; they are not a complete reproducible
+build recipe.
+
+The release Fastlane lane validates time-sensitive store baselines and uploads
+an AAB to Play. An independent verifier should build locally without store
+access or upload. It can use a disposable signing key and compare payloads
+while explicitly accounting for signing differences. A complete recipe must
+then build the production APK and AAB under pinned tools and compare the
+actual distributed artifacts.
+
+[WalletScrutiny's script rules](https://github.com/WalletScrutiny/WalletScrutinyCom/blob/master/docs/script_verifications.md)
+require Docker, Podman, or Nix; a script ending in `build.sh`; a `--binary`
+argument; and an adjacent `COMPARISON_RESULTS.yaml`. No such script or results
+file is included here because the exact production input and complete
+third-party build path have not yet been established.
+
+## Fail closed on future build inputs
+
+`android-inputs.json` pins the Node, Yarn, JDK, Gradle wrapper, lockfile, and
+Android SDK package versions chosen for the next independent build attempt.
+These are **chosen future inputs**, not a reconstruction of the v2.6.3
+publisher's environment. Before any production build, run:
+
+```sh
+python3 reproducibility/verify-android-inputs.py \
+ --source-commit \
+ --env-file /path/to/reviewed/.env.production \
+ --android-sdk-root /path/to/android-sdk
+```
+
+The tracked manifest contains seven source-audited environment names and no
+values. This is a **provisional future-release allowlist**: the GasFree pause
+is included in [combined draft PR #7035](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7035),
+and integration checks for four candidate omissions must be reviewed before
+using it for a release. Changing the list requires a tracked source change.
+The checker rejects
+missing or extra names, a dirty or wrong source checkout, changed dependency
+hashes, mismatched tool versions, missing SDK packages, a symlinked
+`node_modules` root, and links from dependencies to files outside the checkout.
+It does not output environment values. A local dependency install is necessary;
+linking to a sibling `node_modules` directory recreates an observed historical
+build-path dependency and fails this check.
+
+This check does not yet pin the container image, Android command-line tools
+download, Maven artifacts, or every transitive native input. It does not run
+the build or compare a binary and is not a WalletScrutiny `build.sh`. The exact
+production environment names and values still need release-owner review before
+any public recipe or verdict. Run its focused tests with:
+
+```sh
+python3 -m unittest reproducibility/test_verify_android_inputs.py
+```
diff --git a/reproducibility/android-inputs.json b/reproducibility/android-inputs.json
new file mode 100644
index 0000000000..b806f15ca5
--- /dev/null
+++ b/reproducibility/android-inputs.json
@@ -0,0 +1,27 @@
+{
+ "node": "22.23.3",
+ "yarn": "1.22.22",
+ "java": "17.0.19",
+ "yarn_lock_sha256": "a915c8ea0c4446270c0f6c894998f0c4fa481bcc4edbea328e57377613939056",
+ "gradle_wrapper_jar_sha256": "0336f591bc0ec9aa0c9988929b93ecc916b3c1d52aed202c7381db144aa0ef15",
+ "gradle_distribution_sha256": "bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531",
+ "android_packages": {
+ "build-tools/35.0.0": "35.0.0",
+ "ndk/27.0.12077973": "27.0.12077973",
+ "ndk/27.1.12297006": "27.1.12297006",
+ "cmake/3.22.1": "3.22.1"
+ },
+ "android_platform": {
+ "path": "platforms/android-36",
+ "revision": "2"
+ },
+ "environment_names": [
+ "CHANNEL_URL",
+ "ENVIRONMENT",
+ "HEXA_ID_MAINNET",
+ "HEXA_ID_TESTNET",
+ "RELAY",
+ "SIGNING_SERVER_MAINNET",
+ "SIGNING_SERVER_TESTNET"
+ ]
+}
diff --git a/reproducibility/test_verify_android_inputs.py b/reproducibility/test_verify_android_inputs.py
new file mode 100644
index 0000000000..ad629ccd4b
--- /dev/null
+++ b/reproducibility/test_verify_android_inputs.py
@@ -0,0 +1,69 @@
+import importlib.util
+from pathlib import Path
+import tempfile
+import unittest
+
+
+SCRIPT = Path(__file__).with_name("verify-android-inputs.py")
+SPEC = importlib.util.spec_from_file_location("verify_android_inputs", SCRIPT)
+MODULE = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(MODULE)
+
+
+class AndroidInputTests(unittest.TestCase):
+ def test_unapproved_environment_name_is_rejected_without_value(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ env = root / ".env.production"
+ env.write_text("ENVIRONMENT=production\nUNREVIEWED_TOKEN=private-example-value\n")
+ with self.assertRaises(MODULE.InputError) as caught:
+ MODULE.check_env_names(env, ["ENVIRONMENT"])
+ self.assertIn("UNREVIEWED_TOKEN", str(caught.exception))
+ self.assertNotIn("private-example-value", str(caught.exception))
+
+ def test_missing_or_duplicate_approved_name_is_rejected(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ env = root / ".env.production"
+ env.write_text("ENVIRONMENT=production\n")
+ with self.assertRaisesRegex(MODULE.InputError, "missing environment names: RELAY"):
+ MODULE.check_env_names(env, ["ENVIRONMENT", "RELAY"])
+ with self.assertRaisesRegex(MODULE.InputError, "duplicate pinned environment name"):
+ MODULE.check_env_names(env, ["ENVIRONMENT", "ENVIRONMENT"])
+
+ def test_external_or_root_dependency_symlink_is_rejected(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ outside = root / "outside"
+ outside.mkdir()
+ dependencies = root / "checkout/node_modules"
+ dependencies.parent.mkdir()
+ dependencies.symlink_to(outside, target_is_directory=True)
+ with self.assertRaisesRegex(MODULE.InputError, "real directory"):
+ MODULE.check_local_dependencies(dependencies.parent)
+ dependencies.unlink()
+ dependencies.mkdir()
+ (dependencies / "escaped").symlink_to(outside, target_is_directory=True)
+ with self.assertRaisesRegex(MODULE.InputError, "outside this checkout"):
+ MODULE.check_local_dependencies(dependencies.parent)
+
+ def test_internal_dependency_symlink_is_allowed(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ dependencies = root / "node_modules"
+ package = dependencies / "some-package"
+ package.mkdir(parents=True)
+ bin_directory = dependencies / ".bin"
+ bin_directory.mkdir()
+ (bin_directory / "some-package").symlink_to(package, target_is_directory=True)
+ MODULE.check_local_dependencies(root)
+
+ def test_sdk_revision_accepts_android_property_spacing(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ package = Path(temporary)
+ (package / "source.properties").write_text("Pkg.Revision = 3.22.1\n")
+ self.assertEqual(MODULE.sdk_revision(package), "3.22.1")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/reproducibility/verify-android-inputs.py b/reproducibility/verify-android-inputs.py
new file mode 100644
index 0000000000..08e0fcc775
--- /dev/null
+++ b/reproducibility/verify-android-inputs.py
@@ -0,0 +1,186 @@
+#!/usr/bin/env python3
+"""Fail closed on known path, configuration, and toolchain drift before an Android build.
+
+This is an input check, not a complete build recipe or reproducibility verdict.
+Environment values are never printed or written to an output file.
+"""
+
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+
+
+class InputError(Exception):
+ pass
+
+
+KEY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+ASSIGNMENT_RE = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=")
+
+
+def sha256(path):
+ digest = hashlib.sha256()
+ with path.open("rb") as source:
+ for chunk in iter(lambda: source.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def read_env_names(path):
+ """Read only names; deliberately never retain or show the values."""
+ names = set()
+ for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
+ stripped = line.strip()
+ if not stripped or stripped.startswith("#"):
+ continue
+ match = ASSIGNMENT_RE.match(stripped)
+ if not match:
+ raise InputError(f"invalid environment assignment at line {line_number}")
+ name = match.group(1)
+ if name in names:
+ raise InputError(f"duplicate environment name: {name}")
+ names.add(name)
+ return names
+
+
+def expected_env_names(expected):
+ if not isinstance(expected, list) or not expected:
+ raise InputError("pinned environment name list is missing or empty")
+ names = set()
+ for name in expected:
+ if not isinstance(name, str) or not KEY_RE.fullmatch(name):
+ raise InputError("invalid pinned environment name")
+ if name in names:
+ raise InputError(f"duplicate pinned environment name: {name}")
+ names.add(name)
+ return names
+
+
+def check_env_names(env_file, expected_names):
+ actual = read_env_names(env_file)
+ approved = expected_env_names(expected_names)
+ unexpected = sorted(actual - approved)
+ missing = sorted(approved - actual)
+ if unexpected or missing:
+ parts = []
+ if unexpected:
+ parts.append("unexpected environment names: " + ", ".join(unexpected))
+ if missing:
+ parts.append("missing environment names: " + ", ".join(missing))
+ raise InputError("; ".join(parts))
+
+
+def check_local_dependencies(repo):
+ dependencies = repo / "node_modules"
+ if dependencies.is_symlink() or not dependencies.is_dir():
+ raise InputError("node_modules must be a real directory inside this checkout")
+ root = dependencies.resolve()
+ for current, directories, files in os.walk(dependencies, followlinks=False):
+ for name in directories + files:
+ path = Path(current) / name
+ if path.is_symlink():
+ try:
+ target = path.resolve(strict=True)
+ except (OSError, RuntimeError):
+ raise InputError("node_modules contains a broken or cyclic symlink") from None
+ if not target.is_relative_to(root):
+ raise InputError("node_modules contains a symlink outside this checkout")
+
+
+def run(*command, cwd=None):
+ try:
+ result = subprocess.run(command, cwd=cwd, check=True, capture_output=True, text=True)
+ except (OSError, subprocess.CalledProcessError):
+ raise InputError(f"cannot run required command: {command[0]}") from None
+ return result.stdout + result.stderr
+
+
+def check_source(repo, commit):
+ if not re.fullmatch(r"[0-9a-f]{40}", commit):
+ raise InputError("expected source commit must be a full 40-character SHA")
+ actual = run("git", "rev-parse", "HEAD", cwd=repo).strip()
+ if actual != commit:
+ raise InputError("checkout HEAD differs from expected source commit")
+ if run("git", "status", "--porcelain=v1", "--untracked-files=normal", cwd=repo).strip():
+ raise InputError("source checkout has uncommitted files")
+
+
+def check_hash(path, expected, label):
+ if not path.is_file() or sha256(path) != expected:
+ raise InputError(f"{label} differs from the pinned hash")
+
+
+def check_gradle_distribution(repo, expected):
+ wrapper = (repo / "android/gradle/wrapper/gradle-wrapper.properties").read_text(encoding="utf-8")
+ if f"distributionSha256Sum={expected}" not in wrapper.splitlines():
+ raise InputError("Gradle distribution checksum differs from the pinned hash")
+
+
+def sdk_revision(path):
+ properties = path / "source.properties"
+ if not properties.is_file():
+ raise InputError(f"Android SDK package missing: {path.name}")
+ for line in properties.read_text(encoding="utf-8").splitlines():
+ match = re.fullmatch(r"Pkg\.Revision\s*=\s*(\S+)\s*", line)
+ if match:
+ return match.group(1)
+ raise InputError(f"Android SDK package has no revision: {path.name}")
+
+
+def check_toolchain(inputs, sdk_root):
+ node = run("node", "--version").strip().removeprefix("v")
+ yarn = run("yarn", "--version").strip()
+ java_output = run("java", "-XshowSettings:properties", "-version")
+ java_match = re.search(r"^\s*java\.version\s*=\s*(\S+)\s*$", java_output, re.MULTILINE)
+ if (node, yarn, java_match.group(1) if java_match else None) != (
+ inputs["node"], inputs["yarn"], inputs["java"]
+ ):
+ raise InputError("Node, Yarn, or JDK version differs from pinned Android inputs")
+ for package, revision in inputs["android_packages"].items():
+ if sdk_revision(sdk_root / package) != revision:
+ raise InputError(f"Android SDK package revision differs: {package}")
+ platform = inputs["android_platform"]
+ if sdk_revision(sdk_root / platform["path"]) != platform["revision"]:
+ raise InputError("Android platform revision differs from pinned Android inputs")
+ if not (sdk_root / platform["path"] / "android.jar").is_file():
+ raise InputError("pinned Android platform is missing")
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parent.parent)
+ parser.add_argument("--source-commit", required=True)
+ parser.add_argument("--env-file", type=Path, required=True)
+ parser.add_argument("--android-sdk-root", type=Path, default=None)
+ args = parser.parse_args()
+ repo = args.repo.resolve()
+ sdk_root = args.android_sdk_root or os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT")
+ if not sdk_root:
+ raise InputError("ANDROID_HOME or ANDROID_SDK_ROOT is required")
+ sdk_root = Path(sdk_root).resolve()
+ inputs = json.loads((repo / "reproducibility/android-inputs.json").read_text(encoding="utf-8"))
+ check_source(repo, args.source_commit)
+ check_hash(repo / "yarn.lock", inputs["yarn_lock_sha256"], "yarn.lock")
+ check_hash(
+ repo / "android/gradle/wrapper/gradle-wrapper.jar",
+ inputs["gradle_wrapper_jar_sha256"],
+ "Gradle wrapper JAR",
+ )
+ check_gradle_distribution(repo, inputs["gradle_distribution_sha256"])
+ check_local_dependencies(repo)
+ check_env_names(args.env_file, inputs["environment_names"])
+ check_toolchain(inputs, sdk_root)
+ print("Android build inputs verified; this is not a reproducibility verdict.")
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except (InputError, OSError, ValueError, KeyError, json.JSONDecodeError) as error:
+ print(f"Android input check failed: {error}", file=sys.stderr)
+ sys.exit(1)
diff --git a/scripts/check-android-16kb.py b/scripts/check-android-16kb.py
new file mode 100644
index 0000000000..d96535674d
--- /dev/null
+++ b/scripts/check-android-16kb.py
@@ -0,0 +1,236 @@
+#!/usr/bin/env python3
+"""Inspect supplied ELF/AAR/APK bytes; this does not prove Android runtime support.
+
+Primary references, checked 2026-10-15:
+https://developer.android.com/guide/practices/page-sizes
+https://android.googlesource.com/platform/bionic/+/06356e41c5ed7b12220b24c05ba4fdb873b126a7/linker/linker_phdr.cpp
+https://android.googlesource.com/platform/bionic/+/06356e41c5ed7b12220b24c05ba4fdb873b126a7/linker/linker_phdr_16kib_compat.cpp
+
+Keep LOAD alignment, RELRO end alignment, Android 17's effective program
+alignment, and APK ZIP alignment separate. In particular, an unaligned RELRO
+end covering its entire LOAD is exempt from Android 17's prefix adjustment.
+AAR ZIP offsets say nothing about the final APK's packaging.
+"""
+
+import argparse
+import hashlib
+import json
+import pathlib
+import struct
+import sys
+import zipfile
+
+PAGE = 16384
+COMPAT_PAGE = 4096
+PT_LOAD = 1
+PT_GNU_RELRO = 0x6474E552
+MACHINES = {183: "arm64-v8a", 62: "x86_64"}
+ABIS = set(MACHINES.values())
+MAX_LIBRARY_SIZE = 512 * 1024 * 1024
+
+
+class InspectionError(ValueError):
+ """The supplied artifact does not establish the requested static proof."""
+
+
+def sha256(data):
+ return hashlib.sha256(data).hexdigest()
+
+
+def inspect_elf(data, expected_abi=None):
+ if len(data) < 64 or data[:4] != b"\x7fELF":
+ raise InspectionError("missing or truncated ELF64 header")
+ if data[4:7] != bytes((2, 1, 1)):
+ raise InspectionError("expected a little-endian ELF64 version 1 library")
+ fields = struct.unpack_from(" len(data):
+ raise InspectionError("program-header table is outside the supplied file")
+ headers = []
+ for index in range(phnum):
+ ptype, flags, offset, vaddr, _, filesz, memsz, align = struct.unpack_from(
+ " len(data) or vaddr + memsz > 0xFFFFFFFFFFFFFFFF:
+ raise InspectionError("segment range exceeds file or address space")
+ if ptype == PT_LOAD and filesz > memsz:
+ raise InspectionError("LOAD file size exceeds memory size")
+ headers.append({
+ "index": index, "type": "LOAD" if ptype == PT_LOAD else "GNU_RELRO",
+ "flags": flags, "offset": offset, "vaddr": vaddr,
+ "filesz": filesz, "memsz": memsz, "align": align,
+ })
+ loads = [x for x in headers if x["type"] == "LOAD"]
+ relros = [x for x in headers if x["type"] == "GNU_RELRO"]
+ if not loads:
+ raise InspectionError("ELF has no LOAD segment")
+
+ reasons = []
+ load_alignment = all(x["align"] >= PAGE and x["align"] & (x["align"] - 1) == 0 for x in loads)
+ load_congruence = all((x["vaddr"] - x["offset"]) % PAGE == 0 for x in loads)
+ declared_congruence = all(x["align"] <= 1 or (x["vaddr"] - x["offset"]) % x["align"] == 0 for x in loads)
+ if not load_alignment:
+ reasons.append("LOAD p_align is not a power of two of at least 16384")
+ if not load_congruence or not declared_congruence:
+ reasons.append("LOAD virtual/file offsets are not congruent")
+
+ # Mirror CheckProgramHeaderAlignment and FixMinAlignFor16KiB. Invalid
+ # p_align values are separately rejected above, rather than silently ignored.
+ effective = PAGE
+ for item in loads:
+ align = item["align"]
+ if align > 1 and align & (align - 1) == 0:
+ effective = min(effective, align)
+ relro_details = []
+ for item in relros:
+ end = item["vaddr"] + item["memsz"]
+ matching = next((x for x in loads if x["vaddr"] == item["vaddr"]), None)
+ whole_load = matching is not None and matching["memsz"] <= item["memsz"]
+ relro_details.append({
+ **item, "end": end, "end_mod_16384": end % PAGE,
+ "end_aligned": end % PAGE == 0,
+ "matching_load_index": None if matching is None else matching["index"],
+ "covers_entire_matching_load": whole_load,
+ })
+ if len(relro_details) == 1:
+ item = relro_details[0]
+ if item["matching_load_index"] is not None and not item["covers_entire_matching_load"]:
+ lowbit = item["end"] & -item["end"]
+ if lowbit >= COMPAT_PAGE:
+ effective = min(effective, lowbit)
+ overlap = False
+ if effective >= PAGE:
+ previous_end = 0
+ for item in loads:
+ if previous_end > item["vaddr"] // PAGE * PAGE:
+ overlap = True
+ effective = COMPAT_PAGE
+ break
+ previous_end = item["vaddr"] + item["memsz"]
+ if effective < PAGE:
+ reasons.append("Android 17 effective program alignment is %s" % effective)
+ # The guide's end check is deliberately retained even when Android 17's
+ # rejection logic does not inspect a non-prefix/multiple-RELRO layout.
+ # Only the documented-in-source whole-LOAD exception is accepted here.
+ relro_safe = all(x["end_aligned"] or x["covers_entire_matching_load"] for x in relro_details)
+ if not relro_safe:
+ reasons.append("nonaligned RELRO end has no whole-LOAD exemption")
+ return {
+ "abi": abi, "sha256": sha256(data), "size": len(data),
+ "load_alignment_pass": load_alignment,
+ "load_16kb_congruence_pass": load_congruence,
+ "load_declared_congruence_pass": declared_congruence,
+ "loads": loads, "relro": relro_details,
+ "relro_end_alignment_pass": all(x["end_aligned"] for x in relro_details),
+ "relro_layout_pass": relro_safe,
+ "android17_effective_program_alignment": effective,
+ "android17_program_alignment_pass": effective >= PAGE,
+ "android17_load_page_overlap": overlap,
+ "failures": reasons,
+ }
+
+
+def inspect_apk_entry(archive_data, info):
+ """Read the LOCAL header; central-directory header_offset is not data offset."""
+ start = info.header_offset
+ if start < 0 or start + 30 > len(archive_data):
+ raise InspectionError("APK local ZIP header is outside the file")
+ fields = struct.unpack_from(" len(archive_data):
+ raise InspectionError("APK ZIP entry data is outside the supplied file")
+ local_name = archive_data[start + 30:start + 30 + name_len]
+ try:
+ local_name = local_name.decode("utf-8" if flags & 0x800 else "cp437")
+ except UnicodeDecodeError as exc:
+ raise InspectionError("invalid APK local filename encoding") from exc
+ if local_name != info.filename or method != info.compress_type or flags != info.flag_bits:
+ raise InspectionError("APK local and central ZIP headers disagree")
+ if flags & 1:
+ raise InspectionError("encrypted native APK entry is unsupported")
+ if not flags & 8 and (crc != info.CRC or compressed not in (info.compress_size, 0xFFFFFFFF) or size not in (info.file_size, 0xFFFFFFFF)):
+ raise InspectionError("APK local and central ZIP size/CRC fields disagree")
+ if method != zipfile.ZIP_STORED:
+ return {"status": "NOT_PROVEN", "method": method, "data_offset": data_offset,
+ "reason": "compressed native entry: extraction/manifest and runtime require separate proof"}
+ if info.compress_size != info.file_size:
+ raise InspectionError("STORED ZIP entry sizes differ")
+ aligned = data_offset % PAGE == 0
+ return {"status": "PASS" if aligned else "FAIL", "method": method,
+ "data_offset": data_offset, "data_offset_mod_16384": data_offset % PAGE}
+
+
+def inspect_file(path):
+ path = pathlib.Path(path)
+ result = {"path": str(path), "libraries": [], "errors": []}
+ try:
+ data = path.read_bytes()
+ result["sha256"] = sha256(data)
+ suffix = path.suffix.lower()
+ if suffix == ".so":
+ item = inspect_elf(data)
+ item.update({"entry": path.name, "apk_zip": {"status": "NOT_APPLICABLE"}})
+ result["libraries"].append(item)
+ result["kind"] = "ELF"
+ elif suffix in (".aar", ".apk"):
+ result["kind"] = suffix[1:].upper()
+ with zipfile.ZipFile(path) as archive:
+ seen = set()
+ for info in archive.infolist():
+ parts = info.filename.split("/")
+ prefix = "lib" if suffix == ".apk" else "jni"
+ if len(parts) != 3 or parts[0] != prefix or parts[1] not in ABIS or not parts[2].endswith(".so"):
+ continue
+ try:
+ if info.filename in seen:
+ raise InspectionError("duplicate native ZIP entry")
+ seen.add(info.filename)
+ if info.file_size > MAX_LIBRARY_SIZE:
+ raise InspectionError("native entry exceeds inspection size limit")
+ item = inspect_elf(archive.read(info), expected_abi=parts[1])
+ item["entry"] = info.filename
+ item["apk_zip"] = inspect_apk_entry(data, info) if suffix == ".apk" else {"status": "NOT_APPLICABLE"}
+ if item["apk_zip"]["status"] not in ("PASS", "NOT_APPLICABLE"):
+ item["failures"].append("APK ZIP packaging is " + item["apk_zip"]["status"])
+ result["libraries"].append(item)
+ except (InspectionError, ValueError, RuntimeError, EOFError, zipfile.BadZipFile, struct.error) as exc:
+ result["errors"].append(info.filename + ": " + (str(exc) or type(exc).__name__))
+ else:
+ raise InspectionError("expected an explicit .so, .aar, or .apk input")
+ if not result["libraries"]:
+ result["errors"].append("no supported retained 64-bit native libraries inspected")
+ except (OSError, InspectionError, ValueError, zipfile.BadZipFile, struct.error) as exc:
+ result["errors"].append(str(exc))
+ result["status"] = "FAIL" if result["errors"] or any(x["failures"] for x in result["libraries"]) else "PASS"
+ return result
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("artifacts", nargs="+", help="explicit .so, .aar, or .apk paths")
+ args = parser.parse_args(argv)
+ results = [inspect_file(x) for x in args.artifacts]
+ print(json.dumps({
+ "schema": 1, "page_size": PAGE,
+ "scope": "static supplied bytes only; runtime, Portal behavior and production AAB/split identity remain separate",
+ "artifacts": results,
+ }, indent=2, sort_keys=True))
+ return 1 if any(x["status"] != "PASS" for x in results) else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/check_cloud_release_inputs.py b/scripts/check_cloud_release_inputs.py
new file mode 100644
index 0000000000..d99b74181d
--- /dev/null
+++ b/scripts/check_cloud_release_inputs.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python3
+"""Read-only frozen Ruby/Pod/Nitro input check. No install or release operation."""
+import argparse
+import json
+import pathlib
+import sys
+
+from cloud_release_worker import digest, ruby_lock_compatibility
+
+INPUTS = ("Gemfile", "Gemfile.lock", "package.json", "yarn.lock", "ios/Podfile.lock")
+
+
+def inspect(root):
+ ruby_lock_compatibility(root)
+ return {
+ "schema": 1,
+ "state": "INPUTS_ALIGNED",
+ "execution_allowed": False,
+ "frozen_installation_verified": False,
+ "native_acceptance_verified": False,
+ "input_sha256": {name: digest(root / name) for name in INPUTS},
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--root", type=pathlib.Path, default=pathlib.Path("."))
+ args = parser.parse_args()
+ try:
+ result = inspect(args.root)
+ except (OSError, ValueError, KeyError, TypeError):
+ print('Frozen release inputs rejected; no input changed or operation allowed.', file=sys.stderr)
+ return 1
+ print(json.dumps(result, indent=2, sort_keys=True))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/cloud_release_inventory.py b/scripts/cloud_release_inventory.py
new file mode 100644
index 0000000000..74cea0b7e5
--- /dev/null
+++ b/scripts/cloud_release_inventory.py
@@ -0,0 +1,135 @@
+#!/usr/bin/env python3
+"""Read-only Phase B source/configuration inventory. Never handles secret values.
+
+The output is preparation evidence, not an execution gate or release approval.
+Only explicitly allowlisted metadata is included in the report.
+"""
+import argparse
+import json
+import pathlib
+import re
+import subprocess
+
+
+PROPOSED_ENVIRONMENTS = ("keeper-release-ios", "keeper-release-android")
+SOURCE_FILES = (
+ "ios/fastlane/Fastfile", "android/fastlane/Fastfile",
+ "ios/fastlane/Appfile", "android/fastlane/Appfile", "android/app/build.gradle",
+)
+
+
+def git(root, *args):
+ return subprocess.check_output(
+ ["git", "-C", str(root), *args], text=True, stderr=subprocess.DEVNULL
+ ).strip()
+
+
+def release_credential_literals(text):
+ # Scope to the release signing block; Android's public debug credentials
+ # intentionally remain distinct. Return field/line only, never its value.
+ start = re.search(r"signingConfigs\s*\{\s*release\s*\{", text)
+ if not start:
+ return None
+ position = start.end()
+ depth = 1
+ while position < len(text) and depth:
+ depth += (text[position] == "{") - (text[position] == "}")
+ position += 1
+ if depth:
+ return None
+ body = text[start.end():position - 1]
+ findings = []
+ for match in re.finditer(r"\b(storePassword|keyPassword|keyAlias)\s*(?:=\s*)?['\"]", body):
+ line = text[:start.end() + match.start()].count("\n") + 1
+ findings.append({"field": match.group(1), "line": line})
+ return findings
+
+
+def environment_inventory(document):
+ results = []
+ if document is not None and (
+ not isinstance(document, dict) or not isinstance(document.get("environments"), list)
+ ):
+ raise ValueError("invalid environment metadata")
+ environments = document.get("environments", []) if document is not None else []
+ for name in PROPOSED_ENVIRONMENTS:
+ matches = [env for env in environments if isinstance(env, dict) and env.get("name") == name]
+ if document is None:
+ state = "UNKNOWN"
+ reviewers = "UNKNOWN"
+ branch_policy = "UNKNOWN"
+ elif len(matches) != 1:
+ state = "NOT_CONFIGURED" if not matches else "AMBIGUOUS"
+ reviewers = branch_policy = "NOT_VERIFIED"
+ else:
+ state = "CONFIGURED_NOT_VERIFIED"
+ env = matches[0]
+ rules = env.get("protection_rules", [])
+ review_rules = [rule for rule in rules if isinstance(rule, dict) and rule.get("type") == "required_reviewers"] if isinstance(rules, list) else []
+ protected = len(review_rules) == 1 and review_rules[0].get("prevent_self_review") is True and bool(review_rules[0].get("reviewers"))
+ reviewers = "PRESENT" if protected else "NOT_VERIFIED"
+ policy = env.get("deployment_branch_policy")
+ restricted = isinstance(policy, dict) and (policy.get("custom_branch_policies") is True or policy.get("protected_branches") is True)
+ # A collection response cannot prove which exact branch is allowed,
+ # bypass policy, or that reviewer enforcement actually works.
+ branch_policy = "RESTRICTION_PRESENT_EXACT_RULES_UNVERIFIED" if restricted else "NOT_VERIFIED"
+ results.append({"proposed_name": name, "state": state,
+ "independent_reviewers": reviewers, "source_restriction": branch_policy})
+ return results
+
+
+def inventory(root, environments=None):
+ root = pathlib.Path(root)
+ tracked = git(root, "ls-files", "-z").split("\0")
+ php_count = sum(path.lower().endswith(".php") for path in tracked)
+ composer_count = sum(pathlib.PurePosixPath(path).name in ("composer.json", "composer.lock") for path in tracked)
+ source = {}
+ for name in SOURCE_FILES:
+ path = root / name
+ source[name] = path.read_text() if path.is_file() else ""
+ signing = release_credential_literals(source["android/app/build.gradle"])
+ return {
+ "schema": 1,
+ "source_sha": git(root, "rev-parse", "HEAD"),
+ "tracked_tree_dirty": bool(git(root, "status", "--porcelain", "--untracked-files=no")),
+ "scope": "PHASE_B_PREPARATION_ONLY",
+ "execution_allowed": False,
+ "hosted_signing_distribution": "NOT_IMPLEMENTED_NOT_VERIFIED",
+ "source_inventory": {"tracked_php_files": php_count, "tracked_composer_manifests": composer_count,
+ "deployed_runtime_inventory": "UNKNOWN", "php_exposure": "NOT_ESTABLISHED"},
+ "android_release_literal_credentials": {"state": "UNKNOWN" if signing is None else "FOUND_REQUIRES_PRIVATE_TRIAGE" if signing else "NONE_IN_INSPECTED_BLOCK",
+ "locations": signing or []},
+ "existing_lanes": {
+ "ios_build_only_acquires_signing_material": all(token in source["ios/fastlane/Fastfile"] for token in ("get_certificates(", "get_provisioning_profile(")),
+ "ios_upload_action_present": "upload_to_testflight(" in source["ios/fastlane/Fastfile"],
+ "android_upload_action_present": "upload_to_play_store(" in source["android/fastlane/Fastfile"],
+ "lane_execution": "NOT_RUN",
+ },
+ "proposed_protected_environments": environment_inventory(environments),
+ "credential_custody_and_authorization": "UNKNOWN_NOT_INSPECTED",
+ "exact_head_native_security_physical_acceptance": "REQUIRES_SEPARATE_EVIDENCE",
+ "owner_release_approval": "REQUIRES_SEPARATE_EXPLICIT_APPROVAL",
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--root", default=".")
+ parser.add_argument("--environment-metadata", help="Optional read-only GitHub environments JSON; no credentials")
+ args = parser.parse_args()
+ try:
+ metadata = None
+ if args.environment_metadata:
+ path = pathlib.Path(args.environment_metadata)
+ if path.stat().st_size > 1024 * 1024:
+ raise ValueError("metadata too large")
+ metadata = json.loads(path.read_text())
+ result = inventory(args.root, metadata)
+ except (OSError, ValueError, TypeError, subprocess.CalledProcessError):
+ # Do not echo exception text, input, file paths or credential-like data.
+ parser.exit(2, "Release inventory unavailable: invalid source or metadata; no release action performed.\n")
+ print(json.dumps(result, indent=2, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/cloud_release_worker.py b/scripts/cloud_release_worker.py
new file mode 100644
index 0000000000..4c423b539c
--- /dev/null
+++ b/scripts/cloud_release_worker.py
@@ -0,0 +1,405 @@
+#!/usr/bin/env python3
+"""Protected release adapter. Called only by the installed Node authorization driver.
+
+Never invoke for validation. Contracts inject fake actions; real operations need
+the workflow's protected review, exact owner receipt and fresh API authorization.
+"""
+import base64
+import datetime
+import hashlib
+import importlib.util
+import json
+import os
+import pathlib
+import plistlib
+import re
+import secrets
+import shlex
+import shutil
+import subprocess
+import sys
+import zipfile
+
+APP_ID = {"ios": "io.hexawallet.keeper", "android": "io.hexawallet.bitcoinkeeper"}
+CLIENT_KEYS = set("CHANNEL_URL ENVIRONMENT RELAY SIGNING_SERVER_TESTNET SIGNING_SERVER_MAINNET HEXA_ID_TESTNET HEXA_ID_MAINNET ADDRESS BIP85_IMAGE_ENCRYPTIONKEY_DERIVATION_PATH ENC_KEY_STORAGE_IDENTIFIER GAP_LIMIT LETS_EXCHANGE_BASE_URL RENEWAL_WINDOW SENTRY_DNS WALLET_INSTANCE_SERIES".split())
+CURRENT_STAGE = "input-validation"
+CLEANUP_FAILED = False
+
+
+def demand(condition):
+ if not condition:
+ raise ValueError("protected release boundary failed")
+
+
+def digest(path):
+ with pathlib.Path(path).open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def run(arguments, *, env=None, cwd=None, data=None):
+ # Never log commands, raw native/provider output or exceptions: they can
+ # contain signing passwords, request bodies or embedded client configuration.
+ result = subprocess.run([str(arg) for arg in arguments], input=data, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, env=env, cwd=cwd, check=False)
+ demand(result.returncode == 0)
+ return result.stdout
+
+
+def decode_secret(name, target):
+ raw = os.environ.get(name, "")
+ demand(bool(raw))
+ data = base64.b64decode(raw, validate=True)
+ demand(0 < len(data) <= 16 * 1024 * 1024)
+ with pathlib.Path(target).open("xb") as stream:
+ os.chmod(target, 0o600)
+ stream.write(data)
+
+
+def validate_client_config(data, expected):
+ demand(hashlib.sha256(data).hexdigest() == expected)
+ names = []
+ for line in data.decode("utf8").splitlines():
+ if not line.strip() or line.lstrip().startswith("#"):
+ continue
+ match = re.fullmatch(r"([A-Z][A-Z0-9_]*)=([^\r\n]*)", line)
+ demand(match is not None and match[1] in CLIENT_KEYS and match[1] not in names)
+ names.append(match[1])
+ demand(set("CHANNEL_URL ENVIRONMENT RELAY SIGNING_SERVER_TESTNET SIGNING_SERVER_MAINNET HEXA_ID_TESTNET HEXA_ID_MAINNET".split()) <= set(names))
+
+
+def package_overlay(root, record=None):
+ before = run(["git", "show", "HEAD:package.json"], cwd=root)
+ after = (root / "package.json").read_bytes()
+ allowed = ["browser", "react-native", "browserify"]
+ old, new = json.loads(before), json.loads(after)
+ for field in allowed:
+ old.pop(field, None); new.pop(field, None)
+ demand(old == new)
+ demand(set(run(["git", "diff", "HEAD", "--name-only"], cwd=root).decode().splitlines()) <= {"package.json"})
+ actual = {"sourceSha": run(["git", "rev-parse", "HEAD"], cwd=root).decode().strip(),
+ "allowed_fields": allowed, "before_sha256": hashlib.sha256(before).hexdigest(), "after_sha256": hashlib.sha256(after).hexdigest()}
+ if record is not None:
+ demand(actual == record)
+ return actual
+
+
+def ruby_lock_compatibility(root):
+ gems = (root / "Gemfile.lock").read_text()
+ pods = (root / "ios/Podfile.lock").read_text()
+ gem_version = re.search(r"^ cocoapods \(([^)]+)\)$", gems, re.M)
+ pod_version = re.search(r"^COCOAPODS: (\S+)$", pods, re.M)
+ project = re.search(r"^ xcodeproj \(([^)]+)\)$", gems, re.M)
+ demand(gem_version is not None and pod_version is not None and project is not None)
+ demand(gem_version[1] == pod_version[1] == "1.16.2")
+ demand(tuple(map(int, project[1].split('.'))) >= (1, 27, 0))
+ demand(re.search(r"gem\s+['\"]xcodeproj['\"],\s*['\"]<\s*1\.26", (root / "Gemfile").read_text()) is None)
+ # The reviewed Pod lock also updates Nitro. Accept the frozen tuple only
+ # when the manifest, Yarn resolution and native Pod agree; never repair it.
+ nitro = json.loads((root / "package.json").read_text())["dependencies"]["react-native-nitro-modules"]
+ demand(isinstance(nitro, str) and re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", nitro) is not None)
+ yarn = (root / "yarn.lock").read_text()
+ # Reject quoted/combined/duplicate Nitro selectors as ambiguous rather than
+ # ignoring them while accepting an earlier matching unquoted stanza.
+ headers = [line for line in yarn.splitlines() if line and not line[0].isspace()
+ and not line.startswith('#') and 'react-native-nitro-modules@' in line]
+ demand(headers == [f'react-native-nitro-modules@{nitro}:'])
+ resolutions = re.findall(r"^react-native-nitro-modules@([^\n]+):\n((?:[ \t][^\n]*\n|\n)*)", yarn, re.M)
+ demand(len(resolutions) == 1 and resolutions[0][0] == nitro)
+ demand(re.findall(r'^ version "([^"]+)"$', resolutions[0][1], re.M) == [nitro])
+ demand(re.findall(r"^ - NitroModules \(([^)]+)\):$", pods, re.M) == [nitro])
+
+
+def safe_unzip(archive, destination, *, exact_names=None):
+ destination = pathlib.Path(destination)
+ with zipfile.ZipFile(archive) as source:
+ members = source.infolist()
+ demand(len(members) <= 100000 and sum(item.file_size for item in members) <= 4 * 1024 ** 3)
+ names = [item.filename for item in members]
+ demand(len(names) == len(set(names)))
+ if exact_names is not None:
+ demand(set(names) == set(exact_names))
+ for item in members:
+ relative = pathlib.PurePosixPath(item.filename)
+ demand(not relative.is_absolute() and ".." not in relative.parts and "\\" not in item.filename)
+ demand((item.external_attr >> 16) & 0o170000 != 0o120000)
+ target = destination.joinpath(*relative.parts)
+ if item.is_dir():
+ target.mkdir(parents=True, exist_ok=True)
+ else:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ with source.open(item) as src, target.open("xb") as dst:
+ shutil.copyfileobj(src, dst)
+ mode = (item.external_attr >> 16) & 0o777
+ if mode:
+ os.chmod(target, mode)
+
+
+def unpack(context, private):
+ payload = "release.ipa" if context["operation"] == "testflight-upload" else "release.aab"
+ safe_unzip(private / "artifact.zip", private / "input", exact_names=[payload, "receipt.json"])
+ demand(digest(private / "input" / payload) == context["artifactSha256"])
+ receipt_path = private / "input/receipt.json"
+ demand(receipt_path.stat().st_size <= 16384)
+ return json.loads(receipt_path.read_text())
+
+
+def cert_der_from_pem(pem):
+ return run(["openssl", "x509", "-outform", "DER"], data=pem)
+
+
+def validate_profile(profile, expected_cert, team, uuid):
+ expiry = profile.get("ExpirationDate")
+ demand(isinstance(expiry, datetime.datetime))
+ expiry = expiry.replace(tzinfo=datetime.timezone.utc) if expiry.tzinfo is None else expiry
+ demand(expiry > datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2))
+ entitlements = profile.get("Entitlements", {})
+ demand(profile.get("UUID") == uuid and team in profile.get("TeamIdentifier", []))
+ demand(entitlements.get("application-identifier") == team + "." + APP_ID["ios"])
+ demand(entitlements.get("get-task-allow") is False and not profile.get("ProvisionedDevices") and not profile.get("ProvisionsAllDevices"))
+ demand(any(hashlib.sha256(cert).hexdigest() == expected_cert for cert in profile.get("DeveloperCertificates", [])))
+
+
+def verify_ios(artifact, context, private):
+ app_dir = private / "ipa-check"
+ app_dir.mkdir()
+ safe_unzip(artifact, app_dir)
+ apps = list((app_dir / "Payload").glob("*.app"))
+ demand(len(apps) == 1)
+ app = apps[0]
+ run(["codesign", "--verify", "--deep", "--strict", app])
+ certificate_prefix = private / "signed-cert"
+ run(["codesign", "-d", "--extract-certificates", certificate_prefix, app])
+ certificate = pathlib.Path(str(certificate_prefix) + "0").read_bytes()
+ demand(hashlib.sha256(certificate).hexdigest() == context["identitySha256"])
+ run(["openssl", "x509", "-inform", "DER", "-checkend", "7200", "-noout"], data=certificate)
+ profile = plistlib.loads(run(["security", "cms", "-D", "-i", app / "embedded.mobileprovision"]))
+ team, uuid = os.environ.get("KEEPER_IOS_TEAM_ID", ""), os.environ.get("KEEPER_IOS_PROFILE_UUID", "")
+ demand(re.fullmatch(r"[A-Z0-9]{10}", team) is not None)
+ validate_profile(profile, context["identitySha256"], team, uuid)
+ entitlements = plistlib.loads(run(["codesign", "-d", "--entitlements", ":-", app]))
+ demand(entitlements.get("application-identifier") == team + "." + APP_ID["ios"])
+ demand(entitlements.get("com.apple.developer.team-identifier") == team and entitlements.get("get-task-allow") is False)
+
+
+def verify_android(artifact, context, private):
+ pem = run(["keytool", "-printcert", "-jarfile", artifact, "-rfc"])
+ cert = cert_der_from_pem(pem)
+ demand(hashlib.sha256(cert).hexdigest() == context["identitySha256"])
+ run(["openssl", "x509", "-inform", "DER", "-checkend", "7200", "-noout"], data=cert)
+ cert_file = private / "public-certificate.der"
+ cert_file.write_bytes(cert)
+ trust = private / "public-trust.jks"
+ env = {**os.environ, "KEEPER_PUBLIC_TRUST_PASSWORD": secrets.token_hex(24)}
+ run(["keytool", "-importcert", "-noprompt", "-alias", "approved-upload-certificate", "-file", cert_file,
+ "-keystore", trust, "-storepass:env", "KEEPER_PUBLIC_TRUST_PASSWORD"], env=env)
+ # Trust only the independently pinned certificate; strict verification also
+ # rejects unsigned payload entries without rejecting its self-signed chain.
+ run(["jarsigner", "-verify", "-strict", "-keystore", trust, "-storepass:env", "KEEPER_PUBLIC_TRUST_PASSWORD", artifact], env=env)
+
+
+def verify_artifact(artifact, context, root, private):
+ spec = importlib.util.spec_from_file_location("artifact_guard", pathlib.Path(__file__).with_name("verify-release-artifact.py"))
+ verifier = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(verifier)
+ manifest = json.loads((root / "release/version.json").read_text())
+ result = verifier.inspect(artifact, manifest)
+ demand(result["sha256"] == digest(artifact) and result["version"] == context["version"] and result["build"] == context["build"])
+ if artifact.suffix == ".ipa":
+ verify_ios(artifact, context, private)
+ else:
+ verify_android(artifact, context, private)
+
+
+def build_android(root, private, context):
+ key = private / "upload.keystore"
+ decode_secret("KEEPER_ANDROID_KEYSTORE_BASE64", key)
+ demand(all(os.environ.get(name) for name in ("STORE_PASSWORD", "KEY_PASSWORD", "KEY_ALIAS")))
+ cert = run(["keytool", "-exportcert", "-keystore", key, "-storepass:env", "STORE_PASSWORD", "-alias", os.environ["KEY_ALIAS"]])
+ demand(hashlib.sha256(cert).hexdigest() == context["identitySha256"])
+ run(["openssl", "x509", "-inform", "DER", "-checkend", "7200", "-noout"], data=cert)
+ env = {**os.environ, "KEEPER_ANDROID_KEYSTORE": str(key), "ENVFILE": str(root / ".env.production")}
+ run([root / "android/gradlew", "-p", root / "android", ":app:bundleProductionRelease", "--no-daemon", "--console=plain"], cwd=root, env=env)
+ artifact = root / "android/app/build/outputs/bundle/productionRelease/app-production-release.aab"
+ demand(artifact.is_file())
+ return artifact
+
+
+def build_ios(root, private, context):
+ global CLEANUP_FAILED, CURRENT_STAGE
+ team, uuid = os.environ.get("KEEPER_IOS_TEAM_ID", ""), os.environ.get("KEEPER_IOS_PROFILE_UUID", "")
+ demand(re.fullmatch(r"[A-Z0-9]{10}", team) is not None and re.fullmatch(r"[A-Fa-f0-9-]{36}", uuid) is not None)
+ cert_file, profile_file = private / "signing.p12", private / "profile.mobileprovision"
+ decode_secret("KEEPER_IOS_P12_BASE64", cert_file)
+ decode_secret("KEEPER_IOS_PROFILE_BASE64", profile_file)
+ demand(bool(os.environ.get("KEEPER_IOS_P12_PASSWORD")))
+ cert = cert_der_from_pem(run(["openssl", "pkcs12", "-in", cert_file, "-clcerts", "-nokeys", "-passin", "env:KEEPER_IOS_P12_PASSWORD"]))
+ demand(hashlib.sha256(cert).hexdigest() == context["identitySha256"])
+ run(["openssl", "x509", "-inform", "DER", "-checkend", "7200", "-noout"], data=cert)
+ profile = plistlib.loads(run(["security", "cms", "-D", "-i", profile_file]))
+ validate_profile(profile, context["identitySha256"], team, uuid)
+ identity = hashlib.sha1(cert).hexdigest() # Xcode identity selector; SHA256 pin was checked above.
+ keychain = private / "release.keychain-db"
+ password = secrets.token_hex(32)
+ profile_target = pathlib.Path.home() / "Library/MobileDevice/Provisioning Profiles" / (uuid + ".mobileprovision")
+ profile_target.parent.mkdir(parents=True, exist_ok=True)
+ previous_profile = profile_target.read_bytes() if profile_target.exists() else None
+ previous_mode = profile_target.stat().st_mode & 0o777 if profile_target.exists() else None
+ previous_keychains = shlex.split(run(["security", "list-keychains", "-d", "user"]).decode())
+ primary_failed = False
+ created_keychain = False
+ changed_search = False
+ try:
+ run(["security", "create-keychain", "-p", password, keychain])
+ created_keychain = True
+ run(["security", "unlock-keychain", "-p", password, keychain])
+ run(["security", "set-keychain-settings", "-lut", "7200", keychain])
+ changed_search = True
+ run(["security", "list-keychains", "-d", "user", "-s", keychain, *previous_keychains])
+ run(["security", "import", cert_file, "-k", keychain, "-P", os.environ["KEEPER_IOS_P12_PASSWORD"], "-T", "/usr/bin/codesign"])
+ run(["security", "set-key-partition-list", "-S", "apple-tool:,apple:,codesign:", "-s", "-k", password, keychain])
+ profile_target.write_bytes(profile_file.read_bytes())
+ os.chmod(profile_target, 0o600)
+ archive, exported = private / "Keeper.xcarchive", private / "export"
+ settings = ["CODE_SIGN_STYLE=Manual", "DEVELOPMENT_TEAM=" + team, "CODE_SIGN_IDENTITY=" + identity,
+ "PROVISIONING_PROFILE_SPECIFIER=" + uuid, "OTHER_CODE_SIGN_FLAGS=--keychain " + str(keychain)]
+ run(["xcodebuild", "-workspace", root / "ios/hexa_keeper.xcworkspace", "-scheme", "hexa_keeper", "-configuration", "Release",
+ "-destination", "generic/platform=iOS", "-archivePath", archive, "archive", *settings], cwd=root,
+ env={**os.environ, "ENVFILE": str(root / ".env.production")})
+ options = private / "ExportOptions.plist"
+ options.write_bytes(plistlib.dumps({"method": "app-store", "signingStyle": "manual", "teamID": team,
+ "signingCertificate": identity, "provisioningProfiles": {APP_ID["ios"]: uuid},
+ "manageAppVersionAndBuildNumber": False}))
+ run(["xcodebuild", "-exportArchive", "-archivePath", archive, "-exportPath", exported,
+ "-exportOptionsPlist", options, "OTHER_CODE_SIGN_FLAGS=--keychain " + str(keychain)], cwd=root)
+ artifacts = list(exported.glob("*.ipa"))
+ demand(len(artifacts) == 1)
+ return artifacts[0]
+ except BaseException:
+ primary_failed = True
+ raise
+ finally:
+ cleanup_failed = False
+ for command in ([['security', 'list-keychains', '-d', 'user', '-s', *previous_keychains]] if changed_search else []) + ([['security', 'delete-keychain', str(keychain)]] if created_keychain else []):
+ try:
+ result = subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, timeout=30)
+ cleanup_failed |= result.returncode != 0
+ except (OSError, subprocess.TimeoutExpired):
+ cleanup_failed = True
+ try:
+ if previous_profile is None:
+ profile_target.unlink(missing_ok=True)
+ else:
+ profile_target.write_bytes(previous_profile)
+ os.chmod(profile_target, previous_mode)
+ except OSError:
+ cleanup_failed = True
+ CLEANUP_FAILED |= cleanup_failed
+ if cleanup_failed and not primary_failed:
+ CURRENT_STAGE = "signing-cleanup"
+ demand(False)
+
+
+def upload(artifact, root, private, context):
+ # Use a standalone reviewed Fastfile; legacy Appfiles/live/dev lanes are not
+ # loaded. No auto-provisioning, Slack, metadata publication or rollout.
+ work = private / "uploader"
+ (work / "fastlane").mkdir(parents=True)
+ shutil.copyfile(pathlib.Path(__file__).parents[1] / "release/cloud/Fastfile", work / "fastlane/Fastfile")
+ env = {**os.environ, "BUNDLE_GEMFILE": str(pathlib.Path(__file__).parents[1] / "Gemfile"), "KEEPER_VERIFIED_ARTIFACT": str(artifact),
+ "KEEPER_RELEASE_OPERATION": context["operation"], "FASTLANE_SKIP_UPDATE_CHECK": "1", "FASTLANE_OPT_OUT_USAGE": "1"}
+ platform = "ios" if context["operation"] == "testflight-upload" else "android"
+ run(["bundle", "exec", "fastlane", platform, "approved_upload"], cwd=work, env=env)
+
+
+def execute(context, root, private):
+ global CURRENT_STAGE
+ CURRENT_STAGE = "identity-validation"
+ demand(os.environ.get("GITHUB_ACTIONS") == "true" and os.environ.get("RUNNER_ENVIRONMENT") == "github-hosted")
+ demand(os.environ.get("KEEPER_EXPECTED_CERT_SHA256") == context["identitySha256"])
+ demand(os.environ.get("KEEPER_EXPECTED_CONFIG_SHA256") == context["configSha256"])
+ deadline = datetime.datetime.fromisoformat(context["approvalExpiresAt"].replace("Z", "+00:00"))
+ demand(deadline > datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2))
+ signing = context["operation"].endswith("-signed-build")
+ env_file = root / ".env.production"
+ created_env = False
+ try:
+ if signing:
+ CURRENT_STAGE = "source-preflight"
+ demand(context["sourceSha"] == context["driverSha"] and not env_file.exists())
+ package_overlay(root, json.loads(pathlib.Path(os.environ["KEEPER_PACKAGE_OVERLAY_PATH"]).read_text()))
+ if context["operation"] == "ios-signed-build":
+ ruby_lock_compatibility(root)
+ run(["node", pathlib.Path(__file__).with_name("release-version.cjs"), "release-check"], cwd=root,
+ env={**os.environ, "KEEPER_RELEASE_COMMIT": context["sourceSha"]})
+ inventory_spec = importlib.util.spec_from_file_location("source_inventory", pathlib.Path(__file__).with_name("cloud_release_inventory.py"))
+ inventory = importlib.util.module_from_spec(inventory_spec)
+ inventory_spec.loader.exec_module(inventory)
+ demand(inventory.release_credential_literals((root / "android/app/build.gradle").read_text()) == [])
+ config = base64.b64decode(os.environ.get("KEEPER_PRODUCTION_CONFIG_BASE64", ""), validate=True)
+ CURRENT_STAGE = "config-validation"
+ validate_client_config(config, context["configSha256"])
+ with env_file.open("xb") as stream:
+ created_env = True
+ os.chmod(env_file, 0o600)
+ stream.write(config)
+ run(["node", pathlib.Path(__file__).with_name("verify-channel-config.cjs"), env_file], cwd=root)
+ CURRENT_STAGE = "native-build"
+ artifact = (build_ios if context["operation"] == "ios-signed-build" else build_android)(root, private, context)
+ else:
+ artifact = private / "input" / ("release.ipa" if context["operation"] == "testflight-upload" else "release.aab")
+ demand(digest(artifact) == context["artifactSha256"])
+ CURRENT_STAGE = "artifact-verification"
+ verify_artifact(artifact, context, root, private)
+ verified_digest = digest(artifact)
+ if signing:
+ package_overlay(root, json.loads(pathlib.Path(os.environ["KEEPER_PACKAGE_OVERLAY_PATH"]).read_text()))
+ else:
+ run(["git", "diff", "HEAD", "--exit-code"], cwd=root)
+ if not signing:
+ CURRENT_STAGE = "upload-command"
+ upload(artifact, root, private, context)
+ CURRENT_STAGE = "receipt"
+ output = pathlib.Path(os.environ["RUNNER_TEMP"]) / "keeper-release-output"
+ output.mkdir(mode=0o700) # Refuse an existing output; never reuse an older artifact.
+ receipt = {key: context[key] for key in ["sourceSha", "driverSha", "operation", "version", "build", "identitySha256", "configSha256", "runId", "runAttempt", "approvalCommentId", "approvalExpiresAt", "artifactId"]}
+ if not signing:
+ receipt.update(sourceRunId=context["sourceRunId"], sourceRunAttempt=context["sourceRunAttempt"])
+ receipt.update(schema=1, artifactSha256=verified_digest, signatureVerified=True, storeUploaded=not signing,
+ storeProcessingVerified=False, publicPublication=False)
+ if signing:
+ copied = output / ("release.ipa" if artifact.suffix == ".ipa" else "release.aab")
+ shutil.copyfile(artifact, copied)
+ demand(digest(copied) == verified_digest)
+ (output / "receipt.json").write_text(json.dumps(receipt, indent=2))
+ finally:
+ if created_env:
+ env_file.unlink(missing_ok=True)
+
+
+def main():
+ try:
+ command, context_path, argument = sys.argv[1:]
+ if command == "overlay":
+ record = package_overlay(pathlib.Path(context_path))
+ with pathlib.Path(argument).open("x") as stream:
+ os.chmod(argument, 0o600)
+ json.dump(record, stream)
+ return 0
+ if command == "ruby-lock-check":
+ ruby_lock_compatibility(pathlib.Path(context_path))
+ return 0
+ context = json.loads(pathlib.Path(context_path).read_text())
+ if command == "unpack":
+ print(json.dumps(unpack(context, pathlib.Path(argument))))
+ elif command == "execute":
+ execute(context, pathlib.Path(argument), pathlib.Path(os.environ["KEEPER_PRIVATE_DIRECTORY"]))
+ else:
+ demand(False)
+ except Exception:
+ print(json.dumps({"state": "FAILED", "stage": CURRENT_STAGE, "cleanupFailed": CLEANUP_FAILED}), file=sys.stderr)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/compare-android-apks.py b/scripts/compare-android-apks.py
new file mode 100755
index 0000000000..e92f8fa7ca
--- /dev/null
+++ b/scripts/compare-android-apks.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+"""Compare the uncompressed payload entries of two Android APKs.
+
+This is an inspection aid, not a WalletScrutiny build script or a Play attestation.
+It never extracts archive entries to the filesystem.
+"""
+
+from __future__ import annotations
+
+import argparse
+from collections import Counter
+import hashlib
+import json
+from pathlib import Path
+import re
+import sys
+import zipfile
+
+
+CHUNK_SIZE = 1024 * 1024
+MAX_ENTRIES = 100_000
+MAX_ENTRY_BYTES = 2 * 1024**3
+MAX_TOTAL_BYTES = 4 * 1024**3
+
+# APK Signature Scheme v2/v3 blocks are outside ZIP entries. These names cover
+# only root-level JAR/v1 signature material plus Play's certificate stamp.
+JAR_SIGNATURE = re.compile(r"^META-INF/[^/]+\.(?:SF|RSA|DSA|EC)$")
+DEX_FILE = re.compile(r"(?:^|/)classes\d*\.dex$")
+
+
+def is_signing_only(name: str) -> bool:
+ return (
+ name == "META-INF/MANIFEST.MF"
+ or name == "stamp-cert-sha256"
+ or JAR_SIGNATURE.fullmatch(name) is not None
+ )
+
+
+def category(name: str) -> str:
+ if DEX_FILE.search(name) or name.endswith(".dex"):
+ return "dex"
+ if name.startswith("assets/dexopt/") and name.endswith((".prof", ".profm")):
+ return "baseline_profile"
+ if name.startswith("lib/") and name.endswith(".so"):
+ return "native_library"
+ if name.endswith((".jsbundle", ".bundle")) or (
+ name.startswith("assets/") and name.endswith(".js")
+ ):
+ return "javascript_bundle"
+ if name == "AndroidManifest.xml":
+ return "manifest"
+ if name == "resources.arsc" or name.startswith("res/"):
+ return "resource"
+ if name.startswith("META-INF/"):
+ return "metadata"
+ if name.startswith("assets/"):
+ return "asset"
+ return "other"
+
+
+def file_sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as stream:
+ for chunk in iter(lambda: stream.read(CHUNK_SIZE), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def inspect_apk(path: Path) -> dict:
+ if not path.is_file():
+ raise ValueError(f"Not a regular file: {path}")
+
+ with zipfile.ZipFile(path) as archive:
+ infos = archive.infolist()
+ if len(infos) > MAX_ENTRIES:
+ raise ValueError(f"Too many ZIP entries in {path}: {len(infos)}")
+
+ names = [info.filename for info in infos]
+ duplicates = sorted(name for name, count in Counter(names).items() if count > 1)
+ if duplicates:
+ raise ValueError(f"Duplicate ZIP entry names in {path}: {duplicates}")
+
+ files = [info for info in infos if not info.is_dir()]
+ total_bytes = sum(info.file_size for info in files)
+ if total_bytes > MAX_TOTAL_BYTES:
+ raise ValueError(f"Declared uncompressed ZIP size exceeds limit in {path}")
+
+ entries = {}
+ for info in files:
+ if info.file_size > MAX_ENTRY_BYTES:
+ raise ValueError(f"ZIP entry exceeds size limit in {path}: {info.filename}")
+ digest = hashlib.sha256()
+ measured = 0
+ # Passing ZipInfo selects the exact entry; reading to EOF checks its CRC.
+ with archive.open(info) as stream:
+ for chunk in iter(lambda: stream.read(CHUNK_SIZE), b""):
+ measured += len(chunk)
+ if measured > MAX_ENTRY_BYTES:
+ raise ValueError(f"ZIP entry exceeds size limit in {path}: {info.filename}")
+ digest.update(chunk)
+ if measured != info.file_size:
+ raise ValueError(f"Incorrect ZIP entry size in {path}: {info.filename}")
+ entries[info.filename] = {"sha256": digest.hexdigest(), "size": measured}
+
+ return {
+ "path": str(path.resolve()),
+ "apk_sha256": file_sha256(path),
+ "payload_entry_count": len(entries),
+ "entries": entries,
+ }
+
+
+def compare(reference: dict, rebuilt: dict) -> dict:
+ reference_entries = reference["entries"]
+ rebuilt_entries = rebuilt["entries"]
+ differences = []
+ ignored_signing_entries = []
+ matching_payload_entries = 0
+
+ for name in sorted(reference_entries.keys() | rebuilt_entries.keys()):
+ before = reference_entries.get(name)
+ after = rebuilt_entries.get(name)
+ if before == after:
+ if not is_signing_only(name):
+ matching_payload_entries += 1
+ continue
+
+ status = (
+ "only_reference" if after is None else
+ "only_rebuilt" if before is None else
+ "content_mismatch"
+ )
+ detail = {
+ "path": name,
+ "status": status,
+ "category": "signing_only" if is_signing_only(name) else category(name),
+ "reference": before,
+ "rebuilt": after,
+ }
+ if is_signing_only(name):
+ ignored_signing_entries.append(detail)
+ else:
+ differences.append(detail)
+
+ return {
+ "schema_version": 1,
+ "verdict": "match" if not differences else "mismatch",
+ "scope": "one APK versus one APK; uncompressed ZIP file entries",
+ "reference": {key: value for key, value in reference.items() if key != "entries"},
+ "rebuilt": {key: value for key, value in rebuilt.items() if key != "entries"},
+ "summary": {
+ "matching_payload_entries": matching_payload_entries,
+ "payload_differences": len(differences),
+ "ignored_signing_differences": len(ignored_signing_entries),
+ },
+ "differences": differences,
+ "ignored_signing_entries": ignored_signing_entries,
+ }
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("reference_apk", type=Path, help="Published reference APK")
+ parser.add_argument("rebuilt_apk", type=Path, help="APK rebuilt from source")
+ args = parser.parse_args()
+
+ try:
+ report = compare(inspect_apk(args.reference_apk), inspect_apk(args.rebuilt_apk))
+ except (OSError, ValueError, RuntimeError, EOFError, NotImplementedError, zipfile.BadZipFile) as error:
+ report = {"schema_version": 1, "verdict": "invalid_input", "error": str(error)}
+
+ json.dump(report, sys.stdout, indent=2, sort_keys=True)
+ sys.stdout.write("\n")
+ return {"match": 0, "mismatch": 1, "invalid_input": 2}[report["verdict"]]
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/protected-release-plan.cjs b/scripts/protected-release-plan.cjs
new file mode 100644
index 0000000000..f006e0e7e3
--- /dev/null
+++ b/scripts/protected-release-plan.cjs
@@ -0,0 +1,134 @@
+#!/usr/bin/env node
+'use strict';
+
+// Trusted-driver preparation gate only. This file has no signing/upload path.
+const fs = require('node:fs');
+const path = require('node:path');
+const { validateIntent, validateSources } = require('./release-version.cjs');
+const repository = 'KeeperCommunity/bitcoin-keeper';
+const operations = {
+ 'ios-signed-build': 'keeper-release-ios',
+ 'android-signed-build': 'keeper-release-android',
+ 'testflight-upload': 'keeper-release-ios',
+ 'play-internal-upload': 'keeper-release-android',
+};
+const sha = /^[a-f0-9]{40}$/;
+const digest = /^[a-f0-9]{64}$/;
+// Status/check names and bot/app names do not authenticate their workflow
+// origin. No caller/API JSON can mint this module-private capability. The
+// installed canonical/native provenance route is not implemented/verified yet,
+// so collectEvidence deliberately never sets it and authorization fails closed.
+const verifiedCIOrigin = Symbol('verified-installed-ci-origin');
+function requireCondition(condition, code) { if (!condition) throw new Error(code); }
+
+function requestFromEnvironment(env) {
+ const request = {
+ repository: env.GITHUB_REPOSITORY, ref: env.GITHUB_REF, driverSha: env.GITHUB_SHA,
+ sourceSha: env.KEEPER_SOURCE_SHA, releaseRef: env.KEEPER_RELEASE_REF,
+ operation: env.KEEPER_OPERATION, version: env.KEEPER_VERSION,
+ build: env.KEEPER_BUILD, artifactSha256: env.KEEPER_ARTIFACT_SHA256,
+ approvalCommentId: env.KEEPER_APPROVAL_COMMENT_ID,
+ };
+ requireCondition(request.repository === repository && request.ref === 'refs/heads/sprint', 'UNTRUSTED_DRIVER_REF');
+ requireCondition(sha.test(request.driverSha || '') && sha.test(request.sourceSha || ''), 'INVALID_IMMUTABLE_SOURCE');
+ requireCondition(Object.hasOwn(operations, request.operation || ''), 'UNSUPPORTED_OPERATION');
+ requireCondition(/^\d+\.\d+\.\d+$/.test(request.version || '') && request.releaseRef === `release/${request.version}`, 'INVALID_RELEASE_REF_VERSION');
+ requireCondition(/^[1-9]\d{0,9}$/.test(request.build || '') && Number(request.build) <= 2100000000, 'INVALID_BUILD');
+ const upload = request.operation.endsWith('-upload');
+ requireCondition(upload ? digest.test(request.artifactSha256 || '') : request.artifactSha256 === 'pending', 'INVALID_ARTIFACT_BINDING');
+ requireCondition(/^[1-9]\d{0,18}$/.test(request.approvalCommentId || ''), 'INVALID_APPROVAL_REFERENCE');
+ return request;
+}
+
+function approvalBody(request, expiresAt) {
+ const lines = [
+ '## Keeper protected release approval', 'State: APPROVED',
+ `Source commit: ${request.sourceSha}`, `Version: ${request.version}`, `Build: ${request.build}`,
+ `Operation: ${request.operation}`, `Artifact SHA256: ${request.artifactSha256}`,
+ `Workflow commit: ${request.driverSha}`,
+ ];
+ if (request.identitySha256) lines.push(`Signing identity SHA256: ${request.identitySha256}`, `Production config SHA256: ${request.configSha256}`, 'Artifact storage: GitHub Actions public-repository readers (14 days)');
+ return [...lines, `Expires at: ${expiresAt}`].join('\n');
+}
+
+function validateEvidence(request, evidence, now = Date.now()) {
+ requireCondition(evidence.driver?.protected === true && evidence.driver?.commit?.sha === request.driverSha, 'DRIVER_MOVED_OR_UNPROTECTED');
+ requireCondition(evidence.branch?.protected === true && evidence.branch?.commit?.sha === request.sourceSha, 'SOURCE_MOVED_OR_UNPROTECTED');
+ const comment = evidence.comment;
+ requireCondition(comment?.user?.login === 'antuz123' && ['admin', 'maintain', 'write'].includes(evidence.ownerPermission?.permission), 'APPROVAL_AUTHOR_UNAUTHORIZED');
+ const expiration = comment?.body?.match(/\nExpires at: (\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ)$/)?.[1];
+ const expires = Date.parse(expiration);
+ const updated = Date.parse(comment?.updated_at);
+ requireCondition(Number.isFinite(expires) && expires > now && expires <= now + 86400000 && Number.isFinite(updated) && updated <= now && updated >= now - 86400000, 'APPROVAL_STALE_OR_INVALID');
+ requireCondition(comment.body === approvalBody(request, expiration), 'APPROVAL_SCOPE_MISMATCH');
+ const environment = evidence.environment;
+ requireCondition(environment?.name === operations[request.operation] && environment?.can_admins_bypass === false, 'ENVIRONMENT_MISSING_OR_BYPASS_UNVERIFIED');
+ const reviews = environment.protection_rules?.filter(rule => rule.type === 'required_reviewers') || [];
+ requireCondition(reviews.length === 1 && reviews[0].prevent_self_review === true && Array.isArray(reviews[0].reviewers) && reviews[0].reviewers.length > 0, 'INDEPENDENT_ENVIRONMENT_REVIEW_REQUIRED');
+ requireCondition(environment.deployment_branch_policy?.protected_branches === true && environment.deployment_branch_policy?.custom_branch_policies === false, 'ENVIRONMENT_SOURCE_POLICY_UNVERIFIED');
+ const statuses = evidence.statuses;
+ const checks = evidence.checks;
+ requireCondition(statuses?.sha === request.sourceSha && statuses.state === 'success' && Array.isArray(statuses.statuses), 'STATUS_NOT_EXACT_SUCCESS');
+ requireCondition(Number.isSafeInteger(checks?.total_count) && checks.total_count > 0 && checks.total_count <= 100 && checks.total_count === checks.check_runs?.length, 'INCOMPLETE_CHECK_EVIDENCE');
+ requireCondition(checks.check_runs.every(check => check.head_sha === request.sourceSha && check.status === 'completed' && check.conclusion === 'success'), 'CHECKS_NOT_EXACT_SUCCESS');
+ const passedNames = new Set([...statuses.statuses.filter(status => status.state === 'success').map(status => status.context), ...checks.check_runs.map(check => check.name)]);
+ requireCondition(['Tests', 'CodeQL', 'keeper/local-validation'].every(name => passedNames.has(name)), 'REQUIRED_CHECK_MISSING');
+ requireCondition(evidence.manifest?.version === request.version && String(evidence.manifest[request.operation.startsWith('ios-') || request.operation === 'testflight-upload' ? 'iosBuildNumber' : 'androidVersionCode']) === request.build, 'SOURCE_VERSION_BUILD_MISMATCH');
+ requireCondition(validateIntent(evidence.manifest, { now }).length === 0 && validateSources(evidence.manifest, evidence.sources).length === 0, 'RELEASE_SOURCE_PREFLIGHT_FAILED');
+ requireCondition(evidence[verifiedCIOrigin] === true, 'TRUSTED_CI_ORIGIN_NOT_VERIFIED');
+ return {
+ schema: 1, repository, sourceSha: request.sourceSha, driverSha: request.driverSha,
+ operation: request.operation, version: request.version, build: request.build,
+ artifactSha256: request.artifactSha256, environment: operations[request.operation],
+ state: 'AUTHORIZATION_CHECKED_PREPARATION_ONLY',
+ artifact_bytes_and_signature_verified: false,
+ release_worker_implemented: false, execution_allowed: false,
+ };
+}
+
+async function api(endpoint, token) {
+ const response = await fetch(`https://api.github.com/repos/${repository}/${endpoint}`, {
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' },
+ });
+ requireCondition(response.ok, 'READ_ONLY_API_UNAVAILABLE');
+ return response.json();
+}
+
+async function collectEvidence(request, root, token) {
+ const read = name => fs.readFileSync(path.join(root, name), 'utf8');
+ const evidence = {
+ // Only trusted driver code is executed. Candidate files are data.
+ manifest: JSON.parse(read('release/version.json')),
+ sources: {
+ packageText: read('package.json'), android: read('android/app/build.gradle'),
+ ios: read('ios/hexa_keeper.xcodeproj/project.pbxproj'),
+ iosPlists: ['ios/hexa_keeper/Info.plist', 'ios/hexa_keeper_dev-Info.plist'].map(read),
+ },
+ };
+ [evidence.driver, evidence.branch, evidence.comment, evidence.ownerPermission, evidence.environment, evidence.statuses, evidence.checks] = await Promise.all([
+ api('branches/sprint', token),
+ api(`branches/${encodeURIComponent(request.releaseRef)}`, token),
+ api(`issues/comments/${request.approvalCommentId}`, token),
+ api('collaborators/antuz123/permission', token),
+ api(`environments/${operations[request.operation]}`, token),
+ api(`commits/${request.sourceSha}/status?per_page=100`, token),
+ api(`commits/${request.sourceSha}/check-runs?per_page=100`, token),
+ ]);
+ return evidence;
+}
+
+async function main(env = process.env) {
+ const request = requestFromEnvironment(env);
+ requireCondition(env.GH_TOKEN && env.KEEPER_CANDIDATE_PATH, 'DRIVER_CONFIGURATION_MISSING');
+ const evidence = await collectEvidence(request, path.resolve(env.KEEPER_CANDIDATE_PATH), env.GH_TOKEN);
+ const result = validateEvidence(request, evidence);
+ console.log(JSON.stringify(result, null, 2));
+ if (env.GITHUB_OUTPUT) fs.appendFileSync(env.GITHUB_OUTPUT, `environment=${result.environment}\n`);
+}
+
+module.exports = { requestFromEnvironment, approvalBody, validateEvidence, collectEvidence, api };
+if (require.main === module) main().catch(() => {
+ // Never echo tokens, API payloads, user inputs, paths or exception details.
+ console.error('Protected release preparation blocked: source, approval, protection or acceptance evidence is unavailable/invalid. No release action performed.');
+ process.exitCode = 1;
+});
diff --git a/scripts/protected-release-plan.test.cjs b/scripts/protected-release-plan.test.cjs
new file mode 100644
index 0000000000..e6a28430eb
--- /dev/null
+++ b/scripts/protected-release-plan.test.cjs
@@ -0,0 +1,87 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { requestFromEnvironment, approvalBody, validateEvidence } = require('./protected-release-plan.cjs');
+const root = path.join(__dirname, '..');
+const read = name => fs.readFileSync(path.join(root, name), 'utf8');
+const now = Date.parse('2026-10-22T12:00:00Z');
+
+function fixture() {
+ const manifest = JSON.parse(read('release/version.json'));
+ for (const baseline of Object.values(manifest.baselines)) baseline.verifiedAt = '2026-10-22T11:00:00Z';
+ const env = {
+ GITHUB_REPOSITORY: 'KeeperCommunity/bitcoin-keeper', GITHUB_REF: 'refs/heads/sprint',
+ GITHUB_SHA: 'a'.repeat(40), KEEPER_SOURCE_SHA: 'b'.repeat(40),
+ KEEPER_RELEASE_REF: `release/${manifest.version}`, KEEPER_OPERATION: 'testflight-upload',
+ KEEPER_VERSION: manifest.version, KEEPER_BUILD: String(manifest.iosBuildNumber),
+ KEEPER_ARTIFACT_SHA256: 'c'.repeat(64), KEEPER_APPROVAL_COMMENT_ID: '123',
+ };
+ const request = requestFromEnvironment(env);
+ const evidence = {
+ driver: { protected: true, commit: { sha: request.driverSha } },
+ branch: { protected: true, commit: { sha: request.sourceSha } },
+ comment: { user: { login: 'antuz123' }, body: approvalBody(request, '2026-10-22T13:00:00Z'), updated_at: '2026-10-22T11:30:00Z' },
+ ownerPermission: { permission: 'write' },
+ environment: { name: 'keeper-release-ios', can_admins_bypass: false,
+ protection_rules: [{ type: 'required_reviewers', prevent_self_review: true, reviewers: [{ id: 1 }] }],
+ deployment_branch_policy: { protected_branches: true, custom_branch_policies: false } },
+ statuses: { sha: request.sourceSha, state: 'success', statuses: [{ context: 'keeper/local-validation', state: 'success' }] },
+ checks: { total_count: 2, check_runs: ['Tests', 'CodeQL'].map(name => ({ name, head_sha: request.sourceSha, status: 'completed', conclusion: 'success' })) },
+ manifest,
+ sources: { packageText: read('package.json'), android: read('android/app/build.gradle'), ios: read('ios/hexa_keeper.xcodeproj/project.pbxproj'),
+ iosPlists: ['ios/hexa_keeper/Info.plist', 'ios/hexa_keeper_dev-Info.plist'].map(read) },
+ };
+ return { env, request, evidence };
+}
+
+test('complete synthetic names/shape cannot establish trusted CI origin or authorize a plan', () => {
+ const { request, evidence } = fixture();
+ assert.throws(() => validateEvidence(request, evidence, now), /TRUSTED_CI_ORIGIN_NOT_VERIFIED/);
+});
+
+test('forged successful status names, creators and apps never count as authenticated execution evidence', () => {
+ const { request, evidence } = fixture();
+ evidence.statuses.statuses = ['Tests', 'CodeQL', 'keeper/local-validation'].map(context => ({ context, state: 'success', creator: { login: 'github-actions[bot]' } }));
+ evidence.checks = { total_count: 1, check_runs: [{ name: 'Unrelated', head_sha: request.sourceSha, status: 'completed', conclusion: 'success', app: { slug: 'github-actions' } }] };
+ evidence.trustedCIOrigin = true;
+ evidence.originVerified = true;
+ assert.throws(() => validateEvidence(request, evidence, now), /TRUSTED_CI_ORIGIN_NOT_VERIFIED/);
+});
+
+for (const [name, mutate, expectedCode] of [
+ ['moving driver', e => { e.driver.commit.sha = 'd'.repeat(40); }, 'DRIVER_MOVED_OR_UNPROTECTED'],
+ ['moving release source', e => { e.branch.commit.sha = 'd'.repeat(40); }, 'SOURCE_MOVED_OR_UNPROTECTED'],
+ ['unprotected source', e => { e.branch.protected = false; }, 'SOURCE_MOVED_OR_UNPROTECTED'],
+ ['author assertion', e => { e.comment.user.login = 'someone-else'; }, 'APPROVAL_AUTHOR_UNAUTHORIZED'],
+ ['expired owner approval', e => { e.comment.body = e.comment.body.replace('13:00:00Z', '10:00:00Z'); }, 'APPROVAL_STALE_OR_INVALID'],
+ ['wrong artifact approval', e => { e.comment.body = e.comment.body.replace('c'.repeat(64), 'd'.repeat(64)); }, 'APPROVAL_SCOPE_MISMATCH'],
+ ['administrative bypass', e => { e.environment.can_admins_bypass = true; }, 'ENVIRONMENT_MISSING_OR_BYPASS_UNVERIFIED'],
+ ['unverified bypass', e => { delete e.environment.can_admins_bypass; }, 'ENVIRONMENT_MISSING_OR_BYPASS_UNVERIFIED'],
+ ['self approval', e => { e.environment.protection_rules[0].prevent_self_review = false; }, 'INDEPENDENT_ENVIRONMENT_REVIEW_REQUIRED'],
+ ['missing environment', e => { e.environment = null; }, 'ENVIRONMENT_MISSING_OR_BYPASS_UNVERIFIED'],
+ ['stale native status', e => { e.statuses.sha = 'd'.repeat(40); }, 'STATUS_NOT_EXACT_SUCCESS'],
+ ['failed security check', e => { e.checks.check_runs[1].conclusion = 'failure'; }, 'CHECKS_NOT_EXACT_SUCCESS'],
+ ['skipped check', e => { e.checks.check_runs[0].conclusion = 'skipped'; }, 'CHECKS_NOT_EXACT_SUCCESS'],
+ ['wrong-SHA check', e => { e.checks.check_runs[0].head_sha = 'd'.repeat(40); }, 'CHECKS_NOT_EXACT_SUCCESS'],
+ ['incomplete check pagination', e => { e.checks.total_count = 101; }, 'INCOMPLETE_CHECK_EVIDENCE'],
+ ['missing required check', e => { e.checks.check_runs[1].name = 'Other'; }, 'REQUIRED_CHECK_MISSING'],
+ ['stale store counter evidence', e => { e.manifest.baselines.ios.verifiedAt = '2026-10-20T11:00:00Z'; }, 'RELEASE_SOURCE_PREFLIGHT_FAILED'],
+ ['source version mismatch', e => { e.sources.packageText = '{"version":"0.0.0"}'; }, 'RELEASE_SOURCE_PREFLIGHT_FAILED'],
+]) test(`fails closed: ${name}`, () => {
+ const { request, evidence } = fixture();
+ mutate(evidence);
+ assert.throws(() => validateEvidence(request, evidence, now), new RegExp(expectedCode));
+});
+
+test('rejects uninstalled/PR driver, injection, mutable source, invalid artifact and public operation', () => {
+ for (const change of [
+ { GITHUB_REF: 'refs/pull/1/merge' }, { GITHUB_REPOSITORY: 'other/repo' },
+ { KEEPER_SOURCE_SHA: 'sprint' }, { KEEPER_VERSION: '2.6.5;echo secret' },
+ { KEEPER_ARTIFACT_SHA256: 'pending' }, { KEEPER_OPERATION: 'public-release' },
+ ]) {
+ const { env } = fixture();
+ assert.throws(() => requestFromEnvironment({ ...env, ...change }));
+ }
+});
diff --git a/scripts/protected-release-worker.cjs b/scripts/protected-release-worker.cjs
new file mode 100644
index 0000000000..f6cd7ea53c
--- /dev/null
+++ b/scripts/protected-release-worker.cjs
@@ -0,0 +1,126 @@
+#!/usr/bin/env node
+'use strict';
+// Installed trusted driver only. The separate Python adapter has no API authority.
+const fs = require('node:fs');
+const path = require('node:path');
+const os = require('node:os');
+const { execFileSync } = require('node:child_process');
+const gate = require('./protected-release-plan.cjs');
+const hex = /^[a-f0-9]{64}$/;
+function demand(value, code) { if (!value) throw new Error(code); }
+
+function workerRequest(env) {
+ if (env.KEEPER_RELEASE_REQUEST_JSON) {
+ const input = JSON.parse(env.KEEPER_RELEASE_REQUEST_JSON);
+ const fields = { source_sha: 'KEEPER_SOURCE_SHA', release_ref: 'KEEPER_RELEASE_REF', operation: 'KEEPER_OPERATION', version: 'KEEPER_VERSION', build: 'KEEPER_BUILD', artifact_sha256: 'KEEPER_ARTIFACT_SHA256', approval_comment_id: 'KEEPER_APPROVAL_COMMENT_ID', certificate_sha256: 'KEEPER_CERT_SHA256', config_sha256: 'KEEPER_CONFIG_SHA256', artifact_id: 'KEEPER_ARTIFACT_ID' };
+ demand(input && typeof input === 'object' && !Array.isArray(input) && Object.keys(input).length === Object.keys(fields).length && Object.keys(input).every(key => Object.hasOwn(fields, key) && typeof input[key] === 'string'), 'INVALID_REQUEST_JSON');
+ env = { ...env, ...Object.fromEntries(Object.entries(fields).map(([key, name]) => [name, input[key]])) };
+ }
+ const request = gate.requestFromEnvironment(env);
+ request.identitySha256 = env.KEEPER_CERT_SHA256;
+ request.configSha256 = env.KEEPER_CONFIG_SHA256;
+ request.artifactId = env.KEEPER_ARTIFACT_ID;
+ demand(hex.test(request.identitySha256 || '') && hex.test(request.configSha256 || ''), 'EXPECTED_IDENTITIES_REQUIRED');
+ const upload = request.operation.endsWith('-upload');
+ demand(upload ? /^[1-9]\d{0,18}$/.test(request.artifactId || '') : request.artifactId === 'none', 'INVALID_ARTIFACT_REFERENCE');
+ // A signed build executes native project/dependency code with signing material.
+ // Limit that code to the currently installed, protected canonical source.
+ demand(upload || request.sourceSha === request.driverSha, 'SIGNING_REQUIRES_INSTALLED_CANONICAL_SOURCE');
+ return request;
+}
+
+function validateArtifactRun(request, artifact, run, receipt) {
+ demand(!artifact.expired && artifact.workflow_run?.head_sha === request.sourceSha, 'ARTIFACT_SOURCE_MISMATCH');
+ demand(run.head_sha === request.sourceSha && run.head_repository?.full_name === request.repository && run.event === 'workflow_dispatch' && run.conclusion === 'success' && run.path?.split('@')[0] === '.github/workflows/keeper-protected-release-workers.yml', 'UNTRUSTED_ARTIFACT_PRODUCER');
+ const operation = request.operation === 'testflight-upload' ? 'ios-signed-build' : 'android-signed-build';
+ demand(receipt.schema === 1 && receipt.sourceSha === request.sourceSha && receipt.driverSha === request.sourceSha && receipt.operation === operation && receipt.version === request.version && receipt.build === request.build && receipt.artifactSha256 === request.artifactSha256 && receipt.identitySha256 === request.identitySha256 && receipt.configSha256 === request.configSha256 && String(receipt.runId) === String(run.id) && Number(receipt.runAttempt) === run.run_attempt && receipt.signatureVerified === true && receipt.storeUploaded === false, 'SIGNED_RECEIPT_MISMATCH');
+}
+
+function excludeOwnExecutionChecks(request, evidence, run, jobs, current) {
+ demand(String(run.id) === current.runId && run.run_attempt === current.runAttempt && run.head_sha === request.driverSha && run.head_repository?.full_name === request.repository && run.event === 'workflow_dispatch' && run.path?.split('@')[0] === '.github/workflows/keeper-protected-release-workers.yml' && Number.isSafeInteger(run.check_suite_id), 'CURRENT_WORKER_PROVENANCE_UNVERIFIED');
+ demand(Number.isSafeInteger(jobs.total_count) && jobs.total_count <= 100 && jobs.total_count === jobs.jobs?.length, 'INCOMPLETE_CURRENT_ATTEMPT_JOBS');
+ const ownChecks = new Map();
+ for (const job of jobs.jobs) {
+ demand(job.run_id === run.id && job.run_attempt === current.runAttempt && job.head_sha === request.driverSha && ['plan', 'approved-operation'].includes(job.name), 'UNTRUSTED_CURRENT_ATTEMPT_JOB');
+ if (job.check_run_url) {
+ const match = job.check_run_url.match(/^https:\/\/api\.github\.com\/repos\/KeeperCommunity\/bitcoin-keeper\/check-runs\/(\d+)$/);
+ demand(match, 'UNVERIFIED_OWN_CHECK_REFERENCE');
+ ownChecks.set(match[1], job.name);
+ }
+ }
+ const checks = evidence.checks;
+ demand(Number.isSafeInteger(checks?.total_count) && checks.total_count <= 100 && checks.total_count === checks.check_runs?.length, 'INCOMPLETE_SOURCE_CHECKS');
+ const remaining = checks.check_runs.filter(check => !(check.check_suite?.id === run.check_suite_id && ownChecks.get(String(check.id)) === check.name));
+ return { ...evidence, checks: { ...checks, total_count: remaining.length, check_runs: remaining } };
+}
+
+async function freshEvidence(request, root, env) {
+ demand(/^[1-9]\d{0,18}$/.test(env.GITHUB_RUN_ID || '') && /^[1-9]\d{0,8}$/.test(env.GITHUB_RUN_ATTEMPT || ''), 'CURRENT_RUN_REQUIRED');
+ const [evidence, run, jobs] = await Promise.all([
+ gate.collectEvidence(request, root, env.GH_TOKEN),
+ gate.api(`actions/runs/${env.GITHUB_RUN_ID}`, env.GH_TOKEN),
+ gate.api(`actions/runs/${env.GITHUB_RUN_ID}/attempts/${env.GITHUB_RUN_ATTEMPT}/jobs?per_page=100`, env.GH_TOKEN),
+ ]);
+ return excludeOwnExecutionChecks(request, evidence, run, jobs, { runId: env.GITHUB_RUN_ID, runAttempt: Number(env.GITHUB_RUN_ATTEMPT) });
+}
+
+async function main(env = process.env) {
+ const stage = process.argv[2];
+ demand(['request', 'plan', 'revalidate', 'execute'].includes(stage), 'INVALID_STAGE');
+ const request = workerRequest(env);
+ if (env.GITHUB_OUTPUT) fs.appendFileSync(env.GITHUB_OUTPUT, `source_sha=${request.sourceSha}\noperation=${request.operation}\nplatform=${request.operation.startsWith('ios-') || request.operation === 'testflight-upload' ? 'ios' : 'android'}\n`);
+ if (stage === 'request') return;
+ const root = path.resolve(env.KEEPER_CANDIDATE_PATH || '');
+ demand(execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim() === request.sourceSha, 'CHECKOUT_SOURCE_MISMATCH');
+ demand(env.GH_TOKEN, 'READ_ONLY_API_REQUIRED');
+ const evidence = await freshEvidence(request, root, env);
+ const plan = gate.validateEvidence(request, evidence);
+ if (env.GITHUB_OUTPUT) fs.appendFileSync(env.GITHUB_OUTPUT, `environment=${plan.environment}\n`);
+ if (stage !== 'execute') { console.log('Exact source, approval and protection revalidated; no release operation performed.'); return; }
+ demand(env.GITHUB_ACTIONS === 'true' && env.RUNNER_ENVIRONMENT === 'github-hosted', 'HOSTED_PROTECTED_WORKER_REQUIRED');
+ const directory = fs.mkdtempSync(path.join(env.RUNNER_TEMP || os.tmpdir(), 'keeper-release-private-'));
+ fs.chmodSync(directory, 0o700);
+ try {
+ const context = { ...request, runId: env.GITHUB_RUN_ID, runAttempt: Number(env.GITHUB_RUN_ATTEMPT),
+ approvalExpiresAt: evidence.comment.body.match(/\nExpires at: ([^\n]+)$/)[1] };
+ const contextFile = path.join(directory, 'context.json');
+ fs.writeFileSync(contextFile, JSON.stringify(context), { mode: 0o600 });
+ const adapter = path.join(__dirname, 'cloud_release_worker.py');
+ if (request.operation.endsWith('-upload')) {
+ const artifact = await gate.api(`actions/artifacts/${request.artifactId}`, env.GH_TOKEN);
+ const run = await gate.api(`actions/runs/${artifact.workflow_run?.id}`, env.GH_TOKEN);
+ demand(!artifact.expired && artifact.workflow_run?.head_sha === request.sourceSha, 'ARTIFACT_UNAVAILABLE');
+ const response = await fetch(`https://api.github.com/repos/${request.repository}/actions/artifacts/${request.artifactId}/zip`, { headers: { Authorization: `Bearer ${env.GH_TOKEN}`, Accept: 'application/vnd.github+json' } });
+ demand(response.ok, 'ARTIFACT_DOWNLOAD_UNAVAILABLE');
+ const archive = path.join(directory, 'artifact.zip');
+ const handle = fs.openSync(archive, 'wx', 0o600);
+ let total = 0;
+ try { for await (const chunk of response.body) { total += chunk.length; demand(total <= 2 * 1024 ** 3, 'ARTIFACT_TOO_LARGE'); fs.writeSync(handle, chunk); } }
+ finally { fs.closeSync(handle); }
+ const receiptText = execFileSync('python3', [adapter, 'unpack', contextFile, directory], { env: { PATH: env.PATH }, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+ validateArtifactRun(request, artifact, run, JSON.parse(receiptText));
+ context.sourceRunId = run.id;
+ context.sourceRunAttempt = run.run_attempt;
+ fs.writeFileSync(contextFile, JSON.stringify(context), { mode: 0o600 });
+ // Download/preparation may take time. Recheck immediately before loading
+ // the upload adapter; do not reuse a pre-environment/pre-download plan.
+ gate.validateEvidence(request, await freshEvidence(request, root, env));
+ }
+ const executionEnv = { ...env, KEEPER_PRIVATE_DIRECTORY: directory };
+ delete executionEnv.GH_TOKEN;
+ delete executionEnv.GITHUB_TOKEN;
+ execFileSync('python3', [adapter, 'execute', contextFile, root], { env: executionEnv, stdio: ['ignore', 'pipe', 'pipe'] });
+ if (env.GITHUB_OUTPUT) fs.appendFileSync(env.GITHUB_OUTPUT, `artifact_dir=${path.join(env.RUNNER_TEMP, 'keeper-release-output')}\n`);
+ console.log('Approved operation completed; inspect the bounded signed-build or upload-command receipt. No further operation follows automatically.');
+ } finally { fs.rmSync(directory, { recursive: true, force: true }); }
+}
+
+module.exports = { workerRequest, validateArtifactRun, excludeOwnExecutionChecks };
+if (require.main === module) main().catch(error => {
+ try {
+ const failure = JSON.parse(error.stderr?.toString() || '{}');
+ if (failure.state === 'FAILED' && ['input-validation', 'identity-validation', 'source-preflight', 'config-validation', 'native-build', 'signing-cleanup', 'artifact-verification', 'upload-command', 'receipt'].includes(failure.stage)) console.error(`Platform stage failed: ${failure.stage}; signing cleanup failed: ${failure.cleanupFailed === true}`);
+ } catch { /* Never print raw native/provider errors. */ }
+ console.error('Protected release worker blocked/failed; inspect the stage and setup privately. No subsequent operation was executed.');
+ process.exitCode = 1;
+});
diff --git a/scripts/protected-release-worker.test.cjs b/scripts/protected-release-worker.test.cjs
new file mode 100644
index 0000000000..284fa3d8ce
--- /dev/null
+++ b/scripts/protected-release-worker.test.cjs
@@ -0,0 +1,99 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { workerRequest, validateArtifactRun, excludeOwnExecutionChecks } = require('./protected-release-worker.cjs');
+const { approvalBody } = require('./protected-release-plan.cjs');
+function fixture(operation = 'ios-signed-build') {
+ const source = 'a'.repeat(40);
+ const input = { source_sha: source, release_ref: 'release/2.6.5', operation, version: '2.6.5', build: '621',
+ artifact_sha256: operation.endsWith('-upload') ? 'b'.repeat(64) : 'pending', approval_comment_id: '123',
+ certificate_sha256: 'c'.repeat(64), config_sha256: 'd'.repeat(64), artifact_id: operation.endsWith('-upload') ? '234' : 'none' };
+ const env = { GITHUB_REPOSITORY: 'KeeperCommunity/bitcoin-keeper', GITHUB_REF: 'refs/heads/sprint', GITHUB_SHA: source,
+ KEEPER_RELEASE_REQUEST_JSON: JSON.stringify(input) };
+ const request = workerRequest(env);
+ return { input, env, request };
+}
+test('signed build requires current canonical installed source and exact metadata-only request', () => {
+ const { input, env } = fixture();
+ input.source_sha = 'f'.repeat(40);
+ assert.throws(() => workerRequest({ ...env, KEEPER_RELEASE_REQUEST_JSON: JSON.stringify(input) }));
+ input.source_sha = env.GITHUB_SHA;
+ input.arbitrary_secret = 'never-pass-through';
+ assert.throws(() => workerRequest({ ...env, KEEPER_RELEASE_REQUEST_JSON: JSON.stringify(input) }));
+});
+test('upload cannot reuse pending artifact or unapproved signing identity/config', () => {
+ const { input, env } = fixture('testflight-upload');
+ for (const change of [{ artifact_sha256: 'pending' }, { certificate_sha256: '' }, { config_sha256: 'secret-value' }, { artifact_id: 'moving-name' }]) {
+ assert.throws(() => workerRequest({ ...env, KEEPER_RELEASE_REQUEST_JSON: JSON.stringify({ ...input, ...change }) }));
+ }
+});
+test('receipt binds identity, config and explicit signed artifact storage approval', () => {
+ const { request } = fixture();
+ const body = approvalBody(request, '2026-10-22T13:00:00Z');
+ assert.ok(body.includes(`Signing identity SHA256: ${request.identitySha256}`));
+ assert.ok(body.includes(`Production config SHA256: ${request.configSha256}`));
+ assert.ok(body.includes('Artifact storage: GitHub Actions public-repository readers (14 days)'));
+});
+function artifactFixture() {
+ const { request } = fixture('testflight-upload');
+ const artifact = { expired: false, workflow_run: { head_sha: request.sourceSha } };
+ const run = { id: 456, run_attempt: 2, head_sha: request.sourceSha, head_repository: { full_name: request.repository },
+ event: 'workflow_dispatch', conclusion: 'success', path: '.github/workflows/keeper-protected-release-workers.yml' };
+ const receipt = { schema: 1, sourceSha: request.sourceSha, driverSha: request.sourceSha, operation: 'ios-signed-build',
+ version: request.version, build: request.build, artifactSha256: request.artifactSha256, identitySha256: request.identitySha256,
+ configSha256: request.configSha256, runId: '456', runAttempt: 2, signatureVerified: true, storeUploaded: false };
+ return { request, artifact, run, receipt };
+}
+test('accepts only exact completed canonical signing producer receipt', () => {
+ const { request, artifact, run, receipt } = artifactFixture();
+ assert.doesNotThrow(() => validateArtifactRun(request, artifact, run, receipt));
+});
+for (const [name, mutate] of [
+ ['expired artifact', f => { f.artifact.expired = true; }],
+ ['wrong source', f => { f.artifact.workflow_run.head_sha = 'f'.repeat(40); }],
+ ['PR producer', f => { f.run.event = 'pull_request'; }],
+ ['wrong workflow', f => { f.run.path = '.github/workflows/other.yml'; }],
+ ['failed producer', f => { f.run.conclusion = 'failure'; }],
+ ['wrong run attempt', f => { f.receipt.runAttempt = 1; }],
+ ['wrong artifact digest', f => { f.receipt.artifactSha256 = 'e'.repeat(64); }],
+ ['unsigned metadata', f => { f.receipt.signatureVerified = false; }],
+ ['reused upload receipt', f => { f.receipt.storeUploaded = true; }],
+ ['wrong config', f => { f.receipt.configSha256 = 'e'.repeat(64); }],
+]) test(`artifact gate rejects ${name}`, () => {
+ const f = artifactFixture(); mutate(f);
+ assert.throws(() => validateArtifactRun(f.request, f.artifact, f.run, f.receipt));
+});
+
+function selfCheckFixture() {
+ const { request } = fixture();
+ const current = { runId: '1234', runAttempt: 2 };
+ const run = { id: 1234, run_attempt: 2, head_sha: request.driverSha, head_repository: { full_name: request.repository },
+ event: 'workflow_dispatch', path: '.github/workflows/keeper-protected-release-workers.yml', check_suite_id: 5678 };
+ const job = { run_id: 1234, run_attempt: 2, head_sha: request.driverSha, name: 'plan', check_run_url: 'https://api.github.com/repos/KeeperCommunity/bitcoin-keeper/check-runs/789' };
+ const checks = [
+ { id: 789, name: 'plan', check_suite: { id: 5678 }, head_sha: request.sourceSha, status: 'in_progress', conclusion: null },
+ { id: 888, name: 'Tests', check_suite: { id: 9999 }, head_sha: request.sourceSha, status: 'completed', conclusion: 'success' },
+ ];
+ return { request, current, run, jobs: { total_count: 1, jobs: [job] }, evidence: { checks: { total_count: checks.length, check_runs: checks } } };
+}
+test('excludes only this trusted run/attempt pending check; keeps required independent success', () => {
+ const f = selfCheckFixture();
+ const result = excludeOwnExecutionChecks(f.request, f.evidence, f.run, f.jobs, f.current);
+ assert.deepEqual(result.checks.check_runs.map(check => check.name), ['Tests']);
+ assert.equal(result.checks.total_count, 1);
+});
+for (const conclusion of [null, 'failure']) test(`retains unrelated ${conclusion || 'pending'} checks`, () => {
+ const f = selfCheckFixture();
+ f.evidence.checks.check_runs.push({ id: 999, name: 'Other', check_suite: { id: 9999 }, head_sha: f.request.sourceSha, status: conclusion ? 'completed' : 'in_progress', conclusion });
+ f.evidence.checks.total_count++;
+ const result = excludeOwnExecutionChecks(f.request, f.evidence, f.run, f.jobs, f.current);
+ assert.ok(result.checks.check_runs.some(check => check.name === 'Other' && check.conclusion === conclusion));
+});
+test('old attempt, mismatched producer, untrusted check URL and incomplete pagination fail closed', () => {
+ for (const mutate of [f => { f.run.run_attempt = 1; }, f => { f.jobs.jobs[0].run_attempt = 1; },
+ f => { f.run.event = 'pull_request'; }, f => { f.jobs.jobs[0].check_run_url = 'https://other.invalid/check-runs/789'; },
+ f => { f.evidence.checks.total_count = 101; }]) {
+ const f = selfCheckFixture(); mutate(f);
+ assert.throws(() => excludeOwnExecutionChecks(f.request, f.evidence, f.run, f.jobs, f.current));
+ }
+});
diff --git a/scripts/release-version.cjs b/scripts/release-version.cjs
new file mode 100644
index 0000000000..de30abd6da
--- /dev/null
+++ b/scripts/release-version.cjs
@@ -0,0 +1,170 @@
+#!/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;
+ }
+ // 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);
+ 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..c34db5dee9
--- /dev/null
+++ b/scripts/release-version.test.cjs
@@ -0,0 +1,87 @@
+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('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')));
+});
+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/run-automatic-backup-genuine.cjs b/scripts/run-automatic-backup-genuine.cjs
new file mode 100644
index 0000000000..a72bf4cc0d
--- /dev/null
+++ b/scripts/run-automatic-backup-genuine.cjs
@@ -0,0 +1,56 @@
+// This matrix requires the pinned paired Relay, a real native Realm binding
+// and disposable loopback Mongo. Missing prerequisites are a failing check.
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const relaySha = '838049e537e07eb646a2a0393eb969fba43d0739';
+const root = path.resolve(__dirname, '..');
+const fixture = process.env.KEEPER_RELAY_FIXTURE_MODULE;
+assert.equal(process.versions.node.split('.')[0], '22', 'Run the genuine automatic backup matrix with Node 22');
+assert.ok(fixture, 'Set KEEPER_RELAY_FIXTURE_MODULE to the pinned Relay tests/support/automaticBackupHttpFixture.cjs');
+const filename = fs.realpathSync(fixture);
+const checkout = path.dirname(path.dirname(path.dirname(filename)));
+assert.equal(path.relative(checkout, filename), 'tests/support/automaticBackupHttpFixture.cjs');
+const revision = spawnSync('git', ['-C', checkout, 'rev-parse', 'HEAD'], { encoding: 'utf8' });
+assert.equal(revision.status, 0, 'The Relay fixture must be in a Git checkout');
+assert.equal(revision.stdout.trim(), relaySha, `Use paired Relay commit ${relaySha}`);
+const clean = spawnSync('git', ['-C', checkout, 'diff', '--quiet', 'HEAD'], { encoding: 'utf8' });
+assert.equal(clean.status, 0, 'The pinned Relay checkout must have no tracked changes');
+
+const mongoUrl = new URL(process.env.BACKUP_TEST_MONGO_URL || 'mongodb://127.0.0.1:27058');
+assert.equal(mongoUrl.protocol, 'mongodb:');
+assert.ok(['127.0.0.1', 'localhost'].includes(mongoUrl.hostname), 'The matrix only accepts loopback Mongo');
+assert.equal(mongoUrl.port, '27058', 'Use the disposable keeperQA replica set on port 27058');
+assert.ok(!mongoUrl.username && !mongoUrl.password, 'The disposable matrix does not accept credentials');
+
+const Realm = require('realm');
+const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-native-realm-prerequisite-'));
+let probe;
+try {
+ probe = new Realm({
+ path: path.join(directory, 'probe.realm'), inMemory: true,
+ schema: [{ name: 'NativeProbe', primaryKey: 'id', properties: { id: 'string', value: 'int' } }],
+ });
+ probe.write(() => probe.create('NativeProbe', { id: 'native', value: 1 }));
+ assert.equal(probe.objectForPrimaryKey('NativeProbe', 'native').value, 1);
+} finally {
+ probe?.close();
+ Realm.shutdown();
+ fs.rmSync(directory, { recursive: true, force: true });
+}
+
+const matrices = fs.readdirSync(path.join(root, 'tests/recovery'))
+ .filter(filename => filename.endsWith('.integration.cjs')).sort();
+for (const required of ['automaticWriteRealmRelay.integration.cjs',
+ 'automaticLabelProducers.integration.cjs', 'automaticUpgradeProducer.integration.cjs',
+ 'automaticWalletProducer.integration.cjs', 'automaticUSDTProducer.integration.cjs',
+ 'automaticSignerProducer.integration.cjs', 'automaticRecoveryRestore.integration.cjs'])
+ assert.ok(matrices.includes(required), `Missing genuine production matrix ${required}`);
+const result = spawnSync(process.execPath, ['--test', ...matrices.map(filename => `tests/recovery/${filename}`)], {
+ cwd: root, stdio: 'inherit',
+ env: { ...process.env, KEEPER_RELAY_FIXTURE_MODULE: filename, BACKUP_TEST_MONGO_URL: mongoUrl.toString() },
+});
+process.exit(result.status ?? 1);
diff --git a/scripts/run-protected-backup-genuine.cjs b/scripts/run-protected-backup-genuine.cjs
new file mode 100644
index 0000000000..cc556cc60c
--- /dev/null
+++ b/scripts/run-protected-backup-genuine.cjs
@@ -0,0 +1,101 @@
+// Separate opt-in protected-protocol proof. The public v2 lane and its pins stay
+// independent. This guard contains only reviewed identities, never backend code.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { createRequire } = require('node:module');
+
+const BACKEND_COMMIT = '7693ce4bfffcadb5fb71d6478a8befc8e533a844';
+const BACKEND_FILES = Object.freeze({
+ 'package.json': '091bbd47dc459a13276b9dee0122b54ef002c45442771b0d06a408d013ea9988',
+ 'yarn.lock': 'b989c1197f6ddc9530d400a354bab42af8974ac4687f0ba0a178cb2f787b0321',
+ 'src/services/protectedBackupAuth.ts': 'b45fbfe0b1481a52a0158b9cbca79a619e14484e254064ef8efb5155ddfa7ecf',
+ 'src/services/protectedBackup.ts': '087f2d5190d9bcd68ba3a529712d7ca60b06fd487f1f021c0c4907ebd6235a76',
+ 'src/routes/protectedBackup.ts': '6eb2f8ba2c70cc459c88068f81a6dae2e6efa507468c84cafb2a7508fb78bcfb',
+ 'src/routes/routes.ts': '245fec3b717fab83957bc1690cd9d76395c031b0c2525414846ba55081ec2183',
+ 'src/services/backupSnapshot.ts': '3c097222970c88d1d9af154c6cc50bf532f0d1559050af65fafecf2aa59ac187',
+ 'src/services/bhr.ts': '72736ddaca020d293adee9b430343493e07123dfbc54b301914e5d766092df15',
+ 'src/db.ts': '52455dc9472a713afc538189db541ced108e1a0dcb4246b824da0bff120f8992',
+ 'tests/support/protectedBackupFixture.cjs': '3ce114525e34bea75e515df596b10da82a73becadc253e2ecae223cf3d37d38c',
+ 'tests/support/protectedBackupClient.cjs': 'dee3441f65defc0cd5dbbc282bc179210edfa7b544b4db41e501468bece8022f',
+ 'tests/disposableMongo.cjs': 'a9dd8d12f37aafef09003ef47369cb7416692fd07e28ad96c25a0533cf99ee96',
+});
+
+function supportedNode(version) {
+ const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(version);
+ return !!match && Number(match[1]) === 22 &&
+ (Number(match[2]) > 23 || (Number(match[2]) === 23 && Number(match[3]) >= 3));
+}
+
+function disposableMongoUrl(value) {
+ const url = new URL(value || 'mongodb://127.0.0.1:27038');
+ assert.equal(url.protocol, 'mongodb:', 'Use a disposable loopback MongoDB replica');
+ assert.ok(['127.0.0.1', 'localhost'].includes(url.hostname), 'Hosted MongoDB is forbidden in this proof');
+ assert.equal(url.port, '27038', 'Use the separately approved keeperQA fixture on port 27038');
+ assert.ok(!url.username && !url.password, 'This proof does not accept credentials');
+ assert.ok(['', '/'].includes(url.pathname) && !url.search && !url.hash,
+ 'Pass only the loopback server address; the fixture chooses its own database');
+ return url.toString();
+}
+
+function checkedBackend(checkout) {
+ assert.ok(checkout, 'Set KEEPER_PROTECTED_RELAY_CHECKOUT to the separately obtained exact reviewed backend checkout');
+ const directory = fs.realpathSync(checkout);
+ const git = (...arguments_) => spawnSync('git', ['-C', directory, ...arguments_], { encoding: 'utf8' });
+ const head = git('rev-parse', 'HEAD');
+ assert.equal(head.status, 0, 'The protected fixture must be in a Git checkout');
+ assert.equal(head.stdout.trim(), BACKEND_COMMIT, `Use exact reviewed backend ${BACKEND_COMMIT}`);
+ assert.equal(git('diff', '--quiet', 'HEAD').status, 0, 'The reviewed backend must have no tracked changes');
+ for (const [relative, expected] of Object.entries(BACKEND_FILES)) {
+ const filename = path.join(directory, relative);
+ assert.equal(fs.realpathSync(filename), filename, 'The fixed backend inputs must not be symlink aliases');
+ assert.equal(crypto.createHash('sha256').update(fs.readFileSync(filename)).digest('hex'), expected,
+ `Reviewed backend input differs: ${relative}`);
+ }
+ const requireBackend = createRequire(path.join(directory, 'package.json'));
+ for (const [name, version] of [['mongoose', '5.13.20'], ['mongodb', '3.7.4']])
+ assert.equal(requireBackend(`${name}/package.json`).version, version, 'Use the reviewed frozen native driver lane');
+ return directory;
+}
+
+function nativeRealmPrerequisite() {
+ const Realm = require('realm');
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-protected-realm-prerequisite-'));
+ const filename = path.join(directory, 'probe.realm');
+ const options = { path: filename, encryptionKey: Buffer.alloc(64, 7),
+ schema: [{ name: 'NativeProbe', primaryKey: 'id', properties: { id: 'string', value: 'int' } }] };
+ let realm;
+ try {
+ realm = new Realm(options);
+ realm.write(() => realm.create('NativeProbe', { id: 'native', value: 1 }));
+ realm.close();
+ realm = new Realm(options);
+ assert.equal(realm.objectForPrimaryKey('NativeProbe', 'native').value, 1,
+ 'Actual native encrypted Realm must commit and reopen');
+ } finally {
+ if (realm && !realm.isClosed) realm.close();
+ Realm.shutdown();
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+}
+
+function main() {
+ assert.ok(supportedNode(process.versions.node), 'Use Node22.23.3 or a later22.x patch for the protected proof');
+ const checkout = checkedBackend(process.env.KEEPER_PROTECTED_RELAY_CHECKOUT);
+ const mongo = disposableMongoUrl(process.env.BACKUP_TEST_MONGO_URL);
+ nativeRealmPrerequisite();
+ const app = path.resolve(__dirname, '..');
+ const test = 'tests/recovery/protectedWriteRealmRelay.proof.cjs';
+ assert.ok(fs.existsSync(path.join(app, test)), 'Missing separate protected production proof');
+ const result = spawnSync(process.execPath, ['--test', test], {
+ cwd: app, stdio: 'inherit', env: { ...process.env,
+ KEEPER_PROTECTED_RELAY_CHECKOUT: checkout, BACKUP_TEST_MONGO_URL: mongo },
+ });
+ process.exitCode = result.status ?? 1;
+}
+
+module.exports = { BACKEND_COMMIT, BACKEND_FILES, supportedNode, disposableMongoUrl, checkedBackend };
+if (require.main === module) main();
diff --git a/scripts/run-protected-backup-genuine.test.cjs b/scripts/run-protected-backup-genuine.test.cjs
new file mode 100644
index 0000000000..f8bb6fed80
--- /dev/null
+++ b/scripts/run-protected-backup-genuine.test.cjs
@@ -0,0 +1,37 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { test } = require('node:test');
+const { supportedNode, disposableMongoUrl, checkedBackend } = require('./run-protected-backup-genuine.cjs');
+
+test('protected proof requires the reviewed current22 runtime without accepting other majors or prereleases', () => {
+ for (const version of ['22.23.3', 'v22.23.4', '22.24.0']) assert.equal(supportedNode(version), true);
+ for (const version of ['22.16.0', '22.23.2', '20.23.3', '23.0.0', '22.23.3-rc.1', 'invalid'])
+ assert.equal(supportedNode(version), false);
+});
+
+test('protected proof refuses hosted, credentialed, aliased-port or database-selecting Mongo targets', () => {
+ assert.equal(disposableMongoUrl('mongodb://127.0.0.1:27038'), 'mongodb://127.0.0.1:27038');
+ assert.equal(disposableMongoUrl('mongodb://localhost:27038/'), 'mongodb://localhost:27038/');
+ for (const address of ['mongodb://example.invalid:27038', 'mongodb://user:pass@127.0.0.1:27038',
+ 'mongodb+srv://localhost', 'mongodb://127.0.0.1:27028', 'mongodb://127.0.0.1:27038/production',
+ 'mongodb://127.0.0.1:27038/?replicaSet=elsewhere', 'mongodb://127.0.0.1:27038/#fragment'])
+ assert.throws(() => disposableMongoUrl(address));
+});
+
+test('an unreviewed local checkout is rejected before any fixture source can load', () => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-protected-guard-'));
+ try {
+ for (const args of [['init', '--quiet'], ['-c', 'core.hooksPath=/dev/null', '-c', 'commit.gpgsign=false',
+ '-c', 'user.name=Fixture', '-c', 'user.email=fixture@invalid',
+ 'commit', '--quiet', '--allow-empty', '-m', 'Disposable unreviewed fixture']]) {
+ const result = spawnSync('git', ['-C', directory, ...args], { encoding: 'utf8' });
+ assert.equal(result.status, 0, 'Create only an owned disposable local Git fixture');
+ }
+ assert.throws(() => checkedBackend(directory), /Use exact reviewed backend/);
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
diff --git a/scripts/run-protected-upgrade-regression.cjs b/scripts/run-protected-upgrade-regression.cjs
new file mode 100644
index 0000000000..b660c09649
--- /dev/null
+++ b/scripts/run-protected-upgrade-regression.cjs
@@ -0,0 +1,57 @@
+// Supplemental #7066 upgrade regression against the current selected Relay.
+// Keep the historical proof runner and its reviewed source pins unchanged.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { createRequire } = require('node:module');
+const { spawnSync } = require('node:child_process');
+const historical = require('./run-protected-backup-genuine.cjs');
+
+const BACKEND_COMMIT = '29597b27eeeb299205bf7d0555db0a90c38cc4be';
+// Every other fixture input is byte-identical to the historical reviewed pin.
+const BACKEND_FILES = Object.freeze({ ...historical.BACKEND_FILES,
+ 'src/services/protectedBackup.ts': '1487da3778fcc39efc7d453e5ddcbb944d3b8c2912c04632dbb3076f761decd4',
+});
+
+function checkedCurrentBackend(checkout) {
+ assert.ok(checkout, 'Set KEEPER_PROTECTED_RELAY_CHECKOUT to the exact current Relay checkout');
+ const directory = fs.realpathSync(checkout);
+ const git = (...args) => spawnSync('git', ['-C', directory, ...args], { encoding: 'utf8' });
+ const head = git('rev-parse', 'HEAD');
+ assert.equal(head.status, 0, 'The current Relay fixture must be a Git checkout');
+ assert.equal(head.stdout.trim(), BACKEND_COMMIT, `Use current Relay ${BACKEND_COMMIT}`);
+ assert.equal(git('diff', '--quiet', 'HEAD').status, 0, 'Current Relay tracked files must be clean');
+ for (const [relative, expected] of Object.entries(BACKEND_FILES)) {
+ const filename = path.join(directory, relative);
+ assert.equal(fs.realpathSync(filename), filename, 'Fixed Relay inputs must not be symlink aliases');
+ assert.equal(crypto.createHash('sha256').update(fs.readFileSync(filename)).digest('hex'), expected,
+ `Current Relay input differs: ${relative}`);
+ }
+ const requireBackend = createRequire(path.join(directory, 'package.json'));
+ for (const [name, version] of [['mongoose', '5.13.20'], ['mongodb', '3.7.4']])
+ assert.equal(requireBackend(`${name}/package.json`).version, version, 'Use frozen native driver inputs');
+ return directory;
+}
+
+// The fixture imports its admission function through this module export. Only
+// admission changes: production app/backend code, crypto, HTTP and Realm stay real.
+// This opt-in process never updates the historical runner or production config.
+historical.checkedBackend = checkedCurrentBackend;
+
+function main() {
+ assert.ok(historical.supportedNode(process.versions.node), 'Use Node22.23.3 or a later22.x patch');
+ const checkout = checkedCurrentBackend(process.env.KEEPER_PROTECTED_RELAY_CHECKOUT);
+ const mongo = historical.disposableMongoUrl(process.env.BACKUP_TEST_MONGO_URL);
+ const app = path.resolve(__dirname, '..');
+ const test = path.join(app, 'tests/recovery/protectedUpgrade7066.proof.cjs');
+ assert.ok(fs.existsSync(test), 'Missing focused protected-upgrade regression');
+ const result = spawnSync(process.execPath, ['--require', __filename, '--test', test], {
+ cwd: app, stdio: 'inherit', env: { ...process.env,
+ KEEPER_PROTECTED_RELAY_CHECKOUT: checkout, BACKUP_TEST_MONGO_URL: mongo },
+ });
+ process.exitCode = result.status ?? 1;
+}
+
+module.exports = { BACKEND_COMMIT, BACKEND_FILES, checkedCurrentBackend };
+if (require.main === module) main();
diff --git a/scripts/test_check_android_16kb.py b/scripts/test_check_android_16kb.py
new file mode 100644
index 0000000000..39db7f238f
--- /dev/null
+++ b/scripts/test_check_android_16kb.py
@@ -0,0 +1,209 @@
+"""Byte-level regressions for the static Android 16 KB evidence checker."""
+
+import importlib.util
+import io
+import json
+import pathlib
+import struct
+import subprocess
+import sys
+import tempfile
+import unittest
+import warnings
+import zipfile
+from contextlib import redirect_stdout
+from unittest.mock import patch
+
+SPEC = importlib.util.spec_from_file_location("check_android_16kb", pathlib.Path(__file__).with_name("check-android-16kb.py"))
+CHECK = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(CHECK)
+
+
+def elf(loads=None, relros=None, machine=183):
+ loads = loads or [(0, 0, 0x100, 0x100, 0x10000), (0x10000, 0x30000, 0x8000, 0x9000, 0x10000)]
+ relros = [(0x10000, 0x30000, 0x6000, 0x6000)] if relros is None else relros
+ headers = [(1, 6, offset, vaddr, vaddr, filesz, memsz, align) for offset, vaddr, filesz, memsz, align in loads]
+ headers += [(CHECK.PT_GNU_RELRO, 4, offset, vaddr, vaddr, filesz, memsz, 1) for offset, vaddr, filesz, memsz in relros]
+ size = max(64 + 56 * len(headers), *(x[2] + x[5] for x in headers))
+ data = bytearray(size)
+ data[:16] = b"\x7fELF" + bytes((2, 1, 1)) + bytes(9)
+ struct.pack_into(" exception
+ @error&.call(name, exception)
+ raise
+ end
+
+ def sh(command, script, *arguments)
+ kind = case [command, File.basename(script)]
+ when ['node', 'release-version.cjs'] then :preflight
+ when ['node', 'verify-channel-config.cjs'] then :config
+ when ['python3', 'verify-release-artifact.py'] then :artifact
+ else raise "Unexpected shell action: #{command}"
+ end
+ @events << [kind, script, *arguments]
+ raise "Simulated #{kind} failure" if @failure == kind || @failure == arguments.first
+ end
+
+ def build_app(options)
+ @events << [:build_app, options]
+ emit_artifact(:ipa, SharedValues::IPA_OUTPUT_PATH)
+ end
+
+ def gradle(options)
+ @events << [:gradle, options]
+ case options[:task]
+ when 'bundle' then emit_artifact(:aab, SharedValues::GRADLE_AAB_OUTPUT_PATH)
+ when 'assemble' then emit_artifact(:apk, SharedValues::GRADLE_APK_OUTPUT_PATH)
+ when 'clean' then nil
+ else raise "Unexpected Gradle task: #{options[:task]}"
+ end
+ end
+
+ def get_build_number
+ 620
+ end
+
+ def android_get_version_code
+ 627
+ end
+
+ def method_missing(name, *arguments)
+ return @events << [name, *arguments] if (SIGNING_ACTIONS + DISTRIBUTION_ACTIONS).include?(name)
+
+ super
+ end
+
+ def respond_to_missing?(name, include_private = false)
+ (SIGNING_ACTIONS + DISTRIBUTION_ACTIONS).include?(name) || super
+ end
+
+ private
+
+ def emit_artifact(extension, key)
+ return if @missing_output == extension
+
+ path = File.join(@root, "current.#{extension}")
+ File.write(path, 'synthetic artifact')
+ Actions.lane_context[key] = path
+ end
+end
+
+class FastlaneBuildOnlyTest < Minitest::Test
+ ENV_KEYS = %w[ENVFILE KEEPER_NOTIFY_SLACK KEEPER_ANDROID_KEYSTORE STORE_PASSWORD KEY_PASSWORD KEY_ALIAS].freeze
+
+ def setup
+ @saved_env = ENV_KEYS.to_h { |key| [key, ENV[key]] }
+ @root = Dir.mktmpdir('keeper-fastlane-test-')
+ File.write(File.join(@root, '.env.production'), 'synthetic reviewed config')
+ FileUtils.mkdir_p(File.join(@root, 'android', 'app'))
+ File.write(File.join(@root, 'android', 'app', 'release.keystore'), 'synthetic keystore')
+ ENV['KEEPER_NOTIFY_SLACK'] = '1' # build_only must ignore even the opt-in.
+ ENV.delete('KEEPER_ANDROID_KEYSTORE')
+ %w[STORE_PASSWORD KEY_PASSWORD KEY_ALIAS].each { |key| ENV[key] = 'synthetic' }
+ Actions.lane_context.clear
+ end
+
+ def teardown
+ @saved_env.each { |key, value| value.nil? ? ENV.delete(key) : ENV[key] = value }
+ Actions.lane_context.clear
+ FileUtils.remove_entry(@root)
+ end
+
+ def distribution_events(fastlane)
+ fastlane.events.select { |event| FakeFastlane::DISTRIBUTION_ACTIONS.include?(event.first) }
+ end
+
+ def test_ios_selector_rejects_an_unreviewed_environment
+ fastlane = FakeFastlane.new(:ios, @root)
+ selector = File.join(@root, 'envfile-selector')
+ File.write(selector, File.join(@root, 'other.env'))
+ assert_match(/override the reviewed/, assert_raises(RuntimeError) {
+ fastlane.verify_envfile_selector!(File.join(@root, '.env.production'), selector)
+ }.message)
+ File.write(selector, File.join(@root, '.env.production'))
+ fastlane.verify_envfile_selector!(File.join(@root, '.env.production'), selector)
+ end
+
+ %i[ios android].each do |platform|
+ define_method("test_#{platform}_build_only_verifies_current_production_artifacts_without_distribution") do
+ fastlane = FakeFastlane.new(platform, @root)
+ fastlane.run(:build_only)
+ assert_empty distribution_events(fastlane)
+ assert_equal %i[preflight config], fastlane.events.take(2).map(&:first)
+ assert_equal ['release-check'], fastlane.events.first.drop(2)
+ assert_equal File.join(@root, '.env.production'), ENV['ENVFILE']
+ artifacts = fastlane.events.select { |event| event.first == :artifact }.map(&:last)
+ extensions = platform == :ios ? %w[ipa] : %w[aab apk]
+ assert_equal extensions.map { |ext| File.join(@root, "current.#{ext}") }, artifacts
+ if platform == :ios
+ options = fastlane.events.find { |event| event.first == :build_app }.last
+ assert_equal 'hexa_keeper', options[:scheme]
+ assert_equal 'app-store', options[:export_method]
+ assert_equal true, options[:clean]
+ assert_equal({ 'io.hexawallet.keeper' => 'io.hexawallet.keeper AppStore' }, options[:export_options][:provisioningProfiles])
+ else
+ builds = fastlane.events.select { |event| event.first == :gradle }.map(&:last)
+ assert_equal %w[clean bundle assemble], builds.map { |options| options[:task] }
+ assert builds.drop(1).all? { |options| options[:build_type] == 'productionRelease' }
+ assert builds.drop(1).all? { |options| options[:properties]['android.injected.signing.store.file'] == File.join(@root, 'android', 'app', 'release.keystore') }
+ end
+ end
+
+ %i[preflight config artifact].each do |failure|
+ define_method("test_#{platform}_build_only_stops_on_#{failure}_failure_without_distribution") do
+ fastlane = FakeFastlane.new(platform, @root)
+ fastlane.failure = failure
+ assert_raises(RuntimeError) { fastlane.run(:build_only) }
+ assert_empty distribution_events(fastlane)
+ if failure != :artifact
+ assert_empty fastlane.events.select { |event| (FakeFastlane::SIGNING_ACTIONS + %i[build_app gradle artifact]).include?(event.first) }
+ end
+ end
+ end
+
+ define_method("test_#{platform}_build_only_rejects_missing_reviewed_environment_without_distribution") do
+ File.delete(File.join(@root, '.env.production'))
+ fastlane = FakeFastlane.new(platform, @root)
+ assert_match(/Missing reviewed/, assert_raises(RuntimeError) { fastlane.run(:build_only) }.message)
+ assert_equal [:preflight], fastlane.events.map(&:first)
+ assert_empty distribution_events(fastlane)
+ end
+
+ define_method("test_#{platform}_live_still_uploads_only_after_verification") do
+ fastlane = FakeFastlane.new(platform, @root)
+ fastlane.run(:live)
+ upload = platform == :ios ? :upload_to_testflight : :upload_to_play_store
+ assert_equal 1, fastlane.events.count { |event| event.first == upload }
+ artifact_positions = fastlane.events.each_index.select { |index| fastlane.events[index].first == :artifact }
+ assert artifact_positions.all? { |index| index < fastlane.events.index { |event| event.first == upload } }
+ options = fastlane.events.find { |event| event.first == upload }.last
+ assert_equal File.join(@root, platform == :ios ? 'current.ipa' : 'current.aab'), options[platform == :ios ? :ipa : :aab]
+ assert_equal 'internal', options[:track] if platform == :android
+ assert_equal platform == :android ? 1 : 0, fastlane.events.count { |event| event.first == :slack }
+ end
+
+ define_method("test_#{platform}_live_does_not_upload_after_failed_artifact_verification") do
+ fastlane = FakeFastlane.new(platform, @root)
+ fastlane.failure = :artifact
+ assert_raises(RuntimeError) { fastlane.run(:live) }
+ assert_empty fastlane.events.select { |event| %i[upload_to_testflight upload_to_play_store].include?(event.first) }
+ end
+ end
+
+ { ios: { ipa: SharedValues::IPA_OUTPUT_PATH }, android: { aab: SharedValues::GRADLE_AAB_OUTPUT_PATH, apk: SharedValues::GRADLE_APK_OUTPUT_PATH } }.each do |platform, outputs|
+ outputs.each do |extension, key|
+ define_method("test_#{platform}_rejects_stale_#{extension}_from_prior_invocation") do
+ stale = File.join(@root, "stale.#{extension}")
+ File.write(stale, 'old artifact')
+ Actions.lane_context[key] = stale
+ fastlane = FakeFastlane.new(platform, @root)
+ fastlane.missing_output = extension
+ assert_match(/path/, assert_raises(RuntimeError) { fastlane.run(:build_only) }.message)
+ assert_empty distribution_events(fastlane)
+ assert_empty fastlane.events.select { |event| event.first == :artifact }
+ refute Actions.lane_context.key?(key)
+ end
+ end
+ end
+
+ def test_android_rejects_missing_signing_credentials_before_building
+ ENV.delete('STORE_PASSWORD')
+ fastlane = FakeFastlane.new(:android, @root)
+ assert_match(/signing credentials/, assert_raises(RuntimeError) { fastlane.run(:build_only) }.message)
+ assert_empty fastlane.events.select { |event| event.first == :gradle }
+ assert_empty distribution_events(fastlane)
+ end
+
+ def test_android_rejects_missing_keystore_before_building
+ File.delete(File.join(@root, 'android', 'app', 'release.keystore'))
+ fastlane = FakeFastlane.new(:android, @root)
+ assert_match(/keystore/, assert_raises(RuntimeError) { fastlane.run(:build_only) }.message)
+ assert_empty fastlane.events.select { |event| event.first == :gradle }
+ assert_empty distribution_events(fastlane)
+ end
+
+ def test_android_build_only_checks_apk_even_after_aab_passes
+ fastlane = FakeFastlane.new(:android, @root)
+ fastlane.failure = File.join(@root, 'current.apk')
+ assert_raises(RuntimeError) { fastlane.run(:build_only) }
+ assert_equal %w[aab apk], fastlane.events.select { |event| event.first == :artifact }.map { |event| File.extname(event.last).delete_prefix('.') }
+ assert_empty distribution_events(fastlane)
+ end
+end
diff --git a/scripts/test_release_artifact.py b/scripts/test_release_artifact.py
new file mode 100644
index 0000000000..ae6ee89670
--- /dev/null
+++ b/scripts/test_release_artifact.py
@@ -0,0 +1,89 @@
+"""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, "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):
+ 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)
+ 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}), \
+ 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)
+ 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")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/verify-channel-config.cjs b/scripts/verify-channel-config.cjs
new file mode 100644
index 0000000000..6c9d85a987
--- /dev/null
+++ b/scripts/verify-channel-config.cjs
@@ -0,0 +1,85 @@
+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 envContents = fs.readFileSync(envFile, 'utf8');
+if (/^\s*(?:export\s+)?(?:RN_)?(?:GASFREE_API_(?:KEY|SECRET)|LETS_EXCHANGE_API_KEY)\s*=/m.test(envContents)) {
+ throw new Error('Retired API credentials must not be included in a release environment');
+}
+
+const matches = envContents
+ .split(/\r?\n/)
+ .map(line => line.match(/^\s*(?:export\s+)?CHANNEL_URL\s*=\s*(.*?)\s*$/))
+ .filter(Boolean)
+ .map(match => match[1].trim());
+
+if (matches.length !== 1 || matches[0] !== expected) {
+ throw new Error(`Production CHANNEL_URL must be ${expected}`);
+}
+
+const stages = envContents
+ .split(/\r?\n/)
+ .map(line => line.match(/^\s*(?:export\s+)?ENVIRONMENT\s*=\s*(.*?)\s*$/))
+ .filter(Boolean)
+ .map(match => match[1].trim());
+
+if (stages.length !== 1 || stages[0] !== 'PRODUCTION') {
+ throw new Error('Production ENVIRONMENT must be PRODUCTION');
+}
+
+const required = [
+ 'RELAY',
+ 'SIGNING_SERVER_TESTNET',
+ 'SIGNING_SERVER_MAINNET',
+ 'HEXA_ID_TESTNET',
+ 'HEXA_ID_MAINNET',
+];
+const values = Object.fromEntries(required.map((name) => {
+ const matches = envContents
+ .split(/\r?\n/)
+ .map(line => line.match(new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=\\s*(.*?)\\s*$`)))
+ .filter(Boolean)
+ .map(match => match[1].trim());
+ // The native dotenv reader can retain malformed or mixed quotes. Keep the
+ // reviewed value identical to the value that will be embedded in the app.
+ if (matches.length !== 1 || !matches[0] || /['"]/.test(matches[0])) {
+ throw new Error(`Production ${name} must be set exactly once`);
+ }
+ return [name, matches[0]];
+}));
+
+const serviceURLs = {};
+for (const name of ['RELAY', 'SIGNING_SERVER_TESTNET', 'SIGNING_SERVER_MAINNET']) {
+ let url;
+ try {
+ url = new URL(values[name]);
+ } catch {
+ throw new Error(`Production ${name} must be an HTTPS URL`);
+ }
+ if (!values[name].startsWith('https://') || values[name].includes('\\') ||
+ url.protocol !== 'https:' || !url.hostname || url.username || url.password ||
+ url.search || url.hash || !values[name].endsWith('/') || values[name].endsWith('//')) {
+ throw new Error(`Production ${name} must be an HTTPS URL ending in / without credentials or query`);
+ }
+ serviceURLs[name] = url;
+}
+
+for (const name of ['HEXA_ID_TESTNET', 'HEXA_ID_MAINNET']) {
+ if (!/^[0-9a-fA-F]{64}$/.test(values[name])) {
+ throw new Error(`Production ${name} must be a 64-character hex ID`);
+ }
+}
+
+if (serviceURLs.RELAY.hostname.replace(/\.+$/, '') === 'bithyve-dev-relay.el.r.appspot.com' ||
+ serviceURLs.SIGNING_SERVER_MAINNET.hostname.replace(/\.+$/, '') === 'dev-sign.bithyve.com' ||
+ values.HEXA_ID_MAINNET.toLowerCase() ===
+ 'b01623f1065ba45d68b516efe2873f59bfc9b9b2d8b194f94f989d87d711830a') {
+ throw new Error('Production mainnet services must not use development defaults');
+}
+
+console.log('Production channel URL, environment, and service configuration verified');
diff --git a/scripts/verify-channel-config.test.cjs b/scripts/verify-channel-config.test.cjs
new file mode 100644
index 0000000000..8c64475da0
--- /dev/null
+++ b/scripts/verify-channel-config.test.cjs
@@ -0,0 +1,194 @@
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const verifier = path.join(__dirname, 'verify-channel-config.cjs');
+const prebuild = path.join(__dirname, '..', 'appcenter-pre-build.sh');
+const channel = [
+ 'CHANNEL_URL=https://channel.bitcoinkeeper.app/',
+ 'ENVIRONMENT=PRODUCTION',
+ 'RELAY=https://relay.example.invalid/',
+ 'SIGNING_SERVER_TESTNET=https://test-sign.example.invalid/',
+ 'SIGNING_SERVER_MAINNET=https://sign.example.invalid/',
+ `HEXA_ID_TESTNET=${'a'.repeat(64)}`,
+ `HEXA_ID_MAINNET=${'b'.repeat(64)}`,
+ '',
+].join('\n');
+
+function withTempDirectory(run) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-usdt-env-'));
+ try {
+ return run(directory);
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+}
+
+test('release env accepts reviewed channel without retired credentials', () =>
+ withTempDirectory((directory) => {
+ const envFile = path.join(directory, '.env.production');
+ fs.writeFileSync(envFile, channel);
+ const result = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ }));
+
+test('release env rejects missing or duplicate service configuration', () =>
+ withTempDirectory((directory) => {
+ const envFile = path.join(directory, '.env.production');
+ for (const name of ['RELAY', 'SIGNING_SERVER_MAINNET', 'HEXA_ID_MAINNET']) {
+ fs.writeFileSync(envFile, channel.split('\n').filter(line => !line.startsWith(`${name}=`)).join('\n'));
+ const missing = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' });
+ assert.notEqual(missing.status, 0);
+ assert.match(missing.stderr, new RegExp(`Production ${name} must be set exactly once`));
+ }
+ fs.writeFileSync(envFile, `${channel}RELAY=https://another.example.invalid/\n`);
+ const duplicate = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' });
+ assert.notEqual(duplicate.status, 0);
+ assert.match(duplicate.stderr, /Production RELAY must be set exactly once/);
+ }));
+
+test('release env rejects equivalent development mainnet defaults', () =>
+ withTempDirectory((directory) => {
+ const envFile = path.join(directory, '.env.production');
+ for (const config of [
+ channel.replace('SIGNING_SERVER_MAINNET=https://sign.example.invalid/',
+ 'SIGNING_SERVER_MAINNET=https://DEV-SIGN.BITHYVE.COM/path/'),
+ channel.replace('SIGNING_SERVER_MAINNET=https://sign.example.invalid/',
+ 'SIGNING_SERVER_MAINNET=https://dev-sign.bithyve.com../'),
+ channel.replace('RELAY=https://relay.example.invalid/',
+ 'RELAY=https://bithyve-dev-relay.el.r.appspot.com/'),
+ channel.replace(`HEXA_ID_MAINNET=${'b'.repeat(64)}`,
+ 'HEXA_ID_MAINNET=B01623F1065BA45D68B516EFE2873F59BFC9B9B2D8B194F94F989D87D711830A'),
+ ]) {
+ fs.writeFileSync(envFile, config);
+ const result = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' });
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /must not use development defaults/);
+ }
+ }));
+
+test('release env requires usable service URL prefixes', () =>
+ withTempDirectory((directory) => {
+ const envFile = path.join(directory, '.env.production');
+ for (const value of [
+ 'https://relay.example.invalid',
+ 'https://relay.example.invalid//',
+ 'https:relay.example.invalid/',
+ 'https:/relay.example.invalid/',
+ 'https:\\relay.example.invalid/',
+ 'https://relay.example.invalid/\'',
+ '"https://relay.example.invalid/\'',
+ 'https://relay.example.invalid/path?mode=release/',
+ 'https://name:password@relay.example.invalid/',
+ ]) {
+ fs.writeFileSync(envFile, channel.replace('RELAY=https://relay.example.invalid/', `RELAY=${value}`));
+ const result = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' });
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /Production RELAY must be (?:an HTTPS URL|set exactly once)/);
+ }
+ }));
+
+test('release env rejects malformed quotes in channel and stage', () =>
+ withTempDirectory((directory) => {
+ const envFile = path.join(directory, '.env.production');
+ for (const config of [
+ channel.replace('CHANNEL_URL=https://channel.bitcoinkeeper.app/',
+ 'CHANNEL_URL="https://channel.bitcoinkeeper.app/\''),
+ channel.replace('ENVIRONMENT=PRODUCTION', 'ENVIRONMENT="PRODUCTION\''),
+ ]) {
+ fs.writeFileSync(envFile, config);
+ const result = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' });
+ assert.notEqual(result.status, 0);
+ }
+ }));
+
+test('direct Android production release requires and selects the reviewed file', () =>
+ withTempDirectory((directory) => {
+ fs.mkdirSync(path.join(directory, 'scripts'));
+ fs.copyFileSync(verifier, path.join(directory, 'scripts', 'verify-channel-config.cjs'));
+ const bin = path.join(directory, 'bin');
+ fs.mkdirSync(bin);
+ const launcher = path.join(bin, 'react-native');
+ fs.writeFileSync(launcher, '#!/bin/sh\nprintf "%s|%s" "$ENVFILE" "$*" > selected-env\n');
+ fs.chmodSync(launcher, 0o755);
+ fs.writeFileSync(path.join(directory, '.env'), channel);
+ const command = require('../package.json').scripts.androidProductionRelease;
+ const options = {
+ cwd: directory,
+ env: { ...process.env, PATH: `${bin}:${process.env.PATH}` },
+ encoding: 'utf8',
+ };
+ const missing = spawnSync('sh', ['-c', command], options);
+ assert.notEqual(missing.status, 0);
+ assert.equal(fs.existsSync(path.join(directory, 'selected-env')), false);
+
+ fs.writeFileSync(path.join(directory, '.env.production'), channel);
+ const valid = spawnSync('sh', ['-c', command], options);
+ assert.equal(valid.status, 0, valid.stderr);
+ assert.equal(
+ fs.readFileSync(path.join(directory, 'selected-env'), 'utf8'),
+ '.env.production|run-android --mode=productionRelease'
+ );
+ }));
+
+for (const [caseName, stage] of [
+ ['missing', ''],
+ ['development', 'ENVIRONMENT=DEVELOPMENT\n'],
+ ['duplicate', 'ENVIRONMENT=PRODUCTION\nENVIRONMENT=PRODUCTION\n'],
+]) {
+ test(`release env rejects ${caseName} production stage`, () =>
+ withTempDirectory((directory) => {
+ const envFile = path.join(directory, '.env.production');
+ fs.writeFileSync(envFile, `CHANNEL_URL=https://channel.bitcoinkeeper.app/\n${stage}`);
+ const result = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' });
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /Production ENVIRONMENT must be PRODUCTION/);
+ }));
+}
+
+for (const name of [
+ 'GASFREE_API_KEY',
+ 'GASFREE_API_SECRET',
+ 'RN_GASFREE_API_KEY',
+ 'LETS_EXCHANGE_API_KEY',
+ 'RN_LETS_EXCHANGE_API_KEY',
+]) {
+ test(`release env rejects ${name} without logging its value`, () =>
+ withTempDirectory((directory) => {
+ const envFile = path.join(directory, '.env.production');
+ const secret = 'synthetic-secret-not-for-output';
+ fs.writeFileSync(envFile, `${channel}${name}=${secret}\n`);
+ const result = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' });
+ assert.notEqual(result.status, 0);
+ assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/);
+ }));
+}
+
+test('AppCenter rejects retired credential input before writing .env', () =>
+ withTempDirectory((directory) => {
+ const secret = 'synthetic-secret-not-for-output';
+ const result = spawnSync('bash', [prebuild], {
+ cwd: directory,
+ env: { PATH: process.env.PATH, RN_GASFREE_API_SECRET: secret },
+ encoding: 'utf8',
+ });
+ assert.notEqual(result.status, 0);
+ assert.equal(fs.existsSync(path.join(directory, '.env')), false);
+ assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/);
+ }));
+
+test('AppCenter rejects retired swap credential input before writing .env', () =>
+ withTempDirectory((directory) => {
+ const secret = 'synthetic-secret-not-for-output';
+ const result = spawnSync('bash', [prebuild], {
+ cwd: directory,
+ env: { PATH: process.env.PATH, RN_LETS_EXCHANGE_API_KEY: secret },
+ encoding: 'utf8',
+ });
+ assert.notEqual(result.status, 0);
+ assert.equal(fs.existsSync(path.join(directory, '.env')), false);
+ assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/);
+ }));
diff --git a/scripts/verify-release-artifact.py b/scripts/verify-release-artifact.py
new file mode 100644
index 0000000000..16ebaf120b
--- /dev/null
+++ b/scripts/verify-release-artifact.py
@@ -0,0 +1,159 @@
+#!/usr/bin/env python3
+"""Inspect packaged release metadata and required feature markers without dumping secrets.
+
+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.
+"""
+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}"
+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):
+ 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 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:
+ raise ValueError(f"{Path(command[0]).name} failed; inspect tool/environment configuration")
+ 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:
+ 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"
+ 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([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")
+ 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():
+ 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")
+ verify_channel(archive, suffix)
+ 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",
+ "channelUrl": "verified",
+ "signing": "separate verification required"}
+ if suffix == ".apk":
+ 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")
+ 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())
diff --git a/setup.sh b/setup.sh
index 2013fb9bd3..3135bb8cbb 100755
--- a/setup.sh
+++ b/setup.sh
@@ -1,9 +1,6 @@
-# enabling node core modules
-# adding node core modules support in react-native
-rn-nodeify --install buffer,events,process,stream,inherits,path,assert,crypto --hack --yarn
-
-# ios dependency installation
-cd ios && RCT_NEW_ARCH_ENABLED=1 pod install
+#!/bin/sh
+set -eu
-# android SDK location configuration
-cd ../android && touch local.properties && echo "sdk.dir = /Users/$(whoami)/Library/Android/sdk" >local.properties
+# Yarn's prepare hook runs on Android-only machines too. Keep it platform neutral;
+# CocoaPods and the Android SDK are configured explicitly in dev/local-backend/README.md.
+rn-nodeify --install buffer,events,process,stream,inherits,path,assert,crypto --hack --yarn
diff --git a/src/components/AppNumPad/KeyPadView.tsx b/src/components/AppNumPad/KeyPadView.tsx
index efe8d6012d..da2c31702b 100644
--- a/src/components/AppNumPad/KeyPadView.tsx
+++ b/src/components/AppNumPad/KeyPadView.tsx
@@ -28,8 +28,9 @@ const KeyPadView: React.FC = ({
}: Props) => {
const { colorMode } = useColorMode();
+ // Keep the native keypad container stable when pointerEvents changes after login unlocks.
return (
-
+ {illustrations[contentType]}
{descriptions[contentType] && {descriptions[contentType]}}
{asbEnabled && {BackupWallet.assistedServerBackupEnabled}}
+ {contentType !== ContentType.healthCheckSuccessful && (
+ {BackupWallet.retainedOlderCopyNotice}
+ )}
);
}
@@ -74,17 +78,21 @@ function BackupHealthCheckList({ isUaiFlow }) {
const { translations } = useContext(LocalizationContext);
const { BackupWallet, vault: vaultText, common } = translations;
const dispatch = useAppDispatch();
- const { primaryMnemonic, backup, id } = useQuery(RealmSchema.KeeperApp).map(
+ const { primaryMnemonic, id } = useQuery(RealmSchema.KeeperApp).map(
getJSONFromRealmObject
- )[0];
+ )[0] as { primaryMnemonic: string; id: string };
const {
backupMethod,
seedConfirmed,
- automaticCloudBackup,
- backupAllLoading,
- backupAllFailure,
- backupAllSuccess,
+ automaticCloudBackupByAppId,
+ backupAllLoadingByAppId,
+ backupAllFailureByAppId,
+ backupAllSuccessByAppId,
} = useAppSelector((state) => state.bhr);
+ const automaticCloudBackup = isAutomaticCloudBackupEnabled({ automaticCloudBackupByAppId }, id);
+ const backupAllLoading = !!backupAllLoadingByAppId?.[id];
+ const backupAllFailure = !!backupAllFailureByAppId?.[id];
+ const backupAllSuccess = !!backupAllSuccessByAppId?.[id];
const [healthCheckModal, setHealthCheckModal] = useState(false);
const [showConfirmSeedModal, setShowConfirmSeedModal] = useState(isUaiFlow);
const [verificationModal, setVerificationModal] = useState(false);
@@ -103,13 +111,12 @@ function BackupHealthCheckList({ isUaiFlow }) {
setShowConfirmSeedModal(true);
};
-
useEffect(() => {
- if (backupAllSuccess || backupAllFailure) {
+ if (backupAllSuccess) {
if (!automaticCloudBackup) setAsbEnabled(true);
- dispatch(setBackupAllSuccess(false));
- dispatch(setBackupAllFailure(false));
- dispatch(setAutomaticCloudBackup(true));
+ dispatch(setBackupAllSuccess({ appId: id, status: false }));
+ dispatch(setBackupAllFailure({ appId: id, status: false }));
+ dispatch(setAutomaticCloudBackup({ appId: id, enabled: true }));
setHealthCheckModal(true);
}
}, [backupAllSuccess, backupAllFailure]);
@@ -118,12 +125,9 @@ function BackupHealthCheckList({ isUaiFlow }) {
if (seedConfirmed) {
setShowConfirmSeedModal(false);
dispatch(setRecoveryKeyBackedUp({ appId: id as string, status: true }));
- if (!automaticCloudBackup) dispatch(backupAllSignersAndVaults());
- else {
- setTimeout(() => {
- setHealthCheckModal(true);
- }, 100);
- }
+ setTimeout(() => {
+ setHealthCheckModal(true);
+ }, 100);
}
return () => {
dispatch(setSeedConfirmed(false));
@@ -132,13 +136,14 @@ function BackupHealthCheckList({ isUaiFlow }) {
useEffect(() => {
if (backupAllFailure && isFocused) {
- dispatch(setBackupAllFailure(false));
+ setFailedVerificationModal(true);
+ dispatch(setBackupAllFailure({ appId: id, status: false }));
}
}, [backupAllFailure]);
useEffect(() => {
if (backupAllSuccess && isFocused) {
- dispatch(setBackupAllSuccess(false));
+ dispatch(setBackupAllSuccess({ appId: id, status: false }));
dispatch(seedBackedConfirmed(true));
}
}, [backupAllSuccess]);
@@ -191,7 +196,7 @@ function BackupHealthCheckList({ isUaiFlow }) {
} else {
setBackupMismatchModal(true);
}
- })
+ }, id)
);
} else {
dispatch(seedBackedConfirmed(true));
@@ -285,12 +290,12 @@ function BackupHealthCheckList({ isUaiFlow }) {
closeOnOverlayClick={false}
buttonTextColor={`${colorMode}.buttonText`}
buttonBackground={`${colorMode}.pantoneGreen`}
- buttonText={'Backup Now'}
+ buttonText={BackupWallet.backUpNow}
buttonCallback={() => {
- dispatch(backupAllSignersAndVaults());
+ dispatch(backupAllSignersAndVaults(id));
setBackupMismatchModal(false);
}}
- secondaryButtonText="Home"
+ secondaryButtonText={BackupWallet.home}
secondaryCallback={() => {
navigtaion.dispatch(CommonActions.navigate('Home'));
}}
diff --git a/src/components/Backup/ProtectedBackupActions.tsx b/src/components/Backup/ProtectedBackupActions.tsx
new file mode 100644
index 0000000000..035a0a62d5
--- /dev/null
+++ b/src/components/Backup/ProtectedBackupActions.tsx
@@ -0,0 +1,42 @@
+import React from 'react';
+import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
+import { StyleSheet, TouchableOpacity } from 'react-native';
+import Text from 'src/components/KeeperText';
+
+// Backup choices have long, materially different labels. Keep each choice in
+// its own wrapping touch target instead of the shared single-line button row.
+export function ProtectedBackupAction({
+ label,
+ onPress,
+ secondary = false,
+}: {
+ label: string;
+ onPress: () => void;
+ // eslint-disable-next-line react/require-default-props -- Defaulted in the function signature.
+ secondary?: boolean;
+}) {
+ const { colorMode } = useColorMode();
+ return (
+
+
+
+ {label}
+
+
+
+ );
+}
+
+const styles = StyleSheet.create({
+ touchTarget: { width: '100%', marginTop: 12 },
+ button: { minHeight: 48, paddingVertical: 14, paddingHorizontal: 16, borderRadius: 10 },
+ label: { fontSize: 14, textAlign: 'center', flexShrink: 1 },
+});
diff --git a/src/components/HomeScreenHeader.tsx b/src/components/HomeScreenHeader.tsx
index ac9727a035..239ea8af23 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.dispatch(CommonActions.navigate('AssistedBackupStatus'));
},
};
diff --git a/src/components/ImportExportLabels/index.tsx b/src/components/ImportExportLabels/index.tsx
index 72074f47ae..6125fa5d16 100644
--- a/src/components/ImportExportLabels/index.tsx
+++ b/src/components/ImportExportLabels/index.tsx
@@ -1,4 +1,4 @@
-import React, { useState } from 'react';
+import React, { useRef, useState } from 'react';
import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
import { StyleSheet, TouchableOpacity } from 'react-native';
import { useDispatch } from 'react-redux';
@@ -10,6 +10,7 @@ import { hp, wp } from 'src/constants/responsive';
import ActivityIndicatorView from '../AppActivityIndicator/ActivityIndicatorView';
import { useAppSelector } from 'src/store/hooks';
import Colors from 'src/theme/Colors';
+import { captureBackupWriteIntent, currentBackupAccountSession } from 'src/services/backup/transport';
interface ImportExportLabelsProps {
vault: any;
@@ -28,11 +29,15 @@ const ImportExportLabels: React.FC = ({
}) => {
const { colorMode } = useColorMode();
const dispatch = useDispatch();
+ const activeAppId = useAppSelector((state) => state.storage.appId);
+ const originAppId = useRef(activeAppId).current;
const { vault: vaultText } = translations;
const { syncingUTXOs } = useAppSelector((state) => state.utxos);
const [isSyncingLabels, setIsSyncingLabels] = useState(false);
const handleImportLabels = async () => {
+ const originBackupAccountSession = currentBackupAccountSession();
+ const originBackupWriteIntent = captureBackupWriteIntent(originAppId);
try {
setIsSyncingLabels(true);
await importFile(
@@ -101,7 +106,15 @@ const ImportExportLabels: React.FC = ({
origin: standardizeDescriptor(label.origin),
}));
- dispatch(importLabels({ labels: standardizedLabels }));
+ if (originBackupAccountSession !== currentBackupAccountSession()) {
+ onError('Account changed; please import the wallet labels again');
+ return;
+ }
+ dispatch({
+ ...importLabels({ labels: standardizedLabels }, originAppId),
+ originBackupAccountSession,
+ originBackupWriteIntent,
+ });
onSuccess(`Imported ${walletLabels.length} labels successfully`);
} catch (parseError) {
diff --git a/src/components/KeeperModal.tsx b/src/components/KeeperModal.tsx
index 8f5105c2a8..6aea64e919 100644
--- a/src/components/KeeperModal.tsx
+++ b/src/components/KeeperModal.tsx
@@ -2,7 +2,7 @@ import { Box, Modal, useColorMode } from '@gluestack-ui/themed-native-base';
import { ScrollView, StyleSheet, TouchableOpacity, useWindowDimensions } from 'react-native';
import { hp, windowWidth, wp } from 'src/constants/responsive';
import CloseGreen from 'src/assets/images/dark-close-icon.svg';
-import React from 'react';
+import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Text from 'src/components/KeeperText';
import { useKeyboard } from 'src/hooks/useKeyboard';
@@ -17,6 +17,8 @@ import { default as RNModal } from 'react-native-modal';
type ModalProps = {
visible: boolean;
close: any;
+ // eslint-disable-next-line react/require-default-props -- Omitted lifecycle callback has no side effect.
+ onModalHide?: () => void;
title?: string;
subTitle?: string;
subTitleWidth?: number;
@@ -52,6 +54,7 @@ function KeeperModal(props: ModalProps) {
const {
visible,
close,
+ onModalHide,
title = '',
subTitle = null,
subTitleWidth = windowWidth * 0.7,
@@ -87,8 +90,23 @@ function KeeperModal(props: ModalProps) {
const maxModalHeight = Math.min(availableHeight, screenHeight * 0.85);
const { colorMode } = useColorMode();
const isDarKMode = colorMode === 'dark';
+ const [keepMountedForHide, setKeepMountedForHide] = useState(visible);
+ const hidePending = useRef(false);
- if (!visible) {
+ useLayoutEffect(() => {
+ if (visible) {
+ hidePending.current = true;
+ setKeepMountedForHide(true);
+ }
+ }, [visible]);
+
+ useEffect(() => () => {
+ hidePending.current = false;
+ }, []);
+
+ // Existing callers still unmount immediately. Opted-in callers need RNModal to
+ // receive isVisible=false and finish its native close before the next screen.
+ if (!visible && (!onModalHide || !keepMountedForHide)) {
return null;
}
const getCloseIcon = () => (DarkCloseIcon ? : );
@@ -98,10 +116,19 @@ function KeeperModal(props: ModalProps) {
{
+ if (visible || !hidePending.current) return;
+ hidePending.current = false;
+ setKeepMountedForHide(false);
+ onModalHide?.();
+ }}
style={styles.modalContainer}
avoidKeyboard
>
{
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/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/components/TransactionElement.tsx b/src/components/TransactionElement.tsx
index a5adda3fac..401e0f0121 100644
--- a/src/components/TransactionElement.tsx
+++ b/src/components/TransactionElement.tsx
@@ -1,4 +1,4 @@
-import React from 'react';
+import React, { useContext } from 'react';
import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
import { StyleSheet, TouchableOpacity } from 'react-native';
import moment from 'moment';
@@ -21,10 +21,16 @@ import Colors from 'src/theme/Colors';
import useLabelsNew from 'src/hooks/useLabelsNew';
import { Wallet } from 'src/services/wallets/interfaces/wallet';
import { Vault } from 'src/services/wallets/interfaces/vault';
-import { USDTTransaction } from 'src/services/wallets/operations/dollars/USDT';
+import {
+ isHistoricalUnverifiedUSDTRequest,
+ isUSDTStatusUnavailable,
+ USDTTransaction,
+} from 'src/services/wallets/operations/dollars/USDT';
+import { GasFreeTransferStatus } from 'src/services/wallets/operations/dollars/GasFree';
import { EntityKind } from 'src/services/wallets/enums';
import { USDTWallet } from 'src/services/wallets/factories/USDTWalletFactory';
import ThemedColor from './ThemedColor/ThemedColor';
+import { LocalizationContext } from 'src/context/Localization/LocContext';
function TransactionElement({
transaction,
@@ -44,12 +50,19 @@ function TransactionElement({
let amount: number;
let confirmations: number;
let transactionType: string;
+ const legacyUSDTRequest =
+ wallet.entityKind === EntityKind.USDT_WALLET &&
+ isHistoricalUnverifiedUSDTRequest(transaction as USDTTransaction);
+ const unavailableUSDTStatus =
+ wallet.entityKind === EntityKind.USDT_WALLET &&
+ isUSDTStatusUnavailable(transaction as USDTTransaction);
if (wallet.entityKind === EntityKind.USDT_WALLET) {
transactionId =
(transaction as USDTTransaction).txId || (transaction as USDTTransaction).traceId;
date = (transaction as USDTTransaction).timestamp;
amount = parseFloat((transaction as USDTTransaction).amount);
- confirmations = (transaction as USDTTransaction).blockNumber ? 6 : 0; // Assuming 6 confirmations for USDT transactions(no. of conf on Tron doesn't really make any finality sense)
+ confirmations =
+ (transaction as USDTTransaction).status === GasFreeTransferStatus.CHAIN_CONFIRMED ? 1 : 0;
if (
(transaction as USDTTransaction).to === (wallet as USDTWallet).accountStatus.gasFreeAddress
) {
@@ -65,6 +78,7 @@ function TransactionElement({
const { labels } = useLabelsNew({ txid: transactionId });
const { colorMode } = useColorMode();
+ const { translations } = useContext(LocalizationContext);
const formattedDate = moment(date)?.format('DD MMM YY . HH:mm A');
const viewAll_color = ThemedColor({ name: 'viewAll_color' });
@@ -73,6 +87,7 @@ function TransactionElement({
- {confirmations === 0 && !isCached && (
+ {confirmations === 0 && !isCached && !unavailableUSDTStatus && (
)}
- {isCached ? (
+ {legacyUSDTRequest ? null : isCached ? (
) : transactionType === 'Received' ? (
colorMode === 'light' ? (
@@ -104,15 +119,22 @@ function TransactionElement({
- {labels[transactionId]?.[0]?.name || transactionId}
+ {legacyUSDTRequest
+ ? translations.usdtWalletText.legacyRequestTitle
+ : labels[transactionId]?.[0]?.name || transactionId}
{formattedDate}
+ {unavailableUSDTStatus && (
+
+ {translations.usdtWalletText.statusUnavailable}
+
+ )}
{(transaction as Transaction).tags?.includes('potential-dust-spend') && (
@@ -123,15 +145,17 @@ function TransactionElement({
-
+ {!legacyUSDTRequest && (
+
+ )}
{colorMode === 'dark' ? : }
@@ -145,11 +169,17 @@ const styles = StyleSheet.create({
container: {
flexDirection: 'row',
borderRadius: 10,
- height: hp(76),
justifyContent: 'space-between',
alignItems: 'center',
borderBottomWidth: 1,
},
+ standardContainer: {
+ height: hp(76),
+ },
+ legacyContainer: {
+ minHeight: hp(76),
+ paddingVertical: hp(8),
+ },
rowCenter: {
marginHorizontal: wp(10),
flexDirection: 'row',
@@ -167,6 +197,12 @@ const styles = StyleSheet.create({
marginHorizontal: 3,
lineHeight: 17,
},
+ legacyStatus: {
+ fontSize: 10,
+ width: wp(125),
+ marginHorizontal: 3,
+ lineHeight: 13,
+ },
transactionIdText: {
marginHorizontal: 4,
fontSize: 14,
diff --git a/src/context/Localization/language/en.json b/src/context/Localization/language/en.json
index 962b29aee2..35f95a0231 100644
--- a/src/context/Localization/language/en.json
+++ b/src/context/Localization/language/en.json
@@ -185,6 +185,7 @@
"help": "Help"
},
"login": {
+ "startupCredentialError": "Unable to check your passcode. Please try again.",
"welcomeback": "Welcome Back",
"welcome": "Welcome",
"welcomeToBitcoinKeeper": "Welcome to Bitcoin Keeper",
@@ -194,7 +195,7 @@
"MismatchPasscode": "Passcodes do not match",
"enter_your": "Enter your ",
"NewSatrtWalet": "A new hot wallet will be created automatically for you. You can create and manage different kinds of wallets from the wallets section of the app.",
- "RecoverExistingAppDesc": "Have an inaccessible Keeper app with wallets in it? You have nothing to worry if you have that app's 12-word Recovery Key. Insert the words in the Recovery section on the welcome screen and all your wallets will be restored as expected.",
+ "RecoverExistingAppDesc": "Use the Keeper app’s Recovery Key to check its available protected backup. An older read-only recovery copy is a separate choice and may not include newer changes.",
"RecoverApp": "Recover an existing app:",
"Wait": "This step will take a few seconds. You will be able to proceed soon",
"Createpasscode": "Create a passcode",
@@ -223,8 +224,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",
@@ -449,6 +450,10 @@
"faucetDailyLimitTitle": "Daily Limit Reached",
"faucetDailyLimitBody": "You can request test sats up to 5 times per day. Try again after midnight UTC.",
"faucetDailyLimitError": "Daily limit reached. Try again after midnight UTC.",
+ "faucetPendingTitle": "Test sats are still pending",
+ "faucetPropagationPending": "The faucet sent test sats, but this wallet has not seen the transaction yet. Your balance may take a moment to update.",
+ "faucetSyncPending": "The faucet sent test sats, but the wallet could not sync. Check your server connection before requesting again.",
+ "faucetOutcomeUnknown": "The faucet request timed out. Test sats may already have been sent. Check your balance before requesting again.",
"Singlekey": "Single-key",
"multikey2of3": "2 of 3 multi-key",
"multikey3of5": "3 of 5 multi-key",
@@ -667,11 +672,13 @@
"addEmergencyKey": "Add Emergency Key",
"availableAfterDelay": "Key will be available after time-delay",
"inheritanceKeyActivation": "Inheritance Key Activation",
+ "inheritanceActivationNote": "Activation is fixed when this wallet version is created, with any Wallet Timelock added to the selected delay. Receiving or spending funds does not restart it. Resetting requires re-vaulting and transferring funds.",
"emergencyKeyActivation": "Emergency Key Activation",
"changeKey": "Change Key",
"selectActivationTime": "Select activation time",
"chooseNewActivationTimeTitle": "Choose New Activation Time",
"chooseNewActivationTimeDesc": "Please choose the new time for your Inheritance Key to become active",
+ "chooseNewEmergencyActivationTimeDesc": "Please choose the new time for your Emergency Key to become active",
"scanQR": "Scan QR",
"scanOrUpload": "Please scan the QR or upload an image",
"nfcOnTap": "NFC on tap",
@@ -795,16 +802,17 @@
"backupPhrase": "Recovery Key",
"walletSeedWords": "Recovery Key",
"enterRecoveryPhrase": "Recover an existing Keeper App",
- "enterRecoveryPhraseSubTitle": "Enter existing 12-word recovery phrase below",
+ "enterRecoveryPhraseSubTitle": "Enter this Keeper app’s 12-word Recovery Key. Its protected backup is checked first.",
"walletRecoveryPhrase": "Wallet Recovery Phrase",
"showXPubNoteSubText": "Losing your Wallet Seed Words may result in permanent loss of funds. Store them carefully.",
"mobileKeyVerified": "Mobile Key verified successfully",
"seedWordVerified": "Seed Words verified successfully",
"keeperVerified": "Keeper Verified Successfully",
"SeedErrorToast": "Please fill in all seed word fields",
- "appRecoveredSuccessfulTitle": "App Recovered Successfully!",
- "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",
+ "appRecoveredSuccessfulTitle": "Backup recovered",
+ "recoveryIncomplete": "Recovery was not completed. Available backup data could not be fully checked or restored. No older copy was selected automatically.",
+ "appRecoveredSuccessfulSubTitle": "The selected backup’s available recovery data was checked and restored.",
+ "appRecoveredSuccessfulDesc": "Hardware signing keys stay on their devices. Review recovered records before enabling protected backup.",
"mobileKey": "Mobile Key",
"mobileKeySeedWordsTitle": "Mobile Key Seed Words",
"mobileKeySeedNoteSubTitle": "The QR below comprises of your 12-word Mobile Key",
@@ -812,7 +820,24 @@
"storeSecurely": "Write down these words and store them securely.",
"enterAmountToSend": "Enter Amount to Send",
"feePriority": "Fee Priority",
- "seedKey": "Seed Key"
+ "seedKey": "Seed Key",
+ "protectedRecoveryAbsentTitle": "No protected backup found",
+ "protectedRecoveryAbsentBody": "This Recovery Key has no protected copy. You can choose to look for an older read-only recovery copy.",
+ "protectedRecoveryDeletedTitle": "Your protected backup was deleted",
+ "protectedRecoveryDeletedBody": "Keeper will not restore an older copy automatically. An older read-only copy may predate deletion and omit newer changes.",
+ "protectedRecoveryErrorTitle": "Could not check protected backup",
+ "protectedRecoveryErrorBody": "The protected backup could not be checked. No older copy was selected. Check your connection and try again.",
+ "recoverOlderCopy": "Recover an older copy",
+ "recoverOlderCopyTitle": "Recover an older copy?",
+ "recoverOlderCopyBody": "An older read-only backup may predate deletion or omit newer changes. Recovery uses only the complete available records and does not turn on automatic backup.",
+ "protectedRecoverySuccessfulTitle": "Protected backup recovered",
+ "protectedRecoverySuccessfulSubTitle": "The selected protected copy’s available recovery data was checked and restored.",
+ "olderRecoverySuccessfulTitle": "Older backup recovered",
+ "olderRecoverySuccessfulSubTitle": "Recovered from an older copy. Newer changes may be missing. Automatic backup stays off.",
+ "protectedRecoveryEmptyTitle": "Protected backup is empty",
+ "protectedRecoveryEmptyBody": "This protected copy has no recovery records. You may explicitly choose to look for an older read-only copy.",
+ "olderRecoveryErrorTitle": "Older backup recovery incomplete",
+ "olderRecoveryErrorBody": "The older copy could not be fully checked or restored. Keep your Recovery Key and check the connection and available records before trying again."
},
"healthcheck": {
"HealthCheck": "Perform Health Check",
@@ -1037,6 +1062,7 @@
"ManageWalletsSub": "Hide/Unhide Wallets From Homescreen",
"torSettingTitle": "Tor Settings",
"torSettingSubTitle": "Configure in-app Tor and Orbot",
+ "installedAppVersion": "Installed app version",
"versionHistoryTitle": "Version History",
"versionHistorySubTitle": "You can verify the history of your app upgrades here",
"torHeaderSubTitle": "Tor improves your network privacy. To learn more visit: https://www.torproject.org/",
@@ -1090,11 +1116,11 @@
"serverSelectionSubtitle": "Select a server you'd like to use. Add your own node for enhanced privacy.",
"publicServerNote": "It’s recommended to use your own Electrum server to protect your privacy",
"connectToServer": "Connect to Server",
- "assistedServerBackup": "Assisted Server Backup",
- "assistedServerBackupSubtitle": "Back up encrypted data using a community-run Keeper server.",
- "assistedServerDeleteBackupSubtitle": "Do you also want to delete the existing assisted server backup?",
- "assistedServerDeleteBackupModalCTA": "Delete",
- "assistedServerDeleteBackupModalSecondaryCTA": "Only disable",
+ "assistedServerBackup": "Protected server backup",
+ "assistedServerBackupSubtitle": "Keep a new encrypted protected copy. Older read-only recovery copies may remain.",
+ "assistedServerDeleteBackupSubtitle": "This deletes your protected copy and turns off automatic backup. Older encrypted recovery copies may remain read-only. Your wallets and Recovery Key on this device are kept. Turning off automatic backup alone keeps all copies.",
+ "assistedServerDeleteBackupModalCTA": "Delete protected backup",
+ "assistedServerDeleteBackupModalSecondaryCTA": "Turn off automatic backup",
"cameraAccessoff": "Camera access is turned off",
"turnCameraOn": "Turn on the camera in your device settings",
"tapToGoSetting": "Tap to go to settings",
@@ -1140,7 +1166,13 @@
"changeWallet": "Change Wallet",
"customAmount": "Custom amount",
"sendNoteToDevelopers": "Send a note to the developers",
- "messageToDeveloper": "Message to developer"
+ "messageToDeveloper": "Message to developer",
+ "assistedServerDeleteBackupTitle": "Delete protected backup?",
+ "assistedServerDeleteBackupConfirmed": "Protected backup deleted. Older encrypted recovery copies may remain. Your local wallets and Recovery Key are unchanged.",
+ "assistedServerBackupDisabled": "Automatic backup is off. Existing backup copies were kept.",
+ "assistedServerEnableBackupTitle": "Enable protected backup?",
+ "assistedServerEnableBackupSubtitle": "Create or update your protected copy from this device’s recovery data. Older read-only copies are not changed. Keep your Recovery Key safe.",
+ "assistedServerEnableBackupCTA": "Enable protected backup"
},
"onboarding": {
"security": "security",
@@ -1205,15 +1237,15 @@
"enterThe": "Enter the",
"seedWord": "seed word",
"enterSeedWordPlaceholder": "Enter seed word",
- "verifyModalTitle": "Verifying Server Backup",
- "verifyModalSubTitle": "Verifying your server backup integrity against your local data.\nThis may take a moment.",
- "backupFailedModalTitle": "Backup Verification Failed",
- "backupFailedModalSubTitle": "We couldn’t verify your data with the server backup.",
- "backupFailedModalDesc": "There might be a temporary issue with the server or your connection. Please try again later.",
- "mismatchModalTitle": "Data Mismatch Detected",
- "mismatchModalSubTitle": "Your local data doesn’t match the server backup.",
- "mismatchModalDesc": "Some recent changes may not be backed up yet. To avoid data loss, we recommend initiating a backup now.",
- "assistedServerBackupEnabled": "Assisted server backup is now enabled.\nThis will backup your encrypted data on a community-run Keeper server",
+ "verifyModalTitle": "Verifying protected backup",
+ "verifyModalSubTitle": "Comparing the protected copy with recovery data on this device.\nThis may take a moment.",
+ "backupFailedModalTitle": "Protected backup not verified",
+ "backupFailedModalSubTitle": "Keeper could not confirm that the protected copy matches.",
+ "backupFailedModalDesc": "The connection, backup authorization or recovery data could not be checked. Keep your local recovery data and check the backup status.",
+ "mismatchModalTitle": "Protected backup needs updating",
+ "mismatchModalSubTitle": "This device’s recovery data differs from the protected copy.",
+ "mismatchModalDesc": "Review the backup status before updating the protected copy. Older read-only recovery copies are not changed.",
+ "assistedServerBackupEnabled": "Protected backup is now enabled. Automatic updates apply to this encrypted protected copy; older read-only copies may remain.",
"recoveryKeyConfirmDialog": "Recovery Key confirmed",
"recoveryKeyConfirmDialogSubTitle": "Your Recovery Key is confirmed. You remain fully in control of your keys.",
"recoveryConfirmDesc1": "If you have already written down your Recovery Key, confirm it below.",
@@ -1224,7 +1256,9 @@
"doNotStoreDigitally": "Do not store digitally",
"doNotStoreDigitallyBody": "Never save your Recovery Key in screenshots, cloud storage, or any digital format.",
"makeNoOneLooking": "Make sure no one is watching your screen.",
- "recoveryKeyBackedUpSuccessfully": "Recovery Key backed up successfully"
+ "recoveryKeyBackedUpSuccessfully": "Recovery Key backed up successfully",
+ "backUpNow": "Back up protected copy",
+ "retainedOlderCopyNotice": "Older encrypted recovery copies may remain read-only. They are not updated or deleted by changes to the protected copy."
},
"importWallet": {
"addDetails": "Add details",
@@ -1291,12 +1325,12 @@
"keyDeletedSuccessfully": "Key Deleted Successfully",
"keyDeletedSuccessMessage": "Your Key has been deleted successfully. You will have to add the Key again",
"manageKeys": "Manage Keys",
- "deleteVaultWarning": "Key Used in Hidden Vault",
- "vaultWarningSubtitle": "The key you're trying to delete is being used in the hidden vault mentioned below.",
- "deleteVaultInstruction": "Please change the key in the hidden vault, or delete the hidden vault, to delete this key.",
- "deleteMultipleVaultWarning": "Key Used in Multiple Hidden Vaults",
- "multipleVaultWarningSubtitle": "The key you're trying to delete is being used in the hidden vaults mentioned below.",
- "deleteMultipleVaultInstruction": "Please change the key in the hidden vaults, or delete the hidden vaults, to delete this key",
+ "deleteVaultWarning": "Key Used in Wallet",
+ "vaultWarningSubtitle": "This key cannot be deleted because it is used by the wallet below.",
+ "deleteVaultInstruction": "Keep this key until the wallet no longer needs it. Hiding a wallet does not remove its key references.",
+ "deleteMultipleVaultWarning": "Key Used in Multiple Wallets",
+ "multipleVaultWarningSubtitle": "This key cannot be deleted because it is used by the wallets below.",
+ "deleteMultipleVaultInstruction": "Keep this key until these wallets no longer need it. Hiding a wallet does not remove its key references.",
"viewVault": "View Vault",
"back": "Back",
"continue": "Continue",
@@ -1758,8 +1792,8 @@
"masterKeyTitle": "Master Recovery Key",
"masterKeyDescp": "Backup 12-word phrase",
"masterKeyParagraph1": "Each of the vault (multi-key wallet) has configuration details that are needed during recovery.",
- "masterKeyParagraph2": "Your app’s meta data along with all the configuration files are stored on the Keeper cloud server encrypted with the Recovery Key.",
- "masterKeyParagraph3": "Simply backing up or noting down the Master Recovery Key gives you access to all this data which is updated automatically.",
+ "masterKeyParagraph2": "When enabled, protected backup stores an encrypted copy of this app’s recovery data. Older encrypted recovery copies may remain read-only.",
+ "masterKeyParagraph3": "Keep your Recovery Key safe to check available backups. Automatic updates apply only while protected backup is enabled; recovery depends on the copy and records available.",
"masterKeyNote": "Master Recovery Key also gives access to the app’s hot keys. Please secure the key properly.",
"personalCloudTitle": "Personal Cloud Backup",
"personalCloudParagph1": "Wallet configuration files for vaults can additionally be stored on users’ personal cloud. This ensures that the user has access to them even if they do not have the Keeper app.",
@@ -2021,7 +2055,7 @@
"canaryVaultFailed": "Canary wallet creation failed",
"importedWalletFailed": "Wallet import failed!",
"vaultAlreadyExists": "Vault {0} already exists",
- "unableToDeleteAssistedServer": "Unable to delete backup from Assisted Server, Please try again later.",
+ "unableToDeleteAssistedServer": "Could not confirm protected-backup deletion. Your local wallets and Recovery Key are unchanged. Check the backup status before trying again.",
"processFailed": "Process Failed",
"ErrorMappingUnknownSigner": "Error mapping unknown signer to signer",
"scanValidQR": "Please scan a valid QR",
@@ -2152,6 +2186,15 @@
"psbtMissingSignature": "This PSBT does not include a signature for the selected signer"
},
"usdtWalletText": {
+ "pausedTitle": "USDT activity is limited",
+ "pausedBody": "New USDT wallets, sending, buying, selling and swapping are paused. This wallet, its balance and history remain available.",
+ "sendingPausedTitle": "USDT sending is paused",
+ "sendingPausedBody": "Keeper cannot send USDT from this wallet right now. Your wallet details, balance and transaction history remain available.",
+ "receivePausedWarning": "This is your wallet's saved receive address. Keeper cannot send USDT from this wallet while sending is paused. Funds received here cannot be sent through Keeper during the pause. Do not deposit new USDT unless you understand this limitation.",
+ "statusUnavailable": "Status unavailable",
+ "legacyRequestTitle": "Earlier USDT request",
+ "legacyRequestNotice": "Keeper can no longer verify this earlier USDT request. If it completed, it may also appear as a separate on-chain transaction.",
+ "requestedAmount": "Requested Amount",
"pickWalletType": "Pick Your Wallet Type",
"selectCurrency": "Select the currency you would like to use",
"bitcoinWallet": "Bitcoin Wallet",
@@ -2217,5 +2260,77 @@
"disclaimerPoint3": "Your messages are processed securely to help Ask Keeper respond.",
"disclaimerLearnMore": "Learn more about Ask Keeper",
"disclaimerCta": "Got it"
- }
-}
\ No newline at end of file
+ },
+ "recoveryBackup": {
+ "lastOperationGuidance": "Details describe the last unsuccessful operation. Check Again performs a new read-only check and replaces these details.",
+ "deleteNotEnrolled": "No protected copy has been enrolled for this account, so deletion was not confirmed. Older read-only copies and local recovery data are kept. View backup status and choose Back Up Now to create a protected copy, or turn off automatic backup to keep it off.",
+ "viewStatus": "View backup status",
+ "dismiss": "Dismiss",
+ "automaticOn": "Automatic backup is on. Verification of the protected copy is shown below.",
+ "automaticOff": "Automatic backup is off. Existing copies are kept.",
+ "backUpGuidance": "Back Up Now checks this device’s recovery data before updating the protected copy. Records that need review will not be replaced. Check Again only reads the current backup status.",
+ "showDetails": "Show check details",
+ "hideDetails": "Hide check details",
+ "detailsLabel": "Last check details (no recovery data)",
+ "httpStatus": "HTTP status",
+ "elapsed": "Elapsed",
+ "appBuild": "App version (build)",
+ "title": "Protected 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": "Automatic backup is off",
+ "body": "Future automatic updates are stopped. Existing backup copies were not deleted."
+ },
+ "checking": {
+ "title": "Checking protected backup",
+ "body": "Comparing the encrypted protected copy with recovery data on this device."
+ },
+ "different": {
+ "title": "Your protected backup needs updating",
+ "body": "Back Up Now updates only the protected copy when checks to preserve recovery data pass. Missing or different records may need review. Updates include hidden and archived items. Older read-only copies are unchanged. Check your other Keeper devices first; Keeper reads back and verifies an accepted update."
+ },
+ "preparing": {
+ "title": "Preparing protected backup",
+ "body": "Preparing and encrypting the recovery data on this device."
+ },
+ "uploading": {
+ "title": "Updating protected backup",
+ "body": "Sending your encrypted protected copy to Keeper’s server."
+ },
+ "verifying": {
+ "title": "Verifying protected backup",
+ "body": "Reading back the protected copy and checking that its recovery data matches."
+ },
+ "verified": {
+ "title": "Protected backup verified",
+ "body": "This protected copy matches the recovery data checked on this device. Older read-only copies may also remain. Keep your Recovery Key safe."
+ },
+ "conflict": {
+ "title": "Protected backup needs review",
+ "body": "The protected copy contains recovery data that is missing or different on this device. Keeper has not replaced it. Check your other Keeper devices, then check again."
+ },
+ "unverified": {
+ "title": "Protected backup not verified",
+ "body": "Keeper could not confirm that the protected copy matches. Authorization, connection, size or changed data may prevent a complete check. Check again before assuming it is complete."
+ },
+ "retainedCopyNotice": "Older encrypted recovery copies may remain read-only. This status applies only to the protected copy.",
+ "deleted": {
+ "title": "Protected backup was deleted",
+ "body": "The protected copy has a confirmed deletion record. Older read-only recovery copies may remain and are never restored automatically. Local wallets and your Recovery Key are kept."
+ },
+ "deletionRecordedTitle": "Protected backup deletion recorded",
+ "deletionRecordedBody": "Keeper previously confirmed deletion of this protected copy. Check Again to confirm current status. Older read-only copies may remain.",
+ "never-enrolled": {
+ "title": "No protected backup yet",
+ "body": "This account has not enrolled a protected copy. You can enable protected backup from Backup and Recovery. Older read-only copies may remain."
+ },
+ "notificationTitle": "Check your protected backup",
+ "notificationBody": "Your protected backup may differ from this device. Older read-only copies may remain. View details to check it.",
+ "retryNotificationTitle": "Protected backup update not confirmed",
+ "retryNotificationBody": "Keeper could not confirm the protected backup update. Your local recovery data is kept. View details before trying again; older read-only copies may remain."
+}
+}
diff --git a/src/context/Localization/language/es.json b/src/context/Localization/language/es.json
index a59ae5abda..5f9e0ca12b 100644
--- a/src/context/Localization/language/es.json
+++ b/src/context/Localization/language/es.json
@@ -185,6 +185,7 @@
"help": "Help"
},
"login": {
+ "startupCredentialError": "Unable to check your passcode. Please try again.",
"welcomeback": "Welcome Back",
"welcome": "Welcome",
"welcomeToBitcoinKeeper": "Welcome to Bitcoin Keeper",
@@ -194,7 +195,7 @@
"MismatchPasscode": "Passcodes do not match",
"enter_your": "Enter your ",
"NewSatrtWalet": "A new hot wallet will be created automatically for you. You can create and manage different kinds of wallets from the wallets section of the app.",
- "RecoverExistingAppDesc": "Have an inaccessible Keeper app with wallets in it? You have nothing to worry if you have that app's 12-word Recovery Key. Insert the words in the Recovery section on the welcome screen and all your wallets will be restored as expected.",
+ "RecoverExistingAppDesc": "Usa la clave de recuperación de esta app Keeper para comprobar su copia protegida disponible. Recuperar una copia anterior de solo lectura es una opción separada y puede no incluir los cambios más recientes.",
"RecoverApp": "Recover an existing app:",
"Wait": "This step will take a few seconds. You will be able to proceed soon",
"Createpasscode": "Create a passcode",
@@ -223,8 +224,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",
@@ -437,6 +438,10 @@
"faucetDailyLimitTitle": "Daily Limit Reached",
"faucetDailyLimitBody": "You can request test sats up to 5 times per day. Try again after midnight UTC.",
"faucetDailyLimitError": "Daily limit reached. Try again after midnight UTC.",
+ "faucetPendingTitle": "Los sats de prueba siguen pendientes",
+ "faucetPropagationPending": "El grifo envió sats de prueba, pero la cartera aún no ve la transacción. El saldo puede tardar en actualizarse.",
+ "faucetSyncPending": "El grifo envió sats de prueba, pero la cartera no pudo sincronizarse. Comprueba la conexión al servidor antes de volver a solicitarlos.",
+ "faucetOutcomeUnknown": "La solicitud al grifo agotó el tiempo de espera. Puede que ya se hayan enviado sats de prueba. Comprueba el saldo antes de volver a solicitarlos.",
"Singlekey": "Single-key",
"multikey2of3": "2 of 3 multi-key",
"multikey3of5": "3 of 5 multi-key",
@@ -655,11 +660,13 @@
"addEmergencyKey": "Add Emergency Key",
"availableAfterDelay": "Key will be available after time-delay",
"inheritanceKeyActivation": "Inheritance Key Activation",
+ "inheritanceActivationNote": "La activación se fija al crear esta versión de la billetera; cualquier bloqueo temporal de la billetera se suma al plazo seleccionado. Recibir o gastar fondos no reinicia el plazo. Para reiniciarlo hay que crear una nueva versión de la billetera y transferir los fondos.",
"emergencyKeyActivation": "Emergency Key Activation",
"changeKey": "Change Key",
"selectActivationTime": "Select activation time",
"chooseNewActivationTimeTitle": "Choose New Activation Time",
"chooseNewActivationTimeDesc": "Please choose the new time for your Inheritance Key to become active",
+ "chooseNewEmergencyActivationTimeDesc": "Please choose the new time for your Emergency Key to become active",
"scanQR": "Scan QR",
"scanOrUpload": "Please scan the QR or upload an image",
"nfcOnTap": "NFC on tap",
@@ -783,16 +790,17 @@
"backupPhrase": "Recovery Key",
"walletSeedWords": "Recovery Key",
"enterRecoveryPhrase": "Recover an existing Keeper App",
- "enterRecoveryPhraseSubTitle": "Enter existing 12-word recovery phrase below",
+ "enterRecoveryPhraseSubTitle": "Introduce la clave de recuperación de 12 palabras de esta app Keeper. Primero se comprueba la copia protegida.",
"walletRecoveryPhrase": "Wallet Recovery Phrase",
"showXPubNoteSubText": "Losing your Wallet Seed Words may result in permanent loss of funds. Store them carefully.",
"mobileKeyVerified": "Mobile Key verified successfully",
"seedWordVerified": "Seed Words verified successfully",
"keeperVerified": "Keeper Verified Successfully",
"SeedErrorToast": "Please fill in all seed word fields",
- "appRecoveredSuccessfulTitle": "App Recovered Successfully!",
- "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",
+ "appRecoveredSuccessfulTitle": "Copia recuperada",
+ "recoveryIncomplete": "La recuperación no se completó. No se pudieron comprobar o restaurar todos los datos disponibles. No se seleccionó ninguna copia anterior automáticamente.",
+ "appRecoveredSuccessfulSubTitle": "Se comprobaron y restauraron los datos de recuperación disponibles de la copia seleccionada.",
+ "appRecoveredSuccessfulDesc": "Las claves de firma de hardware permanecen en sus dispositivos. Revisa los registros recuperados antes de activar la copia protegida.",
"mobileKey": "Mobile Key",
"mobileKeySeedWordsTitle": "Mobile Key Seed Words",
"mobileKeySeedNoteSubTitle": "The QR below comprises of your 12-word Mobile Key",
@@ -800,7 +808,24 @@
"storeSecurely": "Write down these words and store them securely.",
"enterAmountToSend": "Enter Amount to Send",
"feePriority": "Fee Priority",
- "seedKey": "Seed Key"
+ "seedKey": "Seed Key",
+ "protectedRecoveryAbsentTitle": "No hay copia protegida",
+ "protectedRecoveryAbsentBody": "Esta clave de recuperación no tiene una copia protegida. Puedes elegir buscar una copia anterior de solo lectura.",
+ "protectedRecoveryDeletedTitle": "Tu copia protegida fue eliminada",
+ "protectedRecoveryDeletedBody": "Keeper no restaurará una copia anterior automáticamente. Una copia anterior de solo lectura puede ser previa a la eliminación y omitir cambios recientes.",
+ "protectedRecoveryErrorTitle": "No se pudo comprobar la copia protegida",
+ "protectedRecoveryErrorBody": "No se pudo comprobar la copia protegida. No se seleccionó ninguna copia anterior. Comprueba tu conexión e inténtalo de nuevo.",
+ "recoverOlderCopy": "Recuperar una copia anterior",
+ "recoverOlderCopyTitle": "¿Recuperar una copia anterior?",
+ "recoverOlderCopyBody": "Una copia anterior de solo lectura puede ser previa a la eliminación u omitir cambios recientes. Solo se recuperan los registros completos disponibles y no se activan las copias automáticas.",
+ "protectedRecoverySuccessfulTitle": "Copia protegida recuperada",
+ "protectedRecoverySuccessfulSubTitle": "Se comprobaron y restauraron los datos de recuperación disponibles de la copia protegida seleccionada.",
+ "olderRecoverySuccessfulTitle": "Copia anterior recuperada",
+ "olderRecoverySuccessfulSubTitle": "Se recuperó una copia anterior. Pueden faltar cambios recientes. Las copias automáticas siguen desactivadas.",
+ "protectedRecoveryEmptyTitle": "La copia protegida está vacía",
+ "protectedRecoveryEmptyBody": "Esta copia protegida no tiene registros de recuperación. Puedes elegir buscar una copia anterior de solo lectura.",
+ "olderRecoveryErrorTitle": "Recuperación anterior incompleta",
+ "olderRecoveryErrorBody": "No se pudo comprobar o restaurar toda la copia anterior. Guarda tu clave de recuperación y revisa la conexión y los registros disponibles antes de intentarlo de nuevo."
},
"healthcheck": {
"HealthCheck": "Perform Health Check",
@@ -1025,6 +1050,7 @@
"ManageWalletsSub": "Hide/Unhide Wallets From Homescreen",
"torSettingTitle": "Tor Settings",
"torSettingSubTitle": "Configure in-app Tor and Orbot",
+ "installedAppVersion": "Versión instalada de la app",
"versionHistoryTitle": "Version History",
"versionHistorySubTitle": "You can verify the history of your app upgrades here",
"torHeaderSubTitle": "Tor improves your network privacy. To learn more visit: https://www.torproject.org/",
@@ -1078,11 +1104,11 @@
"serverSelectionSubtitle": "Select a server you'd like to use. Add your own node for enhanced privacy.",
"publicServerNote": "It’s recommended to use your own Electrum server to protect your privacy",
"connectToServer": "Connect to Server",
- "assistedServerBackup": "Assisted Server Backup",
- "assistedServerBackupSubtitle": "Back up encrypted data using a community-run Keeper server.",
- "assistedServerDeleteBackupSubtitle": "Do you also want to delete the existing assisted server backup?",
- "assistedServerDeleteBackupModalCTA": "Delete",
- "assistedServerDeleteBackupModalSecondaryCTA": "Only disable",
+ "assistedServerBackup": "Copia protegida en el servidor",
+ "assistedServerBackupSubtitle": "Guarda una nueva copia cifrada y protegida. Pueden quedar copias anteriores de solo lectura.",
+ "assistedServerDeleteBackupSubtitle": "Esto elimina la copia protegida y desactiva las copias automáticas. Pueden quedar copias cifradas anteriores de solo lectura. Se conservan las carteras y la clave de recuperación de este dispositivo. Desactivar solo las copias automáticas conserva todas las copias.",
+ "assistedServerDeleteBackupModalCTA": "Eliminar la copia protegida",
+ "assistedServerDeleteBackupModalSecondaryCTA": "Desactivar copias automáticas",
"cameraAccessoff": "Camera access is turned off",
"turnCameraOn": "Turn on the camera in your device settings",
"tapToGoSetting": "Tap to go to settings",
@@ -1128,7 +1154,13 @@
"changeWallet": "Change Wallet",
"customAmount": "Custom amount",
"sendNoteToDevelopers": "Send a note to the developers",
- "messageToDeveloper": "Message to developer"
+ "messageToDeveloper": "Message to developer",
+ "assistedServerDeleteBackupTitle": "¿Eliminar la copia protegida?",
+ "assistedServerDeleteBackupConfirmed": "Copia protegida eliminada. Pueden quedar copias cifradas anteriores. Tus carteras locales y tu clave de recuperación no han cambiado.",
+ "assistedServerBackupDisabled": "Las copias automáticas están desactivadas. Las copias existentes se conservaron.",
+ "assistedServerEnableBackupTitle": "¿Activar la copia protegida?",
+ "assistedServerEnableBackupSubtitle": "Crea o actualiza la copia protegida con los datos de recuperación de este dispositivo. Las copias anteriores de solo lectura no cambian. Guarda tu clave de recuperación.",
+ "assistedServerEnableBackupCTA": "Activar la copia protegida"
},
"onboarding": {
"security": "security",
@@ -1193,19 +1225,21 @@
"enterThe": "Enter the",
"seedWord": "seed word",
"enterSeedWordPlaceholder": "Enter seed word",
- "verifyModalTitle": "Verifying Server Backup",
- "verifyModalSubTitle": "Verifying your server backup integrity against your local data.\nThis may take a moment.",
- "backupFailedModalTitle": "Backup Verification Failed",
- "backupFailedModalSubTitle": "We couldn’t verify your data with the server backup.",
- "backupFailedModalDesc": "There might be a temporary issue with the server or your connection. Please try again later.",
- "mismatchModalTitle": "Data Mismatch Detected",
- "mismatchModalSubTitle": "Your local data doesn’t match the server backup.",
- "mismatchModalDesc": "Some recent changes may not be backed up yet. To avoid data loss, we recommend initiating a backup now.",
- "assistedServerBackupEnabled": "Assisted server backup is now enabled.\nThis will backup your encrypted data on a community-run Keeper server",
+ "verifyModalTitle": "Verificando la copia protegida",
+ "verifyModalSubTitle": "Comparando la copia protegida con los datos de recuperación de este dispositivo.\nPuede tardar un momento.",
+ "backupFailedModalTitle": "Copia protegida sin verificar",
+ "backupFailedModalSubTitle": "Keeper no pudo confirmar que la copia protegida coincida.",
+ "backupFailedModalDesc": "No se pudo comprobar la conexión, la autorización o los datos de recuperación. Conserva tus datos locales y comprueba el estado de la copia.",
+ "mismatchModalTitle": "Actualiza la copia protegida",
+ "mismatchModalSubTitle": "Los datos de recuperación del dispositivo difieren de la copia protegida.",
+ "mismatchModalDesc": "Revisa el estado antes de actualizar la copia protegida. Las copias anteriores de solo lectura no cambian.",
+ "assistedServerBackupEnabled": "La copia protegida está activada. Las actualizaciones automáticas se aplican a esta copia cifrada; pueden quedar copias anteriores de solo lectura.",
"recoveryKeyConfirmDialog": "Recovery Key confirmed",
"recoveryKeyConfirmDialogSubTitle": "Your Recovery Key is confirmed. You remain fully in control of your keys.",
"recoveryConfirmDesc1": "If you have already written down your Recovery Key, confirm it below.",
- "recoveryConfirmDesc2": "If not, write these 12 words down and store them safely. Do not store them digitally."
+ "recoveryConfirmDesc2": "If not, write these 12 words down and store them safely. Do not store them digitally.",
+ "backUpNow": "Guardar la copia protegida",
+ "retainedOlderCopyNotice": "Pueden quedar copias cifradas anteriores de solo lectura. Los cambios de la copia protegida no las actualizan ni eliminan."
},
"importWallet": {
"addDetails": "Add details",
@@ -1272,12 +1306,12 @@
"keyDeletedSuccessfully": "Key Deleted Successfully",
"keyDeletedSuccessMessage": "Your Key has been deleted successfully. You will have to add the Key again",
"manageKeys": "Manage Keys",
- "deleteVaultWarning": "Key Used in Hidden Vault",
- "vaultWarningSubtitle": "The key you're trying to delete is being used in the hidden vault mentioned below.",
- "deleteVaultInstruction": "Please change the key in the hidden vault, or delete the hidden vault, to delete this key.",
- "deleteMultipleVaultWarning": "Key Used in Multiple Hidden Vaults",
- "multipleVaultWarningSubtitle": "The key you're trying to delete is being used in the hidden vaults mentioned below.",
- "deleteMultipleVaultInstruction": "Please change the key in the hidden vaults, or delete the hidden vaults, to delete this key",
+ "deleteVaultWarning": "Key Used in Wallet",
+ "vaultWarningSubtitle": "This key cannot be deleted because it is used by the wallet below.",
+ "deleteVaultInstruction": "Keep this key until the wallet no longer needs it. Hiding a wallet does not remove its key references.",
+ "deleteMultipleVaultWarning": "Key Used in Multiple Wallets",
+ "multipleVaultWarningSubtitle": "This key cannot be deleted because it is used by the wallets below.",
+ "deleteMultipleVaultInstruction": "Keep this key until these wallets no longer need it. Hiding a wallet does not remove its key references.",
"viewVault": "View Vault",
"back": "Back",
"continue": "Continue",
@@ -1739,8 +1773,8 @@
"masterKeyTitle": "Master Recovery Key",
"masterKeyDescp": "Backup 12-word phrase",
"masterKeyParagraph1": "Each of the vault (multi-key wallet) has configuration details that are needed during recovery.",
- "masterKeyParagraph2": "Your app’s meta data along with all the configuration files are stored on the Keeper cloud server encrypted with the Recovery Key.",
- "masterKeyParagraph3": "Simply backing up or noting down the Master Recovery Key gives you access to all this data which is updated automatically.",
+ "masterKeyParagraph2": "Cuando está activada, la copia protegida guarda una copia cifrada de los datos de recuperación de esta app. Pueden quedar copias cifradas anteriores de solo lectura.",
+ "masterKeyParagraph3": "Guarda tu clave de recuperación para comprobar las copias disponibles. Las actualizaciones automáticas solo funcionan mientras la copia protegida está activada; la recuperación depende de la copia y de los registros disponibles.",
"masterKeyNote": "Master Recovery Key also gives access to the app’s hot keys. Please secure the key properly.",
"personalCloudTitle": "Personal Cloud Backup",
"personalCloudParagph1": "Wallet configuration files for vaults can additionally be stored on users’ personal cloud. This ensures that the user has access to them even if they do not have the Keeper app.",
@@ -2002,7 +2036,7 @@
"canaryVaultFailed": "Canary wallet creation failed",
"importedWalletFailed": "Wallet import failed!",
"vaultAlreadyExists": "Vault {0} already exists",
- "unableToDeleteAssistedServer": "Unable to delete backup from Assisted Server, Please try again later.",
+ "unableToDeleteAssistedServer": "No se pudo confirmar la eliminación de la copia protegida. Tus carteras locales y tu clave de recuperación no cambiaron. Comprueba el estado antes de intentarlo de nuevo.",
"processFailed": "Process Failed",
"ErrorMappingUnknownSigner": "Error mapping unknown signer to signer",
"scanValidQR": "Please scan a valid QR",
@@ -2133,6 +2167,15 @@
"psbtMissingSignature": "This PSBT does not include a signature for the selected signer"
},
"usdtWalletText": {
+ "pausedTitle": "La actividad de USDT está limitada",
+ "pausedBody": "La creación de carteras de USDT, el envío, la compra, la venta y el intercambio están pausados. Esta cartera, su saldo e historial siguen disponibles.",
+ "sendingPausedTitle": "El envío de USDT está pausado",
+ "sendingPausedBody": "Keeper no puede enviar USDT desde esta cartera ahora mismo. Los detalles, el saldo y el historial de transacciones de la cartera siguen disponibles.",
+ "receivePausedWarning": "Esta es la dirección de recepción guardada de tu cartera. Keeper no puede enviar USDT desde esta cartera mientras el envío esté pausado. Los fondos recibidos aquí no se pueden enviar mediante Keeper durante la pausa. No deposites nuevos USDT a menos que comprendas esta limitación.",
+ "statusUnavailable": "Estado no disponible",
+ "legacyRequestTitle": "Solicitud anterior de USDT",
+ "legacyRequestNotice": "Keeper ya no puede verificar esta solicitud de USDT anterior. Si se completó, también puede aparecer como una transacción separada en la cadena.",
+ "requestedAmount": "Importe solicitado",
"pickWalletType": "Pick Your Wallet Type",
"selectCurrency": "Select the currency you would like to use",
"bitcoinWallet": "Bitcoin Wallet",
@@ -2198,5 +2241,77 @@
"disclaimerPoint3": "Your messages are processed securely to help Ask Keeper respond.",
"disclaimerLearnMore": "Learn more about Ask Keeper",
"disclaimerCta": "Got it"
- }
-}
\ No newline at end of file
+ },
+ "recoveryBackup": {
+ "lastOperationGuidance": "Los detalles describen la última operación sin éxito. Comprobar de nuevo realiza una nueva consulta de solo lectura y reemplaza estos detalles.",
+ "deleteNotEnrolled": "Esta cuenta todavía no ha registrado una copia protegida, por lo que no se confirmó la eliminación. Se conservan las copias anteriores de solo lectura y los datos locales de recuperación. Consulta el estado y elige Crear copia ahora para crear una copia protegida, o desactiva las copias automáticas.",
+ "viewStatus": "Ver estado de la copia",
+ "dismiss": "Cerrar",
+ "automaticOn": "Las copias automáticas están activadas. La verificación de la copia protegida se muestra abajo.",
+ "automaticOff": "Las copias automáticas están desactivadas. Se conservan las copias existentes.",
+ "backUpGuidance": "Crear copia ahora comprueba los datos de recuperación de este dispositivo antes de actualizar la copia protegida. Los registros que necesiten revisión no se reemplazarán. Comprobar de nuevo solo consulta el estado actual.",
+ "showDetails": "Mostrar detalles de comprobación",
+ "hideDetails": "Ocultar detalles de comprobación",
+ "detailsLabel": "Detalles de la última comprobación (sin datos de recuperación)",
+ "httpStatus": "Estado HTTP",
+ "elapsed": "Duración",
+ "appBuild": "Versión de la app (compilación)",
+ "title": "Copia protegida en el servidor",
+ "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": "Copias automáticas desactivadas",
+ "body": "Las actualizaciones automáticas se detuvieron. Las copias existentes no se eliminaron."
+ },
+ "checking": {
+ "title": "Comprobando la copia protegida",
+ "body": "Comparando la copia protegida cifrada con los datos de recuperación de este dispositivo."
+ },
+ "different": {
+ "title": "Actualiza tu copia protegida",
+ "body": "Guardar ahora actualiza solo la copia protegida cuando se superan las comprobaciones para preservar los datos de recuperación. Los registros que faltan o son diferentes pueden requerir revisión. Se incluyen los elementos ocultos y archivados. Las copias anteriores de solo lectura no cambian. Revisa primero tus otros dispositivos Keeper; Keeper vuelve a leer y verificar una actualización aceptada."
+ },
+ "preparing": {
+ "title": "Preparando la copia protegida",
+ "body": "Preparando y cifrando los datos de recuperación de este dispositivo."
+ },
+ "uploading": {
+ "title": "Actualizando la copia protegida",
+ "body": "Enviando la copia protegida cifrada al servidor de Keeper."
+ },
+ "verifying": {
+ "title": "Verificando la copia protegida",
+ "body": "Leyendo la copia protegida y comprobando que sus datos de recuperación coinciden."
+ },
+ "verified": {
+ "title": "Copia protegida verificada",
+ "body": "Esta copia protegida coincide con los datos de recuperación comprobados en el dispositivo. Pueden quedar copias anteriores de solo lectura. Guarda tu clave de recuperación."
+ },
+ "conflict": {
+ "title": "Revisa la copia protegida",
+ "body": "La copia protegida contiene datos de recuperación que faltan o son diferentes en este dispositivo. Keeper no los ha reemplazado. Revisa tus otros dispositivos Keeper y vuelve a comprobar."
+ },
+ "unverified": {
+ "title": "Copia protegida sin verificar",
+ "body": "Keeper no pudo confirmar que la copia protegida coincida. La autorización, la conexión, el tamaño o los cambios de datos pueden impedir una comprobación completa. Comprueba de nuevo antes de darla por completa."
+ },
+ "retainedCopyNotice": "Pueden quedar copias cifradas anteriores de solo lectura. Este estado solo se refiere a la copia protegida.",
+ "deleted": {
+ "title": "La copia protegida fue eliminada",
+ "body": "La copia protegida tiene un registro de eliminación confirmado. Pueden quedar copias anteriores de solo lectura y nunca se restauran automáticamente. Se conservan tus carteras locales y tu clave de recuperación."
+ },
+ "deletionRecordedTitle": "Eliminación de copia protegida registrada",
+ "deletionRecordedBody": "Keeper confirmó anteriormente la eliminación de esta copia protegida. Vuelve a comprobar el estado actual. Pueden quedar copias anteriores de solo lectura.",
+ "never-enrolled": {
+ "title": "Aún no hay copia protegida",
+ "body": "Esta cuenta no ha creado una copia protegida. Puedes activarla en Copia de seguridad y recuperación. Pueden quedar copias anteriores de solo lectura."
+ },
+ "notificationTitle": "Comprueba tu copia protegida",
+ "notificationBody": "Tu copia protegida puede ser diferente de los datos de este dispositivo. Pueden quedar copias anteriores de solo lectura. Consulta los detalles para comprobarla.",
+ "retryNotificationTitle": "Actualización de copia protegida sin confirmar",
+ "retryNotificationBody": "Keeper no pudo confirmar la actualización de la copia protegida. Se conservan tus datos locales de recuperación. Consulta los detalles antes de volver a intentarlo; pueden quedar copias anteriores de solo lectura."
+}
+}
diff --git a/src/hooks/useCollaborativeWalletHandoff.ts b/src/hooks/useCollaborativeWalletHandoff.ts
new file mode 100644
index 0000000000..80e79fea6d
--- /dev/null
+++ b/src/hooks/useCollaborativeWalletHandoff.ts
@@ -0,0 +1,136 @@
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
+
+type Session = {
+ signers: Record;
+ isComplete: boolean;
+ lastSynced: number | null;
+};
+type Scope = { appId: string; network: string };
+type Pending = Scope & {
+ stage: 'add-hide' | 'session-hide' | 'reset';
+ action?: 'continue' | 'new';
+};
+
+/** Only hand off after the native modal has hidden, within the originating account/network. */
+export function useCollaborativeWalletHandoff({
+ appId,
+ network,
+ session,
+ resetSession,
+ navigate,
+}: Scope & { session: Session; resetSession: () => void; navigate: () => void }) {
+ const [addVisible, setAddVisible] = useState(false);
+ const [sessionVisible, setSessionVisible] = useState(false);
+ const [stage, setStage] = useState(null);
+ const scope = useRef(null);
+ const latestSession = useRef(session);
+ const pending = useRef(null);
+
+ useLayoutEffect(() => {
+ scope.current = { appId, network };
+ pending.current = null;
+ setStage(null);
+ setAddVisible(false);
+ setSessionVisible(false);
+ return () => {
+ scope.current = null;
+ pending.current = null;
+ };
+ }, [appId, network]);
+
+ useLayoutEffect(() => {
+ latestSession.current = session;
+ }, [session]);
+
+ const isCurrent = useCallback(
+ (request: Pending) =>
+ !!scope.current?.appId &&
+ scope.current.appId === request.appId &&
+ scope.current.network === request.network,
+ []
+ );
+
+ const beginReset = useCallback(
+ (request: Pending) => {
+ if (!isCurrent(request)) return;
+ pending.current = { ...request, stage: 'reset' };
+ setStage('reset');
+ resetSession();
+ },
+ [isCurrent, resetSession]
+ );
+
+ useEffect(() => {
+ const request = pending.current;
+ if (
+ stage === 'reset' &&
+ request?.stage === 'reset' &&
+ isCurrent(request) &&
+ Object.keys(session.signers).length === 0 &&
+ !session.isComplete &&
+ session.lastSynced === null
+ ) {
+ pending.current = null;
+ setStage(null);
+ navigate();
+ }
+ }, [stage, isCurrent, navigate, session]);
+
+ const cancel = useCallback(() => {
+ pending.current = null;
+ setStage(null);
+ }, []);
+
+ return {
+ addVisible,
+ sessionVisible,
+ waitForAddHide: stage === 'add-hide',
+ waitForSessionHide: stage === 'session-hide',
+ openAdd: () => {
+ if (!pending.current && !sessionVisible) setAddVisible(true);
+ },
+ closeAdd: () => {
+ cancel();
+ setAddVisible(false);
+ },
+ closeSession: () => {
+ cancel();
+ setSessionVisible(false);
+ },
+ selectCollaborative: () => {
+ if (!addVisible || pending.current || !scope.current?.appId) return;
+ pending.current = { ...scope.current, stage: 'add-hide' };
+ setStage('add-hide');
+ setAddVisible(false);
+ },
+ onAddHide: () => {
+ const request = pending.current;
+ if (request?.stage !== 'add-hide' || !isCurrent(request)) return;
+ // Consume the hide once before opening another modal or dispatching a reset.
+ pending.current = null;
+ setStage(null);
+ if (Object.keys(latestSession.current.signers).length > 0) {
+ setSessionVisible(true);
+ } else {
+ beginReset(request);
+ }
+ },
+ finishSession: (action: 'continue' | 'new') => {
+ if (!sessionVisible || pending.current || !scope.current?.appId) return;
+ pending.current = { ...scope.current, stage: 'session-hide', action };
+ setStage('session-hide');
+ setSessionVisible(false);
+ },
+ onSessionHide: () => {
+ const request = pending.current;
+ if (request?.stage !== 'session-hide' || !isCurrent(request)) return;
+ pending.current = null;
+ setStage(null);
+ if (request.action === 'continue') {
+ if (Object.keys(latestSession.current.signers).length > 0) navigate();
+ } else {
+ beginReset(request);
+ }
+ },
+ };
+}
diff --git a/src/hooks/useSettingKeeper.tsx b/src/hooks/useSettingKeeper.tsx
index d9242915b3..63c4292a02 100644
--- a/src/hooks/useSettingKeeper.tsx
+++ b/src/hooks/useSettingKeeper.tsx
@@ -1,5 +1,6 @@
import { CommonActions, useIsFocused, useNavigation } from '@react-navigation/native';
import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
+import { StyleSheet } from 'react-native';
import UpgradeIcon from 'src/assets/images/UpgradeCTAs.svg';
import InheritanceContactIcon from 'src/assets/images/inheritancecontacticon.svg';
import InheritanceRecoveryIcon from 'src/assets/images/inheritanceRecoveryIcon.svg';
@@ -41,7 +42,7 @@ import { KeeperApp } from 'src/models/interfaces/KeeperApp';
import { useQuery } from '@realm/react';
import { RealmSchema } from 'src/storage/realm/enum';
import { getJSONFromRealmObject } from 'src/storage/realm/utils';
-import { useColorMode } from '@gluestack-ui/themed-native-base';
+import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
import { SubscriptionTier } from 'src/models/enums/SubscriptionTier';
import { backupAllSignersAndVaults, deleteBackup } from 'src/store/sagaActions/bhr';
import { useAppDispatch, useAppSelector } from 'src/store/hooks';
@@ -51,16 +52,16 @@ import {
setAutomaticCloudBackup,
setDeleteBackupSuccess,
setDeleteBackupFailure,
+ isAutomaticCloudBackupEnabled,
} from 'src/store/reducers/bhr';
-import useToastMessage from './useToastMessage';
-import ToastErrorIcon from 'src/assets/images/toast_error.svg';
import { setShowTipModal, setThemeMode } from 'src/store/reducers/settings';
import ThemeMode from 'src/models/enums/ThemeMode';
import { credsAuthenticated } from 'src/store/reducers/login';
import usePlan from './usePlan';
import KeeperModal from 'src/components/KeeperModal';
-import { wp } from 'src/constants/responsive';
-import Buttons from 'src/components/Buttons';
+import Text from 'src/components/KeeperText';
+import { ProtectedBackupAction } from 'src/components/Backup/ProtectedBackupActions';
+import { currentBackupAccountSession, getBackupDiagnostic } from 'src/services/backup/transport';
import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg';
import config from 'src/utils/service-utilities/config';
@@ -68,13 +69,14 @@ export const useSettingKeeper = () => {
const dispatch = useAppDispatch();
const { colorMode, toggleColorMode } = useColorMode();
const navigation = useNavigation();
- const { showToast } = useToastMessage();
const isFocused = useIsFocused();
const { isOnL2Above, isOnL4 } = usePlan();
const data = useQuery(RealmSchema.BackupHistory);
const [confirmPass, setConfirmPass] = useState(false);
const [showDeleteBackup, setShowDeleteBackup] = useState(false);
+ const [showEnableBackup, setShowEnableBackup] = useState(false);
+ const [backupFeedback, setBackupFeedback] = useState<{ appId: string; message: string }>();
const themeToggleTimeoutRef = useRef | null>(null);
const backupToggleTimeoutRef = useRef | null>(null);
const { translations } = useContext(LocalizationContext);
@@ -86,18 +88,26 @@ export const useSettingKeeper = () => {
common,
signer: signerText,
error: errorText,
+ recoveryBackup: backupCopy,
} = translations;
const { typeBasedIndicator } = useIndicatorHook({
types: [uaiType.RECOVERY_PHRASE_HEALTH_CHECK],
});
const { id }: KeeperApp = useQuery(RealmSchema.KeeperApp).map(getJSONFromRealmObject)[0];
const {
- backupAllFailure,
- backupAllSuccess,
- automaticCloudBackup,
- deleteBackupSuccess,
- deleteBackupFailure,
+ backupAllFailureByAppId,
+ backupAllSuccessByAppId,
+ automaticCloudBackupByAppId,
+ deleteBackupSuccessByAppId,
+ deleteBackupFailureByAppId,
} = useAppSelector((state) => state.bhr);
+ const automaticCloudBackup = isAutomaticCloudBackupEnabled({ automaticCloudBackupByAppId }, id);
+ const backupAccountSession = currentBackupAccountSession();
+ useEffect(() => setBackupFeedback(undefined), [id, backupAccountSession]);
+ const backupAllFailure = !!backupAllFailureByAppId?.[id];
+ const backupAllSuccess = !!backupAllSuccessByAppId?.[id];
+ const deleteBackupSuccess = !!deleteBackupSuccessByAppId?.[id];
+ const deleteBackupFailure = !!deleteBackupFailureByAppId?.[id];
useEffect(() => {
if (isOnL4) {
@@ -142,8 +152,8 @@ export const useSettingKeeper = () => {
useEffect(() => {
if (backupAllSuccess && isFocused) {
- dispatch(setBackupAllSuccess(false));
- dispatch(setAutomaticCloudBackup(true));
+ dispatch(setBackupAllSuccess({ appId: id, status: false }));
+ dispatch(setAutomaticCloudBackup({ appId: id, enabled: true }));
setTimeout(() => {
dispatch(setShowTipModal({ status: true, address: config.ADDRESS.assistServer }));
}, 1000);
@@ -152,28 +162,34 @@ export const useSettingKeeper = () => {
useEffect(() => {
if (deleteBackupSuccess && isFocused) {
- dispatch(setDeleteBackupSuccess(false));
- dispatch(setAutomaticCloudBackup(false));
+ dispatch(setDeleteBackupSuccess({ appId: id, status: false }));
+ dispatch(setAutomaticCloudBackup({ appId: id, enabled: false }));
+ setBackupFeedback({ appId: id, message: settings.assistedServerDeleteBackupConfirmed });
}
- }, [deleteBackupSuccess]);
+ }, [deleteBackupSuccess, id, isFocused]);
useEffect(() => {
if (deleteBackupFailure && isFocused) {
- dispatch(setDeleteBackupFailure(false));
- showToast(errorText.unableToDeleteAssistedServer, );
+ dispatch(setDeleteBackupFailure({ appId: id, status: false }));
+ const diagnostic = getBackupDiagnostic(id);
+ const message =
+ diagnostic?.operation === 'delete' && diagnostic.category === 'never-enrolled'
+ ? backupCopy.deleteNotEnrolled
+ : errorText.unableToDeleteAssistedServer;
+ setBackupFeedback({ appId: id, message });
}
}, [deleteBackupFailure]);
useEffect(() => {
if (backupAllFailure && isFocused) {
- dispatch(setBackupAllFailure(false));
+ dispatch(setBackupAllFailure({ appId: id, status: false }));
}
}, [backupAllFailure]);
const toggleAutomaticBackupMode = useCallback(() => {
- if (!automaticCloudBackup) dispatch(backupAllSignersAndVaults());
+ if (!automaticCloudBackup) setShowEnableBackup(true);
else setShowDeleteBackup(true);
- }, [automaticCloudBackup, dispatch]);
+ }, [automaticCloudBackup, dispatch, id]);
const debouncedAutomaticBackupToggle = useCallback(() => {
if (backupToggleTimeoutRef.current) {
@@ -261,8 +277,9 @@ export const useSettingKeeper = () => {
{
title: settings.assistedServerBackup,
description: settings.assistedServerBackupSubtitle,
+ expandDescription: true,
icon: ,
- onPress: debouncedAutomaticBackupToggle,
+ onPress: () => navigation.dispatch(CommonActions.navigate('AssistedBackupStatus')),
rightIcon: isOnL2Above ? (
) : (
@@ -456,34 +473,96 @@ export const useSettingKeeper = () => {
];
const DeleteBackupModal = (
- setShowDeleteBackup(false)}
- title={settings.assistedServerBackup}
- subTitleWidth={wp(240)}
- subTitle={settings.assistedServerDeleteBackupSubtitle}
- modalBackground={`${colorMode}.modalWhiteBackground`}
- textColor={`${colorMode}.textGreen`}
- subTitleColor={`${colorMode}.modalSubtitleBlack`}
- Content={() => (
- {
- setShowDeleteBackup(false);
- dispatch(deleteBackup());
- }}
- secondaryCallback={() => {
- setShowDeleteBackup(false);
- dispatch(setAutomaticCloudBackup(false));
- }}
- secondaryText={settings.assistedServerDeleteBackupModalSecondaryCTA}
- />
- )}
- />
+ <>
+ setShowDeleteBackup(false)}
+ title={settings.assistedServerDeleteBackupTitle}
+ modalBackground={`${colorMode}.modalWhiteBackground`}
+ textColor={`${colorMode}.textGreen`}
+ Content={() => (
+
+
+ {settings.assistedServerDeleteBackupSubtitle}
+
+ {
+ setShowDeleteBackup(false);
+ dispatch(deleteBackup(id));
+ }}
+ />
+ {
+ setShowDeleteBackup(false);
+ dispatch(setAutomaticCloudBackup({ appId: id, enabled: false }));
+ setBackupFeedback({ appId: id, message: settings.assistedServerBackupDisabled });
+ }}
+ />
+
+ )}
+ />
+ setShowEnableBackup(false)}
+ title={settings.assistedServerEnableBackupTitle}
+ modalBackground={`${colorMode}.modalWhiteBackground`}
+ textColor={`${colorMode}.textGreen`}
+ Content={() => (
+
+
+ {settings.assistedServerEnableBackupSubtitle}
+
+ {
+ setShowEnableBackup(false);
+ dispatch(backupAllSignersAndVaults(id));
+ }}
+ />
+ setShowEnableBackup(false)}
+ />
+
+ )}
+ />
+ >
);
+ const BackupFeedback =
+ backupFeedback?.appId === id ? (
+
+
+ {backupFeedback.message}
+
+ navigation.dispatch(CommonActions.navigate('AssistedBackupStatus'))}
+ />
+ setBackupFeedback(undefined)}
+ />
+
+ ) : null;
+
return {
+ BackupFeedback,
BackAndRecovery,
General,
keysAndwallet,
@@ -496,3 +575,9 @@ export const useSettingKeeper = () => {
DeleteBackupModal,
};
};
+
+const styles = StyleSheet.create({
+ modalBody: { fontSize: 14, marginBottom: 12 },
+ feedback: { marginHorizontal: 20, marginBottom: 20, padding: 20, borderRadius: 12 },
+ feedbackText: { fontSize: 14 },
+});
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/hooks/useTestSats.tsx b/src/hooks/useTestSats.tsx
index a413c2bdde..86910f60ab 100644
--- a/src/hooks/useTestSats.tsx
+++ b/src/hooks/useTestSats.tsx
@@ -8,6 +8,7 @@ import {
setTestCoinsFailed,
setTestCoinsReceived,
setTestCoinsQuotaReached,
+ setTestCoinsPending,
} from 'src/store/reducers/wallets';
import { LocalizationContext } from 'src/context/Localization/LocContext';
import { useNavigation } from '@react-navigation/native';
@@ -19,9 +20,8 @@ import KeeperModal from 'src/components/KeeperModal';
const useTestSats = ({ wallet }) => {
const { setAppLoading, setLoadingContent } = useContext(AppContext);
- const { testCoinsReceived, testCoinsFailed, testCoinsQuotaReached } = useAppSelector(
- (state) => state.wallet
- );
+ const { testCoinsReceived, testCoinsFailed, testCoinsQuotaReached, testCoinsPending } =
+ useAppSelector((state) => state.wallet);
const { bitcoinNetworkType } = useAppSelector((state) => state.settings);
const { showToast } = useToastMessage();
const dispatch = useDispatch();
@@ -30,21 +30,33 @@ const useTestSats = ({ wallet }) => {
const navigation = useNavigation();
const { colorMode } = useColorMode();
const [quotaModalVisible, setQuotaModalVisible] = useState(false);
+ const [pendingModalKind, setPendingModalKind] = useState(null);
useEffect(() => {
- setAppLoading(false);
if (testCoinsReceived) {
+ setAppLoading(false);
showToast(walletText.recievedSats, );
- setTimeout(() => {
+ const timer = setTimeout(() => {
dispatch(setTestCoinsReceived(false));
navigation.goBack();
}, 3000);
+ return () => clearTimeout(timer);
} else if (testCoinsFailed) {
+ setAppLoading(false);
showToast(errorText.processFailed);
dispatch(setTestCoinsFailed(false));
}
+ return undefined;
}, [testCoinsReceived, testCoinsFailed]);
+ useEffect(() => {
+ if (testCoinsPending) {
+ setAppLoading(false);
+ setPendingModalKind(testCoinsPending);
+ dispatch(setTestCoinsPending(null));
+ }
+ }, [testCoinsPending]);
+
useEffect(() => {
if (testCoinsQuotaReached) {
setAppLoading(false);
@@ -105,6 +117,24 @@ const useTestSats = ({ wallet }) => {
buttonText={common.ok}
buttonCallback={() => setQuotaModalVisible(false)}
/>
+ setPendingModalKind(null)}
+ title={walletText.faucetPendingTitle}
+ subTitle={
+ pendingModalKind === 'unknown'
+ ? walletText.faucetOutcomeUnknown
+ : pendingModalKind === 'sync'
+ ? walletText.faucetSyncPending
+ : walletText.faucetPropagationPending
+ }
+ modalBackground={`${colorMode}.modalWhiteBackground`}
+ textColor={`${colorMode}.textGreen`}
+ subTitleColor={`${colorMode}.modalSubtitleBlack`}
+ showCloseIcon={false}
+ buttonText={common.ok}
+ buttonCallback={() => setPendingModalKind(null)}
+ />
>
);
};
diff --git a/src/hooks/useUSDTWallets.ts b/src/hooks/useUSDTWallets.ts
index dba1d6e868..e9d1a5c556 100644
--- a/src/hooks/useUSDTWallets.ts
+++ b/src/hooks/useUSDTWallets.ts
@@ -1,5 +1,24 @@
import { useState, useCallback, useMemo } from 'react';
import { useQuery } from '@realm/react';
+import { useDispatch, useStore } from 'react-redux';
+import { useAppSelector } from 'src/store/hooks';
+import { updateAppImage } from 'src/store/sagaActions/bhr';
+import { beginBackupLocalOperation, commitBackupLocalOperation, enqueueAutomaticBackupOperation } from 'src/services/backup/automatic';
+import { canonical, recoveryContent } from 'src/services/backup/image';
+import { captureBackupWriteIntent, currentBackupAccountSession, markBackupMutation } from 'src/services/backup/transport';
+import {
+ invalidateBackupRepair,
+ isAutomaticCloudBackupEnabled,
+ setPendingAllBackup,
+} from 'src/store/reducers/bhr';
+import USDT, {
+ DEFAULT_DEADLINE_SECONDS,
+ USDTTransferOptions,
+} from '../services/wallets/operations/dollars/USDT';
+import { captureError } from '../services/sentry';
+import { RealmSchema } from '../storage/realm/enum';
+import dbManager from '../storage/realm/dbManager';
+import { NetworkType, VisibilityType } from '../services/wallets/enums';
import {
generateUSDTWallet,
syncUSDTWalletBalance,
@@ -11,24 +30,15 @@ import {
USDTWalletImportDetails,
USDTWalletSupportedNetwork,
} from '../services/wallets/factories/USDTWalletFactory';
-import { NetworkType, VisibilityType } from '../services/wallets/enums';
-import dbManager from '../storage/realm/dbManager';
-import { RealmSchema } from '../storage/realm/enum';
-import { captureError } from '../services/sentry';
-import USDT, {
- DEFAULT_DEADLINE_SECONDS,
- USDTTransferOptions,
-} from '../services/wallets/operations/dollars/USDT';
-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';
export interface UseUSDTWalletsOptions {
getAll?: boolean;
includeHidden?: boolean;
}
+// Existing USDT wallets remain readable, but new wallet creation and import are paused.
+export const USDT_WALLET_CREATION_PAUSED = true;
+
export interface UseUSDTWalletsReturn {
usdtWallets: USDTWallet[];
error: string | null;
@@ -61,7 +71,15 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall
const allWallets = useQuery(RealmSchema.USDTWallet);
const [error, setError] = useState(null);
const dispatch = useDispatch();
+ const reduxStore = useStore();
const { id: appId }: any = dbManager.getObjectByIndex(RealmSchema.KeeperApp);
+ const renderAccountSession = currentBackupAccountSession();
+ const isOriginCurrent = useCallback(
+ () =>
+ (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id === appId &&
+ reduxStore.getState().storage.appId === appId,
+ [appId, reduxStore]
+ );
const filterByNetwork = (wallets: USDTWallet[]) => {
if (bitcoinNetworkType)
@@ -79,9 +97,7 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall
// Filter hidden wallets if not included
if (!includeHidden) {
- filteredWallets = filteredWallets.filter((wallet) => {
- return wallet.presentationData.visibility !== VisibilityType.HIDDEN;
- });
+ filteredWallets = filteredWallets.filter((wallet) => wallet.presentationData.visibility !== VisibilityType.HIDDEN);
}
return filteredWallets;
@@ -98,7 +114,21 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall
primaryMnemonic?: string;
importDetails?: USDTWalletImportDetails;
}): Promise<{ newWallet?: USDTWallet; error?: string }> => {
+ const originSession = currentBackupAccountSession();
+ const originBackupWriteIntent = captureBackupWriteIntent(appId);
+ const isCurrentCreate = () =>
+ isOriginCurrent() &&
+ renderAccountSession === originSession &&
+ originSession === currentBackupAccountSession();
+ let beganLocalWrite = false;
+ let localOperation;
+ if (USDT_WALLET_CREATION_PAUSED) {
+ return { error: 'USDT wallet setup is paused' };
+ }
+
try {
+ if (!isCurrentCreate()) throw new Error('Account changed');
+ localOperation = beginBackupLocalOperation(appId, originBackupWriteIntent, originSession);
setError(null);
const walletNetworkType = USDTWalletSupportedNetwork;
const allUSDTWallets: USDTWallet[] = (await dbManager.getObjectByIndex(
@@ -107,6 +137,7 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall
null,
true // get all wallets
)) as any;
+ if (!isCurrentCreate()) throw new Error('Account changed');
let lastInstanceNum = -1;
allUSDTWallets.forEach((wallet) => {
@@ -125,6 +156,7 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall
instanceNum: params.type === USDTWalletType.DEFAULT ? lastInstanceNum + 1 : null,
importDetails: params.importDetails,
});
+ if (!isCurrentCreate()) throw new Error('Account changed');
// check if a USDT wallet already exists with the same mnemonic(especially for imported wallets)
const existingWallet = allUSDTWallets.find((wallet) => wallet.id === newWallet.id);
@@ -132,57 +164,137 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall
throw new Error('USDT wallet already exists with the same ID');
}
- await dbManager.createObject(RealmSchema.USDTWallet, newWallet);
+ beganLocalWrite = true;
+ const committedOperation = commitBackupLocalOperation(localOperation, (localRealm) => {
+ localRealm.create(RealmSchema.USDTWallet, newWallet);
+ });
+ if (!committedOperation.committed) throw new Error('Failed to create wallet');
+ if (!isCurrentCreate()) throw new Error('Account changed');
// Create usdt wallet backup
- dispatch(updateAppImage({ wallets: [newWallet], signers: null, updateNodes: false }));
+ dispatch({
+ ...updateAppImage({ wallets: [newWallet], signers: null, updateNodes: false }, appId),
+ originBackupAccountSession: originSession,
+ originBackupWriteIntent,
+ committedOperation,
+ });
return { newWallet };
} catch (err) {
+ if (beganLocalWrite && isAutomaticCloudBackupEnabled(reduxStore.getState().bhr, appId)) {
+ markBackupMutation(appId);
+ dispatch(invalidateBackupRepair(appId));
+ dispatch(setPendingAllBackup({ appId, pending: true }));
+ }
setError(err.message || 'Failed to create wallet');
captureError(err);
return { error: err.message || 'Failed to create wallet' };
}
},
- []
+ [appId, dispatch, isOriginCurrent, reduxStore, renderAccountSession]
);
/**
* Delete a wallet
*/
const deleteWallet = useCallback(async (walletId: string): Promise => {
+ const originAppId = appId;
+ const originSession = currentBackupAccountSession();
+ const originBackupWriteIntent = captureBackupWriteIntent(originAppId);
+ const isCurrentDelete = () =>
+ isOriginCurrent() &&
+ renderAccountSession === originSession &&
+ originSession === currentBackupAccountSession();
try {
- const response = await Relay.deleteAppImageEntity({
- appId,
- signers: null,
- walletIds: [walletId],
+ if (!isCurrentDelete()) return false;
+ const operation = beginBackupLocalOperation(originAppId, originBackupWriteIntent, originSession);
+ const committedOperation = commitBackupLocalOperation(operation, (localRealm) => {
+ const stored = localRealm.objectForPrimaryKey(RealmSchema.USDTWallet, walletId);
+ if (!stored) throw new Error('Wallet deletion target is missing');
+ localRealm.delete(stored);
});
- if (!response.updated) throw new Error('Failed to delete wallet');
-
- await dbManager.deleteObjectById(RealmSchema.USDTWallet, walletId);
+ if (!committedOperation.committed) throw new Error('Failed to delete wallet');
+ if (isAutomaticCloudBackupEnabled(reduxStore.getState().bhr, originAppId)) {
+ try {
+ const result = await enqueueAutomaticBackupOperation(committedOperation, [{
+ operation: 'deleteAppImageEntity', body: { appId: originAppId, signers: [], walletIds: [walletId] },
+ }]);
+ if (!result.backupConfirmed && isCurrentDelete())
+ dispatch(setPendingAllBackup({ appId: originAppId, pending: true }));
+ } catch {
+ if (isCurrentDelete()) dispatch(setPendingAllBackup({ appId: originAppId, pending: true }));
+ }
+ }
return true;
} catch (err) {
- setError(err.message || 'Failed to delete wallet');
+ if (isCurrentDelete()) setError(err.message || 'Failed to delete wallet');
captureError(err);
return false;
}
- }, []);
+ }, [appId, dispatch, isOriginCurrent, reduxStore, renderAccountSession]);
/**
* 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
-
- return true;
- } catch (err) {
- setError(err.message || 'Failed to update wallet');
- captureError(err);
- return false;
- }
- }, []);
+ const updateWallet = useCallback(
+ async (wallet: USDTWallet): Promise => {
+ const originAppId = appId;
+ const operationSession = currentBackupAccountSession();
+ const originBackupWriteIntent = captureBackupWriteIntent(originAppId);
+ const isCurrentUpdate = () =>
+ isOriginCurrent() &&
+ renderAccountSession === operationSession &&
+ operationSession === currentBackupAccountSession();
+ let recoveryChanged = false;
+ try {
+ if (!isCurrentUpdate()) return false;
+ const operation = beginBackupLocalOperation(originAppId, originBackupWriteIntent, operationSession);
+ 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;
+ if (!isCurrentUpdate()) throw new Error('Account changed');
+ const committedOperation = recoveryChanged
+ ? commitBackupLocalOperation(operation, (localRealm) => {
+ const stored = localRealm.objectForPrimaryKey(RealmSchema.USDTWallet, id);
+ if (!stored) throw new Error('Wallet not found');
+ Object.assign(stored, walletUpdateData);
+ })
+ : undefined;
+ const updated = recoveryChanged ? committedOperation.committed
+ : await dbManager.updateObjectById(RealmSchema.USDTWallet, id, walletUpdateData);
+ if (!updated) throw new Error('Failed to update wallet');
+ if (!isCurrentUpdate()) throw new Error('Account changed');
+
+ // 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 }, originAppId),
+ originBackupAccountSession: operationSession,
+ originBackupWriteIntent,
+ committedOperation,
+ });
+
+ 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 && isCurrentUpdate()) {
+ markBackupMutation(originAppId);
+ dispatch(invalidateBackupRepair(originAppId));
+ dispatch(setPendingAllBackup({ appId: originAppId, pending: true }));
+ }
+ if (isCurrentUpdate()) setError(err.message || 'Failed to update wallet');
+ captureError(err);
+ return false;
+ }
+ },
+ [appId, dispatch, isOriginCurrent, renderAccountSession]
+ );
/**
* Syncs a single wallet account status with latest data
@@ -195,13 +307,13 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall
accountStatus: updatedAccountStatus,
};
- await updateWallet(syncedWallet);
+ if (!(await updateWallet(syncedWallet))) throw new Error('Failed to persist synced wallet');
return syncedWallet;
} catch (err) {
captureError(err);
throw new Error('Failed to sync account status');
}
- }, []);
+ }, [updateWallet]);
/**
* Syncs wallet balance
@@ -217,13 +329,13 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall
},
};
- await updateWallet(syncedWallet);
+ if (!(await updateWallet(syncedWallet))) throw new Error('Failed to persist synced wallet');
return syncedWallet;
} catch (err) {
captureError(err);
return wallet;
}
- }, []);
+ }, [updateWallet]);
/**
* Syncs a single wallet with latest data
@@ -236,21 +348,19 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall
specs: updatedSpecs,
};
- await updateWallet(syncedWallet);
+ if (!(await updateWallet(syncedWallet))) throw new Error('Failed to persist synced wallet');
return syncedWallet;
} catch (err) {
captureError(err);
return wallet;
}
- }, []);
+ }, [updateWallet]);
/**
* Get wallet by ID
*/
const getWalletById = useCallback(
- (walletId: string): USDTWallet | null => {
- return usdtWallets.find((wallet) => wallet.id === walletId) || null;
- },
+ (walletId: string): USDTWallet | null => usdtWallets.find((wallet) => wallet.id === walletId) || null,
[usdtWallets]
);
diff --git a/src/hooks/useVault.ts b/src/hooks/useVault.ts
index e9a6309e95..d23b09311f 100644
--- a/src/hooks/useVault.ts
+++ b/src/hooks/useVault.ts
@@ -4,6 +4,7 @@ import { getJSONFromRealmObject } from 'src/storage/realm/utils';
import { useQuery } from '@realm/react';
import { VaultType, VisibilityType } from 'src/services/wallets/enums';
import { useAppSelector } from 'src/store/hooks';
+import { useMemo } from 'react';
type Params =
| {
@@ -25,19 +26,29 @@ const useVault = ({
getFirst = false,
getHiddenWallets = true,
}: Params) => {
- let allVaults: Vault[] = useQuery(RealmSchema.Vault);
-
+ const realmVaults = useQuery(RealmSchema.Vault) as unknown as Vault[];
const { bitcoinNetworkType } = useAppSelector((state) => state.settings);
- allVaults = includeArchived
- ? allVaults.map(getJSONFromRealmObject)
- : allVaults.filtered('archived != true').map(getJSONFromRealmObject);
- // Filter vaults based on network
- allVaults = allVaults.filter((wallet) => wallet.networkType === bitcoinNetworkType);
+ // Select before converting: toJSON traverses address, UTXO and history data.
+ // The useQuery reference changes on Realm writes, but stays stable across
+ // unrelated renders of the same screen.
+ const allVaultsIncludingCanary: Vault[] = useMemo(
+ () =>
+ realmVaults
+ .filter(
+ (vault) =>
+ (includeArchived || !vault.archived) && vault.networkType === bitcoinNetworkType
+ )
+ .map(getJSONFromRealmObject) as unknown as Vault[],
+ [realmVaults, includeArchived, bitcoinNetworkType]
+ );
//Filtering Canary Vaults from at all UI level where Vaults are consumed
- const allVaultsIncludingCanary = allVaults;
- allVaults = allVaults.filter((vault) => vault.type !== VaultType.CANARY);
- const allNonHiddenNonArchivedVaults = allVaults.filter(
- (vault) => vault.presentationData.visibility === VisibilityType.DEFAULT
+ const allVaults = useMemo(
+ () => allVaultsIncludingCanary.filter((vault) => vault.type !== VaultType.CANARY),
+ [allVaultsIncludingCanary]
+ );
+ const allNonHiddenNonArchivedVaults = useMemo(
+ () => allVaults.filter((vault) => vault.presentationData.visibility === VisibilityType.DEFAULT),
+ [allVaults]
);
if (!vaultId) {
if (getHiddenWallets) {
diff --git a/src/hooks/useWalletRefresh.ts b/src/hooks/useWalletRefresh.ts
new file mode 100644
index 0000000000..f1ba509f7c
--- /dev/null
+++ b/src/hooks/useWalletRefresh.ts
@@ -0,0 +1,59 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useDispatch } from 'react-redux';
+import { Vault } from 'src/services/wallets/interfaces/vault';
+import { Wallet } from 'src/services/wallets/interfaces/wallet';
+import { useAppSelector } from 'src/store/hooks';
+import {
+ clearRefreshRequest,
+ startRefreshRequest,
+} from 'src/store/reducers/wallets';
+import { autoSyncWallets, refreshWallets } from 'src/store/sagaActions/wallets';
+
+let nextRefreshRequest = 0;
+
+export const useWalletRefresh = () => {
+ const dispatch = useDispatch();
+ const [requestId, setRequestId] = useState(null);
+ const inFlight = useRef(null);
+ const status = useAppSelector((state) =>
+ requestId ? state.wallet.refreshRequests[requestId] : undefined
+ );
+
+ useEffect(() => {
+ if (requestId && status !== 'pending') {
+ inFlight.current = null;
+ setRequestId(null);
+ dispatch(clearRefreshRequest(requestId));
+ }
+ }, [dispatch, requestId, status]);
+
+ useEffect(() => () => {
+ if (inFlight.current) dispatch(clearRefreshRequest(inFlight.current));
+ }, [dispatch]);
+
+ const start = useCallback(
+ (actionForRequest: (id: string) => { type: string; payload: any }) => {
+ if (inFlight.current) return;
+ const id = `wallet-refresh-${Date.now()}-${++nextRefreshRequest}`;
+ inFlight.current = id;
+ dispatch(startRefreshRequest(id));
+ setRequestId(id);
+ dispatch(actionForRequest(id));
+ },
+ [dispatch]
+ );
+
+ const refresh = useCallback(
+ (wallets: (Wallet | Vault)[], options: { hardRefresh?: boolean; dustScan?: boolean }) => {
+ if (!wallets?.length || wallets.some((wallet) => !wallet)) return;
+ start((id) => refreshWallets(wallets, options, id));
+ },
+ [start]
+ );
+
+ const autoRefresh = useCallback(() => {
+ start((id) => autoSyncWallets(false, false, true, undefined, false, id));
+ }, [start]);
+
+ return { refreshing: !!requestId && status !== 'success' && status !== 'failure', refresh, autoRefresh };
+};
diff --git a/src/hooks/useWallets.tsx b/src/hooks/useWallets.tsx
index 79eb7aeee1..284e039d1f 100644
--- a/src/hooks/useWallets.tsx
+++ b/src/hooks/useWallets.tsx
@@ -2,46 +2,63 @@ import { Wallet } from 'src/services/wallets/interfaces/wallet';
import { RealmSchema } from 'src/storage/realm/enum';
import { getJSONFromRealmObject } from 'src/storage/realm/utils';
import { VisibilityType, WalletType } from 'src/services/wallets/enums';
-import { useObject, useQuery } from '@realm/react';
+import { useQuery } from '@realm/react';
import { useAppSelector } from 'src/store/hooks';
+import { useMemo } from 'react';
type useWalletsInterface = ({ getAll, walletIds }?: { getAll?: boolean; walletIds?: string[] }) => {
wallets: Wallet[];
};
+const filterByNetwork = (wallets: Wallet[], bitcoinNetworkType?: string): Wallet[] =>
+ bitcoinNetworkType
+ ? (wallets
+ .filter((wallet) => wallet.networkType === bitcoinNetworkType)
+ .map(getJSONFromRealmObject) as unknown as Wallet[])
+ : wallets;
+
const useWallets: useWalletsInterface = ({ walletIds = [], getAll = false } = {}) => {
const { bitcoinNetworkType } = useAppSelector((state) => state.settings);
- const allWallets: Wallet[] = useQuery(RealmSchema.Wallet).filter((wallet) =>
- [WalletType.DEFAULT, WalletType.IMPORTED].includes(wallet.type)
- );
-
- const filterByNetwork = (wallets) => {
- if (bitcoinNetworkType)
- return wallets
- .map(getJSONFromRealmObject)
- .filter((wallet) => wallet.networkType === bitcoinNetworkType);
- else return wallets;
- };
+ const realmWallets = useQuery(RealmSchema.Wallet) as unknown as Wallet[];
+ const validWalletIds = walletIds?.filter((item) => !!item) || [];
+ const walletIdsKey = JSON.stringify(validWalletIds);
+ const hasWalletIds = validWalletIds.length > 0;
+
+ // useQuery changes its collection reference when Realm reports an insert,
+ // deletion, or modification. Other screen renders can reuse this snapshot.
+ const listedWallets = useMemo(() => {
+ if (hasWalletIds && !getAll) return [];
+ const regularWallets = realmWallets.filter(
+ (wallet) => wallet.type === WalletType.DEFAULT || wallet.type === WalletType.IMPORTED
+ );
+ const visibleWallets = getAll
+ ? regularWallets
+ : regularWallets.filter(
+ (wallet) => wallet.presentationData.visibility == VisibilityType.DEFAULT
+ );
+ return filterByNetwork(visibleWallets, bitcoinNetworkType);
+ }, [realmWallets, bitcoinNetworkType, getAll, hasWalletIds]);
+
+ // Resolve IDs from the same reactive query. Calling useObject in a loop
+ // changes the number of hooks when a route gains or loses an ID.
+ const selectedWallets = useMemo(() => {
+ if (getAll || !hasWalletIds) return [];
+ const ids = JSON.parse(walletIdsKey) as string[];
+ const matched = ids
+ .map((id) => realmWallets.find((wallet) => wallet.id === id))
+ .filter((wallet): wallet is Wallet => !!wallet);
+ return filterByNetwork(matched, bitcoinNetworkType);
+ }, [realmWallets, bitcoinNetworkType, getAll, hasWalletIds, walletIdsKey]);
if (getAll) {
- return { wallets: filterByNetwork(allWallets) };
+ return { wallets: listedWallets };
}
- const allWalletsNonHidden = allWallets.filter(
- (wallet) => wallet.presentationData.visibility == VisibilityType.DEFAULT
- );
- walletIds = walletIds?.filter((item) => !!item);
- if (walletIds && walletIds.length) {
- const extractedWallets = [];
- for (let index = 0; index < walletIds.length; index += 1) {
- const id = walletIds[index];
- const wallet: Wallet = useObject(RealmSchema.Wallet, id);
- if (wallet) extractedWallets.push(wallet);
- }
- return { wallets: filterByNetwork(extractedWallets) };
+ if (hasWalletIds) {
+ return { wallets: selectedWallets };
}
- return { wallets: filterByNetwork(allWalletsNonHidden) };
+ return { wallets: listedWallets };
};
export default useWallets;
diff --git a/src/navigation/AppStateHandler.tsx b/src/navigation/AppStateHandler.tsx
index 342f2ab15e..34ef589e62 100644
--- a/src/navigation/AppStateHandler.tsx
+++ b/src/navigation/AppStateHandler.tsx
@@ -1,8 +1,9 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { AppState, Linking } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { useDispatch } from 'react-redux';
import { setHasDeepLink } from 'src/store/reducers/login';
+import { autoSyncWallets } from 'src/store/sagaActions/wallets';
const PASSCODE_TIMEOUT = 5 * 60 * 1000;
@@ -11,28 +12,29 @@ const AppStateHandler = () => {
const [appState, setAppState] = useState(AppState.currentState);
const [lastBackgroundTime, setLastBackgroundTime] = useState(null);
const dispatch = useDispatch();
- let triggeredDeepLink = null;
+ const triggeredDeepLink = useRef(null);
useEffect(() => {
- Linking.addEventListener('url', (event) => {
- if (event.url) triggeredDeepLink = event.url;
+ const subscription = Linking.addEventListener('url', (event) => {
+ if (event.url) triggeredDeepLink.current = event.url;
});
- // cleanup is performed in initialAppController for all url events at once.
+ return () => subscription.remove();
+ }, []);
+ useEffect(() => {
const handleAppStateChange = (nextAppState) => {
if (appState === 'active' && nextAppState.match(/inactive|background/)) {
setLastBackgroundTime(Date.now());
} else if (appState.match(/inactive|background/) && nextAppState === 'active') {
// App is coming to the foreground, check elapsed time
const state = navigation.getState();
- const notLoginStack = state?.routes[state.index]?.name !== 'LoginStack';
-
- if (
- notLoginStack &&
- lastBackgroundTime &&
- Date.now() - lastBackgroundTime > PASSCODE_TIMEOUT
- ) {
- dispatch(setHasDeepLink(triggeredDeepLink));
+ const activeRoute = state?.routes[state.index];
+ const notLoginStack = activeRoute?.name !== 'LoginStack';
+ const timedOut = lastBackgroundTime && Date.now() - lastBackgroundTime > PASSCODE_TIMEOUT;
+
+ if (notLoginStack && timedOut) {
+ dispatch(setHasDeepLink(triggeredDeepLink.current));
+ triggeredDeepLink.current = null;
navigation.reset({
index: 0,
routes: [
@@ -44,6 +46,14 @@ const AppStateHandler = () => {
},
],
});
+ } else if (activeRoute?.name === 'App') {
+ // The transient login.isAuthenticated flag is cleared after unlock.
+ // Only an active, unlocked app session should poll archived Vaults.
+ const childState = activeRoute.state;
+ const childRoute = childState?.routes[childState.index || 0];
+ if (childRoute?.name !== 'Login') {
+ dispatch(autoSyncWallets(false, false, false, undefined, true));
+ }
}
}
setAppState(nextAppState);
diff --git a/src/navigation/Navigator.tsx b/src/navigation/Navigator.tsx
index d5ecfc5bbc..b89ab6a517 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';
@@ -153,13 +154,8 @@ import SetupAdditionalServerKey from 'src/screens/SigningDevices/SetupAdditional
import { MultiUserScreen } from 'src/screens/AppSettings/MultiUserScreen';
import { AddMultipleXpubFiles } from 'src/screens/AddSigner/AddMultipleXpubFiles';
import { SignMessageScreen } from 'src/screens/WalletDetails/SignMessageScreen';
-import AddUsdtWallet from 'src/screens/USDT/UsdtAddWallet';
import UsdtDetails from 'src/screens/USDT/UsdtDetails';
import RecieveUsdt from 'src/screens/USDT/RecieveUsdt';
-import BuyUstd from 'src/screens/USDT/BuyUstd';
-import SendUsdt from 'src/screens/USDT/SendUsdt';
-import UsdtAmount from 'src/screens/USDT/UsdtAmount';
-import UsdtSendConfirmation from 'src/screens/USDT/UsdtSendConfirmation';
import UsdtTransactionDetail from 'src/screens/USDT/UsdtTransactionDetail';
import UsdtTransactionHistory from 'src/screens/USDT/UsdtTransactionHistory';
import Usdtsetting from 'src/screens/USDT/Usdtsetting';
@@ -169,8 +165,6 @@ import KeeperSupport from 'src/screens/KeeperConcierge/KeeperSupport';
import Advisors from 'src/screens/Advisors/Advisors';
import FilterAdvisor from 'src/screens/Advisors/FilterAdvisor';
import AdvisorDetail from 'src/screens/Advisors/AdvisorDetail';
-import { Swaps } from 'src/screens/Home/components/buyBtc/Swap/Swaps';
-import { SwapDetails } from 'src/screens/Home/components/buyBtc/Swap/SwapDetails';
import { SwapHistory } from 'src/screens/Home/components/buyBtc/Swap/SwapHistory';
import { SwapHistoryDetail } from 'src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail';
import { SwapAllHistory } from 'src/screens/Home/components/buyBtc/Swap/SwapAllHistory';
@@ -263,6 +257,7 @@ function AppStack() {
+
@@ -293,13 +288,8 @@ function AppStack() {
-
-
-
-
-
@@ -382,8 +372,6 @@ function AppStack() {
-
-
diff --git a/src/navigation/remoteKeyDeepLink.ts b/src/navigation/remoteKeyDeepLink.ts
new file mode 100644
index 0000000000..7df197c51a
--- /dev/null
+++ b/src/navigation/remoteKeyDeepLink.ts
@@ -0,0 +1,25 @@
+const REMOTE_KEY_PATH = /^\/app\/(dev|prod)\/remote\/([0-9a-f]{24})\/?$/;
+
+/** Return only links generated for this build's remote-key exchange. */
+export function getRemoteKeyFromDeepLink(rawUrl: string, environment: string): string | null {
+ const expectedStage = environment === 'PRODUCTION' ? 'prod' : environment === 'DEVELOPMENT' ? 'dev' : null;
+ if (!expectedStage) return null;
+
+ try {
+ const url = new URL(rawUrl);
+ if (
+ url.protocol !== 'https:' ||
+ !['bitcoinkeeper.app', 'www.bitcoinkeeper.app'].includes(url.hostname) ||
+ url.port ||
+ url.username ||
+ url.password
+ ) {
+ return null;
+ }
+
+ const match = REMOTE_KEY_PATH.exec(url.pathname);
+ return match?.[1] === expectedStage ? match[2] : null;
+ } catch {
+ return null;
+ }
+}
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/AddWalletScreen/AddNewWallet.tsx b/src/screens/AddWalletScreen/AddNewWallet.tsx
index 7f622ca730..6af1196c41 100644
--- a/src/screens/AddWalletScreen/AddNewWallet.tsx
+++ b/src/screens/AddWalletScreen/AddNewWallet.tsx
@@ -69,7 +69,7 @@ function AddNewWallet({ navigation, route }) {
const [selectedWalletType, setSelectedWalletType] = useState('');
const [customConfigModalVisible, setCustomConfigModalVisible] = useState(false);
const [showEnhancedOptionsModal, setShowEnhancedOptionsModal] = useState(false);
- const { vaultId } = route.params || {};
+ const { vaultId, isAddInheritanceKeyFromParams } = route.params || {};
const DashedCtaTextColor = ThemedColor({ name: 'DashedCtaTextColor' });
const DashedCtaBorderColor = ThemedColor({ name: 'DashedCtaBorderColor' });
const dashed_CTA_background = ThemedColor({ name: 'dashed_CTA_background' });
@@ -81,7 +81,7 @@ function AddNewWallet({ navigation, route }) {
activeVault?.scheme?.miniscriptScheme?.usedMiniscriptTypes?.includes(
MiniscriptTypes.INHERITANCE
) ||
- route.isAddInheritanceKeyFromParams ||
+ isAddInheritanceKeyFromParams ||
false
);
diff --git a/src/screens/AppSettings/AppVersionHistoty.tsx b/src/screens/AppSettings/AppVersionHistoty.tsx
index 6e411f6029..1304a8ed69 100644
--- a/src/screens/AppSettings/AppVersionHistoty.tsx
+++ b/src/screens/AppSettings/AppVersionHistoty.tsx
@@ -1,7 +1,8 @@
import React, { useContext, useState } from 'react';
import Text from 'src/components/KeeperText';
-import { ScrollView, useColorMode } from '@gluestack-ui/themed-native-base';
+import { Box, ScrollView, useColorMode } from '@gluestack-ui/themed-native-base';
import { Pressable, StyleSheet } from 'react-native';
+import DeviceInfo from 'react-native-device-info';
import VersionHistoryList from 'src/components/SettingComponent/VersionHistoryList';
import ScreenWrapper from 'src/components/ScreenWrapper';
import { RealmSchema } from 'src/storage/realm/enum';
@@ -35,6 +36,14 @@ function AppVersionHistory({ navigation }: any) {
subTitle={settings.versionHistorySubTitle}
/>
+
+
+ {settings.installedAppVersion}
+
+
+ {`${DeviceInfo.getVersion()} (${DeviceInfo.getBuildNumber()})`}
+
+
@@ -44,6 +53,13 @@ function AppVersionHistory({ navigation }: any) {
);
}
const styles = StyleSheet.create({
+ installedVersion: {
+ marginBottom: hp(24),
+ },
+ version: {
+ fontSize: 16,
+ marginTop: hp(8),
+ },
textAppId: {
textAlign: 'center',
fontSize: 10,
diff --git a/src/screens/AppSettings/AssistedBackupStatus.tsx b/src/screens/AppSettings/AssistedBackupStatus.tsx
new file mode 100644
index 0000000000..f9bc9ed8dc
--- /dev/null
+++ b/src/screens/AppSettings/AssistedBackupStatus.tsx
@@ -0,0 +1,165 @@
+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 DeviceInfo from 'react-native-device-info';
+import { RealmSchema } from 'src/storage/realm/enum';
+import { useAppDispatch, useAppSelector } from 'src/store/hooks';
+import { checkBackupFreshness, repairBackup } from 'src/store/sagaActions/bhr';
+import { isAutomaticCloudBackupEnabled } from 'src/store/reducers/bhr';
+import { isBackupVerificationCurrent } from 'src/services/backup/automatic';
+import { getBackupDiagnostic } from 'src/services/backup/transport';
+import { LocalizationContext } from 'src/context/Localization/LocContext';
+import ScreenWrapper from 'src/components/ScreenWrapper';
+import WalletHeader from 'src/components/WalletHeader';
+import { ProtectedBackupAction } from 'src/components/Backup/ProtectedBackupActions';
+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 {
+ automaticCloudBackupByAppId,
+ backupRepairStateByAppId = {},
+ backupRepairRunningByAppId = {},
+ protectedBackupStateByAppId = {},
+ } = useAppSelector((state) => state.bhr);
+ const automaticCloudBackup = isAutomaticCloudBackupEnabled({ automaticCloudBackupByAppId }, id);
+ const recordedPhase = backupRepairStateByAppId[id];
+ const phase =
+ recordedPhase === 'verified' && !isBackupVerificationCurrent(id) ? 'unverified' : recordedPhase;
+ const running = !!backupRepairRunningByAppId[id];
+ const [slow, setSlow] = useState(false);
+ const [showDetails, setShowDetails] = useState(false);
+ const diagnostic = getBackupDiagnostic(id);
+ const deletionRecorded = protectedBackupStateByAppId[id]?.status === 'deleted';
+ useEffect(() => {
+ // Preserve the last failed operation when navigating here from its result.
+ // Check Again explicitly replaces it with a fresh, read-only check.
+ if (id && !getBackupDiagnostic(id)) dispatch(checkBackupFreshness(id));
+ }, [id]);
+ useEffect(() => setShowDetails(false), [id, running]);
+ useEffect(() => {
+ setSlow(false);
+ if (!running) return undefined;
+ const timer = setTimeout(() => setSlow(true), 10_000);
+ return () => clearTimeout(timer);
+ }, [running, phase]);
+ const state = running
+ ? phase || 'checking'
+ : phase === 'deleted' || phase === 'never-enrolled'
+ ? phase
+ : phase === 'unverified'
+ ? 'unverified'
+ : !automaticCloudBackup
+ ? 'disabled'
+ : ['checking', 'preparing', 'uploading', 'verifying'].includes(phase)
+ ? 'unverified'
+ : phase || 'unverified';
+ const canBackUp =
+ automaticCloudBackup &&
+ !deletionRecorded &&
+ ['unverified', 'different', 'never-enrolled'].includes(state);
+ return (
+
+
+
+
+ {automaticCloudBackup ? copy.automaticOn : copy.automaticOff}
+
+
+
+ {copy[state].title}
+
+ {running && }
+
+ {copy[state].body}
+
+ {slow && (
+
+ {copy.slow}
+
+ )}
+ {running && (
+
+ {copy.leave}
+
+ )}
+
+ {deletionRecorded && state !== 'deleted' && (
+
+
+ {copy.deletionRecordedTitle}
+
+
+ {copy.deletionRecordedBody}
+
+
+ )}
+
+ {copy.retainedCopyNotice}
+
+ {!running && (
+
+ {canBackUp && (
+ <>
+
+ {copy.backUpGuidance}
+
+ dispatch(repairBackup(id))}
+ />
+ >
+ )}
+ dispatch(checkBackupFreshness(id))}
+ />
+ {diagnostic && (
+ <>
+
+ {copy.lastOperationGuidance}
+
+ setShowDetails((visible) => !visible)}
+ />
+ {showDetails && (
+
+ {`${copy.detailsLabel}\n${diagnostic.operation} / ${diagnostic.stage} / ${
+ diagnostic.category
+ }\n${copy.httpStatus}: ${diagnostic.httpStatus ?? '—'}; ${copy.elapsed}: ${
+ diagnostic.elapsedMs
+ } ms\n${
+ copy.appBuild
+ }: ${DeviceInfo.getVersion()} (${DeviceInfo.getBuildNumber()})`}
+
+ )}
+ >
+ )}
+
+ )}
+
+ navigation.goBack()} />
+
+
+
+ );
+}
+const styles = StyleSheet.create({
+ content: { paddingTop: hp(16), paddingBottom: hp(40) },
+ automaticStatus: { fontSize: 14, marginBottom: hp(20) },
+ card: { padding: 20, borderRadius: 16, marginBottom: hp(24) },
+ title: { fontSize: 18, marginBottom: hp(16) },
+ body: { fontSize: 14, marginTop: hp(12) },
+ notice: { fontSize: 14, marginTop: hp(8), marginBottom: hp(24) },
+});
diff --git a/src/screens/AppSettings/ManageWallets.tsx b/src/screens/AppSettings/ManageWallets.tsx
index aa67be5207..0fe9f6f0ee 100644
--- a/src/screens/AppSettings/ManageWallets.tsx
+++ b/src/screens/AppSettings/ManageWallets.tsx
@@ -1,4 +1,4 @@
-import React, { useContext, useEffect, useState, useRef } from 'react';
+import React, { useContext, useState, useRef } from 'react';
import Text from 'src/components/KeeperText';
import { StyleSheet, FlatList, TouchableOpacity } from 'react-native';
import { Box, Pressable, useColorMode, HStack } from '@gluestack-ui/themed-native-base';
@@ -42,8 +42,6 @@ import HideAllIcon from 'src/assets/images/hide_wallet.svg';
import usePlan from 'src/hooks/usePlan';
import { deleteAppImageEntity } from 'src/store/sagaActions/bhr';
import { MANAGEWALLETS } from 'src/navigation/contants';
-import { resetRealyVaultState } from 'src/store/reducers/bhr';
-import { useAppSelector } from 'src/store/hooks';
import ToastErrorIcon from 'src/assets/images/toast_error.svg';
import MiniscriptPathSelector, {
MiniscriptPathSelectorRef,
@@ -51,11 +49,33 @@ import MiniscriptPathSelector, {
import WalletHeader from 'src/components/WalletHeader';
import ThemedColor from 'src/components/ThemedColor/ThemedColor';
import USDTGreenLogo from 'src/assets/images/usdt-gree-logo.svg';
+import { currentBackupAccountSession } from 'src/services/backup/transport';
+import { isBackupVerificationCurrent } from 'src/services/backup/automatic';
+import { isAutomaticCloudBackupEnabled } from 'src/store/reducers/bhr';
+import { store } from 'src/store/store';
+import { updateRecoveryVisibility } from 'src/store/sagaActions/wallets';
enum PasswordMode {
DEFAULT = 'DEFAULT',
SHOWALL = 'SHOWALL',
}
+
+const activeRealmAppId = (): string | undefined =>
+ (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as { id: string } | undefined)?.id;
+
+type ListItemProps = {
+ title: string;
+ subtitle: string;
+ balance: number;
+ visibilityToggle: () => void;
+ isHidden: boolean;
+ onDelete: () => void;
+ icon: React.ReactNode;
+ type: EntityKind;
+ isWatchOnly: boolean;
+ canDelete: boolean;
+};
+
function ListItem({
title,
subtitle,
@@ -66,7 +86,8 @@ function ListItem({
icon,
type,
isWatchOnly,
-}) {
+ canDelete,
+}: ListItemProps) {
const { colorMode } = useColorMode();
const isDarkMode = colorMode === 'dark';
const { getSatUnit, getBalance, getCurrencyIcon } = useBalance();
@@ -75,6 +96,8 @@ function ListItem({
const HexagonIconColor = ThemedColor({ name: 'HexagonIcon' });
const isUSDTWallet = type === EntityKind.USDT_WALLET;
+ const deleteEligible = type === EntityKind.VAULT ||
+ (type === EntityKind.WALLET && (balance === 0 || isWatchOnly)) || isUSDTWallet;
return (
- {isHidden &&
- (type == 'VAULT' ||
- (type == 'WALLET' && (balance === 0 || isWatchOnly)) ||
- isUSDTWallet) && (
+ {isHidden && deleteEligible && canDelete && (
} />
)}
+ {isHidden && deleteEligible && !canDelete && !isUSDTWallet && (
+
+ Verify assisted backup before deleting
+
+ )}
state.bhr);
-
const { isOnL2Above } = usePlan();
const navigation: any = useNavigation();
const dispatch = useDispatch();
+ // The verified phase changes after the producer's final remote readback.
+ // Subscribe so Delete becomes available without leaving this screen.
+ useSelector((state: any) => state.bhr);
const [selectedWallet, setSelectedWallet] = useState(null);
const { showToast } = useToastMessage();
const miniscriptPathSelectorRef = useRef(null);
- useEffect(() => {
- if (selectedWallet?.id) {
- if (relayVaultUpdate) {
- showToast(errorText.vaultDeleted, );
- }
- if (relayVaultError) {
- showToast(errorText.failedToDeleteVault, );
- }
- dispatch(resetRealyVaultState());
- }
- }, [relayVaultUpdate, relayVaultError]);
-
const isWallet = selectedWallet?.entityKind === EntityKind.WALLET;
const isUSDTWallet = selectedWallet?.entityKind === EntityKind.USDT_WALLET;
const onProceed = () => {
if (passwordMode === PasswordMode.DEFAULT) {
updateWalletVisibility(selectedWallet, false);
- showToast(errorText.walletUnhidden, );
}
if (passwordMode === PasswordMode.SHOWALL) {
setshowAll(true);
@@ -207,20 +220,64 @@ function ManageWallets() {
};
const deleteSelectedEntity = async () => {
+ if (selectedWallet && !canDeleteRecoveryEntity(selectedWallet)) {
+ showToast('Verify your assisted backup before deleting', );
+ return;
+ }
if (selectedWallet && selectedWallet.entityKind === EntityKind.VAULT) {
- dispatch(deleteVault(selectedWallet.id));
+ const vaultId = selectedWallet.id;
+ const appId = activeRealmAppId();
+ const session = currentBackupAccountSession();
+ dispatch(deleteVault(vaultId, (deleted) => {
+ if (
+ currentBackupAccountSession() !== session ||
+ activeRealmAppId() !== appId
+ ) return;
+ if (deleted && !dbManager.getObjectById(RealmSchema.Vault, vaultId))
+ showToast(errorText.vaultDeleted, );
+ else showToast(errorText.failedToDeleteVault, );
+ }));
}
if (selectedWallet && selectedWallet.entityKind === EntityKind.WALLET) {
- dispatch(deleteAppImageEntity({ walletIds: [selectedWallet.id] }));
- showToast(errorText.waletDeleted, );
+ const walletId = selectedWallet.id;
+ const appId = activeRealmAppId();
+ const session = currentBackupAccountSession();
+ dispatch(deleteAppImageEntity({
+ walletIds: [walletId],
+ onComplete: (deleted) => {
+ if (
+ currentBackupAccountSession() !== session ||
+ activeRealmAppId() !== appId
+ ) return;
+ if (deleted && !dbManager.getObjectById(RealmSchema.Wallet, walletId))
+ showToast(errorText.waletDeleted, );
+ else showToast('Failed to delete wallet', );
+ },
+ }));
}
if (selectedWallet && selectedWallet.entityKind === EntityKind.USDT_WALLET) {
- const success = await deleteUSDTWallet(selectedWallet.id);
- if (success) showToast(errorText.waletDeleted, );
+ const walletId = selectedWallet.id;
+ const appId = activeRealmAppId();
+ const session = currentBackupAccountSession();
+ const success = await deleteUSDTWallet(walletId);
+ if (
+ currentBackupAccountSession() !== session ||
+ activeRealmAppId() !== appId
+ ) return;
+ if (success && !dbManager.getObjectById(RealmSchema.USDTWallet, walletId))
+ showToast(errorText.waletDeleted, );
else showToast('Failed to delete USDT wallet', );
}
};
+ const canDeleteRecoveryEntity = (wallet: Wallet | Vault | USDTWallet): boolean => {
+ if (wallet.entityKind === EntityKind.USDT_WALLET) return true;
+ const appId = activeRealmAppId();
+ const state = store.getState();
+ return !!appId && state.storage.appId === appId &&
+ (!isAutomaticCloudBackupEnabled(state.bhr, appId) || isBackupVerificationCurrent(appId));
+ };
+
const updateWalletVisibility = async (wallet: Wallet | Vault | USDTWallet, hide: boolean) => {
const { id, entityKind } = wallet;
const isWallet = entityKind === EntityKind.WALLET;
@@ -240,17 +297,18 @@ function ManageWallets() {
visibility: visibilityType,
},
};
- await updateUSDTWallet(updatedUSDTWallet);
+ const updated = await updateUSDTWallet(updatedUSDTWallet);
+ if (!updated) showToast('Failed to update wallet visibility', );
+ else if (!hide) showToast(errorText.walletUnhidden, );
} else {
- // case: regular wallet/vault update
- const schema = isWallet ? RealmSchema.Wallet : RealmSchema.Vault;
- dbManager.updateObjectById(schema, id, {
- presentationData: {
- name: wallet.presentationData.name,
- description: wallet.presentationData.description,
- visibility: visibilityType,
- },
- });
+ const appId = activeRealmAppId();
+ const session = currentBackupAccountSession();
+ dispatch(updateRecoveryVisibility(id, isWallet ? EntityKind.WALLET : EntityKind.VAULT,
+ visibilityType, (updated) => {
+ if (activeRealmAppId() !== appId || currentBackupAccountSession() !== session) return;
+ if (!updated) showToast('Failed to update wallet visibility', );
+ else if (!hide) showToast(errorText.walletUnhidden, );
+ }));
}
} catch (error) {
captureError(error);
@@ -402,6 +460,7 @@ function ManageWallets() {
balance={getWalletBalance(item)}
isHidden={item.presentationData.visibility === VisibilityType.HIDDEN}
isWatchOnly={isWatchOnly(item)}
+ canDelete={canDeleteRecoveryEntity(item)}
visibilityToggle={() => {
setSelectedWallet(item);
if (item.presentationData.visibility === VisibilityType.HIDDEN) {
@@ -412,6 +471,10 @@ function ManageWallets() {
}
}}
onDelete={() => {
+ if (!canDeleteRecoveryEntity(item)) {
+ showToast('Verify your assisted backup before deleting', );
+ return;
+ }
if (getWalletBalance(item) > 0 && !isWatchOnly(item)) {
setSelectedWallet(item);
setShowDeleteVaultBalanceAlert(true);
diff --git a/src/screens/AppSettings/Node/NodeSelection.tsx b/src/screens/AppSettings/Node/NodeSelection.tsx
index 71f7579a97..1112eb417d 100644
--- a/src/screens/AppSettings/Node/NodeSelection.tsx
+++ b/src/screens/AppSettings/Node/NodeSelection.tsx
@@ -4,7 +4,6 @@ import { StyleSheet } from 'react-native';
import ScreenWrapper from 'src/components/ScreenWrapper';
import TabBar from 'src/components/TabBar';
import { hp, wp } from 'src/constants/responsive';
-import AddNode from './AddNode';
import Node from 'src/services/electrum/node';
import { NodeDetail } from 'src/services/wallets/interfaces';
import useToastMessage from 'src/hooks/useToastMessage';
@@ -24,7 +23,6 @@ import {
predefinedMainnetNodes,
predefinedTestnetNodes,
} from 'src/services/electrum/predefinedNodes';
-import SelectableServerItem from './components/SelectableServerItem';
import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView';
import { CommonActions, useNavigation } from '@react-navigation/native';
import { LocalizationContext } from 'src/context/Localization/LocContext';
@@ -32,8 +30,12 @@ import { NetworkType } from 'src/services/wallets/enums';
import { updateAppImage } from 'src/store/sagaActions/bhr';
import { useAppSelector } from 'src/store/hooks';
import WalletHeader from 'src/components/WalletHeader';
+import { captureBackupWriteIntent, currentBackupAccountSession } from 'src/services/backup/transport';
+import { beginBackupLocalOperation } from 'src/services/backup/automatic';
+import SelectableServerItem from './components/SelectableServerItem';
+import AddNode from './AddNode';
-const PrivateElectrum = ({ host, port, useSSL, setHost, setPort, setUseSSL, connectionError }) => {
+function PrivateElectrum({ host, port, useSSL, setHost, setPort, setUseSSL, connectionError }) {
return (
);
-};
+}
-const PublicServer = ({ currentlySelectedNode, handleSelectNode }) => {
+function PublicServer({ currentlySelectedNode, handleSelectNode }) {
const { bitcoinNetworkType } = useAppSelector((state) => state.settings);
+
const predefinedNodes =
bitcoinNetworkType === NetworkType.TESTNET ? predefinedTestnetNodes : predefinedMainnetNodes;
return (
@@ -65,9 +68,9 @@ const PublicServer = ({ currentlySelectedNode, handleSelectNode }) => {
))}
);
-};
+}
-const NodeSelection = () => {
+function NodeSelection() {
const dispatch = useDispatch();
const navigation = useNavigation();
const { colorMode } = useColorMode();
@@ -88,6 +91,8 @@ const NodeSelection = () => {
const tabsData = [{ label: settings.publicServer }, { label: settings.privateElectrum }];
const { bitcoinNetworkType } = useAppSelector((state) => state.settings);
+ const renderedAppId = useAppSelector((state) => state.storage.appId);
+ const renderedAccountSession = currentBackupAccountSession();
const nodes: NodeDetail[] = Node.getAllNodes();
@@ -96,6 +101,12 @@ const NodeSelection = () => {
}, [nodes.length]);
const onSaveCallback = async (nodeDetail: NodeDetail) => {
+ const originAppId = renderedAppId;
+ const originBackupAccountSession = renderedAccountSession;
+ if (!originAppId || !Node.isAccountActive(originAppId) ||
+ currentBackupAccountSession() !== originBackupAccountSession) return;
+ const originBackupWriteIntent = captureBackupWriteIntent(originAppId);
+ const operation = beginBackupLocalOperation(originAppId, originBackupWriteIntent, originBackupAccountSession);
setSaveLoading(true);
// Sanitize host
@@ -110,11 +121,20 @@ const NodeSelection = () => {
}
const nodeToSave = { ...nodeDetail };
- const { saved, connectionError: nodeConnectionError } = await Node.save(nodeToSave, nodeList);
+ const { saved, committedOperation, connectionError: nodeConnectionError } = await Node.save(nodeToSave, nodeList, originAppId, operation);
+ if (!Node.isAccountActive(originAppId) || currentBackupAccountSession() !== originBackupAccountSession) {
+ setSaveLoading(false);
+ return;
+ }
if (saved) {
const updatedNodeList = Node.getAllNodes();
setNodeList(updatedNodeList);
- dispatch(updateAppImage({ wallets: null, signers: null, updateNodes: true }));
+ if (committedOperation) dispatch({
+ ...updateAppImage({ wallets: null, signers: null, updateNodes: true }, originAppId),
+ originBackupAccountSession,
+ originBackupWriteIntent,
+ committedOperation,
+ });
const newNode = updatedNodeList.find(
(node) => node.host === nodeToSave.host && node.port === nodeToSave.port
);
@@ -144,6 +164,11 @@ const NodeSelection = () => {
};
const onConnectToNode = async (selectedNode: NodeDetail) => {
+ const originAppId = renderedAppId;
+ const originBackupAccountSession = renderedAccountSession;
+ const isCurrent = () => Node.isAccountActive(originAppId) &&
+ currentBackupAccountSession() === originBackupAccountSession;
+ if (!originAppId || !isCurrent()) return;
let nodes = Node.getAllNodes();
if (
currentlySelectedNode &&
@@ -152,6 +177,7 @@ const NodeSelection = () => {
) {
// disconnect currently selected node(if connected)
await Node.disconnect(currentlySelectedNode);
+ if (!isCurrent()) return;
currentlySelectedNode.isConnected = false;
Node.update(currentlySelectedNode, { isConnected: currentlySelectedNode.isConnected });
@@ -167,11 +193,16 @@ const NodeSelection = () => {
setLoading(true);
const node = { ...selectedNode };
- const { connected, connectedTo, error } = await Node.connectToSelectedNode(node);
+ const { connected, connectedTo, error } = await Node.connectToSelectedNode(node, originAppId, originBackupAccountSession);
+ if (!isCurrent()) {
+ setLoading(false);
+ return;
+ }
if (connected) {
node.isConnected = connected;
await Node.update(node, { isConnected: connected });
+ if (!isCurrent()) return;
dispatch(electrumClientConnectionExecuted({ successful: node.isConnected, connectedTo }));
showToast(`${errorTranslations.ConnectedTo} ${connectedTo}`, );
nodes = nodes.map((item) => {
@@ -305,7 +336,7 @@ const NodeSelection = () => {
);
-};
+}
const styles = StyleSheet.create({
tabBarContainer: {
diff --git a/src/screens/AppSettings/Node/NodeSettings.tsx b/src/screens/AppSettings/Node/NodeSettings.tsx
index dc74de79ca..12a7473804 100644
--- a/src/screens/AppSettings/Node/NodeSettings.tsx
+++ b/src/screens/AppSettings/Node/NodeSettings.tsx
@@ -1,5 +1,5 @@
import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
-import React, { useContext, useEffect, useState } from 'react';
+import React, { useCallback, useContext, useState } from 'react';
import { StyleSheet, FlatList } from 'react-native';
import { hp, wp } from 'src/constants/responsive';
import { LocalizationContext } from 'src/context/Localization/LocContext';
@@ -19,13 +19,16 @@ import DowngradeToPleb from 'src/assets/images/downgradetopleb.svg';
import DowngradeToPlebDark from 'src/assets/images/downgradetoplebDark.svg';
import Buttons from 'src/components/Buttons';
import EmptyListIllustration from 'src/components/EmptyListIllustration';
-import { CommonActions, useNavigation } from '@react-navigation/native';
-import ServerItem from './components/ServerItem';
+import { CommonActions, useFocusEffect, useNavigation } from '@react-navigation/native';
import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView';
import { updateAppImage } from 'src/store/sagaActions/bhr';
import { ELECTRUM_CLIENT } from 'src/services/electrum/client';
import WalletHeader from 'src/components/WalletHeader';
import Text from 'src/components/KeeperText';
+import { captureBackupWriteIntent, currentBackupAccountSession } from 'src/services/backup/transport';
+import { beginBackupLocalOperation, commitBackupLocalOperation } from 'src/services/backup/automatic';
+import { RealmSchema } from 'src/storage/realm/enum';
+import ServerItem from './components/ServerItem';
function ElectrumDisconnectWarningContent() {
const { colorMode } = useColorMode();
@@ -39,6 +42,8 @@ function ElectrumDisconnectWarningContent() {
);
}
+type SelectedNodeAction = { node: NodeDetail; originAppId: string; originBackupAccountSession: number };
+
function NodeSettings() {
const { colorMode } = useColorMode();
const navigation = useNavigation();
@@ -48,84 +53,127 @@ function NodeSettings() {
const { showToast } = useToastMessage();
const [nodeList, setNodeList] = useState([]);
+ const [nodeListAppId, setNodeListAppId] = useState(null);
+ const [nodeListAccountSession, setNodeListAccountSession] = useState(null);
const [loading, setLoading] = useState(false);
const [electrumDisconnectWarningVisible, setElectrumDisconnectWarningVisible] = useState(false);
- const [nodeToDisconnect, setNodeToDisconnect] = useState(null);
- const [nodeToDelete, setNodeToDelete] = useState(null);
+ const [nodeToDisconnect, setNodeToDisconnect] = useState(null);
+ const [nodeToDelete, setNodeToDelete] = useState(null);
- const isNodeListEmpty = nodeList.length === 0;
const isNoNodeConnected =
!ELECTRUM_CLIENT.isClientConnected && nodeList.every((node) => !node.isConnected);
- const nodes: NodeDetail[] = Node.getAllNodes();
-
- useEffect(() => {
- setNodeList(nodes);
- }, [nodes.length]);
+ useFocusEffect(
+ useCallback(() => {
+ const appId = Node.currentAccountId();
+ setNodeListAppId(appId ?? null);
+ setNodeListAccountSession(currentBackupAccountSession());
+ setNodeList(appId ? Node.getAllNodes() : []);
+ }, [])
+ );
- const onDelete = async (selectedItem: NodeDetail) => {
+ const onDelete = async (selectedItem: NodeDetail, originAppId = nodeListAppId,
+ originBackupAccountSession = nodeListAccountSession) => {
+ if (!originAppId || originBackupAccountSession === null || !Node.isAccountActive(originAppId) ||
+ currentBackupAccountSession() !== originBackupAccountSession) return;
+ const originBackupWriteIntent = captureBackupWriteIntent(originAppId);
+ const operation = beginBackupLocalOperation(originAppId, originBackupWriteIntent, originBackupAccountSession);
const isConnected = Node.nodeConnectionStatus(selectedItem);
if (isConnected) await Node.disconnect(selectedItem);
- const status = Node.delete(selectedItem);
- if (status) {
+ if (!Node.isAccountActive(originAppId) || currentBackupAccountSession() !== originBackupAccountSession) return;
+
+ const committedOperation = commitBackupLocalOperation(operation, (localRealm) => {
+ const saved = localRealm.objects(RealmSchema.NodeConnect)
+ .filtered('id == $0 AND networkType == $1', selectedItem.id, selectedItem.networkType)[0];
+ if (!saved) throw new Error('Node deletion target is missing');
+ localRealm.delete(saved);
+ });
+ if (committedOperation.committed) {
const updatedNodes = Node.getAllNodes();
setNodeList(updatedNodes);
- dispatch(updateAppImage({ wallets: null, signers: null, updateNodes: true }));
+ dispatch({
+ ...updateAppImage({ wallets: null, signers: null, updateNodes: true }, originAppId),
+ originBackupAccountSession,
+ originBackupWriteIntent,
+ committedOperation,
+ });
}
};
const onConnectToNode = async (selectedNode: NodeDetail) => {
- let updatedNodes = Node.getAllNodes();
-
- // Disconnect the currently connected node if it's not the selected one
- const currentlySelectedNode = updatedNodes.find((node) => node.isConnected);
- if (currentlySelectedNode && currentlySelectedNode.id !== selectedNode.id) {
- await Node.disconnect(currentlySelectedNode);
- currentlySelectedNode.isConnected = false;
- Node.update(currentlySelectedNode, { isConnected: currentlySelectedNode.isConnected });
- updatedNodes = updatedNodes.map((node) =>
- node.id === currentlySelectedNode.id ? { ...currentlySelectedNode } : node
- );
- }
-
+ const originAppId = nodeListAppId;
+ const originBackupAccountSession = nodeListAccountSession;
+ const isCurrent = () => Node.isAccountActive(originAppId) &&
+ currentBackupAccountSession() === originBackupAccountSession;
+ if (!originAppId || originBackupAccountSession === null || !isCurrent()) return;
dispatch(electrumClientConnectionInitiated());
setLoading(true);
+ try {
+ const currentlySelectedNode = Node.getAllNodes().find((node) => node.isConnected);
+ if (currentlySelectedNode && currentlySelectedNode.id !== selectedNode.id) {
+ Node.disconnect(currentlySelectedNode);
+ if (!isCurrent()) return;
+ Node.update(currentlySelectedNode, { isConnected: false });
+ }
- const { connected, connectedTo, error } = await Node.connectToSelectedNode(selectedNode);
-
- if (connected) {
- selectedNode.isConnected = connected;
- Node.update(selectedNode, { isConnected: connected });
- dispatch(electrumClientConnectionExecuted({ successful: connected, connectedTo }));
- showToast(`${errorString.ConnectedTo} ${connectedTo}`, );
- } else {
- dispatch(electrumClientConnectionExecuted({ successful: connected, error }));
+ const { connected, connectedTo, error } = await Node.connectToSelectedNode(
+ selectedNode,
+ originAppId,
+ originBackupAccountSession
+ );
+ if (!isCurrent()) return;
+ if (connected) {
+ Node.update(selectedNode, { isConnected: true });
+ dispatch(electrumClientConnectionExecuted({ successful: true, connectedTo }));
+ showToast(`${errorString.ConnectedTo} ${connectedTo}`, );
+ } else {
+ dispatch(electrumClientConnectionExecuted({ successful: false, error }));
+ }
+ } catch (error) {
+ if (isCurrent()) {
+ dispatch(
+ electrumClientConnectionExecuted({
+ successful: false,
+ error: error?.message || String(error),
+ })
+ );
+ }
+ } finally {
+ if (isCurrent()) {
+ setLoading(false);
+ setNodeList(Node.getAllNodes());
+ }
}
-
- updatedNodes = updatedNodes.map((node) =>
- node.id === selectedNode.id ? { ...selectedNode } : node
- );
- setNodeList(updatedNodes);
- setLoading(false);
};
- const onDisconnectToNode = async (selectedNode: NodeDetail) => {
+ const onDisconnectToNode = async (selectedNode: NodeDetail, originAppId: string,
+ originBackupAccountSession = nodeListAccountSession) => {
+ const isCurrent = () => Node.isAccountActive(originAppId) &&
+ currentBackupAccountSession() === originBackupAccountSession;
+ if (!isCurrent()) return;
try {
setLoading(true);
Node.disconnect(selectedNode);
- selectedNode.isConnected = false;
- Node.update(selectedNode, { isConnected: selectedNode.isConnected });
- showToast(`${errorString.disconnectedFrom} ${selectedNode.host}`, );
-
- const updatedNodes = nodeList.map((node) =>
- node.id === selectedNode.id ? { ...selectedNode } : node
+ if (!isCurrent()) return;
+ Node.update(selectedNode, { isConnected: false });
+ dispatch(
+ electrumClientConnectionExecuted({
+ successful: false,
+ error: 'Disconnected from Electrum server',
+ })
);
- setNodeList(updatedNodes);
- setLoading(false);
+ showToast(`${errorString.disconnectedFrom} ${selectedNode.host}`, );
} catch (error) {
console.error('Error disconnecting electrum client', error);
- showToast(errorString.failedToDiConnect, );
+ if (isCurrent()) {
+ showToast(errorString.failedToDiConnect, );
+ }
+ } finally {
+ if (isCurrent()) {
+ setLoading(false);
+ setNodeList(Node.getAllNodes());
+ }
}
};
@@ -147,8 +195,14 @@ function NodeSettings() {
item={item}
onDelete={onDelete}
onConnectToNode={onConnectToNode}
- setNodeToDelete={setNodeToDelete}
- setNodeToDisconnect={setNodeToDisconnect}
+ setNodeToDelete={(node: NodeDetail) => {
+ if (nodeListAppId && nodeListAccountSession !== null)
+ setNodeToDelete({ node, originAppId: nodeListAppId, originBackupAccountSession: nodeListAccountSession });
+ }}
+ setNodeToDisconnect={(node: NodeDetail) => {
+ if (nodeListAppId && nodeListAccountSession !== null)
+ setNodeToDisconnect({ node, originAppId: nodeListAppId, originBackupAccountSession: nodeListAccountSession });
+ }}
setElectrumDisconnectWarningVisible={setElectrumDisconnectWarningVisible}
/>
)}
@@ -161,11 +215,11 @@ function NodeSettings() {
{isNoNodeConnected && (
- {'Currently in Offline Mode'}
+ Currently in Offline Mode
)}
@@ -192,10 +246,10 @@ function NodeSettings() {
buttonCallback={async () => {
setElectrumDisconnectWarningVisible(false);
if (nodeToDisconnect) {
- await onDisconnectToNode(nodeToDisconnect);
+ await onDisconnectToNode(nodeToDisconnect.node, nodeToDisconnect.originAppId, nodeToDisconnect.originBackupAccountSession);
setNodeToDisconnect(null);
} else if (nodeToDelete) {
- await onDelete(nodeToDelete);
+ await onDelete(nodeToDelete.node, nodeToDelete.originAppId, nodeToDelete.originBackupAccountSession);
setNodeToDelete(null);
}
}}
diff --git a/src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx b/src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx
index 7ede2e2cde..38988f8ebd 100644
--- a/src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx
+++ b/src/screens/BackupWallet/ViewRecoveryKeyScreen.tsx
@@ -1,4 +1,4 @@
-import React, { useContext, useEffect, useState } from 'react';
+import React, { useContext, useState } from 'react';
import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
import { LocalizationContext } from 'src/context/Localization/LocContext';
import ScreenWrapper from 'src/components/ScreenWrapper';
@@ -13,18 +13,11 @@ import ThemedColor from 'src/components/ThemedColor/ThemedColor';
import Buttons from 'src/components/Buttons';
import ModalWrapper from 'src/components/Modal/ModalWrapper';
import ConfirmSeedWord from 'src/components/SeedWordBackup/ConfirmSeedWord';
-import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView';
-import { backupAllSignersAndVaults, seedBackedUp } from 'src/store/sagaActions/bhr';
+import { seedBackedUp } from 'src/store/sagaActions/bhr';
import { useDispatch } from 'react-redux';
import { setRecoveryKeyStatus } from 'src/store/reducers/account';
-import { useAppSelector } from 'src/store/hooks';
import useToastMessage from 'src/hooks/useToastMessage';
import TickIcon from 'src/assets/images/icon_tick.svg';
-import {
- setAutomaticCloudBackup,
- setBackupAllFailure,
- setBackupAllSuccess,
-} from 'src/store/reducers/bhr';
type KeeperApp = {
id: string;
@@ -41,22 +34,9 @@ export const ViewRecoveryKeyScreen = ({ navigation }) => {
const [showWordIndex, setShowWordIndex] = useState('');
const seedTextColor = ThemedColor({ name: 'seedTextColor' });
const [confirmSeedModal, setConfirmSeedModal] = useState(false);
- const [loader, setLoader] = useState(false);
const dispatch = useDispatch();
- const { backupAllFailure, backupAllSuccess } = useAppSelector((state) => state.bhr);
const { showToast } = useToastMessage();
- useEffect(() => {
- if (backupAllSuccess || backupAllFailure) {
- dispatch(setBackupAllSuccess(false));
- dispatch(setBackupAllFailure(false));
- dispatch(setAutomaticCloudBackup(true));
- setLoader(false);
- showToast(backupTxt.recoveryKeyBackedUpSuccessfully, );
- navigation.goBack();
- }
- }, [backupAllSuccess, backupAllFailure]);
-
const SeedCard = ({ item, index }: { item; index }) => {
return (
{
words={words}
confirmBtnPress={() => {
setConfirmSeedModal(false);
- setLoader(true);
dispatch(seedBackedUp());
dispatch(setRecoveryKeyStatus({ appId, status: 'confirmed' }));
- dispatch(backupAllSignersAndVaults());
+ showToast(backupTxt.recoveryKeyBackedUpSuccessfully, );
+ navigation.goBack();
}}
/>
-
);
diff --git a/src/screens/Channel/ConnectChannel.tsx b/src/screens/Channel/ConnectChannel.tsx
index c4b3dec289..9ef7342a43 100644
--- a/src/screens/Channel/ConnectChannel.tsx
+++ b/src/screens/Channel/ConnectChannel.tsx
@@ -1,4 +1,4 @@
-import { ActivityIndicator, StyleSheet , TouchableOpacity} from 'react-native';
+import { ActivityIndicator, StyleSheet, TouchableOpacity } from 'react-native';
import { Box, ScrollView, VStack, useColorMode } from '@gluestack-ui/themed-native-base';
import React, { useContext, useEffect, useRef, useState } from 'react';
import ScreenWrapper from 'src/components/ScreenWrapper';
@@ -36,8 +36,9 @@ import useVault from 'src/hooks/useVault';
import { updateKeyDetails } from 'src/store/sagaActions/wallets';
import ReceiveAddress from '../Recieve/ReceiveAddress';
import ReceiveQR from '../Recieve/ReceiveQR';
-import QRScanner from 'src/components/QRScanner';
+import ChannelRequestScanner from 'src/services/channel/ChannelRequestScanner';
import { getUSBSignerDetails } from 'src/hardware/usbSigner';
+import { InvalidChannelQRCodeError } from 'src/services/channel/crypto';
import { SignerType, VaultType } from 'src/services/wallets/enums';
import WalletOperations from 'src/services/wallets/operations';
import { getKeyUID } from 'src/utils/utilities';
@@ -52,35 +53,27 @@ import { setShowTipModal } from 'src/store/reducers/settings';
function ScanAndInstruct({ onBarCodeRead, mode, receivingAddress }) {
const { colorMode } = useColorMode();
- const [channelCreated, setChannelCreated] = useState(false);
const { translations } = useContext(LocalizationContext);
const { settings } = translations;
- const callback = (data) => {
- let success = onBarCodeRead(data);
- if (success) {
- setChannelCreated(true);
- }
- };
-
- return !channelCreated ? (
-
- ) : (
-
- {mode === InteracationMode.ADDRESS_VERIFICATION ? (
-
-
-
-
- ) : (
-
-
- {settings.KeeperDesktopApp}
-
-
-
- )}
-
+ return (
+
+
+ {mode === InteracationMode.ADDRESS_VERIFICATION ? (
+
+
+
+
+ ) : (
+
+
+ {settings.KeeperDesktopApp}
+
+
+
+ )}
+
+
);
}
@@ -199,7 +192,10 @@ function ConnectChannel() {
return true;
} catch (error) {
console.log('Error in onBarCodeRead:', error);
- if (error.message && error.message.includes('TypeError: invalid key length 1')) {
+ if (
+ error instanceof InvalidChannelQRCodeError ||
+ error.message?.includes('TypeError: invalid key length 1')
+ ) {
showToast(errorText.QrScannedDesptopInvalid, );
} else {
showToast(errorText.failedToConnectDesktop, );
diff --git a/src/screens/HelpAi/HelpAiChat.tsx b/src/screens/HelpAi/HelpAiChat.tsx
index afd7bf0d2f..df90b185e5 100644
--- a/src/screens/HelpAi/HelpAiChat.tsx
+++ b/src/screens/HelpAi/HelpAiChat.tsx
@@ -11,6 +11,7 @@ import {
TextInput,
View,
} from 'react-native';
+import type { NativeScrollEvent, NativeSyntheticEvent } from 'react-native';
import DeviceInfo from 'react-native-device-info';
import Buttons from 'src/components/Buttons';
import KeeperModal from 'src/components/KeeperModal';
@@ -37,11 +38,13 @@ import { useAppDispatch, useAppSelector } from 'src/store/hooks';
import {
appendHelpAiMessage,
createHelpAiThread,
+ discardHelpAiFailedMessage,
incrementHelpAiIssueCount,
setHelpAiChatMeta,
setHelpAiDraft,
setHelpAiDraftStatus,
setHelpAiEscalationStage,
+ setHelpAiFailedMessageId,
setHelpAiRawMessages,
type HelpAiDraftStatus,
type HelpAiRenderMessage,
@@ -65,6 +68,12 @@ import Fonts from 'src/constants/Fonts';
import ChatIcon from 'src/assets/images/chat.svg';
import { sanitizeHelpAiReplyLinks, sanitizeHelpAiSources } from 'src/utils/helpAiLinkPolicy';
import { detectSensitiveInput, detectSensitiveInDraft } from 'src/utils/helpAiSensitiveData';
+import {
+ canSendChatMessage,
+ findRetryableChatMessage,
+ isNearChatBottom,
+ planChatSend,
+} from 'src/utils/helpAiChatBehavior';
// Enhanced error handler to distinguish between all backend rate limit codes
const getHelpAiFriendlyError = (error: any, scope: 'chat' | 'issue'): string => {
@@ -139,6 +148,12 @@ const HelpAiChat = ({ navigation, route }) => {
const disclaimerPoints = [askAi.disclaimerPoint1, askAi.disclaimerPoint2, askAi.disclaimerPoint3];
const { showToast } = useToastMessage();
const listRef = useRef>(null);
+ const initialScrollPending = useRef(true);
+ const readingEarlier = useRef(false);
+ const userScrolling = useRef(false);
+ const forceFollow = useRef(false);
+ const sendingRef = useRef(false);
+ const discardedFailedMessageId = useRef(null);
const generatedConversationId = useMemo(() => `conv_${Date.now().toString(36)}`, []);
const conversationId = route?.params?.conversationId || generatedConversationId;
const initialPrompt = route?.params?.prefillText || '';
@@ -153,6 +168,7 @@ const HelpAiChat = ({ navigation, route }) => {
text: greetings.current,
};
const messages = persistedThread?.messages?.length ? persistedThread.messages : [defaultIntro];
+ const failedMessage = findRetryableChatMessage(messages, persistedThread?.failedMessageId);
const rawChatMessages = persistedThread?.rawMessages || [];
const draft = persistedThread?.draft || null;
const draftStatus: HelpAiDraftStatus = persistedThread?.draftStatus || 'pending_review';
@@ -163,7 +179,6 @@ const HelpAiChat = ({ navigation, route }) => {
const [input, setInput] = useState(initialPrompt);
const [sending, setSending] = useState(false);
const [typing, setTyping] = useState(false);
- const [lastFailedText, setLastFailedText] = useState(null);
const [showDisclaimerModal, setShowDisclaimerModal] = useState(false);
useEffect(() => {
@@ -181,16 +196,28 @@ const HelpAiChat = ({ navigation, route }) => {
setShowDisclaimerModal(false);
};
- const scrollToBottom = () => {
- requestAnimationFrame(() => listRef.current?.scrollToEnd({ animated: true }));
+ const scrollToBottom = (animated: boolean) => {
+ requestAnimationFrame(() => listRef.current?.scrollToEnd({ animated }));
};
- useEffect(() => {
- if (!messages.length) return undefined;
- // Small delay to let FlatList measure new content before scrolling
- const t = setTimeout(scrollToBottom, 150);
- return () => clearTimeout(t);
- }, [messages.length]);
+ const updateReadingPosition = (event: NativeSyntheticEvent) => {
+ if (!userScrolling.current) return;
+ const { contentOffset, layoutMeasurement, contentSize } = event.nativeEvent;
+ readingEarlier.current = !isNearChatBottom(
+ contentOffset.y,
+ layoutMeasurement.height,
+ contentSize.height
+ );
+ };
+
+ const handleContentSizeChange = (_width: number, height: number) => {
+ if (height <= 0) return;
+ if (initialScrollPending.current || forceFollow.current || !readingEarlier.current) {
+ scrollToBottom(!initialScrollPending.current);
+ }
+ initialScrollPending.current = false;
+ forceFollow.current = false;
+ };
const appendMessage = (message: HelpAiRenderMessage) => {
dispatch(appendHelpAiMessage({ conversationId, message }));
@@ -214,23 +241,38 @@ const HelpAiChat = ({ navigation, route }) => {
}
};
- const sendToChat = async (text: string) => {
- if (!text.trim()) return;
+ const sendToChat = async (text: string, retryMessageId?: string) => {
+ if (sendingRef.current) return;
+ if (retryMessageId && retryMessageId === discardedFailedMessageId.current) return;
+ if (!canSendChatMessage(failedMessage?.id, retryMessageId)) {
+ showToast('Retry or discard the unsent message first.');
+ return;
+ }
+ const retryMessage = findRetryableChatMessage(messages, retryMessageId);
+ if (retryMessageId && !retryMessage) return;
+ const { outboundText, appendUserMessage } = planChatSend(text, retryMessage);
+ if (!outboundText) return;
if (!appId) {
showToast('Missing app id. Please restart the app and try again.');
return;
}
- const sensitiveResult = detectSensitiveInput(text.trim());
+ const sensitiveResult = detectSensitiveInput(outboundText);
if (sensitiveResult) {
showToast(sensitiveResult.message);
return;
}
- const outboundText = text.trim();
- setInput('');
+ const messageId = retryMessageId || nowId();
+ sendingRef.current = true;
+ forceFollow.current = true;
+ readingEarlier.current = false;
+ if (appendUserMessage) {
+ setInput('');
+ dispatch(setHelpAiFailedMessageId({ conversationId, messageId: null }));
+ appendMessage({ id: messageId, type: 'user', text: outboundText });
+ }
setSending(true);
setTyping(true);
- appendMessage({ id: nowId(), type: 'user', text: outboundText });
try {
const metadata = chatMeta || (await buildMetadata());
@@ -286,16 +328,23 @@ const HelpAiChat = ({ navigation, route }) => {
dispatch(appendHelpAiMessage({ conversationId, message: escalationRenderMsg }));
}
});
- setLastFailedText(null);
+ dispatch(setHelpAiFailedMessageId({ conversationId, messageId: null }));
} catch (error) {
showToast(getHelpAiFriendlyError(error, 'chat'));
- setLastFailedText(outboundText);
+ dispatch(setHelpAiFailedMessageId({ conversationId, messageId }));
} finally {
+ sendingRef.current = false;
setSending(false);
setTyping(false);
}
};
+ const discardFailedMessage = () => {
+ if (!failedMessage || sendingRef.current) return;
+ discardedFailedMessageId.current = failedMessage.id;
+ dispatch(discardHelpAiFailedMessage({ conversationId }));
+ };
+
const submitDraftIssue = async () => {
if (!draft || !chatMeta) return;
if (!appId) {
@@ -496,6 +545,24 @@ const HelpAiChat = ({ navigation, route }) => {
)}
contentContainerStyle={styles.messagesContainer}
keyboardShouldPersistTaps="handled"
+ onContentSizeChange={handleContentSizeChange}
+ onScrollBeginDrag={() => {
+ userScrolling.current = true;
+ forceFollow.current = false;
+ }}
+ onScroll={updateReadingPosition}
+ onScrollEndDrag={(event) => {
+ updateReadingPosition(event);
+ userScrolling.current = false;
+ }}
+ onMomentumScrollBegin={() => {
+ userScrolling.current = true;
+ }}
+ onMomentumScrollEnd={(event) => {
+ updateReadingPosition(event);
+ userScrolling.current = false;
+ }}
+ scrollEventThrottle={16}
ListFooterComponent={
<>
{typing && (
@@ -558,12 +625,12 @@ const HelpAiChat = ({ navigation, route }) => {
style={[
styles.sendBtn,
{
- opacity: sending ? 0.6 : 1,
- backgroundColor: Colors.primaryGreen,
- },
+ opacity: sending || failedMessage ? 0.6 : 1,
+ backgroundColor: Colors.primaryGreen,
+ },
]}
onPress={() => sendToChat(input)}
- disabled={sending}
+ disabled={sending || !!failedMessage}
>
{isDarkMode ? (
@@ -574,12 +641,32 @@ const HelpAiChat = ({ navigation, route }) => {
- {lastFailedText ? (
- sendToChat(lastFailedText)}>
-
- Retry last failed message
+ {failedMessage ? (
+
+
+ Message not sent. Retry or discard it before sending another.
-
+
+ sendToChat(failedMessage.text, failedMessage.id)}
+ disabled={sending}
+ >
+
+ Retry
+
+
+
+
+ Discard
+
+
+
+
) : null}
)}
- {content}
+ {/* Keep tab descendants (including elevated FABs) out of the footer's native parent. */}
+
+ {content}
+ {
diff --git a/src/screens/Home/InititalAppController.tsx b/src/screens/Home/InititalAppController.tsx
index 26d81b9ae1..9837071457 100644
--- a/src/screens/Home/InititalAppController.tsx
+++ b/src/screens/Home/InititalAppController.tsx
@@ -58,6 +58,7 @@ import ThemeMode from 'src/models/enums/ThemeMode';
import { getString, setItem } from 'src/storage';
import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView';
import { setAccountManagerDetails } from 'src/store/reducers/concierge';
+import { getRemoteKeyFromDeepLink } from 'src/navigation/remoteKeyDeepLink';
export const KEEPER_PRIVATE_LINK = 'KEEPER_PRIVATE_LINK';
function InititalAppController({ navigation, electrumErrorVisible, setElectrumErrorVisible }) {
@@ -85,8 +86,9 @@ function InititalAppController({ navigation, electrumErrorVisible, setElectrumEr
function handleDeepLinkEvent(event) {
const { url } = event;
if (url) {
- if (url.includes('remote/')) {
- handleRemoteKeyDeepLink(url);
+ const encryptionKey = getRemoteKeyFromDeepLink(url, config.ENVIRONMENT);
+ if (encryptionKey) {
+ handleRemoteKeyDeepLink(encryptionKey);
} else if (url.includes('kp/')) {
handleKeeperPrivate(url);
}
@@ -100,9 +102,8 @@ function InititalAppController({ navigation, electrumErrorVisible, setElectrumEr
const { inProgress, start } = useAsync();
- const handleRemoteKeyDeepLink = async (initialUrl: string) => {
+ const handleRemoteKeyDeepLink = async (encryptionKey: string) => {
dispatch(setAppWideLoading(true));
- const encryptionKey = initialUrl.split('remote/')[1];
const hash = getHashFromKey(encryptionKey);
if (encryptionKey && hash) {
try {
@@ -338,21 +339,17 @@ function InititalAppController({ navigation, electrumErrorVisible, setElectrumEr
async function handleDeepLinking() {
try {
const initialUrl = await Linking.getInitialURL();
- if (initialUrl) {
- if (initialUrl.includes('remote/')) {
- handleRemoteKeyDeepLink(initialUrl);
- }
- }
+ if (initialUrl) handleDeepLinkEvent({ url: initialUrl });
} catch (error) {
//
}
}
useEffect(() => {
- Linking.addEventListener('url', handleDeepLinkEvent);
- handleDeepLinking();
+ const subscription = Linking.addEventListener('url', handleDeepLinkEvent);
+ if (!hasDeepLink) handleDeepLinking();
return () => {
- Linking.removeAllListeners('url');
+ subscription.remove();
};
}, []);
diff --git a/src/screens/Home/Notifications/NotificationsCenter.tsx b/src/screens/Home/Notifications/NotificationsCenter.tsx
index 26abf067b2..16fdfe7ba9 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';
@@ -91,7 +90,9 @@ const Card = memo(({ uai }: CardProps) => {
const [insightModal, setInsightModal] = useState(false);
const { signerMap } = useSignerMap();
const snapshots = useAppSelector((state) => state.cachedTxn.snapshots);
- const { backupAllLoading } = useAppSelector((state) => state.bhr);
+ const backupAllLoading = useAppSelector(
+ (state) => !!state.bhr.backupAllLoadingByAppId?.[state.storage.appId]
+ );
const { translations } = useContext(LocalizationContext);
const { common, notification, error: errorTranslation } = translations;
@@ -298,7 +299,7 @@ const Card = memo(({ uai }: CardProps) => {
text: common.View,
cta: () => {
dispatch(uaiActioned({ uaiId: uai.id, action: false }));
- dispatch(backupAllSignersAndVaults());
+ navigtaion.dispatch(CommonActions.navigate('AssistedBackupStatus'));
},
},
},
diff --git a/src/screens/Home/components/Keys/ManageKeys.tsx b/src/screens/Home/components/Keys/ManageKeys.tsx
index 4532415f77..75d4035aca 100644
--- a/src/screens/Home/components/Keys/ManageKeys.tsx
+++ b/src/screens/Home/components/Keys/ManageKeys.tsx
@@ -1,12 +1,13 @@
import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
import React, { useCallback, useContext, useEffect, useState } from 'react';
-import { StyleSheet } from 'react-native';
+import { StyleSheet, Pressable } from 'react-native';
+import Text from 'src/components/KeeperText';
import ToastErrorIcon from 'src/assets/images/toast_error.svg';
import KeeperModal from 'src/components/KeeperModal';
import { LocalizationContext } from 'src/context/Localization/LocContext';
import SignerContent from './SignerContent';
-import { useFocusEffect, useNavigation } from '@react-navigation/native';
+import { CommonActions, useFocusEffect, useNavigation } from '@react-navigation/native';
import SignerList from './SignerList';
import KeyAddedModal from 'src/components/KeyAddedModal';
@@ -106,6 +107,14 @@ const ManageKeys = ({ addedSigner }) => {
onPress={handleModalOpen}
containerStyle={{ right: wp(22.5) }}
/>
+ navigation.dispatch(CommonActions.navigate('DeleteKeys'))}
+ style={{ paddingVertical: hp(12) }}
+ >
+ {translations.signer.manageKeys}
+
diff --git a/src/screens/Home/components/Settings/Component/SettingCard.tsx b/src/screens/Home/components/Settings/Component/SettingCard.tsx
index 089e89feab..254e7099bb 100644
--- a/src/screens/Home/components/Settings/Component/SettingCard.tsx
+++ b/src/screens/Home/components/Settings/Component/SettingCard.tsx
@@ -12,6 +12,7 @@ import Colors from 'src/theme/Colors';
interface SettingCardItemProps {
title?: string;
description?: string;
+ expandDescription?: boolean;
icon?: React.ReactNode;
rightIcon?: React.ReactNode;
isDiamond?: boolean;
@@ -100,6 +101,7 @@ const SettingCard: React.FC = ({
? titleColor ?? `${colorMode}.balanceText`
: `${colorMode}.secondaryLightGrey`
}
+ allowFontScaling={!!item.expandDescription}
fontSize={14}
medium
style={styles.title}
@@ -110,7 +112,8 @@ const SettingCard: React.FC = ({
{
const { signer: signerText, inheritancePlanning, settings, common } = translations;
const {
BackAndRecovery,
+ BackupFeedback,
General,
keysAndwallet,
Tips,
@@ -51,7 +52,9 @@ const KeeperSettings = ({ route }) => {
};
}, []); // Empty dependency array means this runs once on mount
- const { backupAllLoading } = useAppSelector((state) => state.bhr);
+ const backupAllLoading = useAppSelector(
+ (state) => !!state.bhr.backupAllLoadingByAppId?.[state.storage.appId]
+ );
const dispatch = useDispatch();
return (
@@ -68,6 +71,7 @@ const KeeperSettings = ({ route }) => {
icon={}
showDot={false}
/>
+ {BackupFeedback}
{
const { colorMode } = useColorMode();
- const isDarkMode = colorMode === 'dark';
const navigation = useNavigation();
const { wallets } = useWallets({ getAll: true });
const { translations } = useContext(LocalizationContext);
- const { wallet: walletText, home, common, usdtWalletText } = translations;
+ const { wallet: walletText, home, common } = translations;
const { getWalletCardGradient, getWalletTags } = useWalletAsset();
const { allVaults } = useVault({
includeArchived: false,
getFirst: true,
getHiddenWallets: false,
});
- const { usdtWallets, createWallet } = useUSDTWallets();
+ const { usdtWallets } = useUSDTWallets();
const { collaborativeSession } = useAppSelector((state) => state.vault);
+ const { appId } = useAppSelector((state) => state.storage);
const { bitcoinNetworkType } = useAppSelector((state) => state.settings);
const dispatch = useDispatch();
- const [showAddWalletModal, setShowAddWalletModal] = useState(false);
- const [collabSessionExistsModalVisible, setCollabSessionExistsModalVisible] = useState(false);
- const [pullRefresh, setPullRefresh] = useState(false);
+ const resetSession = useCallback(() => dispatch(resetCollaborativeSession()), [dispatch]);
+ const navigateToCollaborativeWallet = useCallback(
+ () => navigation.navigate('SetupCollaborativeWallet'),
+ [navigation]
+ );
+ const collaborativeHandoff = useCollaborativeWalletHandoff({
+ appId,
+ network: bitcoinNetworkType,
+ session: collaborativeSession,
+ resetSession,
+ navigate: navigateToCollaborativeWallet,
+ });
+ const { refreshing: pullRefresh, autoRefresh } = useWalletRefresh();
const { walletSyncing } = useAppSelector((state) => state.wallet);
- const [pickWalletType, setPickWalletType] = useState(false);
- const [createUsdtWallet, setCreateUsdtWallet] = useState(false);
const syncing =
ELECTRUM_CLIENT.isClientConnected &&
Object.values(walletSyncing).some((isSyncing) => isSyncing);
@@ -140,12 +140,6 @@ const HomeWallet = () => {
...usdtWallets,
].filter((item) => item !== null);
const [isShowAmount, setIsShowAmount] = useState(false);
- const DashedCta_hexagonBackgroundColor = ThemedColor({
- name: 'DashedCta_hexagonBackgroundColor',
- });
- const dashed_CTA_background = ThemedColor({
- name: 'dashed_CTA_background',
- });
const { showToast } = useToastMessage();
const pendingDustToast = useAppSelector((state: any) => state.utxos.pendingDustToast);
@@ -157,52 +151,8 @@ const HomeWallet = () => {
}
}, [pendingDustToast]);
- const handleCollaborativeWalletCreation = () => {
- setShowAddWalletModal(false);
- if (Object.keys(collaborativeSession.signers).length > 0) {
- setCollabSessionExistsModalVisible(true);
- } else {
- dispatch(resetCollaborativeSession());
- setTimeout(() => {
- navigation.navigate('SetupCollaborativeWallet');
- }, 500); // delaying navigation by 0.5 second to ensure collaborative session reset
- }
- };
-
const pullDownRefresh = () => {
- setPullRefresh(true);
-
- dispatch(autoSyncWallets(false, false, true));
- setPullRefresh(false);
- };
-
- const importUSDTWallet = async (mnemonic) => {
- try {
- const { newWallet, error } = await createWallet({
- type: USDTWalletType.IMPORTED,
- name: 'USDT Wallet',
- description: 'Imported USDT Wallet',
- importDetails: {
- mnemonic,
- },
- });
-
- if (newWallet) {
- showToast('USDT wallet imported successfully!', );
- setTimeout(() => {
- navigation.dispatch(
- CommonActions.navigate({
- name: 'Home',
- params: { selectedOption: 'Wallets' },
- })
- );
- }, 900);
- } else {
- throw new Error(error);
- }
- } catch (err) {
- showToast(`Failed to import USDT wallet: ${err.message}`, );
- }
+ autoRefresh();
};
const CREATE_WALLET_OPTIONS = [
@@ -211,7 +161,7 @@ const HomeWallet = () => {
subtitle: walletText.createWalletDesc,
icon: ,
onPress: () => {
- setShowAddWalletModal(false);
+ collaborativeHandoff.closeAdd();
navigation.navigate('AddNewWallet');
},
id: 'newWallet',
@@ -221,7 +171,7 @@ const HomeWallet = () => {
subtitle: walletText.restoreExistingWallet,
icon: ,
onPress: () => {
- setShowAddWalletModal(false);
+ collaborativeHandoff.closeAdd();
navigation.navigate('VaultConfigurationCreation');
},
id: 'importWallet',
@@ -230,42 +180,10 @@ const HomeWallet = () => {
title: common.collaborativeWallet,
subtitle: walletText.walletWithFamily,
icon: ,
- onPress: handleCollaborativeWalletCreation,
+ onPress: collaborativeHandoff.selectCollaborative,
id: 'collaborativeWallet',
},
];
- const CREATE_USDT_WALLET_OPTIONS = [
- {
- title: walletText.createWallet,
- subtitle: 'Create a new USDT wallet',
- icon: ,
- onPress: () => {
- navigation.navigate('addUsdtWallet');
- setCreateUsdtWallet(false);
- },
- id: 'usdtnewWallet',
- },
- {
- title: home.ImportWallet,
- subtitle: walletText.restoreExistingWallet,
- icon: ,
- onPress: () => {
- setCreateUsdtWallet(false);
- navigation.dispatch(
- CommonActions.navigate({
- name: 'EnterSeedScreen',
- params: {
- isImport: true,
- isUSDTWallet: true,
- importSeedCta: importUSDTWallet,
- },
- })
- );
- },
- id: 'usdtimportWallet',
- },
- ];
-
const renderWalletCard = ({ item }: { item: Wallet | Vault | USDTWallet }) => (
{
}
- onPress={() => setPickWalletType(true)}
+ onPress={collaborativeHandoff.openAdd}
/>
{
ItemSeparatorComponent={() => }
/>
setShowAddWalletModal(false)}
+ close={collaborativeHandoff.closeAdd}
+ onModalHide={collaborativeHandoff.waitForAddHide ? collaborativeHandoff.onAddHide : undefined}
textColor={`${colorMode}.textGreen`}
subTitleColor={`${colorMode}.modalSubtitleBlack`}
showCloseIcon
@@ -309,96 +228,17 @@ const HomeWallet = () => {
)}
/>
setCreateUsdtWallet(false)}
- textColor={`${colorMode}.textGreen`}
- subTitleColor={`${colorMode}.modalSubtitleBlack`}
- showCloseIcon
- Content={() => (
-
- {CREATE_USDT_WALLET_OPTIONS.map((option, index) => (
-
- ))}
-
- )}
- />
- setCollabSessionExistsModalVisible(false)}
+ visible={collaborativeHandoff.sessionVisible}
+ close={collaborativeHandoff.closeSession}
+ onModalHide={
+ collaborativeHandoff.waitForSessionHide ? collaborativeHandoff.onSessionHide : undefined
+ }
title={walletText.collaborativeSessionExists}
subTitle={walletText.collaborativeSessionExistsDesc}
buttonText={common.continueSession}
secondaryButtonText={common.startNew}
- secondaryCallback={() => {
- setCollabSessionExistsModalVisible(false);
- dispatch(resetCollaborativeSession());
- setTimeout(() => {
- navigation.navigate('SetupCollaborativeWallet');
- }, 500);
- }}
- buttonCallback={() => {
- setCollabSessionExistsModalVisible(false);
- navigation.navigate('SetupCollaborativeWallet');
- }}
- />
- setPickWalletType(false)}
- title={usdtWalletText.pickWalletType}
- subTitle={usdtWalletText.selectCurrency}
- textColor={`${colorMode}.textGreen`}
- subTitleColor={`${colorMode}.modalSubtitleBlack`}
- modalBackground={`${colorMode}.modalWhiteBackground`}
- Content={() => (
-
- {
- setShowAddWalletModal(true);
- setPickWalletType(false);
- }}
- >
-
- }
- backgroundColor={Colors.BrightOrange}
- />
-
- {usdtWalletText.bitcoinWallet}
-
-
-
- {bitcoinNetworkType === USDTWalletSupportedNetwork ? (
- {
- setCreateUsdtWallet(true);
- setPickWalletType(false);
- }}
- >
-
- }
- backgroundColor={Colors.DesaturatedTeal}
- />
-
- {usdtWalletText.dollarWallet}
-
-
-
- ) : null}
-
- )}
+ secondaryCallback={() => collaborativeHandoff.finishSession('new')}
+ buttonCallback={() => collaborativeHandoff.finishSession('continue')}
/>
);
@@ -457,26 +297,4 @@ const styles = StyleSheet.create({
borderRadius: 12,
borderWidth: 1,
},
- customStyle: {
- marginBottom: hp(10),
- },
- DashedCtaStyle: {
- width: windowWidth * 0.88,
- },
- walletTypeContainer: {
- gap: wp(15),
- marginBottom: hp(10),
- flexDirection: 'row',
- justifyContent: 'center',
- alignContent: 'center',
- },
- typeCard: {
- width: wp(148),
- height: hp(104),
- alignItems: 'center',
- borderWidth: 1,
- justifyContent: 'center',
- borderRadius: 12,
- gap: wp(10),
- },
});
diff --git a/src/screens/Home/components/buyBtc/BuyBtc.tsx b/src/screens/Home/components/buyBtc/BuyBtc.tsx
index ecb21234a9..060c20ef4a 100644
--- a/src/screens/Home/components/buyBtc/BuyBtc.tsx
+++ b/src/screens/Home/components/buyBtc/BuyBtc.tsx
@@ -19,11 +19,11 @@ import useToastMessage from 'src/hooks/useToastMessage';
import ToastErrorIcon from 'src/assets/images/toast_error.svg';
import AcquireCard from './AcquireCard';
import BtcAcquireIcon from 'src/assets/images/bitcoin-acquire-icon.svg';
-import UsdtWalletLogo from 'src/assets/images/usdt-wallet-logo.svg';
-import { useUSDTWallets } from 'src/hooks/useUSDTWallets';
-import { fetchSellBtcLink, fetchSellUsdtLink } from 'src/services/thirdparty/ramp';
-import Buttons from 'src/components/Buttons';
+import { fetchSellBtcLink } from 'src/services/thirdparty/ramp';
import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView';
+import { useQuery } from '@realm/react';
+import { RealmSchema } from 'src/storage/realm/enum';
+import { SwapHistory } from './Swap/SwapHistory';
const BuyBtc = () => {
const { colorMode } = useColorMode();
@@ -35,21 +35,17 @@ const BuyBtc = () => {
const { buyBTC: buyBTCText, common } = translations;
const [visibleBuyBtc, setVisibleBuyBtc] = useState(false);
const [selectedWallet, setSelectedWallet] = useState(null);
- const [selectedUsdtWallet, setSelectedUsdtWallet] = useState(null);
const navigation = useNavigation();
const [graphData, setGraphData] = useState([]);
const [error, setError] = useState(false);
const [stats, setStats] = useState(null);
const [visibleSellBtc, setVisibleSellBtc] = useState(false);
- const [visibleSellUsdt, setVisibleSellUsdt] = useState(false);
- const [visibleBuyUsdt, setVisibleBuyUsdt] = useState(false);
const { wallets } = useWallets();
const { allVaults } = useVault({ getHiddenWallets: false });
const { showToast } = useToastMessage();
const allWallets = [...wallets, ...allVaults];
- const { usdtWallets } = useUSDTWallets();
- const [usdtPrice, setUsdtPrice] = useState(null);
+ const previousSwaps = useQuery(RealmSchema.SwapHistory);
const [loading, setLoading] = useState(false);
useEffect(() => {
@@ -58,13 +54,9 @@ const BuyBtc = () => {
const loadBtcPrice = async () => {
try {
- let [usdtData, btcPrice] = await Promise.all([
- Relay.getUsdtPrice(currencyCode),
- Relay.getBtcPrice(currencyCode),
- ]);
+ const btcPrice = await Relay.getBtcPrice(currencyCode);
const { dailyPrice, high24h, latestPrice, low24h, percentChange, valueChange } =
manipulateBitcoinPrices(btcPrice?.prices);
- setUsdtPrice(usdtData[0].current_price.toFixed(2));
setGraphData(dailyPrice);
setStats({ high24h, low24h, latestPrice, percentChange, valueChange });
} catch (error) {
@@ -106,31 +98,8 @@ const BuyBtc = () => {
}}
graphContent={}
/>
- }
- amount={`${BtcPrice?.symbol} ${usdtPrice ?? '--'} `}
- buyCallback={() => {
- if (usdtWallets.length) setVisibleBuyUsdt(true);
- else showToast('Please create a USDT wallet to proceed.', );
- }}
- sellCallback={() => {
- if (usdtWallets.length > 0) {
- setVisibleSellUsdt(true);
- } else showToast("You don't have USDT yet.", );
- }}
- />
+ {previousSwaps.length > 0 && }
-
- {
- navigation.dispatch(CommonActions.navigate('Swaps'));
- }}
- fullWidth
- />
- {buyBTCText.transactionOnRamp}
@@ -164,30 +133,6 @@ const BuyBtc = () => {
);
}}
/>
- setVisibleBuyUsdt(false)}
- title={buyBTCText.selectWallet}
- subTitle={buyBTCText.selectWalletDesc}
- modalBackground={`${colorMode}.modalWhiteBackground`}
- textColor={`${colorMode}.textGreen`}
- subTitleColor={`${colorMode}.modalSubtitleBlack`}
- Content={() => (
-
- )}
- buttonText={selectedUsdtWallet ? common.proceed : null}
- buttonCallback={() => {
- if (!selectedUsdtWallet) return;
- setVisibleBuyUsdt(false);
- navigation.dispatch(
- CommonActions.navigate({ name: 'buyUstd', params: { usdtWallet: selectedUsdtWallet } })
- );
- }}
- />
setVisibleSellBtc(false)}
@@ -218,36 +163,6 @@ const BuyBtc = () => {
}
}}
/>
- setVisibleSellUsdt(false)}
- title={buyBTCText.proceedToRamp}
- modalBackground={`${colorMode}.modalWhiteBackground`}
- textColor={`${colorMode}.textGreen`}
- subTitleColor={`${colorMode}.modalSubtitleBlack`}
- Content={() => (
-
- {buyBTCText.rediredctToRampPage}
-
- )}
- buttonText={common.confirm}
- buttonCallback={async () => {
- try {
- setLoading(true);
- setVisibleSellUsdt(false);
- const url = await fetchSellUsdtLink();
- Linking.openURL(url.toString());
- } catch (error) {
- showToast('Error while fetching ramp url');
- } finally {
- setLoading(false);
- }
- }}
- />
);
@@ -296,11 +211,6 @@ const styles = StyleSheet.create({
width: wp(160),
borderRadius: 8,
},
- button_container: {
- width: windowWidth,
- marginVertical: hp(10),
- paddingHorizontal: wp(12),
- },
info_container: {
maxWidth: windowWidth,
paddingHorizontal: wp(12),
diff --git a/src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail.tsx b/src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail.tsx
index 9d4683f5d9..d658f6a45e 100644
--- a/src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail.tsx
+++ b/src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail.tsx
@@ -8,7 +8,7 @@ import useToastMessage from 'src/hooks/useToastMessage';
import ToastErrorIcon from 'src/assets/images/toast_error.svg';
import { useDispatch } from 'react-redux';
import { getTnxDetails } from 'src/store/sagaActions/swap';
-import { CoinLogo } from './Swaps';
+import { CoinLogo } from './component/CoinLogo';
import { StyleSheet } from 'react-native';
import CircleIconWrapper from 'src/components/CircleIconWrapper';
import { hp, wp } from 'src/constants/responsive';
diff --git a/src/screens/Home/components/buyBtc/Swap/Swaps.tsx b/src/screens/Home/components/buyBtc/Swap/Swaps.tsx
index 1b382f2676..9bcc6d6ffa 100644
--- a/src/screens/Home/components/buyBtc/Swap/Swaps.tsx
+++ b/src/screens/Home/components/buyBtc/Swap/Swaps.tsx
@@ -14,8 +14,6 @@ import { useAppSelector } from 'src/store/hooks';
import ToastErrorIcon from 'src/assets/images/toast_error.svg';
import Checked from 'src/assets/images/tick_icon.svg';
import { createSwapTnx, getSwapQuote, loadCoinDetails } from 'src/store/sagaActions/swap';
-import BtcAcquireIcon from 'src/assets/images/bitcoin-acquire-icon.svg';
-import UsdtWalletLogo from 'src/assets/images/usdt-wallet-logo.svg';
import Colors from 'src/theme/Colors';
import { useUSDTWallets } from 'src/hooks/useUSDTWallets';
import useVault from 'src/hooks/useVault';
@@ -23,41 +21,11 @@ import useWallets from 'src/hooks/useWallets';
import KeeperModal from 'src/components/KeeperModal';
import BuyBtcModalContent from '../BuyBtcModalContent';
import { SwapHistory } from './SwapHistory';
-import CircleIconWrapper from 'src/components/CircleIconWrapper';
import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg';
import { LocalizationContext } from 'src/context/Localization/LocContext';
import { EntityKind } from 'src/services/wallets/enums';
+import { CoinLogo } from './component/CoinLogo';
-export const CoinLogo = ({
- code,
- CircleWidth,
- logoWidth,
- logoHeight,
-}: {
- code: string;
- isLarge?: boolean;
- CircleWidth?: number;
- logoWidth?: number;
- logoHeight?: number;
-}) => {
- const isBtc = code === 'BTC';
-
- return (
-
-
- ) : (
-
- )
- }
- backgroundColor={isBtc ? Colors.BrightOrange : Colors.DesaturatedTeal}
- width={CircleWidth}
- />
-
- );
-};
export const SwitchButton = ({ onPress, coinData }) => {
const { colorMode } = useColorMode();
diff --git a/src/screens/Home/components/buyBtc/Swap/component/CoinLogo.tsx b/src/screens/Home/components/buyBtc/Swap/component/CoinLogo.tsx
new file mode 100644
index 0000000000..a5f4383630
--- /dev/null
+++ b/src/screens/Home/components/buyBtc/Swap/component/CoinLogo.tsx
@@ -0,0 +1,36 @@
+import { Box } from '@gluestack-ui/themed-native-base';
+import React from 'react';
+import BtcAcquireIcon from 'src/assets/images/bitcoin-acquire-icon.svg';
+import UsdtWalletLogo from 'src/assets/images/usdt-wallet-logo.svg';
+import CircleIconWrapper from 'src/components/CircleIconWrapper';
+import Colors from 'src/theme/Colors';
+
+export const CoinLogo = ({
+ code,
+ CircleWidth,
+ logoWidth,
+ logoHeight,
+}: {
+ code: string;
+ CircleWidth?: number;
+ logoWidth?: number;
+ logoHeight?: number;
+}) => {
+ const isBtc = code === 'BTC';
+
+ return (
+
+
+ ) : (
+
+ )
+ }
+ backgroundColor={isBtc ? Colors.BrightOrange : Colors.DesaturatedTeal}
+ width={CircleWidth}
+ />
+
+ );
+};
diff --git a/src/screens/Home/components/buyBtc/Swap/component/SwapTransactionCard.tsx b/src/screens/Home/components/buyBtc/Swap/component/SwapTransactionCard.tsx
index 0cc07b9234..ec600bec8c 100644
--- a/src/screens/Home/components/buyBtc/Swap/component/SwapTransactionCard.tsx
+++ b/src/screens/Home/components/buyBtc/Swap/component/SwapTransactionCard.tsx
@@ -15,7 +15,7 @@ import SwapConfirmingIcon from '../../../../../../assets/images/swap-confirmint.
import SwapProcessingIcon from '../../../../../../assets/images/swap-processing.svg';
import SwapSuccessIcon from '../../../../../../assets/images/swap-success.svg';
import SwapOverDueIcon from '../../../../../../assets/images/swap-overDue.svg';
-import { CoinLogo } from '../Swaps';
+import { CoinLogo } from './CoinLogo';
import SwapPriceArrow from 'src/assets/images/swap-price-arrow.svg';
import SwapPriceArrowWhite from 'src/assets/images/swap-price-arrow-white.svg';
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..b6970cef1a 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';
@@ -49,7 +49,11 @@ import BounceLoader from 'src/components/BounceLoader';
import { formatCoolDownTime, PasswordTimeout } from 'src/utils/PasswordTimeout';
import Buttons from 'src/components/Buttons';
import PinDotView from 'src/components/AppPinInput/PinDotView';
-import { setAutomaticCloudBackup, setBackupType } from 'src/store/reducers/bhr';
+import {
+ setAutomaticCloudBackup,
+ setBackupType,
+ isAutomaticCloudBackupEnabled,
+} from 'src/store/reducers/bhr';
import Relay from 'src/services/backend/Relay';
import { setAccountManagerDetails } from 'src/store/reducers/concierge';
import Fonts from 'src/constants/Fonts';
@@ -84,7 +88,9 @@ function LoginScreen({ navigation, route }) {
// useAppSelector((state) => state.settings.subscription) === SubscriptionTier.L4;
const isOnPleb = false;
const isKeeperPrivate = false;
- const { automaticCloudBackup } = useAppSelector((state) => state.bhr);
+ const automaticCloudBackup = useAppSelector((state) =>
+ isAutomaticCloudBackupEnabled(state.bhr, appId)
+ );
const login_button_backGround = ThemedColor({ name: 'login_button_backGround' });
const slider_background = ThemedColor({ name: 'slider_background' });
@@ -104,6 +110,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);
@@ -209,21 +216,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(() => {
@@ -267,8 +269,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({
@@ -283,9 +291,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));
+ }
}
};
@@ -408,9 +419,9 @@ function LoginScreen({ navigation, route }) {
dispatch(setSubscription(updatedSubscription.name));
dispatch(setOfflineStatus(true));
// disable assisted server backup for pleb
- dispatch(setAutomaticCloudBackup(false));
+ dispatch(setAutomaticCloudBackup({ appId: app.id, enabled: false }));
dispatch(setPlebDueToOffline(true));
- dispatch(setAutoUpdateEnabledBeforeDowngrade(automaticCloudBackup));
+ dispatch(setAutoUpdateEnabledBeforeDowngrade({ appId: app.id, enabled: automaticCloudBackup }));
navigation.replace('App');
}
diff --git a/src/screens/NewKeeperAppScreen/NewKeeperAppScreen.tsx b/src/screens/NewKeeperAppScreen/NewKeeperAppScreen.tsx
index 00477729a0..6b2f9b489e 100644
--- a/src/screens/NewKeeperAppScreen/NewKeeperAppScreen.tsx
+++ b/src/screens/NewKeeperAppScreen/NewKeeperAppScreen.tsx
@@ -2,7 +2,7 @@
/* eslint-disable react/no-unstable-nested-components */
import { ActivityIndicator, StyleSheet, BackHandler , TouchableOpacity} from 'react-native';
import Text from 'src/components/KeeperText';
-import React, { useContext, useEffect, useState } from 'react';
+import React, { useContext, useEffect, useRef, useState } from 'react';
import { hp, windowWidth, wp } from 'src/constants/responsive';
import { useAppDispatch, useAppSelector } from 'src/store/hooks';
import AppIcon from 'src/assets/images/new-app-icon.svg';
@@ -14,6 +14,7 @@ import ScreenWrapper from 'src/components/ScreenWrapper';
import { getApp } from '@react-native-firebase/app';
import { getMessaging, getToken } from '@react-native-firebase/messaging';
import { setupKeeperApp } from 'src/store/sagaActions/storage';
+import { setAppCreationError } from 'src/store/reducers/login';
import useToastMessage from 'src/hooks/useToastMessage';
import { Box, Pressable, useColorMode } from '@gluestack-ui/themed-native-base';
import LoadingAnimation from 'src/components/Loader';
@@ -28,6 +29,7 @@ import Colors from 'src/theme/Colors';
import { useIsFocused } from '@react-navigation/native';
import Fonts from 'src/constants/Fonts';
import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg';
+import { currentBackupAccountSession } from 'src/services/backup/transport';
export function Tile({ title, subTitle, onPress, Icon = null, loading = false }) {
const { colorMode } = useColorMode();
@@ -113,24 +115,32 @@ function NewKeeperApp({ navigation }: { navigation }) {
const { translations } = useContext(LocalizationContext);
const { login, common, error: errorText, home } = translations;
const isFocused = useIsFocused();
+ const nextNavigation = useRef | null>(null);
+ const navigationActive = useRef(true);
+ const renderedAccountSession = currentBackupAccountSession();
const isMultiAccountFlow = !!useAppSelector((state) => state.account).allAccounts.length;
useEffect(() => {
+ let active = true;
+ const accountSession = currentBackupAccountSession();
if (appCreated) {
setInitiating(false);
- updateFCM();
+ updateFCM(() => active && accountSession === currentBackupAccountSession());
}
if (appCreationError) {
setModalVisible(false);
setInitiating(false);
}
+ return () => {
+ active = false;
+ };
}, [appCreated, appCreationError]);
- async function updateFCM() {
+ async function updateFCM(isCurrent: () => boolean) {
try {
const app = getApp();
const token = await getToken(getMessaging(app));
- dispatch(updateFCMTokens([token]));
+ if (isCurrent()) dispatch(updateFCMTokens([token]));
} catch (error) {
//
}
@@ -144,12 +154,25 @@ function NewKeeperApp({ navigation }: { navigation }) {
useEffect(() => {
if (appRecreated) {
- setTimeout(() => {
- navigation.replace('App', { screen: 'Home' });
+ const accountSession = currentBackupAccountSession();
+ const timer = setTimeout(() => {
+ if (accountSession === currentBackupAccountSession()) {
+ navigation.replace('App', { screen: 'Home' });
+ }
}, 3000);
+ return () => clearTimeout(timer);
}
+ return undefined;
}, [appRecreated]);
+ useEffect(() => {
+ navigationActive.current = true;
+ return () => {
+ navigationActive.current = false;
+ if (nextNavigation.current !== null) clearTimeout(nextNavigation.current);
+ };
+ }, []);
+
useEffect(() => {
const backAction = () => true;
const backHandler = BackHandler.addEventListener('hardwareBackPress', backAction);
@@ -157,19 +180,24 @@ function NewKeeperApp({ navigation }: { navigation }) {
}, []);
useEffect(() => {
+ let active = true;
+ const accountSession = currentBackupAccountSession();
if (keeperInitiating) {
setModalVisible(true);
- createNewApp();
+ createNewApp(() => active && accountSession === currentBackupAccountSession());
}
+ return () => {
+ active = false;
+ };
}, [keeperInitiating]);
- async function createNewApp() {
+ async function createNewApp(isCurrent: () => boolean) {
try {
const app = getApp();
const fcmToken = await getToken(getMessaging(app));
- dispatch(setupKeeperApp(fcmToken));
+ if (isCurrent()) dispatch(setupKeeperApp(fcmToken));
} catch (error) {
- dispatch(setupKeeperApp());
+ if (isCurrent()) dispatch(setupKeeperApp());
}
}
@@ -318,23 +346,6 @@ function NewKeeperApp({ navigation }: { navigation }) {
- {}}
- visible={appCreationError}
- title={common.somethingWrong}
- subTitle={login.checkinternetConnection}
- modalBackground={`${colorMode}.modalWhiteBackground`}
- textColor={`${colorMode}.textGreen`}
- subTitleColor={`${colorMode}.modalSubtitleBlack`}
- Content={Box}
- buttonText={common.retry}
- buttonCallback={() => {
- setInitiating(true);
- }}
- subTitleWidth={wp(250)}
- showCloseIcon={false}
- />
{}}
@@ -347,9 +358,16 @@ function NewKeeperApp({ navigation }: { navigation }) {
subTitleColor={`${colorMode}.modalSubtitleBlack`}
buttonText={appCreated ? common.next : null}
buttonCallback={() => {
+ if (
+ !navigationActive.current ||
+ nextNavigation.current !== null ||
+ renderedAccountSession !== currentBackupAccountSession()
+ ) return;
setModalVisible(false);
- setTimeout(() => {
- navigation.replace('App', { screen: 'Home' });
+ nextNavigation.current = setTimeout(() => {
+ if (renderedAccountSession === currentBackupAccountSession()) {
+ navigation.replace('App', { screen: 'Home' });
+ }
}, 500);
}}
subTitleWidth={wp(300)}
@@ -364,6 +382,7 @@ function NewKeeperApp({ navigation }: { navigation }) {
Content={Box}
buttonText={common.retry}
buttonCallback={() => {
+ dispatch(setAppCreationError(false));
setInitiating(true);
}}
modalBackground={`${colorMode}.modalWhiteBackground`}
diff --git a/src/screens/QRScreens/RegisterWithChannel.tsx b/src/screens/QRScreens/RegisterWithChannel.tsx
index f678dadc36..0f98be7318 100644
--- a/src/screens/QRScreens/RegisterWithChannel.tsx
+++ b/src/screens/QRScreens/RegisterWithChannel.tsx
@@ -22,33 +22,29 @@ import {
import useSignerFromKey from 'src/hooks/useSignerFromKey';
import { hcStatusType } from 'src/models/interfaces/HeathCheckTypes';
import { healthCheckStatusUpdate } from 'src/store/sagaActions/bhr';
-import QRScanner from 'src/components/QRScanner';
+import ChannelRequestScanner from 'src/services/channel/ChannelRequestScanner';
+import { InvalidChannelQRCodeError } from 'src/services/channel/crypto';
import { VaultType } from 'src/services/wallets/enums';
import BackgroundTimer from 'react-native-background-timer';
import { useAppSelector } from 'src/store/hooks';
import WalletHeader from 'src/components/WalletHeader';
import { LocalizationContext } from 'src/context/Localization/LocContext';
+import useToastMessage from 'src/hooks/useToastMessage';
+import ToastErrorIcon from 'src/assets/images/toast_error.svg';
function ScanAndInstruct({ onBarCodeRead }) {
const { colorMode } = useColorMode();
- const [channelCreated, setChannelCreated] = useState(false);
const { translations } = useContext(LocalizationContext);
const { vault: vaultTranslation } = translations;
-
- const callback = (data) => {
- onBarCodeRead(data);
- setChannelCreated(true);
- };
- return !channelCreated ? (
-
- ) : (
- // TODO: Move this to a component
-
-
- {vaultTranslation.registerVaultFromDesktop}
-
-
-
+ return (
+
+
+
+ {vaultTranslation.registerVaultFromDesktop}
+
+
+
+
);
}
@@ -64,7 +60,8 @@ function RegisterWithChannel() {
};
const { signer } = useSignerFromKey(vaultKey);
const { translations } = useContext(LocalizationContext);
- const { choosePlan } = translations;
+ const { choosePlan, error: errorText } = translations;
+ const { showToast } = useToastMessage();
const [channel] = useState(io(config.CHANNEL_URL));
const decryptionKey = useRef();
@@ -84,20 +81,31 @@ function RegisterWithChannel() {
const firstExtAdd = vault.specs.addresses.external[0]; // for cross validation from desktop app.
const onBarCodeRead = (data) => {
- decryptionKey.current = data;
- const sha = crypto.createHash('sha256');
- sha.update(data);
- const room = sha.digest().toString('hex');
- const requestBody = {
- action: EMIT_MODES.REGISTER_MULTISIG,
- signerType,
- descriptorString,
- miniscriptPolicy,
- walletName,
- firstExtAdd,
- };
- const requestData = createCipherGcm(JSON.stringify(requestBody), decryptionKey.current);
- channel.emit(JOIN_CHANNEL, { room, network: bitcoinNetworkType, requestData });
+ try {
+ decryptionKey.current = data;
+ const sha = crypto.createHash('sha256');
+ sha.update(data);
+ const room = sha.digest().toString('hex');
+ const requestBody = {
+ action: EMIT_MODES.REGISTER_MULTISIG,
+ signerType,
+ descriptorString,
+ miniscriptPolicy,
+ walletName,
+ firstExtAdd,
+ };
+ const requestData = createCipherGcm(JSON.stringify(requestBody), decryptionKey.current);
+ channel.emit(JOIN_CHANNEL, { room, network: bitcoinNetworkType, requestData });
+ return true;
+ } catch (error) {
+ showToast(
+ error instanceof InvalidChannelQRCodeError
+ ? errorText.QrScannedDesptopInvalid
+ : errorText.failedToConnectDesktop,
+
+ );
+ return false;
+ }
};
useEffect(() => {
diff --git a/src/screens/QRScreens/SignWithChannel.tsx b/src/screens/QRScreens/SignWithChannel.tsx
index 9983e3da1e..675ac4173a 100644
--- a/src/screens/QRScreens/SignWithChannel.tsx
+++ b/src/screens/QRScreens/SignWithChannel.tsx
@@ -26,7 +26,8 @@ import {
import useSignerFromKey from 'src/hooks/useSignerFromKey';
import { getPsbtForHwi } from 'src/hardware';
import { hcStatusType } from 'src/models/interfaces/HeathCheckTypes';
-import QRScanner from 'src/components/QRScanner';
+import ChannelRequestScanner from 'src/services/channel/ChannelRequestScanner';
+import { InvalidChannelQRCodeError } from 'src/services/channel/crypto';
import { updateKeyDetails } from 'src/store/sagaActions/wallets';
import BackgroundTimer from 'react-native-background-timer';
import WalletHeader from 'src/components/WalletHeader';
@@ -37,23 +38,17 @@ import { validatePSBT } from 'src/utils/utilities';
function ScanAndInstruct({ onBarCodeRead }) {
const { colorMode } = useColorMode();
- const [channelCreated, setChannelCreated] = useState(false);
const { translations } = useContext(LocalizationContext);
const { choosePlan } = translations;
-
- const callback = (data) => {
- onBarCodeRead(data);
- setChannelCreated(true);
- };
- return !channelCreated ? (
-
- ) : (
-
-
- {choosePlan.continuesigntransWithDesktop}
-
-
-
+ return (
+
+
+
+ {choosePlan.continuesigntransWithDesktop}
+
+
+
+
);
}
@@ -107,21 +102,32 @@ function SignWithChannel() {
}
const onBarCodeRead = async (data) => {
- decryptionKey.current = data;
- const sha = crypto.createHash('sha256');
- sha.update(data);
- const room = sha.digest().toString('hex');
- const psbt = await getPsbtForHwi(serializedPSBT, activeVault);
- const requestBody = {
- action: EMIT_MODES.SIGN_TX,
- signerType,
- psbt,
- miniscriptPolicy,
- walletName,
- hmac,
- };
- const requestData = createCipherGcm(JSON.stringify(requestBody), decryptionKey.current);
- channel.emit(JOIN_CHANNEL, { room, network: bitcoinNetworkType, requestData });
+ try {
+ decryptionKey.current = data;
+ const sha = crypto.createHash('sha256');
+ sha.update(data);
+ const room = sha.digest().toString('hex');
+ const psbt = await getPsbtForHwi(serializedPSBT, activeVault);
+ const requestBody = {
+ action: EMIT_MODES.SIGN_TX,
+ signerType,
+ psbt,
+ miniscriptPolicy,
+ walletName,
+ hmac,
+ };
+ const requestData = createCipherGcm(JSON.stringify(requestBody), decryptionKey.current);
+ channel.emit(JOIN_CHANNEL, { room, network: bitcoinNetworkType, requestData });
+ return true;
+ } catch (error) {
+ showToast(
+ error instanceof InvalidChannelQRCodeError
+ ? errorText.QrScannedDesptopInvalid
+ : errorText.failedToConnectDesktop,
+
+ );
+ return false;
+ }
};
useEffect(() => {
diff --git a/src/screens/Recieve/ReceiveScreen.tsx b/src/screens/Recieve/ReceiveScreen.tsx
index 6befa1e08d..ab38812359 100644
--- a/src/screens/Recieve/ReceiveScreen.tsx
+++ b/src/screens/Recieve/ReceiveScreen.tsx
@@ -3,7 +3,7 @@ import Text from 'src/components/KeeperText';
import { Box, useColorMode, Pressable, HStack } from '@gluestack-ui/themed-native-base';
import { ScrollView, StyleSheet, Vibration, TouchableOpacity, TextInput } from 'react-native';
-import React, { useContext, useEffect, useState } from 'react';
+import React, { useContext, useEffect, useRef, useState } from 'react';
import Buttons from 'src/components/Buttons';
import ScreenWrapper from 'src/components/ScreenWrapper';
@@ -96,6 +96,8 @@ function ReceiveScreen({ route }: { route }) {
const [addressUsed, setAddressUsed] = useState(false);
const dispatch = useAppDispatch();
+ const selectedAppId = useAppSelector((state) => state.storage.appId);
+ const originAppId = useRef(selectedAppId).current;
const { showToast } = useToastMessage();
@@ -111,7 +113,7 @@ function ReceiveScreen({ route }: { route }) {
const [localCurrencyKind, setLocalCurrencyKind] = useState(currentCurrency);
const generateNewReceiveAddress = () => {
- dispatch(generateNewAddress(wallet));
+ dispatch(generateNewAddress(wallet, originAppId));
Vibration.vibrate(50);
const newTotalAddressesCount = totalAddressesCount + 1;
setTotalAddressesCount(newTotalAddressesCount);
diff --git a/src/screens/Recovery/EnterSeedScreen.tsx b/src/screens/Recovery/EnterSeedScreen.tsx
index ecace068df..3e8bbeb55e 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';
@@ -27,7 +34,13 @@ import Dropdown from 'src/components/Dropdown';
import { SIGNTRANSACTION } from 'src/navigation/contants';
import { hcStatusType } from 'src/models/interfaces/HeathCheckTypes';
import RecoverySuccessModalContent from './RecoverySuccessModalContent';
-import { resetSeedWords, setAppImageError, setSeedWord } from 'src/store/reducers/bhr';
+import {
+ resetRecoveryDiscovery,
+ resetSeedWords,
+ setAppImageError,
+ setSeedWord,
+} from 'src/store/reducers/bhr';
+import type { BackupRecoverySource } from 'src/services/backup/restore';
import Fonts from 'src/constants/Fonts';
import { SEED_WORDS_12, SEED_WORDS_18, SEED_WORDS_24, seedWordItem } from './constants';
import Colors from 'src/theme/Colors';
@@ -66,9 +79,8 @@ function EnterSeedScreen({ route, navigation }) {
selectedNumberOfWordsFromParams,
isForgot = false,
} = route.params || {};
- const { appImageError } = useAppSelector((state) => state.bhr);
-
- const { appCreated } = useAppSelector((state) => state.storage);
+ const { appImageError, recoveryDiscovery } = useAppSelector((state) => state.bhr);
+ const activeAppId = useAppSelector((state) => state.storage.appId);
const { colorMode } = useColorMode();
const { showToast } = useToastMessage();
const dispatch = useDispatch();
@@ -77,6 +89,10 @@ function EnterSeedScreen({ route, navigation }) {
const [seedData, setSeedData] = useState();
const [invalidSeedsModal, setInvalidSeedsModal] = useState(false);
const [recoverySuccessModal, setRecoverySuccessModal] = useState(false);
+ const [recoverySuccessSource, setRecoverySuccessSource] =
+ useState('protected');
+ const [showRecoveryDiscovery, setShowRecoveryDiscovery] = useState(false);
+ const pendingRecoverySource = useRef('protected');
const [recoveryLoading, setRecoveryLoading] = useState(false);
const [hcLoading, setHcLoading] = useState(false);
const [suggestedWords, setSuggestedWords] = useState([]);
@@ -100,6 +116,7 @@ function EnterSeedScreen({ route, navigation }) {
const isHealthCheck = mode === InteracationMode.HEALTH_CHECK;
const isSignTransaction = parentScreen === SIGNTRANSACTION;
const isIdentification = mode === InteracationMode.IDENTIFICATION;
+ const isRecovery = !isHealthCheck && !isImport && !isSignTransaction && !isIdentification;
const green_modal_text_color = ThemedColor({ name: 'green_modal_text_color' });
const green_modal_background = ThemedColor({ name: 'green_modal_background' });
@@ -116,23 +133,57 @@ function EnterSeedScreen({ route, navigation }) {
};
useEffect(() => {
- if (appCreated && recoveryLoading) {
+ if (!isRecovery) return undefined;
+ dispatch(resetRecoveryDiscovery());
+ return () => {
+ dispatch(resetRecoveryDiscovery());
+ };
+ }, [dispatch, isRecovery]);
+
+ useEffect(() => {
+ if (!isRecovery || !recoveryLoading) return;
+ if (recoveryDiscovery.status === 'restored') {
+ const { provenance } = recoveryDiscovery;
setRecoveryLoading(false);
+ if (
+ !provenance ||
+ provenance.source !== pendingRecoverySource.current ||
+ provenance.keeperAppId !== activeAppId
+ ) {
+ showToast(seed.recoveryIncomplete, );
+ return;
+ }
+ setRecoverySuccessSource(provenance.source);
setRecoverySuccessModal(true);
dispatch(resetSeedWords());
dispatch(resetPasscodeTimeout());
+ } else if (
+ ['protected-absent', 'protected-empty', 'protected-deleted', 'read-error'].includes(
+ recoveryDiscovery.status
+ )
+ ) {
+ setRecoveryLoading(false);
+ if (recoveryDiscovery.error !== 'Invalid mnemonic') setShowRecoveryDiscovery(true);
}
- }, [appCreated]);
+ }, [recoveryDiscovery, recoveryLoading, isRecovery, activeAppId]);
useEffect(() => {
- if (appImageError) {
- if (appImageError === 'Network Error') {
+ if (appImageError && isRecovery) {
+ if (recoveryDiscovery.status === 'read-error' && appImageError !== 'Invalid mnemonic') {
+ dispatch(setAppImageError(''));
+ } else if (appImageError === 'Network Error') {
dispatch(setAppImageError(''));
setRecoveryLoading(false);
setShowNetworkModal(true);
- } else openInvalidSeedsModal();
+ } else if (appImageError === 'Invalid mnemonic') {
+ openInvalidSeedsModal();
+ } else {
+ setRecoveryLoading(false);
+ showToast(seed.recoveryIncomplete, );
+ dispatch(setAppImageError(''));
+ }
}
- }, [appImageError]);
+ }, [appImageError, isRecovery, recoveryDiscovery.status]);
const generateSeedWordsArray = useCallback(() => {
const seedArray = [];
@@ -315,10 +366,12 @@ function EnterSeedScreen({ route, navigation }) {
};
const handleGetAppImage = async () => {
+ dispatch(resetRecoveryDiscovery());
+ pendingRecoverySource.current = 'protected';
setRecoveryLoading(true);
try {
const seedWord = seedWords.map((word) => word.name).join(' ');
- dispatch(getAppImage(seedWord, isForgot));
+ dispatch(getAppImage(seedWord, isForgot, { source: 'protected' }));
} catch (err) {
console.error('getAppImage error:', err);
showToast(seed.SeedErrorToast, );
@@ -588,7 +641,6 @@ function EnterSeedScreen({ route, navigation }) {
);
};
- const isRecovery = !isHealthCheck && !isImport && !isSignTransaction && !isIdentification;
const rememberModalContent = () => {
return (
@@ -627,6 +679,47 @@ function EnterSeedScreen({ route, navigation }) {
);
}
+ const olderCopyAvailable = ['protected-absent', 'protected-empty', 'protected-deleted'].includes(
+ recoveryDiscovery.status
+ );
+ const recoveryDiscoveryTitle =
+ recoveryDiscovery.status === 'protected-deleted'
+ ? seed.protectedRecoveryDeletedTitle
+ : recoveryDiscovery.status === 'protected-empty'
+ ? seed.protectedRecoveryEmptyTitle
+ : recoveryDiscovery.status === 'protected-absent'
+ ? seed.protectedRecoveryAbsentTitle
+ : recoveryDiscovery.source === 'legacy-older'
+ ? seed.olderRecoveryErrorTitle
+ : seed.protectedRecoveryErrorTitle;
+ const recoveryDiscoveryBody =
+ recoveryDiscovery.status === 'protected-deleted'
+ ? seed.protectedRecoveryDeletedBody
+ : recoveryDiscovery.status === 'protected-empty'
+ ? seed.protectedRecoveryEmptyBody
+ : recoveryDiscovery.status === 'protected-absent'
+ ? seed.protectedRecoveryAbsentBody
+ : recoveryDiscovery.source === 'legacy-older'
+ ? seed.olderRecoveryErrorBody
+ : seed.protectedRecoveryErrorBody;
+ const closeRecoveryDiscovery = () => {
+ setShowRecoveryDiscovery(false);
+ dispatch(resetRecoveryDiscovery());
+ };
+ const recoverOlderCopy = () => {
+ setShowRecoveryDiscovery(false);
+ dispatch(resetRecoveryDiscovery());
+ pendingRecoverySource.current = 'legacy-older';
+ setRecoveryLoading(true);
+ const mnemonic = seedWords.map((word) => word.name).join(' ');
+ dispatch(
+ getAppImage(mnemonic, isForgot, {
+ source: 'legacy-older',
+ olderCopyConfirmed: true,
+ })
+ );
+ };
+
return (
+ setShowNetworkModal(false)}
visible={showNetworkModal}
- title="Something went wrong"
- subTitle="Please check your internet connection and try again."
+ title={seed.protectedRecoveryErrorTitle}
+ subTitle={seed.protectedRecoveryErrorBody}
modalBackground={`${colorMode}.modalWhiteBackground`}
textColor={`${colorMode}.textGreen`}
subTitleColor={`${colorMode}.modalSubtitleBlack`}
subTitleWidth={wp(230)}
showCloseIcon={false}
- buttonText={'Try again'}
+ buttonText={common.ok}
buttonCallback={() => setShowNetworkModal(false)}
/>
('');
- const {
- backupMethod,
- automaticCloudBackup,
- backupAllLoading,
- backupAllFailure,
- backupAllSuccess,
- } = useAppSelector((state) => state.bhr);
+ const { backupMethod } = useAppSelector((state) => state.bhr);
const isChangePassword = parentScreen === PRIVACYANDDISPLAY;
const seedTextColor = ThemedColor({ name: 'seedTextColor' });
const { id: appId } = dbManager.getObjectByIndex(RealmSchema.KeeperApp);
- const [asbEnabled, setAsbEnabled] = useState(false);
useEffect(() => {
if (backupMethod !== null && next && !isHealthCheck && !isInheritancePlaning) {
- if (asbEnabled) dispatch(backupAllSignersAndVaults());
- else setBackupSuccessModal(true);
- }
- }, [backupMethod]);
-
- useEffect(() => {
- if (backupAllSuccess || backupAllFailure) {
- if (!automaticCloudBackup) setAsbEnabled(true);
- dispatch(setBackupAllSuccess(false));
- dispatch(setBackupAllFailure(false));
- dispatch(setAutomaticCloudBackup(true));
setBackupSuccessModal(true);
}
- }, [backupAllSuccess, backupAllFailure]);
+ }, [backupMethod]);
const getNoteSubtitle = () => {
@@ -324,7 +299,6 @@ function ExportSeedScreen({ route, navigation }) {
})
);
} else {
- if (!automaticCloudBackup) setAsbEnabled(true);
dispatch(seedBackedUp());
dispatch(setRecoveryKeyBackedUp({ appId, status: true }));
}
@@ -357,7 +331,6 @@ function ExportSeedScreen({ route, navigation }) {
{BackupWallet.backupSuccessParagraph}
- {asbEnabled && {BackupWallet.assistedServerBackupEnabled}}
)}
@@ -383,7 +356,6 @@ function ExportSeedScreen({ route, navigation }) {
)}
/>
-
);
}
diff --git a/src/screens/Send/SendConfirmation.tsx b/src/screens/Send/SendConfirmation.tsx
index c142e84d6d..6b3150e644 100644
--- a/src/screens/Send/SendConfirmation.tsx
+++ b/src/screens/Send/SendConfirmation.tsx
@@ -2,7 +2,7 @@ import { StyleSheet, TouchableOpacity, ScrollView } from 'react-native';
import Text from 'src/components/KeeperText';
import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
import { CommonActions, useIsFocused, useNavigation } from '@react-navigation/native';
-import React, { useCallback, useContext, useEffect, useState } from 'react';
+import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { sendPhaseTwo } from 'src/store/sagaActions/send_and_receive';
import { hp, wp } from 'src/constants/responsive';
import Share from 'react-native-share';
@@ -67,6 +67,7 @@ import WalletIcon from 'src/assets/images/daily_wallet.svg';
import MultiSendSvg from 'src/assets/images/@.svg';
import useExchangeRates from 'src/hooks/useExchangeRates';
import Relay from 'src/services/backend/Relay';
+import { captureBackupWriteIntent, currentBackupAccountSession } from 'src/services/backup/transport';
export interface SendConfirmationRouteParams {
sender: Wallet | Vault;
@@ -100,6 +101,8 @@ function SendConfirmation({ route }) {
const { colorMode } = useColorMode();
const { showToast } = useToastMessage();
const dispatch = useDispatch();
+ const activeAppId = useAppSelector((state) => state.storage.appId);
+ const originAppId = useRef(activeAppId).current;
const isFocused = useIsFocused();
const {
sender,
@@ -312,12 +315,16 @@ function SendConfirmation({ route }) {
}
}
+ const originBackupAccountSession = currentBackupAccountSession();
+ const originBackupWriteIntent = originAppId
+ ? captureBackupWriteIntent(originAppId)
+ : undefined;
WalletUtilities.fetchCurrentBlockHeight()
.then(({ currentBlockHeight }) => {
setTimeout(() => {
dispatch(sendPhaseTwoReset());
- dispatch(
- sendPhaseTwo({
+ dispatch({
+ ...sendPhaseTwo({
wallet: sender,
currentBlockHeight,
txnPriority: transactionPriority,
@@ -328,8 +335,10 @@ function SendConfirmation({ route }) {
),
},
note,
- })
- );
+ }, originAppId),
+ originBackupAccountSession,
+ originBackupWriteIntent,
+ });
}, 200);
})
.catch(() => showToast(errorText.failedToFetchCurrentBlock, ));
@@ -1058,4 +1067,4 @@ function updateSatsAmountInMsg(message: string, newAmount) {
console.log('🚀 ~ updateSatsAmountInMsg ~ error:', error);
return message;
}
-}
\ No newline at end of file
+}
diff --git a/src/screens/SignTransaction/SignTransactionScreen.tsx b/src/screens/SignTransaction/SignTransactionScreen.tsx
index eae120b884..10e80c129f 100644
--- a/src/screens/SignTransaction/SignTransactionScreen.tsx
+++ b/src/screens/SignTransaction/SignTransactionScreen.tsx
@@ -172,6 +172,8 @@ function SignTransactionScreen() {
const card = useRef(new CKTapCard()).current;
const satochipCard = useRef(new SatochipCard()).current;
const dispatch = useDispatch();
+ const activeAppId = useAppSelector((state) => state.storage.appId);
+ const originAppId = useRef(activeAppId).current;
const cachedTxn = useAppSelector((state) => state.cachedTxn);
const cachedTxid = useAppSelector((state) => state.sendAndReceive.sendPhaseTwo.cachedTxid);
@@ -808,7 +810,7 @@ function SignTransactionScreen() {
txnPriority: tnxDetails.transactionPriority,
note,
miniscriptTxElements,
- })
+ }, originAppId)
);
} else {
showToast(errorText.notEnoughtSignature);
diff --git a/src/screens/SigningDevices/DeleteKeys.tsx b/src/screens/SigningDevices/DeleteKeys.tsx
index aad8b4b531..77a1bb859e 100644
--- a/src/screens/SigningDevices/DeleteKeys.tsx
+++ b/src/screens/SigningDevices/DeleteKeys.tsx
@@ -1,4 +1,4 @@
-import React, { useContext, useEffect, useState } from 'react';
+import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { Box, Pressable, useColorMode } from '@gluestack-ui/themed-native-base';
import { hp, windowWidth, wp } from 'src/constants/responsive';
import ScreenWrapper from 'src/components/ScreenWrapper';
@@ -6,7 +6,6 @@ import PasscodeVerifyModal from 'src/components/Modal/PasscodeVerify';
import KeeperModal from 'src/components/KeeperModal';
import useSigners from 'src/hooks/useSigners';
import { StyleSheet, ScrollView } from 'react-native';
-import { SDIcons } from '../Vault/SigningDeviceIcons';
import Text from 'src/components/KeeperText';
import { getSignerDescription, getSignerNameFromType } from 'src/hardware';
import DeleteIcon from 'src/assets/images/delete_bin.svg';
@@ -14,14 +13,15 @@ import ShowIcon from 'src/assets/images/show.svg';
import { useDispatch } from 'react-redux';
import { updateSignerDetails } from 'src/store/sagaActions/wallets';
import { Signer, Vault } from 'src/services/wallets/interfaces/vault';
-import useVault from 'src/hooks/useVault';
-import { CommonActions, useNavigation } from '@react-navigation/native';
+import { useQuery } from '@realm/react';
+import { RealmSchema } from 'src/storage/realm/enum';
+import { getJSONFromRealmObject } from 'src/storage/realm/utils';
+import { CommonActions, useFocusEffect, useNavigation } from '@react-navigation/native';
import ActionCard from 'src/components/ActionCard';
import WalletVault from 'src/assets/images/wallet_vault.svg';
import { archiveSigningDevice, deleteSigningDevice } from 'src/store/sagaActions/vaults';
-import useArchivedVault from 'src/hooks/useArchivedVaults';
import { LocalizationContext } from 'src/context/Localization/LocContext';
-import { SignerType } from 'src/services/wallets/enums';
+import { SignerType, VaultType, VisibilityType } from 'src/services/wallets/enums';
import { RECOVERY_KEY_SIGNER_NAME } from 'src/constants/defaultData';
import KeyCard from 'src/components/SigningDevices/KeyCard';
import HexagonIcon from 'src/components/HexagonIcon';
@@ -39,6 +39,25 @@ import HideWalletIcon from 'src/assets/images/hide_wallet.svg';
import useToastMessage from 'src/hooks/useToastMessage';
import TickIcon from 'src/assets/images/icon_tick.svg';
import usePlan from 'src/hooks/usePlan';
+import { store } from 'src/store/store';
+import dbManager from 'src/storage/realm/dbManager';
+import { currentBackupAccountSession } from 'src/services/backup/transport';
+import { SDIcons } from '../Vault/SigningDeviceIcons';
+
+type DeletionOrigin = { appId: string; accountSession: number };
+type DeletionIntent = DeletionOrigin & { signer: Signer };
+
+const isCurrentDeletionOrigin = (origin: DeletionOrigin) => {
+ if (
+ !origin.appId || store.getState().storage.appId !== origin.appId ||
+ currentBackupAccountSession() !== origin.accountSession
+ ) return false;
+ try {
+ return (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as { id?: string } | undefined)?.id === origin.appId;
+ } catch {
+ return false;
+ }
+};
function DeleteKeys({ route }) {
const { colorMode } = useColorMode();
@@ -59,14 +78,28 @@ function DeleteKeys({ route }) {
);
const dispatch = useDispatch();
+ const renderedAppId = useAppSelector((state) => state.storage.appId);
+ const renderedSession = currentBackupAccountSession();
const navigation = useNavigation();
const [unhidingKeyUID, setUnhidingKeyUID] = useState('');
- const [multipleHidden, setMultipleHidden] = useState(false);
- const { allVaults } = useVault({ includeArchived: true });
- const { archivedVaults } = useArchivedVault();
+ // Deletion safety must include hidden/canary wallets and both networks.
+ // Presentation hooks intentionally filter those records out.
+ const vaultRecords = useQuery(RealmSchema.Vault);
+ // Realm types toJSON as DefaultObject; this query contains Vault records.
+ const readVaults = (): Vault[] =>
+ vaultRecords.map((record) => getJSONFromRealmObject(record) as unknown as Vault);
const [warningEnabled, setHideWarning] = useState(false);
- const [vaultsUsed, setVaultsUsed] = useState();
- const [signerToDelete, setSignerToDelete] = useState();
+ const [warningKeyUID, setWarningKeyUID] = useState(null);
+ // Store only the key identity: names, visibility and all current references
+ // must be read again when the warning rerenders, including newly added ones.
+ const vaultsUsed = warningKeyUID === null
+ ? []
+ : readVaults().filter(
+ (vault) => !vault.archived && vault.signers.some((s) => getKeyUID(s) === warningKeyUID)
+ );
+ const [deletionIntent, setDeletionIntent] = useState(null);
+ const pendingDeletion = useRef(null);
+ const signerToDelete = deletionIntent?.signer;
const [deletedSigner, setDeletedSigner] = useState();
const deletingKeyModalVisible = useAppSelector((state) => state.bhr.deletingKeyModalVisible);
const keyDeletedSuccessModalVisible = useAppSelector(
@@ -81,20 +114,65 @@ function DeleteKeys({ route }) {
const [showAllForced, setShowAllForced] = useState(false);
const [passwordMode, setPasswordMode] = useState(PasswordMode.DEFAULT);
+ useFocusEffect(
+ useCallback(
+ () => () => {
+ pendingDeletion.current = null;
+ setDeletionIntent(null);
+ setConfirmPassVisible(false);
+ setWarningKeyUID(null);
+ setHideWarning(false);
+ },
+ []
+ )
+ );
+
const displaySigners = showAll ? [...allUnhideSigners, ...hiddenSigners] : allUnhideSigners;
+ // References remain blocking even when their names must stay concealed.
+ const showReferenceDetails = vaultsUsed.length > 0 && vaultsUsed.every(
+ (vault) =>
+ typeof vault.id === 'string' && vault.id.trim().length > 0 &&
+ vault.type !== VaultType.CANARY &&
+ vault.presentationData?.visibility === VisibilityType.DEFAULT
+ );
+ const showMultipleReferences = vaultsUsed.length > 1 && showReferenceDetails;
- const onSuccess = () => {
- if (signerToDelete) {
- const involvedArchivedVaults = archivedVaults.filter((vault) =>
- vault.signers.find((s) => getKeyUID(s) === getKeyUID(signerToDelete))
- );
- if (involvedArchivedVaults.length) {
- dispatch(archiveSigningDevice([signerToDelete]));
+ const cancelDeletion = (intent: DeletionIntent | null) => {
+ if (pendingDeletion.current !== intent) return;
+ pendingDeletion.current = null;
+ setDeletionIntent(null);
+ setConfirmPassVisible(false);
+ };
+
+ const onSuccess = (intent: DeletionIntent | null) => {
+ if (intent && pendingDeletion.current === intent) {
+ // Consume synchronously: replayed/cancelled callbacks cannot reuse this
+ // authorization or clear a later selection before React rerenders.
+ cancelDeletion(intent);
+ // Dispatch-time origin stamping must not rebind an old confirmation.
+ if (!isCurrentDeletionOrigin(intent)) return;
+ const { signer } = intent;
+ // Read live Results at invocation; a retained callback must not use a
+ // render-time snapshot from before a new active or archived reference.
+ const references = getReferences(signer);
+ const vaultsInvolved = references.filter((vault) => !vault.archived);
+ if (vaultsInvolved.length) {
+ setWarningKeyUID(getKeyUID(signer));
+ setHideWarning(true);
+ return;
+ }
+ if (references.some((vault) => vault.archived)) {
+ dispatch({
+ ...archiveSigningDevice([signer]), originAppId: intent.appId,
+ originBackupAccountSession: intent.accountSession,
+ });
} else {
- dispatch(deleteSigningDevice([signerToDelete]));
+ dispatch({
+ ...deleteSigningDevice([signer]), originAppId: intent.appId,
+ originBackupAccountSession: intent.accountSession,
+ });
}
- setDeletedSigner(signerToDelete);
- setSignerToDelete(null);
+ setDeletedSigner(signer);
}
};
const onForceProceed = () => {
@@ -125,20 +203,28 @@ function DeleteKeys({ route }) {
}
};
+ const getReferences = (signer: Signer): Vault[] =>
+ readVaults()
+ .filter((vault) => vault.signers.some((s) => getKeyUID(s) === getKeyUID(signer)));
+
const handleDelete = (signer: Signer) => {
- setMultipleHidden(false);
- const vaultsInvolved = allVaults.filter(
- (vault) => !vault.archived && vault.signers.find((s) => getKeyUID(s) === getKeyUID(signer))
- );
+ const origin = { appId: renderedAppId, accountSession: renderedSession };
+ if (!isCurrentDeletionOrigin(origin)) return;
+ pendingDeletion.current = null;
+ setDeletionIntent(null);
+ setHideWarning(false);
+ setWarningKeyUID(null);
+ const vaultsInvolved = getReferences(signer).filter((vault) => !vault.archived);
if (vaultsInvolved.length > 0) {
- if (vaultsInvolved.length > 1) setMultipleHidden(true);
setHideWarning(true);
- setVaultsUsed(vaultsInvolved);
+ setWarningKeyUID(getKeyUID(signer));
setConfirmPassVisible(false);
return;
}
+ const intent = { ...origin, signer };
+ pendingDeletion.current = intent;
+ setDeletionIntent(intent);
setConfirmPassVisible(true);
- setSignerToDelete(signer);
};
useEffect(() => {
@@ -193,7 +279,7 @@ function DeleteKeys({ route }) {
showsHorizontalScrollIndicator={false}
>
{vaultsUsed.map((vault) => (
-
+
- {multipleHidden
+ {showMultipleReferences
? signerText.deleteMultipleVaultInstruction
: signerText.deleteVaultInstruction}
@@ -217,7 +303,7 @@ function DeleteKeys({ route }) {
return (
-
+
{allUnhideSigners.length === 0 && !showAll ? (
@@ -240,13 +326,11 @@ function DeleteKeys({ route }) {
handleDelete(signer) : null
- }
+ primaryAction={showDelete ? () => handleDelete(signer) : null}
secondaryAction={() =>
signer.hidden === true ? unhide(signer) : hideSigner(signer)
}
- primaryText={signer.hidden === true && showDelete ? signerText.delete : null}
+ primaryText={showDelete ? signerText.delete : null}
secondaryText={signer.hidden === true ? signerText.unhide : 'Hide'}
primaryIcon={showDelete ? : null}
secondaryIcon={signer.hidden === true ? : }
@@ -287,13 +371,17 @@ function DeleteKeys({ route }) {
setHideWarning(false)}
title={
- multipleHidden ? signerText.deleteMultipleVaultWarning : signerText.deleteVaultWarning
+ showMultipleReferences ? signerText.deleteMultipleVaultWarning : signerText.deleteVaultWarning
}
subTitle={
- multipleHidden ? signerText.multipleVaultWarningSubtitle : signerText.vaultWarningSubtitle
+ !showReferenceDetails
+ ? signerText.deleteVaultInstruction
+ : showMultipleReferences
+ ? signerText.multipleVaultWarningSubtitle
+ : signerText.vaultWarningSubtitle
}
buttonText={signerText.viewVault}
secondaryButtonText={signerText.back}
@@ -307,7 +395,9 @@ function DeleteKeys({ route }) {
navigation.dispatch(CommonActions.navigate('ManageWallets'));
}}
textColor={`${colorMode}.textGreen`}
- Content={() => }
+ Content={() =>
+ showReferenceDetails ? : null
+ }
/>
setConfirmPassVisible(false)}
+ close={() => cancelDeletion(deletionIntent)}
title={signerText.enterPasscode}
subTitleWidth={wp(240)}
subTitle={signerText.confirmPasscodeToDeleteKey}
@@ -371,8 +461,8 @@ function DeleteKeys({ route }) {
)}
setConfirmPassVisible(false)}
- onSuccess={onSuccess}
+ close={() => cancelDeletion(deletionIntent)}
+ onSuccess={() => onSuccess(deletionIntent)}
/>
)}
diff --git a/src/screens/SigningDevices/RemoteSharing.tsx b/src/screens/SigningDevices/RemoteSharing.tsx
index f029090868..1e1064ff6e 100644
--- a/src/screens/SigningDevices/RemoteSharing.tsx
+++ b/src/screens/SigningDevices/RemoteSharing.tsx
@@ -117,7 +117,7 @@ function RemoteSharing({ route }: ScreenProps) {
if (res?.id) {
const result = await Share.share({
title: RemoteShareText[mode].msgTitle,
- message: `${RemoteShareText[mode].msgDesc}\nhttps://bitcoinkeeper.app/${
+ message: `${RemoteShareText[mode].msgDesc}\nhttps://www.bitcoinkeeper.app/${
DeepLinkIdentifier[config.ENVIRONMENT]
}/remote/${encryptionKey}`,
});
diff --git a/src/screens/Splash/SplashScreen.tsx b/src/screens/Splash/SplashScreen.tsx
index bc418b3e94..eb64ef6bda 100644
--- a/src/screens/Splash/SplashScreen.tsx
+++ b/src/screens/Splash/SplashScreen.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect } from 'react';
+import React, { useContext, useEffect, useRef, useState } from 'react';
import { StyleSheet } from 'react-native';
import { useColorMode } from '@gluestack-ui/themed-native-base';
import RestClient from 'src/services/rest/RestClient';
@@ -6,7 +6,7 @@ import { useAppSelector } from 'src/store/hooks';
import * as SecureStore from 'src/storage/secure-store';
import Animated, {
interpolate,
- runOnJS,
+ cancelAnimation,
useAnimatedStyle,
useSharedValue,
withSpring,
@@ -19,19 +19,20 @@ import { NetworkType } from 'src/services/wallets/enums';
import { changeBitcoinNetwork } from 'src/store/sagaActions/settings';
import { setDefaultWalletCreated } from 'src/store/reducers/storage';
import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg';
+import KeeperModal from 'src/components/KeeperModal';
+import { LocalizationContext } from 'src/context/Localization/LocContext';
function SplashScreen({ navigation }) {
const { torEnbled, themeMode, bitcoinNetworkType } = useAppSelector((state) => state.settings);
const dispatch = useDispatch();
const { toggleColorMode, colorMode } = useColorMode();
- const animate = () => {
- progress.value = withTiming(4, { duration: 3000 }, (finished) => {
- if (finished) {
- runOnJS(navigateToApp)();
- }
- });
- };
+ const { translations } = useContext(LocalizationContext);
+ const [startupError, setStartupError] = useState(false);
+ const [attempt, setAttempt] = useState(0);
+ const readPending = useRef(true);
+ const mounted = useRef(false);
+ const progress = useSharedValue(0);
useEffect(() => {
if (!bitcoinNetworkType) {
@@ -48,27 +49,52 @@ function SplashScreen({ navigation }) {
}, []);
useEffect(() => {
- animate();
+ mounted.current = true;
+ // The animation is decorative. Credential availability, rather than its
+ // duration, determines when startup can advance.
+ progress.value = withTiming(4, { duration: 3000 });
if (themeMode === 'DARK' || themeMode === 'PRIVATE') {
toggleColorMode();
}
RestClient.setUseTor(torEnbled);
+ return () => {
+ mounted.current = false;
+ cancelAnimation(progress);
+ };
}, []);
- const navigateToApp = async () => {
- try {
- const hasCreds = await SecureStore.hasPin();
- if (hasCreds) {
- navigation.replace('Login', { relogin: false });
- } else {
- navigation.replace('CreatePin');
+ useEffect(() => {
+ let current = true;
+ readPending.current = true;
+ const navigateToApp = async () => {
+ try {
+ const hasCreds = await SecureStore.hasPin({ throwOnError: true });
+ if (!current) return;
+ if (hasCreds) {
+ navigation.replace('Login', { relogin: false });
+ } else {
+ navigation.replace('CreatePin');
+ }
+ } catch {
+ if (current) {
+ readPending.current = false;
+ setStartupError(true);
+ }
}
- } catch (err) {
- console.log(err);
- }
+ };
+ navigateToApp();
+ return () => {
+ current = false;
+ };
+ }, [attempt, navigation]);
+
+ const retryStartup = () => {
+ if (!mounted.current || readPending.current) return;
+ readPending.current = true;
+ setStartupError(false);
+ setAttempt((previous) => previous + 1);
};
- const progress = useSharedValue(0);
const inputRange = [0, 1, 2, 3, 4];
const heightRange = [0, windowHeight * 2, windowHeight * 2, windowHeight, windowHeight];
const widthRange = [0, windowHeight * 2, windowHeight * 2, windowHeight, windowWidth];
@@ -115,6 +141,18 @@ function SplashScreen({ navigation }) {
+ {}}
+ showCloseIcon={false}
+ dismissible={false}
+ title={translations.common.somethingWrong}
+ subTitle={translations.login.startupCredentialError}
+ buttonText={translations.common.retry}
+ buttonCallback={retryStartup}
+ modalBackground={`${colorMode}.modalWhiteBackground`}
+ textColor={`${colorMode}.textGreen`}
+ />
);
}
diff --git a/src/screens/USDT/RecieveUsdt.tsx b/src/screens/USDT/RecieveUsdt.tsx
index 68cdbd2c1f..b7c0637aa0 100644
--- a/src/screens/USDT/RecieveUsdt.tsx
+++ b/src/screens/USDT/RecieveUsdt.tsx
@@ -1,6 +1,6 @@
import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
import React, { useContext } from 'react';
-import { StyleSheet } from 'react-native';
+import { ScrollView, StyleSheet } from 'react-native';
import KeeperQRCode from 'src/components/KeeperQRCode';
import Text from 'src/components/KeeperText';
import ScreenWrapper from 'src/components/ScreenWrapper';
@@ -19,9 +19,22 @@ const RecieveUsdt = ({ route }) => {
return (
-
+
+
+
+ {usdtWalletText.sendingPausedTitle}
+
+
+ {usdtWalletText.receivePausedWarning}
+
+
+
{
{usdtWalletText.sendOnlyUsdt}
-
+
);
};
@@ -54,6 +67,20 @@ const RecieveUsdt = ({ route }) => {
export default RecieveUsdt;
const styles = StyleSheet.create({
+ scrollContent: {
+ flexGrow: 1,
+ },
+ warning: {
+ borderWidth: 1,
+ borderRadius: 10,
+ marginHorizontal: 16,
+ marginTop: hp(12),
+ paddingHorizontal: 16,
+ paddingVertical: hp(12),
+ },
+ warningBody: {
+ marginTop: hp(6),
+ },
container: {
alignItems: 'center',
marginTop: hp(20),
diff --git a/src/screens/USDT/UsdtDetails.tsx b/src/screens/USDT/UsdtDetails.tsx
index 745964ce3e..c8e751b50e 100644
--- a/src/screens/USDT/UsdtDetails.tsx
+++ b/src/screens/USDT/UsdtDetails.tsx
@@ -13,10 +13,8 @@ import { getAvailableBalanceUSDTWallet } from 'src/services/wallets/factories/US
import WalletDetailHeader from '../WalletDetails/components/WalletDetailHeader';
import DetailCards from '../WalletDetails/components/DetailCards';
import ThemedColor from 'src/components/ThemedColor/ThemedColor';
-import MoreCard from '../WalletDetails/components/MoreCard';
-import KeeperModal from 'src/components/KeeperModal';
-import SwapSvg from 'src/assets/images/swap.svg';
import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView';
+import KeeperModal from 'src/components/KeeperModal';
function TransactionsAndUTXOs({ transactions, setPullRefresh, pullRefresh, wallet }) {
const [initialLoading, setInitialLoading] = useState(false);
@@ -39,14 +37,14 @@ const UsdtDetails = ({ route }) => {
const { colorMode } = useColorMode();
const navigation = useNavigation();
const { translations } = useContext(LocalizationContext);
- const { common } = translations;
+ const { common, usdtWalletText } = translations;
const { getWalletCardGradient, getWalletTags } = useWalletAsset();
const [pullRefresh, setPullRefresh] = useState(false);
const { usdtWalletId } = route.params || {};
const { getWalletById } = useUSDTWallets();
const usdtWallet = getWalletById(usdtWalletId);
- const [showmore, setShowMore] = useState(false);
const viewAll_color = ThemedColor({ name: 'viewAll_color' });
+ const [showSendPaused, setShowSendPaused] = useState(false);
return (
@@ -64,21 +62,26 @@ const UsdtDetails = ({ route }) => {
- navigation.dispatch(CommonActions.navigate('sendUsdt', { usdtWallet }))
- }
+ sendCallback={() => setShowSendPaused(true)}
receiveCallback={() =>
navigation.dispatch(CommonActions.navigate('usdtReceive', { usdtWallet }))
}
- buyCallback={() =>
- navigation.dispatch(CommonActions.navigate('buyUstd', { usdtWallet }))
- }
wallet={usdtWallet}
/>
+
+
+ {usdtWalletText.pausedTitle}
+
+
+ {usdtWalletText.pausedBody}
+
+
{usdtWallet ? (
{
)}
setShowMore(false)}
- title={common.moreOptions}
- subTitleColor={`${colorMode}.modalSubtitleBlack`}
- textColor={`${colorMode}.textGreen`}
+ visible={showSendPaused}
+ close={() => setShowSendPaused(false)}
+ title={usdtWalletText.sendingPausedTitle}
+ subTitle={usdtWalletText.sendingPausedBody}
modalBackground={`${colorMode}.modalWhiteBackground`}
- Content={() => {
- return (
-
- {
- setShowMore(false);
- }}
- Icon={}
- />
-
- );
- }}
+ textColor={`${colorMode}.textGreen`}
+ subTitleColor={`${colorMode}.modalSubtitleBlack`}
+ buttonText={common.ok}
+ buttonCallback={() => setShowSendPaused(false)}
/>
);
@@ -168,7 +161,7 @@ const styles = StyleSheet.create({
paddingHorizontal: 18,
},
walletContainer: {
- paddingTop: wp(30),
+ paddingTop: hp(8),
paddingBottom: 20,
flex: 1,
justifyContent: 'space-between',
@@ -227,6 +220,21 @@ const styles = StyleSheet.create({
justifyContent: 'center',
marginTop: hp(20),
},
+ pausedNotice: {
+ marginHorizontal: wp(22),
+ marginTop: hp(65),
+ paddingHorizontal: wp(16),
+ paddingVertical: hp(12),
+ borderWidth: 1,
+ borderRadius: 10,
+ },
+ pausedTitle: {
+ fontSize: wp(14),
+ },
+ pausedBody: {
+ fontSize: wp(12),
+ marginTop: hp(6),
+ },
detailCardsContainer: {
zIndex: 1000,
},
diff --git a/src/screens/USDT/UsdtTransactionDetail.tsx b/src/screens/USDT/UsdtTransactionDetail.tsx
index 521ac6f099..3b1e0778b6 100644
--- a/src/screens/USDT/UsdtTransactionDetail.tsx
+++ b/src/screens/USDT/UsdtTransactionDetail.tsx
@@ -18,13 +18,15 @@ import Edit from 'src/assets/images/edit.svg';
import EditDark from 'src/assets/images/edit-white.svg';
import { current } from '@reduxjs/toolkit';
import StatusContent from './components/StatusContent';
-import { USDTTransaction } from 'src/services/wallets/operations/dollars/USDT';
+import {
+ isHistoricalUnverifiedUSDTRequest,
+ isUSDTStatusUnavailable,
+ USDTTransaction,
+} from 'src/services/wallets/operations/dollars/USDT';
import { USDTWallet } from 'src/services/wallets/factories/USDTWalletFactory';
import Link from 'src/assets/images/link.svg';
import LinkDark from 'src/assets/images/link-white.svg';
import openLink from 'src/utils/OpenLink';
-import useToastMessage from 'src/hooks/useToastMessage';
-import ToastErrorIcon from 'src/assets/images/toast_error.svg';
export function EditNoteContent({ existingNote, noteRef }: { existingNote: string; noteRef }) {
const updateNote = useCallback((text) => {
@@ -52,6 +54,10 @@ const UsdtTransactionDetail = ({ route }) => {
const transactionId = transaction.txId || transaction.traceId;
const date = transaction.timestamp;
const amount = parseFloat(transaction.amount);
+ // A trace without a chain transaction ID is a historical provider request.
+ // Its final result cannot be established after the provider was retired.
+ const legacyRequest = isHistoricalUnverifiedUSDTRequest(transaction);
+ const unavailableStatus = isUSDTStatusUnavailable(transaction);
const status = transaction.status;
let transactionType: string;
if (transaction.to === wallet.accountStatus.gasFreeAddress) {
@@ -66,7 +72,6 @@ const UsdtTransactionDetail = ({ route }) => {
const [visible, setVisible] = useState(false);
const [updatingLabel, setUpdatingLabel] = useState(false);
const close = () => setVisible(false);
- const { showToast } = useToastMessage();
function InfoCard({
title,
@@ -120,12 +125,14 @@ const UsdtTransactionDetail = ({ route }) => {
- {transactionType === 'Received' ? (
+ {legacyRequest ? null : transactionType === 'Received' ? (
colorMode === 'dark' ? (
) : (
@@ -146,6 +153,11 @@ const UsdtTransactionDetail = ({ route }) => {
+ {legacyRequest && (
+
+ {usdtWalletText.requestedAmount}
+
+ )}
{amount} USDT
@@ -182,14 +194,10 @@ const UsdtTransactionDetail = ({ route }) => {
*/}
{
if (transaction.txId) {
redirectToBlockExplorer(transaction.txId);
- } else if (transaction.traceId) {
- showToast(
- 'Transaction is being processed and does not have a Transaction ID yet.',
-
- );
}
}}
>
@@ -213,8 +221,15 @@ const UsdtTransactionDetail = ({ route }) => {
title={usdtWalletText.status}
showIcon={false}
letterSpacing={2.4}
- Content={() => }
+ Content={() => }
/>
+ {legacyRequest && (
+
+ )}
{transactionType === 'Sent' && (
{
title={
transactionType === 'Received'
? usdtWalletText.recievedAmount
+ : legacyRequest
+ ? usdtWalletText.requestedAmount
: usdtWalletText.sendingAmount
}
describtion={`${amount} USDT`}
showIcon={false}
letterSpacing={2.4}
/>
- {transaction.transferFee || transaction.fee ? (
+ {!legacyRequest && (transaction.transferFee || transaction.fee) ? (
{
letterSpacing={2.4}
/>
) : null}
- {transaction.activateFee ? (
+ {!legacyRequest && transaction.activateFee ? (
{
+const StatusContent = ({ status, unavailable = false }) => {
const { colorMode } = useColorMode();
- const containerbackgroundColor =
- status === GasFreeTransferStatus.SUCCEED
- ? Colors.PaleTropicalTeal
- : status === GasFreeTransferStatus.CONFIRMING
- ? Colors.lightOrange
- : Colors.lightindigoblue;
+ const { translations } = useContext(LocalizationContext);
+ // A legacy SUCCEED value is not proof of a confirmed chain transaction.
+ const statusUnavailable =
+ unavailable ||
+ status === GasFreeTransferStatus.SUCCEED ||
+ status === GasFreeTransferStatus.UNVERIFIED;
+ const chainConfirmed = status === GasFreeTransferStatus.CHAIN_CONFIRMED;
+ const containerbackgroundColor = statusUnavailable
+ ? Colors.lightindigoblue
+ : chainConfirmed
+ ? Colors.PaleTropicalTeal
+ : status === GasFreeTransferStatus.CONFIRMING
+ ? Colors.lightOrange
+ : Colors.lightindigoblue;
- const textColor =
- status === GasFreeTransferStatus.SUCCEED
- ? Colors.TropicalTeal
- : status === GasFreeTransferStatus.CONFIRMING
- ? Colors.darkOrange
- : Colors.indigoblue;
+ const textColor = statusUnavailable
+ ? Colors.indigoblue
+ : chainConfirmed
+ ? Colors.TropicalTeal
+ : status === GasFreeTransferStatus.CONFIRMING
+ ? Colors.darkOrange
+ : Colors.indigoblue;
return (
{
style={styles.container}
>
- {status === GasFreeTransferStatus.SUCCEED ? 'SUCCESS' : status}
+ {statusUnavailable
+ ? translations.usdtWalletText.statusUnavailable
+ : chainConfirmed
+ ? 'SUCCESS'
+ : status}
);
@@ -40,7 +54,8 @@ const styles = StyleSheet.create({
container: {
borderWidth: 1,
borderRadius: 30,
- width: wp(80),
+ minWidth: wp(80),
+ paddingHorizontal: wp(8),
height: hp(20),
justifyContent: 'center',
alignItems: 'center',
diff --git a/src/screens/UTXOManagement/UTXOLabeling.tsx b/src/screens/UTXOManagement/UTXOLabeling.tsx
index 2b137dd6a2..95bbe6e382 100644
--- a/src/screens/UTXOManagement/UTXOLabeling.tsx
+++ b/src/screens/UTXOManagement/UTXOLabeling.tsx
@@ -54,6 +54,8 @@ function UTXOLabeling() {
const { transactions: txTranslations, wallet: walletTranslations, common } = translations;
const dispatch = useDispatch();
+ const activeAppId = useAppSelector((state) => state.storage.appId);
+ const originAppId = useRef(activeAppId).current;
// Live reactive wallet from Realm so spendability updates immediately after saga writes
const liveWalletResult = useWallets({ walletIds: [wallet.id] }).wallets[0];
const liveVaultResult = useVault({ vaultId: wallet.id }).activeVault;
@@ -127,7 +129,7 @@ function UTXOLabeling() {
const finalLabels = [{ name: noteRef.current, isSystem: false }];
if (txNoteLabels[utxo.txId][0]?.name) {
const labelChanges = getLabelChanges(txNoteLabels[utxo.txId], finalLabels);
- dispatch(bulkUpdateLabels({ labelChanges, txId: utxo.txId, wallet }));
+ dispatch(bulkUpdateLabels({ labelChanges, txId: utxo.txId, wallet }, originAppId));
} else {
dispatch(
addLabels({
@@ -135,13 +137,13 @@ function UTXOLabeling() {
txId: utxo.txId,
wallet,
type: LabelRefType.TXN,
- })
+ }, originAppId)
);
}
} else {
if (txNoteLabels[utxo.txId][0]?.name) {
const labelChanges = getLabelChanges(txNoteLabels[utxo.txId], []);
- dispatch(bulkUpdateLabels({ labelChanges, txId: utxo.txId, wallet }));
+ dispatch(bulkUpdateLabels({ labelChanges, txId: utxo.txId, wallet }, originAppId));
}
}
}
@@ -251,7 +253,7 @@ function UTXOLabeling() {
{
- dispatch(markUTXOSpendability({ wallet, txId: utxo.txId, vout: utxo.vout, spendability: 'spendable' }));
+ dispatch(markUTXOSpendability({ wallet, txId: utxo.txId, vout: utxo.vout, spendability: 'spendable' }, originAppId));
showToast('Coin marked spendable', );
}}
>
@@ -264,7 +266,7 @@ function UTXOLabeling() {
{
- dispatch(markUTXOSpendability({ wallet, txId: utxo.txId, vout: utxo.vout, spendability: 'doNotSpend' }));
+ dispatch(markUTXOSpendability({ wallet, txId: utxo.txId, vout: utxo.vout, spendability: 'doNotSpend' }, originAppId));
showToast('Coin marked Do Not Spend', );
}}
>
diff --git a/src/screens/UTXOManagement/components/LabelsEditor.tsx b/src/screens/UTXOManagement/components/LabelsEditor.tsx
index 58db542da5..3f703b0a96 100644
--- a/src/screens/UTXOManagement/components/LabelsEditor.tsx
+++ b/src/screens/UTXOManagement/components/LabelsEditor.tsx
@@ -28,6 +28,8 @@ function LabelsEditor({ utxo = null, address = null, wallet, onLabelsSaved, read
const { showToast } = useToastMessage();
const processDispatched = useRef(false);
const dispatch = useDispatch();
+ const activeAppId = useAppSelector((state) => state.storage.appId);
+ const originAppId = useRef(activeAppId).current;
const labelsKey = address ? address : `${utxo.txId}:${utxo.vout}`;
const getSortedNames = (labels) =>
@@ -106,9 +108,9 @@ function LabelsEditor({ utxo = null, address = null, wallet, onLabelsSaved, read
const labelChanges = getLabelChanges(initialLabels, finalLabels);
processDispatched.current = true;
if (address) {
- dispatch(bulkUpdateLabels({ labelChanges, address, wallet }));
+ dispatch(bulkUpdateLabels({ labelChanges, address, wallet }, originAppId));
} else {
- dispatch(bulkUpdateLabels({ labelChanges, UTXO: utxo, wallet }));
+ dispatch(bulkUpdateLabels({ labelChanges, UTXO: utxo, wallet }, originAppId));
}
};
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..5960a974a5 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,
]);
@@ -210,7 +212,7 @@ function AddReserveKey({ route }) {
{vaultTranslations.inheritanceKeyActivation}
- {vaultTranslations.availableAfterDelay}
+ {vaultTranslations.inheritanceActivationNote}
@@ -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/AllTransactions.tsx b/src/screens/Vault/AllTransactions.tsx
index ff3377922b..35638a64ea 100644
--- a/src/screens/Vault/AllTransactions.tsx
+++ b/src/screens/Vault/AllTransactions.tsx
@@ -1,13 +1,12 @@
import { FlatList, RefreshControl } from 'react-native';
-import React, { useState } from 'react';
+import React from 'react';
import { useColorMode } from '@gluestack-ui/themed-native-base';
import { useQuery } from '@realm/react';
-import { useDispatch } from 'react-redux';
import { RealmSchema } from 'src/storage/realm/enum';
import TransactionElement from 'src/components/TransactionElement';
import { getJSONFromRealmObject } from 'src/storage/realm/utils';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
+import { useWalletRefresh } from 'src/hooks/useWalletRefresh';
import { Wallet } from 'src/services/wallets/interfaces/wallet';
import useVault from 'src/hooks/useVault';
import { EntityKind } from 'src/services/wallets/enums';
@@ -17,7 +16,6 @@ import WalletHeader from 'src/components/WalletHeader';
function AllTransactions({ route }) {
const { colorMode } = useColorMode();
- const dispatch = useDispatch();
const { title, entityKind, subtitle, vaultId = '' } = route?.params;
const { activeVault: vault } = useVault({ vaultId });
@@ -25,22 +23,17 @@ function AllTransactions({ route }) {
.map(getJSONFromRealmObject)
.filter((wallet) => !wallet.archived)[0];
- const [pullRefresh, setPullRefresh] = useState(false);
+ const { refreshing: pullRefresh, refresh } = useWalletRefresh();
const vaultTrans: Transaction[] = vault?.specs?.transactions || [];
const walletTrans: Transaction[] = wallet?.specs.transactions || [];
+ const currentWallet = entityKind === EntityKind.WALLET ? wallet : vault;
const renderTransactionElement = ({ item }) => (
-
+
);
const pullDownRefresh = () => {
- setPullRefresh(true);
- refreshVault();
- setPullRefresh(false);
- };
-
- const refreshVault = () => {
- dispatch(refreshWallets([vault], { hardRefresh: true }));
+ refresh([currentWallet], { hardRefresh: true });
};
return (
diff --git a/src/screens/Vault/ChoosePolicyNew.tsx b/src/screens/Vault/ChoosePolicyNew.tsx
index 390114b990..9d6bec45a8 100644
--- a/src/screens/Vault/ChoosePolicyNew.tsx
+++ b/src/screens/Vault/ChoosePolicyNew.tsx
@@ -1,7 +1,7 @@
import Text from 'src/components/KeeperText';
import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
import { StyleSheet, TouchableOpacity } from 'react-native';
-import React, { useCallback, useContext, useEffect, useState } from 'react';
+import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import {
DelayedPolicyUpdate,
SignerPolicy,
@@ -46,6 +46,8 @@ import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg';
import ThemedColor from 'src/components/ThemedColor/ThemedColor';
function ChoosePolicyNew({ navigation, route }) {
+ const selectedAppId = useAppSelector((state) => state.storage.appId);
+ const originAppId = useRef(selectedAppId).current;
const { colorMode } = useColorMode();
const isDarkMode = colorMode === 'dark';
const { showToast } = useToastMessage();
@@ -193,7 +195,7 @@ function ChoosePolicyNew({ navigation, route }) {
restrictions: newPolicy.restrictions,
signingDelay: newPolicy.signingDelay,
};
- dispatch(updateSignerPolicy(signer, route.params.vaultKey, policyUpdates, verificationToken));
+ dispatch(updateSignerPolicy(signer, route.params.vaultKey, policyUpdates, verificationToken, originAppId));
};
useEffect(() => {
diff --git a/src/screens/Vault/ResetEmergencyKey.tsx b/src/screens/Vault/ResetEmergencyKey.tsx
index 838e055488..f99c452800 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();
@@ -213,7 +213,7 @@ function ResetEmergencyKey({ route }) {
{vaultText.chooseNewActivationTimeTitle}
- {vaultText.chooseNewActivationTimeDesc}
+ {vaultText.chooseNewEmergencyActivationTimeDesc}
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/VaultConfigurationRecreation.tsx b/src/screens/Vault/VaultConfigurationRecreation.tsx
index c84e686c26..753190ca7b 100644
--- a/src/screens/Vault/VaultConfigurationRecreation.tsx
+++ b/src/screens/Vault/VaultConfigurationRecreation.tsx
@@ -9,6 +9,7 @@ import ImportIcon from 'src/assets/images/import.svg';
import { LocalizationContext } from 'src/context/Localization/LocContext';
import OptionCard from 'src/components/OptionCard';
import RNFS from 'react-native-fs';
+import { getDocumentReadPath } from 'src/utils/documentReadPath';
import { pick, types } from '@react-native-documents/picker';
import Colors from 'src/theme/Colors';
import Text from 'src/components/KeeperText';
@@ -54,7 +55,8 @@ function VaultConfigurationCreation() {
type: [types.docx, types.allFiles],
allowMultiSelection: false,
});
- const content = await RNFS.readFile(response[0].uri, 'utf8');
+ const readPath = getDocumentReadPath(response[0].uri, Platform.OS);
+ const content = await RNFS.readFile(readPath, 'utf8');
navigateToSetup(content);
} catch (err) {
console.log(err);
diff --git a/src/screens/Vault/VaultDetails.tsx b/src/screens/Vault/VaultDetails.tsx
index 4ae46546d7..c5f4b92445 100644
--- a/src/screens/Vault/VaultDetails.tsx
+++ b/src/screens/Vault/VaultDetails.tsx
@@ -9,7 +9,7 @@ import SignerIcon from 'src/assets/images/keys-icon.svg';
import KeeperModal from 'src/components/KeeperModal';
import TransactionElement from 'src/components/TransactionElement';
import { MiniscriptTypes, VaultType } from 'src/services/wallets/enums';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
+import { useWalletRefresh } from 'src/hooks/useWalletRefresh';
import { setIntroModal } from 'src/store/reducers/vaults';
import { useAppSelector } from 'src/store/hooks';
import { useDispatch } from 'react-redux';
@@ -155,9 +155,11 @@ function VaultDetails({ navigation, route }: ScreenProps) {
viewTransaction = null,
} = route.params || {};
const dispatch = useDispatch();
+ const activeAppId = useAppSelector((state) => state.storage.appId);
+ const originAppId = useRef(activeAppId).current;
const { showToast } = useToastMessage();
const { activeVault: vault } = useVault({ vaultId });
- const [pullRefresh, setPullRefresh] = useState(false);
+ const { refreshing: pullRefresh, refresh } = useWalletRefresh();
const { vaultSigners: keys } = useSigners(vault.id);
const transactions = useMemo(
() =>
@@ -372,9 +374,7 @@ function VaultDetails({ navigation, route }: ScreenProps) {
}, [syncing, ELECTRUM_CLIENT]);
const syncVault = (hardRefresh) => {
- setPullRefresh(true);
- dispatch(refreshWallets([vault], { hardRefresh }));
- setPullRefresh(false);
+ refresh([vault], { hardRefresh });
};
const showTimelockModalContent = useCallback(() => {
@@ -442,7 +442,7 @@ function VaultDetails({ navigation, route }: ScreenProps) {
const txid = tnx?.potentialTxId || getTnxIdFromCachedTnx(tnx);
for (const broadcastedTnx of transactions) {
if (broadcastedTnx.txid === txid) {
- dispatch(discardBroadcastedTnx({ cachedTxid: tnx.txid, vault }));
+ dispatch(discardBroadcastedTnx({ cachedTxid: tnx.txid, vault }, originAppId));
}
}
}
diff --git a/src/screens/Vault/VaultMigrationController.tsx b/src/screens/Vault/VaultMigrationController.tsx
index bfb688e194..d0ea0f63d7 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 {
@@ -304,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);
};
@@ -375,34 +400,14 @@ function VaultMigrationController({
return;
}
- let initialTimelock = 0;
+ const initialTimelock = resolveInitialTimelock(
+ miniscriptTypes,
+ initialTimelockDuration,
+ (label) => getTimelockDuration(label, bitcoinNetworkType)
+ );
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;
- // }
- // }
-
- if (initialTimelockDuration) {
- initialTimelock = getTimelockDuration(initialTimelockDuration, bitcoinNetworkType);
- if (!initialTimelock) {
- showToast('Failed to determine initial timelock duration', );
- return;
- }
- }
+ const currentTimeForLock = await getCurrentTimeForLock();
const inheritanceSignerWithTimelocks = [];
const emergencySignerWithTimelocks = [];
@@ -416,7 +421,7 @@ function VaultMigrationController({
}
inheritanceSignerWithTimelocks.push({
signer: key,
- timelock: getCurrentTimeForLock() + initialTimelock + timelock,
+ timelock: currentTimeForLock + initialTimelock + timelock,
});
}
}
@@ -430,7 +435,7 @@ function VaultMigrationController({
}
emergencySignerWithTimelocks.push({
signer: key,
- timelock: getCurrentTimeForLock() + initialTimelock + timelock,
+ timelock: currentTimeForLock + initialTimelock + timelock,
});
}
}
@@ -440,7 +445,7 @@ function VaultMigrationController({
inheritanceSignerWithTimelocks,
emergencySignerWithTimelocks,
vaultInfo.vaultScheme,
- initialTimelock ? getCurrentTimeForLock() + initialTimelock : 0
+ initialTimelock ? currentTimeForLock + initialTimelock : 0
);
if (!miniscriptElements) {
diff --git a/src/screens/Vault/VaultSettings.tsx b/src/screens/Vault/VaultSettings.tsx
index 49b37e43e9..802cb65c42 100644
--- a/src/screens/Vault/VaultSettings.tsx
+++ b/src/screens/Vault/VaultSettings.tsx
@@ -32,6 +32,9 @@ import PrivateVaultSetupIcon from 'src/assets/privateImages/vault_setup.svg';
import Text from 'src/components/KeeperText';
import { ConciergeTag } from 'src/models/enums/ConciergeTag';
import ConciergeNeedHelp from 'src/assets/images/conciergeNeedHelp.svg';
+import { useDispatch } from 'react-redux';
+import { updateRecoveryVisibility } from 'src/store/sagaActions/wallets';
+import { currentBackupAccountSession } from 'src/services/backup/transport';
import SettingCard from '../Home/components/Settings/Component/SettingCard';
import EditWalletDetailsModal from '../WalletDetails/EditWalletDetailsModal';
import WalletConfiguration from './components/WalletConfiguration';
@@ -42,10 +45,10 @@ import { NfcTech } from 'react-native-nfc-manager';
import { useQuery } from '@realm/react';
import ImportExportLabels from 'src/components/ImportExportLabels';
import ToastErrorIcon from 'src/assets/images/toast_error.svg';
-import { useSelector } from 'react-redux';
import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg';
import ThemedColor from 'src/components/ThemedColor/ThemedColor';
function VaultSettings({ route }) {
+ const dispatch = useDispatch();
const { colorMode } = useColorMode();
const isDarkMode = colorMode === 'dark';
const navigation = useNavigation();
@@ -109,15 +112,28 @@ function VaultSettings({ route }) {
const updateWalletVisibility = () => {
try {
- dbManager.updateObjectById(RealmSchema.Vault, vault.id, {
- presentationData: {
- name: vault.presentationData.name,
- description: vault.presentationData.description,
- visibility: VisibilityType.HIDDEN,
- },
- });
- showToast(vaultText.vaultHiddenSuccessMessage, , IToastCategory.DEFAULT, 5000);
- navigation.navigate('Home');
+ const appId = (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id;
+ const backupSession = currentBackupAccountSession();
+ dispatch(
+ updateRecoveryVisibility(vault.id, EntityKind.VAULT, VisibilityType.HIDDEN, (updated) => {
+ if (
+ currentBackupAccountSession() !== backupSession ||
+ (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id !== appId
+ )
+ return;
+ if (!updated) {
+ showToast(walletText.somethingWentWrong, );
+ return;
+ }
+ showToast(
+ vaultText.vaultHiddenSuccessMessage,
+ ,
+ IToastCategory.DEFAULT,
+ 5000
+ );
+ navigation.navigate('Home');
+ })
+ );
} catch (error) {
console.log(error);
}
diff --git a/src/screens/Vault/components/TransactionsAndUTXOs.tsx b/src/screens/Vault/components/TransactionsAndUTXOs.tsx
index b9d9be1d5b..c5ca3f4e9c 100644
--- a/src/screens/Vault/components/TransactionsAndUTXOs.tsx
+++ b/src/screens/Vault/components/TransactionsAndUTXOs.tsx
@@ -1,14 +1,13 @@
import { FlatList, RefreshControl, TouchableOpacity } from 'react-native';
-import React, { useContext, useState } from 'react';
+import React, { useContext } from 'react';
import { CommonActions, useNavigation } from '@react-navigation/native';
import TransactionElement from 'src/components/TransactionElement';
import { Vault } from 'src/services/wallets/interfaces/vault';
import { Box, HStack, VStack } from '@gluestack-ui/themed-native-base';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
+import { useWalletRefresh } from 'src/hooks/useWalletRefresh';
import EmptyStateView from 'src/components/EmptyView/EmptyStateView';
import NoVaultTransactionIcon from 'src/assets/images/emptystate.svg';
import IconArrowBlack from 'src/assets/images/icon_arrow_black.svg';
-import { useDispatch } from 'react-redux';
import Text from 'src/components/KeeperText';
import { windowHeight, wp } from 'src/constants/responsive';
import { EntityKind } from 'src/services/wallets/enums';
@@ -24,14 +23,11 @@ function TransactionsAndUTXOs({
autoRefresh: boolean;
}) {
const { colorMode } = useColorMode();
- const [pullRefresh, setPullRefresh] = useState(false);
+ const { refreshing: pullRefresh, refresh } = useWalletRefresh();
const { translations } = useContext(LocalizationContext);
const { home } = translations;
- const dispatch = useDispatch();
const syncVault = () => {
- setPullRefresh(true);
- dispatch(refreshWallets([vault], { hardRefresh: true }));
- setPullRefresh(false);
+ refresh([vault], { hardRefresh: true });
};
const navigation = useNavigation();
@@ -71,6 +67,7 @@ function TransactionsAndUTXOs({
title: home.vaultTransactions,
subtitle: home.incommingAndOutgoing,
entityKind: EntityKind.VAULT,
+ vaultId: vault.id,
})
);
}}
diff --git a/src/screens/ViewTransactions/TransactionDetails.tsx b/src/screens/ViewTransactions/TransactionDetails.tsx
index 6d0bd4220a..5782fad77d 100644
--- a/src/screens/ViewTransactions/TransactionDetails.tsx
+++ b/src/screens/ViewTransactions/TransactionDetails.tsx
@@ -71,6 +71,8 @@ function TransactionDetails({ route }) {
const close = () => setVisible(false);
const noteRef = useRef();
const dispatch = useDispatch();
+ const activeAppId = useAppSelector((state) => state.storage.appId);
+ const originAppId = useRef(activeAppId).current;
const [updatingLabel, setUpdatingLabel] = React.useState(false);
const { bitcoinNetworkType } = useAppSelector((state) => state.settings);
const insets = useSafeAreaInsets();
@@ -88,7 +90,7 @@ function TransactionDetails({ route }) {
const finalLabels = [{ name: noteRef.current, isSystem: false }];
if (labels[transaction.txid][0]?.name) {
const labelChanges = getLabelChanges(labels[transaction.txid], finalLabels);
- dispatch(bulkUpdateLabels({ labelChanges, txId: transaction.txid, wallet }));
+ dispatch(bulkUpdateLabels({ labelChanges, txId: transaction.txid, wallet }, originAppId));
} else {
dispatch(
addLabels({
@@ -96,13 +98,13 @@ function TransactionDetails({ route }) {
txId: transaction.txid,
wallet,
type: LabelRefType.TXN,
- })
+ }, originAppId)
);
}
} else {
if (labels[transaction.txid][0]?.name) {
const labelChanges = getLabelChanges(labels[transaction.txid], []);
- dispatch(bulkUpdateLabels({ labelChanges, txId: transaction.txid, wallet }));
+ dispatch(bulkUpdateLabels({ labelChanges, txId: transaction.txid, wallet }, originAppId));
}
}
}
diff --git a/src/screens/ViewTransactions/TransactionHistory.tsx b/src/screens/ViewTransactions/TransactionHistory.tsx
index c546c47ce8..bfd56a6faa 100644
--- a/src/screens/ViewTransactions/TransactionHistory.tsx
+++ b/src/screens/ViewTransactions/TransactionHistory.tsx
@@ -1,28 +1,41 @@
import { FlatList, RefreshControl, StatusBar, StyleSheet } from 'react-native';
import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
-import React, { use, useContext, useMemo, useState } from 'react';
+import React, { useContext, useMemo } from 'react';
import { hp, wp } from 'src/constants/responsive';
import { LocalizationContext } from 'src/context/Localization/LocContext';
import { Wallet } from 'src/services/wallets/interfaces/wallet';
+import { Vault } from 'src/services/wallets/interfaces/vault';
import { CommonActions, useNavigation } from '@react-navigation/native';
import TransactionElement from 'src/components/TransactionElement';
import EmptyStateView from 'src/components/EmptyView/EmptyStateView';
import NoTransactionIcon from 'src/assets/images/noTransaction.svg';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
+import { useWalletRefresh } from 'src/hooks/useWalletRefresh';
import { useDispatch } from 'react-redux';
import { setStateFromSnapshot } from 'src/store/reducers/send_and_receive';
import CurrencyTypeSwitch from 'src/components/Switch/CurrencyTypeSwitch';
import WalletHeader from 'src/components/WalletHeader';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
+import { useQuery } from '@realm/react';
+import { RealmSchema } from 'src/storage/realm/enum';
+import { getJSONFromRealmObject } from 'src/storage/realm/utils';
+import { EntityKind } from 'src/services/wallets/enums';
function TransactionHistory({ route }) {
const { colorMode } = useColorMode();
const navigation = useNavigation();
const { translations } = useContext(LocalizationContext);
const { common, transactions: transactionsText } = translations;
- const { wallet }: { wallet: Wallet } = route.params;
- const [pullRefresh, setPullRefresh] = useState(false);
+ const { wallet: routeWallet }: { wallet: Wallet | Vault } = route.params;
+ const walletRecord = useQuery(RealmSchema.Wallet, (collection) =>
+ collection.filtered('id == $0', routeWallet.id)
+ )[0];
+ const vaultRecord = useQuery(RealmSchema.Vault, (collection) =>
+ collection.filtered('id == $0', routeWallet.id)
+ )[0];
+ const record = routeWallet.entityKind === EntityKind.VAULT ? vaultRecord : walletRecord;
+ const wallet = record ? (getJSONFromRealmObject(record) as unknown as Wallet | Vault) : routeWallet;
+ const { refreshing: pullRefresh, refresh } = useWalletRefresh();
const dispatch = useDispatch();
const insets = useSafeAreaInsets();
const transactions = useMemo(
@@ -67,9 +80,7 @@ function TransactionHistory({ route }) {
);
const pullDownRefresh = () => {
- setPullRefresh(true);
- dispatch(refreshWallets([wallet], { hardRefresh: true }));
- setPullRefresh(false);
+ refresh([wallet], { hardRefresh: true });
};
return (
diff --git a/src/screens/WalletDetails/WalletDetails.tsx b/src/screens/WalletDetails/WalletDetails.tsx
index f5f9422437..ec901ff5ca 100644
--- a/src/screens/WalletDetails/WalletDetails.tsx
+++ b/src/screens/WalletDetails/WalletDetails.tsx
@@ -7,7 +7,7 @@ import AddWalletIcon from 'src/assets/images/addWallet_illustration.svg';
import TickIcon from 'src/assets/images/icon_tick.svg';
import { hp, wp } from 'src/constants/responsive';
import Text from 'src/components/KeeperText';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
+import { useWalletRefresh } from 'src/hooks/useWalletRefresh';
import { setIntroModal } from 'src/store/reducers/wallets';
import { useAppSelector } from 'src/store/hooks';
import useWallets from 'src/hooks/useWallets';
@@ -27,7 +27,7 @@ import ThemedColor from 'src/components/ThemedColor/ThemedColor';
import { useUTXOSpendability } from 'src/hooks/useUTXOSpendability';
// TODO: add type definitions to all components
-function TransactionsAndUTXOs({ transactions, setPullRefresh, pullRefresh, wallet }) {
+function TransactionsAndUTXOs({ transactions, pullRefresh, onRefresh, wallet }) {
const { walletSyncing } = useAppSelector((state) => state.wallet);
const syncing = walletSyncing && wallet ? !!walletSyncing[wallet.id] : false;
@@ -36,9 +36,9 @@ function TransactionsAndUTXOs({ transactions, setPullRefresh, pullRefresh, walle
>
);
@@ -69,7 +69,7 @@ function WalletDetails({ route }: ScreenProps) {
const { walletSyncing } = useAppSelector((state) => state.wallet);
const syncing = walletSyncing && wallet ? !!walletSyncing[wallet.id] : false;
const introModal = useAppSelector((state) => state.wallet.introModal) || false;
- const [pullRefresh, setPullRefresh] = useState(false);
+ const { refreshing: pullRefresh, refresh } = useWalletRefresh();
const viewAll_color = ThemedColor({ name: 'viewAll_color' });
useEffect(() => {
@@ -113,9 +113,7 @@ function WalletDetails({ route }: ScreenProps) {
}, [viewTransaction, wallet, navigation]);
const pullDownRefresh = (hardRefresh) => {
- setPullRefresh(true);
- dispatch(refreshWallets([wallet], { hardRefresh }));
- setPullRefresh(false);
+ refresh([wallet], { hardRefresh });
};
return (
@@ -179,9 +177,9 @@ function WalletDetails({ route }: ScreenProps) {
) : null}
pullDownRefresh(true)}
/>
) : (
diff --git a/src/screens/WalletDetails/WalletSettings.tsx b/src/screens/WalletDetails/WalletSettings.tsx
index df16b1542e..736687d1a8 100644
--- a/src/screens/WalletDetails/WalletSettings.tsx
+++ b/src/screens/WalletDetails/WalletSettings.tsx
@@ -17,6 +17,8 @@ import dbManager from 'src/storage/realm/dbManager';
import { RealmSchema } from 'src/storage/realm/enum';
import { EntityKind, VisibilityType } from 'src/services/wallets/enums';
import { captureError } from 'src/services/sentry';
+import { currentBackupAccountSession } from 'src/services/backup/transport';
+import { refreshWallets, updateRecoveryVisibility } from 'src/store/sagaActions/wallets';
import BackupModalContent from '../AppSettings/BackupModal';
import { credsAuthenticated } from 'src/store/reducers/login';
import { useDispatch } from 'react-redux';
@@ -31,7 +33,6 @@ import ToastErrorIcon from 'src/assets/images/toast_error.svg';
import Instruction from 'src/components/Instruction';
import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg';
import ThemedColor from 'src/components/ThemedColor/ThemedColor';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
function WalletSettings({ route }) {
const { colorMode } = useColorMode();
@@ -67,20 +68,28 @@ function WalletSettings({ route }) {
const updateWalletVisibility = () => {
try {
- const updatedPresentationData = {
- ...wallet.presentationData,
- visibility: VisibilityType.HIDDEN,
- };
- dbManager.updateObjectById(RealmSchema.Wallet, wallet.id, {
- presentationData: updatedPresentationData,
- });
- showToast(
- walletTranslation.walletHiddenSuccessMessage,
- ,
- IToastCategory.DEFAULT,
- 5000
+ const appId = (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id;
+ const backupSession = currentBackupAccountSession();
+ dispatch(
+ updateRecoveryVisibility(wallet.id, EntityKind.WALLET, VisibilityType.HIDDEN, (updated) => {
+ if (
+ currentBackupAccountSession() !== backupSession ||
+ (dbManager.getObjectByIndex(RealmSchema.KeeperApp) as any)?.id !== appId
+ )
+ return;
+ if (!updated) {
+ showToast(walletTranslation.somethingWentWrong);
+ return;
+ }
+ showToast(
+ walletTranslation.walletHiddenSuccessMessage,
+ ,
+ IToastCategory.DEFAULT,
+ 5000
+ );
+ navigation.navigate('Home');
+ })
);
- navigation.navigate('Home');
} catch (error) {
captureError(error);
showToast(walletTranslation.somethingWentWrong);
diff --git a/src/screens/WalletDetails/components/Transactions.tsx b/src/screens/WalletDetails/components/Transactions.tsx
index 3e83162957..8aa5b810a6 100644
--- a/src/screens/WalletDetails/components/Transactions.tsx
+++ b/src/screens/WalletDetails/components/Transactions.tsx
@@ -1,7 +1,5 @@
import { FlatList, RefreshControl } from 'react-native';
-import React, { useContext, useEffect, useMemo, useState } from 'react';
-import { useDispatch } from 'react-redux';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
+import React, { useContext, useEffect, useMemo } from 'react';
import EmptyStateView from 'src/components/EmptyView/EmptyStateView';
import NoTransactionIcon from 'src/assets/images/noTransaction.svg';
import TransactionElement from 'src/components/TransactionElement';
@@ -48,12 +46,12 @@ function TransactionItem({ item, wallet, navigation, index }) {
function Transactions({
transactions,
- setPullRefresh,
+ setPullRefresh = undefined,
pullRefresh,
currentWallet,
- setInitialLoading,
+ setInitialLoading = undefined,
+ onBitcoinRefresh = undefined,
}) {
- const dispatch = useDispatch();
const navigation = useNavigation();
const { translations } = useContext(LocalizationContext);
const { common } = translations;
@@ -80,16 +78,19 @@ function Transactions({
}, [transactions]);
const pullDownRefresh = async () => {
- setInitialLoading(true);
+ if (currentWallet.entityKind !== EntityKind.USDT_WALLET) {
+ onBitcoinRefresh?.();
+ return;
+ }
+ setPullRefresh?.(true);
+ setInitialLoading?.(true);
try {
- if (currentWallet.entityKind === EntityKind.USDT_WALLET) {
- await syncWallet(currentWallet);
- } else dispatch(refreshWallets([currentWallet], { hardRefresh: true }));
+ await syncWallet(currentWallet);
} catch (error) {
captureError(error);
} finally {
- setPullRefresh(false);
- setInitialLoading(false);
+ setPullRefresh?.(false);
+ setInitialLoading?.(false);
}
};
diff --git a/src/services/backend/Relay.ts b/src/services/backend/Relay.ts
index 8a35b6ae26..78db61fda9 100644
--- a/src/services/backend/Relay.ts
+++ b/src/services/backend/Relay.ts
@@ -1,3 +1,5 @@
+import { backupPost } from '../backup/transport';
+import type { BackupWriteIntent } from '../backup/intent';
import { NetworkType } from 'src/services/wallets/enums';
import { SubScriptionPlan } from 'src/models/interfaces/Subscription';
import {
@@ -17,6 +19,11 @@ import { Platform } from 'react-native';
const { HEXA_ID, RELAY } = config;
const TOR_ENDPOINT = 'https://check.torproject.org/api/ip';
+function requireBackupWriteIntent(intent: BackupWriteIntent | undefined): BackupWriteIntent {
+ if (!intent) throw new Error('Backup write intent unavailable');
+ return intent;
+}
+
interface SignerChange {
oldSignerId: string;
newSignerId: string;
@@ -106,16 +113,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;
+ }, intent: BackupWriteIntent | undefined): 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, false, requireBackupWriteIntent(intent));
const data = res.data || res.json;
return data;
} catch (err) {
@@ -126,13 +142,14 @@ export default class Relay {
public static migrateXfp = async (
appId: string,
- signerChanges: SignerChange[]
+ signerChanges: SignerChange[],
+ intent: BackupWriteIntent | undefined
): Promise<{
updated: boolean;
err?: string;
}> => {
try {
- const res = await RestClient.post(`${RELAY}migrateXfps`, { appId, signerChanges });
+ const res = await backupPost(`${RELAY}migrateXfps`, { appId, signerChanges }, false, requireBackupWriteIntent(intent));
const data = res.data || res.json;
return data;
} catch (err) {
@@ -142,7 +159,8 @@ export default class Relay {
};
public static deleteAppImageEntity = async (
- entityList
+ entityList,
+ intent: BackupWriteIntent | undefined
): Promise<{
status: string;
updated: boolean;
@@ -150,7 +168,7 @@ export default class Relay {
message?: string;
}> => {
try {
- const res = await RestClient.post(`${RELAY}deleteAppImageEntity`, entityList);
+ const res = await backupPost(`${RELAY}deleteAppImageEntity`, entityList, false, requireBackupWriteIntent(intent));
const data = res.data || res.json;
return data;
} catch (err) {
@@ -160,7 +178,8 @@ export default class Relay {
};
public static deleteVaultImage = async (
- entityList
+ entityList,
+ intent: BackupWriteIntent | undefined
): Promise<{
status: string;
updated: boolean;
@@ -168,7 +187,7 @@ export default class Relay {
message?: string;
}> => {
try {
- const res = await RestClient.post(`${RELAY}deleteVaults`, entityList);
+ const res = await backupPost(`${RELAY}deleteVaults`, entityList, false, requireBackupWriteIntent(intent));
const data = res.data || res.json;
return data;
} catch (err) {
@@ -178,7 +197,8 @@ export default class Relay {
};
public static updateVaultImage = async (
- vaultData
+ vaultData,
+ intent: BackupWriteIntent | undefined
): Promise<{
status?: number;
data?: {
@@ -188,7 +208,7 @@ export default class Relay {
message?: string;
}> => {
try {
- const res = await RestClient.post(`${RELAY}updateVaultImage`, vaultData);
+ const res = await backupPost(`${RELAY}updateVaultImage`, vaultData, false, requireBackupWriteIntent(intent));
const data = res.data || res.json;
return data;
} catch (err) {
@@ -213,32 +233,47 @@ export default class Relay {
public static getTestcoins = async (
recipientAddress: string,
- network: any,
+ network: NetworkType,
appId: string
): Promise<{
- txid: any;
- funded: any;
+ txid: string;
+ funded: boolean;
}> => {
- if (network === NetworkType.MAINNET) {
+ if (network !== NetworkType.TESTNET) {
throw new Error('Invalid network: failed to fund via testnet');
}
try {
- const res = await RestClient.post(`${config.RELAY}testnetFaucet`, {
- recipientAddress,
- appId,
- });
- const { txid, funded } = res.data;
+ const res = await RestClient.post(
+ `${config.RELAY}testnetFaucet`,
+ { recipientAddress, appId },
+ undefined,
+ { timeout: 20000 }
+ );
+ const { txid, funded } = res.data || {};
+ if (!funded || typeof txid !== 'string' || !/^[0-9a-f]{64}$/i.test(txid)) {
+ throw new Error('FAUCET_OUTCOME_UNKNOWN');
+ }
return {
txid,
funded,
};
} catch (err) {
+ if (err?.message === 'FAUCET_OUTCOME_UNKNOWN') throw err;
if (err.response?.status === 429) {
throw new Error('FAUCET_DAILY_LIMIT_REACHED');
}
- if (err.response) throw new Error(err.response.data.err);
- if (err.code) throw new Error(err.code);
+ if (
+ err?.code === 'ECONNABORTED' ||
+ err?.code === 'ETIMEDOUT' ||
+ err?.code === 'ERR_NETWORK' ||
+ err?.response?.status >= 500
+ ) {
+ // The relay may have broadcast before the response was lost. Never retry automatically.
+ throw new Error('FAUCET_OUTCOME_UNKNOWN');
+ }
+ if (err?.response) throw new Error(err.response.data?.err || 'FAUCET_REQUEST_FAILED');
+ throw new Error('FAUCET_REQUEST_FAILED');
}
};
@@ -270,29 +305,30 @@ export default class Relay {
public static modifyLabels = async (
appId: string,
addLabels: any[],
- deleteLabels: any[]
+ deleteLabels: any[],
+ intent: BackupWriteIntent | undefined
): Promise<{
updated: boolean;
}> => {
try {
- const res = (await RestClient.post(`${RELAY}modifyLabels`, {
+ const res = (await backupPost(`${RELAY}modifyLabels`, {
appId,
addLabels,
deleteLabels,
- })) as AxiosResponse;
+ }, false, requireBackupWriteIntent(intent))) as AxiosResponse;
const { updated } = res.data || res.json;
return {
updated,
};
} catch (err) {
- console.log('err', err);
- if (err.code) throw new Error(err.code);
+ captureError(err);
+ throw new Error('Failed to update backup labels. Check the backup before trying again.');
}
};
public static checkTorStatus = async () => {
try {
- const response = await RestClient.get(TOR_ENDPOINT, { timeout: 20000 });
+ const response = await RestClient.get(TOR_ENDPOINT, undefined, { timeout: 20000 });
const data = (response as AxiosResponse).data || (response as any).json;
return data.IsTor;
} catch (error) {
@@ -427,8 +463,10 @@ export default class Relay {
};
public static backupAllSignersAndVaults = async (
- allData
+ allData,
+ intent: BackupWriteIntent | undefined
): Promise<{
+ updated?: boolean;
status?: number;
data?: {
updated: boolean;
@@ -437,7 +475,7 @@ export default class Relay {
message?: string;
}> => {
try {
- const res = await RestClient.post(`${RELAY}backupAllSignersAndVaults`, allData);
+ const res = await backupPost(`${RELAY}backupAllSignersAndVaults`, allData, false, requireBackupWriteIntent(intent));
const data = res.data || res.json;
return data;
} catch (err) {
@@ -472,7 +510,8 @@ export default class Relay {
};
public static deleteBackup = async (
- body
+ body,
+ intent: BackupWriteIntent | undefined
): Promise<{
status?: number;
data?: {
@@ -482,7 +521,7 @@ export default class Relay {
message?: string;
}> => {
try {
- const res = await RestClient.post(`${RELAY}deleteBackup`, body);
+ const res = await backupPost(`${RELAY}deleteBackup`, body, true, requireBackupWriteIntent(intent));
const data = res.data || res.json;
return data;
} catch (err) {
@@ -804,4 +843,3 @@ export default class Relay {
}
};
}
-
diff --git a/src/services/backup/authority.ts b/src/services/backup/authority.ts
new file mode 100644
index 0000000000..e5e95cfd34
--- /dev/null
+++ b/src/services/backup/authority.ts
@@ -0,0 +1,238 @@
+import './encoding';
+import { Buffer } from 'buffer';
+import { HDKey, HARDENED_OFFSET } from '@scure/bip32';
+import { mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';
+import { wordlist } from '@scure/bip39/wordlists/english.js';
+import { secp256k1 } from '@noble/curves/secp256k1.js';
+import { equalBytes } from '@noble/curves/utils.js';
+import { hkdf } from '@noble/hashes/hkdf.js';
+import { sha256 } from '@noble/hashes/sha2.js';
+import { bytesToHex, hexToBytes, utf8ToBytes } from '@noble/hashes/utils.js';
+
+export type ProtectedBackupPath = '/backup/v3/enroll' | '/backup/v3/snapshot' | '/backup/v3/mutate';
+export type PublicBackupJwk = Readonly<{
+ kty: 'EC';
+ crv: 'secp256k1';
+ x: string;
+ y: string;
+}>;
+export type BackupAuthority = Readonly<{
+ namespaceId: string;
+ publicJwk: PublicBackupJwk;
+ kid: string;
+ signRawBody: (
+ rawBytes: Uint8Array,
+ path: ProtectedBackupPath,
+ audience: string,
+ nowSeconds?: number
+ ) => string;
+ dispose: () => void;
+}>;
+export type ExpectedBackupAccount = Readonly<{ id: string; primarySeed: string }>;
+
+const PATHS = new Set(['/backup/v3/enroll', '/backup/v3/snapshot', '/backup/v3/mutate']);
+const OPERATIONS = new Set([
+ 'updateAppImage',
+ 'migrateXfps',
+ 'deleteAppImageEntity',
+ 'deleteVaults',
+ 'updateVaultImage',
+ 'modifyLabels',
+ 'deleteBackup',
+ 'repairAppBackup',
+]);
+const MAX_BODY_BYTES = 32 * 1024 * 1024;
+const unavailable = (): never => {
+ throw new Error('PROTECTED_BACKUP_AUTHORITY_UNAVAILABLE');
+};
+const unsigned = (value: unknown): value is number =>
+ typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && !Object.is(value, -0);
+const object = (value: unknown): value is Record =>
+ value !== null && typeof value === 'object' && !Array.isArray(value);
+const exactKeys = (value: unknown, keys: string[]) => {
+ if (
+ !object(value) ||
+ Object.keys(value).length !== keys.length ||
+ keys.some((key) => !Object.prototype.hasOwnProperty.call(value, key))
+ )
+ unavailable();
+};
+const base64url = (bytes: Uint8Array): string =>
+ Buffer.from(bytes).toString('base64').replace(/[=]/g, '').replace(/\+/g, '-').replace(/\//g, '_');
+
+// Prevent signing a different namespace/key or operation envelope by mistake.
+// Transport constructs this JSON; Relay independently applies its strict parser.
+function assertBodyTarget(
+ raw: Uint8Array,
+ path: ProtectedBackupPath,
+ namespaceId: string,
+ jwk: PublicBackupJwk
+) {
+ const text = Buffer.from(raw).toString('utf8');
+ if (!Buffer.from(text, 'utf8').equals(Buffer.from(raw))) unavailable();
+ const body = JSON.parse(text);
+ exactKeys(
+ body,
+ path === '/backup/v3/mutate'
+ ? [
+ 'namespaceId',
+ 'publicJwk',
+ 'operation',
+ 'expectedRevision',
+ 'expectedGeneration',
+ 'authEpoch',
+ 'data',
+ ]
+ : ['namespaceId', 'publicJwk']
+ );
+ exactKeys(body.publicJwk, ['kty', 'crv', 'x', 'y']);
+ if (
+ body.namespaceId !== namespaceId ||
+ Object.keys(jwk).some((key) => body.publicJwk[key] !== jwk[key])
+ )
+ unavailable();
+ if (
+ path === '/backup/v3/mutate' &&
+ (!OPERATIONS.has(body.operation) ||
+ typeof body.expectedRevision !== 'string' ||
+ !/^[a-f0-9]{64}$/.test(body.expectedRevision) ||
+ !unsigned(body.expectedGeneration) ||
+ !unsigned(body.authEpoch) ||
+ !object(body.data))
+ )
+ unavailable();
+}
+
+/** Derive only from the original Keeper account Recovery Key, without a passphrase. */
+export function deriveBackupAuthority(
+ primaryMnemonic: string,
+ expectedAccount?: ExpectedBackupAccount
+): BackupAuthority {
+ let seed: Uint8Array | undefined;
+ let signingSeed: Uint8Array | undefined;
+ let master: HDKey | undefined;
+ let child: HDKey | undefined;
+ let delivered = false;
+ try {
+ if (
+ typeof primaryMnemonic !== 'string' ||
+ primaryMnemonic.length > 1024 ||
+ !validateMnemonic(primaryMnemonic, wordlist)
+ )
+ unavailable();
+ seed = mnemonicToSeedSync(primaryMnemonic, '');
+ if (expectedAccount !== undefined) {
+ if (
+ !object(expectedAccount) ||
+ typeof expectedAccount.id !== 'string' ||
+ !/^[a-f0-9]{64}$/.test(expectedAccount.id) ||
+ typeof expectedAccount.primarySeed !== 'string' ||
+ // Existing image encryption hashes the stored hex text. Clean restore
+ // derives lowercase hex, so accepting uppercase here could authorize
+ // ciphertext that its recovery mnemonic cannot decrypt.
+ !/^[a-f0-9]{128}$/.test(expectedAccount.primarySeed)
+ )
+ unavailable();
+ const expectedSeed = hexToBytes(expectedAccount.primarySeed);
+ try {
+ if (!equalBytes(seed, expectedSeed) || bytesToHex(sha256(seed)) !== expectedAccount.id)
+ unavailable();
+ } finally {
+ expectedSeed.fill(0);
+ }
+ }
+ signingSeed = hkdf(
+ sha256,
+ seed,
+ utf8ToBytes('BitcoinKeeper/BackupAuthority/v1'),
+ utf8ToBytes('secp256k1-signing-seed'),
+ 32
+ );
+ // Invalid masters throw. The pinned BIP32 implementation handles hardened
+ // invalid-child skipping/overflow; no alternate seed or profile is chosen.
+ master = HDKey.fromMasterSeed(signingSeed);
+ child = master.deriveChild(HARDENED_OFFSET);
+ const compressed = child.publicKey;
+ if (!compressed) unavailable();
+ const point = secp256k1.Point.fromBytes(compressed).toBytes(false);
+ const publicJwk: PublicBackupJwk = Object.freeze({
+ kty: 'EC',
+ crv: 'secp256k1',
+ x: base64url(point.slice(1, 33)),
+ y: base64url(point.slice(33, 65)),
+ });
+ const canonical = JSON.stringify({
+ crv: publicJwk.crv,
+ kty: publicJwk.kty,
+ x: publicJwk.x,
+ y: publicJwk.y,
+ });
+ const kid = base64url(sha256(utf8ToBytes(canonical)));
+ const namespaceId = `bk3_${kid}`;
+ const authority: BackupAuthority = Object.freeze({
+ namespaceId,
+ publicJwk,
+ kid,
+ signRawBody(rawBytes, path, audience, nowSeconds = Math.floor(Date.now() / 1000)) {
+ try {
+ if (
+ !child ||
+ !(rawBytes instanceof Uint8Array) ||
+ rawBytes.length > MAX_BODY_BYTES ||
+ !PATHS.has(path) ||
+ typeof audience !== 'string' ||
+ !audience.length ||
+ audience.length > 256 ||
+ utf8ToBytes(audience).length > 256 ||
+ Array.from(audience).some(
+ (character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127
+ ) ||
+ !unsigned(nowSeconds) ||
+ nowSeconds > Number.MAX_SAFE_INTEGER - 120
+ )
+ unavailable();
+ const raw = Uint8Array.from(rawBytes);
+ assertBodyTarget(raw, path, namespaceId, publicJwk);
+ const header = { alg: 'ES256K', kid, typ: 'keeper-backup+jws' };
+ const claims = {
+ v: 3,
+ aud: audience,
+ method: 'POST',
+ path,
+ namespaceId,
+ bodySha256: bytesToHex(sha256(raw)),
+ iat: nowSeconds,
+ exp: nowSeconds + 120,
+ };
+ const input = `${base64url(utf8ToBytes(JSON.stringify(header)))}.${base64url(
+ utf8ToBytes(JSON.stringify(claims))
+ )}`;
+ // Pinned2.4.0 HDKey.sign accepts a SHA256 digest with prehash:false
+ // and returns deterministic, compact low-S ECDSA; hash exactly once.
+ const signature = child.sign(sha256(utf8ToBytes(input)));
+ if (signature.length !== 64) unavailable();
+ return `${input}.${base64url(signature)}`;
+ } catch {
+ return unavailable();
+ }
+ },
+ dispose() {
+ try {
+ child?.wipePrivateData();
+ } finally {
+ child = undefined;
+ }
+ },
+ });
+ delivered = true;
+ return authority;
+ } catch {
+ return unavailable();
+ } finally {
+ // Best effort only: JavaScript/library temporaries cannot promise erasure.
+ seed?.fill(0);
+ signingSeed?.fill(0);
+ master?.wipePrivateData();
+ if (!delivered) child?.wipePrivateData();
+ }
+}
diff --git a/src/services/backup/automatic.ts b/src/services/backup/automatic.ts
new file mode 100644
index 0000000000..3cad428318
--- /dev/null
+++ b/src/services/backup/automatic.ts
@@ -0,0 +1,761 @@
+/* eslint-disable no-await-in-loop -- CAS fanout must use each acknowledged revision in order. */
+import realmDatabase from 'src/storage/realm/realm';
+import config from 'src/utils/service-utilities/config';
+import { RealmSchema } from 'src/storage/realm/enum';
+import { generateEncryptionKey, hash256 } from 'src/utils/service-utilities/encryption';
+import { getKeyUID } from 'src/utils/utilities';
+import type { BackupWriteIntent } from './intent';
+import { readProtectedBackup, protectedBackupMutation, protectedBackupBase,
+ sameProtectedBackupBase, assertProtectedBackupWriteReady } from './protected';
+import {
+ BackupImage,
+ canonical,
+ recoveryContent,
+ decodeImage,
+ decryptRecord,
+ compareImages,
+ validateProtectedRecoveryMetadata,
+} from './image';
+import { captureLocalRecovery, backupMetadataMatches } from './localSnapshot';
+import {
+ BACKUP_DEADLINE_MS,
+ backupBaselineEpoch,
+ backupConsentEpoch,
+ canAccessBackupAccount,
+ clearVerifiedRemoteRevision,
+ currentBackupAccountSession,
+ markBackupQueuedMutation,
+ notifyBackupReconciliation,
+ recordVerifiedRemoteRevision,
+ setAutomaticBackupPostHandler,
+ setBackupLocalEvidenceProvider,
+ captureBackupWriteIntent,
+ isCapturedBackupWriteIntent,
+ withBackupSession,
+ clearBackupDiagnostic,
+ recordBackupDiagnostic,
+ BackupDiagnosticStage,
+ backupNotEnrolledError,
+} from './transport';
+
+export type AutomaticBackupMutation = {
+ operation:
+ | 'updateAppImage'
+ | 'migrateXfps'
+ | 'deleteAppImageEntity'
+ | 'deleteVaults'
+ | 'updateVaultImage'
+ | 'modifyLabels'
+ | 'deleteBackup';
+ body: any;
+};
+type Capture = ReturnType;
+export type BackupLocalOperation = Readonly<{
+ appId: string;
+ accountSession: number;
+ consentEpoch: number;
+ database: any;
+ generation: number;
+ before: Capture;
+ origin?: BackupWriteIntent;
+ fresh: boolean;
+}>;
+export type BackupLocalCommit = Readonly<{ committed: boolean; intent?: BackupWriteIntent }>;
+type Proof = {
+ operation: BackupLocalOperation;
+ after: Capture;
+ generation: number;
+ deletion?: boolean;
+ deadline?: number;
+};
+const proofs = new WeakMap();
+const operations = new WeakSet();
+const managedCommits = new WeakSet();
+const results = new WeakMap