App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-11-24] [$175] [Sentry: APP-NZR] TypeError: Cannot read properties of undefined (reading 'toLowerCase')

Open MelvinBot opened this issue 3 weeks ago • 27 comments

Summary

Editing the receipt requirement amount can throw an unhandled TypeError when a keyboard event has no nativeEvent.key.

Sentry: https://expensify.sentry.io/issues/APP-NZR

Reported impact: 1 user, 2 events; first seen November 8, 2026 at 19:36 UTC.

Platform: Web, Chrome Mobile on Android, standalone. Release: 9.5.33 Route: /workspaces/:policyID/rules/require-receipts Mechanism: Unhandled (onerror), level error.

Error and first-party frames

TypeError: Cannot read properties of undefined (reading 'toLowerCase')

src/components/AmountEditingController/utils.ts:26 — isForwardDeleteKeyPress
  const key = event.nativeEvent.key.toLowerCase();
src/components/AmountEditingController/hooks/useAmountSelection.ts:75
  forwardDeletePressedRef.current = isForwardDeleteKeyPress(event);
AmountFormFieldInput.tsx:39 — handleInputKeyPress
  handleKeyPress(event);
react-native-web TextInput handleKeyDown → onKeyPress(e)

Root cause

AmountEditingController/utils.ts:25–39 calls event.nativeEvent.key.toLowerCase() without checking that key is a string. The amount input forwards keyboard events into this helper, so an undefined key throws instead of being treated as a non-forward-delete event.

Mobile Chrome/IME behavior is a suspected trigger, not confirmed. Exact UI reproduction steps have not been established.

Expected behavior

Receipt-threshold editing should not throw when a keyboard event has a missing or non-string key.

Suggested fix

  • Return false for missing/non-string keys before calling toLowerCase().
  • Add regression coverage for missing/non-string keys and existing forward-delete shortcuts.

Parent tracker: [Tracking] Top Sentry crashes monthly check-in

Slack thread: https://expensify.slack.com/archives/C027V2LD9D1/p1794236798557059

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @mallenexpensify

MelvinBot avatar Nov 09 '26 18:11 MelvinBot

Triggered auto assignment to Contributor-plus team member for initial proposal review - @parasharrajat (External)

melvin-bot[bot] avatar Nov 09 '26 18:11 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022119865281675410521

melvin-bot[bot] avatar Nov 09 '26 18:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

Typing in the receipt requirement amount field (/workspaces/:policyID/rules/require-receipts) can crash with TypeError: Cannot read properties of undefined (reading 'toLowerCase') when the keyboard event reaching the amount editor has no nativeEvent.key, which Sentry shows on Chrome for Android.

What is the root cause of that problem?

Some keyboard events on Android Chrome (likely IME or autofill, as the issue notes) arrive without a key. react-native-web's TextInput passes those events on to onKeyPress unchanged. The amount editor then assumes key is always a string:

  • isForwardDeleteKeyPress in src/components/AmountEditingController/utils.ts calls event.nativeEvent.key.toLowerCase() with no check (line 26). It's called from handleKeyPress in hooks/useAmountSelection.ts, which is the stack in Sentry.
  • handleKeyPress in src/components/AmountEditingController/hooks/useDetachedSignEditingController.ts (line 78) does the same event.nativeEvent.key.toLowerCase() before delegating to the controller. Any input that uses the detached sign controller would hit the same crash one frame earlier.

AmountEditingKeyPressEvent in types.ts types key as a plain string, so TypeScript doesn't flag either call.

What changes do you think we should make in order to solve the problem?

  1. In utils.ts, add a small helper, e.g. getNormalizedKey(event), that returns event.nativeEvent?.key lowercased when it's a string and '' otherwise. Use it in isForwardDeleteKeyPress, so a missing key simply returns false (not a forward delete).
  2. Use the same helper in useDetachedSignEditingController.ts's handleKeyPress, so the backspace check is skipped and the event still goes on to controller.handleKeyPress.
  3. Change key in AmountEditingKeyPressEvent to key?: string so the types match what the browser actually sends and future callers have to handle it.

Forward-delete (Delete, Ctrl+D on macOS/iOS, the iOS Safari accessibility Ctrl case) and backspace sign deletion keep working as before.

What specific scenarios should we cover in automated tests?

In tests/unit/components/AmountEditingControllerUtilsTest.ts:

  • isForwardDeleteKeyPress returns false and doesn't throw when nativeEvent.key is undefined, a non-string, or 'Unidentified'.
  • The existing Delete and macOS Ctrl+D cases still return true.

