From 04be52e61569b88597ccc24504993247cd33ac48 Mon Sep 17 00:00:00 2001 From: Antuz tap Date: Thu, 22 Oct 2026 23:31:42 +0000 Subject: [PATCH] Reconcile one guarded startup failure app observer --- .../tests/startup-failure-observer.test.cjs | 150 +++++++++++++++ docs/r5/STARTUP-FAILURE-BOUNDARIES.md | 90 ++++----- src/screens/Splash/SplashScreen.tsx | 45 ++--- src/storage/secure-store.ts | 53 +++--- src/storage/startup-failure-observer.ts | 106 +++++++++++ tests/screens/SplashScreen.test.tsx | 63 ++++--- .../startupCredentialDiagnostics.test.ts | 171 +++++++++++++----- tests/services/startupCredentials.test.ts | 26 +-- 8 files changed, 541 insertions(+), 163 deletions(-) create mode 100644 .github/tests/startup-failure-observer.test.cjs create mode 100644 src/storage/startup-failure-observer.ts diff --git a/.github/tests/startup-failure-observer.test.cjs b/.github/tests/startup-failure-observer.test.cjs new file mode 100644 index 000000000..d19f8ef3a --- /dev/null +++ b/.github/tests/startup-failure-observer.test.cjs @@ -0,0 +1,150 @@ +'use strict'; +// Execute actual production TS boundaries with synthetic native/store inputs only. +const assert = require('node:assert/strict'); +const test = require('node:test'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); +const root = path.resolve(__dirname, '../..'); +const helperPath = 'src/storage/startup-failure-observer.ts'; + +function compile(source, extra = {}) { + const context = { exports: {}, global: {}, __DEV__: true, + console: new Proxy({}, { get() { throw new Error('Console must not be used'); } }), ...extra }; + vm.runInNewContext(ts.transpileModule(source, { compilerOptions: { + module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020, + } }).outputText, context); + return context; +} +function helper(extra) { return compile(fs.readFileSync(path.join(root, helperPath), 'utf8'), extra); } +function plain(value) { return JSON.parse(JSON.stringify(value)); } +function store({ getState = () => ({ account: { allAccounts: [] } }), read, observer } = {}) { + const observed = [], calls = [], h = helper(); + const context = compile(fs.readFileSync(path.join(root, 'src/storage/secure-store.ts'), 'utf8'), { + require(name) { + if (name === 'react-native-keychain') return { getGenericPassword(options) { calls.push(options); return read(options); } }; + if (name === 'src/store/store') return { store: { getState } }; + if (name === './startup-failure-observer') return h.exports; + if (name === 'node-rsa') return function NodeRSA() {}; + if (name === '../utils/service-utilities/config') return {}; + throw new Error('Unexpected synthetic require'); + }, + }); + return { call: (options = { throwOnError: true }, observe = observer || (row => observed.push(plain(row)))) => + context.exports.hasPin(options, observe), observed, calls, raw: context.exports.hasPin }; +} + +test('existing native call arguments/count/results are unchanged and successes emit nothing', async () => { + const f = store({ getState: () => ({ account: { allAccounts: [ + { accountIdentifier: '' }, { accountIdentifier: 'synthetic-second-account' }, + ] } }), read: options => Promise.resolve(options.service ? { password: '{"hash":"synthetic"}' } : false) }); + assert.equal(await f.call(), true); + assert.deepEqual(plain(f.calls), [{}, { service: 'synthetic-second-account' }]); + assert.equal(Object.hasOwn(f.calls[0], 'service'), true); + assert.equal(f.calls[0].service, undefined); + assert.deepEqual(f.observed, []); + const empty = store({ read: () => Promise.resolve(false) }); + assert.equal(await empty.call(), false); assert.equal(empty.calls.length, 1); + assert.deepEqual(empty.observed, []); +}); + +test('account state, synchronous native throw, native rejection and JSON failure remain distinct', async () => { + const error = Object.assign(new Error('PRIVATE_SENTINEL'), { code: '-34018' }); + for (const [phase, outcome, settings, code] of [ + ['ACCOUNT_STATE', 'THREW', { getState() { throw error; } }, null], + ['NATIVE_CREDENTIAL_READ', 'THREW', { read() { throw error; } }, null], + ['NATIVE_CREDENTIAL_READ', 'REJECTED', { read: () => Promise.reject(error) }, -34018], + ]) { + const f = store(settings); + await assert.rejects(f.call(), caught => caught === error); + assert.deepEqual(f.observed, [{ phase, outcome, errorName: 'Error', nativeCode: code }]); + assert.equal(f.calls.length, phase === 'ACCOUNT_STATE' ? 0 : 1); + assert.equal(JSON.stringify(f.observed).includes('PRIVATE_SENTINEL'), false); + } + const json = store({ read: () => Promise.resolve({ password: 'PRIVATE_SENTINEL' }) }); + await assert.rejects(json.call(), error => error.name === 'SyntaxError'); + assert.deepEqual(json.observed, [{ phase: 'CREDENTIAL_JSON', outcome: 'THREW', errorName: 'SyntaxError', nativeCode: null }]); +}); + +test('legacy false-on-error and original rejection identity survive observer/getter failures', async () => { + let getters = 0; + const error = {}; + Object.defineProperties(error, { name: { get() { getters++; throw new Error('PRIVATE_SENTINEL'); } }, + code: { get() { getters++; throw new Error('PRIVATE_SENTINEL'); } } }); + const f = store({ read: () => Promise.reject(error), observer() { throw new Error('PRIVATE_OBSERVER'); } }); + await assert.rejects(f.call(), caught => caught === error); + assert.equal(await f.call({ throwOnError: false }), false); + assert.equal(f.calls.length, 2); + const before = getters; + await assert.rejects(f.raw({ throwOnError: true }), caught => caught === error); + assert.equal(getters, before); // No observer means no error-property inspection. +}); + +test('only canonical decimal int32 codes at native rejection are retained without coercion', () => { + const { reportStartupFailure } = helper().exports; + for (const [code, expected] of [['-2147483648', -2147483648], ['2147483647', 2147483647], ['0', 0], + ['2147483648', null], ['-2147483649', null], ['-0', null], ['+1', null], ['01', null], + [' 1', null], ['-34018\n', null], ['-34018\r\n', null], ['-34018\u2028', null], + ['-34018\u2029', null], ['1e3', null], ['1.0', null], ['\u22121', null], [1, null], + [{ toString() { throw new Error('PRIVATE_SENTINEL'); } }, null]]) { + const rows = []; + reportStartupFailure(row => rows.push(plain(row)), 'NATIVE_CREDENTIAL_READ', 'REJECTED', { name: 'Error', code }); + assert.equal(rows[0].nativeCode, expected); + assert.equal(JSON.stringify(rows).includes('PRIVATE_SENTINEL'), false); + } + let codeRead = false; + reportStartupFailure(() => {}, 'NAVIGATION', 'THREW', { get code() { codeRead = true; return '-34018'; } }); + assert.equal(codeRead, false); + const rows = []; + reportStartupFailure(row => rows.push(row), 'PRIVATE_SENTINEL', 'THREW', {}); + reportStartupFailure(row => rows.push(row), 'ACCOUNT_STATE', 'REJECTED', {}); + assert.deepEqual(rows, []); +}); + +test('dev-only native hook emits one fixed Error-level marker and never invokes console/LogBox', () => { + const calls = []; + const h = helper({ global: { nativeLoggingHook: (...args) => calls.push(args) }, Date: { now: () => 1700000000123 } }); + h.exports.reportStartupFailure(h.exports.observeStartupFailure, 'NATIVE_CREDENTIAL_READ', 'REJECTED', + { name: 'PRIVATE_SENTINEL', code: '-34018', message: 'PRIVATE_SENTINEL', stack: 'PRIVATE_SENTINEL' }); + assert.deepEqual(calls, [['KEEPER_STARTUP_FAILURE_V1|1700000000123|NATIVE_CREDENTIAL_READ|REJECTED|OTHER|-34018', 3]]); + const quiet = helper({ __DEV__: false, global: { nativeLoggingHook() { throw new Error('must not call'); } } }); + quiet.exports.observeStartupFailure({ phase: 'ACCOUNT_STATE', outcome: 'THREW', errorName: 'Error', nativeCode: null }); + const broken = helper({ global: Object.defineProperty({}, 'nativeLoggingHook', { get() { throw new Error('PRIVATE_SENTINEL'); } }) }); + assert.doesNotThrow(() => broken.exports.observeStartupFailure(null)); + assert.doesNotThrow(() => helper({ global: { nativeLoggingHook() { throw new Error('PRIVATE_SENTINEL'); } } }).exports + .observeStartupFailure({ phase: 'ACCOUNT_STATE', outcome: 'THREW', errorName: 'Error', nativeCode: null })); +}); + +function navigate({ read, replace, current = true, report } = {}) { + const source = fs.readFileSync(path.join(root, 'src/screens/Splash/SplashScreen.tsx'), 'utf8'); + const tree = ts.createSourceFile('Splash.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + let selected; + function visit(node) { + if (ts.isVariableDeclaration(node) && node.name.getText(tree) === 'navigateToApp') { + assert.equal(selected, undefined); selected = node.initializer.getText(tree); + } + ts.forEachChild(node, visit); + } + visit(tree); assert.ok(selected); + const failures = [], flags = [], reads = [], marker = () => {}; + const context = { current, readPending: { current: true }, setStartupError: value => flags.push(value), + SecureStore: { hasPin(...args) { reads.push(args); return read(); } }, + startupFailureObserver: marker, reportStartupFailure: report || ((...args) => failures.push(args)), + navigation: { replace }, exports: {} }; + vm.runInNewContext(ts.transpileModule('exports.run = ' + selected, { compilerOptions: { target: ts.ScriptTarget.ES2020 } }).outputText, context); + return { run: context.exports.run, failures, flags, reads, marker, context }; +} + +test('actual Splash closure records navigation throws separately without duplicating credential failures', async () => { + const error = new Error('PRIVATE_SENTINEL'); + const nav = navigate({ read: () => Promise.resolve(false), replace() { throw error; } }); + await nav.run(); assert.equal(nav.failures.length, 1); + assert.deepEqual(nav.failures[0].slice(1, 3), ['NAVIGATION', 'THREW']); + assert.equal(nav.failures[0][3], error); assert.deepEqual(nav.flags, [true]); + assert.equal(nav.reads.length, 1); assert.equal(nav.reads[0][1], nav.marker); + const native = navigate({ read: () => Promise.reject(error), replace() { throw new Error('must not navigate'); } }); + await native.run(); assert.deepEqual(native.failures, []); assert.deepEqual(native.flags, [true]); + const stale = navigate({ current: false, read: () => Promise.resolve(true), replace() { throw new Error('must not navigate'); } }); + await stale.run(); assert.deepEqual(stale.flags, []); assert.deepEqual(stale.failures, []); +}); diff --git a/docs/r5/STARTUP-FAILURE-BOUNDARIES.md b/docs/r5/STARTUP-FAILURE-BOUNDARIES.md index 414555a8a..d269e34a2 100644 --- a/docs/r5/STARTUP-FAILURE-BOUNDARIES.md +++ b/docs/r5/STARTUP-FAILURE-BOUNDARIES.md @@ -1,46 +1,52 @@ -# 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: +# Startup observation reconciliation A: app transport + +This package preserves both producer ancestries: [#7129](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7129) +`cd9d50a80bdd9035b532604bd10bcfeb21fe484e` and [#7131](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7131) +`e34331083959c94b5f0a17603d8c1f578305c474`. Its fixed source-review baseline +`4b6cabc55a82d4f9d200a97db137202d01236e82` has those two parents and exactly +the already reviewed #7129 tree. That join is not a native/release candidate; +selected #7131 work is exposed across this app package A and successor B. +Full new changed code/test text across both packages is approximately18.3k +characters/4 tokens before final formatting; per-package estimates and exact +commits belong in their handoffs. Existing producer PRs remain review links. + +A selects exactly one development-only direct native hook from #7131 and adds +#7129's current-attempt/unmount guard. The old console.info emitter is removed. +Its old pure classifier remains temporarily because the unchanged canonical +parser's source-vocabulary controls still use it. It emits no log and is not +called by the app. Successor B removes it and connects the V1 collector to the +canonical parser; A alone does not claim V1 fixed-receipt collection. + +The original1bc iOS window built/installed successfully and failed Create a +passcode. [The exact artifact readout](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7123) +retained credential-error and Retry flags in one snapshot. Its616 own-process +error records contain18 CONNECTION markers and598 unclassified records. Neither +the snapshot nor those categories identify a Keychain/navigation cause. The +original source and evidence remain immutable; no pass transfers to this source. + +The optional second `hasPin` callback receives only fixed phase/outcome/error-name +values and an optional numeric code. Only the original native-read rejection may +retain a canonical ASCII decimal-string signed int32 code. Guarded getters never +forward the original error, message, stack, credential, service/account identifier +or native response. No observer means no error-property inspection. Original +rejection identity, legacy false-on-error semantics, read count/service choice, +modal, Retry, success navigation and cleanup remain intact. Navigation failures +have their own phase after the original read. Abandoned attempts emit nothing. + +A current development failure emits one direct Error-level3 hook call, such as: ```text -KEEPER_STARTUP_ERROR stage=KEYCHAIN_READ category=NATIVE_CODE_NEG34018 +KEEPER_STARTUP_FAILURE_V1|1500|NATIVE_CREDENTIAL_READ|REJECTED|Error|-34018 ``` -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. +This is illustrative grammar, not an observed native code. No console/LogBox call +or production observer is introduced. Pinned RN0.83.9 source supports the direct +Error sink. Actual hosted transport and marker visibility remain UNVERIFIED. +There is no SDK, selector, query, deadline, dependency or acceptance change in A. + +Source controls cover original results/errors, every read boundary, hostile +getters, observer/sink faults, production silence, navigation, Retry and late +unmount. A does not correct the observed app failure or establish native, +backend, physical-device or release acceptance. No native window is queued. +The complete collection/privacy/ambiguity controls are a separate successor B, +which must be reviewed and integrated before the next combined diagnostic source. diff --git a/src/screens/Splash/SplashScreen.tsx b/src/screens/Splash/SplashScreen.tsx index 692044af1..083b107a5 100644 --- a/src/screens/Splash/SplashScreen.tsx +++ b/src/screens/Splash/SplashScreen.tsx @@ -4,12 +4,6 @@ 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, @@ -27,6 +21,11 @@ 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'; +import { + observeStartupFailure, + reportStartupFailure, + StartupFailureReceipt, +} from 'src/storage/startup-failure-observer'; function SplashScreen({ navigation }) { const { torEnbled, themeMode, bitcoinNetworkType } = useAppSelector((state) => state.settings); @@ -72,31 +71,33 @@ function SplashScreen({ navigation }) { useEffect(() => { let current = true; readPending.current = true; + const startupFailureObserver = + typeof __DEV__ !== 'undefined' && __DEV__ + ? (receipt: StartupFailureReceipt) => { + if (current) observeStartupFailure(receipt); + } + : undefined; const navigateToApp = async () => { - let failure: StartupFailureFact | undefined; - let stage: StartupFailureStage = 'READ_CALL'; + let hasCreds; + try { + hasCreds = await SecureStore.hasPin({ throwOnError: true }, startupFailureObserver); + } catch { + if (current) { + readPending.current = false; + setStartupError(true); + } + return; + } + if (!current) return; try { - 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 (error) { + reportStartupFailure(startupFailureObserver, 'NAVIGATION', 'THREW', 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 6e7607f26..fa7fd4ac7 100644 --- a/src/storage/secure-store.ts +++ b/src/storage/secure-store.ts @@ -3,10 +3,10 @@ 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'; + reportStartupFailure, + StartupFailureObserver, + StartupFailurePhase, +} from './startup-failure-observer'; export const store = async (hash: string, enc_key: string, identifier: string) => { try { @@ -72,14 +72,12 @@ 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, - onReadFailure, -}: { - throwOnError?: boolean; - onReadFailure?: (fact: StartupFailureFact) => void; -} = {}) => { - let stage: StartupFailureStage = 'STATE_READ'; +export const hasPin = async ( + { throwOnError = false }: { throwOnError?: boolean } = {}, + onFailure: StartupFailureObserver | undefined = undefined +) => { + let phase: StartupFailurePhase = 'ACCOUNT_STATE'; + let reported = false; try { let allAccounts = reduxStore.getState().account.allAccounts; // if allAccounts is empty | upgraded app with old passcode configuration @@ -87,17 +85,30 @@ export const hasPin = async ({ allAccounts = [{ accountIdentifier: undefined }]; } for (const index in allAccounts) { - stage = 'SERVICE_SELECT'; + phase = 'ACCOUNT_STATE'; const identifier = allAccounts[index].accountIdentifier == '' ? undefined : allAccounts[index].accountIdentifier; - stage = 'KEYCHAIN_READ'; - const credentials = await Keychain.getGenericPassword({ - service: identifier, - }); + phase = 'NATIVE_CREDENTIAL_READ'; + let pending; + try { + pending = Keychain.getGenericPassword({ service: identifier }); + } catch (err) { + reported = true; + reportStartupFailure(onFailure, phase, 'THREW', err); + throw err; + } + let credentials; + try { + credentials = await pending; + } catch (err) { + reported = true; + reportStartupFailure(onFailure, phase, 'REJECTED', err); + throw err; + } + phase = 'CREDENTIAL_JSON'; if (credentials) { - stage = 'CREDENTIAL_PARSE'; const password = JSON.parse(credentials.password); if (password) { return true; @@ -106,11 +117,7 @@ export const hasPin = async ({ } return false; } catch (err) { - try { - onReadFailure?.(startupFailureFact(stage, err)); - } catch { - // An observer cannot replace the original rejection or legacy false. - } + if (!reported) reportStartupFailure(onFailure, phase, 'THREW', err); if (throwOnError) throw err; return false; } diff --git a/src/storage/startup-failure-observer.ts b/src/storage/startup-failure-observer.ts new file mode 100644 index 000000000..4a086cb08 --- /dev/null +++ b/src/storage/startup-failure-observer.ts @@ -0,0 +1,106 @@ +// Development diagnostics only. Never forward an error object or credential value. +export type StartupFailurePhase = + | 'ACCOUNT_STATE' + | 'NATIVE_CREDENTIAL_READ' + | 'CREDENTIAL_JSON' + | 'NAVIGATION'; +export type StartupFailureOutcome = 'THREW' | 'REJECTED'; +export type StartupFailureReceipt = { + phase: StartupFailurePhase; + outcome: StartupFailureOutcome; + errorName: string; + nativeCode: number | null; +}; +export type StartupFailureObserver = (receipt: StartupFailureReceipt) => void; + +const NAMES = [ + 'Error', + 'TypeError', + 'SyntaxError', + 'ReferenceError', + 'RangeError', + 'EvalError', + 'URIError', + 'AggregateError', + 'OTHER', + 'UNKNOWN', +]; +const PHASES = ['ACCOUNT_STATE', 'NATIVE_CREDENTIAL_READ', 'CREDENTIAL_JSON', 'NAVIGATION']; + +export const reportStartupFailure = ( + observer: StartupFailureObserver | undefined, + phase: StartupFailurePhase, + outcome: StartupFailureOutcome, + error: unknown +) => { + if (typeof observer !== 'function') return; + try { + if ( + !PHASES.includes(phase) || + !['THREW', 'REJECTED'].includes(outcome) || + (outcome === 'REJECTED' && phase !== 'NATIVE_CREDENTIAL_READ') + ) + return; + let errorName = 'UNKNOWN'; + let nativeCode: number | null = null; + if (error !== null && (typeof error === 'object' || typeof error === 'function')) { + try { + const { name } = error as { name?: unknown }; + errorName = typeof name === 'string' ? (NAMES.includes(name) ? name : 'OTHER') : 'UNKNOWN'; + } catch { + /* An error getter cannot affect the original failure. */ + } + if (phase === 'NATIVE_CREDENTIAL_READ' && outcome === 'REJECTED') { + try { + const { code } = error as { code?: unknown }; + // RNKeychain10.0.0 rejects with an NSString decimal OSStatus. Do not + // reinterpret other codes, numbers, whitespace or coercible objects. + if (typeof code === 'string' && /^(?:0|-?[1-9][0-9]{0,9})$/.exec(code)?.[0] === code) { + const numeric = Number(code); + if (Number.isInteger(numeric) && numeric >= -2147483648 && numeric <= 2147483647) { + nativeCode = numeric; + } + } + } catch { + /* No error message, stack or getter exception is inspected. */ + } + } + } + observer({ phase, outcome, errorName, nativeCode }); + } catch { + /* Diagnostics must never replace or mask an original result/error. */ + } +}; + +export const observeStartupFailure: StartupFailureObserver = (receipt) => { + try { + if (typeof __DEV__ === 'undefined' || !__DEV__) return; + const hook = (global as unknown as { nativeLoggingHook?: unknown }).nativeLoggingHook; + if (typeof hook !== 'function') return; + const { phase, outcome, errorName, nativeCode } = receipt; + if ( + !PHASES.includes(phase) || + !['THREW', 'REJECTED'].includes(outcome) || + !NAMES.includes(errorName) || + (outcome === 'REJECTED' && phase !== 'NATIVE_CREDENTIAL_READ') || + (nativeCode !== null && + (phase !== 'NATIVE_CREDENTIAL_READ' || + outcome !== 'REJECTED' || + !Number.isInteger(nativeCode) || + nativeCode < -2147483648 || + nativeCode > 2147483647)) + ) + return; + const when = Date.now(); + if (!Number.isSafeInteger(when) || when < 0 || when > 100000000000000) return; + const marker = `KEEPER_STARTUP_FAILURE_V1|${when}|${phase}|${outcome}|${errorName}|${ + nativeCode === null ? 'NONE' : nativeCode + }`; + // RN0.83.9's direct hook reaches the JS os_log Error sink at level3. + // Bypass console.error's ExceptionsManager/LogBox wrapper. Hosted capture + // remains unverified until this exact diagnostic source actually runs. + hook(marker, 3); + } catch { + /* Missing hooks, clock/getter failures and observers are optional. */ + } +}; diff --git a/tests/screens/SplashScreen.test.tsx b/tests/screens/SplashScreen.test.tsx index 311f1ffa0..db17d589b 100644 --- a/tests/screens/SplashScreen.test.tsx +++ b/tests/screens/SplashScreen.test.tsx @@ -9,8 +9,9 @@ const mockEvents: string[] = []; let mockSettings; let mockColorMode = 'light'; let mockDev = false; -let startupInfo; +let startupHook; const previousDev = __DEV__; +const previousHook = (global as any).nativeLoggingHook; jest.mock('src/store/hooks', () => ({ useAppSelector: (select) => select({ settings: mockSettings }), @@ -78,8 +79,10 @@ function visibleDialogs() { } beforeEach(() => { (global as any).__DEV__ = true; - startupInfo = jest.spyOn(console, 'info').mockImplementation(() => {}); + startupHook = jest.fn(); + (global as any).nativeLoggingHook = startupHook; jest.useFakeTimers(); + jest.setSystemTime(1500); mockSettings = { torEnbled: false, themeMode: 'LIGHT', bitcoinNetworkType: 'MAINNET' }; mockColorMode = 'light'; mockDev = false; @@ -98,7 +101,7 @@ afterEach(() => { jest.clearAllTimers(); jest.useRealTimers(); (global as any).__DEV__ = previousDev; - startupInfo.mockRestore(); + (global as any).nativeLoggingHook = previousHook; }); test('starts the credential read without waiting for the splash animation', async () => { @@ -106,10 +109,7 @@ 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, - onReadFailure: expect.any(Function), - }); + expect(mockHasPin).toHaveBeenCalledWith({ throwOnError: true }, expect.any(Function)); expect(navigation.replace).not.toHaveBeenCalled(); await act(async () => pin.resolve(true)); expect(navigation.replace).toHaveBeenCalledWith('Login', { relogin: false }); @@ -211,13 +211,18 @@ test('rerendering preserves the selected network and does not read credentials a }); 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' }); + mockHasPin.mockImplementationOnce(async (_, onFailure) => { + onFailure({ + phase: 'NATIVE_CREDENTIAL_READ', + outcome: 'REJECTED', + errorName: 'Error', + nativeCode: -34018, + }); throw Error('PRIVATE_SENTINEL'); }); await mount(); - expect(startupInfo.mock.calls).toEqual([ - ['KEEPER_STARTUP_ERROR stage=KEYCHAIN_READ category=NATIVE_CODE_NEG34018'], + expect(startupHook.mock.calls).toEqual([ + ['KEEPER_STARTUP_FAILURE_V1|1500|NATIVE_CREDENTIAL_READ|REJECTED|Error|-34018', 3], ]); expect(visibleDialogs()).toHaveLength(1); expect(navigation.replace).not.toHaveBeenCalled(); @@ -234,12 +239,8 @@ test.each([true, false])( 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(startupHook.mock.calls).toEqual([ + ['KEEPER_STARTUP_FAILURE_V1|1500|NAVIGATION|THREW|TypeError|NONE', 3], ]); expect(visibleDialogs()).toHaveLength(1); } @@ -253,18 +254,24 @@ test('production supplies no observation callback and never inspects failure pro const failure = Object.defineProperty({}, 'code', { get: code }); mockHasPin.mockRejectedValue(failure); await mount(); - expect(mockHasPin).toHaveBeenCalledWith({ throwOnError: true }); + expect(mockHasPin).toHaveBeenCalledWith({ throwOnError: true }, undefined); expect(code).not.toHaveBeenCalled(); - expect(startupInfo).not.toHaveBeenCalled(); + expect(startupHook).not.toHaveBeenCalled(); expect(visibleDialogs()).toHaveLength(1); }); test('logger failure preserves the generic Retry and the next successful credential read', async () => { - startupInfo.mockImplementation(() => { + startupHook.mockImplementation(() => { throw Error('PRIVATE_SENTINEL'); }); - mockHasPin.mockRejectedValueOnce(Error('PRIVATE_SENTINEL')).mockResolvedValue(false); + mockHasPin + .mockImplementationOnce(async (_, observer) => { + observer({ phase: 'ACCOUNT_STATE', outcome: 'THREW', errorName: 'Error', nativeCode: null }); + throw Error('PRIVATE_SENTINEL'); + }) + .mockResolvedValue(false); await mount(); + expect(startupHook).toHaveBeenCalledTimes(1); expect(visibleDialogs()).toHaveLength(1); await act(async () => visibleDialogs()[0].props.buttonCallback()); expect(navigation.replace).toHaveBeenCalledWith('CreatePin'); @@ -273,11 +280,21 @@ test('logger failure preserves the generic Retry and the next successful credent test('an abandoned attempt cannot emit a late failure marker', async () => { const read = deferred(); - mockHasPin.mockReturnValue(read.promise); + let observer; + mockHasPin.mockImplementationOnce((_, onFailure) => { + observer = onFailure; + return read.promise; + }); await mount(); act(() => screen.unmount()); screen = null; + observer({ + phase: 'NATIVE_CREDENTIAL_READ', + outcome: 'REJECTED', + errorName: 'Error', + nativeCode: -34018, + }); await act(async () => read.reject(Error('PRIVATE_SENTINEL'))); - expect(startupInfo).not.toHaveBeenCalled(); + expect(startupHook).not.toHaveBeenCalled(); expect(navigation.replace).not.toHaveBeenCalled(); }); diff --git a/tests/services/startupCredentialDiagnostics.test.ts b/tests/services/startupCredentialDiagnostics.test.ts index 0b23f40ec..86d28b98e 100644 --- a/tests/services/startupCredentialDiagnostics.test.ts +++ b/tests/services/startupCredentialDiagnostics.test.ts @@ -1,28 +1,78 @@ import { + observeStartupFailure, reportStartupFailure, - startupFailureFact, -} from '../../src/storage/startup-credential-diagnostics'; +} from '../../src/storage/startup-failure-observer'; const previousDev = __DEV__; +const previousHook = Object.getOwnPropertyDescriptor(global, 'nativeLoggingHook'); afterEach(() => { (global as any).__DEV__ = previousDev; + if (previousHook) Object.defineProperty(global, 'nativeLoggingHook', previousHook); + else delete (global as any).nativeLoggingHook; 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)}`, +function installHook(value) { + Object.defineProperty(global, 'nativeLoggingHook', { configurable: true, writable: true, value }); +} + +test('only canonical native rejection codes supply a bounded code without coercion', () => { + for (const [code, expected] of [ + ['-34018', -34018], + ['-25308', -25308], + ['0', 0], + ['2147483647', 2147483647], + ['-2147483648', -2147483648], + [-25308, null], + ['+1', null], + ['01', null], + ['-0', null], + [' 1', null], + ['1e3', null], + ['-34018\n', null], + ['2147483648', null], + [ + { + toString() { + throw Error('PRIVATE_SENTINEL'); + }, + }, + null, + ], + ]) { + const observer = jest.fn(); + reportStartupFailure(observer, 'NATIVE_CREDENTIAL_READ', 'REJECTED', { + code, + name: 'Error', + message: 'PRIVATE_SENTINEL', + }); + expect(observer).toHaveBeenCalledWith({ + phase: 'NATIVE_CREDENTIAL_READ', + outcome: 'REJECTED', + errorName: 'Error', + nativeCode: expected, }); + expect(JSON.stringify(observer.mock.calls)).not.toContain('PRIVATE_SENTINEL'); } - expect(startupFailureFact('CREDENTIAL_PARSE', { code: '-34018', name: 'SyntaxError' })).toEqual({ - stage: 'CREDENTIAL_PARSE', - category: 'SYNTAX_ERROR', + const observer = jest.fn(); + let codeReads = 0; + reportStartupFailure(observer, 'CREDENTIAL_JSON', 'THREW', { + name: 'SyntaxError', + get code() { + codeReads++; + return '-34018'; + }, + }); + expect(codeReads).toBe(0); + expect(observer).toHaveBeenCalledWith({ + phase: 'CREDENTIAL_JSON', + outcome: 'THREW', + errorName: 'SyntaxError', + nativeCode: null, }); }); -test('unknown values and hostile error accessors cannot escape or replace the failure', () => { +test('unknown private fields and hostile error accessors cannot escape or replace a failure', () => { const values = [ null, 'PRIVATE_SENTINEL', @@ -46,60 +96,99 @@ test('unknown values and hostile error accessors cannot escape or replace the fa }, ]; for (const value of values) { - expect(startupFailureFact('KEYCHAIN_READ', value)).toEqual({ - stage: 'KEYCHAIN_READ', - category: 'UNKNOWN', - }); + const observer = jest.fn(); + expect(() => + reportStartupFailure(observer, 'NATIVE_CREDENTIAL_READ', 'REJECTED', value) + ).not.toThrow(); + expect(observer).toHaveBeenCalledTimes(1); + expect(observer.mock.calls[0][0].nativeCode).toBeNull(); + expect(['UNKNOWN', 'OTHER']).toContain(observer.mock.calls[0][0].errorName); + expect(JSON.stringify(observer.mock.calls)).not.toContain('PRIVATE_SENTINEL'); } - expect(startupFailureFact('PRIVATE_SENTINEL' as any, new TypeError('PRIVATE_SENTINEL'))).toEqual({ - stage: 'READ_CALL', - category: 'TYPE_ERROR', - }); + const observer = jest.fn(); + reportStartupFailure(observer, 'PRIVATE_SENTINEL' as any, 'THREW', new Error('PRIVATE_SENTINEL')); + expect(observer).not.toHaveBeenCalled(); }); -test('development output is one fixed info marker without warnings, errors or raw fields', () => { +test('development output is one direct Error-level marker without console or LogBox calls', () => { (global as any).__DEV__ = true; + const hook = jest.fn(); + installHook(hook); + jest.spyOn(Date, 'now').mockReturnValue(1500); 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'], + reportStartupFailure(observeStartupFailure, 'NATIVE_CREDENTIAL_READ', 'REJECTED', { + code: '-34018', + name: 'Error', + message: 'PRIVATE_SENTINEL', + }); + expect(hook.mock.calls).toEqual([ + ['KEEPER_STARTUP_FAILURE_V1|1500|NATIVE_CREDENTIAL_READ|REJECTED|Error|-34018', 3], ]); + expect(info).not.toHaveBeenCalled(); expect(warn).not.toHaveBeenCalled(); expect(error).not.toHaveBeenCalled(); - expect(JSON.stringify(info.mock.calls)).not.toContain('PRIVATE_SENTINEL'); + expect(JSON.stringify(hook.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'); +test('production and missing observers inspect nothing, and failing hooks stay harmless', () => { + let hookReads = 0, + errorReads = 0; + Object.defineProperty(global, 'nativeLoggingHook', { + configurable: true, + get() { + hookReads++; + throw Error('PRIVATE_SENTINEL'); + }, }); const fact = { - get stage() { + get phase() { throw Error('PRIVATE_SENTINEL'); }, } as any; (global as any).__DEV__ = false; - expect(() => reportStartupFailure(fact)).not.toThrow(); - expect(info).not.toHaveBeenCalled(); + expect(() => observeStartupFailure(fact)).not.toThrow(); + expect(hookReads).toBe(0); + reportStartupFailure(undefined, 'NAVIGATION', 'THREW', { + get name() { + errorReads++; + throw Error('PRIVATE_SENTINEL'); + }, + }); + expect(errorReads).toBe(0); (global as any).__DEV__ = true; - expect(() => reportStartupFailure(fact)).not.toThrow(); - expect(() => reportStartupFailure({ stage: 'READ_CALL', category: 'UNKNOWN' })).not.toThrow(); + expect(() => observeStartupFailure(fact)).not.toThrow(); + installHook(() => { + throw Error('PRIVATE_SENTINEL'); + }); + expect(() => + observeStartupFailure({ + phase: 'ACCOUNT_STATE', + outcome: 'THREW', + errorName: 'Error', + nativeCode: null, + }) + ).not.toThrow(); }); -test('a changing fact accessor is read once and never interpolated after validation', () => { +test('a changing fact accessor is read once before validating and forming the fixed marker', () => { (global as any).__DEV__ = true; - const info = jest.spyOn(console, 'info').mockImplementation(() => {}); + const hook = jest.fn(); + installHook(hook); + jest.spyOn(Date, 'now').mockReturnValue(1500); let reads = 0; - reportStartupFailure({ - get stage() { - return ++reads === 1 ? 'READ_CALL' : 'PRIVATE_SENTINEL'; + observeStartupFailure({ + get phase() { + return ++reads === 1 ? 'ACCOUNT_STATE' : 'PRIVATE_SENTINEL'; }, - category: 'UNKNOWN', + outcome: 'THREW', + errorName: 'UNKNOWN', + nativeCode: null, } as any); expect(reads).toBe(1); - expect(info).toHaveBeenCalledWith('KEEPER_STARTUP_ERROR stage=READ_CALL category=UNKNOWN'); + expect(hook).toHaveBeenCalledWith( + 'KEEPER_STARTUP_FAILURE_V1|1500|ACCOUNT_STATE|THREW|UNKNOWN|NONE', + 3 + ); }); diff --git a/tests/services/startupCredentials.test.ts b/tests/services/startupCredentials.test.ts index 82319ced3..9ba6088e3 100644 --- a/tests/services/startupCredentials.test.ts +++ b/tests/services/startupCredentials.test.ts @@ -69,16 +69,21 @@ test.each(['STATE_READ', 'SERVICE_SELECT', 'KEYCHAIN_READ', 'CREDENTIAL_PARSE']) if (stage === 'CREDENTIAL_PARSE') mockGetGenericPassword.mockResolvedValue({ password: 'PRIVATE_SENTINEL' }); if (stage === 'CREDENTIAL_PARSE') { - await expect(hasPin({ throwOnError: true, onReadFailure: observe })).rejects.toBeInstanceOf( - SyntaxError - ); + await expect(hasPin({ throwOnError: true }, observe)).rejects.toBeInstanceOf(SyntaxError); } else { - await expect(hasPin({ throwOnError: true, onReadFailure: observe })).rejects.toBe(failure); + await expect(hasPin({ throwOnError: true }, observe)).rejects.toBe(failure); } expect(observe).toHaveBeenCalledTimes(1); expect(observe).toHaveBeenCalledWith({ - stage, - category: stage === 'CREDENTIAL_PARSE' ? 'SYNTAX_ERROR' : 'ERROR', + phase: + stage === 'CREDENTIAL_PARSE' + ? 'CREDENTIAL_JSON' + : stage === 'KEYCHAIN_READ' + ? 'NATIVE_CREDENTIAL_READ' + : 'ACCOUNT_STATE', + outcome: stage === 'KEYCHAIN_READ' ? 'REJECTED' : 'THREW', + errorName: stage === 'CREDENTIAL_PARSE' ? 'SyntaxError' : 'Error', + nativeCode: null, }); expect(JSON.stringify(observe.mock.calls)).not.toContain('PRIVATE_SENTINEL'); } @@ -87,11 +92,8 @@ test.each(['STATE_READ', 'SERVICE_SELECT', 'KEYCHAIN_READ', 'CREDENTIAL_PARSE']) 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'); - }, + const action = hasPin({ throwOnError }, () => { + throw new Error('OBSERVER_SENTINEL'); }); if (throwOnError) await expect(action).rejects.toBe(original); else await expect(action).resolves.toBe(false); @@ -100,6 +102,6 @@ test.each([true, false])('observer failure preserves throwOnError=%s', async (th 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); + await expect(hasPin({ throwOnError: true }, observe)).resolves.toBe(false); expect(observe).not.toHaveBeenCalled(); });