Skip to content

Remove unsafe assertions from useGeographicalStateAndCountryFromRoute - #100001

Merged
blimpich merged 4 commits into
Expensify:mainfrom
KJ21-ENG:seatbelt/c3-260901-r3
Sep 29, 2026
Merged

blimpich merged 4 commits into
Expensify:mainfrom
KJ21-ENG:seatbelt/c3-260901-r3

Conversation

@KJ21-ENG

@KJ21-ENG KJ21-ENG commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Removes three unsafe type assertions from the address-route helper and adds 14 focused tests. Valid state and country codes update the address fields; missing or invalid values are ignored.

Fixed Issues

$ #94739
PROPOSAL: #94739 (comment)

Tests

The 14 focused hook tests passed, covering valid, missing and invalid values, custom parameter names and inherited values.

To repeat: npm test -- tests/unit/hooks/useGeographicalStateAndCountryFromRoute.test.ts.

Recorded manual coverage: Windows Chrome against the staging API on commit 2cad3b0, including address links and an API-offline segment. Other platform, High Traffic account and logged-out results are not documented here. The existing author checklist is retained; the attached recording does not establish those additional results.

Offline tests

Load the PR build and address form while online. Disconnect the network, then repeat the valid and invalid address-link checks below. Valid values should still update the fields; invalid values should leave existing fields unchanged. Reconnect afterward. Record network failures separately from JavaScript errors. If the app cannot load a route while offline, report that limitation rather than marking the case passed.

QA Steps

Use a build containing this PR while already signed in. Paste each path below into that build's URL and hard-reload after navigating so the query parameter reaches the address page. These checks do not require saving the address. The logged-out sign-in flow currently drops the query parameter on main, so it does not exercise this hook.

  1. Open /settings/profile/address. Note the existing Country and State values so a saved or default value is not mistaken for a value supplied by the URL.
  2. Open /settings/profile/address?country=US. Confirm Country shows United States.
  3. With Country set to United States, open /settings/profile/address?state=MO. Confirm State shows Missouri.
  4. Test the State parameter with state=ASDF, state=, state=constructor and state=MO-hash-a12341, using the same address path. Before each case, note the current fields. Confirm the invalid value does not replace them and the page does not crash.
  5. Repeat for Country with country=XX, country=, country=toString and country=US-hash-a12341. Also open the address path without query parameters. Existing or default values may remain; invalid values must not become selections.

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Reported Windows Chrome walkthrough against the staging API at commit 2cad3b0. It covers valid, invalid, empty, prototype-key and hash-suffixed address parameters, plus API-offline checks. Expected network failures appear during the offline segment. This recording does not demonstrate other platforms or logged-out coverage.

PR100001-v2-correction-walkthrough-8x-captioned.mp4

@KJ21-ENG KJ21-ENG changed the title Remove unsafe type assertions from geographical route parameters Remove unsafe assertions from useGeographicalStateAndCountryFromRoute Sep 1, 2026
@KJ21-ENG
KJ21-ENG marked this pull request as ready for review September 28, 2026 15:13
@KJ21-ENG
KJ21-ENG requested review from a team as code owners September 28, 2026 15:13
@melvin-bot

melvin-bot Bot commented Sep 28, 2026

Copy link
Copy Markdown

@ikevin127 Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot
melvin-bot Bot requested review from a team and removed request for a team September 28, 2026 15:13

@dylanexpensify dylanexpensify left a comment

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.

Performance related, product input not required

@ikevin127

ikevin127 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Screen.Recording.2026-09-28.at.16.29.53.mov

Comment on lines +11 to +17
function isState(value: string): value is State {
return Object.hasOwn(COMMON_CONST.STATES, value);
}

function isCountry(value: string): value is Country {
return Object.hasOwn(CONST.ALL_COUNTRIES, value);
}

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.

🟢 src/hooks/useGeographicalStateAndCountryFromRoute.ts:11-17 - fold the typeof check into the guards.

The call sites carry a narrowing step that belongs inside the predicate:

state: typeof stateFromUrl === 'string' && isState(stateFromUrl) ? COMMON_CONST.STATES[stateFromUrl].stateISO : undefined,
country: typeof countryFromUrl === 'string' && isCountry(countryFromUrl) ? countryFromUrl : undefined,

routeParams[stateParamName] is unknown, so the typeof is load-bearing, but it is the guard's job. Taking unknown removes it from both call sites and makes each predicate self-contained:

function isState(value: unknown): value is State {
    return typeof value === 'string' && Object.hasOwn(COMMON_CONST.STATES, value);
}

function isCountry(value: unknown): value is Country {
    return typeof value === 'string' && Object.hasOwn(CONST.ALL_COUNTRIES, value);
}

return {
    state: isState(stateFromUrl) ? COMMON_CONST.STATES[stateFromUrl].stateISO : undefined,
    country: isCountry(countryFromUrl) ? countryFromUrl : undefined,
};

Same behavior, and the non-string values test case already covers it.

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.

Done. Both guards now accept unknown and check typeof value === 'string' internally. The call sites use the guards directly. The non-string test still passes on the updated head.

type StateAndCountry = {state?: State; country?: Country};