In tests/unit/components/useDetachedSignEditingControllerTest.tsx:

  • handleKeyPress with a missing key doesn't throw, doesn't delete the sign, and still forwards the event to the base controller.

What alternative solutions did you explore? (Optional)

Using optional chaining at each call site (event.nativeEvent.key?.toLowerCase()). That fixes the crash too, but one shared helper plus the optional type is safer, because both call sites behave the same and the compiler catches new ones.

fitzyracing1 avatar Nov 09 '26 19:11 fitzyracing1

Proposal

What is the root cause of that problem?

There are two affected call sites in the amount editing controller pipeline where event.nativeEvent.key.toLowerCase() is called without verifying that key is a valid string:

1. Forward-delete keypress detector (src/components/AmountEditingController/utils.ts:25-27)

function isForwardDeleteKeyPress(event: AmountEditingKeyPressEvent): boolean {
    const key = event.nativeEvent.key.toLowerCase();

In React Native Web's TextInput keyboard pipeline, Android Chrome virtual keyboards, composition/IME events, and autofill often emit synthetic key events where nativeEvent.key is undefined (or empty/non-string). Calling .toLowerCase() directly on undefined throws TypeError: Cannot read properties of undefined (reading 'toLowerCase').

2. Detached-sign controller handler (src/components/AmountEditingController/hooks/useDetachedSignEditingController.ts:77-85)

const handleKeyPress = (event: AmountEditingKeyPressEvent) => {
    const key = event.nativeEvent.key.toLowerCase();

    if (key === 'backspace') {
        deleteSignBeforeCaret();
    }

    controller.handleKeyPress(event);
};

useDetachedSignEditingController performs the exact same unsafe .toLowerCase() operation. Any amount screen utilizing detached signs (such as negative expenses or detached currency sign controllers) crashes with the identical unhandled TypeError when an IME or autofill key event arrives.

3. Strict typing masks optionality (src/components/AmountEditingController/types.ts:7-12)

type AmountEditingKeyPressEvent = {
    nativeEvent: {
        key: string;
        ctrlKey?: boolean;
    };
};

Because key is typed as a required string, TypeScript does not warn developers that browser/native synthetic events can dispatch with key omitted or undefined.


What changes do you think we should make in order to solve the problem?

1. Guard rawKey in isForwardDeleteKeyPress (src/components/AmountEditingController/utils.ts:25-37)

Safely check that rawKey is a string before calling .toLowerCase(). If missing or non-string, return false early:

function isForwardDeleteKeyPress(event: AmountEditingKeyPressEvent): boolean {
    const rawKey = event.nativeEvent.key;
    if (typeof rawKey !== 'string') {
        return false;
    }

    const key = rawKey.toLowerCase();
    if (isMobileSafari() && key === CONST.PLATFORM_SPECIFIC_KEYS.CTRL.DEFAULT) {
        // ...
    }
}

2. Guard useDetachedSignEditingController with unconditional delegation (src/components/AmountEditingController/hooks/useDetachedSignEditingController.ts:77-85)

const handleKeyPress = (event: AmountEditingKeyPressEvent) => {
    const key = event.nativeEvent.key;

    if (typeof key === 'string' && key.toLowerCase() === 'backspace') {
        deleteSignBeforeCaret();
    }

    controller.handleKeyPress(event);
};

Critical Architectural Invariant: controller.handleKeyPress(event) must always be called unconditionally, even when key is missing or malformed. In useAmountSelection.ts:74-76, handleKeyPress updates forwardDeletePressedRef.current = isForwardDeleteKeyPress(event). If a malformed key event were dropped without delegating, any previous forward-delete flag would remain stale and incorrectly offset the caret on subsequent edits! Unconditional delegation resets the flag safely.

3. Update type definition in types.ts (src/components/AmountEditingController/types.ts:7-12)

type AmountEditingKeyPressEvent = {
    nativeEvent: {
        key?: string;
        ctrlKey?: boolean;
    };
};

What alternative solutions did you explore? (Optional)

  • Only guarding isForwardDeleteKeyPress (competitor approach): Leaves useDetachedSignEditingController completely exposed to the exact same production crash.
  • Optional chaining without type check (event?.nativeEvent?.key?.toLowerCase()): While safe against undefined, it still throws if key is passed as a non-string object/number from unexpected native bridge event structures. Using typeof rawKey !== 'string' is standard in Expensify core libraries.

What automated tests can you add to prevent this from re-occurring?

  1. In tests/unit/components/AmountEditingControllerUtilsTest.ts: Add tests under describe('isForwardDeleteKeyPress'):

    it('returns false without throwing when key is undefined, null, or missing', () => {
        expect(isForwardDeleteKeyPress({nativeEvent: {}} as AmountEditingKeyPressEvent)).toBe(false);
        expect(isForwardDeleteKeyPress({nativeEvent: {key: undefined}} as unknown as AmountEditingKeyPressEvent)).toBe(false);
        expect(isForwardDeleteKeyPress({nativeEvent: {key: null}} as unknown as AmountEditingKeyPressEvent)).toBe(false);
    });
    
  2. In tests/unit/components/useDetachedSignEditingControllerTest.tsx: Add a test verifying that handleKeyPress gracefully handles keyless events and still delegates to the underlying controller without throwing:

    it('handles malformed keypress events without throwing and clears forward-delete state', () => {
        const {result} = renderController({value: '10'});
        expect(() => {
            act(() => result.current.handleKeyPress({nativeEvent: {}} as AmountEditingKeyPressEvent));
        }).not.toThrow();
    });
    

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 09 '26 19:11 kevinjosh10

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 09 '26 19:11 melvin-bot[bot]

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 09 '26 19:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

When editing an amount input managed by AmountEditingController (such as workspace receipt requirement rules at /workspaces/:policyID/rules/require-receipts), keyboard events where nativeEvent.key is missing or undefined (common on Mobile Chrome on Android, virtual IME keyboards, and autofill) trigger an unhandled runtime error: TypeError: Cannot read properties of undefined (reading 'toLowerCase').

What is the root cause of that problem?

  1. In src/components/AmountEditingController/utils.ts (line 26), isForwardDeleteKeyPress directly calls event.nativeEvent.key.toLowerCase() without verifying that key is defined or of type string.
  2. In src/components/AmountEditingController/hooks/useDetachedSignEditingController.ts (line 78), handleKeyPress also directly calls event.nativeEvent.key.toLowerCase() to check for 'backspace' before delegating to the base controller, causing the same unhandled TypeError when key is undefined.
  3. In src/components/AmountEditingController/types.ts (line 9), AmountEditingKeyPressEvent types key as a non-optional string, which does not reflect the reality of browser/React Native Web synthetic keyboard events on mobile platforms where key can be omitted.

What changes do you think we should make in order to solve the problem?

  1. In src/components/AmountEditingController/types.ts: Update AmountEditingKeyPressEvent to type key?: string to reflect optional key data on synthetic keyboard events.
  2. In src/components/AmountEditingController/utils.ts: In isForwardDeleteKeyPress, guard event?.nativeEvent?.key: if it is not a valid string, return false early so the event is safely treated as a non-forward-delete keypress.
  3. In src/components/AmountEditingController/hooks/useDetachedSignEditingController.ts: In handleKeyPress, safely check if event.nativeEvent.key?.toLowerCase() === 'backspace' before calling deleteSignBeforeCaret(), and continue delegating to controller.handleKeyPress(event).
  4. In tests/unit/components/AmountEditingControllerUtilsTest.ts: Add test coverage asserting that isForwardDeleteKeyPress returns false and does not throw when key is undefined or omitted.
  5. In tests/unit/components/useDetachedSignEditingControllerTest.tsx: Add test coverage asserting that handleKeyPress safely handles events where key is undefined without throwing.

What alternative solutions did you explore? (Optional)

Creating a separate shared getNormalizedKey helper function. However, direct safe type guards at the two consumer sites are cleaner, more idiomatic TypeScript, and avoid adding extra exported utility overhead.

Contributor details

Your Expensify account email: [email protected]

gorky117-cell avatar Nov 09 '26 19:11 gorky117-cell

📣 @gorky117-cell! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 09 '26 19:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~013bdd0475abb70c10

gorky117-cell avatar Nov 09 '26 19:11 gorky117-cell

⚠️ Invalid email. Please make sure to create an Expensify account with this email first here.

melvin-bot[bot] avatar Nov 09 '26 19:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~013bdd0475abb70c10

gorky117-cell avatar Nov 09 '26 19:11 gorky117-cell

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 09 '26 19:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

Editing the receipt requirement amount (/workspaces/:policyID/rules/require-receipts) can throw an unhandled TypeError: Cannot read properties of undefined (reading 'toLowerCase') when a keyboard event has no nativeEvent.key (seen on mobile Chrome/IME events).

What is the root cause of that problem?

isForwardDeleteKeyPress in src/components/AmountEditingController/utils.ts calls event.nativeEvent.key.toLowerCase() with no guard that key is a string. It is called from useAmountSelection.ts:75 via handleInputKeyPress on every keypress, so any event with a missing or non-string key throws instead of being treated as a non-forward-delete event. Verified against the current source on main.

What changes do you think we should make in order to solve the problem?

Return false early in isForwardDeleteKeyPress when event.nativeEvent.key is not a string, before calling toLowerCase(). No behaviour change for real keys — Delete and Ctrl+D on Mac/iOS still return true as before.

What alternative solutions did you explore? (Optional)

Guarding at the caller in useAmountSelection.ts was considered, but the helper is the single place every keypress flows through, so guarding there covers all current and future callers.

How will you verify the fix?

Add regression tests for a missing key and a non-string key (both must return false without throwing), plus the existing forward-delete cases (Delete, Ctrl+D on Mac/iOS). Then verify on the receipt-threshold page that editing the amount no longer throws on such events, and run the AmountEditingController test suite.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01c5c6bc0e7d162f7b

khizzcr7 avatar Nov 10 '26 00:11 khizzcr7

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 10 '26 00:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

Sentry error APP-NZR: TypeError: Cannot read properties of undefined (reading 'toLowerCase').

What is the root cause of that problem?

In src/libs/OptionsListUtils.ts or search filter helpers: A string search comparator calls .toLowerCase() on an optional field (such as option.text, option.alternateText, or report.reportName) without nullish coalescing or optional chaining (option?.text?.toLowerCase()), leading to an uncaught TypeError when an option item has undefined text or is missing attributes.

What changes do you think we should make in order to solve the problem?

  1. In src/libs/OptionsListUtils.ts:
    • Replace direct .toLowerCase() calls with optional chaining and fallback empty string: (option.text ?? '').toLowerCase() or (option.alternateText ?? '').toLowerCase().
  2. Add defensive guards across all text-matching helper functions handling user-generated option collections.

What alternative solutions did you explore? (Optional)

Ensuring all upstream data sources always populate strings, which is vulnerable to corrupt or partial Onyx records.

TassioSales avatar Nov 11 '26 13:11 TassioSales

@MelvinBot Propose solution here.

parasharrajat avatar Nov 11 '26 15:11 parasharrajat

Proposal

What is the root cause of that problem?

The amount editor calls event.nativeEvent.key.toLowerCase() without checking whether key is a string. A missing key therefore produces the exact reported exception.

There are two affected handlers: the forward-delete helper in the reported stack and the detached-sign controller, which performs the same unsafe operation before forwarding the event.

Code evidence

This explains the supplied Sentry stack; option-search filtering does not. The exact keyboard/IME trigger remains unconfirmed.

What changes do you think we should make in order to solve the problem?

  1. Guard both handlers with a string-type check. The forward-delete helper should return false for missing/non-string keys.
  2. In the detached-sign handler, only perform backspace sign deletion for a valid string key. Always forward the event to the base controller, including malformed keys, so its previous forward-delete state is cleared.
  3. Make key optional in the local event type. Retain runtime type guards to handle unexpected non-string values.
  4. Add regression tests covering:
    • Missing, undefined, null, and non-string keys without exceptions.
    • No accidental sign deletion.
    • Forward-delete state resetting after a malformed event.
    • Existing Delete, macOS/iOS Ctrl+D, Safari accessibility Control, and Backspace behavior.

The existing three relevant unit suites passed: 84 tests. No code was changed, and the production keyboard sequence was not reproduced.

What alternative solutions did you explore? (Optional)

Optional chaining alone handles missing keys but still throws for non-string values. Guarding only the forward-delete helper leaves the detached-sign handler vulnerable. Unrelated option-filter changes would not address this stack.


Next Steps for Contributor+ team: To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106409) to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.


view run

MelvinBot avatar Nov 11 '26 15:11 MelvinBot

Hi @parasharrajat, my proposal from Nov 9 already covers this exact solution—guarding both isForwardDeleteKeyPress and useDetachedSignEditingController, updating the AmountEditingKeyPressEvent type, and adding regression tests for missing/undefined keys.

I have the branch and unit test suite tested and ready to open as a PR immediately if assigned. Thank you!

gorky117-cell avatar Nov 11 '26 16:11 gorky117-cell

@gorky117-cell we don't accept proposals like that. Please read contributing guidelines

parasharrajat avatar Nov 11 '26 16:11 parasharrajat

@MelvinBot What is your suggested code change for your proposal here https://github.com/Expensify/App/issues/106409#issuecomment-6800264016

parasharrajat avatar Nov 11 '26 17:11 parasharrajat