From a806da91dcc3d18e8f3a1bb94a4bb2f246dd0107 Mon Sep 17 00:00:00 2001 From: Antuz tap Date: Thu, 22 Oct 2026 22:50:30 +0000 Subject: [PATCH 1/3] Add bounded development observations at startup failure boundaries --- .github/native/ios_startup_errors.py | 18 ++- .github/tests/test_ios_startup_errors.py | 41 +++++++ docs/r5/STARTUP-FAILURE-BOUNDARIES.md | 46 ++++++++ src/screens/Splash/SplashScreen.tsx | 24 +++- src/storage/secure-store.ts | 22 +++- src/storage/startup-credential-diagnostics.ts | 81 ++++++++++++++ tests/screens/SplashScreen.test.tsx | 83 +++++++++++++- .../startupCredentialDiagnostics.test.ts | 105 ++++++++++++++++++ tests/services/startupCredentials.test.ts | 62 ++++++++++- 9 files changed, 476 insertions(+), 6 deletions(-) create mode 100644 docs/r5/STARTUP-FAILURE-BOUNDARIES.md create mode 100644 src/storage/startup-credential-diagnostics.ts create mode 100644 tests/services/startupCredentialDiagnostics.test.ts diff --git a/.github/native/ios_startup_errors.py b/.github/native/ios_startup_errors.py index dda8d0176..5d4e9decf 100644 --- a/.github/native/ios_startup_errors.py +++ b/.github/native/ios_startup_errors.py @@ -48,6 +48,14 @@ _ERROR_SEVERITIES = {'e', 'er', 'error', 'f', 'ft', 'fault'} _ERROR_MARKER = re.compile( r'\b(?:error|exception|fatal)\b|\b[\w.$]*(?:Exception|Error)\b', re.IGNORECASE) +STARTUP_STAGES = ('READ_CALL', 'STATE_READ', 'SERVICE_SELECT', 'KEYCHAIN_READ', + 'CREDENTIAL_PARSE', 'NAVIGATE_LOGIN', 'NAVIGATE_CREATE_PIN') +STARTUP_CATEGORIES = ('NATIVE_CODE_NEG34018', 'NATIVE_CODE_NEG25308', 'NATIVE_CODE_NEG25291', + 'NATIVE_CODE_NEG25293', 'NATIVE_CODE_NEG26275', 'NATIVE_CODE_NEG50', + 'ERROR', 'TYPE_ERROR', 'SYNTAX_ERROR', 'RANGE_ERROR', 'REFERENCE_ERROR', 'UNKNOWN') +_STARTUP_MARKER = re.compile( + r'KEEPER_STARTUP_ERROR stage=(' + '|'.join(STARTUP_STAGES) + + r') category=(' + '|'.join(STARTUP_CATEGORIES) + r')') def classify(payload, executable): @@ -79,6 +87,8 @@ def classify(payload, executable): 'scan_limit_reached': False, 'record_limit_reached': False, 'parse_status': 'UNKNOWN', 'cause': 'UNDETERMINED', 'scope': 'PREFIXED_OWN_PROCESS_MARKERS_ONLY_NOT_CAUSE_OR_ACCEPTANCE', + 'startup_failure_facts': [], 'startup_failure_fact_limit_reached': False, + 'startup_failure_scope': 'FIXED_DEVELOPMENT_STAGE_MARKERS_NOT_AUTHENTICATED_CAUSE', } for index, raw in enumerate(io.StringIO(prefix)): if index >= MAX_SCAN_LINES: @@ -110,9 +120,15 @@ def classify(payload, executable): if match['process'] != executable: continue result['matching_process_records'] += 1 + marker = _STARTUP_MARKER.fullmatch(match['message']) + if marker: + if len(result['startup_failure_facts']) < 32: + result['startup_failure_facts'].append({'stage': marker[1], 'category': marker[2]}) + else: + result['startup_failure_fact_limit_reached'] = True categories = [name for name, pattern in _CATEGORY_PATTERNS.items() if pattern.search(match['message'])] - error = (bool(categories) or match['severity'].lower() in _ERROR_SEVERITIES or + error = (bool(marker) or bool(categories) or match['severity'].lower() in _ERROR_SEVERITIES or bool(_ERROR_MARKER.search(match['message']))) if error: result['error_records'] += 1 diff --git a/.github/tests/test_ios_startup_errors.py b/.github/tests/test_ios_startup_errors.py index 7b0d56398..5ad6564dc 100644 --- a/.github/tests/test_ios_startup_errors.py +++ b/.github/tests/test_ios_startup_errors.py @@ -2,6 +2,7 @@ import importlib.util import json +import re from pathlib import Path import unittest from unittest import mock @@ -19,6 +20,46 @@ def record(message, process=APP, severity='Df', timestamp='2026-10-22 09:22:33.1 class IOSStartupErrorsTest(unittest.TestCase): + def test_precise_development_marker_uses_only_the_shared_fixed_vocabulary(self): + source = (Path(__file__).resolve().parents[2] / + 'src/storage/startup-credential-diagnostics.ts').read_text() + stages = re.search(r'STARTUP_FAILURE_STAGES = \[(.*?)\] as const', source, re.S)[1] + self.assertEqual(tuple(re.findall(r"'([^']+)'", stages)), ios.STARTUP_STAGES) + categories = [] + for name in ('NATIVE_CODES', 'ERROR_NAMES'): + block = re.search(r'const ' + name + r' = \{(.*?)\} as const', source, re.S)[1] + categories.extend(re.findall(r":\s*'([^']+)'", block)) + self.assertEqual(tuple(categories + ['UNKNOWN']), ios.STARTUP_CATEGORIES) + for stage in ios.STARTUP_STAGES: + for category in ios.STARTUP_CATEGORIES: + self.assertIn("'" + category + "'", source) + marker = f'KEEPER_STARTUP_ERROR stage={stage} category={category}' + result = ios.classify(record(marker, severity='I'), APP) + self.assertEqual(result['startup_failure_facts'], [{'stage': stage, 'category': category}]) + self.assertEqual(result['error_records'], 1) + self.assertEqual(result['cause'], 'UNDETERMINED') + + def test_foreign_malformed_and_private_marker_variants_supply_no_fixed_facts(self): + marker = 'KEEPER_STARTUP_ERROR stage=KEYCHAIN_READ category=NATIVE_CODE_NEG34018' + for payload in [record(marker, process='OtherApp'), marker, + record('prefix ' + marker), record(marker + ' PRIVATE_SENTINEL'), + record(marker.replace('KEYCHAIN_READ', 'PRIVATE_SENTINEL')), + record(marker.replace('NATIVE_CODE_NEG34018', 'PRIVATE_SENTINEL')), + record(marker.replace('KEEPER_STARTUP_ERROR', 'keeper_startup_error'))]: + with self.subTest(payload=payload[:15]): + result = ios.classify(payload, APP) + self.assertEqual(result['startup_failure_facts'], []) + self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result)) + + def test_marker_observations_remain_bounded_and_never_establish_native_cause(self): + marker = 'KEEPER_STARTUP_ERROR stage=READ_CALL category=UNKNOWN' + result = ios.classify('\n'.join([record(marker)] * 40), APP) + self.assertEqual(len(result['startup_failure_facts']), 32) + self.assertTrue(result['startup_failure_fact_limit_reached']) + self.assertEqual(result['error_records'], 40) + self.assertEqual(result['cause'], 'UNDETERMINED') + self.assertNotIn('PASS', json.dumps(result)) + def test_exact_process_prefix_preserves_existing_generic_error_contract(self): payload = '\n'.join([ 'Filtering the log data using the process predicate', diff --git a/docs/r5/STARTUP-FAILURE-BOUNDARIES.md b/docs/r5/STARTUP-FAILURE-BOUNDARIES.md new file mode 100644 index 000000000..414555a8a --- /dev/null +++ b/docs/r5/STARTUP-FAILURE-BOUNDARIES.md @@ -0,0 +1,46 @@ +# Fixed startup failure observations + +The exact `1bc34890cb8618b2fffd446a63924974e0fe15b5` iOS diagnostic +window built and installed successfully, then failed its first Create a passcode +assertion. [The pinned artifact readout](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7123) +found the fixed passcode-check error and Retry in one retained hierarchy snapshot. +The snapshot does not establish the current route, tap delivery or failure cause. +Its 616 own-process error records include 18 CONNECTION markers and 598 +unclassified records. Those categories remain separate from this new observer. + +The Splash catch covers both `hasPin` and the subsequent navigation call. +`hasPin` itself covers Redux state, account-service selection, native Keychain +reading and credential JSON parsing. An ordinary empty fresh Keychain resolves +false and selects CreatePin. The retained error UI cannot distinguish those +boundaries. No specific Keychain, entitlement, SDK or navigation defect is proven. + +The optional `hasPin` observer receives only a fixed stage and category. It never +receives an Error, credential, account/service identifier or native response. +Original rejection and legacy false-on-error behavior remain intact, including +when the observer throws. Splash keeps its existing generic modal, Retry and +navigation behavior. Abandoned attempts emit nothing. + +In development only, a current failed attempt emits one `console.info` line: + +```text +KEEPER_STARTUP_ERROR stage=KEYCHAIN_READ category=NATIVE_CODE_NEG34018 +``` + +This is an illustrative fixed marker, not an observed native status. Categories +contain only whitelisted native code labels or built-in error-name labels. +Code and name accessors are guarded; unknown values stay UNKNOWN. There is no +warning/error LogBox call, raw message, stack, arbitrary code, production log, +new credential operation, fallback, SDK option, native query or deadline change. + +The existing bounded iOS compact-log parser accepts only a complete exact marker +in a valid own-process record. It regenerates at most 32 fixed facts and exposes +the cap. Rendered logs are not authenticated causal evidence. An absent marker +cannot establish that a boundary succeeded: actual native log routing and marker +visibility are unverified until a new exact-candidate hosted window runs. + +Source checks cover the read boundaries, native-code and hostile-accessor privacy, +observer/logger faults, production silence, navigation exceptions, Retry and late +unmount behavior, plus foreign/malformed/capped log records. These are source +controls, not native acceptance or a correction of the observed startup failure. +The immutable `1bc` window and its Android continuation remain unchanged. No +personal Mac, native queue, release signing, upload or distribution is involved. diff --git a/src/screens/Splash/SplashScreen.tsx b/src/screens/Splash/SplashScreen.tsx index eb64ef6bd..692044af1 100644 --- a/src/screens/Splash/SplashScreen.tsx +++ b/src/screens/Splash/SplashScreen.tsx @@ -4,6 +4,12 @@ import { useColorMode } from '@gluestack-ui/themed-native-base'; import RestClient from 'src/services/rest/RestClient'; import { useAppSelector } from 'src/store/hooks'; import * as SecureStore from 'src/storage/secure-store'; +import { + reportStartupFailure, + startupFailureFact, + StartupFailureFact, + StartupFailureStage, +} from 'src/storage/startup-credential-diagnostics'; import Animated, { interpolate, cancelAnimation, @@ -67,16 +73,30 @@ function SplashScreen({ navigation }) { let current = true; readPending.current = true; const navigateToApp = async () => { + let failure: StartupFailureFact | undefined; + let stage: StartupFailureStage = 'READ_CALL'; try { - const hasCreds = await SecureStore.hasPin({ throwOnError: true }); + const hasCreds = await SecureStore.hasPin({ + throwOnError: true, + ...(__DEV__ + ? { + onReadFailure: (fact: StartupFailureFact) => { + failure = fact; + }, + } + : {}), + }); if (!current) return; if (hasCreds) { + stage = 'NAVIGATE_LOGIN'; navigation.replace('Login', { relogin: false }); } else { + stage = 'NAVIGATE_CREATE_PIN'; navigation.replace('CreatePin'); } - } catch { + } catch (error) { if (current) { + if (__DEV__) reportStartupFailure(failure ?? startupFailureFact(stage, error)); readPending.current = false; setStartupError(true); } diff --git a/src/storage/secure-store.ts b/src/storage/secure-store.ts index 88abadce2..6e7607f26 100644 --- a/src/storage/secure-store.ts +++ b/src/storage/secure-store.ts @@ -2,6 +2,11 @@ import * as Keychain from 'react-native-keychain'; import NodeRSA from 'node-rsa'; import config from '../utils/service-utilities/config'; import { store as reduxStore } from 'src/store/store'; +import { + startupFailureFact, + StartupFailureFact, + StartupFailureStage, +} from './startup-credential-diagnostics'; export const store = async (hash: string, enc_key: string, identifier: string) => { try { @@ -67,7 +72,14 @@ export const fetch = async (hash_current: string) => { // Startup must distinguish an unreadable Keychain from a successfully empty // one. Preserve legacy behavior unless the caller explicitly requests errors. -export const hasPin = async ({ throwOnError = false }: { throwOnError?: boolean } = {}) => { +export const hasPin = async ({ + throwOnError = false, + onReadFailure, +}: { + throwOnError?: boolean; + onReadFailure?: (fact: StartupFailureFact) => void; +} = {}) => { + let stage: StartupFailureStage = 'STATE_READ'; try { let allAccounts = reduxStore.getState().account.allAccounts; // if allAccounts is empty | upgraded app with old passcode configuration @@ -75,14 +87,17 @@ export const hasPin = async ({ throwOnError = false }: { throwOnError?: boolean allAccounts = [{ accountIdentifier: undefined }]; } for (const index in allAccounts) { + stage = 'SERVICE_SELECT'; const identifier = allAccounts[index].accountIdentifier == '' ? undefined : allAccounts[index].accountIdentifier; + stage = 'KEYCHAIN_READ'; const credentials = await Keychain.getGenericPassword({ service: identifier, }); if (credentials) { + stage = 'CREDENTIAL_PARSE'; const password = JSON.parse(credentials.password); if (password) { return true; @@ -91,6 +106,11 @@ export const hasPin = async ({ throwOnError = false }: { throwOnError?: boolean } return false; } catch (err) { + try { + onReadFailure?.(startupFailureFact(stage, err)); + } catch { + // An observer cannot replace the original rejection or legacy false. + } if (throwOnError) throw err; return false; } diff --git a/src/storage/startup-credential-diagnostics.ts b/src/storage/startup-credential-diagnostics.ts new file mode 100644 index 000000000..eae2e746a --- /dev/null +++ b/src/storage/startup-credential-diagnostics.ts @@ -0,0 +1,81 @@ +// Fixed development observations only. Never retain or forward an Error object. +export const STARTUP_FAILURE_STAGES = [ + 'READ_CALL', + 'STATE_READ', + 'SERVICE_SELECT', + 'KEYCHAIN_READ', + 'CREDENTIAL_PARSE', + 'NAVIGATE_LOGIN', + 'NAVIGATE_CREATE_PIN', +] as const; +export type StartupFailureStage = (typeof STARTUP_FAILURE_STAGES)[number]; + +const NATIVE_CODES = { + '-34018': 'NATIVE_CODE_NEG34018', + '-25308': 'NATIVE_CODE_NEG25308', + '-25291': 'NATIVE_CODE_NEG25291', + '-25293': 'NATIVE_CODE_NEG25293', + '-26275': 'NATIVE_CODE_NEG26275', + '-50': 'NATIVE_CODE_NEG50', +} as const; +const ERROR_NAMES = { + Error: 'ERROR', + TypeError: 'TYPE_ERROR', + SyntaxError: 'SYNTAX_ERROR', + RangeError: 'RANGE_ERROR', + ReferenceError: 'REFERENCE_ERROR', +} as const; +export const STARTUP_FAILURE_CATEGORIES = [ + ...Object.values(NATIVE_CODES), + ...Object.values(ERROR_NAMES), + 'UNKNOWN', +] as const; +export type StartupFailureCategory = (typeof STARTUP_FAILURE_CATEGORIES)[number]; +export type StartupFailureFact = Readonly<{ + stage: StartupFailureStage; + category: StartupFailureCategory; +}>; + +export const startupFailureFact = ( + stage: StartupFailureStage, + error: unknown +): StartupFailureFact => { + let category: StartupFailureCategory = 'UNKNOWN'; + // Accessors may themselves throw. No dynamic value is returned or logged. + try { + if (error && (typeof error === 'object' || typeof error === 'function')) { + const { code } = error as { code?: unknown }; + if ( + stage === 'KEYCHAIN_READ' && + (typeof code === 'string' || typeof code === 'number') && + Object.prototype.hasOwnProperty.call(NATIVE_CODES, code) + ) { + category = NATIVE_CODES[String(code) as keyof typeof NATIVE_CODES]; + } else { + const { name } = error as { name?: unknown }; + if (typeof name === 'string' && Object.prototype.hasOwnProperty.call(ERROR_NAMES, name)) { + category = ERROR_NAMES[name as keyof typeof ERROR_NAMES]; + } + } + } + } catch { + // Unknown is more accurate than letting diagnostics replace the failure. + } + return { + stage: STARTUP_FAILURE_STAGES.includes(stage) ? stage : 'READ_CALL', + category, + }; +}; + +export const reportStartupFailure = (fact: StartupFailureFact) => { + if (!__DEV__) return; + try { + const { stage, category } = fact; + if (STARTUP_FAILURE_STAGES.includes(stage) && STARTUP_FAILURE_CATEGORIES.includes(category)) { + // One info line adds no LogBox warning/error and exports no raw details. + console.info(`KEEPER_STARTUP_ERROR stage=${stage} category=${category}`); + } + } catch { + // Logging never changes credential, navigation, Retry or unmount semantics. + } +}; diff --git a/tests/screens/SplashScreen.test.tsx b/tests/screens/SplashScreen.test.tsx index ef7c7d967..311f1ffa0 100644 --- a/tests/screens/SplashScreen.test.tsx +++ b/tests/screens/SplashScreen.test.tsx @@ -9,6 +9,8 @@ const mockEvents: string[] = []; let mockSettings; let mockColorMode = 'light'; let mockDev = false; +let startupInfo; +const previousDev = __DEV__; jest.mock('src/store/hooks', () => ({ useAppSelector: (select) => select({ settings: mockSettings }), @@ -75,6 +77,8 @@ function visibleDialogs() { return screen.root.findAllByType('Modal').filter((modal) => modal.props.visible); } beforeEach(() => { + (global as any).__DEV__ = true; + startupInfo = jest.spyOn(console, 'info').mockImplementation(() => {}); jest.useFakeTimers(); mockSettings = { torEnbled: false, themeMode: 'LIGHT', bitcoinNetworkType: 'MAINNET' }; mockColorMode = 'light'; @@ -93,6 +97,8 @@ afterEach(() => { screen = null; jest.clearAllTimers(); jest.useRealTimers(); + (global as any).__DEV__ = previousDev; + startupInfo.mockRestore(); }); test('starts the credential read without waiting for the splash animation', async () => { @@ -100,7 +106,10 @@ test('starts the credential read without waiting for the splash animation', asyn mockHasPin.mockReturnValue(pin.promise); await mount(); expect(mockHasPin).toHaveBeenCalledTimes(1); - expect(mockHasPin).toHaveBeenCalledWith({ throwOnError: true }); + expect(mockHasPin).toHaveBeenCalledWith({ + throwOnError: true, + onReadFailure: expect.any(Function), + }); expect(navigation.replace).not.toHaveBeenCalled(); await act(async () => pin.resolve(true)); expect(navigation.replace).toHaveBeenCalledWith('Login', { relogin: false }); @@ -200,3 +209,75 @@ test('rerendering preserves the selected network and does not read credentials a expect(mockDispatch).not.toHaveBeenCalled(); expect(mockHasPin).toHaveBeenCalledTimes(1); }); + +test('a precise read observation produces one fixed marker and preserves generic Retry', async () => { + mockHasPin.mockImplementationOnce(async ({ onReadFailure }) => { + onReadFailure({ stage: 'KEYCHAIN_READ', category: 'NATIVE_CODE_NEG34018' }); + throw Error('PRIVATE_SENTINEL'); + }); + await mount(); + expect(startupInfo.mock.calls).toEqual([ + ['KEEPER_STARTUP_ERROR stage=KEYCHAIN_READ category=NATIVE_CODE_NEG34018'], + ]); + expect(visibleDialogs()).toHaveLength(1); + expect(navigation.replace).not.toHaveBeenCalled(); + expect(JSON.stringify(visibleDialogs()[0].props)).not.toContain('PRIVATE_SENTINEL'); +}); + +test.each([true, false])( + 'post-read navigation failure is classified separately (credentials=%s)', + async (hasCreds) => { + const read = deferred(); + mockHasPin.mockReturnValue(read.promise); + await mount(); + navigation.replace.mockImplementation(() => { + throw new TypeError('PRIVATE_SENTINEL'); + }); + await act(async () => read.resolve(hasCreds)); + expect(startupInfo.mock.calls).toEqual([ + [ + `KEEPER_STARTUP_ERROR stage=${ + hasCreds ? 'NAVIGATE_LOGIN' : 'NAVIGATE_CREATE_PIN' + } category=TYPE_ERROR`, + ], + ]); + expect(visibleDialogs()).toHaveLength(1); + } +); + +test('production supplies no observation callback and never inspects failure properties', async () => { + (global as any).__DEV__ = false; + const code = jest.fn(() => { + throw Error('PRIVATE_SENTINEL'); + }); + const failure = Object.defineProperty({}, 'code', { get: code }); + mockHasPin.mockRejectedValue(failure); + await mount(); + expect(mockHasPin).toHaveBeenCalledWith({ throwOnError: true }); + expect(code).not.toHaveBeenCalled(); + expect(startupInfo).not.toHaveBeenCalled(); + expect(visibleDialogs()).toHaveLength(1); +}); + +test('logger failure preserves the generic Retry and the next successful credential read', async () => { + startupInfo.mockImplementation(() => { + throw Error('PRIVATE_SENTINEL'); + }); + mockHasPin.mockRejectedValueOnce(Error('PRIVATE_SENTINEL')).mockResolvedValue(false); + await mount(); + expect(visibleDialogs()).toHaveLength(1); + await act(async () => visibleDialogs()[0].props.buttonCallback()); + expect(navigation.replace).toHaveBeenCalledWith('CreatePin'); + expect(visibleDialogs()).toHaveLength(0); +}); + +test('an abandoned attempt cannot emit a late failure marker', async () => { + const read = deferred(); + mockHasPin.mockReturnValue(read.promise); + await mount(); + act(() => screen.unmount()); + screen = null; + await act(async () => read.reject(Error('PRIVATE_SENTINEL'))); + expect(startupInfo).not.toHaveBeenCalled(); + expect(navigation.replace).not.toHaveBeenCalled(); +}); diff --git a/tests/services/startupCredentialDiagnostics.test.ts b/tests/services/startupCredentialDiagnostics.test.ts new file mode 100644 index 000000000..0b23f40ec --- /dev/null +++ b/tests/services/startupCredentialDiagnostics.test.ts @@ -0,0 +1,105 @@ +import { + reportStartupFailure, + startupFailureFact, +} from '../../src/storage/startup-credential-diagnostics'; + +const previousDev = __DEV__; +afterEach(() => { + (global as any).__DEV__ = previousDev; + jest.restoreAllMocks(); +}); + +test('only known native codes at the Keychain boundary supply a fixed code category', () => { + for (const code of ['-34018', -25308, '-25291', '-25293', '-26275', '-50']) { + expect(startupFailureFact('KEYCHAIN_READ', { code, message: 'PRIVATE_SENTINEL' })).toEqual({ + stage: 'KEYCHAIN_READ', + category: `NATIVE_CODE_NEG${String(code).slice(1)}`, + }); + } + expect(startupFailureFact('CREDENTIAL_PARSE', { code: '-34018', name: 'SyntaxError' })).toEqual({ + stage: 'CREDENTIAL_PARSE', + category: 'SYNTAX_ERROR', + }); +}); + +test('unknown values and hostile error accessors cannot escape or replace the failure', () => { + const values = [ + null, + 'PRIVATE_SENTINEL', + { code: 'PRIVATE_SENTINEL', name: '__proto__' }, + { + get code() { + throw Error('PRIVATE_SENTINEL'); + }, + }, + { + get name() { + throw Error('PRIVATE_SENTINEL'); + }, + }, + { + code: { + toString() { + throw Error('PRIVATE_SENTINEL'); + }, + }, + }, + ]; + for (const value of values) { + expect(startupFailureFact('KEYCHAIN_READ', value)).toEqual({ + stage: 'KEYCHAIN_READ', + category: 'UNKNOWN', + }); + } + expect(startupFailureFact('PRIVATE_SENTINEL' as any, new TypeError('PRIVATE_SENTINEL'))).toEqual({ + stage: 'READ_CALL', + category: 'TYPE_ERROR', + }); +}); + +test('development output is one fixed info marker without warnings, errors or raw fields', () => { + (global as any).__DEV__ = true; + const info = jest.spyOn(console, 'info').mockImplementation(() => {}); + const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + const error = jest.spyOn(console, 'error').mockImplementation(() => {}); + reportStartupFailure( + startupFailureFact('KEYCHAIN_READ', { code: '-34018', message: 'PRIVATE_SENTINEL' }) + ); + expect(info.mock.calls).toEqual([ + ['KEEPER_STARTUP_ERROR stage=KEYCHAIN_READ category=NATIVE_CODE_NEG34018'], + ]); + expect(warn).not.toHaveBeenCalled(); + expect(error).not.toHaveBeenCalled(); + expect(JSON.stringify(info.mock.calls)).not.toContain('PRIVATE_SENTINEL'); +}); + +test('production ignores observation fields, and a failing logger remains harmless', () => { + const info = jest.spyOn(console, 'info').mockImplementation(() => { + throw Error('PRIVATE_SENTINEL'); + }); + const fact = { + get stage() { + throw Error('PRIVATE_SENTINEL'); + }, + } as any; + (global as any).__DEV__ = false; + expect(() => reportStartupFailure(fact)).not.toThrow(); + expect(info).not.toHaveBeenCalled(); + (global as any).__DEV__ = true; + expect(() => reportStartupFailure(fact)).not.toThrow(); + expect(() => reportStartupFailure({ stage: 'READ_CALL', category: 'UNKNOWN' })).not.toThrow(); +}); + +test('a changing fact accessor is read once and never interpolated after validation', () => { + (global as any).__DEV__ = true; + const info = jest.spyOn(console, 'info').mockImplementation(() => {}); + let reads = 0; + reportStartupFailure({ + get stage() { + return ++reads === 1 ? 'READ_CALL' : 'PRIVATE_SENTINEL'; + }, + category: 'UNKNOWN', + } as any); + expect(reads).toBe(1); + expect(info).toHaveBeenCalledWith('KEEPER_STARTUP_ERROR stage=READ_CALL category=UNKNOWN'); +}); diff --git a/tests/services/startupCredentials.test.ts b/tests/services/startupCredentials.test.ts index 94e749585..82319ced3 100644 --- a/tests/services/startupCredentials.test.ts +++ b/tests/services/startupCredentials.test.ts @@ -1,16 +1,23 @@ // Exercise the real credential-read boundary, without writing native storage. const mockGetGenericPassword = jest.fn(); let mockAccounts = []; +let mockStateFailure; jest.mock('react-native-keychain', () => ({ getGenericPassword: (...args) => mockGetGenericPassword(...args), })); jest.mock('src/store/store', () => ({ - store: { getState: () => ({ account: { allAccounts: mockAccounts } }) }, + store: { + getState: () => { + if (mockStateFailure) throw mockStateFailure; + return { account: { allAccounts: mockAccounts } }; + }, + }, })); jest.mock('src/utils/service-utilities/config', () => ({ __esModule: true, default: {} })); const { hasPin } = require('../../src/storage/secure-store'); beforeEach(() => { mockAccounts = []; + mockStateFailure = undefined; mockGetGenericPassword.mockReset(); }); @@ -43,3 +50,56 @@ test('reads the existing account service names without writing credentials', asy [{ service: 'synthetic-second-account' }], ]); }); + +test.each(['STATE_READ', 'SERVICE_SELECT', 'KEYCHAIN_READ', 'CREDENTIAL_PARSE'])( + 'observes fixed %s facts while preserving the actual rejection', + async (stage) => { + const failure = new Error('PRIVATE_SENTINEL'); + const observe = jest.fn(); + if (stage === 'STATE_READ') mockStateFailure = failure; + if (stage === 'SERVICE_SELECT') + mockAccounts = [ + { + get accountIdentifier() { + throw failure; + }, + }, + ]; + if (stage === 'KEYCHAIN_READ') mockGetGenericPassword.mockRejectedValue(failure); + if (stage === 'CREDENTIAL_PARSE') + mockGetGenericPassword.mockResolvedValue({ password: 'PRIVATE_SENTINEL' }); + if (stage === 'CREDENTIAL_PARSE') { + await expect(hasPin({ throwOnError: true, onReadFailure: observe })).rejects.toBeInstanceOf( + SyntaxError + ); + } else { + await expect(hasPin({ throwOnError: true, onReadFailure: observe })).rejects.toBe(failure); + } + expect(observe).toHaveBeenCalledTimes(1); + expect(observe).toHaveBeenCalledWith({ + stage, + category: stage === 'CREDENTIAL_PARSE' ? 'SYNTAX_ERROR' : 'ERROR', + }); + expect(JSON.stringify(observe.mock.calls)).not.toContain('PRIVATE_SENTINEL'); + } +); + +test.each([true, false])('observer failure preserves throwOnError=%s', async (throwOnError) => { + const original = new Error('PRIVATE_SENTINEL'); + mockGetGenericPassword.mockRejectedValue(original); + const action = hasPin({ + throwOnError, + onReadFailure: () => { + throw new Error('OBSERVER_SENTINEL'); + }, + }); + if (throwOnError) await expect(action).rejects.toBe(original); + else await expect(action).resolves.toBe(false); +}); + +test('a successful empty native read supplies no failure observation', async () => { + const observe = jest.fn(); + mockGetGenericPassword.mockResolvedValue(false); + await expect(hasPin({ throwOnError: true, onReadFailure: observe })).resolves.toBe(false); + expect(observe).not.toHaveBeenCalled(); +}); From ed5749d47d8e8f79b596062c9c8760d8e4a1aa8e Mon Sep 17 00:00:00 2001 From: Antuz tap Date: Thu, 22 Oct 2026 22:55:07 +0000 Subject: [PATCH 2/3] Request info records in the existing bounded iOS diagnostic query --- .github/native/hosted_native.py | 5 ++++- .github/tests/test_hosted_native.py | 9 +++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/native/hosted_native.py b/.github/native/hosted_native.py index 6ed673839..faee713c1 100644 --- a/.github/native/hosted_native.py +++ b/.github/native/hosted_native.py @@ -377,7 +377,10 @@ def ios_details(): predicate = ('process == "%s" AND (messageType == "error" OR messageType == "fault" ' 'OR eventMessage CONTAINS[c] "error" OR eventMessage CONTAINS[c] "exception" ' 'OR eventMessage CONTAINS[c] "fatal")') % executable - args = ['xcrun', 'simctl', 'spawn', device, 'log', 'show', '--style', 'compact', + # RN0.83.9 forwards a single console.info string unchanged to + # RCTDefaultLogFunction / OS_LOG_TYPE_INFO. Request that level in the + # existing bounded query; persistence/routing still need native proof. + args = ['xcrun', 'simctl', 'spawn', device, 'log', 'show', '--info', '--style', 'compact', '--last', '10m', '--predicate', predicate] path = PRIVATE / 'ios-startup-errors.log' # Keep log/xcrun notices private and separate from compact records. diff --git a/.github/tests/test_hosted_native.py b/.github/tests/test_hosted_native.py index aa0472127..2c861825e 100644 --- a/.github/tests/test_hosted_native.py +++ b/.github/tests/test_hosted_native.py @@ -340,8 +340,13 @@ def test_ios_collector_keeps_launch_prefix_when_log_is_truncated_and_preserves_f ' BUNDLE private-path/index.js\n PREBUNDLE private-path/index.js\n') def compact_log(args, stdout, **kwargs): - self.assertEqual(args[args.index('--style') + 1], 'compact') - self.assertEqual(args[args.index('--last') + 1], '10m') + self.assertEqual(args, [ + 'xcrun', 'simctl', 'spawn', 'owned-simulator', 'log', 'show', '--info', + '--style', 'compact', '--last', '10m', '--predicate', + 'process == "hexa_keeper_dev" AND (messageType == "error" OR messageType == "fault" ' + 'OR eventMessage CONTAINS[c] "error" OR eventMessage CONTAINS[c] "exception" ' + 'OR eventMessage CONTAINS[c] "fatal")']) + self.assertEqual(kwargs['timeout'], 25) stdout.write(b'2026-10-17 09:22:33.123 Df hexa_keeper_dev[123:abc] ReferenceError: launch module failed token=private\n') stdout.write(b'2026-10-17 09:22:34.123 E OtherApp[124:def] Error: private unrelated data\n') # The first MiB ends within a continuation, not a complete record. From cd9d50a80bdd9035b532604bd10bcfeb21fe484e Mon Sep 17 00:00:00 2001 From: Antuz tap Date: Thu, 22 Oct 2026 22:56:19 +0000 Subject: [PATCH 3/3] Recognize the exact pinned React Native compact log envelope --- .github/native/ios_startup_errors.py | 3 ++- .github/tests/test_ios_startup_errors.py | 15 +++++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/.github/native/ios_startup_errors.py b/.github/native/ios_startup_errors.py index 5d4e9decf..76cbe09de 100644 --- a/.github/native/ios_startup_errors.py +++ b/.github/native/ios_startup_errors.py @@ -54,7 +54,8 @@ 'NATIVE_CODE_NEG25293', 'NATIVE_CODE_NEG26275', 'NATIVE_CODE_NEG50', 'ERROR', 'TYPE_ERROR', 'SYNTAX_ERROR', 'RANGE_ERROR', 'REFERENCE_ERROR', 'UNKNOWN') _STARTUP_MARKER = re.compile( - r'KEEPER_STARTUP_ERROR stage=(' + '|'.join(STARTUP_STAGES) + + # Exact RN0.83.9 OSLog subsystem/category in the compact message envelope. + r'(?:\[com\.facebook\.react\.log:javascript\] )?KEEPER_STARTUP_ERROR stage=(' + '|'.join(STARTUP_STAGES) + r') category=(' + '|'.join(STARTUP_CATEGORIES) + r')') diff --git a/.github/tests/test_ios_startup_errors.py b/.github/tests/test_ios_startup_errors.py index 5ad6564dc..c062262e8 100644 --- a/.github/tests/test_ios_startup_errors.py +++ b/.github/tests/test_ios_startup_errors.py @@ -34,15 +34,22 @@ def test_precise_development_marker_uses_only_the_shared_fixed_vocabulary(self): for category in ios.STARTUP_CATEGORIES: self.assertIn("'" + category + "'", source) marker = f'KEEPER_STARTUP_ERROR stage={stage} category={category}' - result = ios.classify(record(marker, severity='I'), APP) - self.assertEqual(result['startup_failure_facts'], [{'stage': stage, 'category': category}]) - self.assertEqual(result['error_records'], 1) - self.assertEqual(result['cause'], 'UNDETERMINED') + for envelope in ('', '[com.facebook.react.log:javascript] '): + result = ios.classify(record(envelope + marker, severity='I'), APP) + self.assertEqual(result['startup_failure_facts'], [{'stage': stage, 'category': category}]) + self.assertEqual(result['error_records'], 1) + self.assertEqual(result['cause'], 'UNDETERMINED') def test_foreign_malformed_and_private_marker_variants_supply_no_fixed_facts(self): marker = 'KEEPER_STARTUP_ERROR stage=KEYCHAIN_READ category=NATIVE_CODE_NEG34018' for payload in [record(marker, process='OtherApp'), marker, record('prefix ' + marker), record(marker + ' PRIVATE_SENTINEL'), + record('[com.facebook.react:javascript] ' + marker), + record('[com.facebook.react.log:native] ' + marker), + record('[com.facebook.react.log:javascriptX] ' + marker), + record('[com.facebook.react.log:javascript] ' + marker), + record('[com.facebook.react.log:javascript] ' + marker + ' suffix'), + record('[com.facebook.react.log:javascript] ' + marker, process='OtherApp'), record(marker.replace('KEYCHAIN_READ', 'PRIVATE_SENTINEL')), record(marker.replace('NATIVE_CODE_NEG34018', 'PRIVATE_SENTINEL')), record(marker.replace('KEEPER_STARTUP_ERROR', 'keeper_startup_error'))]: