Skip to content
Merged
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
58 changes: 48 additions & 10 deletions src/components/Onfido/index.native.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import FullscreenLoadingIndicator from '@components/FullscreenLoadingIndicator';
import ActivityIndicator from '@components/ActivityIndicator';

import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';

import getPlatform from '@libs/getPlatform';
import goToSettings from '@libs/goToSettings';
Expand All @@ -20,8 +21,31 @@ const {AppStateTracker} = NativeModules;

function Onfido({sdkToken, onUserExit, onSuccess, onError}: OnfidoProps) {
const {translate} = useLocalize();
const styles = useThemeStyles();

useEffect(() => {
// Back is exposed while OnfidoSDK.start() is still pending, so a late resolve/reject could navigate or mutate
// wallet/bank-account state after the user has already left. Ignore the callbacks once this component unmounts.
let isActive = true;
const handleSuccess: OnfidoProps['onSuccess'] = (data) => {
if (!isActive) {
return;
}
onSuccess(data);
};
const handleUserExit: OnfidoProps['onUserExit'] = (isUserInitiated) => {
if (!isActive) {
return;
}
onUserExit(isUserInitiated);
};
const handleError: OnfidoProps['onError'] = (error) => {
if (!isActive) {
return;
}
onError(error);
};

OnfidoSDK.start({
sdkToken,
theme: OnfidoTheme.AUTOMATIC,
Expand All @@ -38,7 +62,7 @@ function Onfido({sdkToken, onUserExit, onSuccess, onError}: OnfidoProps) {
},
},
})
.then(onSuccess)
.then(handleSuccess)
.catch((error: OnfidoError) => {
const errorMessage: string = error.message ?? CONST.ERROR.UNKNOWN_ERROR;
const errorType = error.type;
Expand All @@ -50,18 +74,23 @@ function Onfido({sdkToken, onUserExit, onSuccess, onError}: OnfidoProps) {
if (([CONST.ONFIDO.ERROR.USER_CANCELLED, CONST.ONFIDO.ERROR.USER_TAPPED_BACK, CONST.ONFIDO.ERROR.USER_EXITED] as string[]).includes(errorMessage)) {
if (getPlatform() === CONST.PLATFORM.ANDROID) {
AppStateTracker.getWasAppRelaunchedFromIcon().then((wasAppRelaunchedFromIcon) => {
onUserExit(!wasAppRelaunchedFromIcon);
handleUserExit(!wasAppRelaunchedFromIcon);
});
return;
}

onUserExit(true);
handleUserExit(true);
return;
}

if (!!errorMessage && getPlatform() === CONST.PLATFORM.IOS) {
checkMultiple([PERMISSIONS.IOS.MICROPHONE, PERMISSIONS.IOS.CAMERA])
.then((statuses) => {
// The permission check resolves asynchronously, so the user may have already backed out (unmounting this
// component) by the time it settles. Skip the alert to avoid showing a stale permission prompt on the screen they returned to.
if (!isActive) {
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot address #96819 (review).
It's edge case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressing Julesssss' concern about the isActive approach dropping success/error results in this critical flow.

TL;DR: The guards don't drop a success/error in the normal flow — they only fire when the component unmounts before OnfidoSDK.start() settles. In the happy path that never happens, so I'd lean toward keeping them (agreeing with situchan that the drop scenario is a narrow edge case). Details + an alternative below.

Why normal success/error is never dropped: the native Onfido UI presents on top of this still-mounted component (we only render the spinner underneath). So when start() resolves/rejects, this component is still mounted, isActive === true, and the callback runs — the parent only unmounts us as a result of that callback. isActive is false only when something tears this component down before the SDK settles. In practice that's the user tapping Back on the init spinner (the case these guards were added for), where start() comes back as exit/cancel, not a genuine success. A real success/error is dropped only in the edge case situchan flagged: an external Onyx/navigation change unmounts the flow while the native modal is still up.

Why I'd keep the guards rather than remove them: the callbacks aren't pure "record the result" — several navigate or show global UI, which is exactly what breaks if they run after unmount. So the guards are actively preventing the stale-navigation / stale-toast bugs raised earlier in this review.

Per-caller side effects of each callback (why the guards matter)
  • onUserExit → Navigation.goBack() (OnfidoStep), onBackButtonPress() + setOnfidoKey(...) React state (requestor VerifyIdentity). Late call → stale double-navigation / setState-after-unmount. Must stay guarded.
  • onError → global Growl.error(...) on all three callers, plus clearOnfidoToken() + onBackButtonPress() on the requestor page. Late call → a stale toast on whatever screen the user returned to, and a stray navigation.
  • onSuccess → mostly action dispatch (verifyIdentity* + draft writes), which is safe post-unmount — but the requestor page also calls onSubmit?.(), which advances the step.

Net: removing the guards trades a very-rare dropped verification (the user can retry) for visibly-stale navigation/toasts. Since the drop is only reachable via that external-unmount edge case, keeping the current approach seems right.

If you'd rather bias toward never losing a completed verification (Julesssss' preference), the surgical option is to ungard handleSuccess only — the pure recording path. Caveat: on the requestor page onSuccess also calls onSubmit?.() (navigation), so it isn't 100% side-effect-free. Just say the word and I'll push that variant.

Relevant code: guards, permission-alert guard, unmount cleanup.

const isMicAllowed = statuses[PERMISSIONS.IOS.MICROPHONE] === RESULTS.GRANTED;
const isCameraAllowed = statuses[PERMISSIONS.IOS.CAMERA] === RESULTS.GRANTED;
let alertTitle: TranslationPaths | '' = '';
Expand All @@ -81,12 +110,12 @@ function Onfido({sdkToken, onUserExit, onSuccess, onError}: OnfidoProps) {
[
{
text: translate('common.cancel'),
onPress: () => onUserExit(true),
onPress: () => handleUserExit(true),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Skip stale permission alerts after Back

On iOS with camera or microphone permission denied, backing out while OnfidoSDK.start() is pending can still let the async permission-check branch show Alert.alert after this component has unmounted. The fresh evidence after the follow-up fix is that isActive is only checked inside handleUserExit/handleError (including this alert button callback), so the global alert itself is still created on whatever screen the user returned to; skip the permission-alert branch when !isActive before calling Alert.alert.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot is this valid?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, this is valid. The isActive guard added in the follow-up covers handleSuccess/handleUserExit/handleError, but the iOS permission branch calls Alert.alert(...) with no isActive check in front of it.

Since Back is now exposed while OnfidoSDK.start() is pending, this window is reachable: user denies camera/mic → backs out (component unmounts, isActive = false) → start() rejects → the .catch enters the iOS branch → checkMultiple(...).then(...) resolves and fires Alert.alert. Alert.alert is a global native prompt, not tied to this component, so the stale permission alert pops up on whatever screen the user returned to. Guarding only the button onPress callbacks doesn't stop the alert from appearing — it just no-ops the exit action if a button is tapped.

Fix as suggested: short-circuit when unmounted before presenting the alert, e.g. add if (!isActive) { return; } at the top of the checkMultiple(...).then((statuses) => { ... }) callback (line 88), which also keeps the handleError fallback in that same callback from running after unmount.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot address this then

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🤖 Addressed in 45f9f21.

Good catch — the isActive guard was only inside handleUserExit/handleError, so the iOS permission branch still built and presented Alert.alert(...) even after unmount. Added an early if (!isActive) return; at the top of the checkMultiple(...).then(...) callback so the stale permission prompt is skipped once the user has backed out during a pending OnfidoSDK.start():

checkMultiple([PERMISSIONS.IOS.MICROPHONE, PERMISSIONS.IOS.CAMERA])
    .then((statuses) => {
        // The permission check resolves asynchronously, so the user may have already backed out (unmounting this
        // component) by the time it settles. Skip the alert to avoid showing a stale permission prompt on the screen they returned to.
        if (!isActive) {
            return;
        }
        ...

npm run fmt and lint-changed are clean. The typecheck failures in this environment are pre-existing ResultMetadata generic errors in unrelated files (card/sidebar hooks) — none in Onfido/index.native.tsx. This is native-only and can't be exercised on the web build.

},
{
text: translate('common.settings'),
onPress: () => {
onUserExit();
handleUserExit();
goToSettings();
},
},
Expand All @@ -95,20 +124,29 @@ function Onfido({sdkToken, onUserExit, onSuccess, onError}: OnfidoProps) {
);
return;
}
onError(errorMessage);
handleError(errorMessage);
})
.catch(() => {
onError(errorMessage);
handleError(errorMessage);
});
} else {
onError(errorMessage);
handleError(errorMessage);
}
});

return () => {
isActive = false;
};
Comment on lines +137 to +139

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Cancel native Onfido launch after Back exits loading

Fresh evidence after the follow-up fix is that unmount cleanup now only flips isActive; it never cancels the already-issued OnfidoSDK.start(...) call, whose API launches the native flow and only settles the promise when the SDK session succeeds or exits. When a user taps the now-exposed header Back during the initialization spinner, this component unmounts but the native SDK can still present the capture flow over the previous screen; the new guards only suppress later JS callbacks. Please keep Back unavailable until the native flow has presented, or add a real cancellation/launch guard before relying on this cleanup.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot is this valid case?
I think this loading page is hidden by onfido step pages so unlikely to see back button during onfido flow.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Partly valid — the underlying race is real, but the mental model in your rebuttal has one gap worth calling out.

Why it's a real race: I checked the SDK surface — @onfido/react-native-sdk (v15.1.0) exposes no stop()/cancel()/dismiss() method. Once OnfidoSDK.start() fires, the only things that settle it are the native flow succeeding or the user exiting it inside the native UI. Our cleanup only flips isActive, which suppresses the JS callbacks — it can't cancel an in-flight native launch:

return () => {
    isActive = false;
};

So the bot is technically correct that a start() already issued isn't cancelled by unmounting.

The gap in "hidden by onfido step pages": the spinner + Back button are shown before the native Onfido UI presents (during start() init), not during/after it. In that pre-presentation window the native flow isn't up yet, so Back is reachable. Once the native flow presents it covers everything — but the race is precisely about tapping Back before that. So "you won't see Back during the onfido flow" is true; "you can't tap Back before it presents" is not.

But it's low severity, and I'd lean toward deferring rather than blocking:

  • The isActive guards you already added neutralize the dangerous outcomes (no stale navigation or wallet/bank-account mutation from late callbacks).
  • The only residual symptom is cosmetic: on a slow enough init the native capture UI could present over the previous screen after the user left — and they can just exit it, with onUserExit suppressed so no state changes.
  • Whether that window is even reachable depends entirely on the native init duration (token validation + config fetch + camera setup), which I can't measure from code — near-instant on a fast connection, tappable on a slow one.

Since there's no SDK cancel to call, the only way to fully close it is to keep Back unavailable until the native flow presents — which partly works against this PR's goal of exposing Back. Given the guards already prevent the harmful effects, treating this as a follow-up/won't-fix seems reasonable rather than a blocker.

// Onfido should be initialized only once on mount
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return <FullscreenLoadingIndicator />;
return (
<ActivityIndicator
size={CONST.ACTIVITY_INDICATOR_SIZE.LARGE}
style={styles.flex1}
/>
Comment on lines +145 to +148

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Guard pending Onfido start after Back is exposed

Now that this inline ActivityIndicator no longer blocks the header, users can tap Back while OnfidoSDK.start() is still pending, but the effect above has no cleanup/ignore-after-unmount guard. In the native callers I checked, those late callbacks still navigate or mutate wallet/bank-account state (OnfidoStep passes goBack/verifyIdentity, and the verify-identity pages update drafts or call onBackButtonPress), so backing out during initialization can still let a later SDK resolve/reject open the flow, navigate a second time, or submit/show an error after the user has left. Please cancel or ignore the pending promise after unmount before exposing Back during loading.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🤖 Addressed in 1238fa0.

Good catch — with Back now tappable during loading, a late OnfidoSDK.start() resolve/reject could navigate or mutate wallet/bank-account state after the user has already left. I added an isActive guard that the effect's cleanup flips to false on unmount, and routed every callback (onSuccess / onUserExit / onError, including the Android relaunch path and the iOS permission Alert handlers) through guarded wrappers that no-op after unmount. See src/components/Onfido/index.native.tsx:26-47 and the cleanup at src/components/Onfido/index.native.tsx:133-135.

ActivityIndicator cleanly unmounts and stops rendering; the SDK promise chain itself can't be cancelled, but its callbacks are now ignored once the component is gone, so backing out during initialization no longer double-navigates or submits/errors after exit.

);
}

export default Onfido;
Loading