fix(files): refresh expired outside-workspace grants (#3078)

* fix(files): refresh expired outside file grants

* fix(files): scope outside grants to local runtime
This commit is contained in:
Pascal André
2026-08-22 20:26:20 +03:00
committed by GitHub
parent f7a0d1f0f6
commit c452a8092c
4 changed files with 203 additions and 63 deletions
+51 -39
View File
@@ -49,7 +49,7 @@ import { shouldAllowFileDraftSave, shouldScheduleFileAutosave } from '@/lib/file
import { getRuntimeUrlResolver } from '@/lib/runtime-url'; import { getRuntimeUrlResolver } from '@/lib/runtime-url';
import { acquireRuntimeUrlAuthToken, refreshRuntimeUrlAuthToken, subscribeRuntimeUrlAuthToken } from '@/lib/runtime-auth'; import { acquireRuntimeUrlAuthToken, refreshRuntimeUrlAuthToken, subscribeRuntimeUrlAuthToken } from '@/lib/runtime-auth';
import { getRuntimeApiBaseUrl, getRuntimeKey } from '@/lib/runtime-switch'; import { getRuntimeApiBaseUrl, getRuntimeKey } from '@/lib/runtime-switch';
import { getOutsideFileGrant } from '@/lib/outsideFileGrants'; import { getOutsideFileGrant, resolveOutsideFileReadOptions } from '@/lib/outsideFileGrants';
import { subscribeToFileContentInvalidation } from '@/lib/fileContentInvalidation'; import { subscribeToFileContentInvalidation } from '@/lib/fileContentInvalidation';
import { DiagramEditor } from '@/components/diagram'; import { DiagramEditor } from '@/components/diagram';
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs'; import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
@@ -842,6 +842,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
}, [openPaths, selectedPath]); }, [openPaths, selectedPath]);
const selectedFile = React.useMemo(() => (effectiveSelectedPath ? toFileNode(effectiveSelectedPath) : null), [effectiveSelectedPath, toFileNode]); const selectedFile = React.useMemo(() => (effectiveSelectedPath ? toFileNode(effectiveSelectedPath) : null), [effectiveSelectedPath, toFileNode]);
const selectedFilePath = selectedFile?.path ?? ''; const selectedFilePath = selectedFile?.path ?? '';
const [, setOutsideFileGrantRevision] = React.useState(0);
React.useEffect(() => { React.useEffect(() => {
if (!root || !selectedPath) return; if (!root || !selectedPath) return;
@@ -862,6 +863,14 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
}), }),
[mode, selectedFileIsOutsideWorkspace, selectedOutsideFileGrant, root], [mode, selectedFileIsOutsideWorkspace, selectedOutsideFileGrant, root],
); );
const resolveFileReadOptions = React.useCallback(async (path: string) => {
const previousGrant = getOutsideFileGrant(path);
const readOptions = await resolveOutsideFileReadOptions(path, root, mode === 'editor-only');
if (readOptions.outsideFileGrant && readOptions.outsideFileGrant !== previousGrant) {
setOutsideFileGrantRevision((revision) => revision + 1);
}
return readOptions;
}, [mode, root]);
// Editor tabs horizontal scroll fades // Editor tabs horizontal scroll fades
const editorTabsScrollRef = React.useRef<HTMLDivElement>(null); const editorTabsScrollRef = React.useRef<HTMLDivElement>(null);
@@ -1546,38 +1555,35 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
}; };
}, [currentDirectory, debouncedSearchQuery, searchFiles, showHidden, showGitignored]); }, [currentDirectory, debouncedSearchQuery, searchFiles, showHidden, showGitignored]);
const readFile = React.useCallback(async (path: string, options?: { allowOutsideWorkspace?: boolean; outsideFileGrant?: string; optional?: boolean }): Promise<string> => { const readFile = React.useCallback(async (path: string): Promise<string> => {
const options = await resolveFileReadOptions(path);
if (files.readFile) { if (files.readFile) {
const result = await files.readFile(path, { ...(options ?? {}), directory: root || undefined }); const result = await files.readFile(path, { ...options, directory: root || undefined });
return result.content ?? ''; return result.content ?? '';
} }
const params = new URLSearchParams({ path }); const params = new URLSearchParams({ path });
if (options?.allowOutsideWorkspace) { if (options.allowOutsideWorkspace) {
params.set('allowOutsideWorkspace', 'true'); params.set('allowOutsideWorkspace', 'true');
} }
if (options?.outsideFileGrant) { if (options.outsideFileGrant) {
params.set('outsideFileGrant', options.outsideFileGrant); params.set('outsideFileGrant', options.outsideFileGrant);
} }
if (options?.optional) {
params.set('optional', 'true');
}
if (root) { if (root) {
params.set('directory', root); params.set('directory', root);
} }
const response = await runtimeFetch(`/api/fs/read?${params.toString()}`, { const response = await runtimeFetch(`/api/fs/read?${params.toString()}`);
cache: options?.optional ? 'no-store' : 'default',
});
if (!response.ok) { if (!response.ok) {
const error = await response.json().catch(() => ({ error: response.statusText })); const error = await response.json().catch(() => ({ error: response.statusText }));
throw new Error((error as { error?: string }).error || t('filesView.error.readFileFailed')); throw new Error((error as { error?: string }).error || t('filesView.error.readFileFailed'));
} }
return response.text(); return response.text();
}, [files, root, t]); }, [files, resolveFileReadOptions, root, t]);
const readFileStat = React.useCallback(async (path: string, options?: { allowOutsideWorkspace?: boolean; outsideFileGrant?: string }): Promise<FileStatSnapshot | null> => { const readFileStat = React.useCallback(async (path: string): Promise<FileStatSnapshot | null> => {
if (files.statFile) { if (files.statFile) {
const result = await files.statFile(path, { ...(options ?? {}), directory: root || undefined }); const options = await resolveFileReadOptions(path);
const result = await files.statFile(path, { ...options, directory: root || undefined });
return { return {
path: result.path, path: result.path,
size: result.size, size: result.size,
@@ -1585,7 +1591,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
}; };
} }
return null; return null;
}, [files, root]); }, [files, resolveFileReadOptions, root]);
React.useEffect(() => { React.useEffect(() => {
if (!root || !files.statFile || openPaths.length === 0) { if (!root || !files.statFile || openPaths.length === 0) {
@@ -1597,7 +1603,8 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
void Promise.all(paths.map(async (path) => { void Promise.all(paths.map(async (path) => {
try { try {
const stat = await files.statFile?.(path, { directory: root || undefined }); const options = await resolveFileReadOptions(path);
const stat = await files.statFile?.(path, { ...options, directory: root || undefined });
if (!cancelled && stat && !stat.isFile) { if (!cancelled && stat && !stat.isFile) {
removeOpenPathsByPrefix(root, path); removeOpenPathsByPrefix(root, path);
} }
@@ -1611,7 +1618,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
return () => { return () => {
cancelled = true; cancelled = true;
}; };
}, [files, openPaths, removeOpenPathsByPrefix, root]); }, [files, openPaths, removeOpenPathsByPrefix, resolveFileReadOptions, root]);
const displayedContent = React.useMemo(() => const displayedContent = React.useMemo(() =>
fileContent.length > MAX_VIEW_CHARS fileContent.length > MAX_VIEW_CHARS
@@ -1824,6 +1831,13 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
setDesktopImageSrc(''); setDesktopImageSrc('');
setLoadedFilePath(null); setLoadedFilePath(null);
setContentDetectedBinary(false); setContentDetectedBinary(false);
setFileLoading(true);
// Prime asset URLs; read and stat resolve again immediately before their calls.
await resolveFileReadOptions(node.path);
if (!isCurrentLoad()) {
return;
}
const selectedIsImage = isImageFile(node.path); const selectedIsImage = isImageFile(node.path);
const isSvg = isSvgFile(node.path); const isSvg = isSvgFile(node.path);
@@ -1838,7 +1852,6 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
if (runtime.isDesktop && selectedIsImage && !isSvg) { if (runtime.isDesktop && selectedIsImage && !isSvg) {
setFileContent(''); setFileContent('');
setDraftContent(''); setDraftContent('');
setFileLoading(true);
return; return;
} }
@@ -1869,15 +1882,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
return; return;
} }
setFileLoading(true); await readFile(node.path)
const outsideFileGrant = getOutsideFileGrant(node.path);
const readOptions = {
allowOutsideWorkspace: mode === 'editor-only' && Boolean(root) && !isPathWithinRoot(node.path, root),
outsideFileGrant,
};
await readFile(node.path, readOptions)
.then((content) => { .then((content) => {
if (!isCurrentLoad()) { if (!isCurrentLoad()) {
return; return;
@@ -1898,7 +1903,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
? `${editorContent.slice(0, MAX_VIEW_CHARS)}\n\n… truncated …` ? `${editorContent.slice(0, MAX_VIEW_CHARS)}\n\n… truncated …`
: editorContent); : editorContent);
setLoadedFilePath(node.path); setLoadedFilePath(node.path);
void readFileStat(node.path, readOptions) void readFileStat(node.path)
.then((stat) => { .then((stat) => {
if (stat && isCurrentLoad()) { if (stat && isCurrentLoad()) {
lastLoadedFileStatRef.current = stat; lastLoadedFileStatRef.current = stat;
@@ -1963,7 +1968,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
setFileLoading(false); setFileLoading(false);
} }
}); });
}, [expandPaths, isMobile, loadDirectory, mode, readFile, readFileStat, removeOpenPathsByPrefix, root, runtime.isDesktop, searchQuery, setSelectedPath, t]); }, [expandPaths, isMobile, loadDirectory, readFile, readFileStat, removeOpenPathsByPrefix, resolveFileReadOptions, root, runtime.isDesktop, searchQuery, setSelectedPath, t]);
const ensurePathVisible = React.useCallback(async (targetPath: string, includeTarget: boolean) => { const ensurePathVisible = React.useCallback(async (targetPath: string, includeTarget: boolean) => {
if (!root) { if (!root) {
@@ -2089,7 +2094,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
return; return;
} }
void readFileStat(selectedFile.path, selectedFileReadOptions) void readFileStat(selectedFile.path)
.then((latestStat) => { .then((latestStat) => {
if (cancelled || !latestStat) { if (cancelled || !latestStat) {
return; return;
@@ -2125,7 +2130,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
cancelled = true; cancelled = true;
window.clearInterval(interval); window.clearInterval(interval);
}; };
}, [loadedFilePath, readFileStat, selectedFile?.path, selectedFileReadOptions]); }, [loadedFilePath, readFileStat, selectedFile?.path]);
const discardAndContinue = React.useCallback(() => { const discardAndContinue = React.useCallback(() => {
const nextFile = pendingSelectFileRef.current; const nextFile = pendingSelectFileRef.current;
@@ -2595,12 +2600,12 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
diagramXmlRef.current = xml; diagramXmlRef.current = xml;
diagramSavedXmlRef.current = xml; diagramSavedXmlRef.current = xml;
setDraftContent(xml); setDraftContent(xml);
const stat = await readFileStat(path, selectedFileReadOptions).catch(() => null); const stat = await readFileStat(path).catch(() => null);
if (stat) { if (stat) {
lastLoadedFileStatRef.current = stat; lastLoadedFileStatRef.current = stat;
} }
return true; return true;
}, [files, readFileStat, selectedFileReadOptions, t]); }, [files, readFileStat, t]);
React.useEffect(() => { React.useEffect(() => {
return () => { return () => {
@@ -3027,7 +3032,9 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
[lightTheme.metadata.id, darkTheme.metadata.id], [lightTheme.metadata.id, darkTheme.metadata.id],
); );
const pdfAssetAuthKey = selectedFile?.path && isSelectedPdf const pdfAssetAuthKey = selectedFile?.path
&& isSelectedPdf
&& (!selectedFileReadOptions.allowOutsideWorkspace || selectedFileReadOptions.outsideFileGrant)
? `${selectedFile.path}|${selectedFileReadOptions.allowOutsideWorkspace ? 'outside' : 'workspace'}|${selectedFileReadOptions.outsideFileGrant ?? ''}|${fileContentRevision}` ? `${selectedFile.path}|${selectedFileReadOptions.allowOutsideWorkspace ? 'outside' : 'workspace'}|${selectedFileReadOptions.outsideFileGrant ?? ''}|${fileContentRevision}`
: ''; : '';
@@ -3050,7 +3057,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
: desktopImageSrc) : desktopImageSrc)
: ''; : '';
const pdfSrc = selectedFile?.path && isSelectedPdf && pdfAssetAuthReadyKey === pdfAssetAuthKey const pdfSrc = selectedFile?.path && isSelectedPdf && pdfAssetAuthKey && pdfAssetAuthReadyKey === pdfAssetAuthKey
? getRuntimeUrlResolver().authenticatedAsset('/api/fs/raw', { ? getRuntimeUrlResolver().authenticatedAsset('/api/fs/raw', {
path: selectedFile.path, path: selectedFile.path,
allowOutsideWorkspace: selectedFileReadOptions.allowOutsideWorkspace ? 'true' : undefined, allowOutsideWorkspace: selectedFileReadOptions.allowOutsideWorkspace ? 'true' : undefined,
@@ -3082,14 +3089,19 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
setFileError(null); setFileError(null);
const readOptions = await resolveFileReadOptions(selectedFile.path);
if (cancelled) {
return;
}
const srcPromise = files.readFileBinary const srcPromise = files.readFileBinary
? files.readFileBinary(selectedFile.path, selectedFileReadOptions).then((result) => result.dataUrl) ? files.readFileBinary(selectedFile.path, readOptions).then((result) => result.dataUrl)
: (async () => { : (async () => {
const response = await runtimeFetch('/api/fs/raw', { const response = await runtimeFetch('/api/fs/raw', {
query: { query: {
path: selectedFile.path, path: selectedFile.path,
allowOutsideWorkspace: selectedFileReadOptions.allowOutsideWorkspace ? 'true' : undefined, allowOutsideWorkspace: readOptions.allowOutsideWorkspace ? 'true' : undefined,
outsideFileGrant: selectedFileReadOptions.outsideFileGrant, outsideFileGrant: readOptions.outsideFileGrant,
directory: root || undefined, directory: root || undefined,
}, },
}); });
@@ -3135,7 +3147,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
URL.revokeObjectURL(objectUrl); URL.revokeObjectURL(objectUrl);
} }
}; };
}, [fileContentRevision, files, isSelectedImage, isSelectedSvg, root, selectedFile?.path, selectedFileReadOptions, t]); }, [fileContentRevision, files, isSelectedImage, isSelectedSvg, resolveFileReadOptions, root, selectedFile?.path, selectedFileReadOptions, t]);
const handleCloseDialog = React.useCallback(() => setActiveDialog(null), []); const handleCloseDialog = React.useCallback(() => setActiveDialog(null), []);
+17 -8
View File
@@ -1,3 +1,4 @@
import { z } from 'zod';
import type { ProjectEntry, RuntimeAPIs, TerminalShell } from '@/lib/api/types'; import type { ProjectEntry, RuntimeAPIs, TerminalShell } from '@/lib/api/types';
import { getInjectedBootOutcome } from '@/lib/desktopBoot'; import { getInjectedBootOutcome } from '@/lib/desktopBoot';
import type { DraftStarterRef } from '@/lib/draftStarters'; import type { DraftStarterRef } from '@/lib/draftStarters';
@@ -640,6 +641,12 @@ const isDesktopFileGrantResult = (
value !== null && typeof value === 'object' && !Array.isArray(value) value !== null && typeof value === 'object' && !Array.isArray(value)
); );
const desktopExistingFileGrantSchema = z.object({
path: z.string().min(1),
outsideFileGrant: z.string().min(1),
expiresAt: z.number().finite(),
});
export const requestFileAccess = async ( export const requestFileAccess = async (
options?: { filters?: Array<{ name: string; extensions: string[] }>; defaultPath?: string } options?: { filters?: Array<{ name: string; extensions: string[] }>; defaultPath?: string }
): Promise<{ success: boolean; path?: string; outsideFileGrant?: string; error?: string }> => { ): Promise<{ success: boolean; path?: string; outsideFileGrant?: string; error?: string }> => {
@@ -682,7 +689,10 @@ export const requestFileAccess = async (
export const requestExistingFileAccess = async ( export const requestExistingFileAccess = async (
path: string path: string
): Promise<{ success: boolean; path?: string; outsideFileGrant?: string; error?: string }> => { ): Promise<
| { success: true; path: string; outsideFileGrant: string; expiresAt: number }
| { success: false; error: string }
> => {
const targetPath = typeof path === 'string' ? path.trim() : ''; const targetPath = typeof path === 'string' ? path.trim() : '';
if (!targetPath) { if (!targetPath) {
return { success: false, error: 'Path is required' }; return { success: false, error: 'Path is required' };
@@ -693,15 +703,14 @@ export const requestExistingFileAccess = async (
try { try {
const selected = await getDesktopBridge()?.grantFileAccess?.(targetPath); const selected = await getDesktopBridge()?.grantFileAccess?.(targetPath);
if (!isDesktopFileGrantResult(selected)) { const parsed = desktopExistingFileGrantSchema.safeParse(selected);
if (!parsed.success) {
return { success: false, error: 'File access was not granted' }; return { success: false, error: 'File access was not granted' };
} }
const grantedPath = typeof selected.path === 'string' ? selected.path : ''; return {
const outsideFileGrant = typeof selected.outsideFileGrant === 'string' ? selected.outsideFileGrant : ''; success: true,
if (!grantedPath || !outsideFileGrant) { ...parsed.data,
return { success: false, error: 'File access was not granted' }; };
}
return { success: true, path: grantedPath, outsideFileGrant };
} catch (error) { } catch (error) {
console.warn('Failed to request existing file access', error); console.warn('Failed to request existing file access', error);
return { success: false, error: error instanceof Error ? error.message : String(error) }; return { success: false, error: error instanceof Error ? error.message : String(error) };
@@ -0,0 +1,76 @@
import { expect, test } from 'bun:test';
import { initializeRuntimeEndpoint, switchRuntimeEndpoint } from './runtime-switch';
import { getOutsideFileGrant, resolveOutsideFileReadOptions } from './outsideFileGrants';
test('renews an expired outside-file grant before returning read options', async () => {
let now = 1_000;
let grantRequests = 0;
let grantFileAccess = async (path: string) => {
grantRequests += 1;
return { path, outsideFileGrant: `grant-${grantRequests}`, expiresAt: now + 60_000 };
};
const originalNow = Date.now;
const originalWindow = globalThis.window;
Date.now = () => now;
Object.defineProperty(globalThis, 'window', {
configurable: true,
value: {
__OPENCHAMBER_ELECTRON__: { runtime: 'electron' },
__OPENCHAMBER_DESKTOP__: {
invoke: async () => null,
grantFileAccess: (path: string) => grantFileAccess(path),
},
dispatchEvent: () => true,
location: { origin: 'http://127.0.0.1:57123' },
},
});
initializeRuntimeEndpoint({ apiBaseUrl: 'http://127.0.0.1:57123/api', runtimeKey: 'local' });
try {
expect(await resolveOutsideFileReadOptions('C:/workspace/file.txt', 'C:/workspace', true))
.toEqual({ allowOutsideWorkspace: false });
expect(await resolveOutsideFileReadOptions('C:/outside/file.txt', 'C:/workspace', false))
.toEqual({ allowOutsideWorkspace: false });
expect(grantRequests).toBe(0);
const first = await resolveOutsideFileReadOptions('C:/outside/file.txt', 'C:/workspace', true);
now += 55_001;
const [renewed, concurrent] = await Promise.all([
resolveOutsideFileReadOptions('C:/outside/file.txt', 'C:/workspace', true),
resolveOutsideFileReadOptions('C:/outside/file.txt', 'C:/workspace', true),
]);
expect(first).toEqual({ allowOutsideWorkspace: true, outsideFileGrant: 'grant-1' });
expect(renewed).toEqual({ allowOutsideWorkspace: true, outsideFileGrant: 'grant-2' });
expect(concurrent).toEqual(renewed);
expect(grantRequests).toBe(2);
switchRuntimeEndpoint({ apiBaseUrl: 'https://remote.example/api', runtimeKey: 'remote' });
expect(await resolveOutsideFileReadOptions('C:/outside/file.txt', 'C:/workspace', true))
.toEqual({ allowOutsideWorkspace: true, outsideFileGrant: undefined });
expect(grantRequests).toBe(2);
switchRuntimeEndpoint({ apiBaseUrl: 'http://127.0.0.1:57123/api', runtimeKey: 'local' });
let finishGrantRequest: (grant: { path: string; outsideFileGrant: string; expiresAt: number }) => void = () => undefined;
grantFileAccess = (path) => new Promise((resolve) => {
finishGrantRequest = resolve;
grantRequests += 1;
void path;
});
const pending = resolveOutsideFileReadOptions('C:/outside/pending.txt', 'C:/workspace', true);
switchRuntimeEndpoint({ apiBaseUrl: 'https://remote.example/api', runtimeKey: 'remote' });
finishGrantRequest({
path: 'C:/outside/pending.txt',
outsideFileGrant: 'stale-grant',
expiresAt: now + 10 * 60 * 1000,
});
expect(await pending).toEqual({ allowOutsideWorkspace: true, outsideFileGrant: undefined });
switchRuntimeEndpoint({ apiBaseUrl: 'http://127.0.0.1:57123/api', runtimeKey: 'local' });
expect(getOutsideFileGrant('C:/outside/pending.txt')).toBe(undefined);
} finally {
switchRuntimeEndpoint({ apiBaseUrl: 'http://127.0.0.1:57123/api', runtimeKey: 'local' });
Date.now = originalNow;
Object.defineProperty(globalThis, 'window', { configurable: true, value: originalWindow });
}
});
+59 -16
View File
@@ -1,13 +1,17 @@
import { requestExistingFileAccess } from '@/lib/desktop'; import { requestExistingFileAccess } from '@/lib/desktop';
import { isFilePathWithinDirectory, normalizeFilePath } from '@/lib/path-utils'; import { isFilePathWithinDirectory, normalizeFilePath } from '@/lib/path-utils';
import { getRuntimeKey } from '@/lib/runtime-switch';
type OutsideFileGrantEntry = { type OutsideFileGrantEntry = {
outsideFileGrant: string; outsideFileGrant: string;
expiresAt: number; expiresAt: number;
}; };
const DEFAULT_GRANT_TTL_MS = 10 * 60 * 1000; const GRANT_RENEWAL_BUFFER_MS = 5_000;
const grantsByPath = new Map<string, OutsideFileGrantEntry>(); const grantsByCacheKey = new Map<string, OutsideFileGrantEntry>();
const pendingGrantsByCacheKey = new Map<string, Promise<string | undefined>>();
const grantCacheKey = (path: string, runtimeKey = getRuntimeKey()): string => `${runtimeKey}\0${path}`;
export const getOutsideFileGrant = (path: string): string | undefined => { export const getOutsideFileGrant = (path: string): string | undefined => {
const normalizedPath = normalizeFilePath(path); const normalizedPath = normalizeFilePath(path);
@@ -15,13 +19,14 @@ export const getOutsideFileGrant = (path: string): string | undefined => {
return undefined; return undefined;
} }
const entry = grantsByPath.get(normalizedPath); const cacheKey = grantCacheKey(normalizedPath);
const entry = grantsByCacheKey.get(cacheKey);
if (!entry) { if (!entry) {
return undefined; return undefined;
} }
if (entry.expiresAt <= Date.now()) { if (entry.expiresAt <= Date.now()) {
grantsByPath.delete(normalizedPath); grantsByCacheKey.delete(cacheKey);
return undefined; return undefined;
} }
@@ -31,18 +36,17 @@ export const getOutsideFileGrant = (path: string): string | undefined => {
const rememberOutsideFileGrant = ( const rememberOutsideFileGrant = (
path: string, path: string,
outsideFileGrant: string, outsideFileGrant: string,
expiresAt?: number, expiresAt: number,
runtimeKey: string,
): void => { ): void => {
const normalizedPath = normalizeFilePath(path); const normalizedPath = normalizeFilePath(path);
if (!normalizedPath || !outsideFileGrant) { if (!normalizedPath || !outsideFileGrant) {
return; return;
} }
grantsByPath.set(normalizedPath, { grantsByCacheKey.set(grantCacheKey(normalizedPath, runtimeKey), {
outsideFileGrant, outsideFileGrant,
expiresAt: typeof expiresAt === 'number' && Number.isFinite(expiresAt) expiresAt: expiresAt - GRANT_RENEWAL_BUFFER_MS,
? expiresAt
: Date.now() + DEFAULT_GRANT_TTL_MS,
}); });
}; };
@@ -55,19 +59,58 @@ export const ensureOutsideFileGrantForDesktop = async (
return undefined; return undefined;
} }
const runtimeKey = getRuntimeKey();
if (runtimeKey !== 'local') {
return undefined;
}
const cacheKey = grantCacheKey(normalizedPath, runtimeKey);
const existing = getOutsideFileGrant(normalizedPath); const existing = getOutsideFileGrant(normalizedPath);
if (existing) { if (existing) {
return existing; return existing;
} }
const result = await requestExistingFileAccess(normalizedPath); const pending = pendingGrantsByCacheKey.get(cacheKey);
if (!result.success || !result.path || !result.outsideFileGrant) { if (pending) {
return undefined; return pending;
} }
rememberOutsideFileGrant(result.path, result.outsideFileGrant); const request = requestExistingFileAccess(normalizedPath).then((result) => {
if (normalizeFilePath(result.path) !== normalizedPath) { if (!result.success || getRuntimeKey() !== runtimeKey) {
rememberOutsideFileGrant(normalizedPath, result.outsideFileGrant); return undefined;
}
const { path: grantedPath, outsideFileGrant, expiresAt } = result;
if (expiresAt <= Date.now() + GRANT_RENEWAL_BUFFER_MS) {
return undefined;
}
rememberOutsideFileGrant(grantedPath, outsideFileGrant, expiresAt, runtimeKey);
if (normalizeFilePath(grantedPath) !== normalizedPath) {
rememberOutsideFileGrant(normalizedPath, outsideFileGrant, expiresAt, runtimeKey);
}
return outsideFileGrant;
});
pendingGrantsByCacheKey.set(cacheKey, request);
try {
return await request;
} finally {
pendingGrantsByCacheKey.delete(cacheKey);
} }
return result.outsideFileGrant; };
export const resolveOutsideFileReadOptions = async (
path: string,
workspaceRoot: string,
enabled: boolean,
): Promise<{ allowOutsideWorkspace: boolean; outsideFileGrant?: string }> => {
const allowOutsideWorkspace = enabled
&& Boolean(workspaceRoot)
&& !isFilePathWithinDirectory(path, workspaceRoot);
if (!allowOutsideWorkspace) {
return { allowOutsideWorkspace: false };
}
return {
allowOutsideWorkspace: true,
outsideFileGrant: await ensureOutsideFileGrantForDesktop(path, workspaceRoot),
};
}; };