Skip to content

fix(mobile): recover pairing saves from Android SecureStore failures - #11430

Merged
brennanb2025 merged 5 commits into
mainfrom
brennanb2025/mobile-6600-save-host
Jul 31, 2026
Merged

brennanb2025 merged 5 commits into
mainfrom
brennanb2025/mobile-6600-save-host

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Orca Mobile could complete pairing but then fail to save the host, blocking onboarding:

Pairing succeeded but couldn't save the host:
Call to function 'ExpoSecureStore.setValueWithKeyAsync' has been rejected.
Caused by: Could not encrypt the value for key 'orca.host-token.host-1782629088232' under keychain 'key_v1'.
Caused by: unknown

The address-family theory does not fit #6600: pairing already succeeded, so the failure occurred later while persisting the device token. The bundled [email protected] Android sources show that this exact message reaches the GeneralSecurityException path while encrypting under the shared default Android alias; passing a different keychainService selects a different alias.

This PR centralizes native pairing secrets behind a bounded keychain generation:

  • Generation 0 preserves the existing default service and WHEN_UNLOCKED_THIS_DEVICE_ONLY options, so normal iOS/Android saves and legacy credentials keep their existing path.
  • Only Android SecureStore errors containing Could not encrypt the value for key trigger rotation. iOS and unrelated/transient errors propagate without consuming a generation.
  • Host tokens, relay pairing journals, relay credential bundles, and direct-upgrade journals all use the recovery layer. Relay-enabled onboarding writes through it before opening either connection candidate.
  • Writes and deletes serialize around the shared generation. Unreadable or malformed generation state rejects writes before SecureStore; reads and deletes scan downward from the durable upper bound, while reads fail closed on a stored-but-unreadable newer credential.
  • Deletes attempt every bounded generation and propagate partial failures. A failed fresh-alias write stays durably pending and retries that alias instead of consuming more generations; confirmed rotations and scans remain capped.

Refs #6600.

What the user sees before and after

Before

Pairing succeeds, but Orca then says it could not save the host. The host is unavailable, so onboarding cannot finish.

After

When Android's existing SecureStore alias rejects encryption, Orca retries with a fresh bounded alias and saves the host. Normal Android and iOS pairing behavior remains unchanged.

Screenshots

No visual change.

Testing

  • Full mobile Vitest suite: 352 files / 2623 passed / 2 skipped
  • Mobile TypeScript typecheck
  • Mobile oxlint
  • Mobile oxfmt check
  • iOS release-version tests: 11 runs / 23 assertions
  • Added regression coverage for the normal iOS generation-0 save, Android-only rotation, relay-enabled pairing, durable-pointer failures, stale-credential rejection, pending-alias retries, legacy reads, partial deletes, mutation serialization, and the generation cap
  • Proved non-vacuity independently: disabling the Android recovery predicate made exactly the 3 recovery integration tests RED; reverting the stale-read and pending-generation guards made their focused tests RED. Restoring the source returned all 352 files green
  • Native Android/iOS build and physical-device verification were not available

