Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
9564ca3
Stop exposing app data to the iOS Files app
NicolasBonet Jul 20, 2026
c30cf1c
Fix Jest mocks for new file storage locations
NicolasBonet Jul 20, 2026
bdbf8f3
Move nitro-sqlite patch to subdirectory and document it
NicolasBonet Jul 21, 2026
065abaf
Link upstream and tracking issues in nitro-sqlite patch details
NicolasBonet Jul 21, 2026
9e66396
Bump Mobile-Expensify to restore documentsDirectory declaration
NicolasBonet Jul 21, 2026
68ac36d
Preserve queued receipts and rewrite their persisted paths in the iOS…
NicolasBonet Jul 21, 2026
bb1ce6b
Rewrite odometer image paths in the Documents migration
NicolasBonet Jul 22, 2026
aa78425
Keep Documents visible in the Files app for user downloads
NicolasBonet Jul 23, 2026
9961ef4
Keep queued receipts in Documents so users can see them
NicolasBonet Jul 23, 2026
b69a861
Merge branch 'main' into nicolas-ios-files-app-data-exposure
NicolasBonet Jul 28, 2026
f0135ef
Update Mobile-Expensify submodule to 3c66ebd
NicolasBonet Jul 29, 2026
8247c01
Update Mobile-Expensify submodule to 5b97cab
NicolasBonet Jul 29, 2026
850a538
Merge remote-tracking branch 'origin/main' into nicolas-ios-files-app…
NicolasBonet Jul 29, 2026
1f490f5
Merge branch 'main' into nicolas-ios-files-app-data-exposure
NicolasBonet Aug 3, 2026
12edd32
Merge remote-tracking branch 'origin/main' into nicolas-ios-files-app…
NicolasBonet Aug 7, 2026
4e8c768
Merge remote-tracking branch 'origin/main' into nicolas-ios-files-app…
NicolasBonet Aug 11, 2026
951f42f
Merge remote-tracking branch 'origin/main' into nicolas-ios-files-app…
NicolasBonet Aug 18, 2026
ce966b3
Address review findings on file migration safety
NicolasBonet Aug 18, 2026
ac763e6
Fix CI: restore OSBotify-managed submodule pointer and spellcheck words
NicolasBonet Aug 18, 2026
7c588bc
Split semicolon-joined comments into separate sentences
NicolasBonet Aug 19, 2026
6b78934
Fail migration on attachment record rewrite errors and delete source …
NicolasBonet Aug 19, 2026
a301333
Delete the Onyx state dump once sharing completes
NicolasBonet Aug 20, 2026
16d8f91
Skip attachment record path scan once it has completed
NicolasBonet Aug 20, 2026
ac542bc
Fix lint directive placement and export bucket for migration flag
NicolasBonet Aug 20, 2026
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
9 changes: 8 additions & 1 deletion jest/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,14 @@ jest.mock('react-native-fs', () => ({
res([]);
}),
),
CachesDirectoryPath: jest.fn(),
exists: jest.fn(() => Promise.resolve(false)),
mkdir: jest.fn(() => Promise.resolve()),
moveFile: jest.fn(() => Promise.resolve()),
copyFile: jest.fn(() => Promise.resolve()),
writeFile: jest.fn(() => Promise.resolve()),
DocumentDirectoryPath: '/mock/documents',
CachesDirectoryPath: '/mock/caches',
LibraryDirectoryPath: '/mock/library',
}));

