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:
@@ -49,7 +49,7 @@ import { shouldAllowFileDraftSave, shouldScheduleFileAutosave } from '@/lib/file
|
||||
import { getRuntimeUrlResolver } from '@/lib/runtime-url';
|
||||
import { acquireRuntimeUrlAuthToken, refreshRuntimeUrlAuthToken, subscribeRuntimeUrlAuthToken } from '@/lib/runtime-auth';
|
||||
import { getRuntimeApiBaseUrl, getRuntimeKey } from '@/lib/runtime-switch';
|
||||
import { getOutsideFileGrant } from '@/lib/outsideFileGrants';
|
||||
import { getOutsideFileGrant, resolveOutsideFileReadOptions } from '@/lib/outsideFileGrants';
|
||||
import { subscribeToFileContentInvalidation } from '@/lib/fileContentInvalidation';
|
||||
import { DiagramEditor } from '@/components/diagram';
|
||||
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
||||
@@ -842,6 +842,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
}, [openPaths, selectedPath]);
|
||||
const selectedFile = React.useMemo(() => (effectiveSelectedPath ? toFileNode(effectiveSelectedPath) : null), [effectiveSelectedPath, toFileNode]);
|
||||
const selectedFilePath = selectedFile?.path ?? '';
|
||||
const [, setOutsideFileGrantRevision] = React.useState(0);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!root || !selectedPath) return;
|
||||
@@ -862,6 +863,14 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
}),
|
||||
[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
|
||||
const editorTabsScrollRef = React.useRef<HTMLDivElement>(null);
|
||||
@@ -1546,38 +1555,35 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
};
|
||||
}, [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) {
|
||||
const result = await files.readFile(path, { ...(options ?? {}), directory: root || undefined });
|
||||
const result = await files.readFile(path, { ...options, directory: root || undefined });
|
||||
return result.content ?? '';
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({ path });
|
||||
if (options?.allowOutsideWorkspace) {
|
||||
if (options.allowOutsideWorkspace) {
|
||||
params.set('allowOutsideWorkspace', 'true');
|
||||
}
|
||||
if (options?.outsideFileGrant) {
|
||||
if (options.outsideFileGrant) {
|
||||
params.set('outsideFileGrant', options.outsideFileGrant);
|
||||
}
|
||||
if (options?.optional) {
|
||||
params.set('optional', 'true');
|
||||
}
|
||||
if (root) {
|
||||
params.set('directory', root);
|
||||
}
|
||||
const response = await runtimeFetch(`/api/fs/read?${params.toString()}`, {
|
||||
cache: options?.optional ? 'no-store' : 'default',
|
||||
});
|
||||
const response = await runtimeFetch(`/api/fs/read?${params.toString()}`);
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
throw new Error((error as { error?: string }).error || t('filesView.error.readFileFailed'));
|
||||
}
|
||||
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) {
|
||||
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 {
|
||||
path: result.path,
|
||||
size: result.size,
|
||||
@@ -1585,7 +1591,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}, [files, root]);
|
||||
}, [files, resolveFileReadOptions, root]);
|
||||
|
||||
React.useEffect(() => {
|
||||
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) => {
|
||||
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) {
|
||||
removeOpenPathsByPrefix(root, path);
|
||||
}
|
||||
@@ -1611,7 +1618,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [files, openPaths, removeOpenPathsByPrefix, root]);
|
||||
}, [files, openPaths, removeOpenPathsByPrefix, resolveFileReadOptions, root]);
|
||||
|
||||
const displayedContent = React.useMemo(() =>
|
||||
fileContent.length > MAX_VIEW_CHARS
|
||||
@@ -1824,6 +1831,13 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
setDesktopImageSrc('');
|
||||
setLoadedFilePath(null);
|
||||
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 isSvg = isSvgFile(node.path);
|
||||
@@ -1838,7 +1852,6 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
if (runtime.isDesktop && selectedIsImage && !isSvg) {
|
||||
setFileContent('');
|
||||
setDraftContent('');
|
||||
setFileLoading(true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1869,15 +1882,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
return;
|
||||
}
|
||||
|
||||
setFileLoading(true);
|
||||
|
||||
const outsideFileGrant = getOutsideFileGrant(node.path);
|
||||
const readOptions = {
|
||||
allowOutsideWorkspace: mode === 'editor-only' && Boolean(root) && !isPathWithinRoot(node.path, root),
|
||||
outsideFileGrant,
|
||||
};
|
||||
|
||||
await readFile(node.path, readOptions)
|
||||
await readFile(node.path)
|
||||
.then((content) => {
|
||||
if (!isCurrentLoad()) {
|
||||
return;
|
||||
@@ -1898,7 +1903,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
? `${editorContent.slice(0, MAX_VIEW_CHARS)}\n\n… truncated …`
|
||||
: editorContent);
|
||||
setLoadedFilePath(node.path);
|
||||
void readFileStat(node.path, readOptions)
|
||||
void readFileStat(node.path)
|
||||
.then((stat) => {
|
||||
if (stat && isCurrentLoad()) {
|
||||
lastLoadedFileStatRef.current = stat;
|
||||
@@ -1963,7 +1968,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
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) => {
|
||||
if (!root) {
|
||||
@@ -2089,7 +2094,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
return;
|
||||
}
|
||||
|
||||
void readFileStat(selectedFile.path, selectedFileReadOptions)
|
||||
void readFileStat(selectedFile.path)
|
||||
.then((latestStat) => {
|
||||
if (cancelled || !latestStat) {
|
||||
return;
|
||||
@@ -2125,7 +2130,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
cancelled = true;
|
||||
window.clearInterval(interval);
|
||||
};
|
||||
}, [loadedFilePath, readFileStat, selectedFile?.path, selectedFileReadOptions]);
|
||||
}, [loadedFilePath, readFileStat, selectedFile?.path]);
|
||||
|
||||
const discardAndContinue = React.useCallback(() => {
|
||||
const nextFile = pendingSelectFileRef.current;
|
||||
@@ -2595,12 +2600,12 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
diagramXmlRef.current = xml;
|
||||
diagramSavedXmlRef.current = xml;
|
||||
setDraftContent(xml);
|
||||
const stat = await readFileStat(path, selectedFileReadOptions).catch(() => null);
|
||||
const stat = await readFileStat(path).catch(() => null);
|
||||
if (stat) {
|
||||
lastLoadedFileStatRef.current = stat;
|
||||
}
|
||||
return true;
|
||||
}, [files, readFileStat, selectedFileReadOptions, t]);
|
||||
}, [files, readFileStat, t]);
|
||||
|
||||
React.useEffect(() => {
|
||||
return () => {
|
||||
@@ -3027,7 +3032,9 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
[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}`
|
||||
: '';
|
||||
|
||||
@@ -3050,7 +3057,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
: desktopImageSrc)
|
||||
: '';
|
||||
|
||||
const pdfSrc = selectedFile?.path && isSelectedPdf && pdfAssetAuthReadyKey === pdfAssetAuthKey
|
||||
const pdfSrc = selectedFile?.path && isSelectedPdf && pdfAssetAuthKey && pdfAssetAuthReadyKey === pdfAssetAuthKey
|
||||
? getRuntimeUrlResolver().authenticatedAsset('/api/fs/raw', {
|
||||
path: selectedFile.path,
|
||||
allowOutsideWorkspace: selectedFileReadOptions.allowOutsideWorkspace ? 'true' : undefined,
|
||||
@@ -3082,14 +3089,19 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
|
||||
setFileError(null);
|
||||
|
||||
const readOptions = await resolveFileReadOptions(selectedFile.path);
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const srcPromise = files.readFileBinary
|
||||
? files.readFileBinary(selectedFile.path, selectedFileReadOptions).then((result) => result.dataUrl)
|
||||
? files.readFileBinary(selectedFile.path, readOptions).then((result) => result.dataUrl)
|
||||
: (async () => {
|
||||
const response = await runtimeFetch('/api/fs/raw', {
|
||||
query: {
|
||||
path: selectedFile.path,
|
||||
allowOutsideWorkspace: selectedFileReadOptions.allowOutsideWorkspace ? 'true' : undefined,
|
||||
outsideFileGrant: selectedFileReadOptions.outsideFileGrant,
|
||||
allowOutsideWorkspace: readOptions.allowOutsideWorkspace ? 'true' : undefined,
|
||||
outsideFileGrant: readOptions.outsideFileGrant,
|
||||
directory: root || undefined,
|
||||
},
|
||||
});
|
||||
@@ -3135,7 +3147,7 @@ export const FilesView: React.FC<FilesViewProps> = ({ mode = 'full' }) => {
|
||||
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), []);
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { z } from 'zod';
|
||||
import type { ProjectEntry, RuntimeAPIs, TerminalShell } from '@/lib/api/types';
|
||||
import { getInjectedBootOutcome } from '@/lib/desktopBoot';
|
||||
import type { DraftStarterRef } from '@/lib/draftStarters';
|
||||
@@ -640,6 +641,12 @@ const isDesktopFileGrantResult = (
|
||||
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 (
|
||||
options?: { filters?: Array<{ name: string; extensions: string[] }>; defaultPath?: string }
|
||||
): Promise<{ success: boolean; path?: string; outsideFileGrant?: string; error?: string }> => {
|
||||
@@ -682,7 +689,10 @@ export const requestFileAccess = async (
|
||||
|
||||
export const requestExistingFileAccess = async (
|
||||
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() : '';
|
||||
if (!targetPath) {
|
||||
return { success: false, error: 'Path is required' };
|
||||
@@ -693,15 +703,14 @@ export const requestExistingFileAccess = async (
|
||||
|
||||
try {
|
||||
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' };
|
||||
}
|
||||
const grantedPath = typeof selected.path === 'string' ? selected.path : '';
|
||||
const outsideFileGrant = typeof selected.outsideFileGrant === 'string' ? selected.outsideFileGrant : '';
|
||||
if (!grantedPath || !outsideFileGrant) {
|
||||
return { success: false, error: 'File access was not granted' };
|
||||
}
|
||||
return { success: true, path: grantedPath, outsideFileGrant };
|
||||
return {
|
||||
success: true,
|
||||
...parsed.data,
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn('Failed to request existing file access', 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 });
|
||||
}
|
||||
});
|
||||
@@ -1,13 +1,17 @@
|
||||
import { requestExistingFileAccess } from '@/lib/desktop';
|
||||
import { isFilePathWithinDirectory, normalizeFilePath } from '@/lib/path-utils';
|
||||
import { getRuntimeKey } from '@/lib/runtime-switch';
|
||||
|
||||
type OutsideFileGrantEntry = {
|
||||
outsideFileGrant: string;
|
||||
expiresAt: number;
|
||||
};
|
||||
|
||||
const DEFAULT_GRANT_TTL_MS = 10 * 60 * 1000;
|
||||
const grantsByPath = new Map<string, OutsideFileGrantEntry>();
|
||||
const GRANT_RENEWAL_BUFFER_MS = 5_000;
|
||||
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 => {
|
||||
const normalizedPath = normalizeFilePath(path);
|
||||
@@ -15,13 +19,14 @@ export const getOutsideFileGrant = (path: string): string | undefined => {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const entry = grantsByPath.get(normalizedPath);
|
||||
const cacheKey = grantCacheKey(normalizedPath);
|
||||
const entry = grantsByCacheKey.get(cacheKey);
|
||||
if (!entry) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (entry.expiresAt <= Date.now()) {
|
||||
grantsByPath.delete(normalizedPath);
|
||||
grantsByCacheKey.delete(cacheKey);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -31,18 +36,17 @@ export const getOutsideFileGrant = (path: string): string | undefined => {
|
||||
const rememberOutsideFileGrant = (
|
||||
path: string,
|
||||
outsideFileGrant: string,
|
||||
expiresAt?: number,
|
||||
expiresAt: number,
|
||||
runtimeKey: string,
|
||||
): void => {
|
||||
const normalizedPath = normalizeFilePath(path);
|
||||
if (!normalizedPath || !outsideFileGrant) {
|
||||
return;
|
||||
}
|
||||
|
||||
grantsByPath.set(normalizedPath, {
|
||||
grantsByCacheKey.set(grantCacheKey(normalizedPath, runtimeKey), {
|
||||
outsideFileGrant,
|
||||
expiresAt: typeof expiresAt === 'number' && Number.isFinite(expiresAt)
|
||||
? expiresAt
|
||||
: Date.now() + DEFAULT_GRANT_TTL_MS,
|
||||
expiresAt: expiresAt - GRANT_RENEWAL_BUFFER_MS,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -55,19 +59,58 @@ export const ensureOutsideFileGrantForDesktop = async (
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const runtimeKey = getRuntimeKey();
|
||||
if (runtimeKey !== 'local') {
|
||||
return undefined;
|
||||
}
|
||||
const cacheKey = grantCacheKey(normalizedPath, runtimeKey);
|
||||
const existing = getOutsideFileGrant(normalizedPath);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const result = await requestExistingFileAccess(normalizedPath);
|
||||
if (!result.success || !result.path || !result.outsideFileGrant) {
|
||||
return undefined;
|
||||
const pending = pendingGrantsByCacheKey.get(cacheKey);
|
||||
if (pending) {
|
||||
return pending;
|
||||
}
|
||||
|
||||
rememberOutsideFileGrant(result.path, result.outsideFileGrant);
|
||||
if (normalizeFilePath(result.path) !== normalizedPath) {
|
||||
rememberOutsideFileGrant(normalizedPath, result.outsideFileGrant);
|
||||
const request = requestExistingFileAccess(normalizedPath).then((result) => {
|
||||
if (!result.success || getRuntimeKey() !== runtimeKey) {
|
||||
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),
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user