Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/native/hosted_native.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
19 changes: 18 additions & 1 deletion .github/native/ios_startup_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@
_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(
# 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')')


def classify(payload, executable):
Expand Down Expand Up @@ -79,6 +88,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:
Expand Down Expand Up @@ -110,9 +121,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
Expand Down
9 changes: 7 additions & 2 deletions .github/tests/test_hosted_native.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
48 changes: 48 additions & 0 deletions .github/tests/test_ios_startup_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import importlib.util
import json
import re
from pathlib import Path
import unittest
from unittest import mock
Expand All @@ -19,6 +20,53 @@ 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}'
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'))]:
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',
Expand Down
46 changes: 46 additions & 0 deletions docs/r5/STARTUP-FAILURE-BOUNDARIES.md
Original file line number Diff line number Diff line change
@@ -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.
24 changes: 22 additions & 2 deletions src/screens/Splash/SplashScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
}
Expand Down
22 changes: 21 additions & 1 deletion src/storage/secure-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -67,22 +72,32 @@ 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
if (!allAccounts.length) {
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;
Expand All @@ -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;
}
Expand Down
81 changes: 81 additions & 0 deletions src/storage/startup-credential-diagnostics.ts
Original file line number Diff line number Diff line change
@@ -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.
}
};
Loading