jest.mock('react-native-share', () => ({
Expand Down
20 changes: 19 additions & 1 deletion patches/react-native-nitro-sqlite/details.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# `react-native-nitro-sqlite` patches
# react-native-nitro-sqlite patches

### [react-native-nitro-sqlite+9.6.0+001+dont-mask-original-error-on-rollback-failure.patch](react-native-nitro-sqlite+9.6.0+001+dont-mask-original-error-on-rollback-failure.patch)

Expand All @@ -15,3 +15,21 @@
- Upstream PR/issue: Already fixed upstream in 9.7.0 via https://github.com/margelo/react-native-nitro-sqlite/pull/292. We stay on 9.6.0 because the 9.7.0 podspec force-enables `SQLITE_THREADSAFE=0` on iOS and its new per-database queue breaks second opens of the same database (used by `src/libs/ExportOnyxState/index.native.ts`). The patch can be dropped when those are resolved and we bump.
- E/App issue: https://github.com/Expensify/App/issues/97908
- PR introducing patch: https://github.com/Expensify/App/pull/97954

### [react-native-nitro-sqlite+9.6.0+002+store-database-outside-documents.patch](react-native-nitro-sqlite+9.6.0+002+store-database-outside-documents.patch)

- Reason:

```
The library stores SQLite databases in the iOS Documents directory, which is exposed to users
via the Files app when file sharing is enabled. This patch stores databases in
Library/Application Support instead (persistent, backed up, never user-visible) and migrates
databases created by older app versions out of Documents on first launch. The database and its
-wal/-shm journal files are copied as a set before the originals are deleted, and if the copy
fails the database keeps being opened from Documents and the migration retries on the next
launch, so committed writes are never separated from their WAL.
```

- Upstream PR/issue: https://github.com/margelo/react-native-nitro-sqlite/issues/289
- E/App issue: https://github.com/Expensify/App/issues/96649
- PR introducing patch: https://github.com/Expensify/App/pull/96531
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
diff --git a/node_modules/react-native-nitro-sqlite/ios/OnLoad.mm b/node_modules/react-native-nitro-sqlite/ios/OnLoad.mm
index 6ce7258..65c29cb 100644
--- a/node_modules/react-native-nitro-sqlite/ios/OnLoad.mm
+++ b/node_modules/react-native-nitro-sqlite/ios/OnLoad.mm
@@ -10,6 +10,63 @@
using namespace margelo::nitro;
using namespace margelo::nitro::rnnitrosqlite;

+// The Documents directory can be exposed to the user (Files app) when file sharing
+// is enabled, so databases are stored in Library/Application Support instead.
+// Databases created by older app versions are moved out of Documents on first launch.
+//
+// The "OnyxDB" name must match the database the app opens: DEFAULT_DB_NAME in
+// src/CONST/index.ts and DB_NAME in react-native-onyx's SQLiteProvider. A Jest test
+// (MoveFilesOutOfDocumentsTest) fails if the names drift apart.
+static void migrateDatabaseFiles(NSString *fromDirectory, NSString *toDirectory) {
+ NSFileManager *fileManager = [NSFileManager defaultManager];
+ NSArray<NSString *> *databaseFiles = @[ @"OnyxDB", @"OnyxDB-wal", @"OnyxDB-shm" ];
+
+ if (![fileManager fileExistsAtPath:[fromDirectory stringByAppendingPathComponent:@"OnyxDB"]]) {
+ // Nothing to migrate. A previous run may have been interrupted after copying the set but
+ // before removing the journal files, so sweep any leftovers out of Documents.
+ [fileManager removeItemAtPath:[fromDirectory stringByAppendingPathComponent:@"OnyxDB-wal"] error:nil];
+ [fileManager removeItemAtPath:[fromDirectory stringByAppendingPathComponent:@"OnyxDB-shm"] error:nil];
+ return;
+ }
+
+ // A database in Documents means an older build was writing there, so it is the live copy.
+ // Remove whatever sits at the destination (e.g. after a downgrade and re-upgrade) so a -wal
+ // from one database generation is never replayed into a database from another.
+ for (NSString *file in databaseFiles) {
+ [fileManager removeItemAtPath:[toDirectory stringByAppendingPathComponent:file] error:nil];
+ }
+
+ // Copy the whole set before deleting anything: committed-but-uncheckpointed writes live in
+ // the -wal file and SQLite only replays it when it sits next to its database, so the files
+ // must never be separated. If any copy fails, the intact originals in Documents keep being
+ // used (see the fallback in +load) and the migration retries on the next launch.
+ for (NSString *file in databaseFiles) {
+ NSString *sourcePath = [fromDirectory stringByAppendingPathComponent:file];
+ if (![fileManager fileExistsAtPath:sourcePath]) {
+ continue;
+ }
+
+ NSError *error = nil;
+ if (![fileManager copyItemAtPath:sourcePath toPath:[toDirectory stringByAppendingPathComponent:file] error:&error]) {
+ NSLog(@"Failed to migrate database file %@: %@", file, error.localizedDescription);
+ return;
+ }
+ }
+
+ // The database file is deleted first, and the journals only once that succeeds: if the
+ // database cannot be removed, the existence check in +load keeps using the source database
+ // on this launch, so its -wal must stay next to it or committed writes would be lost.
+ // An interruption after the first delete can only leave journal files behind, which the
+ // sweep above removes on the next launch.
+ NSError *removeError = nil;
+ if (![fileManager removeItemAtPath:[fromDirectory stringByAppendingPathComponent:@"OnyxDB"] error:&removeError]) {
+ NSLog(@"Failed to remove migrated database from its old location: %@", removeError.localizedDescription);
+ return;
+ }
+ [fileManager removeItemAtPath:[fromDirectory stringByAppendingPathComponent:@"OnyxDB-wal"] error:nil];
+ [fileManager removeItemAtPath:[fromDirectory stringByAppendingPathComponent:@"OnyxDB-shm"] error:nil];
+}
+
+ (void)load {
// Get appGroupID value from Info.plist using key "AppGroup"
NSString *appGroupID = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"RNNitroSQLite_AppGroup"];
@@ -30,9 +80,24 @@

documentPath = [storeUrl path];
} else {
- // Get iOS app's document directory (to safely store database .sqlite3 file)
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true);
+ // Store databases in Library/Application Support, which is persistent, backed up,
+ // and never exposed to the user via the Files app (unlike the Documents directory)
+ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, true);
documentPath = [paths objectAtIndex:0];
+
+ NSFileManager *fileManager = [NSFileManager defaultManager];
+ if (![fileManager fileExistsAtPath:documentPath]) {
+ [fileManager createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:nil];
+ }
+
+ NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) objectAtIndex:0];
+ migrateDatabaseFiles(documentsDirectory, documentPath);
+
+ // If the database could not be moved out of Documents, keep opening it there rather than
+ // creating a fresh empty one; the migration retries on the next launch.
+ if ([fileManager fileExistsAtPath:[documentsDirectory stringByAppendingPathComponent:@"OnyxDB"]]) {
+ documentPath = documentsDirectory;
+ }
}