Mobile Checks is the relevant CI gate for this code. The root PR Checks Vitest shards use the root configuration, which excludes mobile/**.

AI Review Report

A fresh independent two-pass adversarial review re-examined the full pairing, relay, persistence, relaunch, cleanup, and concurrency lifecycles after the four earlier design passes. Its first pass found two material regressions—stale credential fallback and generation-budget exhaustion—and its second returned clean after the fixes.

The review-driven changes ensure relay pairing reaches recovery before connecting, unreliable generation pointers cannot orphan or shadow credentials, current-generation read failures cannot fall back to superseded credentials, failed fresh aliases stay pending without burning generations, partial deletion failures remain durable retry signals, and iOS failures do not rotate.

Security Audit

Native pairing secrets remain in SecureStore with WHEN_UNLOCKED_THIS_DEVICE_ONLY; there is no plaintext AsyncStorage or filesystem fallback. Rotation is restricted to the Android encryption rejection, all generations are bounded, and cleanup attempts every possible service so retired credentials are not silently stranded.

No dependency, native module, manifest, command-execution, path-handling, IPC, or desktop surface changed.

Verified vs. device-assumed

Verified from the reported sequence and bundled source:

  • Pairing completed, excluding the unreachable-address family as the cause of [Bug]: Couldn't save the host when pairing on Orca Mobile #6600.
  • The exact rejection reaches a null-message GeneralSecurityException branch while encrypting under the shared default Android alias.
  • keychainService selects another Android alias.
  • Unit/integration tests exercise host save, relaunch reads, relay onboarding, cleanup, concurrency, and normal generation-0 iOS call options.

Not device-verified:

  • Which AndroidKeyStore operation threw the exception.
  • Whether the affected device's failure is alias-local or device-wide.
  • Whether a fresh alias succeeds on the reported Android 13 device.
  • Physical-device reinstall, relaunch, relay, and iOS Keychain behavior.

If the affected keystore rejects every alias, the fix fails safe and surfaces the error rather than downgrading secret storage.

…unusable

Orca Mobile could reach a state where pairing succeeded but the host could
never be saved, with every attempt failing identically:

  Could not encrypt the value for key 'orca.host-token.host-...'
  under keychain 'key_v1'. Caused by: unknown

expo-secure-store derives ONE Android keystore alias from the keychain
service (`<service>:unauthenticated`) and shares it across every host token,
so a single unusable alias rejects all writes. Its built-in self-heal only
covers KeyPermanentlyInvalidatedException, and a null-message
GeneralSecurityException takes the unrecoverable branch instead — leaving
onboarding permanently blocked, which a reinstall does not clear.

Route host-token persistence through a keychain generation that rotates to a
fresh service (and therefore a fresh alias) only after a write has already
failed. Generation 0 keeps expo's default service so tokens written by
earlier builds stay readable, reads walk back through retired services, and
deletes clear every generation so a rotation cannot strand a live credential.

Refs #6600
@greptile-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR introduces a bounded keychain-generation recovery layer (pairing-keychain.ts) that intercepts Android-only SecureStore encryption failures and retries the write under a fresh keychainService, which selects a distinct Android keystore alias. All pairing secrets (host tokens, relay credentials, pairing journals, direct-upgrade journals) are routed through this layer.

  • New module pairing-keychain.ts manages a durable generation pointer in AsyncStorage and a per-item presence record (Android only). Writes serialize through a mutation queue; reads drain the queue then probe downward from the recorded generation. Generation 0 preserves the existing default service so legacy credentials remain readable without migration.
  • Rotation semantics: only Android Could not encrypt the value for key errors trigger a generation increment; the write commits a pending generation record before the SecureStore write, confirms it after success, and fails closed if confirmation storage fails. A cap of 8 generations bounds recovery cost.
  • Callers (host-store.ts, mobile-relay-credential-bundle.ts, mobile-relay-direct-upgrade-journal.ts, mobile-relay-pairing-journal-store.ts) are each a straightforward substitution of the three SecureStore call sites for the keychain layer equivalents.

Confidence Score: 5/5

Safe to merge. The recovery layer is correctly ordered, fail-closed on stale reads, bounded at 8 generations, and iOS-gated so no rotation fires on non-Android devices.

The write-ordering invariants are all correct and independently tested. The read path correctly fails closed when a presence record exists but the item is absent, preventing silent fallback to superseded credentials. The mutation queue serializes all writes while reads safely drain it. No credential-loss, stale-read, or unbounded-growth paths were found.

Files Needing Attention: No files require special attention. The four caller files are mechanical substitutions; all meaningful logic lives in pairing-keychain.ts, which is thoroughly covered by pairing-keychain.test.ts.

Important Files Changed

Filename Overview
mobile/src/transport/pairing-keychain.ts New core module implementing bounded keychain-generation recovery. Write ordering, presence records, fail-closed reads, mutation serialization, and the generation cap are all correctly implemented and well-commented.
mobile/src/transport/pairing-keychain.test.ts 403-line test file covering all meaningful branches: normal write, alias-local recovery, cap enforcement, pending-alias retry, write-order invariant, stale-read rejection, legacy fallback, partial delete, malformed record handling, and mutation serialization.
mobile/src/transport/host-store.ts Replaces three direct SecureStore call sites with pairing-keychain equivalents; adds resetPairingKeychainForTests() to the test-reset function. Clean mechanical substitution.
mobile/src/transport/mobile-relay-pairing-journal-store.ts Same three-site substitution pattern; adds resetPairingKeychainForTests() to the module-level reset. The existing metadata-first write ordering for crash safety is preserved.
mobile/src/transport/mobile-relay-credential-bundle.ts Three SecureStore call sites replaced with pairing-keychain equivalents; KEYCHAIN_OPTIONS constant removed. No behavioural change on the read/write paths.
mobile/src/transport/mobile-relay-direct-upgrade-journal.ts Same pattern as mobile-relay-credential-bundle.ts. Clean substitution with no logic changes.

Reviews (5): Last reviewed commit: "fix(mobile): fail closed on unreadable p..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Introduces generation-aware pairing keychain persistence with AsyncStorage generation and presence records, SecureStore alias rotation, serialized mutations, recovery, and deletion cleanup. Native host, relay credential, direct-upgrade, and pairing-journal persistence now use shared pairing-keychain helpers, while web storage remains unchanged. Tests cover iOS defaults, Android rotation and failure handling, presence semantics, malformed records, deletion behavior, and relaunch recovery.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the primary fix for recovering pairing saves after Android SecureStore failures.
Description check ✅ Passed The description covers the summary, visual changes, testing, AI review, security audit, and platform risks, with detailed verification and limitations.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 54122ea5-f376-4e89-ad06-273ddcaf3d49

📥 Commits

Reviewing files that changed from the base of the PR and between 24a2acc and f15a1ba.

📒 Files selected for processing (4)
  • mobile/src/transport/host-store.test.ts
  • mobile/src/transport/host-store.ts
  • mobile/src/transport/host-token-keychain.test.ts
  • mobile/src/transport/host-token-keychain.ts

…r it

Greptile flagged that a token could be stored under a generation the
generation record never captured. `commitGeneration` swallowed the
AsyncStorage failure and cached the new generation in memory, so the write
succeeded for the rest of the session — but the next launch re-read the old
record, and because reads only walk back from the recorded generation they
never probed the newer service. The host silently vanished and the user had
to re-pair, which is the same class of loss this change set out to fix.

Record the rotation first and let a storage failure propagate, so a token is
never written under a generation reads won't reach. Advancing the record
before the write is safe because reads walk back through every older service;
the worst case is one spent generation and one extra probe per miss.
@brennanb2025 brennanb2025 changed the title fix(mobile): recover pairing save when the Android keystore alias is unusable fix(mobile): recover pairing saves from Android SecureStore failures Jul 30, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
mobile/src/transport/pairing-keychain.ts (1)

106-142: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Minor: untested case where a retried write on an already-pending generation succeeds but the confirm write fails again.

When loaded.pending is true and SecureStore.setItemAsync succeeds but the follow-up commitGeneration(generation, false) throws, the surrounding catch sets firstError to that confirm failure, and since loaded.pending is true the function immediately re-throws it (Line 124-126) — even though the secret was durably written under the already-recorded pending alias and is reachable on the next read. Callers will see a spurious failure on an otherwise-successful write. Data isn't lost (safe fallback), but this isn't covered by a test the way the initial-rotation confirm failure is (Lines 183-208).


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1af76043-8ad7-4134-b5cf-5d6f807e2156

📥 Commits

Reviewing files that changed from the base of the PR and between ca859bd and 8d92641.

📒 Files selected for processing (9)
  • mobile/src/transport/host-store.test.ts
  • mobile/src/transport/host-store.ts
  • mobile/src/transport/mobile-relay-credential-bundle.test.ts
  • mobile/src/transport/mobile-relay-credential-bundle.ts
  • mobile/src/transport/mobile-relay-direct-upgrade-journal.ts
  • mobile/src/transport/mobile-relay-pairing-journal-store.test.ts
  • mobile/src/transport/mobile-relay-pairing-journal-store.ts
  • mobile/src/transport/pairing-keychain.test.ts
  • mobile/src/transport/pairing-keychain.ts

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Verified against the bundled expo-secure-store 55.0.13 Android source: the report is correct. Absent SharedPreferences entries return null, and stored entries also return null for a missing keystore entry, KeyPermanentlyInvalidatedException, and BadPaddingException.

Pushed 8708e63: Android now durably records each item generation before its SecureStore write, restores the prior marker on ordinary write failure, and treats null at a recorded generation as a hard failure instead of scanning into a superseded credential. Unmarked legacy items retain the bounded fallback scan; iOS still bypasses the marker and uses the default generation-0 service.

Regression proof: restoring only pairing-keychain.ts to the previous production source made the new test fail (the presence marker stayed null and the stale-token path remained reachable). Mobile-owned Vitest baseline was 352 files / 2,623 passed / 2 skipped; final is 352 files / 2,624 passed / 2 skipped. Mobile typecheck, lint, and changed-file format checks also pass; no simulator/emulator was used.

@brennanb2025 brennanb2025 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current-head queue review at 8708e6372f: no findings. Fresh verification: 69 affected mobile tests, mobile typecheck, root oxlint, affected-file formatting, and git merge-tree --write-tree against current main all pass. Reverting only pairing-keychain.ts to the prior reviewed commit makes the new fail-closed regressions fail, confirming non-vacuity. The remaining review thread was invalid for the pinned dependency: [email protected] emits the exact Could not encrypt the value for key prefix matched by the guard, and the thread is now resolved. Device QA reproduces the save failure at the parent and confirms rotation, persisted generation, and relaunch at this head, with the native hardware-keystore caveat documented. No merge performed.

@brennanb2025
brennanb2025 merged commit 7db0101 into main Jul 31, 2026
42 checks passed
nwparker added a commit that referenced this pull request Jul 31, 2026
…s null

Clearing the presence record on the self-heal removed the only thing that
stops readPairingKeychainItem's generation walk, so the next read fell back to
the superseded value under an older generation -- exactly what #11430's
presence record exists to prevent, and reachable for host device tokens and
relay resume bundles after an Android encrypt rotation. Return null and leave
the record in place; the null return alone unlatches every caller's orphan
cleanup, and delete/re-pair already clear or re-stamp the record.

Co-authored-by: Orca <[email protected]>
nwparker added a commit that referenced this pull request Jul 31, 2026
…shake (#11690)

* fix(mobile): restore pairing self-heal and recover a wedged handshake

readPairingKeychainItem threw when an Android presence record pointed at a
SecureStore entry that read back null. Android reports absent and undecryptable
identically, so the keystore fault the presence record was added to survive
latched every caller out of its own orphan cleanup: the pairing journal store
never reached its null-secret branch, stale winner-stamped metadata survived,
and every later QR scan failed with "mobile relay pairing recovery pending".
Report absent instead and drop the stale presence claim, still without falling
back to the superseded older generation.

The handshake-timeout path closed the socket with no handleSocketClosed
fallback, unlike the connect-timeout and activity-probe paths. When React
Native omits onclose for a wedged transport the client stayed in 'handshaking'
forever with no reconnect armed.

* fix(mobile): keep the presence pin when a recorded keychain item reads null

Clearing the presence record on the self-heal removed the only thing that
stops readPairingKeychainItem's generation walk, so the next read fell back to
the superseded value under an older generation -- exactly what #11430's
presence record exists to prevent, and reachable for host device tokens and
relay resume bundles after an Android encrypt rotation. Return null and leave
the record in place; the null return alone unlatches every caller's orphan
cleanup, and delete/re-pair already clear or re-stamp the record.

Co-authored-by: Orca <[email protected]>

* fix(mobile): date synthesized socket closes in transport diagnostics

Move the log-only close clocks behind handleSocketClosed's stale guard so a
synthesized close records them and a late onclose can't clobber the replacement.

Co-authored-by: Orca <[email protected]>

* fix(mobile): account for delayed synthesized closes

---------

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#11430)

* fix(mobile): recover pairing save when the Android keystore alias is unusable

Orca Mobile could reach a state where pairing succeeded but the host could
never be saved, with every attempt failing identically:

  Could not encrypt the value for key 'orca.host-token.host-...'
  under keychain 'key_v1'. Caused by: unknown

expo-secure-store derives ONE Android keystore alias from the keychain
service (`<service>:unauthenticated`) and shares it across every host token,
so a single unusable alias rejects all writes. Its built-in self-heal only
covers KeyPermanentlyInvalidatedException, and a null-message
GeneralSecurityException takes the unrecoverable branch instead — leaving
onboarding permanently blocked, which a reinstall does not clear.

Route host-token persistence through a keychain generation that rotates to a
fresh service (and therefore a fresh alias) only after a write has already
failed. Generation 0 keeps expo's default service so tokens written by
earlier builds stay readable, reads walk back through retired services, and
deletes clear every generation so a rotation cannot strand a live credential.

Refs stablyai#6600

* fix(mobile): record a keychain rotation before storing the token under it

Greptile flagged that a token could be stored under a generation the
generation record never captured. `commitGeneration` swallowed the
AsyncStorage failure and cached the new generation in memory, so the write
succeeded for the rest of the session — but the next launch re-read the old
record, and because reads only walk back from the recorded generation they
never probed the newer service. The host silently vanished and the user had
to re-pair, which is the same class of loss this change set out to fix.

Record the rotation first and let a storage failure propagate, so a token is
never written under a generation reads won't reach. Advancing the record
before the write is safe because reads walk back through every older service;
the worst case is one spent generation and one extra probe per miss.

* fix(mobile): harden pairing keychain recovery

* fix(mobile): harden pairing keychain recovery state

* fix(mobile): fail closed on unreadable pairing credentials
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…shake (stablyai#11690)

* fix(mobile): restore pairing self-heal and recover a wedged handshake

readPairingKeychainItem threw when an Android presence record pointed at a
SecureStore entry that read back null. Android reports absent and undecryptable
identically, so the keystore fault the presence record was added to survive
latched every caller out of its own orphan cleanup: the pairing journal store
never reached its null-secret branch, stale winner-stamped metadata survived,
and every later QR scan failed with "mobile relay pairing recovery pending".
Report absent instead and drop the stale presence claim, still without falling
back to the superseded older generation.

The handshake-timeout path closed the socket with no handleSocketClosed
fallback, unlike the connect-timeout and activity-probe paths. When React
Native omits onclose for a wedged transport the client stayed in 'handshaking'
forever with no reconnect armed.

* fix(mobile): keep the presence pin when a recorded keychain item reads null

Clearing the presence record on the self-heal removed the only thing that
stops readPairingKeychainItem's generation walk, so the next read fell back to
the superseded value under an older generation -- exactly what stablyai#11430's
presence record exists to prevent, and reachable for host device tokens and
relay resume bundles after an Android encrypt rotation. Return null and leave
the record in place; the null return alone unlatches every caller's orphan
cleanup, and delete/re-pair already clear or re-stamp the record.

Co-authored-by: Orca <[email protected]>

* fix(mobile): date synthesized socket closes in transport diagnostics

Move the log-only close clocks behind handleSocketClosed's stale guard so a
synthesized close records them and a late onclose can't clobber the replacement.

Co-authored-by: Orca <[email protected]>

* fix(mobile): account for delayed synthesized closes

---------

Co-authored-by: Orca <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant