From b8d8d497c9f8a21fb390a5f7ad128380effbd693 Mon Sep 17 00:00:00 2001 From: zjncs <18910855655@163.com> Date: Tue, 3 Nov 2026 22:05:16 +0800 Subject: [PATCH] fix(authoring): protect draft files and unsaved edits Signed-off-by: zjncs <18910855655@163.com> --- .../authoring/draft-file-editor.test.tsx | 13 ++++++++++++- .../features/authoring/draft-file-editor.tsx | 18 ++++++++++++++++-- web/src/pages/authoring/draft-detail.tsx | 9 +++++---- 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/web/src/features/authoring/draft-file-editor.test.tsx b/web/src/features/authoring/draft-file-editor.test.tsx index 34f28e0a2..2ae114336 100644 --- a/web/src/features/authoring/draft-file-editor.test.tsx +++ b/web/src/features/authoring/draft-file-editor.test.tsx @@ -7,7 +7,7 @@ import { DraftFileEditor } from './draft-file-editor' import i18n from '@/i18n/config' vi.mock('@tanstack/react-router', () => ({ useBlocker: () => ({ status: 'idle' }) })) -vi.mock('@/api/client', () => ({ authoringApi: { getDraft: vi.fn(), readFile: vi.fn(), saveFile: vi.fn(), deleteFile: vi.fn() } })) +vi.mock('@/api/client', () => ({ authoringApi: { getDraft: vi.fn(), listFiles: vi.fn(), readFile: vi.fn(), saveFile: vi.fn(), deleteFile: vi.fn() } })) vi.mock('@/shared/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } })) const clients: QueryClient[] = [] function mount() { @@ -60,6 +60,17 @@ describe('draft files', () => { expect(authoringApi.saveFile).not.toHaveBeenCalled() }) + it('refuses to overwrite a file absent from the cached list', async () => { + vi.mocked(authoringApi.listFiles).mockResolvedValue([{ path: 'new.md' }]) + mount() + await screen.findByLabelText('File content') + fireEvent.change(screen.getByLabelText('Path'), { target: { value: 'new.md' } }) + fireEvent.click(screen.getByRole('button', { name: 'Create file' })) + await waitFor(() => expect(authoringApi.listFiles).toHaveBeenCalledWith(42)) + await waitFor(() => expect(screen.getByRole('button', { name: 'Create file' }).disabled).toBe(false)) + expect(authoringApi.saveFile).not.toHaveBeenCalled() + }) + it('uses server encoding rather than an extension to protect binary bytes', async () => { vi.mocked(authoringApi.readFile).mockResolvedValue({ content: '/wAB', encoding: 'base64', sha256: 'binary' }) mount() diff --git a/web/src/features/authoring/draft-file-editor.tsx b/web/src/features/authoring/draft-file-editor.tsx index 4c089fb09..2043b8f93 100644 --- a/web/src/features/authoring/draft-file-editor.tsx +++ b/web/src/features/authoring/draft-file-editor.tsx @@ -46,6 +46,7 @@ export function DraftFileEditor({ draftId, files, revision, onSaved, onDirtyChan enabled: path != null, meta: { skipGlobalErrorHandler: true }, retry: false, staleTime: Infinity, }) + const loadedFile = read.data const blocker = useBlocker({ shouldBlockFn: () => dirty || busy, enableBeforeUnload: dirty || busy, withResolver: true }) useEffect(() => { onDirtyChange(dirty || busy) }, [dirty, busy, onDirtyChange]) @@ -78,7 +79,20 @@ export function DraftFileEditor({ draftId, files, revision, onSaved, onDirtyChan toast.error(t('authoring.files.exists')) return } - if (await mutateFile(() => authoringApi.saveFile(draftId, { path: next, content: '', expectedRevision: revision }), 'authoring.files.created', next)) setNewPath('') + const created = await mutateFile(async () => { + // Read the revision before listing files. Any concurrent creation after + // that revision either appears in the list or makes the write conflict. + const snapshot = await authoringApi.getDraft(draftId) + if (snapshot.revision == null) throw new Error(t('authoring.ui.loadFailed')) + const latestFiles = await authoringApi.listFiles(draftId) + if (latestFiles.some(file => file.path === next)) { + throw new Error(t('authoring.files.exists')) + } + return authoringApi.saveFile(draftId, { + path: next, content: '', expectedRevision: snapshot.revision, + }) + }, 'authoring.files.created', next) + if (created) setNewPath('') } const upload = async () => { if (!uploadFile || !newPath.trim() || busy || dirty) return @@ -112,7 +126,7 @@ export function DraftFileEditor({ draftId, files, revision, onSaved, onDirtyChan {!path &&

{t('authoring.files.empty')}

} {path && read.isPending &&

{t('authoring.ui.loading')}

} {path && read.isError && void read.refetch()} />} - {path && read.isSuccess && (read.data.encoding === 'text' ? mutateFile(() => authoringApi.saveFile(draftId, { path, content, expectedRevision: read.data.revision }), 'authoring.files.saved')} /> :
+ {path && loadedFile && (loadedFile.encoding === 'text' ? mutateFile(() => authoringApi.saveFile(draftId, { path, content, expectedRevision: loadedFile.revision }), 'authoring.files.saved')} /> :

{path}

{t('authoring.files.size')}: {formatBytes(selected?.size ?? 0)}

sha256: {selected?.sha256}

diff --git a/web/src/pages/authoring/draft-detail.tsx b/web/src/pages/authoring/draft-detail.tsx index 380daf15b..b834f2f0c 100644 --- a/web/src/pages/authoring/draft-detail.tsx +++ b/web/src/pages/authoring/draft-detail.tsx @@ -31,11 +31,11 @@ function DraftWorkbench({ id }: { id: number }) { }) const files = useQuery({ queryKey: ['authoring', 'draft', id, 'files'], queryFn: () => authoringApi.listFiles(id), - enabled: validId && draft.isSuccess, meta: { skipGlobalErrorHandler: true }, retry: false, + enabled: validId && draft.data != null, meta: { skipGlobalErrorHandler: true }, retry: false, }) const runs = useQuery({ queryKey: ['authoring', 'draft', id, 'runs'], queryFn: () => authoringApi.listRuns(id), - enabled: validId && draft.isSuccess, meta: { skipGlobalErrorHandler: true }, retry: false, + enabled: validId && draft.data != null, meta: { skipGlobalErrorHandler: true }, retry: false, refetchInterval: query => query.state.data?.some(run => run.active) ? 1500 : false, }) const activeRun = runs.data?.some(run => run.active) ?? false @@ -60,7 +60,7 @@ function DraftWorkbench({ id }: { id: number }) { if (!validId) return

{t('authoring.detail.loadFailed')}

if (draft.isPending) return

{t('authoring.ui.loading')}

- if (draft.isError) return void draft.refetch()} /> + if (!draft.data) return void draft.refetch()} /> const current = draft.data if (current.revision == null) return

{t('authoring.detail.loadFailed')}

return ( @@ -79,10 +79,11 @@ function DraftWorkbench({ id }: { id: number }) {

{t('authoring.detail.structureOnly')}

{dirty &&

{t('authoring.detail.saveFirst')}

} + {draft.isError && void draft.refetch()} />} {files.isPending &&

{t('authoring.ui.loading')}

} {files.isError && void files.refetch()} />} - {files.isSuccess && } + {files.data && }

{t('authoring.detail.tabRuns')}