Skip to content

[Payment due @ikevin127] [HOLD on https://github.com/Expensify/react-native-onyx/pull/848] fix: export Onyx state through Onyx - #101568

Open
chrispader wants to merge 12 commits into
Expensify:mainfrom
margelo:@chrispader/fix/export-onyx-state-via-onyx
Open

chrispader wants to merge 12 commits into
Expensify:mainfrom
margelo:@chrispader/fix/export-onyx-state-via-onyx

Conversation

@chrispader

@chrispader chrispader commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

Exporting Onyx state currently opens OnyxDB directly from Expensify, creating a second connection to storage that Onyx already owns. NitroSQLite 9.8.2 rejects that duplicate open, so the Troubleshoot export can fail without producing a file. This prerequisite makes both native and web exports read through Onyx while keeping masking and file sharing in Expensify.

@NicolasBonet @ikevin127

Explanation of Change

Pin react-native-onyx to the head of Onyx PR #848 until that change is released. ExportOnyxState/index.ts exports the shared read and file-saving functions directly and re-exports masking from masking.ts. A small saveTextFile helper handles the platform difference: it reuses localFileCreate to stage a Blob download on web or a temporary share-sheet file on native, then removes the temporary resource. I did not reuse localFileDownload because it saves to Android's public Downloads directory and swallows errors, whereas this export shares from the app cache and reports failures.

The focused export tests pass locally. The isolated install still has TypeScript/ESLint dependency errors outside these files, so those checks depend on CI.

This PR is a prerequisite for the NitroSQLite 9.8.2 upgrade. After the Onyx PR is merged and published, replace the Git pin with its released version before merging this PR.

Fixed Issues

Related prerequisite; the upgrade PR fixes the issue: #101448

No separate approved proposal applies to this prerequisite.

Tests

  1. Open Settings → Troubleshoot and export Onyx state on native and web. Verify a file is available to share or download and its contents contain the expected Onyx keys.
  2. With masking enabled, verify sensitive values in the exported file are masked. Use a test account and do not share an unmasked export.
  3. Repeat while offline; exporting local state should still work. If storage or file sharing fails, verify an error dialog appears.
  4. Verify no errors appear in the JS console during the successful export.

Manual device and browser verification is pending.

Offline tests

  1. Sign in while online, then disconnect the device or browser.
  2. Export Onyx state from Settings → Troubleshoot. Verify the local state still downloads or opens in the share sheet and that no network connection is required.

Offline verification is pending.

QA Steps

  1. In an Android, iOS, or web staging build containing this PR, open Settings → Troubleshoot and export Onyx state. Verify the file is available to share or download and its sensitive fields are masked.
  2. Repeat while offline. Verify the export still works and no JS console error appears.
  3. After [WIP] [HOLD on #101568] chore(deps): Update NitroSQLite to 9.8.2 #101437 includes this prerequisite, repeat the native export and verify there is no duplicate-connection error.

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 that 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
    • 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, 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

None attached. The normal export UI is unchanged, and manual device/browser verification is still pending.

@github-actions

Copy link
Copy Markdown
Contributor

⚠️ This PR is possibly changing native code and/or updating libraries, it may cause problems with HybridApp. Please check if any patch updates are required in the HybridApp repo and run an AdHoc build to verify that HybridApp will not break. Ask Contributor Plus for help if you are not sure how to handle this. ⚠️

@chrispader chrispader changed the title fix: export Onyx state through Onyx [HOLD on react-native-onyx#848] fix: export Onyx state through Onyx Sep 18, 2026
@codecov

codecov Bot commented Sep 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/libs/ExportOnyxState/index.ts 100.00% <100.00%> (+100.00%) ⬆️
src/libs/ExportOnyxState/masking.ts 80.95% <100.00%> (ø)
src/libs/fileDownload/DownloadUtils.ts 25.00% <100.00%> (+25.00%) ⬆️
src/libs/saveTextFile/index.native.ts 100.00% <100.00%> (ø)
src/libs/saveTextFile/index.ts 100.00% <100.00%> (ø)
...c/pages/settings/Troubleshoot/TroubleshootPage.tsx 77.77% <100.00%> (+77.77%) ⬆️
... and 25 files with indirect coverage changes

@chrispader
chrispader marked this pull request as ready for review September 18, 2026 13:46
@chrispader
chrispader requested review from a team as code owners September 18, 2026 13:46
@melvin-bot
melvin-bot Bot requested review from flaviadefaria and inimaga and removed request for a team September 18, 2026 13:46
@melvin-bot

melvin-bot Bot commented Sep 18, 2026

Copy link
Copy Markdown

@inimaga 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]

@chrispader chrispader changed the title [HOLD on react-native-onyx#848] fix: export Onyx state through Onyx [HOLD on https://github.com/Expensify/react-native-onyx/pull/848] fix: export Onyx state through Onyx Sep 18, 2026
@chrispader
chrispader requested a review from tgolen as a code owner September 18, 2026 18:11

@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.

The core move is right: stop opening OnyxDB a second time, read through Onyx, and collapse two platform-specific ExportOnyxState files into one.

Deleting the hand-rolled IndexedDB cursor and the raw SELECT * is a real simplification, and the web path finally propagates errors instead of hanging forever on a failed indexedDB.open (the old openRequest.onerror was never wired up, so the promise just never settled).

Findings below are ordered by what I would want fixed before approval.

Comment thread src/libs/saveTextFile/index.ts
Comment thread src/libs/saveTextFile/index.ts Outdated
Comment thread src/libs/saveTextFile/index.native.ts Outdated
Comment thread src/pages/settings/Troubleshoot/TroubleshootPage.tsx Outdated
Comment thread src/pages/settings/Troubleshoot/TroubleshootPage.tsx
Comment thread tests/unit/ExportOnyxStateProviderTest.ts
Comment thread src/libs/ExportOnyxState/index.ts Outdated
@chrispader chrispader changed the title [HOLD on https://github.com/Expensify/react-native-onyx/pull/848] fix: export Onyx state through Onyx [WIP] [HOLD on https://github.com/Expensify/react-native-onyx/pull/848] fix: export Onyx state through Onyx Sep 19, 2026
@chrispader chrispader changed the title [WIP] [HOLD on https://github.com/Expensify/react-native-onyx/pull/848] fix: export Onyx state through Onyx [HOLD on https://github.com/Expensify/react-native-onyx/pull/848] fix: export Onyx state through Onyx Sep 19, 2026
@chrispader

Copy link
Copy Markdown
Contributor Author

Addressed all review comments by @ikevin127 !

@chrispader chrispader changed the title [HOLD on https://github.com/Expensify/react-native-onyx/pull/848] fix: export Onyx state through Onyx [WIP] [HOLD on https://github.com/Expensify/react-native-onyx/pull/848] fix: export Onyx state through Onyx Sep 19, 2026
@chrispader chrispader changed the title [WIP] [HOLD on https://github.com/Expensify/react-native-onyx/pull/848] fix: export Onyx state through Onyx [HOLD on https://github.com/Expensify/react-native-onyx/pull/848] fix: export Onyx state through Onyx Sep 19, 2026
"../../src/libs/ExportOnyxState/index.ts" "@typescript-eslint/no-unsafe-type-assertion" 2
"../../src/libs/fileDownload/DownloadUtils.ts" "no-restricted-syntax" 1
"../../src/libs/ExportOnyxState/masking.ts" "@typescript-eslint/no-unsafe-type-assertion" 14
"../../src/libs/fileDownload/DownloadUtils.ts" "no-restricted-syntax" 2

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.

🟡 config/eslint/eslint.seatbelt.tsv

- "../../src/libs/fileDownload/DownloadUtils.ts"       "no-restricted-syntax"  1
+ "../../src/libs/fileDownload/DownloadUtils.ts"       "no-restricted-syntax"  2

This raises the allowance without a matching violation. Verified:

  • main's seatbelt for that file is 1.
  • At PR head 672f7277, DownloadUtils.ts has exactly one import * as (import * as ApiUtils from '@libs/ApiUtils'), which is the single ImportNamespaceSpecifier violation. openExternalLink is a named import, matching main.
  • I read all three no-restricted-syntax blocks in config/eslint/eslint.config.mjs. The src/** selectors are TSEnumDeclaration, React.forwardRef, four ImportNamespaceSpecifier variants, the Pressable sentryLabel rule, LabeledStatement and WithStatement. None of them match try/finally, setTimeout, link.remove() or export {createDownloadLink}.

So the file should still be 1. CI stays green because the seatbelt is a ceiling, which is exactly why this matters: it silently re-opens room for one more namespace import in a file this PR touches, and nobody will notice.

Most likely a merge artifact from 551329df0 resolving a generated file to the older value. Please re-run the seatbelt regeneration (or set it back to 1) and confirm lint still passes.

Comment on lines +95 to +96
const dataToShare = maskOnyxState(value, shouldMaskOnyxState);
await shareAsFile(JSON.stringify(dataToShare));

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.

🟢 NIT: No success-path assertion at the page level

TroubleshootPageTest.ts sets up a working happy path in beforeEach but every test forces a failure, so nothing ever asserts what shareAsFile receives. Concretely, if someone changed

const dataToShare = maskOnyxState(value, shouldMaskOnyxState);
await shareAsFile(JSON.stringify(dataToShare));

to pass value instead of dataToShare, every test in this PR still passes and the app ships an unmasked Onyx dump containing auth tokens. That is the one regression in this flow with a real security consequence, and it is one assertion away:

it('shares the masked state', async () => {
    render(React.createElement(TroubleshootPage));

    fireEvent.press(screen.getByRole('button', {name: exportButtonName}));

    await waitFor(() => {
        expect(shareAsFile).toHaveBeenCalledWith(JSON.stringify(maskedState));
    });
    expect(maskOnyxState).toHaveBeenCalledWith(exportedState, undefined);
});

Comment on lines +11 to +19
jest.mock('@libs/ApiUtils', () => ({
getApiRoot: jest.fn(() => 'https://example.com'),
}));
jest.mock('@libs/fileDownload/FileUtils', () => ({
appendTimeToFileName: jest.fn((fileName: string) => fileName),
getFileName: jest.fn((fileName: string) => fileName),
}));
jest.mock('@libs/tryResolveUrlFromApiRoot', () => jest.fn((url: string) => url));
jest.mock('@userActions/Link', () => ({openExternalLink: jest.fn()}));

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.

🟢 NIT: createDownloadLink's home drags the API stack into the test

saveTextFileTest.ts now has to mock four modules that have nothing to do with saving a text file:

jest.mock('@libs/ApiUtils', () => ({getApiRoot: jest.fn(() => 'https://example.com')}));
jest.mock('@libs/fileDownload/FileUtils', () => ({...}));
jest.mock('@libs/tryResolveUrlFromApiRoot', () => jest.fn((url: string) => url));
jest.mock('@userActions/Link', () => ({openExternalLink: jest.fn()}));

purely because importing createDownloadLink pulls in fetchFileDownload's whole dependency tree.

That is fallout from my own suggestion, so I will own it: the cleaner placement is its own module, say src/libs/fileDownload/createDownloadLink.ts, re-exported from DownloadUtils for existing callers. Then saveTextFile imports a pure DOM helper and the mock list collapses.

Not blocking, but worth doing while the code is fresh. Note also that the @userActions/Link mock is already dead: DownloadUtils imports @libs/openExternalLink now, so that mock targets a module this test never loads, and the real @libs/openExternalLink is pulled in unmocked.

import saveTextFileNative from '@libs/saveTextFile/index.native';
import type SaveTextFile from '@libs/saveTextFile/types';

type ShareOptions = {url: string; failOnCancel: boolean};

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.

🟢 NIT: Re-derived type in a test file

type ShareOptions = {url: string; failOnCancel: boolean};

This duplicates react-native-share's own options type. Prefer importing it so the mock's signature tracks the library rather than drifting from it. Same idea as saveTextFileWeb correctly importing the production SaveTextFile type rather than restating it.

@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.

🟢 All seven of my previous comments are addressed. One new issue found, plus three nits.

Merge after the seatbelt line is corrected and swap the git pin github:margelo/react-native-onyx#a9da3ceb. The seatbelt is a one-line fix and the only thing I would hold on.

The other three 🟢 items are polish and can land here or as a follow-up, though the masked-state assertion is cheap enough that I would just add it.

@melvin-bot melvin-bot Bot changed the title [HOLD on https://github.com/Expensify/react-native-onyx/pull/848] fix: export Onyx state through Onyx [Payment due @ikevin127] [HOLD on https://github.com/Expensify/react-native-onyx/pull/848] fix: export Onyx state through Onyx Sep 19, 2026
@melvin-bot

melvin-bot Bot commented Sep 19, 2026

Copy link
Copy Markdown

🎯 @ikevin127, thanks for reviewing and testing this PR! 🎉

A payment issue will be created for your review once this PR is deployed to production.
E/E issue linked to the PR - no internal issue.

If payment is not needed (e.g., regression PR review fix etc), react with 👎 to this comment to prevent the payment issue from being created.

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.

2 participants