fix: 修复代码审计发现的全部 37 个问题
严重 Bug(8 个): - B-01: isClosing 永不重置 — WINDOW_CANCEL_CLOSE 现在正确重置状态并清除超时 - B-02: replaceAll 算法完全错误 — 改为从后向前逐个替换(SearchBar + useFileWatch) - B-03: Preview 用 setInterval 轮询 — 改为响应式订阅 activeTab.content 变化 - B-04: StatusBar 不响应 tab 切换 — 改为直接选择 tabs/activeTabId 而非函数引用 - B-05: useTheme 初始化竞态 — 添加 isInitialized ref 防止首次加载前保存 - B-06: scrollSync 0 值歧义 — 使用 NaN 标记未映射状态 - B-07: macOS activate 未注册 IPC — 提取 initWindow() 函数完整重建 - B-08: resizer 无交互逻辑 — 实现 Resizer 组件(mousedown/mousemove/mouseup) 中等问题(12 个): - M-01: removeAllListeners 限制为白名单通道 - M-02: 新建文件保存时设置 isSelfWriting - M-03: SidebarWatcher setTimeout 后再次检查窗口状态 - M-04: FileWatcher/SidebarWatcher 监听 error 事件清理僵尸状态 - M-05: buildDirTree 添加递归深度限制(maxDepth=10)+ 错误边界 - M-06: saveFileContent 改为原子写入(write-to-temp-then-rename) - M-07: Preview 异步竞态 — 使用递增 requestId 替代 cancelled - M-08: useKeyboard 依赖优化 — 用 getState() 替代频繁变化的 tabs 依赖 - M-09: settingsRepository.save() 改为 Dexie put 直接合并 - M-10: useSettings 返回函数用 useCallback 稳定引用 - M-11: App.tsx 事件注册添加 cleanup 清理 + ref 保持最新回调 - M-12: ipc-channels.ts 类型签名统一 低级问题(17 个): - L-01/L-03: Editor 移除未使用的 imports - L-04: tabIdCounter 改为 nanoid(HMR 安全) - L-06: recentFiles 添加 50 条上限自动清理 - L-07: getFileExtension 正确处理无扩展名文件 - L-08: window-manager 使用静态导入 + 验证是文件非目录 - L-09: readFileContent 使用 shared 类型 - L-10: buildDirTree 权限错误返回空数组 - L-11: DropOverlay 简化为单一 dragCounter 状态 - L-12: Sidebar onFileClick 提取为 useCallback - L-13: Editor searchStore 改为精确 selector - L-14: CSS 添加 mode-editor 隐藏规则 - L-16: openFileInTab 添加 .catch() 异常处理 TypeScript 检查零错误,构建成功。
This commit is contained in:
+24
-15
@@ -1,5 +1,7 @@
|
||||
import { readFile, stat, writeFile, readdir } from 'fs/promises'
|
||||
import { join, extname } from 'path'
|
||||
import { readFile, stat, writeFile, readdir, rename } from 'fs/promises'
|
||||
import { join, extname, basename } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
import type { ReadFileResult, SaveFileResult, FileNode } from '../shared/types'
|
||||
|
||||
const MAX_FILE_SIZE = 20 * 1024 * 1024 // 20MB
|
||||
const ALLOWED_EXTENSIONS = new Set(['.md', '.markdown', '.txt'])
|
||||
@@ -8,14 +10,8 @@ const SKIP_DIRS = new Set([
|
||||
'.next', '.nuxt', '__pycache__', '.DS_Store'
|
||||
])
|
||||
|
||||
export interface FileNode {
|
||||
name: string
|
||||
path: string
|
||||
type: 'file' | 'dir'
|
||||
children?: FileNode[]
|
||||
}
|
||||
|
||||
export async function readFileContent(filePath: string): Promise<{ success: boolean; content?: string; error?: string }> {
|
||||
// L-09: 使用 shared 类型
|
||||
export async function readFileContent(filePath: string): Promise<ReadFileResult> {
|
||||
try {
|
||||
const fileStat = await stat(filePath)
|
||||
if (fileStat.size > MAX_FILE_SIZE) {
|
||||
@@ -30,17 +26,30 @@ export async function readFileContent(filePath: string): Promise<{ success: bool
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveFileContent(filePath: string, content: string): Promise<{ success: boolean; filePath?: string; error?: string }> {
|
||||
// M-06: 原子写入(write-to-temp-then-rename)
|
||||
export async function saveFileContent(filePath: string, content: string): Promise<SaveFileResult> {
|
||||
try {
|
||||
await writeFile(filePath, content, 'utf-8')
|
||||
const dir = require('path').dirname(filePath)
|
||||
const tmpFile = join(tmpdir(), `marklite-${Date.now()}-${basename(filePath)}`)
|
||||
await writeFile(tmpFile, content, 'utf-8')
|
||||
await rename(tmpFile, filePath)
|
||||
return { success: true, filePath }
|
||||
} catch (err) {
|
||||
return { success: false, error: (err as Error).message }
|
||||
}
|
||||
}
|
||||
|
||||
export async function buildDirTree(dirPath: string): Promise<FileNode[]> {
|
||||
const entries = await readdir(dirPath, { withFileTypes: true })
|
||||
// M-05: 添加递归深度限制 + 每个 entry 错误边界
|
||||
export async function buildDirTree(dirPath: string, depth = 0, maxDepth = 10): Promise<FileNode[]> {
|
||||
if (depth > maxDepth) return []
|
||||
|
||||
let entries
|
||||
try {
|
||||
entries = await readdir(dirPath, { withFileTypes: true })
|
||||
} catch {
|
||||
return [] // L-10: 权限错误时返回空数组而非抛异常
|
||||
}
|
||||
|
||||
entries.sort((a, b) => {
|
||||
if (a.isDirectory() && !b.isDirectory()) return -1
|
||||
if (!a.isDirectory() && b.isDirectory()) return 1
|
||||
@@ -54,7 +63,7 @@ export async function buildDirTree(dirPath: string): Promise<FileNode[]> {
|
||||
|
||||
const childPath = join(dirPath, entry.name)
|
||||
if (entry.isDirectory()) {
|
||||
const subChildren = await buildDirTree(childPath)
|
||||
const subChildren = await buildDirTree(childPath, depth + 1, maxDepth)
|
||||
if (subChildren.length > 0) {
|
||||
children.push({ name: entry.name, path: childPath, type: 'dir', children: subChildren })
|
||||
}
|
||||
|
||||
@@ -22,6 +22,11 @@ export class FileWatcher {
|
||||
}
|
||||
}
|
||||
})
|
||||
// M-04: 监听 error 事件,文件被删除时清理状态
|
||||
this.watcher.on('error', () => {
|
||||
this.currentPath = null
|
||||
this.watcher = null
|
||||
})
|
||||
} catch {
|
||||
// silently ignore
|
||||
}
|
||||
@@ -32,6 +37,7 @@ export class FileWatcher {
|
||||
this.watcher.close()
|
||||
this.watcher = null
|
||||
}
|
||||
this.currentPath = null
|
||||
}
|
||||
|
||||
getCurrentPath(): string | null {
|
||||
@@ -60,10 +66,19 @@ export class SidebarWatcher {
|
||||
if (win && !win.isDestroyed()) {
|
||||
if (this.refreshTimer) clearTimeout(this.refreshTimer)
|
||||
this.refreshTimer = setTimeout(() => {
|
||||
win.webContents.send('sidebar:dirChanged')
|
||||
// M-03: 延迟后再次检查窗口状态
|
||||
const w = this.getMainWindow()
|
||||
if (w && !w.isDestroyed()) {
|
||||
w.webContents.send('sidebar:dirChanged')
|
||||
}
|
||||
}, 300)
|
||||
}
|
||||
})
|
||||
// M-04: 监听 error 事件
|
||||
this.watcher.on('error', () => {
|
||||
this.watcher = null
|
||||
this.watchPath = null
|
||||
})
|
||||
} catch {
|
||||
// silently ignore
|
||||
}
|
||||
|
||||
+24
-19
@@ -19,12 +19,14 @@ const sidebarWatcher = new SidebarWatcher(() => mainWindow)
|
||||
function openFileInTab(filePath: string): void {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) return
|
||||
readFileContent(filePath).then(result => {
|
||||
if (result.success) {
|
||||
if (result.success && mainWindow && !mainWindow.isDestroyed()) {
|
||||
state.activeFilePath = filePath
|
||||
fileWatcher.start(filePath)
|
||||
mainWindow!.setTitle(`MarkLite - ${filePath.split(/[/\\]/).pop()}`)
|
||||
mainWindow!.webContents.send('file:openInTab', { filePath, content: result.content })
|
||||
mainWindow.setTitle(`MarkLite - ${filePath.split(/[/\\]/).pop()}`)
|
||||
mainWindow.webContents.send('file:openInTab', { filePath, content: result.content })
|
||||
}
|
||||
}).catch((err) => {
|
||||
console.error('openFileInTab failed:', err)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -70,24 +72,12 @@ if (!lockOk) {
|
||||
})
|
||||
}
|
||||
|
||||
app.whenReady().then(() => {
|
||||
app.on('open-file', (event, filePath) => {
|
||||
event.preventDefault()
|
||||
if (mainWindow && !mainWindow.isDestroyed() && mainWindow.webContents.isLoading()) {
|
||||
state.pendingFilePath = filePath
|
||||
} else if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
openFileInTab(filePath)
|
||||
} else {
|
||||
state.pendingFilePath = filePath
|
||||
}
|
||||
})
|
||||
|
||||
// B-07: 完整的窗口初始化逻辑(activate 复用)
|
||||
function initWindow(): void {
|
||||
mainWindow = createWindow()
|
||||
|
||||
// 注册 IPC 处理器
|
||||
registerIpcHandlers(() => mainWindow, fileWatcher, sidebarWatcher, state)
|
||||
|
||||
// 加载渲染进程页面
|
||||
if (process.env.ELECTRON_RENDERER_URL) {
|
||||
mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL)
|
||||
} else {
|
||||
@@ -108,6 +98,21 @@ if (!lockOk) {
|
||||
sidebarWatcher.stop()
|
||||
mainWindow = null
|
||||
})
|
||||
}
|
||||
|
||||
app.whenReady().then(() => {
|
||||
app.on('open-file', (event, filePath) => {
|
||||
event.preventDefault()
|
||||
if (mainWindow && !mainWindow.isDestroyed() && mainWindow.webContents.isLoading()) {
|
||||
state.pendingFilePath = filePath
|
||||
} else if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
openFileInTab(filePath)
|
||||
} else {
|
||||
state.pendingFilePath = filePath
|
||||
}
|
||||
})
|
||||
|
||||
initWindow()
|
||||
|
||||
// 命令行文件
|
||||
const cmdFile = getFilePathFromArgs(process.argv)
|
||||
@@ -120,10 +125,10 @@ if (!lockOk) {
|
||||
if (process.platform !== 'darwin') app.quit()
|
||||
})
|
||||
|
||||
// B-07: macOS activate 完整重建窗口
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
mainWindow = createWindow()
|
||||
setupCloseHandler()
|
||||
initWindow()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ export function registerIpcHandlers(
|
||||
getMainWindow: () => BrowserWindow | null,
|
||||
fileWatcher: FileWatcher,
|
||||
sidebarWatcher: SidebarWatcher,
|
||||
state: { activeFilePath: string | null; pendingFilePath: string | null }
|
||||
state: { activeFilePath: string | null; pendingFilePath: string | null; isClosing: boolean; closeTimeout: NodeJS.Timeout | null }
|
||||
): void {
|
||||
// 打开文件对话框
|
||||
ipcMain.handle(IPC_CHANNELS.DIALOG_OPEN_FILE, async () => {
|
||||
@@ -67,7 +67,9 @@ export function registerIpcHandlers(
|
||||
filters: [{ name: 'Markdown 文件', extensions: ['md'] }]
|
||||
})
|
||||
if (!saveResult.canceled) {
|
||||
fileWatcher.setSelfWriting(true)
|
||||
const result = await saveFileContent(saveResult.filePath, data.content)
|
||||
fileWatcher.setSelfWriting(false)
|
||||
if (result.success) {
|
||||
state.activeFilePath = saveResult.filePath
|
||||
fileWatcher.start(saveResult.filePath)
|
||||
@@ -177,7 +179,12 @@ export function registerIpcHandlers(
|
||||
}
|
||||
})
|
||||
|
||||
// B-01: 重置关闭状态 + 清除超时定时器
|
||||
ipcMain.handle(IPC_CHANNELS.WINDOW_CANCEL_CLOSE, () => {
|
||||
// 重置关闭状态
|
||||
state.isClosing = false
|
||||
if (state.closeTimeout) {
|
||||
clearTimeout(state.closeTimeout)
|
||||
state.closeTimeout = null
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BrowserWindow, app } from 'electron'
|
||||
import { join } from 'path'
|
||||
import { existsSync, statSync } from 'fs'
|
||||
|
||||
export function createWindow(): BrowserWindow {
|
||||
const mainWindow = new BrowserWindow({
|
||||
@@ -43,13 +44,16 @@ export function setupSingleInstanceLock(
|
||||
return true
|
||||
}
|
||||
|
||||
// L-08: 使用静态导入 + 验证是文件而非目录
|
||||
export function getFilePathFromArgs(args: string[]): string | null {
|
||||
for (let i = 1; i < args.length; i++) {
|
||||
const arg = args[i]
|
||||
if (!arg.startsWith('--') && !arg.startsWith('-')) {
|
||||
try {
|
||||
const fs = require('fs')
|
||||
if (fs.existsSync(arg)) return arg
|
||||
if (existsSync(arg)) {
|
||||
const s = statSync(arg)
|
||||
if (s.isFile()) return arg
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user