diff --git a/apps/desktop/e2e/local-files.spec.ts b/apps/desktop/e2e/local-files.spec.ts index 8877e2d845b..7657fc2bad9 100644 --- a/apps/desktop/e2e/local-files.spec.ts +++ b/apps/desktop/e2e/local-files.spec.ts @@ -1,3 +1,4 @@ +import { execFileSync } from 'node:child_process' import { mkdirSync, readFileSync, @@ -72,6 +73,64 @@ const FIXTURE_PAGE = `Local file fixture ` +/** + * Two FAT disk images with the same volume name, folder, and file layout, for one mount point. + * macOS gives the second the first's device number and FAT gives both the same inodes, so only + * the volume UUID (from each image's serial number) tells them apart. Null when this machine + * cannot create or mount disk images. + */ +function lookAlikeDrives(root: string) { + if (process.platform !== 'darwin') return null + const mountPoint = join(realpathSync(root), 'Drive') + mkdirSync(mountPoint) + const hdiutil = (...args: string[]) => execFileSync('hdiutil', args, { stdio: 'pipe' }) + const attach = (image: string) => + hdiutil('attach', '-nobrowse', '-noautoopen', '-mountpoint', mountPoint, image) + const unplug = () => { + try { + hdiutil('detach', mountPoint) + } catch { + try { + hdiutil('detach', '-force', mountPoint) + } catch {} + } + } + try { + const images = ['A', 'B'].map((name) => { + const image = join(root, `${name}.dmg`) + hdiutil( + 'create', + '-size', + '8m', + '-fs', + 'MS-DOS', + '-volname', + 'REPORTS', + '-layout', + 'NONE', + image + ) + attach(image) + mkdirSync(join(mountPoint, 'Shared')) + writeFileSync(join(mountPoint, 'Shared', 'report.txt'), `drive ${name}`) + unplug() + return image + }) + return { + report: join(mountPoint, 'Shared', 'report.txt'), + unplug, + /** Swaps which drive is plugged in at the mount point. */ + plug: (drive: 'A' | 'B') => { + unplug() + attach(images[drive === 'A' ? 0 : 1]) + }, + } + } catch { + unplug() + return null + } +} + type LocalFileResponse = Awaited>> interface ToolCall { @@ -1041,3 +1100,41 @@ test('remembered folder grants survive restart until forgotten, replaced, or sig expect(await answerTextRead("Don't allow")).toMatchObject({ ok: false }) }) }) + +test('a remembered folder grant does not follow a look-alike drive', async ({ localFiles }) => { + const drives = lookAlikeDrives(localFiles.root) + test.skip(!drives, 'This runner cannot create and mount FAT disk images with hdiutil.') + if (!drives) return + localFiles.calls.drive = { toolName: 'read_local_file', args: { path: drives.report } } + const driveA = { ok: true, data: { text: 'drive A' } } + try { + drives.plug('A') + let session = await localFiles.open() + const permission = await session.requestPermission({ operation: 'read', toolCallId: 'drive' }) + await answerShellDialog(permission.prompt, 'Allow folder') + expect(await permission.result).toMatchObject(driveA) + + /** With drive B plugged in, the grant asks again; with A back, it reads without asking. */ + const declineLookAlike = async () => { + const asked = await session.requestPermission({ operation: 'read', toolCallId: 'drive' }) + await answerShellDialog(asked.prompt, "Don't allow") + expect(await asked.result).toMatchObject({ ok: false }) + drives.plug('A') + expect(await session.invoke({ operation: 'read', toolCallId: 'drive' })).toMatchObject(driveA) + } + + await test.step('swapping drives while the app runs asks again, and the original returns', async () => { + drives.plug('B') + await declineLookAlike() + }) + + await test.step('a look-alike drive plugged in before launch asks again, and the original returns', async () => { + await localFiles.close(session) + drives.plug('B') + session = await localFiles.open(session.desktop.userData) + await declineLookAlike() + }) + } finally { + drives.unplug() + } +}) diff --git a/apps/desktop/native/directory.cc b/apps/desktop/native/directory.cc index efb06b40b94..33a92cb25a0 100644 --- a/apps/desktop/native/directory.cc +++ b/apps/desktop/native/directory.cc @@ -5,6 +5,11 @@ #include #include +#ifdef __APPLE__ +#include +#include +#endif + #include #include #include @@ -333,12 +338,90 @@ static napi_value CloseFile(napi_env env, napi_callback_info info) { return promise; } +struct VolumeRead { + napi_async_work work = nullptr; + napi_deferred deferred = nullptr; + std::string path; + /** Empty when the file system reports no volume UUID. */ + std::string id; + int error = 0; +}; + +static void ReadVolume(napi_env, void* data) { +#ifdef __APPLE__ + auto* request = static_cast(data); + struct attrlist attributes = {}; + attributes.bitmapcount = ATTR_BIT_MAP_COUNT; + attributes.volattr = ATTR_VOL_INFO | ATTR_VOL_UUID; + struct __attribute__((packed)) { + uint32_t length; + uuid_t uuid; + } reply = {}; + if (getattrlist(request->path.c_str(), &attributes, &reply, sizeof(reply), FSOPT_NOFOLLOW) != 0) { + if (errno != ENOTSUP) request->error = errno; + return; + } + if (reply.length < sizeof(reply) || uuid_is_null(reply.uuid)) return; + uuid_string_t text; + uuid_unparse_upper(reply.uuid, text); + request->id = text; +#endif +} + +static void CompleteVolume(napi_env env, napi_status status, void* data) { + auto* request = static_cast(data); + if (status != napi_ok || request->error != 0) { + napi_value error; + const char* code = AccessDeniedCode(request->error); + napi_create_error(env, code ? String(env, code) : nullptr, + String(env, "Could not read the folder's volume."), &error); + napi_reject_deferred(env, request->deferred, error); + } else { + napi_value result; + if (request->id.empty()) napi_get_null(env, &result); + else result = String(env, request->id.c_str()); + napi_resolve_deferred(env, request->deferred, result); + } + napi_delete_async_work(env, request->work); + delete request; +} + +/** + * The UUID of the volume holding a path, or null where the file system has none or cannot report + * one (and on Linux). + * FAT and exFAT derive theirs from the volume serial number, so look-alike drives that reuse a + * device number and inode still differ here. + */ +static napi_value VolumeId(napi_env env, napi_callback_info info) { + size_t count = 1; + napi_value argument; + auto* request = new VolumeRead(); + if (napi_get_cb_info(env, info, &count, &argument, nullptr, nullptr) != napi_ok || count != 1 || + !ReadPath(env, argument, request->path) || request->path.empty() || request->path[0] != '/') { + delete request; + napi_throw_type_error(env, nullptr, "Expected an absolute path."); + return nullptr; + } + napi_value promise; + if (napi_create_promise(env, &request->deferred, &promise) != napi_ok || + napi_create_async_work(env, nullptr, String(env, "ReadVolumeId"), ReadVolume, + CompleteVolume, request, &request->work) != napi_ok || + napi_queue_async_work(env, request->work) != napi_ok) { + if (request->work) napi_delete_async_work(env, request->work); + delete request; + napi_throw_error(env, nullptr, "Could not schedule the volume read."); + return nullptr; + } + return promise; +} + NAPI_MODULE_INIT() { napi_property_descriptor properties[] = { {"readDirectory", nullptr, ReadDirectory, nullptr, nullptr, nullptr, napi_default, nullptr}, {"openApproved", nullptr, OpenApproved, nullptr, nullptr, nullptr, napi_default, nullptr}, {"closeFile", nullptr, CloseFile, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"volumeId", nullptr, VolumeId, nullptr, nullptr, nullptr, napi_default, nullptr}, }; - napi_define_properties(env, exports, 3, properties); + napi_define_properties(env, exports, 4, properties); return exports; } diff --git a/apps/desktop/src/main/browser-agent/file-transfer.test.ts b/apps/desktop/src/main/browser-agent/file-transfer.test.ts index bc4569f37c6..f58d3508993 100644 --- a/apps/desktop/src/main/browser-agent/file-transfer.test.ts +++ b/apps/desktop/src/main/browser-agent/file-transfer.test.ts @@ -2,6 +2,7 @@ import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' import { open, rename, rm, truncate } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { fileURLToPath } from 'node:url' import { BROWSER_FILE_TRANSFER_MAX_BYTES } from '@sim/browser-protocol' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -21,6 +22,7 @@ function appSession(fetch: (url: string, init: RequestInit) => Promise beforeEach(() => { temp = mkdtempSync(join(tmpdir(), 'sim-file-transfer-')) vi.mocked(app.getPath).mockReturnValue(temp) + vi.mocked(app.getAppPath).mockReturnValue(fileURLToPath(new URL('../../..', import.meta.url))) }) afterEach(async () => { diff --git a/apps/desktop/src/main/local-file-permissions.test.ts b/apps/desktop/src/main/local-file-permissions.test.ts index 2101f5093dd..c647453b158 100644 --- a/apps/desktop/src/main/local-file-permissions.test.ts +++ b/apps/desktop/src/main/local-file-permissions.test.ts @@ -1,6 +1,7 @@ import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { fileURLToPath } from 'node:url' import { afterEach, beforeEach, expect, it, vi } from 'vitest' vi.mock('electron', () => import('@/test/electron-mock')) @@ -8,6 +9,7 @@ vi.mock('@/main/dialogs', () => ({ showShellDialog: vi.fn(async () => ({ response: 1 })), })) +import { app } from 'electron' import { captureAccountDataGeneration } from '@/main/account-data-generation' import { showShellDialog } from '@/main/dialogs' import { LocalFilePermissions } from '@/main/local-file-permissions' @@ -30,6 +32,7 @@ function permissionContext() { let root: string beforeEach(async () => { + vi.mocked(app.getAppPath).mockReturnValue(fileURLToPath(new URL('../..', import.meta.url))) root = await realpath(await mkdtemp(join(tmpdir(), 'sim-folder-consent-'))) }) afterEach(async () => { diff --git a/apps/desktop/src/main/local-file-permissions.ts b/apps/desktop/src/main/local-file-permissions.ts index 84f6deb6e83..fc88784c4ee 100644 --- a/apps/desktop/src/main/local-file-permissions.ts +++ b/apps/desktop/src/main/local-file-permissions.ts @@ -10,7 +10,7 @@ import { type LocalFileAccess, type LocalFilesystemService, } from '@/main/local-filesystem' -import { openNativeFile } from '@/main/native-directory' +import { openNativeFile, readVolumeId } from '@/main/native-directory' const MAX_PENDING_REQUESTS = 32 @@ -188,6 +188,7 @@ export class LocalFilePermissions { if (this.fullFileAccess() || (await this.filesystem.nativeAccess(folder))) return const root = await lstat(folder, { bigint: true }) if (!root.isDirectory()) throw new Error('The folder is no longer available.') + const identity = { dev: root.dev, ino: root.ino, volume: await readVolumeId(folder) } signal.throwIfAborted() const parent = await context.parent() await this.currentContext(contexts, signal) @@ -228,7 +229,7 @@ export class LocalFilePermissions { } if (result.response !== 0) throw new Error('The user did not allow this local file access.') const current = await this.currentContext(contexts, signal) - await this.filesystem.grantDirectory({ path: folder }, current.generation, root) + await this.filesystem.grantDirectory({ path: folder }, current.generation, identity) return } } diff --git a/apps/desktop/src/main/local-filesystem-grant-store.test.ts b/apps/desktop/src/main/local-filesystem-grant-store.test.ts index 8b9fc5e8540..355afbdcb33 100644 --- a/apps/desktop/src/main/local-filesystem-grant-store.test.ts +++ b/apps/desktop/src/main/local-filesystem-grant-store.test.ts @@ -20,6 +20,8 @@ describe('createEncryptedLocalFilesystemGrantStore', () => { {}, { dev: 1, ino: Number.MAX_SAFE_INTEGER }, { dev: '1', ino: '18446744073709551615' }, + { dev: '1', ino: '2', volume: null }, + { dev: '1', ino: '2', volume: '5C7BA5AA-1DC5-32AC-B374-9F6F8C7BBF04' }, ])('encrypts grants at rest and restores their exact identity %j', async (identity) => { const directory = await mkdtemp(join(tmpdir(), 'sim-localfs-store-')) const filePath = join(directory, 'grants.json') diff --git a/apps/desktop/src/main/local-filesystem-grant-store.ts b/apps/desktop/src/main/local-filesystem-grant-store.ts index 3b7dc887198..136293349e4 100644 --- a/apps/desktop/src/main/local-filesystem-grant-store.ts +++ b/apps/desktop/src/main/local-filesystem-grant-store.ts @@ -15,6 +15,7 @@ const MAX_GRANT_ID_LENGTH = 128 const MAX_GRANT_NAME_LENGTH = 512 const MAX_GRANT_PATH_LENGTH = 4_096 const MAX_GRANT_BOOKMARK_LENGTH = 256 * 1024 +const VOLUME_ID_PATTERN = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/ const logger = createLogger('LocalFilesystemGrantStore') export interface PersistedLocalFilesystemGrant { @@ -23,6 +24,8 @@ export interface PersistedLocalFilesystemGrant { rootPath: string dev?: number | string ino?: number | string + /** The volume UUID; null when the volume has none, absent on grants saved before it was kept. */ + volume?: string | null bookmark?: string } @@ -68,6 +71,9 @@ function isPersistedGrant(value: unknown): value is PersistedLocalFilesystemGran !grant.rootPath.includes('\0') && ((grant.dev === undefined && grant.ino === undefined) || (isStoredIdentity(grant.dev) && isStoredIdentity(grant.ino))) && + (grant.volume === undefined || + grant.volume === null || + (typeof grant.volume === 'string' && VOLUME_ID_PATTERN.test(grant.volume))) && (grant.bookmark === undefined || (typeof grant.bookmark === 'string' && grant.bookmark.length > 0 && diff --git a/apps/desktop/src/main/local-filesystem.test.ts b/apps/desktop/src/main/local-filesystem.test.ts index 054dae14204..cdc7b89a101 100644 --- a/apps/desktop/src/main/local-filesystem.test.ts +++ b/apps/desktop/src/main/local-filesystem.test.ts @@ -30,6 +30,11 @@ vi.mock('node:fs/promises', async (importOriginal) => { } }) +/** Two look-alike drives: same name, layout, device number, and inodes, different serial. */ +const DRIVE_A = '5C7BA5AA-1DC5-32AC-B374-9F6F8C7BBF04' +const DRIVE_B = '07D688A4-AF9B-3A27-AD3C-A6C6D46FE0E3' +vi.mock('@/main/native-directory', () => ({ readVolumeId: vi.fn(async () => DRIVE_A) })) + import type { LocalFilesystemMount, LocalFilesystemResponse } from '@sim/desktop-bridge' import { Menu } from 'electron' import { accessDeniedMessage, LocalFilesystemService } from '@/main/local-filesystem' @@ -37,6 +42,7 @@ import type { LocalFilesystemGrantStore, PersistedLocalFilesystemGrant, } from '@/main/local-filesystem-grant-store' +import { readVolumeId } from '@/main/native-directory' class MemoryGrantStore implements LocalFilesystemGrantStore { grants: PersistedLocalFilesystemGrant[] = [] @@ -72,6 +78,7 @@ describe('LocalFilesystemService', () => { let service: LocalFilesystemService beforeEach(async () => { + vi.mocked(readVolumeId).mockResolvedValue(DRIVE_A) root = await mkdtemp(join(tmpdir(), 'sim-localfs-')) await mkdir(join(root, 'src')) await writeFile(join(root, 'README.md'), 'hello world\nsecond line\n') @@ -764,7 +771,7 @@ describe('LocalFilesystemService', () => { ], [ 'saved without a device and inode', - ({ dev, ino, ...legacy }: PersistedLocalFilesystemGrant) => legacy, + ({ dev, ino, volume, ...legacy }: PersistedLocalFilesystemGrant) => legacy, ], ])('keeps a grant %s inactive until the user selects the folder again', async (_, change) => { const grantStore = new MemoryGrantStore() @@ -804,4 +811,80 @@ describe('LocalFilesystemService', () => { expect(dataOf(await restarted.handle({ operation: 'list_mounts' }))).toEqual({ mounts: [] }) expect(grantStore.grants).toMatchObject([{ id: 'volume-root' }]) }) + + it('keeps a remembered grant inactive on a look-alike drive and restores it when the original returns', async () => { + const grantStore = new MemoryGrantStore() + const granted = await mount( + new LocalFilesystemService({ chooseDirectory: async () => root, grantStore }) + ) + vi.mocked(readVolumeId).mockResolvedValue(DRIVE_B) + + const restarted = new LocalFilesystemService({ grantStore }) + await restarted.initialize() + expect(dataOf(await restarted.handle({ operation: 'list_mounts' }))).toEqual({ mounts: [] }) + await expect( + restarted.handle({ operation: 'read', uri: `${granted.uri}README.md` }) + ).resolves.toMatchObject({ ok: false, code: 'ACCESS_DENIED' }) + expect(grantStore.grants).toMatchObject([{ id: granted.id, volume: DRIVE_A }]) + + vi.mocked(readVolumeId).mockResolvedValue(DRIVE_A) + await expect( + restarted.handle({ operation: 'read', uri: `${granted.uri}README.md` }) + ).resolves.toMatchObject({ ok: true }) + }) + + it('deactivates an active grant when a look-alike drive replaces its volume mid-session', async () => { + const grantStore = new MemoryGrantStore() + const remembering = new LocalFilesystemService({ + chooseDirectory: async () => root, + grantStore, + }) + const granted = await mount(remembering) + vi.mocked(readVolumeId).mockResolvedValue(DRIVE_B) + + await expect( + remembering.handle({ operation: 'read', uri: `${granted.uri}README.md` }) + ).resolves.toMatchObject({ ok: false, code: 'ACCESS_DENIED' }) + expect(dataOf(await remembering.handle({ operation: 'list_mounts' }))).toEqual({ mounts: [] }) + expect(grantStore.grants).toMatchObject([{ id: granted.id, volume: DRIVE_A }]) + }) + + it('restores grants on a volume without a UUID by device and inode, including older grants', async () => { + vi.mocked(readVolumeId).mockResolvedValue(null) + const grantStore = new MemoryGrantStore() + const granted = await mount( + new LocalFilesystemService({ chooseDirectory: async () => root, grantStore }) + ) + const [{ volume, ...legacy }] = grantStore.grants + expect(volume).toBeNull() + grantStore.grants = [legacy] + + const restarted = new LocalFilesystemService({ grantStore }) + await restarted.initialize() + expect(dataOf(await restarted.handle({ operation: 'list_mounts' }))).toEqual({ + mounts: [granted], + }) + }) + + it('restores a grant saved before volumes were recorded by device and inode, then records its volume', async () => { + const grantStore = new MemoryGrantStore() + const granted = await mount( + new LocalFilesystemService({ chooseDirectory: async () => root, grantStore }) + ) + const [stored] = grantStore.grants + const { volume, ...legacy } = stored + grantStore.grants = [legacy] + + const restarted = new LocalFilesystemService({ grantStore }) + await restarted.initialize() + expect(dataOf(await restarted.handle({ operation: 'list_mounts' }))).toEqual({ + mounts: [granted], + }) + expect(grantStore.grants).toEqual([stored]) + + vi.mocked(readVolumeId).mockResolvedValue(DRIVE_B) + const lookAlike = new LocalFilesystemService({ grantStore }) + await lookAlike.initialize() + expect(dataOf(await lookAlike.handle({ operation: 'list_mounts' }))).toEqual({ mounts: [] }) + }) }) diff --git a/apps/desktop/src/main/local-filesystem.ts b/apps/desktop/src/main/local-filesystem.ts index 958c3fa111f..d9595dedc6e 100644 --- a/apps/desktop/src/main/local-filesystem.ts +++ b/apps/desktop/src/main/local-filesystem.ts @@ -38,7 +38,7 @@ import type { LocalFilesystemGrantStore, PersistedLocalFilesystemGrant, } from '@/main/local-filesystem-grant-store' -import { openNativeFile } from '@/main/native-directory' +import { openNativeFile, readVolumeId } from '@/main/native-directory' const MAX_URI_LENGTH = 4096 const MAX_LIST_ENTRIES = 500 @@ -129,38 +129,58 @@ export function displayPath(path: string): string { }) } +/** Where a granted folder lives: its device, inode, and volume UUID (null if the volume has none). */ +interface FolderIdentity { + dev: bigint + ino: bigint + volume: string | null +} + /** * Checks that a remembered folder path still names the folder the user granted. * - * Identity is the canonical path plus its device and inode numbers: - * - same device and inode: the granted folder, restored without asking. - * - same device, different inode or no longer a directory: the folder was replaced, so the grant - * is dropped. - * - a different device, or a grant saved before identities were recorded: unconfirmed. Inode - * numbers are not unique across volumes (FAT and exFAT derive them from a file's position, so a - * different drive with the same name and layout matches), and a remounted drive or share can - * get a new device number. The grant is kept but stays inactive until the user allows the - * folder again, which records its new identity. + * Identity is the canonical path plus its device, inode, and volume UUID: + * - same device, volume, and inode: the granted folder, restored without asking. A grant saved + * before volumes were recorded is matched on device and inode alone, as it always was, and its + * current volume is recorded so every later check compares it. + * - same device and volume, different inode or no longer a directory: the folder was replaced, so + * the grant is dropped. + * - a different device or volume, or a grant saved before device and inode were recorded: + * unconfirmed. Device and inode numbers alone cannot tell drives apart: FAT and exFAT derive + * inodes from a file's position, and macOS hands the next drive the same device number, so a + * different drive with the same name and layout matches both. Its volume UUID (from the + * FAT/exFAT serial number) does not. A remounted drive or share can also get a new device + * number. The grant is kept but stays inactive until the user allows the folder again, which + * records its new identity. A volume with no UUID (and every Linux volume) falls back to the + * device and inode alone. * - missing, unreadable, or now reached through a link: unavailable. The grant is kept and * retried on use. */ async function confirmGrantIdentity( rootPath: string, - expected: { dev: bigint; ino: bigint } | undefined -): Promise { + expected: { dev: bigint; ino: bigint; volume?: string | null } | undefined +): Promise { let resolved: string let metadata: BigIntStats + let volume: string | null try { resolved = await realpath(rootPath) metadata = await stat(resolved, { bigint: true }) + volume = await readVolumeId(resolved) } catch { return 'unavailable' } if (resolved !== rootPath) return 'unavailable' - if (!expected || metadata.dev !== expected.dev) { + if ( + !expected || + metadata.dev !== expected.dev || + (expected.volume !== undefined && volume !== expected.volume) + ) { return metadata.isDirectory() ? 'unconfirmed' : 'unavailable' } - return metadata.isDirectory() && metadata.ino === expected.ino ? metadata : 'replaced' + return metadata.isDirectory() && metadata.ino === expected.ino + ? { dev: metadata.dev, ino: metadata.ino, volume } + : 'replaced' } /** Operations that read inside one granted folder, named by the request's `uri`. */ @@ -172,10 +192,8 @@ const GRANT_SCOPED_OPERATIONS: ReadonlySet = new Set([ 'stat', ]) -interface GrantedMount extends LocalFilesystemMount { +interface GrantedMount extends LocalFilesystemMount, FolderIdentity { rootPath: string - dev: bigint - ino: bigint bookmark?: string stopAccessing?: () => void } @@ -785,7 +803,7 @@ export class LocalFilesystemService { async grantDirectory( selected: SelectedDirectory, generation: number, - expected?: { dev: bigint; ino: bigint } + expected?: FolderIdentity ): Promise { const stopAccessing = selected.bookmark ? this.startAccessingBookmark(selected.bookmark) @@ -802,6 +820,7 @@ export class LocalFilesystemService { try { const rootPath = await realpath(selected.path) const rootStat = await stat(rootPath, { bigint: true }) + const volume = await readVolumeId(rootPath) if (!isAccountDataGenerationCurrent(generation)) { throw new LocalFilesystemError('CANCELLED', 'The folder request expired during sign-out.') } @@ -813,7 +832,8 @@ export class LocalFilesystemService { expected && (rootPath !== selected.path || rootStat.dev !== expected.dev || - rootStat.ino !== expected.ino) + rootStat.ino !== expected.ino || + volume !== expected.volume) ) { throw new LocalFilesystemError( 'ACCESS_DENIED', @@ -846,6 +866,7 @@ export class LocalFilesystemService { rootPath, dev: rootStat.dev, ino: rootStat.ino, + volume, remembered: existing?.remembered ?? false, ...(bookmark ? { bookmark } : {}), ...(nextStopAccessing ? { stopAccessing: nextStopAccessing } : {}), @@ -931,14 +952,20 @@ export class LocalFilesystemService { */ private async assertMountCurrent(mount: GrantedMount): Promise { let root: BigIntStats + let volume: string | null try { root = await lstat(mount.rootPath, { bigint: true }) + volume = await readVolumeId(mount.rootPath) } catch (error) { throw accessDeniedMessage(error) ? error : folderUnavailable() } const current = this.mounts.get(mount.id) if (!current || current.rootPath !== mount.rootPath) throw mountNotFound() - if (current === mount && root.isDirectory() && root.dev !== mount.dev) { + if ( + current === mount && + root.isDirectory() && + (root.dev !== mount.dev || volume !== mount.volume) + ) { mount.stopAccessing?.() this.mounts.delete(mount.id) this.unavailable.set(mount.id, this.persistedGrant(mount)) @@ -948,9 +975,11 @@ export class LocalFilesystemService { if ( current.dev !== mount.dev || current.ino !== mount.ino || + current.volume !== mount.volume || !root.isDirectory() || root.dev !== mount.dev || - root.ino !== mount.ino + root.ino !== mount.ino || + volume !== mount.volume ) { throw new LocalFilesystemError( 'ACCESS_DENIED', @@ -1104,7 +1133,7 @@ export class LocalFilesystemService { await earlier } - /** Activates, keeps, or drops one waiting grant; returns whether the stored grant set changed. */ + /** Activates, keeps, or drops one waiting grant; returns whether the stored grants changed. */ private async reviveGrant( grant: PersistedLocalFilesystemGrant, generation: number @@ -1113,7 +1142,7 @@ export class LocalFilesystemService { const expected = grant.dev === undefined || grant.ino === undefined ? undefined - : { dev: BigInt(grant.dev), ino: BigInt(grant.ino) } + : { dev: BigInt(grant.dev), ino: BigInt(grant.ino), volume: grant.volume } const identity = await confirmGrantIdentity(grant.rootPath, expected) if (!isAccountDataGenerationCurrent(generation) || this.unavailable.get(grant.id) !== grant) { stopAccessing?.() @@ -1136,13 +1165,12 @@ export class LocalFilesystemService { name: basename(grant.rootPath) || grant.name || 'Local files', uri: localUri(grant.id), rootPath: grant.rootPath, - dev: identity.dev, - ino: identity.ino, + ...identity, remembered: true, ...(grant.bookmark ? { bookmark: grant.bookmark } : {}), ...(stopAccessing ? { stopAccessing } : {}), }) - return false + return grant.volume === undefined } private persistedGrant(mount: GrantedMount): PersistedLocalFilesystemGrant { @@ -1152,6 +1180,7 @@ export class LocalFilesystemService { rootPath: mount.rootPath, dev: mount.dev.toString(), ino: mount.ino.toString(), + volume: mount.volume, ...(mount.bookmark ? { bookmark: mount.bookmark } : {}), } } diff --git a/apps/desktop/src/main/native-directory.ts b/apps/desktop/src/main/native-directory.ts index 224d16b37dd..8921067fd88 100644 --- a/apps/desktop/src/main/native-directory.ts +++ b/apps/desktop/src/main/native-directory.ts @@ -19,6 +19,7 @@ interface NativeDirectoryBridge { ino: bigint, directory: boolean ) => Promise + volumeId: (path: string) => Promise } let bridge: NativeDirectoryBridge | undefined @@ -69,3 +70,11 @@ export function readNativeDirectory( ): Promise { return nativeBridge().readDirectory(descriptor, limit) } + +/** + * The UUID of the volume holding `path` (not following a final link), or null where the file + * system reports none. Always null on Linux. + */ +export function readVolumeId(path: string): Promise { + return nativeBridge().volumeId(path) +}