HybridNitroSQLite::docPath = [documentPath UTF8String];
4 changes: 4 additions & 0 deletions src/ONYXKEYS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,9 @@ const ONYXKEYS = {
// Max width supported for HTML <canvas> element
MAX_CANVAS_WIDTH: 'maxCanvasWidth',

// Whether the MoveFilesOutOfDocuments migration has rewritten attachment record paths, so later launches skip the collection scan
ATTACHMENT_RECORD_PATHS_MIGRATED: 'attachmentRecordPathsMigrated',

// Stores last visited path
LAST_VISITED_PATH: 'lastVisitedPath',

Expand Down Expand Up @@ -1781,6 +1784,7 @@ type OnyxValuesMapping = {
[ONYXKEYS.PRESERVED_ACCOUNT]: OnyxTypes.Account;
[ONYXKEYS.NVP_DISMISSED_PRODUCT_TRAINING]: OnyxTypes.DismissedProductTraining;
[ONYXKEYS.NVP_SUBMIT_MIGRATION_MODAL_SHOWN]: boolean;
[ONYXKEYS.ATTACHMENT_RECORD_PATHS_MIGRATED]: boolean;
[ONYXKEYS.CORPAY_ONBOARDING_FIELDS]: OnyxTypes.CorpayOnboardingFields;
[ONYXKEYS.LAST_FULL_RECONNECT_TIME]: string;
[ONYXKEYS.TRAVEL_PROVISIONING]: OnyxTypes.TravelProvisioning;
Expand Down
1 change: 1 addition & 0 deletions src/libs/ExportOnyxState/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ const safeOnyxKeys = new Set<string>([
ONYXKEYS.AGENT_TEMPLATES,
ONYXKEYS.ARE_AGENTS_LOADED,
ONYXKEYS.ARE_POLICY_ROOMS_LOADED,
ONYXKEYS.ATTACHMENT_RECORD_PATHS_MIGRATED,
ONYXKEYS.BETAS,
ONYXKEYS.BETA_CONFIGURATION,
ONYXKEYS.CACHED_PDF_PATHS,
Expand Down
9 changes: 7 additions & 2 deletions src/libs/ExportOnyxState/index.native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,19 @@ const shareAsFile: ShareAsFile = (fileContent) => {
try {
// Define new filename and path for the app info file
const infoFileName = CONST.DEFAULT_ONYX_DUMP_FILE_NAME;
const infoFilePath = `${RNFS.DocumentDirectoryPath}/${infoFileName}`;
// The dump only needs to live long enough to be shared, so it goes in Caches, which
// is never exposed to the user (unlike Documents, which the iOS Files app shows when
// file sharing is enabled) and which the OS can reclaim afterwards
const infoFilePath = `${RNFS.CachesDirectoryPath}/${infoFileName}`;
const actualInfoFile = `file://${infoFilePath}`;

RNFS.writeFile(infoFilePath, fileContent, 'utf8').then(() => {
// Share targets copy the file while the share sheet is open, so once the promise
// settles (including cancel, since failOnCancel is false) the dump can be deleted
Share.open({
url: actualInfoFile,
failOnCancel: false,
});
}).finally(() => RNFS.unlink(infoFilePath).catch(() => {}));
});
} catch (error) {
console.error('Error renaming and sharing file:', error);
Expand Down
16 changes: 14 additions & 2 deletions src/libs/actions/Attachment/index.native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import Onyx from 'react-native-onyx';

import type {CacheAttachmentProps, GetCachedAttachmentProps, RemoveCachedAttachmentProps} from './types';

const ATTACHMENT_DIR = `${RNFS.DocumentDirectoryPath}/attachments`;
// Cached attachments are re-downloadable, so they live in Caches, which the OS may purge
// and which is never exposed to the user via the iOS Files app (unlike Documents)
const ATTACHMENT_DIR = `${RNFS.CachesDirectoryPath}/attachments`;
Comment thread
NicolasBonet marked this conversation as resolved.
Resolved

async function cacheAttachment({attachmentID, uri, mimeType}: CacheAttachmentProps) {
const isLocalFile = uri.startsWith('file://');
Expand All @@ -22,6 +24,8 @@ async function cacheAttachment({attachmentID, uri, mimeType}: CacheAttachmentPro
const destPath = `${ATTACHMENT_DIR}/${fileName}`;

try {
// The OS can purge Caches wholesale, so the directory may need recreating
await RNFS.mkdir(ATTACHMENT_DIR);
await RNFS.copyFile(uri, destPath);
await Onyx.set(`${ONYXKEYS.COLLECTION.ATTACHMENT}${attachmentID}`, {
attachmentID,
Expand Down Expand Up @@ -56,6 +60,8 @@ async function cacheAttachment({attachmentID, uri, mimeType}: CacheAttachmentPro

const fileName = `${attachmentID}.${attachmentFileExtension}`;
const filePath = `${ATTACHMENT_DIR}/${fileName}`;
// The OS can purge Caches wholesale, so the directory may need recreating
await RNFS.mkdir(ATTACHMENT_DIR);
await RNFetchBlob.config({path: filePath}).fetch('GET', uri);

await Onyx.set(`${ONYXKEYS.COLLECTION.ATTACHMENT}${attachmentID}`, {
Expand All @@ -78,7 +84,13 @@ async function getCachedAttachment({attachmentID, attachment, currentSource}: Ge

const localSource = attachment?.source;
if (localSource) {
return localSource;
// The OS can purge Caches while the Onyx record survives, so verify the file still
// exists. If it was purged, fall back to the current source and re-cache it.
const localFileExists = await RNFS.exists(localSource);
if (localFileExists) {
return localSource;

@linhvovan29546 linhvovan29546 Aug 31, 2026 •

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.

Checklist from #99490: getCachedAttachment returns the cached localSource as a bare filesystem path (no file:// scheme). RN's on Android requires that scheme to load a local file, so it rendered as a broken thumbnail.

Already fixed in #99546.

}
cacheAttachment({attachmentID, uri: currentSource});
}

return currentSource;
Expand Down
51 changes: 24 additions & 27 deletions src/libs/fileDownload/index.ios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,15 @@ const isUserCancelled = (err: unknown) => {
};

/**
* Downloads the file to Documents section in iOS
* Downloads the file to the given directory. Files the user asked to download go to Documents,
* which the iOS Files app shows to the user as the app's folder because file sharing is enabled.
* Files that only need a temporary local copy (e.g. for saving to Photos) go to the cache
* directory, which the Files app never exposes.
*/
function downloadFile(fileUrl: string, fileName: string) {
const dirs = RNFetchBlob.fs.dirs;

// The iOS files will download to documents directory
const path = dirs.DocumentDir;

// Fetching the attachment
function downloadFile(fileUrl: string, fileName: string, directory: string) {
return RNFetchBlob.config({
fileCache: true,
path: `${path}/${fileName}`,
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
path: `${path}/Expensify/${fileName}`,
},
path: `${directory}/${fileName}`,
}).fetch('GET', fileUrl);
}

Expand All @@ -71,12 +63,17 @@ const postDownloadFile = (translate: LocalizedTranslate, url: string, fileName?:
.then((fileData) => {
const resolvedFileName = fileName ?? 'Expensify';
const finalFileName = appendTimestamp ? appendTimeToFileName(resolvedFileName) : resolvedFileName;
const expensifyDir = `${RNFS.DocumentDirectoryPath}/Expensify`;
// The file only exists to be handed to the share sheet, so it is written to the
// cache directory, which the iOS Files app never shows to the user
const expensifyDir = `${RNFS.CachesDirectoryPath}/Expensify`;
const localPath = `${expensifyDir}/${finalFileName}`;
return RNFS.mkdir(expensifyDir).then(() => {
return RNFS.writeFile(localPath, fileData, 'utf8')
.then(() => Share.open({url: localPath, failOnCancel: false, saveToFiles: true}))
.then(() => RNFS.unlink(localPath));
return (
RNFS.writeFile(localPath, fileData, 'utf8')
// The share sheet lets the user save the file to the Files app. The staged copy is removed afterwards.
.then(() => Share.open({url: localPath, failOnCancel: false, saveToFiles: true}))
.then(() => RNFS.unlink(localPath))
Comment thread
luacmartins marked this conversation as resolved.
Resolved
);
});
})
.catch((error) => {
Expand Down Expand Up @@ -104,24 +101,24 @@ function downloadImage(fileUrl: string) {
*/
function downloadVideo(fileUrl: string, fileName: string): Promise<PhotoIdentifier> {
return new Promise((resolve, reject) => {
let documentPathUri: string | null = null;
let tempPathUri: string | null = null;
let cameraRollAsset: PhotoIdentifier;

// Because CameraRoll doesn't allow direct downloads of video with remote URIs, we first download as documents, then copy to photo lib and unlink the original file.
downloadFile(fileUrl, fileName)
// Because CameraRoll doesn't allow direct downloads of video with remote URIs, we first download to the cache, then copy to photo lib and unlink the temporary file.
downloadFile(fileUrl, fileName, RNFetchBlob.fs.dirs.CacheDir)
.then((attachment) => {
documentPathUri = attachment.data as string | null;
if (!documentPathUri) {
tempPathUri = attachment.data as string | null;
if (!tempPathUri) {
throw new Error('Error downloading video');
}
return CameraRoll.saveAsset(documentPathUri);
return CameraRoll.saveAsset(tempPathUri);
})
.then((attachment) => {
cameraRollAsset = attachment;
if (!documentPathUri) {
if (!tempPathUri) {
throw new Error('Error downloading video');
}
return RNFetchBlob.fs.unlink(documentPathUri);
return RNFetchBlob.fs.unlink(tempPathUri);
})
.then(() => {
resolve(cameraRollAsset);
Expand Down Expand Up @@ -154,7 +151,7 @@ const fileDownload: FileDownload = (translate, fileUrl, fileName, successMessage
break;
}

fileDownloadPromise = downloadFile(fileUrl, attachmentName);
fileDownloadPromise = downloadFile(fileUrl, attachmentName, RNFetchBlob.fs.dirs.DocumentDir);
break;
}

Expand Down
5 changes: 4 additions & 1 deletion src/libs/localFileCreate/index.native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ const localFileCreate: LocalFileCreate = (fileName, textContent, appendTimestamp
const {fileExtension} = splitExtensionFromFileName(fileName);
const fileNameWithExtension = fileExtension ? fileName : `${fileName}.txt`;
const newFileName = appendTimestamp ? appendTimeToFileName(fileNameWithExtension) : fileNameWithExtension;
const dir = RNFetchBlob.fs.dirs.DocumentDir;
// These files are temporary hand-offs to a share/copy flow that deletes them afterwards,
// so they belong in the cache directory, which is never exposed to the user (unlike
// Documents, which the iOS Files app shows when file sharing is enabled)
const dir = RNFetchBlob.fs.dirs.CacheDir;
const path = `${dir}/${newFileName}`;

return RNFetchBlob.fs.writeFile(path, textContent, 'utf8').then(() => RNFetchBlob.fs.stat(path).then(({size}) => ({path, newFileName, size})));
Expand Down
3 changes: 2 additions & 1 deletion src/libs/migrateOnyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import CONST from '@src/CONST';

import Log from './Log';
import ConvertGpsPointsTo2DArray from './migrations/ConvertGpsPointsTo2DArray';
import MoveFilesOutOfDocuments from './migrations/MoveFilesOutOfDocuments';
import {endSpan, getSpan, startSpan} from './telemetry/activeSpans';

export default function () {
Expand All @@ -16,7 +17,7 @@ export default function () {
});

// Add all migrations to an array so they are executed in order
const migrationPromises: Array<() => Promise<void>> = [ConvertGpsPointsTo2DArray];
const migrationPromises: Array<() => Promise<void>> = [ConvertGpsPointsTo2DArray, MoveFilesOutOfDocuments];

// Reduce all promises down to a single promise. All promises run in a linear fashion, waiting for the
// previous promise to finish before moving onto the next one.
Expand Down
Loading
Loading