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
150 changes: 150 additions & 0 deletions .github/tests/startup-failure-observer.test.cjs
Original file line number Diff line number Diff line change
@@ -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, []);
});
90 changes: 48 additions & 42 deletions docs/r5/STARTUP-FAILURE-BOUNDARIES.md
Original file line number Diff line number Diff line change
@@ -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.
45 changes: 23 additions & 22 deletions src/screens/Splash/SplashScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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);
Expand Down Expand Up @@ -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);
}
Expand Down
Loading