function isState(value: string): value is State {
return Object.hasOwn(COMMON_CONST.STATES, value);

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.

🟢 src/hooks/useGeographicalStateAndCountryFromRoute.ts:12 and :16 - say why it is Object.hasOwn and not hasKey.

ObjectUtils sits right next to isRecord in the same import and exports hasKey, so the next person who touches this will reasonably reach for it. That swap silently reopens the prototype hole this PR just closed, and the prototype keys test is the only thing that would catch it.

One line makes the constraint explicit:

// `Object.hasOwn` rather than `in` or `ObjectUtils.hasKey`: the prototype chain would match
// `constructor` and `toString`, which are not states and would type-narrow incorrectly.
function isState(value: unknown): value is State {

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.

Added a comment explaining that own-key checks prevent prototype properties such as constructor and toString from being treated as state or country codes. The prototype-key test passes.

@@ -1,4 +1,5 @@
import CONST from '@src/CONST';
import {isRecord} from '@src/libs/ObjectUtils';

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.

🟢 src/hooks/useGeographicalStateAndCountryFromRoute.ts:2 - import path should be @libs/ObjectUtils

Every other isRecord consumer uses @libs/ObjectUtils (Navigation.ts, GetStateForActionHandlers.ts, OAuthClient.ts, getPendingReceiptRequests.native.ts). The only @src/libs/ outlier is a pre-existing one in Table/middlewares/filtering.ts.

No functional difference, but this is a fresh import line so it may as well match.

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.

Done. The import now uses @libs/ObjectUtils, and the changed files pass ESLint and formatting checks.

@ikevin127

Copy link
Copy Markdown
Contributor

Note

Not a blocker for this PR, but please merge main before we merge this.

While testing the logged-out deeplink flow I hit a not-found on your branch:

  1. Log out
  2. Navigate to /settings/profile/address?state=IL
  3. Enter email and sign in
  4. Lands on /not-found?state=IL showing "Hmm... it's not here"

I checked the same flow on staging and it does not reproduce there. Staging resolves to /settings/profile/address and shows the already-saved value.

This is not caused by your change. The hook only runs inside AddressPage via StateSelector.tsx:50 and CountrySelector.tsx:44, so on a not-found render it never executes, and this PR touches no routing or session file.

The cause is the branch base. This branch is 9240 commits behind main (base is from around Sept 1), and the post-signin redirect machinery was reworked in that window:

File base → main
src/libs/actions/Session/index.ts +181 / −69
src/libs/Navigation/linkingConfig/config.ts +147 / −4
src/libs/Navigation/linkingConfig/subscribe.ts +8 / −1
src/libs/Navigation/helpers/getAdaptedStateFromPath.ts +1 / −1

The exitTo handling in particular now resets the root through getAdaptedStateFromPath(exitTo) rather than the older Navigation.goBack(ROUTES.HOME) path. The SETTINGS_ADDRESS linking entry itself is unchanged, so the difference is purely in how the deeplink is restored after sign-in.

What I need before merge:

  1. Merge latest main into this branch and confirm the not-found no longer reproduces locally.
  2. Re-record the walkthrough afterwards. The current recording is against commit 2cad3b0, which predates a month of main, so it no longer demonstrates behavior on what we would actually ship. This also makes the already-ticked checklist item "If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected" accurate.

Separately, and worth noting for QA rather than for you to fix here: on current main the logged-out deeplink drops the query parameter entirely, so ?state=IL never reaches the hook and the saved value is shown instead. That flow fails gracefully rather than 404ing, but the parameter is still lost. If it is meant to work, that is a pre-existing bug for its own issue and is unrelated to this PR.

Please also drop the logged-out variant from QA step 6, since the parameter cannot survive sign-in today. Testing the hook while already signed in (paste the URL, then hard-reload on it) covers what this PR actually changes.

cc @KJ21-ENG

@ikevin127 ikevin127 left a comment

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.

🟢 LGTM - Clean PR. Code is correct and behavior-preserving; ☝️ findings are all polish, and the merging of main issue should be addressed before this is merged.

@melvin-bot
melvin-bot Bot requested a review from blimpich September 28, 2026 23:55
@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

All contributors have signed the CLA ✍️ ✅
Posted by the CLA Assistant Lite bot.

@KJ21-ENG
KJ21-ENG marked this pull request as draft September 29, 2026 11:19
@KJ21-ENG
KJ21-ENG force-pushed the seatbelt/c3-260901-r3 branch from 0a00eeb to 1583977 Compare September 29, 2026 11:22

@KJ21-ENG KJ21-ENG left a comment •

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.

@ikevin127 Thanks for the review. I addressed the three polish suggestions and merged main.

@KJ21-ENG
KJ21-ENG marked this pull request as ready for review September 29, 2026 12:05
@blimpich
blimpich merged commit a496d91 into Expensify:main Sep 29, 2026
42 of 46 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

🚧 blimpich has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify

Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/blimpich in version: 9.4.96-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 cancelled 🔪
🍎 iOS 🍎 cancelled 🔪

@MelvinBot

Copy link
Copy Markdown
Contributor

No help site update is needed: this PR is an internal type-safety fix to how the address page reads state and country URL parameters, and no help article describes that behavior.


view run

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/blimpich in version: 9.4.99-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@MelvinBot

Copy link
Copy Markdown
Contributor

No help site update is needed. This PR hardens how the address page validates the state and country URL parameters. It changes nothing users see in normal use, and no article under docs/articles mentions these parameters.


view run

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/Julesssss in version: 9.4.99-2 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Bundle Size Analysis (Sentry):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants