From b9449f6ec46a71079af9c396fcbca24532d7ab73 Mon Sep 17 00:00:00 2001 From: 235skw Date: Sat, 24 Oct 2026 08:45:35 +0000 Subject: [PATCH 1/6] =?UTF-8?q?fix:=20=E7=AC=AC1=E6=89=B9=20=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=AE=89=E5=85=A8=E4=BF=AE=E5=A4=8D=EF=BC=88=E5=A4=87?= =?UTF-8?q?=E4=BB=BD=E6=81=A2=E5=A4=8D=E6=A0=A1=E9=AA=8C=E3=80=81=E9=98=B2?= =?UTF-8?q?=E6=8A=96=E4=BF=9D=E5=AD=98flush=E3=80=81=E4=B8=BB=E5=AF=86?= =?UTF-8?q?=E9=92=A5=E9=98=B2=E8=A6=86=E7=9B=96=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- api.go | 20 +- api_diagram.go | 3 +- app.go | 32 ++- frontend/src/App.tsx | 42 +++- frontend/src/components/MainLayout.tsx | 10 +- frontend/src/components/NoteEditor.tsx | 78 ++++++ frontend/src/components/Sidebar.tsx | 2 + frontend/src/editorFlush.test.ts | 34 +++ frontend/src/editorFlush.ts | 21 ++ frontend/src/mainLayoutLoadRace.test.ts | 10 + frontend/wailsjs/go/main/App.d.ts | 2 + frontend/wailsjs/go/main/App.js | 4 + internal/attachments/attachments.go | 15 +- internal/backup/backup.go | 312 +++++++++++++++++------- internal/backup/backup_test.go | 209 ++++++++++++++++ internal/core/core.go | 62 +++-- internal/database/database.go | 30 ++- internal/fsutil/fsutil.go | 43 ++++ internal/fsutil/fsutil_test.go | 40 +++ internal/notes/notes.go | 82 +++++-- main.go | 1 + mobile/mobile.go | 17 +- 22 files changed, 886 insertions(+), 183 deletions(-) create mode 100644 frontend/src/editorFlush.test.ts create mode 100644 frontend/src/editorFlush.ts create mode 100644 frontend/src/mainLayoutLoadRace.test.ts create mode 100644 internal/backup/backup_test.go create mode 100644 internal/fsutil/fsutil.go create mode 100644 internal/fsutil/fsutil_test.go diff --git a/api.go b/api.go index 539919f..4aee962 100644 --- a/api.go +++ b/api.go @@ -8,6 +8,7 @@ import ( "errors" "locknote/internal/attachments" "locknote/internal/database" + "locknote/internal/fsutil" "locknote/internal/markdown" "locknote/internal/notebooks" "locknote/internal/notes" @@ -265,7 +266,7 @@ func (a *App) RestoreBackup() error { return nil } - return a.core.Backup().RestoreBackup(openPath) + return a.core.RestoreBackup(openPath) } func (a *App) ImportBackupWithKey(dataKey string) (int, error) { @@ -314,7 +315,7 @@ func (a *App) ExportNoteAsMarkdown(noteID string) (string, error) { if err != nil { return "", err } - err = writeFileAtomic(savePath, []byte(exportedContent)) + err = fsutil.WriteFileAtomic(savePath, []byte(exportedContent), 0600) if err != nil { return "", err } @@ -471,7 +472,7 @@ func (a *App) exportMarkdownAttachments(content, exportDir string, now time.Time } fileName := uniqueExportImageName(attachment.OriginalName, attachment.MIMEType, attachment.ID, usedNames) fileNames[id] = fileName - if err := writeFileAtomic(filepath.Join(assetsDirPath, fileName), data); err != nil { + if err := fsutil.WriteFileAtomic(filepath.Join(assetsDirPath, fileName), data, 0600); err != nil { return "", err } } @@ -614,19 +615,6 @@ func (a *App) DetachAttachmentFromNote(noteID, attachmentID string) error { return a.core.Attachments().DetachFromNote(noteID, attachmentID) } -func writeFileAtomic(path string, data []byte) error { - tempPath := path + ".tmp" - if err := os.WriteFile(tempPath, data, 0600); err != nil { - os.Remove(tempPath) - return err - } - if err := os.Rename(tempPath, path); err != nil { - os.Remove(tempPath) - return err - } - return nil -} - // Notebook APIs func (a *App) CreateNotebook(name, icon string) (*notebooks.Notebook, error) { diff --git a/api_diagram.go b/api_diagram.go index 657fbd3..98899c1 100644 --- a/api_diagram.go +++ b/api_diagram.go @@ -3,6 +3,7 @@ package main import ( "encoding/xml" "errors" + "locknote/internal/fsutil" "strings" "github.com/wailsapp/wails/v2/pkg/runtime" @@ -35,7 +36,7 @@ func saveDiagramSVG(svg string, choosePath func() (string, error)) (string, erro if !strings.HasSuffix(strings.ToLower(path), ".svg") { path += ".svg" } - if err := writeFileAtomic(path, []byte(svg)); err != nil { + if err := fsutil.WriteFileAtomic(path, []byte(svg), 0600); err != nil { return "", err } return path, nil diff --git a/app.go b/app.go index db6a69e..ee97f47 100644 --- a/app.go +++ b/app.go @@ -6,12 +6,14 @@ package main import ( "context" + "errors" "fmt" "locknote/internal/core" "log" "os" "path/filepath" "sync" + "sync/atomic" "time" "github.com/wailsapp/wails/v2/pkg/runtime" @@ -29,6 +31,8 @@ type App struct { windowWatcherOnce sync.Once watcherStop chan struct{} lastMinimized bool + allowClose atomic.Bool + closeRequestStart atomic.Bool } func NewApp() *App { @@ -150,6 +154,26 @@ func (a *App) shutdown(ctx context.Context) { } } +func (a *App) beforeClose(ctx context.Context) bool { + if a.allowClose.Load() { + return false + } + if a.closeRequestStart.CompareAndSwap(false, true) { + runtime.EventsEmit(ctx, "app:before-close") + time.AfterFunc(3*time.Second, func() { + if !a.allowClose.Swap(true) { + runtime.Quit(ctx) + } + }) + } + return true +} + +func (a *App) ConfirmClose() { + a.allowClose.Store(true) + runtime.Quit(a.ctx) +} + func (a *App) startWindowWatcher() { a.windowWatcher = time.NewTicker(500 * time.Millisecond) go func() { @@ -196,8 +220,12 @@ func (a *App) checkWindowState() { // ============ 委托给 core 的安全相关方法 ============ -func (a *App) IsFirstRun() bool { - return a.core.IsFirstRun() +func (a *App) IsFirstRun() (bool, error) { + c := a.getCoreIfReady() + if c == nil { + return false, errors.New("应用尚未就绪,请稍候重试") + } + return c.IsFirstRun() } func (a *App) SetupPassword(password, hint, displayKey string) (*core.SetupResult, error) { diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index d1e7114..56a9ea9 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -10,6 +10,7 @@ import { SetupScreen } from './components/SetupScreen'; import { StartupProgressScreen } from './components/StartupProgressScreen'; import * as App from '../wailsjs/go/main/App'; import { EventsEmit, EventsOn } from '../wailsjs/runtime/runtime'; +import { flushEditor } from './editorFlush'; // Extend Window interface for Wails runtime declare global { @@ -203,13 +204,15 @@ function AppRoot() { if (key === 'l') { e.preventDefault(); - App.Lock() - .then(() => { + void (async () => { + try { + await flushEditor(); + await App.Lock(); useStore.getState().setUnlocked(false); - }) - .catch((error) => { + } catch (error) { console.error('Failed to lock:', error); - }); + } + })(); return; } @@ -244,6 +247,35 @@ function AppRoot() { }; }, []); + useEffect(() => { + const handleVisibilityChange = () => { + if (document.visibilityState === 'hidden') { + void flushEditor(); + } + }; + const handleBlur = () => { + void flushEditor(); + }; + document.addEventListener('visibilitychange', handleVisibilityChange); + window.addEventListener('blur', handleBlur); + return () => { + document.removeEventListener('visibilitychange', handleVisibilityChange); + window.removeEventListener('blur', handleBlur); + }; + }, []); + + useEffect(() => { + const offBeforeClose = EventsOn('app:before-close', async () => { + await flushEditor(); + App.ConfirmClose().catch((error) => { + console.error('Failed to confirm window close:', error); + }); + }); + return () => { + offBeforeClose(); + }; + }, []); + // Track user activity to reset the idle lock timer useEffect(() => { if (!isUnlocked) { diff --git a/frontend/src/components/MainLayout.tsx b/frontend/src/components/MainLayout.tsx index ce6d9aa..2fc2843 100644 --- a/frontend/src/components/MainLayout.tsx +++ b/frontend/src/components/MainLayout.tsx @@ -59,21 +59,25 @@ export function MainLayout() { }, [setCommandPaletteOpen]); useEffect(() => { + let cancelled = false; const loadSelectedNote = async () => { if (selectedNoteId) { try { const note = await App.GetNote(selectedNoteId); - setSelectedNote(note); + if (!cancelled) setSelectedNote(note); } catch (error) { console.error('Failed to load note:', error); - setSelectedNote(null); + if (!cancelled) setSelectedNote(null); } - } else { + } else if (!cancelled) { setSelectedNote(null); } }; loadSelectedNote(); + return () => { + cancelled = true; + }; }, [selectedNoteId, setSelectedNote]); const renderContent = () => { diff --git a/frontend/src/components/NoteEditor.tsx b/frontend/src/components/NoteEditor.tsx index 19b36d6..4cd9456 100644 --- a/frontend/src/components/NoteEditor.tsx +++ b/frontend/src/components/NoteEditor.tsx @@ -9,6 +9,7 @@ import remarkGfm from 'remark-gfm'; import { useStore, EditorMode } from '../store'; import { formatMessage, useI18n } from '../i18n'; import { attachmentMarkdown, fileToDataURL, markdownUrlTransform, parseAttachmentId } from '../imageAttachments'; +import { registerEditorFlush } from '../editorFlush'; import { decodeTextBytes, detectTextEncoding, getDroppedTextTitle, isSupportedTextFile, TEXT_FILE_ENCODINGS, type TextFileEncoding } from '../droppedTextFile'; import { notes, tags } from '../../wailsjs/go/models'; import * as App from '../../wailsjs/go/main/App'; @@ -259,6 +260,7 @@ export function NoteEditor({ const latestDraftRef = useRef({ selectedNote, title, content }); latestDraftRef.current = { selectedNote, title, content }; const saveTimeoutRef = useRef | null>(null); + const pendingSaveRef = useRef<{ noteId: string; title: string; content: string } | null>(null); const tagMenuContainerRef = useRef(null); const contextMenuRef = useRef(null); const titleInputRef = useRef(null); @@ -520,6 +522,11 @@ export function NoteEditor({ current.title === snapshot.title && current.content === snapshot.content) { updateSelectedNote(updated); } + if (pendingSaveRef.current?.noteId === snapshot.selectedNote.id && + pendingSaveRef.current.title === snapshot.title && + pendingSaveRef.current.content === snapshot.content) { + pendingSaveRef.current = null; + } const notesList = await App.ListNotes(); const safeNotes = notesList || []; setNotes(safeNotes); @@ -539,6 +546,72 @@ export function NoteEditor({ return pending; }, [selectedNote, title, content, updateSelectedNote, setNotes, onNotesReloaded, t.common.error]); + const flushPendingSave = useCallback(async () => { + const pending = pendingSaveRef.current; + if (!pending) return; + if (saveTimeoutRef.current) { + clearTimeout(saveTimeoutRef.current); + saveTimeoutRef.current = null; + } + + const current = latestDraftRef.current; + if (current.selectedNote?.id === pending.noteId && + pending.title === current.selectedNote.title && + pending.content === current.selectedNote.content) { + pendingSaveRef.current = null; + return; + } + if (current.selectedNote?.id === pending.noteId && + current.title === pending.title && current.content === pending.content) { + if (await saveNote() && pendingSaveRef.current === pending) { + pendingSaveRef.current = null; + } + return; + } + + const save = saveQueueRef.current.then(async () => { + await App.UpdateNote(pending.noteId, pending.title, pending.content); + const notesList = await App.ListNotes(); + const safeNotes = notesList || []; + setNotes(safeNotes); + onNotesReloaded?.(safeNotes); + }); + saveQueueRef.current = save.catch(() => undefined); + await save; + if (pendingSaveRef.current === pending) { + pendingSaveRef.current = null; + } + }, [saveNote, setNotes, onNotesReloaded]); + + useEffect(() => registerEditorFlush(flushPendingSave), [flushPendingSave]); + + useEffect(() => { + const activeNote = selectedNote; + return () => { + const pending = pendingSaveRef.current; + if (!activeNote || !pending || pending.noteId !== activeNote.id) return; + if (pending.title === activeNote.title && pending.content === activeNote.content) { + pendingSaveRef.current = null; + return; + } + if (saveTimeoutRef.current) { + clearTimeout(saveTimeoutRef.current); + saveTimeoutRef.current = null; + } + pendingSaveRef.current = null; + const save = saveQueueRef.current.then(async () => { + await App.UpdateNote(pending.noteId, pending.title, pending.content); + const notesList = await App.ListNotes(); + const safeNotes = notesList || []; + setNotes(safeNotes); + onNotesReloaded?.(safeNotes); + }); + saveQueueRef.current = save.catch((error) => { + console.error('Failed to save note after selection changed:', error); + }); + }; + }, [selectedNote, setNotes, onNotesReloaded]); + useEffect(() => { if (!selectedNote) return; @@ -546,9 +619,14 @@ export function NoteEditor({ clearTimeout(saveTimeoutRef.current); } + const pending = { noteId: selectedNote.id, title, content }; + pendingSaveRef.current = pending; saveTimeoutRef.current = setTimeout(() => { + saveTimeoutRef.current = null; if (title !== selectedNote.title || content !== selectedNote.content) { saveNote(); + } else if (pendingSaveRef.current === pending) { + pendingSaveRef.current = null; } }, 800); diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 28d996b..73dd107 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -2,6 +2,7 @@ import { FileText, Search, Settings, Lock, Clock, CheckSquare, Image as ImageIco import { useStore, ViewType } from '../store'; import { useI18n } from '../i18n'; import * as App from '../../wailsjs/go/main/App'; +import { flushEditor } from '../editorFlush'; interface NavItem { id: ViewType; @@ -32,6 +33,7 @@ export function Sidebar() { ]; const handleLock = async () => { + await flushEditor(); await App.Lock(); setUnlocked(false); }; diff --git a/frontend/src/editorFlush.test.ts b/frontend/src/editorFlush.test.ts new file mode 100644 index 0000000..e6bf5b0 --- /dev/null +++ b/frontend/src/editorFlush.test.ts @@ -0,0 +1,34 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { flushEditor, registerEditorFlush } from './editorFlush.js'; + +test('flushEditor awaits the registered editor save and unregister removes it', async () => { + let completed = false; + const unregister = registerEditorFlush(async () => { + await Promise.resolve(); + completed = true; + }); + + await flushEditor(); + assert.equal(completed, true); + + unregister(); + completed = false; + await flushEditor(); + assert.equal(completed, false); +}); + +test('flushEditor swallows save errors', async () => { + const unregister = registerEditorFlush(async () => { + throw new Error('save failed'); + }); + let rejected = false; + try { + await flushEditor(); + } catch { + rejected = true; + } finally { + unregister(); + } + assert.equal(rejected, false); +}); diff --git a/frontend/src/editorFlush.ts b/frontend/src/editorFlush.ts new file mode 100644 index 0000000..2599e1c --- /dev/null +++ b/frontend/src/editorFlush.ts @@ -0,0 +1,21 @@ +type EditorFlushHandler = () => Promise; + +let editorFlushHandler: EditorFlushHandler | null = null; + +export function registerEditorFlush(fn: EditorFlushHandler): () => void { + editorFlushHandler = fn; + return () => { + if (editorFlushHandler === fn) { + editorFlushHandler = null; + } + }; +} + +export async function flushEditor(): Promise { + if (!editorFlushHandler) return; + try { + await editorFlushHandler(); + } catch (error) { + console.error('Failed to flush editor:', error); + } +} diff --git a/frontend/src/mainLayoutLoadRace.test.ts b/frontend/src/mainLayoutLoadRace.test.ts new file mode 100644 index 0000000..3f67026 --- /dev/null +++ b/frontend/src/mainLayoutLoadRace.test.ts @@ -0,0 +1,10 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; + +const source = readFileSync('src/components/MainLayout.tsx', 'utf8'); + +test('selected-note loads ignore responses after the selection changes', () => { + assert.equal(/let cancelled = false;[\s\S]*const note = await App\.GetNote\(selectedNoteId\);[\s\S]*if \(!cancelled\) setSelectedNote\(note\);/.test(source), true); + assert.equal(/return \(\) => \{\s*cancelled = true;\s*\};/.test(source), true); +}); diff --git a/frontend/wailsjs/go/main/App.d.ts b/frontend/wailsjs/go/main/App.d.ts index 8223b51..d58fe8c 100755 --- a/frontend/wailsjs/go/main/App.d.ts +++ b/frontend/wailsjs/go/main/App.d.ts @@ -19,6 +19,8 @@ export function BatchDeleteNotes(arg1:Array):Promise; export function ChangePassword(arg1:string,arg2:string,arg3:string):Promise; +export function ConfirmClose():Promise; + export function CreateBackup():Promise; export function CreateImageFromDataURL(arg1:string,arg2:string,arg3:string):Promise; diff --git a/frontend/wailsjs/go/main/App.js b/frontend/wailsjs/go/main/App.js index 1b0987e..5f83219 100755 --- a/frontend/wailsjs/go/main/App.js +++ b/frontend/wailsjs/go/main/App.js @@ -22,6 +22,10 @@ export function ChangePassword(arg1, arg2, arg3) { return window['go']['main']['App']['ChangePassword'](arg1, arg2, arg3); } +export function ConfirmClose() { + return window['go']['main']['App']['ConfirmClose'](); +} + export function CreateBackup() { return window['go']['main']['App']['CreateBackup'](); } diff --git a/internal/attachments/attachments.go b/internal/attachments/attachments.go index 1f92168..1641967 100644 --- a/internal/attachments/attachments.go +++ b/internal/attachments/attachments.go @@ -15,6 +15,7 @@ import ( _ "image/png" "locknote/internal/crypto" "locknote/internal/database" + "locknote/internal/fsutil" "os" "path/filepath" "strings" @@ -235,12 +236,7 @@ func (s *Service) writeEncryptedBytes(cipherPath string, key []byte, plaintext [ return err } - tempPath := fullPath + "." + uuid.NewString() + ".tmp" - if err := os.WriteFile(tempPath, ciphertext, 0600); err != nil { - return err - } - if err := os.Rename(tempPath, fullPath); err != nil { - _ = os.Remove(tempPath) + if err := fsutil.WriteFileAtomic(fullPath, ciphertext, 0600); err != nil { return err } return nil @@ -278,12 +274,7 @@ func (s *Service) CreateImage(input CreateImageInput) (*Attachment, error) { if err := os.MkdirAll(filepath.Dir(fullPath), 0700); err != nil { return nil, err } - tempPath := fullPath + ".tmp" - if err := os.WriteFile(tempPath, ciphertext, 0600); err != nil { - return nil, err - } - if err := os.Rename(tempPath, fullPath); err != nil { - _ = os.Remove(tempPath) + if err := fsutil.WriteFileAtomic(fullPath, ciphertext, 0600); err != nil { return nil, err } diff --git a/internal/backup/backup.go b/internal/backup/backup.go index b8ff538..9395ab8 100644 --- a/internal/backup/backup.go +++ b/internal/backup/backup.go @@ -5,14 +5,35 @@ package backup import ( "archive/zip" + "errors" "fmt" "io" + "locknote/internal/crypto" + "locknote/internal/fsutil" "os" "path/filepath" + "strconv" "strings" + "time" ) -const maxZipFileSize = 500 * 1024 * 1024 // 500 MB per file +var ( + maxZipFileSize int64 = 500 * 1024 * 1024 + maxZipTotalSize int64 = 4 * 1024 * 1024 * 1024 + maxZipEntries = 100000 + + sensitiveFiles = map[string]bool{ + "locknote.db": true, + "locknote.db-journal": true, + "locknote.db-wal": true, + "locknote.db-shm": true, + "notebase.db": true, + "notebase.db-journal": true, + "notebase.db-wal": true, + "notebase.db-shm": true, + "data_key_verifier": true, + } +) type Service struct { dataDir string @@ -22,70 +43,117 @@ func NewService(dataDir string) *Service { return &Service{dataDir: dataDir} } +func skippedBackupPath(name string) bool { + name = filepath.ToSlash(filepath.Clean(name)) + if sensitiveFiles[filepath.Base(name)] { + return true + } + return name == "restore-snapshots" || strings.HasPrefix(name, "restore-snapshots/") +} + +func safeZipDestination(root, name string) (string, string, bool) { + if filepath.IsAbs(name) { + return "", "", false + } + cleanName := filepath.Clean(filepath.FromSlash(name)) + if cleanName == "." || cleanName == ".." || strings.HasPrefix(cleanName, ".."+string(os.PathSeparator)) { + return "", "", false + } + if skippedBackupPath(cleanName) { + return "", "", false + } + destination := filepath.Join(root, cleanName) + relative, err := filepath.Rel(root, destination) + if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(os.PathSeparator)) { + return "", "", false + } + return destination, relative, true +} + func (s *Service) ExtractBackupToTemp(inputPath string) (string, error) { tempDir, err := os.MkdirTemp("", "locknote-import-*") if err != nil { return "", err } + if err := extractZip(inputPath, tempDir); err != nil { + _ = os.RemoveAll(tempDir) + return "", err + } + return tempDir, nil +} +func extractZip(inputPath, destinationDir string) error { reader, err := zip.OpenReader(inputPath) if err != nil { - os.RemoveAll(tempDir) - return "", err + return err } defer reader.Close() - for _, file := range reader.File { - destPath := filepath.Join(tempDir, file.Name) - cleanDestPath := filepath.Clean(destPath) + if len(reader.File) > maxZipEntries { + return fmt.Errorf("zip contains too many entries (%d)", len(reader.File)) + } - if !strings.HasPrefix(cleanDestPath, filepath.Clean(tempDir)+string(os.PathSeparator)) { + var totalSize int64 + for _, file := range reader.File { + destination, _, safe := safeZipDestination(destinationDir, file.Name) + if !safe { continue } - if file.FileInfo().IsDir() { - os.MkdirAll(cleanDestPath, 0700) + if err := os.MkdirAll(destination, 0700); err != nil { + return err + } continue } - - if file.UncompressedSize64 > maxZipFileSize { - os.RemoveAll(tempDir) - return "", fmt.Errorf("file %s exceeds size limit (%d bytes)", file.Name, file.UncompressedSize64) + if maxZipFileSize < 0 || file.UncompressedSize64 > uint64(maxZipFileSize) { + return fmt.Errorf("file %s exceeds size limit (%d bytes)", file.Name, maxZipFileSize) } - - if err := os.MkdirAll(filepath.Dir(cleanDestPath), 0700); err != nil { - os.RemoveAll(tempDir) - return "", err + if err := os.MkdirAll(filepath.Dir(destination), 0700); err != nil { + return err } - destFile, err := os.OpenFile(cleanDestPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) + source, err := file.Open() if err != nil { - os.RemoveAll(tempDir) - return "", err + return err } - - srcFile, err := file.Open() + output, err := os.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { - destFile.Close() - os.RemoveAll(tempDir) - return "", err + _ = source.Close() + return err } - - _, err = io.Copy(destFile, io.LimitReader(srcFile, maxZipFileSize+1)) - srcFile.Close() - destFile.Close() - - if err != nil { - os.RemoveAll(tempDir) - return "", err + remaining := maxZipTotalSize - totalSize + limit := maxZipFileSize + 1 + if remaining < limit { + limit = remaining + 1 + } + if limit < 0 { + limit = 0 + } + copied, copyErr := io.Copy(output, io.LimitReader(source, limit)) + sourceCloseErr := source.Close() + outputCloseErr := output.Close() + if copyErr != nil { + return copyErr + } + if sourceCloseErr != nil { + return sourceCloseErr + } + if outputCloseErr != nil { + return outputCloseErr + } + if copied > maxZipFileSize { + return fmt.Errorf("file %s exceeds size limit (%d bytes)", file.Name, maxZipFileSize) + } + totalSize += copied + if totalSize > maxZipTotalSize { + return fmt.Errorf("zip exceeds total size limit (%d bytes)", maxZipTotalSize) } } - - return tempDir, nil + return nil } func (s *Service) CleanupTempDir(tempDir string) { - os.RemoveAll(tempDir) + _ = os.RemoveAll(tempDir) } func (s *Service) CreateBackup(outputPath string) error { @@ -98,33 +166,22 @@ func (s *Service) CreateBackup(outputPath string) error { zipWriter := zip.NewWriter(zipFile) defer zipWriter.Close() - sensitiveFiles := map[string]bool{ - "locknote.db": true, - "locknote.db-journal": true, - "locknote.db-wal": true, - "locknote.db-shm": true, - "notebase.db": true, - "notebase.db-journal": true, - "notebase.db-wal": true, - "notebase.db-shm": true, - "data_key_verifier": true, - } - err = filepath.Walk(s.dataDir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } - if info.IsDir() { - return nil - } - relPath, err := filepath.Rel(s.dataDir, path) if err != nil { return err } - - if sensitiveFiles[filepath.Base(relPath)] { + if info.IsDir() { + if relPath == "restore-snapshots" { + return filepath.SkipDir + } + return nil + } + if skippedBackupPath(relPath) { return nil } @@ -132,7 +189,7 @@ func (s *Service) CreateBackup(outputPath string) error { if err != nil { return err } - header.Name = relPath + header.Name = filepath.ToSlash(relPath) header.Method = zip.Deflate writer, err := zipWriter.CreateHeader(header) @@ -156,53 +213,140 @@ func (s *Service) CreateBackup(outputPath string) error { return err } -func (s *Service) RestoreBackup(inputPath string) error { - reader, err := zip.OpenReader(inputPath) +func (s *Service) RestoreBackup(inputPath string, cryptoService *crypto.Service, key []byte) error { + if key == nil { + return errors.New("请先解锁") + } + tempDir, err := s.ExtractBackupToTemp(inputPath) if err != nil { return err } - defer reader.Close() - - for _, file := range reader.File { - destPath := filepath.Join(s.dataDir, file.Name) - cleanDestPath := filepath.Clean(destPath) + defer s.CleanupTempDir(tempDir) - if !strings.HasPrefix(cleanDestPath, filepath.Clean(s.dataDir)+string(os.PathSeparator)) { - continue + notesDir := filepath.Join(tempDir, "notes") + if _, err := os.Stat(notesDir); err != nil { + if os.IsNotExist(err) { + return errors.New("备份中没有笔记") } - - if file.FileInfo().IsDir() { - os.MkdirAll(cleanDestPath, 0700) - continue + return err + } + noteFiles := 0 + err = filepath.Walk(notesDir, func(path string, info os.FileInfo, walkErr error) error { + if walkErr != nil { + return walkErr } - - if file.UncompressedSize64 > maxZipFileSize { - return fmt.Errorf("file %s exceeds size limit (%d bytes)", file.Name, file.UncompressedSize64) + if info.IsDir() || filepath.Ext(info.Name()) != ".enc" { + return nil } - - if err := os.MkdirAll(filepath.Dir(cleanDestPath), 0700); err != nil { + noteFiles++ + ciphertext, err := os.ReadFile(path) + if err != nil { return err } + if _, err := cryptoService.Decrypt(key, ciphertext); err != nil { + return errors.New("该备份不属于当前密码库,请使用「用恢复密钥导入」") + } + return nil + }) + if err != nil { + return err + } + if noteFiles == 0 { + return errors.New("备份中没有笔记") + } - destFile, err := os.OpenFile(cleanDestPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) - if err != nil { - return err + snapshotDir := filepath.Join(s.dataDir, "restore-snapshots", strconv.FormatInt(time.Now().UnixNano(), 10)) + if err := os.MkdirAll(snapshotDir, 0700); err != nil { + return err + } + + var applied []string + snapshots := make(map[string]string) + newFiles := make(map[string]bool) + rollback := func(cause error) error { + var rollbackErr error + for i := len(applied) - 1; i >= 0; i-- { + destination := applied[i] + if snapshotPath, ok := snapshots[destination]; ok { + data, err := os.ReadFile(snapshotPath) + if err == nil { + err = fsutil.WriteFileAtomic(destination, data, 0600) + } + if err != nil { + rollbackErr = errors.Join(rollbackErr, err) + } + } else if newFiles[destination] { + if err := os.Remove(destination); err != nil && !os.IsNotExist(err) { + rollbackErr = errors.Join(rollbackErr, err) + } + } } + _ = os.RemoveAll(snapshotDir) + return errors.Join(cause, rollbackErr) + } - srcFile, err := file.Open() + err = filepath.Walk(tempDir, func(path string, info os.FileInfo, walkErr error) error { + if walkErr != nil { + return walkErr + } + if info.IsDir() { + return nil + } + relPath, err := filepath.Rel(tempDir, path) if err != nil { - destFile.Close() return err } - - _, err = io.Copy(destFile, io.LimitReader(srcFile, maxZipFileSize+1)) - srcFile.Close() - destFile.Close() - + if skippedBackupPath(relPath) { + return nil + } + destination := filepath.Join(s.dataDir, relPath) + if err := os.MkdirAll(filepath.Dir(destination), 0700); err != nil { + return err + } + snapshotPath := filepath.Join(snapshotDir, relPath) + if _, err := os.Stat(destination); err == nil { + if err := os.MkdirAll(filepath.Dir(snapshotPath), 0700); err != nil { + return err + } + source, err := os.Open(destination) + if err != nil { + return err + } + snapshot, err := os.OpenFile(snapshotPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) + if err != nil { + _ = source.Close() + return err + } + _, copyErr := io.Copy(snapshot, source) + sourceCloseErr := source.Close() + snapshotCloseErr := snapshot.Close() + if copyErr != nil { + return copyErr + } + if sourceCloseErr != nil { + return sourceCloseErr + } + if snapshotCloseErr != nil { + return snapshotCloseErr + } + snapshots[destination] = snapshotPath + } else if os.IsNotExist(err) { + newFiles[destination] = true + } else { + return err + } + data, err := os.ReadFile(path) if err != nil { return err } + if err := fsutil.WriteFileAtomic(destination, data, 0600); err != nil { + return err + } + applied = append(applied, destination) + return nil + }) + if err != nil { + return rollback(err) } - return nil } diff --git a/internal/backup/backup_test.go b/internal/backup/backup_test.go new file mode 100644 index 0000000..f046ee2 --- /dev/null +++ b/internal/backup/backup_test.go @@ -0,0 +1,209 @@ +package backup + +import ( + "archive/zip" + "bytes" + "os" + "path/filepath" + "testing" + + "locknote/internal/crypto" +) + +type zipTestEntry struct { + name string + data []byte +} + +func writeTestZip(t *testing.T, path string, entries []zipTestEntry) { + t.Helper() + file, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + writer := zip.NewWriter(file) + for _, entry := range entries { + part, err := writer.Create(entry.name) + if err != nil { + t.Fatal(err) + } + if _, err := part.Write(entry.data); err != nil { + t.Fatal(err) + } + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + if err := file.Close(); err != nil { + t.Fatal(err) + } +} + +func TestCreateBackupExcludesSensitiveFilesAndRestoreSnapshots(t *testing.T) { + dataDir := t.TempDir() + for _, name := range []string{"locknote.db", "data_key_verifier", "notes/note.enc", "restore-snapshots/123/notes/old.enc"} { + path := filepath.Join(dataDir, name) + if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("file"), 0600); err != nil { + t.Fatal(err) + } + } + + backupPath := filepath.Join(t.TempDir(), "backup.zip") + if err := NewService(dataDir).CreateBackup(backupPath); err != nil { + t.Fatal(err) + } + reader, err := zip.OpenReader(backupPath) + if err != nil { + t.Fatal(err) + } + defer reader.Close() + var names []string + for _, file := range reader.File { + names = append(names, file.Name) + } + if len(names) != 1 || names[0] != "notes/note.enc" { + t.Fatalf("backup entries = %v, want only notes/note.enc", names) + } +} + +func TestRestoreBackupOverwritesAndSnapshotsOriginal(t *testing.T) { + serviceCrypto := crypto.NewService() + key := serviceCrypto.DeriveDataKey("same-vault-key") + ciphertext, err := serviceCrypto.Encrypt(key, []byte("restored note")) + if err != nil { + t.Fatal(err) + } + dataDir := t.TempDir() + notePath := filepath.Join(dataDir, "notes", "aa", "note.enc") + if err := os.MkdirAll(filepath.Dir(notePath), 0700); err != nil { + t.Fatal(err) + } + oldContent := []byte("old ciphertext") + if err := os.WriteFile(notePath, oldContent, 0600); err != nil { + t.Fatal(err) + } + backupPath := filepath.Join(t.TempDir(), "backup.zip") + writeTestZip(t, backupPath, []zipTestEntry{{name: "notes/aa/note.enc", data: ciphertext}}) + + if err := NewService(dataDir).RestoreBackup(backupPath, serviceCrypto, key); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(notePath) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, ciphertext) { + t.Fatal("restored note ciphertext does not match backup") + } + snapshotRoot := filepath.Join(dataDir, "restore-snapshots") + var snapshotPath string + err = filepath.Walk(snapshotRoot, func(path string, info os.FileInfo, err error) error { + if err == nil && !info.IsDir() { + snapshotPath = path + } + return err + }) + if err != nil { + t.Fatal(err) + } + snapshot, err := os.ReadFile(snapshotPath) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(snapshot, oldContent) { + t.Fatalf("snapshot = %q, want %q", snapshot, oldContent) + } +} + +func TestRestoreBackupRejectsDifferentKeyWithoutChangingFiles(t *testing.T) { + serviceCrypto := crypto.NewService() + backupKey := serviceCrypto.DeriveDataKey("backup-key") + currentKey := serviceCrypto.DeriveDataKey("current-key") + ciphertext, err := serviceCrypto.Encrypt(backupKey, []byte("note")) + if err != nil { + t.Fatal(err) + } + dataDir := t.TempDir() + notePath := filepath.Join(dataDir, "notes", "note.enc") + if err := os.MkdirAll(filepath.Dir(notePath), 0700); err != nil { + t.Fatal(err) + } + original := []byte("unchanged") + if err := os.WriteFile(notePath, original, 0600); err != nil { + t.Fatal(err) + } + backupPath := filepath.Join(t.TempDir(), "backup.zip") + writeTestZip(t, backupPath, []zipTestEntry{{name: "notes/note.enc", data: ciphertext}}) + + if err := NewService(dataDir).RestoreBackup(backupPath, serviceCrypto, currentKey); err == nil { + t.Fatal("expected different-key restore to fail") + } + got, err := os.ReadFile(notePath) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, original) { + t.Fatalf("original file changed: got %q", got) + } +} + +func TestRestoreBackupSkipsSensitiveAndTraversalEntries(t *testing.T) { + serviceCrypto := crypto.NewService() + key := serviceCrypto.DeriveDataKey("same-vault") + ciphertext, err := serviceCrypto.Encrypt(key, []byte("note")) + if err != nil { + t.Fatal(err) + } + dataDir := t.TempDir() + originalDB := []byte("existing db") + if err := os.WriteFile(filepath.Join(dataDir, "locknote.db"), originalDB, 0600); err != nil { + t.Fatal(err) + } + originalVerifier := []byte("existing verifier") + if err := os.WriteFile(filepath.Join(dataDir, "data_key_verifier"), originalVerifier, 0600); err != nil { + t.Fatal(err) + } + outsidePath := filepath.Join(filepath.Dir(dataDir), "evil") + _ = os.Remove(outsidePath) + backupPath := filepath.Join(t.TempDir(), "backup.zip") + writeTestZip(t, backupPath, []zipTestEntry{ + {name: "notes/note.enc", data: ciphertext}, + {name: "locknote.db", data: []byte("malicious db")}, + {name: "data_key_verifier", data: []byte("malicious verifier")}, + {name: "../evil", data: []byte("outside")}, + }) + + if err := NewService(dataDir).RestoreBackup(backupPath, serviceCrypto, key); err != nil { + t.Fatal(err) + } + for name, want := range map[string][]byte{ + "locknote.db": originalDB, + "data_key_verifier": originalVerifier, + } { + got, err := os.ReadFile(filepath.Join(dataDir, name)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatalf("%s changed: got %q", name, got) + } + } + if _, err := os.Stat(outsidePath); !os.IsNotExist(err) { + t.Fatalf("traversal entry was written outside the data directory: %v", err) + } +} + +func TestExtractBackupRejectsOversizedEntry(t *testing.T) { + previousLimit := maxZipFileSize + maxZipFileSize = 3 + defer func() { maxZipFileSize = previousLimit }() + + backupPath := filepath.Join(t.TempDir(), "backup.zip") + writeTestZip(t, backupPath, []zipTestEntry{{name: "notes/oversized.enc", data: []byte("four")}}) + if _, err := NewService(t.TempDir()).ExtractBackupToTemp(backupPath); err == nil { + t.Fatal("expected oversized zip entry to fail") + } +} diff --git a/internal/core/core.go b/internal/core/core.go index 7b3f5fe..df31167 100644 --- a/internal/core/core.go +++ b/internal/core/core.go @@ -11,6 +11,7 @@ import ( "locknote/internal/backup" "locknote/internal/crypto" "locknote/internal/database" + "locknote/internal/fsutil" "locknote/internal/notebooks" "locknote/internal/notes" "locknote/internal/smartviews" @@ -43,6 +44,7 @@ type Core struct { backupService *backup.Service dataDir string + setupMu sync.Mutex isUnlocked bool dataKey []byte mu sync.RWMutex @@ -131,8 +133,12 @@ func (c *Core) GetDataDir() string { // ============ 安全与解锁相关 ============ // IsFirstRun 检查是否是首次运行(未设置主密码) -func (c *Core) IsFirstRun() bool { - return !c.db.HasMasterPassword() +func (c *Core) IsFirstRun() (bool, error) { + hasMasterPassword, err := c.db.HasMasterPassword() + if err != nil { + return false, err + } + return !hasMasterPassword, nil } func (c *Core) dataKeyVerifierFilePath() string { @@ -144,7 +150,7 @@ func (c *Core) writeDataKeyVerifierFile(dataKey []byte) error { if err != nil { return err } - return os.WriteFile(c.dataKeyVerifierFilePath(), ciphertext, 0600) + return fsutil.WriteFileAtomic(c.dataKeyVerifierFilePath(), ciphertext, 0600) } func (c *Core) verifyDataKeyWithFile(dataKey []byte) (bool, error) { @@ -165,43 +171,50 @@ func (c *Core) verifyDataKeyWithFile(dataKey []byte) (bool, error) { // SetupPassword 初始化主密码(首次运行时调用) func (c *Core) SetupPassword(password, hint, displayKey string) (*SetupResult, error) { + c.setupMu.Lock() + defer c.setupMu.Unlock() + + hasMasterPassword, err := c.db.HasMasterPassword() + if err != nil { + return nil, fmt.Errorf("无法读取密码库状态: %w", err) + } + if hasMasterPassword { + return nil, errors.New("密码库已存在,请使用解锁或恢复密钥重置") + } if len([]rune(password)) < minPasswordLength { return nil, errPasswordTooShort } - - c.mu.Lock() + dataKey, err := c.cryptoService.ParseDisplayKey(displayKey) + if err != nil { + return nil, errors.New("密钥格式不正确") + } salt, err := c.cryptoService.GenerateSalt() if err != nil { - c.mu.Unlock() return nil, err } passwordKey := c.cryptoService.DeriveKey(password, salt) - dataKey := c.cryptoService.DeriveDataKey(displayKey) encryptedDataKey, err := c.cryptoService.Encrypt(passwordKey, dataKey) if err != nil { - c.mu.Unlock() return nil, err } verifier, err := c.cryptoService.Encrypt(passwordKey, []byte("LOCKNOTE_VERIFY")) if err != nil { - c.mu.Unlock() return nil, err } - err = c.db.SaveMasterPassword(salt, verifier, hint, encryptedDataKey) - if err != nil { - c.mu.Unlock() + if err := c.writeDataKeyVerifierFile(dataKey); err != nil { return nil, err } - if err := c.writeDataKeyVerifierFile(dataKey); err != nil { - c.mu.Unlock() + if err := c.db.InsertMasterPassword(salt, verifier, hint, encryptedDataKey); err != nil { + _ = os.Remove(c.dataKeyVerifierFilePath()) return nil, err } + c.mu.Lock() c.dataKey = dataKey c.isUnlocked = true c.noteService.SetMasterKey(dataKey) @@ -236,28 +249,23 @@ func (c *Core) VerifyDataKey(displayKey string) (bool, error) { // Unlock 使用密码解锁 func (c *Core) Unlock(password string) (bool, error) { - c.mu.Lock() - mp, err := c.db.GetMasterPassword() if err != nil { - c.mu.Unlock() return false, err } - passwordKey := c.cryptoService.DeriveKey(password, mp.Salt) _, err = c.cryptoService.Decrypt(passwordKey, mp.Verifier) if err != nil { - c.mu.Unlock() return false, nil } dataKey, err := c.cryptoService.Decrypt(passwordKey, mp.EncryptedDataKey) if err != nil { - c.mu.Unlock() return false, nil } + c.mu.Lock() c.dataKey = dataKey c.isUnlocked = true c.noteService.SetMasterKey(dataKey) @@ -358,7 +366,7 @@ func (c *Core) ChangePassword(oldPassword, newPassword, newHint string) error { return err } - err = c.db.SaveMasterPassword(newSalt, newVerifier, newHint, newEncryptedDataKey) + err = c.db.UpdateMasterPassword(newSalt, newVerifier, newHint, newEncryptedDataKey) if err != nil { return err } @@ -411,7 +419,7 @@ func (c *Core) ResetPasswordWithDataKey(displayKey, newPassword, newHint string) return err } - err = c.db.SaveMasterPassword(newSalt, newVerifier, newHint, newEncryptedDataKey) + err = c.db.UpdateMasterPassword(newSalt, newVerifier, newHint, newEncryptedDataKey) if err != nil { c.mu.Unlock() return err @@ -529,6 +537,16 @@ func (c *Core) Backup() *backup.Service { return c.backupService } +func (c *Core) RestoreBackup(path string) error { + c.mu.RLock() + key := append([]byte(nil), c.dataKey...) + c.mu.RUnlock() + if key == nil { + return errors.New("请先解锁") + } + return c.backupService.RestoreBackup(path, c.cryptoService, key) +} + // ============ 设置相关 ============ // GetSettings 获取设置 diff --git a/internal/database/database.go b/internal/database/database.go index b16ec53..e126fe2 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -299,20 +299,40 @@ func (d *DB) addNotebookIdColumn() { d.db.Exec(`CREATE INDEX IF NOT EXISTS idx_notes_list ON notes(deleted_at, pinned DESC, sort_order ASC, updated_at DESC)`) } -func (d *DB) HasMasterPassword() bool { +func (d *DB) HasMasterPassword() (bool, error) { var count int - d.db.QueryRow("SELECT COUNT(*) FROM master_password").Scan(&count) - return count > 0 + if err := d.db.QueryRow("SELECT COUNT(*) FROM master_password").Scan(&count); err != nil { + return false, err + } + return count > 0, nil } -func (d *DB) SaveMasterPassword(salt, verifier []byte, hint string, encryptedDataKey []byte) error { +func (d *DB) InsertMasterPassword(salt, verifier []byte, hint string, encryptedDataKey []byte) error { _, err := d.db.Exec(` - INSERT OR REPLACE INTO master_password (id, salt, verifier, hint, encrypted_data_key) + INSERT INTO master_password (id, salt, verifier, hint, encrypted_data_key) VALUES (1, ?, ?, ?, ?) `, salt, verifier, hint, encryptedDataKey) return err } +func (d *DB) UpdateMasterPassword(salt, verifier []byte, hint string, encryptedDataKey []byte) error { + result, err := d.db.Exec(` + UPDATE master_password SET salt = ?, verifier = ?, hint = ?, encrypted_data_key = ? + WHERE id = 1 + `, salt, verifier, hint, encryptedDataKey) + if err != nil { + return err + } + rowsAffected, err := result.RowsAffected() + if err != nil { + return err + } + if rowsAffected != 1 { + return fmt.Errorf("master password record not found") + } + return nil +} + func (d *DB) GetMasterPassword() (*MasterPassword, error) { var mp MasterPassword err := d.db.QueryRow(` diff --git a/internal/fsutil/fsutil.go b/internal/fsutil/fsutil.go new file mode 100644 index 0000000..fbb167d --- /dev/null +++ b/internal/fsutil/fsutil.go @@ -0,0 +1,43 @@ +package fsutil + +import ( + "os" + "path/filepath" + "runtime" +) + +func WriteFileAtomic(path string, data []byte, perm os.FileMode) error { + dir := filepath.Dir(path) + temp, err := os.CreateTemp(dir, filepath.Base(path)+".tmp-*") + if err != nil { + return err + } + tempPath := temp.Name() + defer os.Remove(tempPath) + + if _, err := temp.Write(data); err != nil { + temp.Close() + return err + } + if err := temp.Sync(); err != nil { + temp.Close() + return err + } + if err := temp.Close(); err != nil { + return err + } + if err := os.Chmod(tempPath, perm); err != nil { + return err + } + if err := os.Rename(tempPath, path); err != nil { + return err + } + + if runtime.GOOS != "windows" { + if directory, err := os.Open(dir); err == nil { + _ = directory.Sync() + _ = directory.Close() + } + } + return nil +} diff --git a/internal/fsutil/fsutil_test.go b/internal/fsutil/fsutil_test.go new file mode 100644 index 0000000..03e3f28 --- /dev/null +++ b/internal/fsutil/fsutil_test.go @@ -0,0 +1,40 @@ +package fsutil + +import ( + "os" + "path/filepath" + "runtime" + "testing" +) + +func TestWriteFileAtomic(t *testing.T) { + path := filepath.Join(t.TempDir(), "note.enc") + want := []byte("encrypted content") + + if err := WriteFileAtomic(path, want, 0600); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(got) != string(want) { + t.Fatalf("content = %q, want %q", got, want) + } + if runtime.GOOS != "windows" { + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0600 { + t.Fatalf("permissions = %04o, want 0600", info.Mode().Perm()) + } + } + entries, err := os.ReadDir(filepath.Dir(path)) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Name() != filepath.Base(path) { + t.Fatalf("unexpected temporary files remain: %v", entries) + } +} diff --git a/internal/notes/notes.go b/internal/notes/notes.go index 8c61f08..44c94c3 100644 --- a/internal/notes/notes.go +++ b/internal/notes/notes.go @@ -7,9 +7,11 @@ import ( "archive/zip" "encoding/json" "errors" + "fmt" "io" "locknote/internal/crypto" "locknote/internal/database" + "locknote/internal/fsutil" "log" "os" "path/filepath" @@ -28,6 +30,12 @@ type Service struct { mu sync.RWMutex } +var ( + maxImportZipFileSize int64 = 500 * 1024 * 1024 + maxImportZipTotalSize int64 = 4 * 1024 * 1024 * 1024 + maxImportZipEntries = 100000 +) + type Note struct { ID string `json:"id"` Title string `json:"title"` @@ -139,12 +147,7 @@ func (s *Service) Create(title, content string) (*Note, error) { return nil, err } - tempPath := fullPath + ".tmp" - if err := os.WriteFile(tempPath, ciphertext, 0600); err != nil { - return nil, err - } - if err := os.Rename(tempPath, fullPath); err != nil { - os.Remove(tempPath) + if err := fsutil.WriteFileAtomic(fullPath, ciphertext, 0600); err != nil { return nil, err } @@ -279,13 +282,15 @@ func (s *Service) Update(id, title, content string) (*Note, error) { historyPath := s.buildCipherPath("history", historyID) historyFullPath := filepath.Join(s.dataDir, historyPath) if err := os.MkdirAll(filepath.Dir(historyFullPath), 0700); err == nil { - if err := os.WriteFile(historyFullPath, oldCiphertext, 0600); err == nil { + if err := fsutil.WriteFileAtomic(historyFullPath, oldCiphertext, 0600); err == nil { historyRecord = &database.NoteHistory{ ID: historyID, NoteID: id, CipherPath: historyPath, CreatedAt: time.Now(), } + } else { + log.Printf("[Update] failed to write history for note %s: %v", id, err) } } @@ -322,12 +327,7 @@ func (s *Service) Update(id, title, content string) (*Note, error) { } fullPath := filepath.Join(s.dataDir, meta.CipherPath) - tempPath := fullPath + ".tmp" - if err := os.WriteFile(tempPath, ciphertext, 0600); err != nil { - return nil, err - } - if err := os.Rename(tempPath, fullPath); err != nil { - os.Remove(tempPath) + if err := fsutil.WriteFileAtomic(fullPath, ciphertext, 0600); err != nil { return nil, err } @@ -864,23 +864,39 @@ func (s *Service) extractZip(zipPath, destDir string) error { } defer reader.Close() - const maxFileSize uint64 = 500 * 1024 * 1024 + if len(reader.File) > maxImportZipEntries { + return fmt.Errorf("zip contains too many entries (%d)", len(reader.File)) + } + root := filepath.Clean(destDir) + var totalSize int64 for _, file := range reader.File { - destPath := filepath.Join(destDir, file.Name) - cleanDestPath := filepath.Clean(destPath) - - if !strings.HasPrefix(cleanDestPath, filepath.Clean(destDir)+string(os.PathSeparator)) { + if filepath.IsAbs(file.Name) { + continue + } + cleanDestPath := filepath.Clean(filepath.Join(root, filepath.FromSlash(file.Name))) + relative, err := filepath.Rel(root, cleanDestPath) + if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(os.PathSeparator)) { continue } if file.FileInfo().IsDir() { - os.MkdirAll(cleanDestPath, 0700) + if err := os.MkdirAll(cleanDestPath, 0700); err != nil { + return err + } continue } - if file.UncompressedSize64 > maxFileSize { + if maxImportZipFileSize < 0 || file.UncompressedSize64 > uint64(maxImportZipFileSize) { return errors.New("file in zip exceeds size limit") } + remaining := maxImportZipTotalSize - totalSize + limit := maxImportZipFileSize + 1 + if remaining < limit { + limit = remaining + 1 + } + if limit < 0 { + limit = 0 + } if err := os.MkdirAll(filepath.Dir(cleanDestPath), 0700); err != nil { return err @@ -897,12 +913,24 @@ func (s *Service) extractZip(zipPath, destDir string) error { return err } - _, err = io.Copy(destFile, io.LimitReader(srcFile, int64(maxFileSize)+1)) - srcFile.Close() - destFile.Close() - - if err != nil { - return err + copied, copyErr := io.Copy(destFile, io.LimitReader(srcFile, limit)) + sourceCloseErr := srcFile.Close() + destCloseErr := destFile.Close() + if copyErr != nil { + return copyErr + } + if sourceCloseErr != nil { + return sourceCloseErr + } + if destCloseErr != nil { + return destCloseErr + } + if copied > maxImportZipFileSize { + return errors.New("file in zip exceeds size limit") + } + totalSize += copied + if totalSize > maxImportZipTotalSize { + return errors.New("zip exceeds total size limit") } } @@ -942,7 +970,7 @@ func (s *Service) MigrateOldNotes() (int, error) { continue } - if err := os.WriteFile(newFullPath, ciphertext, 0600); err != nil { + if err := fsutil.WriteFileAtomic(newFullPath, ciphertext, 0600); err != nil { continue } diff --git a/main.go b/main.go index 9b61b1a..7112594 100644 --- a/main.go +++ b/main.go @@ -30,6 +30,7 @@ func main() { BackgroundColour: &options.RGBA{R: 244, G: 251, B: 246, A: 1}, OnStartup: app.startup, OnShutdown: app.shutdown, + OnBeforeClose: app.beforeClose, Bind: []interface{}{ app, }, diff --git a/mobile/mobile.go b/mobile/mobile.go index 49dd6aa..f67cad8 100644 --- a/mobile/mobile.go +++ b/mobile/mobile.go @@ -39,8 +39,8 @@ func mobileCall[T any](operation string, zero T, fn func() (T, error)) (value T, func mobileCallRead[T any](operation string, zero T, fn func() (T, error)) (value T, err error) { value = zero - mobileMu.Lock() - defer mobileMu.Unlock() + mobileMu.RLock() + defer mobileMu.RUnlock() defer func() { if recovered := recover(); recovered != nil { value = zero @@ -116,11 +116,16 @@ func Close() { // IsFirstRun 检查是否是首次运行 func IsFirstRun() bool { - return mobileCallValue("IsFirstRun", true, func() bool { + return mobileCallValue("IsFirstRun", false, func() bool { if coreInstance == nil { - return true + return false + } + isFirstRun, err := coreInstance.IsFirstRun() + if err != nil { + fmt.Printf("locknote mobile IsFirstRun error: %v\n", err) + return false } - return coreInstance.IsFirstRun() + return isFirstRun }) } @@ -707,7 +712,7 @@ func RestoreBackup(inputPath string) error { if coreInstance == nil { return errNotInitialized } - return coreInstance.Backup().RestoreBackup(inputPath) + return coreInstance.RestoreBackup(inputPath) }) } From 69ee9bae6c66da9a5987e7eb52ea8b7f2a3f4fc9 Mon Sep 17 00:00:00 2001 From: 235skw Date: Sat, 24 Oct 2026 08:52:54 +0000 Subject: [PATCH 2/6] =?UTF-8?q?fix:=20=E7=AC=AC2=E6=89=B9=20=E5=81=A5?= =?UTF-8?q?=E5=A3=AE=E6=80=A7=E4=BF=AE=E5=A4=8D=EF=BC=88=E5=B0=B1=E7=BB=AA?= =?UTF-8?q?=E4=BF=9D=E6=8A=A4=E3=80=81=E8=BF=81=E7=A7=BB=E6=A0=A1=E9=AA=8C?= =?UTF-8?q?=E3=80=81=E7=AC=94=E8=AE=B0=E7=BC=93=E5=AD=98=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- api.go | 485 +++++++++++++++++++++---- api_test.go | 26 ++ app.go | 74 +++- frontend/src/App.tsx | 71 ++-- frontend/src/appStartup.test.ts | 17 +- frontend/src/components/NoteEditor.tsx | 18 +- frontend/src/i18n/locales/en-US.ts | 15 + frontend/src/i18n/locales/zh-CN.ts | 15 + frontend/src/i18n/locales/zh-TW.ts | 15 + frontend/src/markdownLinks.test.ts | 12 + internal/attachments/attachments.go | 8 + internal/attachments/limits_test.go | 23 ++ internal/core/core.go | 52 ++- internal/database/database.go | 91 +++-- internal/database/database_test.go | 59 +++ internal/fsutil/fsutil.go | 36 +- internal/notes/notes.go | 400 ++++++++++---------- internal/notes/notes_test.go | 50 +++ 18 files changed, 1077 insertions(+), 390 deletions(-) create mode 100644 api_test.go create mode 100644 frontend/src/markdownLinks.test.ts create mode 100644 internal/attachments/limits_test.go create mode 100644 internal/database/database_test.go diff --git a/api.go b/api.go index 4aee962..5bb3c7b 100644 --- a/api.go +++ b/api.go @@ -22,108 +22,209 @@ import ( "strconv" "strings" "time" + "unicode" "github.com/wailsapp/wails/v2/pkg/runtime" ) func (a *App) CreateNote(title, content string) (*notes.Note, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Notes().Create(title, content) + return c.Notes().Create(title, content) } func (a *App) GetNote(id string) (*notes.Note, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Notes().Get(id) + return c.Notes().Get(id) } func (a *App) UpdateNote(id, title, content string) (*notes.Note, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Notes().Update(id, title, content) + return c.Notes().Update(id, title, content) } func (a *App) SetNotePinned(id string, pinned bool) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Notes().SetPinned(id, pinned) + return c.Notes().SetPinned(id, pinned) } func (a *App) SoftDeleteNote(id string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Notes().SoftDelete(id) + return c.Notes().SoftDelete(id) } func (a *App) RestoreNote(id string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Notes().Restore(id) + return c.Notes().Restore(id) } func (a *App) DeleteNote(id string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Notes().Delete(id) + return c.Notes().Delete(id) } func (a *App) ListNotes() ([]*notes.Note, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Notes().List() + return c.Notes().List() } func (a *App) ListNotesPaginated(limit, offset int) (*notes.ListResult, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Notes().ListPaginated(limit, offset) + return c.Notes().ListPaginated(limit, offset) } func (a *App) SearchNotes(query string) ([]*notes.Note, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Notes().Search(query) + return c.Notes().Search(query) } func (a *App) MigrateOldNotes() (int, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return 0, coreErr + } + a.UpdateActivity() - return a.core.Notes().MigrateOldNotes() + return c.Notes().MigrateOldNotes() } func (a *App) ListDeletedNotes() ([]*notes.Note, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Notes().ListDeleted() + return c.Notes().ListDeleted() } func (a *App) GetNoteHistory(noteID string) ([]*notes.Note, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Notes().GetHistory(noteID) + return c.Notes().GetHistory(noteID) } func (a *App) RestoreNoteFromHistory(noteID, historyID string) (*notes.Note, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Notes().RestoreFromHistory(noteID, historyID) + return c.Notes().RestoreFromHistory(noteID, historyID) } func (a *App) CreateTag(name, color string) (*tags.Tag, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Tags().Create(name, color) + return c.Tags().Create(name, color) } func (a *App) UpdateTag(id, name, color string) (*tags.Tag, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Tags().Update(id, name, color) + return c.Tags().Update(id, name, color) } func (a *App) DeleteTag(id string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Tags().Delete(id) + return c.Tags().Delete(id) } func (a *App) ListTags() ([]*tags.Tag, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Tags().List() + return c.Tags().List() } func (a *App) AddTagToNote(noteID, tagID string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Tags().AddToNote(noteID, tagID) + return c.Tags().AddToNote(noteID, tagID) } func (a *App) RemoveTagFromNote(noteID, tagID string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Tags().RemoveFromNote(noteID, tagID) + return c.Tags().RemoveFromNote(noteID, tagID) } func parseOptionalDate(value string) (*time.Time, error) { @@ -141,16 +242,31 @@ func parseOptionalDate(value string) (*time.Time, error) { } func (a *App) ListTodos() ([]*todos.Todo, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Todos().List() + return c.Todos().List() } func (a *App) GetTodo(id string) (*todos.Todo, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Todos().Get(id) + return c.Todos().Get(id) } func (a *App) CreateTodo(title, priority, dueAt string) (*todos.Todo, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() parsedDueAt, err := parseOptionalDate(dueAt) @@ -163,10 +279,15 @@ func (a *App) CreateTodo(title, priority, dueAt string) (*todos.Todo, error) { Priority: priority, DueAt: parsedDueAt, } - return a.core.Todos().Create(input) + return c.Todos().Create(input) } func (a *App) UpdateTodo(id, title, priority, dueAt string) (*todos.Todo, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() parsedDueAt, err := parseOptionalDate(dueAt) @@ -174,7 +295,7 @@ func (a *App) UpdateTodo(id, title, priority, dueAt string) (*todos.Todo, error) return nil, err } - return a.core.Todos().Update(todos.UpdateTodoInput{ + return c.Todos().Update(todos.UpdateTodoInput{ ID: id, Title: title, Priority: priority, @@ -183,49 +304,94 @@ func (a *App) UpdateTodo(id, title, priority, dueAt string) (*todos.Todo, error) } func (a *App) SetTodoCompleted(id string, completed bool) (*todos.Todo, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Todos().SetCompleted(id, completed) + return c.Todos().SetCompleted(id, completed) } func (a *App) DeleteTodo(id string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Todos().Delete(id) + return c.Todos().Delete(id) } func (a *App) CreateTodoSubtask(todoID, title string) (*todos.Subtask, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Todos().CreateSubtask(todoID, title) + return c.Todos().CreateSubtask(todoID, title) } func (a *App) UpdateTodoSubtask(id, title string) (*todos.Subtask, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Todos().UpdateSubtask(id, title) + return c.Todos().UpdateSubtask(id, title) } func (a *App) SetTodoSubtaskCompleted(id string, completed bool) (*todos.Subtask, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Todos().SetSubtaskCompleted(id, completed) + return c.Todos().SetSubtaskCompleted(id, completed) } func (a *App) DeleteTodoSubtask(id string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Todos().DeleteSubtask(id) + return c.Todos().DeleteSubtask(id) } func (a *App) GetSettings() (*database.Settings, error) { - return a.core.GetSettings() + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + + return c.GetSettings() } func (a *App) UpdateSettings(autoLockMinutes int, lockOnMinimize, lockOnSleep bool) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + settings := &database.Settings{ AutoLockMinutes: autoLockMinutes, LockOnMinimize: lockOnMinimize, LockOnSleep: lockOnSleep, } - return a.core.UpdateSettings(settings) + return c.UpdateSettings(settings) } func (a *App) CreateBackup() (string, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return "", coreErr + } + a.UpdateActivity() savePath, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{ @@ -242,7 +408,7 @@ func (a *App) CreateBackup() (string, error) { return "", nil } - err = a.core.Backup().CreateBackup(savePath) + err = c.Backup().CreateBackup(savePath) if err != nil { return "", err } @@ -251,6 +417,11 @@ func (a *App) CreateBackup() (string, error) { } func (a *App) RestoreBackup() error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() openPath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{ @@ -266,10 +437,15 @@ func (a *App) RestoreBackup() error { return nil } - return a.core.RestoreBackup(openPath) + return c.RestoreBackup(openPath) } func (a *App) ImportBackupWithKey(dataKey string) (int, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return 0, coreErr + } + a.UpdateActivity() openPath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{ @@ -285,20 +461,25 @@ func (a *App) ImportBackupWithKey(dataKey string) (int, error) { return 0, nil } - return a.core.Notes().ImportFromBackup(openPath, dataKey) + return c.Notes().ImportFromBackup(openPath, dataKey) } func (a *App) ExportNoteAsMarkdown(noteID string) (string, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return "", coreErr + } + a.UpdateActivity() - note, err := a.core.Notes().Get(noteID) + note, err := c.Notes().Get(noteID) if err != nil { return "", err } savePath, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{ Title: "导出笔记", - DefaultFilename: note.Title + ".md", + DefaultFilename: sanitizeFileName(note.Title) + ".md", Filters: []runtime.FileFilter{ {DisplayName: "Markdown 文件", Pattern: "*.md"}, }, @@ -323,6 +504,26 @@ func (a *App) ExportNoteAsMarkdown(noteID string) (string, error) { return savePath, nil } +func sanitizeFileName(name string) string { + var sanitized strings.Builder + for _, char := range name { + if unicode.IsControl(char) || strings.ContainsRune(`/\:*?"<>|`, char) { + sanitized.WriteRune('_') + } else { + sanitized.WriteRune(char) + } + } + name = strings.Trim(sanitized.String(), " .") + runes := []rune(name) + if len(runes) > 100 { + name = strings.Trim(string(runes[:100]), " .") + } + if name == "" { + return "note" + } + return name +} + var attachmentURLPattern = regexp.MustCompile(`locknote-attachment://([A-Za-z0-9_-]+)`) func formatAssetsDirName(t time.Time) string { @@ -453,6 +654,11 @@ func createUniqueAssetsDir(baseDir string, now time.Time) (string, string, error } func (a *App) exportMarkdownAttachments(content, exportDir string, now time.Time) (string, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return "", coreErr + } + attachmentIDs := collectAttachmentIDs(content) if len(attachmentIDs) == 0 { return content, nil @@ -466,7 +672,7 @@ func (a *App) exportMarkdownAttachments(content, exportDir string, now time.Time fileNames := make(map[string]string, len(attachmentIDs)) usedNames := map[string]int{} for _, id := range attachmentIDs { - attachment, data, err := a.core.Attachments().GetData(id) + attachment, data, err := c.Attachments().GetData(id) if err != nil { return "", err } @@ -481,6 +687,11 @@ func (a *App) exportMarkdownAttachments(content, exportDir string, now time.Time } func (a *App) ImportMarkdown() (*notes.Note, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() openPath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{ @@ -502,7 +713,7 @@ func (a *App) ImportMarkdown() (*notes.Note, error) { } title := markdown.ExtractTitle(openPath, string(content)) - return a.core.Notes().Create(title, string(content)) + return c.Notes().Create(title, string(content)) } func parseImageDataURL(dataURL string) (string, []byte, error) { @@ -529,6 +740,11 @@ func imageMIMEFromFile(path string, data []byte) string { } func (a *App) ImportImage(noteID string) (*attachments.Attachment, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() openPath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{ @@ -552,7 +768,7 @@ func (a *App) ImportImage(noteID string) (*attachments.Attachment, error) { if mimeType == "" { return nil, errors.New("不支持的图片格式") } - return a.core.Attachments().CreateImage(attachments.CreateImageInput{ + return c.Attachments().CreateImage(attachments.CreateImageInput{ OriginalName: filepath.Base(openPath), MIMEType: mimeType, Data: data, @@ -561,111 +777,216 @@ func (a *App) ImportImage(noteID string) (*attachments.Attachment, error) { } func (a *App) CreateImageFromDataURL(noteID, originalName, dataURL string) (*attachments.Attachment, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Attachments().CreateImageFromDataURL(noteID, originalName, dataURL) + return c.Attachments().CreateImageFromDataURL(noteID, originalName, dataURL) } func (a *App) GetAttachmentDataURL(id string) (string, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return "", coreErr + } + a.UpdateActivity() - return a.core.Attachments().GetDataURL(id) + return c.Attachments().GetDataURL(id) } func (a *App) GetAttachmentThumbnailDataURL(id string) (string, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return "", coreErr + } + a.UpdateActivity() - return a.core.Attachments().GetThumbnailDataURL(id) + return c.Attachments().GetThumbnailDataURL(id) } func (a *App) ListAttachments() ([]*attachments.Attachment, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Attachments().ListImages() + return c.Attachments().ListImages() } func (a *App) ListDeletedAttachments() ([]*attachments.Attachment, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Attachments().ListDeletedImages() + return c.Attachments().ListDeletedImages() } func (a *App) SoftDeleteAttachment(id string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Attachments().SoftDelete(id) + return c.Attachments().SoftDelete(id) } func (a *App) RestoreAttachment(id string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Attachments().Restore(id) + return c.Attachments().Restore(id) } func (a *App) DeleteAttachment(id string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Attachments().Delete(id) + return c.Attachments().Delete(id) } func (a *App) SetAttachmentFavorite(id string, favorite bool) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Attachments().SetFavorite(id, favorite) + return c.Attachments().SetFavorite(id, favorite) } func (a *App) AttachAttachmentToNote(noteID, attachmentID string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Attachments().AttachToNote(noteID, attachmentID) + return c.Attachments().AttachToNote(noteID, attachmentID) } func (a *App) DetachAttachmentFromNote(noteID, attachmentID string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Attachments().DetachFromNote(noteID, attachmentID) + return c.Attachments().DetachFromNote(noteID, attachmentID) } // Notebook APIs func (a *App) CreateNotebook(name, icon string) (*notebooks.Notebook, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Notebooks().Create(name, icon) + return c.Notebooks().Create(name, icon) } func (a *App) UpdateNotebook(id, name, icon string) (*notebooks.Notebook, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Notebooks().Update(id, name, icon) + return c.Notebooks().Update(id, name, icon) } func (a *App) DeleteNotebook(id string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Notebooks().Delete(id) + return c.Notebooks().Delete(id) } func (a *App) ListNotebooks() ([]*notebooks.Notebook, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.Notebooks().List() + return c.Notebooks().List() } func (a *App) ReorderNotebooks(ids []string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Notebooks().ReorderNotebooks(ids) + return c.Notebooks().ReorderNotebooks(ids) } func (a *App) SetNotebookPinned(id string, pinned bool) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Notebooks().SetPinned(id, pinned) + return c.Notebooks().SetPinned(id, pinned) } func (a *App) SetNoteNotebook(noteID string, notebookID *string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Notes().SetNotebook(noteID, notebookID) + return c.Notes().SetNotebook(noteID, notebookID) } func (a *App) SetNotesNotebook(noteIDs []string, notebookID *string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Notes().SetNotesNotebook(noteIDs, notebookID) + return c.Notes().SetNotesNotebook(noteIDs, notebookID) } func (a *App) BatchDeleteNotes(noteIDs []string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Notes().BatchSoftDelete(noteIDs) + return c.Notes().BatchSoftDelete(noteIDs) } func (a *App) BatchAddTagToNotes(noteIDs []string, tagID string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() for _, noteID := range noteIDs { - if err := a.core.Tags().AddToNote(noteID, tagID); err != nil { + if err := c.Tags().AddToNote(noteID, tagID); err != nil { return err } } @@ -673,33 +994,63 @@ func (a *App) BatchAddTagToNotes(noteIDs []string, tagID string) error { } func (a *App) ReorderNotes(ids []string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.Notes().ReorderNotes(ids) + return c.Notes().ReorderNotes(ids) } // SmartView APIs func (a *App) CreateSmartView(name, icon string, filter smartviews.Filter) (*smartviews.SmartView, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.SmartViews().Create(name, icon, filter) + return c.SmartViews().Create(name, icon, filter) } func (a *App) UpdateSmartView(id, name, icon string, filter smartviews.Filter) (*smartviews.SmartView, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.SmartViews().Update(id, name, icon, filter) + return c.SmartViews().Update(id, name, icon, filter) } func (a *App) DeleteSmartView(id string) error { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return coreErr + } + a.UpdateActivity() - return a.core.SmartViews().Delete(id) + return c.SmartViews().Delete(id) } func (a *App) ListSmartViews() ([]*smartviews.SmartView, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.SmartViews().List() + return c.SmartViews().List() } func (a *App) GetSmartView(id string) (*smartviews.SmartView, error) { + c, coreErr := a.coreOrErr() + if coreErr != nil { + return nil, coreErr + } + a.UpdateActivity() - return a.core.SmartViews().Get(id) + return c.SmartViews().Get(id) } diff --git a/api_test.go b/api_test.go new file mode 100644 index 0000000..ff971f9 --- /dev/null +++ b/api_test.go @@ -0,0 +1,26 @@ +package main + +import ( + "strings" + "testing" +) + +func TestSanitizeFileName(t *testing.T) { + tests := []struct { + name string + want string + }{ + {"bad/name\\file:?.md", "bad_name_file__.md"}, + {" .hidden. ", "hidden"}, + {"\x00\x1f", "__"}, + {"...", "note"}, + } + for _, test := range tests { + if got := sanitizeFileName(test.name); got != test.want { + t.Errorf("sanitizeFileName(%q) = %q, want %q", test.name, got, test.want) + } + } + if got := len([]rune(sanitizeFileName(strings.Repeat("x", 101)))); got != 100 { + t.Fatalf("sanitized filename length = %d, want 100", got) + } +} diff --git a/app.go b/app.go index ee97f47..c26eff5 100644 --- a/app.go +++ b/app.go @@ -141,6 +141,14 @@ func (a *App) getCoreIfReady() *core.Core { } } +func (a *App) coreOrErr() (*core.Core, error) { + c := a.getCoreIfReady() + if c == nil { + return nil, errors.New("应用尚未就绪,请稍候重试") + } + return c, nil +} + func (a *App) startWindowWatcherOnce() { a.windowWatcherOnce.Do(func() { a.startWindowWatcher() @@ -221,55 +229,93 @@ func (a *App) checkWindowState() { // ============ 委托给 core 的安全相关方法 ============ func (a *App) IsFirstRun() (bool, error) { - c := a.getCoreIfReady() - if c == nil { - return false, errors.New("应用尚未就绪,请稍候重试") + c, err := a.coreOrErr() + if err != nil { + return false, err } return c.IsFirstRun() } func (a *App) SetupPassword(password, hint, displayKey string) (*core.SetupResult, error) { - return a.core.SetupPassword(password, hint, displayKey) + c, err := a.coreOrErr() + if err != nil { + return nil, err + } + return c.SetupPassword(password, hint, displayKey) } func (a *App) VerifyDataKey(displayKey string) (bool, error) { - return a.core.VerifyDataKey(displayKey) + c, err := a.coreOrErr() + if err != nil { + return false, err + } + return c.VerifyDataKey(displayKey) } func (a *App) Unlock(password string) (bool, error) { - return a.core.Unlock(password) + c, err := a.coreOrErr() + if err != nil { + return false, err + } + return c.Unlock(password) } func (a *App) Lock() { - a.core.Lock() + if c := a.getCoreIfReady(); c != nil { + c.Lock() + } } func (a *App) IsUnlocked() bool { - return a.core.IsUnlocked() + if c := a.getCoreIfReady(); c != nil { + return c.IsUnlocked() + } + return false } func (a *App) GetPasswordHint() (string, error) { - return a.core.GetPasswordHint() + c, err := a.coreOrErr() + if err != nil { + return "", err + } + return c.GetPasswordHint() } func (a *App) ChangePassword(oldPassword, newPassword, newHint string) error { - return a.core.ChangePassword(oldPassword, newPassword, newHint) + c, err := a.coreOrErr() + if err != nil { + return err + } + return c.ChangePassword(oldPassword, newPassword, newHint) } func (a *App) ResetPasswordWithDataKey(displayKey, newPassword, newHint string) error { - return a.core.ResetPasswordWithDataKey(displayKey, newPassword, newHint) + c, err := a.coreOrErr() + if err != nil { + return err + } + return c.ResetPasswordWithDataKey(displayKey, newPassword, newHint) } func (a *App) UpdateActivity() { - a.core.UpdateActivity() + if c := a.getCoreIfReady(); c != nil { + c.UpdateActivity() + } } func (a *App) GenerateDataKey() (string, error) { - return a.core.GenerateDataKey() + c, err := a.coreOrErr() + if err != nil { + return "", err + } + return c.GenerateDataKey() } func (a *App) GetDataDir() string { - return a.core.GetDataDir() + if c := a.getCoreIfReady(); c != nil { + return c.GetDataDir() + } + return "" } func (a *App) GetVersion() string { diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 56a9ea9..b25e4bb 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -11,6 +11,7 @@ import { StartupProgressScreen } from './components/StartupProgressScreen'; import * as App from '../wailsjs/go/main/App'; import { EventsEmit, EventsOn } from '../wailsjs/runtime/runtime'; import { flushEditor } from './editorFlush'; +import { formatMessage, useI18n } from './i18n'; // Extend Window interface for Wails runtime declare global { @@ -48,40 +49,27 @@ function isWailsRuntimeReady(): boolean { ); } -// Wait for Wails runtime to be ready. Windows cold starts can take longer on -// first launch while WebView2 and the Wails bridge warm up. async function waitForWailsRuntime(): Promise { - const checkInterval = 100; // Check every 100ms - - for (;;) { - if (isWailsRuntimeReady()) { - return; - } - await new Promise(resolve => setTimeout(resolve, checkInterval)); + if (!isWailsRuntimeReady()) { + throw new Error('Wails runtime is not ready'); } } -const wailsRuntimeReady = waitForWailsRuntime(); const FIRST_RUN_STARTUP_MINIMUM_MS = 1400; -async function waitForCoreReady(onStatus?: (message: string) => void): Promise { - const retryDelay = 300; - - for (;;) { - const ready = await App.IsCoreReady(); - if (ready) { - return; - } - - const startupError = await App.GetStartupError(); - if (startupError) { - onStatus?.(`启动失败:${startupError}`); - } else { - onStatus?.('正在准备本地数据...'); - } - - await new Promise(resolve => setTimeout(resolve, retryDelay)); +async function waitForCoreReady( + onStatus: ((message: string) => void) | undefined, + messages: { preparingData: string; failed: string }, +): Promise { + const ready = await App.IsCoreReady(); + if (ready) return; + const startupError = await App.GetStartupError(); + if (startupError) { + onStatus?.(formatMessage(messages.failed, { error: startupError })); + throw new Error(startupError); } + onStatus?.(messages.preparingData); + throw new Error('应用核心尚未就绪'); } async function waitForMinimumStartupDisplay(startedAt: number, firstRun: boolean): Promise { @@ -110,9 +98,10 @@ function throttle void>(func: T, limit: number } function AppRoot() { + const { t } = useI18n(); const { isUnlocked, isFirstRun, setUnlocked, setFirstRun, setVersion, setDataDir } = useStore(); const [loading, setLoading] = useState(true); - const [startupMessage, setStartupMessage] = useState('正在启动应用核心...'); + const [startupMessage, setStartupMessage] = useState(t.startup.starting); const [startupProgress, setStartupProgress] = useState(8); const [showOnboarding, setShowOnboarding] = useState(false); @@ -126,12 +115,9 @@ function AppRoot() { }, []); useEffect(() => { - // Only emit frontend:ready after runtime is ready - const emitReady = async () => { - await wailsRuntimeReady; - EventsEmit('frontend:ready'); - }; - emitReady(); + void waitForWailsRuntime() + .then(() => EventsEmit('frontend:ready')) + .catch((error) => console.error('Failed to emit frontend readiness:', error)); }, []); useEffect(() => { @@ -142,11 +128,11 @@ function AppRoot() { try { // First, wait for Wails runtime to be ready setStartupProgress(18); - await wailsRuntimeReady; + await waitForWailsRuntime(); setStartupProgress(34); - await waitForCoreReady(setStartupMessage); + await waitForCoreReady(setStartupMessage, t.startup); - setStartupMessage('正在读取本地数据...'); + setStartupMessage(t.startup.readingData); setStartupProgress(68); const firstRun = await App.IsFirstRun(); setFirstRun(firstRun); @@ -163,7 +149,7 @@ function AppRoot() { setDataDir(dataDir); if (firstRun) { - setStartupMessage('正在初始化...'); + setStartupMessage(t.startup.initializing); } setStartupProgress(92); await waitForMinimumStartupDisplay(startupStartedAt, firstRun); @@ -171,8 +157,13 @@ function AppRoot() { setLoading(false); } catch (error) { console.error('Init error:', error); + if (retryCount >= 120) { + setStartupMessage(formatMessage(t.startup.failed, { error: String(error) })); + setStartupProgress(100); + return; + } // Retry on failure - WebView2 may still be initializing on Windows first run. - setStartupMessage(`正在启动应用核心... (${retryCount + 1})`); + setStartupMessage(formatMessage(t.startup.retrying, { count: retryCount + 1 })); setStartupProgress(12); await new Promise(resolve => setTimeout(resolve, retryDelay)); return init(retryCount + 1); @@ -180,7 +171,7 @@ function AppRoot() { }; init(); - }, [setFirstRun, setUnlocked, setVersion, setDataDir]); + }, [setFirstRun, setUnlocked, setVersion, setDataDir, t.startup]); useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { diff --git a/frontend/src/appStartup.test.ts b/frontend/src/appStartup.test.ts index 27faca1..b874807 100644 --- a/frontend/src/appStartup.test.ts +++ b/frontend/src/appStartup.test.ts @@ -7,25 +7,24 @@ const onboardingSource = readFileSync('src/components/OnboardingScreen.tsx', 'ut const startupProgressSource = readFileSync('src/components/StartupProgressScreen.tsx', 'utf8'); test('App waits for Wails runtime without falling through to the first-run screen on Windows cold start', () => { - assert.equal(/const wailsRuntimeReady = waitForWailsRuntime\(\);/.test(source), true); - assert.equal(/waitForWailsRuntime\(maxWaitTime = 10000\)/.test(source), false); - assert.equal(/Date\.now\(\) - startTime < maxWaitTime/.test(source), false); - assert.equal(/Wails runtime not ready after timeout[\s\S]*setLoading\(false\)/.test(source), false); - assert.equal(/await wailsRuntimeReady;/.test(source), true); + assert.equal(/async function waitForWailsRuntime/.test(source), true); + assert.equal(/if \(!isWailsRuntimeReady\(\)\)/.test(source), true); + assert.equal(/await waitForWailsRuntime\(\);/.test(source), true); }); test('App waits for background core initialization before calling first-run APIs', () => { assert.equal(/waitForCoreReady/.test(source), true); - assert.equal(/await waitForCoreReady\(setStartupMessage\);/.test(source), true); + assert.equal(/await waitForCoreReady\(setStartupMessage, t\.startup\);/.test(source), true); assert.equal(/App\.IsCoreReady/.test(source), true); assert.equal(/App\.GetStartupError/.test(source), true); - assert.equal(source.indexOf('await waitForCoreReady(setStartupMessage);') < source.indexOf('const firstRun = await App.IsFirstRun();'), true); + assert.equal(source.indexOf('await waitForCoreReady(setStartupMessage, t.startup);') < source.indexOf('const firstRun = await App.IsFirstRun();'), true); }); test('App shows a cold-start message while the Windows runtime is still warming up', () => { assert.equal(/const \[startupMessage, setStartupMessage\]/.test(source), true); - assert.equal(/useState\('正在启动应用核心\.\.\.'\)/.test(source), true); - assert.equal(/setStartupMessage\(`正在启动应用核心\.\.\. \(\$\{retryCount \+ 1\}\)`\)/.test(source), true); + assert.equal(/retryCount >= 120/.test(source), true); + assert.equal(/setStartupMessage\(formatMessage\(t\.startup\.failed/.test(source), true); + assert.equal(/setStartupProgress\(100\)/.test(source), true); assert.equal(/ & } const markdownComponents: Components = { + a: ({ href, children, ...props }) => ( + { + if (href?.startsWith('#')) return; + event.preventDefault(); + if (href && /^(https?:|mailto:)/i.test(href)) BrowserOpenURL(href); + }} + > + {children} + + ), img: AttachmentImage, pre: PreviewCodeBlock, }; function PreviewMarkdown({ markdown, fontSize, collapsedByDefault = false }: { markdown: string; fontSize: string; collapsedByDefault?: boolean }) { + const { t } = useI18n(); const headingPrefix = useId(); const [tocOpen, setTocOpen] = useState(!collapsedByDefault); const [tocMaxHeight, setTocMaxHeight] = useState(0); @@ -204,7 +218,7 @@ function PreviewMarkdown({ markdown, fontSize, collapsedByDefault = false }: { m scrollContainer.scrollTo({ top: targetTop, behavior: 'instant' as ScrollBehavior }); } }; - return
{markdown}
{toc.length > 0 && }
; + return
{markdown}
{toc.length > 0 && }
; } interface NoteEditorProps { diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index df62a31..79f4ebb 100644 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -37,6 +37,15 @@ export const enUS: Translations = { redo: 'Redo', }, + startup: { + starting: 'Starting application core...', + retrying: 'Starting application core... ({count})', + preparingData: 'Preparing local data...', + readingData: 'Reading local data...', + initializing: 'Initializing...', + failed: 'The app failed to start. Try again later or reopen the app: {error}', + }, + // Sidebar sidebar: { notes: 'Notes', @@ -71,6 +80,8 @@ export const enUS: Translations = { rename: 'Rename', moveTo: 'Move to...', deleteNote: 'Delete', + expandLeftList: 'Expand note list', + collapseLeftList: 'Collapse note list', deleteNoteTitle: 'Delete note?', deleteNoteDesc: 'The note will be moved to trash. You can restore it later.', deleteNotebookTitle: 'Delete notebook?', @@ -125,6 +136,9 @@ export const enUS: Translations = { tagsTooltip: 'Tags', historyTooltip: 'Version history', exportTooltip: 'Export', + tableOfContents: 'Contents', + collapseTableOfContents: 'Collapse contents', + expandTableOfContents: 'Expand contents', selectNote: 'Select a note to edit', selectNoteTip: 'Select a note from the list or create a new one', lastEdited: 'Last edited', @@ -320,6 +334,7 @@ export const enUS: Translations = { importMarkdownDesc: 'Import notes from Markdown files', backupSuccess: 'Backup successful', backupFailed: 'Backup failed', + securityHint: 'Backups include notes, history, and attachments only; Restore Backup works only within the same vault. To move to another device or vault, use recovery-key import.', restoreSuccess: 'Restore successful', restoreFailed: 'Restore failed', importSuccess: 'Import successful', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 1e1a693..595ef78 100644 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -35,6 +35,15 @@ export const zhCN = { redo: '重做', }, + startup: { + starting: '正在启动应用核心...', + retrying: '正在启动应用核心... ({count})', + preparingData: '正在准备本地数据...', + readingData: '正在读取本地数据...', + initializing: '正在初始化...', + failed: '应用启动失败,请稍后重试或重新打开应用:{error}', + }, + // 侧边栏 sidebar: { notes: '笔记', @@ -69,6 +78,8 @@ export const zhCN = { rename: '重命名', moveTo: '移动到...', deleteNote: '删除', + expandLeftList: '展开左侧列表', + collapseLeftList: '收起左侧列表', deleteNoteTitle: '删除笔记?', deleteNoteDesc: '该笔记将移动到回收站,你可以稍后在回收站中恢复。', deleteNotebookTitle: '删除笔记本?', @@ -123,6 +134,9 @@ export const zhCN = { tagsTooltip: '标签', historyTooltip: '历史版本', exportTooltip: '导出', + tableOfContents: '目录', + collapseTableOfContents: '收起目录', + expandTableOfContents: '展开目录', selectNote: '选择一篇笔记开始编辑', selectNoteTip: '从左侧列表选择笔记,或创建新笔记', lastEdited: '最后编辑于', @@ -318,6 +332,7 @@ export const zhCN = { importMarkdownDesc: '从 Markdown 文件导入笔记', backupSuccess: '备份成功', backupFailed: '备份失败', + securityHint: '备份仅包含笔记、历史版本和附件;“恢复备份”仅适用于同一密码库。迁移到其他设备或密码库,请使用恢复密钥导入。', restoreSuccess: '恢复成功', restoreFailed: '恢复失败', importSuccess: '导入成功', diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index 94f9a28..91fce27 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -37,6 +37,15 @@ export const zhTW: Translations = { redo: '重做', }, + startup: { + starting: '正在啟動應用程式核心...', + retrying: '正在啟動應用程式核心... ({count})', + preparingData: '正在準備本機資料...', + readingData: '正在讀取本機資料...', + initializing: '正在初始化...', + failed: '應用程式啟動失敗,請稍後重試或重新開啟應用程式:{error}', + }, + // 側邊欄 sidebar: { notes: '筆記', @@ -71,6 +80,8 @@ export const zhTW: Translations = { rename: '重新命名', moveTo: '移動到...', deleteNote: '刪除', + expandLeftList: '展開左側列表', + collapseLeftList: '收起左側列表', deleteNoteTitle: '刪除筆記?', deleteNoteDesc: '該筆記將移動到回收站,你可以稍後在回收站中還原。', deleteNotebookTitle: '刪除筆記本?', @@ -125,6 +136,9 @@ export const zhTW: Translations = { tagsTooltip: '標籤', historyTooltip: '歷史版本', exportTooltip: '匯出', + tableOfContents: '目錄', + collapseTableOfContents: '收起目錄', + expandTableOfContents: '展開目錄', selectNote: '選擇一篇筆記開始編輯', selectNoteTip: '從左側列表選擇筆記,或建立新筆記', lastEdited: '最後編輯於', @@ -320,6 +334,7 @@ export const zhTW: Translations = { importMarkdownDesc: '從 Markdown 檔案匯入筆記', backupSuccess: '備份成功', backupFailed: '備份失敗', + securityHint: '備份僅包含筆記、歷史版本和附件;「還原備份」僅適用於同一密碼庫。移轉到其他裝置或密碼庫,請使用復原金鑰匯入。', restoreSuccess: '還原成功', restoreFailed: '還原失敗', importSuccess: '匯入成功', diff --git a/frontend/src/markdownLinks.test.ts b/frontend/src/markdownLinks.test.ts new file mode 100644 index 0000000..a23b80f --- /dev/null +++ b/frontend/src/markdownLinks.test.ts @@ -0,0 +1,12 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; + +const source = readFileSync('src/components/NoteEditor.tsx', 'utf8'); + +test('Markdown links allow fragments, open approved schemes externally, and block other schemes', () => { + assert.equal(/href\?\.startsWith\('#'\)/.test(source), true); + assert.equal(/https\?:\|mailto:/i.test(source), true); + assert.equal(/BrowserOpenURL\(href\)/.test(source), true); + assert.equal(/event\.preventDefault\(\)/.test(source), true); +}); diff --git a/internal/attachments/attachments.go b/internal/attachments/attachments.go index 1641967..82da90d 100644 --- a/internal/attachments/attachments.go +++ b/internal/attachments/attachments.go @@ -37,6 +37,8 @@ type Service struct { const thumbnailMaxPixelSize = 384 +var maxImageBytes = 50 << 20 + type CreateImageInput struct { OriginalName string MIMEType string @@ -142,6 +144,9 @@ func ParseImageDataURL(dataURL string) (string, []byte, error) { if len(parts) != 2 { return "", nil, errors.New("invalid image data URL") } + if len(parts[1]) > maxImageBytes*4/3+16 { + return "", nil, errors.New("image data exceeds 50 MiB limit") + } mimeType := strings.ToLower(strings.TrimSpace(parts[0])) if !strings.HasPrefix(mimeType, "image/") { return "", nil, errors.New("data URL is not an image") @@ -258,6 +263,9 @@ func (s *Service) CreateImage(input CreateImageInput) (*Attachment, error) { if len(input.Data) == 0 { return nil, errors.New("image data is required") } + if len(input.Data) > maxImageBytes { + return nil, errors.New("image data exceeds 50 MiB limit") + } mimeType, err := normalizeImageMIME(input.MIMEType) if err != nil { return nil, err diff --git a/internal/attachments/limits_test.go b/internal/attachments/limits_test.go new file mode 100644 index 0000000..7dbbf83 --- /dev/null +++ b/internal/attachments/limits_test.go @@ -0,0 +1,23 @@ +package attachments + +import ( + "bytes" + "strings" + "testing" +) + +func TestImageUploadLimitsAreCheckedBeforeDecodeOrWrite(t *testing.T) { + originalLimit := maxImageBytes + maxImageBytes = 3 + t.Cleanup(func() { maxImageBytes = originalLimit }) + + if _, _, err := ParseImageDataURL("data:image/png;base64," + strings.Repeat("A", maxImageBytes*4/3+17)); err == nil { + t.Fatal("expected oversized base64 payload to be rejected") + } + + service := NewService(nil, "") + service.SetMasterKey(bytes.Repeat([]byte{1}, 32)) + if _, err := service.CreateImage(CreateImageInput{MIMEType: "image/png", Data: []byte{1, 2, 3, 4}}); err == nil { + t.Fatal("expected oversized image bytes to be rejected") + } +} diff --git a/internal/core/core.go b/internal/core/core.go index df31167..d980c36 100644 --- a/internal/core/core.go +++ b/internal/core/core.go @@ -17,6 +17,7 @@ import ( "locknote/internal/smartviews" "locknote/internal/tags" "locknote/internal/todos" + "log" "os" "path/filepath" "sync" @@ -44,13 +45,17 @@ type Core struct { backupService *backup.Service dataDir string - setupMu sync.Mutex - isUnlocked bool - dataKey []byte - mu sync.RWMutex - lastActivity time.Time - lockTimer *time.Timer - lockCallback LockCallback + setupMu sync.Mutex + settingsMu sync.Mutex + autoLockMinutes int + autoLockMinutesLoaded bool + autoLockSettingsErr error + isUnlocked bool + dataKey []byte + mu sync.RWMutex + lastActivity time.Time + lockTimer *time.Timer + lockCallback LockCallback } // SetupResult 是初始化密码后的返回结果 @@ -447,7 +452,23 @@ func (c *Core) UpdateActivity() { } func (c *Core) startLockTimer() { - settings, _ := c.db.GetSettings() + c.settingsMu.Lock() + if !c.autoLockMinutesLoaded { + settings, err := c.db.GetSettings() + c.autoLockMinutesLoaded = true + if err != nil { + c.autoLockSettingsErr = err + } else { + c.autoLockMinutes = settings.AutoLockMinutes + } + } + autoLockMinutes := c.autoLockMinutes + settingsErr := c.autoLockSettingsErr + c.settingsMu.Unlock() + if settingsErr != nil { + log.Printf("failed to read auto-lock setting: %v", settingsErr) + return + } c.mu.Lock() defer c.mu.Unlock() @@ -457,11 +478,11 @@ func (c *Core) startLockTimer() { c.lockTimer = nil } - if settings == nil || settings.AutoLockMinutes <= 0 { + if autoLockMinutes <= 0 { return } - autoLockDuration := time.Duration(settings.AutoLockMinutes) * time.Minute + autoLockDuration := time.Duration(autoLockMinutes) * time.Minute c.lockTimer = time.AfterFunc(autoLockDuration, func() { c.mu.RLock() @@ -544,7 +565,11 @@ func (c *Core) RestoreBackup(path string) error { if key == nil { return errors.New("请先解锁") } - return c.backupService.RestoreBackup(path, c.cryptoService, key) + if err := c.backupService.RestoreBackup(path, c.cryptoService, key); err != nil { + return err + } + c.noteService.ClearContentCache() + return nil } // ============ 设置相关 ============ @@ -560,6 +585,11 @@ func (c *Core) UpdateSettings(s *database.Settings) error { if err != nil { return err } + c.settingsMu.Lock() + c.autoLockMinutes = s.AutoLockMinutes + c.autoLockMinutesLoaded = true + c.autoLockSettingsErr = nil + c.settingsMu.Unlock() // 设置更新后重启计时器,使新的 autoLockMinutes 立即生效 c.startLockTimer() return nil diff --git a/internal/database/database.go b/internal/database/database.go index e126fe2..b60d8a5 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -6,10 +6,13 @@ package database import ( "database/sql" "fmt" + "log" "strings" "time" ) +const schemaVersion = 1 + func parseSQLiteTime(v any) (time.Time, error) { switch t := v.(type) { case time.Time: @@ -141,6 +144,17 @@ func New(dbPath string) (*DB, error) { db.SetMaxOpenConns(1) db.SetMaxIdleConns(1) + if _, err := db.Exec(`PRAGMA busy_timeout = 5000;`); err != nil { + _ = db.Close() + return nil, err + } + var journalMode string + if err := db.QueryRow(`PRAGMA journal_mode = WAL;`).Scan(&journalMode); err != nil { + log.Printf("failed to enable SQLite WAL mode: %v", err) + } else if !strings.EqualFold(journalMode, "wal") { + log.Printf("SQLite journal mode is %q; WAL was requested", journalMode) + } + // Ensure FK constraints are enforced. if _, err := db.Exec(`PRAGMA foreign_keys = ON;`); err != nil { _ = db.Close() @@ -255,48 +269,61 @@ func (d *DB) migrate() error { return err } - d.addNotebookIdColumn() - - return nil + if err := d.addNotebookIdColumn(); err != nil { + return err + } + _, err = d.db.Exec(fmt.Sprintf(`PRAGMA user_version = %d;`, schemaVersion)) + return err } -func (d *DB) addNotebookIdColumn() { +func (d *DB) hasColumn(table, name string) (bool, error) { var count int - err := d.db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('notes') WHERE name='notebook_id'`).Scan(&count) - if err != nil || count == 0 { - d.db.Exec(`ALTER TABLE notes ADD COLUMN notebook_id TEXT REFERENCES notebooks(id) ON DELETE SET NULL`) - d.db.Exec(`CREATE INDEX IF NOT EXISTS idx_notes_notebook_id ON notes(notebook_id)`) + query := fmt.Sprintf(`SELECT COUNT(*) FROM pragma_table_info('%s') WHERE name = ?`, table) + if err := d.db.QueryRow(query, name).Scan(&count); err != nil { + return false, err } + return count > 0, nil +} - err = d.db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('notes') WHERE name='sort_order'`).Scan(&count) - if err != nil || count == 0 { - d.db.Exec(`ALTER TABLE notes ADD COLUMN sort_order INTEGER DEFAULT 0`) - d.db.Exec(`CREATE INDEX IF NOT EXISTS idx_notes_sort_order ON notes(sort_order)`) +func (d *DB) ensureColumn(table, name, statement string) error { + exists, err := d.hasColumn(table, name) + if err != nil { + return err } - - // Add pinned column to notebooks table if not exists - err = d.db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('notebooks') WHERE name='pinned'`).Scan(&count) - if err != nil || count == 0 { - d.db.Exec(`ALTER TABLE notebooks ADD COLUMN pinned INTEGER DEFAULT 0`) - d.db.Exec(`CREATE INDEX IF NOT EXISTS idx_notebooks_pinned ON notebooks(pinned)`) + if exists { + return nil } + _, err = d.db.Exec(statement) + return err +} - // Add created_at and updated_at columns to notebooks table if not exists - err = d.db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('notebooks') WHERE name='created_at'`).Scan(&count) - if err != nil || count == 0 { - d.db.Exec(`ALTER TABLE notebooks ADD COLUMN created_at DATETIME DEFAULT CURRENT_TIMESTAMP`) - d.db.Exec(`ALTER TABLE notebooks ADD COLUMN updated_at DATETIME DEFAULT CURRENT_TIMESTAMP`) +func (d *DB) addNotebookIdColumn() error { + for _, migration := range []struct { + table, name, statement string + }{ + {"notes", "notebook_id", `ALTER TABLE notes ADD COLUMN notebook_id TEXT REFERENCES notebooks(id) ON DELETE SET NULL`}, + {"notes", "sort_order", `ALTER TABLE notes ADD COLUMN sort_order INTEGER DEFAULT 0`}, + {"notebooks", "pinned", `ALTER TABLE notebooks ADD COLUMN pinned INTEGER DEFAULT 0`}, + {"notebooks", "created_at", `ALTER TABLE notebooks ADD COLUMN created_at DATETIME DEFAULT CURRENT_TIMESTAMP`}, + {"notebooks", "updated_at", `ALTER TABLE notebooks ADD COLUMN updated_at DATETIME DEFAULT CURRENT_TIMESTAMP`}, + {"notes", "encrypted_title", `ALTER TABLE notes ADD COLUMN encrypted_title BLOB`}, + {"notes", "encrypted_preview", `ALTER TABLE notes ADD COLUMN encrypted_preview BLOB`}, + } { + if err := d.ensureColumn(migration.table, migration.name, migration.statement); err != nil { + return err + } } - - // Add encrypted_title and encrypted_preview columns for list performance - err = d.db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('notes') WHERE name='encrypted_title'`).Scan(&count) - if err != nil || count == 0 { - d.db.Exec(`ALTER TABLE notes ADD COLUMN encrypted_title BLOB`) - d.db.Exec(`ALTER TABLE notes ADD COLUMN encrypted_preview BLOB`) + for _, statement := range []string{ + `CREATE INDEX IF NOT EXISTS idx_notes_notebook_id ON notes(notebook_id)`, + `CREATE INDEX IF NOT EXISTS idx_notes_sort_order ON notes(sort_order)`, + `CREATE INDEX IF NOT EXISTS idx_notebooks_pinned ON notebooks(pinned)`, + `CREATE INDEX IF NOT EXISTS idx_notes_list ON notes(deleted_at, pinned DESC, sort_order ASC, updated_at DESC)`, + } { + if _, err := d.db.Exec(statement); err != nil { + return err + } } - - // Add composite index for list query optimization - d.db.Exec(`CREATE INDEX IF NOT EXISTS idx_notes_list ON notes(deleted_at, pinned DESC, sort_order ASC, updated_at DESC)`) + return nil } func (d *DB) HasMasterPassword() (bool, error) { diff --git a/internal/database/database_test.go b/internal/database/database_test.go new file mode 100644 index 0000000..05b2104 --- /dev/null +++ b/internal/database/database_test.go @@ -0,0 +1,59 @@ +package database + +import ( + "path/filepath" + "testing" +) + +func TestMigrateIsIdempotentAndSetsSchemaVersion(t *testing.T) { + db, err := New(filepath.Join(t.TempDir(), "locknote.db")) + if err != nil { + t.Fatalf("open database: %v", err) + } + defer db.Close() + + if err := db.migrate(); err != nil { + t.Fatalf("first migration: %v", err) + } + if err := db.migrate(); err != nil { + t.Fatalf("second migration: %v", err) + } + var version int + if err := db.db.QueryRow(`PRAGMA user_version;`).Scan(&version); err != nil { + t.Fatalf("read user_version: %v", err) + } + if version != schemaVersion { + t.Fatalf("user_version = %d, want %d", version, schemaVersion) + } +} + +func TestMasterPasswordInsertUpdateAndClosedDBErrors(t *testing.T) { + db, err := New(filepath.Join(t.TempDir(), "locknote.db")) + if err != nil { + t.Fatalf("open database: %v", err) + } + if err := db.InsertMasterPassword([]byte("salt"), []byte("verifier"), "hint", []byte("key")); err != nil { + t.Fatalf("insert master password: %v", err) + } + if err := db.InsertMasterPassword([]byte("salt"), []byte("verifier"), "hint", []byte("key")); err == nil { + t.Fatal("expected duplicate master password insert to fail") + } + if err := db.UpdateMasterPassword([]byte("salt2"), []byte("verifier2"), "hint2", []byte("key2")); err != nil { + t.Fatalf("update master password: %v", err) + } + if err := db.Close(); err != nil { + t.Fatalf("close database: %v", err) + } + if _, err := db.HasMasterPassword(); err == nil { + t.Fatal("expected HasMasterPassword to fail on closed database") + } + + emptyDB, err := New(filepath.Join(t.TempDir(), "empty.db")) + if err != nil { + t.Fatalf("open empty database: %v", err) + } + defer emptyDB.Close() + if err := emptyDB.UpdateMasterPassword(nil, nil, "", nil); err == nil { + t.Fatal("expected update without an existing password record to fail") + } +} diff --git a/internal/fsutil/fsutil.go b/internal/fsutil/fsutil.go index fbb167d..5dad393 100644 --- a/internal/fsutil/fsutil.go +++ b/internal/fsutil/fsutil.go @@ -7,28 +7,48 @@ import ( ) func WriteFileAtomic(path string, data []byte, perm os.FileMode) error { + tempPath, err := WriteTemp(path, data, perm) + if err != nil { + return err + } + defer os.Remove(tempPath) + return Commit(tempPath, path) +} + +func WriteTemp(path string, data []byte, perm os.FileMode) (string, error) { dir := filepath.Dir(path) temp, err := os.CreateTemp(dir, filepath.Base(path)+".tmp-*") if err != nil { - return err + return "", err } tempPath := temp.Name() - defer os.Remove(tempPath) + failed := true + defer func() { + if failed { + _ = os.Remove(tempPath) + } + }() if _, err := temp.Write(data); err != nil { - temp.Close() - return err + _ = temp.Close() + return "", err } if err := temp.Sync(); err != nil { - temp.Close() - return err + _ = temp.Close() + return "", err } if err := temp.Close(); err != nil { - return err + return "", err } if err := os.Chmod(tempPath, perm); err != nil { - return err + return "", err } + failed = false + return tempPath, nil +} + +func Commit(tempPath, path string) error { + dir := filepath.Dir(path) if err := os.Rename(tempPath, path); err != nil { return err } diff --git a/internal/notes/notes.go b/internal/notes/notes.go index 44c94c3..b308a3c 100644 --- a/internal/notes/notes.go +++ b/internal/notes/notes.go @@ -23,11 +23,20 @@ import ( ) type Service struct { - db *database.DB - dataDir string - crypto *crypto.Service - masterKey []byte - mu sync.RWMutex + db *database.DB + dataDir string + crypto *crypto.Service + masterKey []byte + mu sync.RWMutex + cacheMu sync.RWMutex + contentCache map[string]cachedNoteContent +} + +type cachedNoteContent struct { + updatedAt time.Time + cipherPath string + title string + content string } var ( @@ -71,15 +80,76 @@ type NoteContent struct { Content string `json:"content"` } +func (s *Service) listTitlePreview(meta *database.NoteMeta, key []byte) (string, string, bool) { + title, preview := "", "" + fallback := meta.EncryptedTitle == nil + if meta.EncryptedTitle != nil { + decrypted, err := s.crypto.Decrypt(key, meta.EncryptedTitle) + if err != nil { + fallback = true + } else { + title = string(decrypted) + } + } + if meta.EncryptedPreview != nil { + if decrypted, err := s.crypto.Decrypt(key, meta.EncryptedPreview); err == nil { + preview = string(decrypted) + } + } + if !fallback { + return title, preview, true + } + ciphertext, err := os.ReadFile(filepath.Join(s.dataDir, meta.CipherPath)) + if err != nil { + log.Printf("failed to read note file %s: %v", meta.ID, err) + return "", "", false + } + plaintext, err := s.crypto.Decrypt(key, ciphertext) + if err != nil { + log.Printf("failed to decrypt note %s: %v", meta.ID, err) + return "", "", false + } + var noteContent NoteContent + if err := json.Unmarshal(plaintext, ¬eContent); err != nil { + log.Printf("failed to unmarshal note %s: %v", meta.ID, err) + return "", "", false + } + return noteContent.Title, s.extractPreview(noteContent.Content), true +} + +func (s *Service) noteFromMeta(meta *database.NoteMeta, key []byte, dbTags []*database.Tag) (*Note, bool) { + title, preview, ok := s.listTitlePreview(meta, key) + if !ok { + return nil, false + } + tags := make([]Tag, len(dbTags)) + for i, tag := range dbTags { + tags[i] = Tag{ID: tag.ID, Name: tag.Name, Color: tag.Color} + } + return &Note{ + ID: meta.ID, + Title: title, + Content: preview, + CreatedAt: formatTime(meta.CreatedAt), + UpdatedAt: formatTime(meta.UpdatedAt), + Pinned: meta.Pinned, + DeletedAt: formatTimePtr(meta.DeletedAt), + NotebookID: meta.NotebookID, + Tags: tags, + }, true +} + func NewService(db *database.DB, dataDir string) *Service { return &Service{ - db: db, - dataDir: dataDir, - crypto: crypto.NewService(), + db: db, + dataDir: dataDir, + crypto: crypto.NewService(), + contentCache: make(map[string]cachedNoteContent), } } func (s *Service) SetMasterKey(key []byte) { + s.ClearContentCache() s.mu.Lock() defer s.mu.Unlock() if s.masterKey != nil { @@ -90,6 +160,40 @@ func (s *Service) SetMasterKey(key []byte) { s.masterKey = key } +func (s *Service) ClearContentCache() { + s.cacheMu.Lock() + s.contentCache = make(map[string]cachedNoteContent) + s.cacheMu.Unlock() +} + +func (s *Service) cachedContent(meta *database.NoteMeta) (NoteContent, bool) { + s.cacheMu.RLock() + cached, ok := s.contentCache[meta.ID] + s.cacheMu.RUnlock() + if !ok || cached.cipherPath != meta.CipherPath || !cached.updatedAt.Equal(meta.UpdatedAt) { + return NoteContent{}, false + } + return NoteContent{Title: cached.title, Content: cached.content}, true +} + +func (s *Service) storeContent(meta *database.NoteMeta, content NoteContent) { + s.cacheMu.Lock() + if s.contentCache == nil { + s.contentCache = make(map[string]cachedNoteContent) + } + s.contentCache[meta.ID] = cachedNoteContent{ + updatedAt: meta.UpdatedAt, cipherPath: meta.CipherPath, + title: content.Title, content: content.Content, + } + s.cacheMu.Unlock() +} + +func (s *Service) removeCachedContent(id string) { + s.cacheMu.Lock() + delete(s.contentCache, id) + s.cacheMu.Unlock() +} + func (s *Service) getMasterKey() ([]byte, error) { s.mu.RLock() defer s.mu.RUnlock() @@ -147,9 +251,11 @@ func (s *Service) Create(title, content string) (*Note, error) { return nil, err } - if err := fsutil.WriteFileAtomic(fullPath, ciphertext, 0600); err != nil { + tempPath, err := fsutil.WriteTemp(fullPath, ciphertext, 0600) + if err != nil { return nil, err } + defer os.Remove(tempPath) meta := &database.NoteMeta{ ID: id, @@ -162,9 +268,13 @@ func (s *Service) Create(title, content string) (*Note, error) { } if err := s.db.CreateNote(meta); err != nil { - os.Remove(fullPath) return nil, err } + if err := fsutil.Commit(tempPath, fullPath); err != nil { + _ = s.db.DeleteNotePermanently(id) + return nil, err + } + s.storeContent(meta, noteContent) return &Note{ ID: id, @@ -194,20 +304,21 @@ func (s *Service) Get(id string) (*Note, error) { return nil, err } - fullPath := filepath.Join(s.dataDir, meta.CipherPath) - ciphertext, err := os.ReadFile(fullPath) - if err != nil { - return nil, err - } - - plaintext, err := s.crypto.Decrypt(key, ciphertext) - if err != nil { - return nil, err - } - - var noteContent NoteContent - if err := json.Unmarshal(plaintext, ¬eContent); err != nil { - return nil, err + noteContent, ok := s.cachedContent(meta) + if !ok { + fullPath := filepath.Join(s.dataDir, meta.CipherPath) + ciphertext, err := os.ReadFile(fullPath) + if err != nil { + return nil, err + } + plaintext, err := s.crypto.Decrypt(key, ciphertext) + if err != nil { + return nil, err + } + if err := json.Unmarshal(plaintext, ¬eContent); err != nil { + return nil, err + } + s.storeContent(meta, noteContent) } dbTags, err := s.db.GetNoteTags(id) @@ -296,8 +407,13 @@ func (s *Service) Update(id, title, content string) (*Note, error) { if len(existingHistory) >= historyMaxCount { for i := historyMaxCount - 1; i < len(existingHistory); i++ { - os.Remove(filepath.Join(s.dataDir, existingHistory[i].CipherPath)) - s.db.DeleteSingleHistory(existingHistory[i].ID) + if err := s.db.DeleteSingleHistory(existingHistory[i].ID); err != nil { + log.Printf("[Update] failed to prune history record %s: %v", existingHistory[i].ID, err) + continue + } + if err := os.Remove(filepath.Join(s.dataDir, existingHistory[i].CipherPath)); err != nil && !os.IsNotExist(err) { + log.Printf("[Update] failed to prune history file %s: %v", existingHistory[i].ID, err) + } } } } @@ -327,9 +443,11 @@ func (s *Service) Update(id, title, content string) (*Note, error) { } fullPath := filepath.Join(s.dataDir, meta.CipherPath) - if err := fsutil.WriteFileAtomic(fullPath, ciphertext, 0600); err != nil { + tempPath, err := fsutil.WriteTemp(fullPath, ciphertext, 0600) + if err != nil { return nil, err } + defer os.Remove(tempPath) if contentChanged { meta.UpdatedAt = time.Now() @@ -337,8 +455,15 @@ func (s *Service) Update(id, title, content string) (*Note, error) { meta.EncryptedTitle = encryptedTitle meta.EncryptedPreview = encryptedPreview if err := s.db.UpdateNoteAndCreateHistory(meta, historyRecord); err != nil { + if historyRecord != nil { + _ = os.Remove(filepath.Join(s.dataDir, historyRecord.CipherPath)) + } + return nil, err + } + if err := fsutil.Commit(tempPath, fullPath); err != nil { return nil, err } + s.storeContent(meta, noteContent) dbTags, _ := s.db.GetNoteTags(id) tags := make([]Tag, len(dbTags)) @@ -381,16 +506,26 @@ func (s *Service) Delete(id string) error { return err } - fullPath := filepath.Join(s.dataDir, meta.CipherPath) - os.Remove(fullPath) - - history, _ := s.db.GetNoteHistory(id) - for _, h := range history { - os.Remove(filepath.Join(s.dataDir, h.CipherPath)) + history, err := s.db.GetNoteHistory(id) + if err != nil { + return err } - s.db.DeleteNoteHistory(id) - - return s.db.DeleteNotePermanently(id) + if err := s.db.DeleteNoteHistory(id); err != nil { + return err + } + for _, item := range history { + if err := os.Remove(filepath.Join(s.dataDir, item.CipherPath)); err != nil && !os.IsNotExist(err) { + log.Printf("[Delete] failed to remove history file %s: %v", item.ID, err) + } + } + if err := s.db.DeleteNotePermanently(id); err != nil { + return err + } + s.removeCachedContent(id) + if err := os.Remove(filepath.Join(s.dataDir, meta.CipherPath)); err != nil && !os.IsNotExist(err) { + log.Printf("[Delete] failed to remove note file %s: %v", id, err) + } + return nil } func (s *Service) List() ([]*Note, error) { @@ -413,62 +548,9 @@ func (s *Service) List() ([]*Note, error) { notes := make([]*Note, 0, len(metas)) for _, meta := range metas { - var title, preview string - - // Try to use cached encrypted title/preview first (fast path) - if meta.EncryptedTitle != nil { - if decrypted, err := s.crypto.Decrypt(key, meta.EncryptedTitle); err == nil { - title = string(decrypted) - } - } - if meta.EncryptedPreview != nil { - if decrypted, err := s.crypto.Decrypt(key, meta.EncryptedPreview); err == nil { - preview = string(decrypted) - } - } - - // Fallback to reading file if cache is empty (for old notes) - if title == "" { - fullPath := filepath.Join(s.dataDir, meta.CipherPath) - ciphertext, err := os.ReadFile(fullPath) - if err != nil { - log.Printf("[ListNotes] failed to read note file %s: %v", meta.ID, err) - continue - } - - plaintext, err := s.crypto.Decrypt(key, ciphertext) - if err != nil { - log.Printf("[ListNotes] failed to decrypt note %s: %v", meta.ID, err) - continue - } - - var noteContent NoteContent - if err := json.Unmarshal(plaintext, ¬eContent); err != nil { - log.Printf("[ListNotes] failed to unmarshal note %s: %v", meta.ID, err) - continue - } - title = noteContent.Title - preview = s.extractPreview(noteContent.Content) + if note, ok := s.noteFromMeta(meta, key, tagsByNoteID[meta.ID]); ok { + notes = append(notes, note) } - - // Get tags from batch result - dbTags := tagsByNoteID[meta.ID] - tags := make([]Tag, len(dbTags)) - for i, t := range dbTags { - tags[i] = Tag{ID: t.ID, Name: t.Name, Color: t.Color} - } - - notes = append(notes, &Note{ - ID: meta.ID, - Title: title, - Content: preview, - CreatedAt: formatTime(meta.CreatedAt), - UpdatedAt: formatTime(meta.UpdatedAt), - Pinned: meta.Pinned, - DeletedAt: formatTimePtr(meta.DeletedAt), - NotebookID: meta.NotebookID, - Tags: tags, - }) } return notes, nil @@ -494,20 +576,21 @@ func (s *Service) Search(query string) ([]*Note, error) { var results []*Note for _, meta := range metas { - fullPath := filepath.Join(s.dataDir, meta.CipherPath) - ciphertext, err := os.ReadFile(fullPath) - if err != nil { - continue - } - - plaintext, err := s.crypto.Decrypt(key, ciphertext) - if err != nil { - continue - } - - var noteContent NoteContent - if err := json.Unmarshal(plaintext, ¬eContent); err != nil { - continue + noteContent, ok := s.cachedContent(meta) + if !ok { + fullPath := filepath.Join(s.dataDir, meta.CipherPath) + ciphertext, err := os.ReadFile(fullPath) + if err != nil { + continue + } + plaintext, err := s.crypto.Decrypt(key, ciphertext) + if err != nil { + continue + } + if err := json.Unmarshal(plaintext, ¬eContent); err != nil { + continue + } + s.storeContent(meta, noteContent) } titleMatch := strings.Contains(strings.ToLower(noteContent.Title), query) @@ -566,62 +649,9 @@ func (s *Service) ListPaginated(limit, offset int) (*ListResult, error) { notes := make([]*Note, 0, len(metas)) for _, meta := range metas { - var title, preview string - - // Try to use cached encrypted title/preview first (fast path) - if meta.EncryptedTitle != nil { - if decrypted, err := s.crypto.Decrypt(key, meta.EncryptedTitle); err == nil { - title = string(decrypted) - } - } - if meta.EncryptedPreview != nil { - if decrypted, err := s.crypto.Decrypt(key, meta.EncryptedPreview); err == nil { - preview = string(decrypted) - } - } - - // Fallback to reading file if cache is empty (for old notes) - if title == "" { - fullPath := filepath.Join(s.dataDir, meta.CipherPath) - ciphertext, err := os.ReadFile(fullPath) - if err != nil { - log.Printf("[ListNotesPaginated] failed to read note file %s: %v", meta.ID, err) - continue - } - - plaintext, err := s.crypto.Decrypt(key, ciphertext) - if err != nil { - log.Printf("[ListNotesPaginated] failed to decrypt note %s: %v", meta.ID, err) - continue - } - - var noteContent NoteContent - if err := json.Unmarshal(plaintext, ¬eContent); err != nil { - log.Printf("[ListNotesPaginated] failed to unmarshal note %s: %v", meta.ID, err) - continue - } - title = noteContent.Title - preview = s.extractPreview(noteContent.Content) - } - - // Get tags from batch result - dbTags := tagsByNoteID[meta.ID] - tags := make([]Tag, len(dbTags)) - for i, t := range dbTags { - tags[i] = Tag{ID: t.ID, Name: t.Name, Color: t.Color} + if note, ok := s.noteFromMeta(meta, key, tagsByNoteID[meta.ID]); ok { + notes = append(notes, note) } - - notes = append(notes, &Note{ - ID: meta.ID, - Title: title, - Content: preview, - CreatedAt: formatTime(meta.CreatedAt), - UpdatedAt: formatTime(meta.UpdatedAt), - Pinned: meta.Pinned, - DeletedAt: formatTimePtr(meta.DeletedAt), - NotebookID: meta.NotebookID, - Tags: tags, - }) } return &ListResult{Notes: notes, Total: total}, nil @@ -648,54 +678,9 @@ func (s *Service) ListDeleted() ([]*Note, error) { notes := make([]*Note, 0, len(metas)) for _, meta := range metas { - var title, preview string - - // Try to use cached encrypted title/preview first - if meta.EncryptedTitle != nil { - if decrypted, err := s.crypto.Decrypt(key, meta.EncryptedTitle); err == nil { - title = string(decrypted) - } - } - if meta.EncryptedPreview != nil { - if decrypted, err := s.crypto.Decrypt(key, meta.EncryptedPreview); err == nil { - preview = string(decrypted) - } + if note, ok := s.noteFromMeta(meta, key, nil); ok { + notes = append(notes, note) } - - // Fallback to reading file if cache is empty - if title == "" { - fullPath := filepath.Join(s.dataDir, meta.CipherPath) - ciphertext, err := os.ReadFile(fullPath) - if err != nil { - log.Printf("[ListDeleted] failed to read note file %s: %v", meta.ID, err) - continue - } - - plaintext, err := s.crypto.Decrypt(key, ciphertext) - if err != nil { - log.Printf("[ListDeleted] failed to decrypt note %s: %v", meta.ID, err) - continue - } - - var noteContent NoteContent - if err := json.Unmarshal(plaintext, ¬eContent); err != nil { - log.Printf("[ListDeleted] failed to unmarshal note %s: %v", meta.ID, err) - continue - } - title = noteContent.Title - preview = s.extractPreview(noteContent.Content) - } - - notes = append(notes, &Note{ - ID: meta.ID, - Title: title, - Content: preview, - CreatedAt: formatTime(meta.CreatedAt), - UpdatedAt: formatTime(meta.UpdatedAt), - Pinned: meta.Pinned, - DeletedAt: formatTimePtr(meta.DeletedAt), - Tags: []Tag{}, - }) } return notes, nil @@ -854,6 +839,7 @@ func (s *Service) ImportFromBackup(backupPath, displayKey string) (int, error) { return 0, errors.New("无法导入任何笔记,请检查密钥是否正确") } + s.ClearContentCache() return importedCount, nil } diff --git a/internal/notes/notes_test.go b/internal/notes/notes_test.go index 1ca8f2d..44f5843 100644 --- a/internal/notes/notes_test.go +++ b/internal/notes/notes_test.go @@ -2,6 +2,7 @@ package notes import ( "bytes" + "os" "path/filepath" "testing" "time" @@ -28,6 +29,55 @@ func newTestNotesService(t *testing.T) *Service { return service } +func TestListUsesEncryptedEmptyTitleWithoutReadingNoteFile(t *testing.T) { + service := newTestNotesService(t) + note, err := service.Create("", "body") + if err != nil { + t.Fatalf("create note: %v", err) + } + if err := os.Remove(filepath.Join(service.dataDir, service.buildCipherPath("notes", note.ID))); err != nil { + t.Fatalf("remove note file: %v", err) + } + listed, err := service.List() + if err != nil { + t.Fatalf("list notes: %v", err) + } + if len(listed) != 1 || listed[0].ID != note.ID || listed[0].Title != "" { + t.Fatalf("listed notes = %#v, want the empty-title note", listed) + } +} + +func TestSearchUsesAndClearsContentCache(t *testing.T) { + service := newTestNotesService(t) + note, err := service.Create("cached title", "initial content") + if err != nil { + t.Fatalf("create note: %v", err) + } + if _, err := service.Update(note.ID, "cached title", "updated searchable content"); err != nil { + t.Fatalf("update note: %v", err) + } + if err := os.Remove(filepath.Join(service.dataDir, service.buildCipherPath("notes", note.ID))); err != nil { + t.Fatalf("remove note file: %v", err) + } + results, err := service.Search("searchable") + if err != nil { + t.Fatalf("search cached content: %v", err) + } + if len(results) != 1 || results[0].ID != note.ID { + t.Fatalf("search results = %#v, want cached note", results) + } + service.SetMasterKey(nil) + service.cacheMu.RLock() + cacheSize := len(service.contentCache) + service.cacheMu.RUnlock() + if cacheSize != 0 { + t.Fatalf("cache size after clearing master key = %d, want 0", cacheSize) + } + if _, err := service.Search("searchable"); err == nil { + t.Fatal("expected search to fail after clearing the master key") + } +} + func TestUpdateSkipsHistoryForUneditedEmptyInitialNote(t *testing.T) { service := newTestNotesService(t) From b5941e8f524ee35ce6f9f2166c67993266a62af6 Mon Sep 17 00:00:00 2001 From: 235skw Date: Sat, 24 Oct 2026 08:53:00 +0000 Subject: [PATCH 3/6] =?UTF-8?q?docs:=20=E7=AC=AC3=E6=89=B9=20=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E6=A8=A1=E5=9E=8B=E8=AF=B4=E6=98=8E=E4=B8=8E=E7=95=8C?= =?UTF-8?q?=E9=9D=A2=E6=9C=AC=E5=9C=B0=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.en.md | 13 ++++++++----- README.md | 7 +++++-- frontend/src/components/BackupView.tsx | 1 + frontend/src/components/MainLayout.tsx | 4 +++- frontend/src/components/TagsView.tsx | 4 ++-- frontend/src/searchTagsMerge.test.ts | 2 +- 6 files changed, 20 insertions(+), 11 deletions(-) diff --git a/README.en.md b/README.en.md index 2b47928..e8c9191 100644 --- a/README.en.md +++ b/README.en.md @@ -190,13 +190,16 @@ locknote/ The Wails entry point, same-package APIs, and tests of unexported functions remain at the root. Source contract tests live in tests/source/: run go test ./tests/source, or go test ./... for all Go tests. -## Security Notes +## Security Model -- Master key only resides in memory after unlocking +LockNote encrypts note bodies, titles and previews, note history, attachments and thumbnails, and todo titles. Tag names, notebook names, original attachment filenames, smart-view filters, password hints, timestamps, and file counts and sizes are not encrypted. + +Backups contain only notes, history, and attachments; they do not contain tags, notebooks, todos, settings, or the database. **Restore Backup works only with a backup from the same vault.** To move data to another device or use a different key, use recovery-key import. If both the password and recovery key are lost, the data is unrecoverable by design. + +- The master key remains in memory only after unlocking - Each note uses an independent random nonce -- Ciphertext files use atomic write -- Password reset supported via recovery key -- If you lose both your login password and the recovery key, your data cannot be recovered +- Ciphertext files are written atomically +- Password reset is supported through the recovery key ## Version diff --git a/README.md b/README.md index 9daca1a..28332c4 100644 --- a/README.md +++ b/README.md @@ -190,13 +190,16 @@ locknote/ 根目录保留 Wails 入口及同包 API;依赖未导出函数的单元测试随实现保留在根目录。 源码契约测试统一位于 tests/source/,可运行 go test ./tests/source;完整 Go 测试运行 go test ./...。 -## 安全说明 +## 安全模型 + +LockNote 使用加密密钥保护笔记正文、标题和预览、历史版本、附件及缩略图,以及待办事项标题。标签名称、笔记本名称、附件原始文件名、智能视图筛选条件、密码提示、时间戳及文件数量和大小不加密。 + +备份仅包含笔记、历史版本和附件,不包含标签、笔记本、待办事项、设置或数据库。**“恢复备份”仅适用于同一密码库的备份**;要迁移到其他设备或使用不同密钥,请选择“用恢复密钥导入”。如果密码和恢复密钥都丢失,数据将按设计无法恢复。 - 主密钥仅在解锁后驻留内存 - 每篇笔记使用独立随机 nonce - 密文文件采用原子写入 - 支持恢复密钥重置密码 -- 如果你同时遗失登录密码和恢复密钥,数据将无法恢复 ## 版本 diff --git a/frontend/src/components/BackupView.tsx b/frontend/src/components/BackupView.tsx index b9fe7ad..a129c3e 100644 --- a/frontend/src/components/BackupView.tsx +++ b/frontend/src/components/BackupView.tsx @@ -118,6 +118,7 @@ export function BackupView({ embedded = false }: BackupViewProps) {

{t.backup.title}

{t.backup.subtitle}

+

{t.backup.securityHint}

)} diff --git a/frontend/src/components/MainLayout.tsx b/frontend/src/components/MainLayout.tsx index 2fc2843..61cd469 100644 --- a/frontend/src/components/MainLayout.tsx +++ b/frontend/src/components/MainLayout.tsx @@ -1,4 +1,5 @@ import { useEffect } from 'react'; +import { useI18n } from '../i18n'; import { useStore } from '../store'; import { Sidebar } from './Sidebar'; import { NoteList } from './NoteList'; @@ -12,6 +13,7 @@ import { CalendarView } from './CalendarView'; import * as App from '../../wailsjs/go/main/App'; export function MainLayout() { + const { t } = useI18n(); const { currentView, setNotes, @@ -92,7 +94,7 @@ export function MainLayout() {