mirror of
https://github.com/LHY0125/PathEditor.git
synced 2026-06-29 01:45:54 +08:00
v5.1: 全面代码审查修复 — 安全加固 + 功能修复 + 测试补全 + 工程化
安全修复 (CRITICAL): - 启用 CSP (default-src 'self') - read_text_file 限制文件扩展名白名单 (.json/.csv/.txt) - capabilities 显式声明窗口权限 - profile 名校验增强 (null 字节/控制字符/长度限制) 功能修复 (HIGH): - AnalyzeDialog 重新打开时正确刷新数据 - UndoRedoButtons 订阅路径长度变化确保响应性 - 禁用状态持久化错误处理 (.catch → console.warn) - 硬编码中文全部迁移到 i18n (6 处) - PATH 长度检查改用 UTF-16 字符计数 - PATH 写入前 null 字节校验 - CLI export 拒绝写入系统目录 - savePaths 职责分离: window.confirm → Tauri ask() 对话框 代码质量 (MEDIUM): - 导入路径统一过滤 (sanitize_paths: null 字节/分号/空白) - 原子写入 (atomic_write: disabled.json + profiles) - 验证缓存自动清理 (PathTable useEffect) - Scanner 线程错误处理改进 (.unwrap → .map_err) - Ctrl+F 去重 (移除 use-keyboard 重复处理) - Profile 路径列表 key 修复 (index → path) - 生产构建启用日志插件 (Warn 级别) - export_paths JSON 序列化改 expect 测试: - Rust: 35 → 48 测试 (+13) - Frontend: 80 → 85 测试 (+5) - Vitest 全局 jsdom + 覆盖率阈值 (80%) - 安装 @vitest/coverage-v8 + test:coverage 脚本 - 移除未使用的 @testing-library/jest-dom 工程化: - CI 添加 Cargo 缓存 (Swatinem/rust-cache@v2) - CI 添加 cargo fmt --check - tsconfig.test.json 覆盖测试文件类型检查 - cargo fmt 全量格式化 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -37,8 +37,9 @@ export function AnalyzeDialog({ open, onClose }: Props) {
|
||||
|
||||
const prevOpen = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!open || prevOpen.current) return;
|
||||
prevOpen.current = open;
|
||||
if (!open) { prevOpen.current = false; return; }
|
||||
if (prevOpen.current) return;
|
||||
prevOpen.current = true;
|
||||
setLoading(true);
|
||||
const paths = getEnabledPaths();
|
||||
Promise.all([
|
||||
@@ -184,7 +185,7 @@ function ToolsTab({
|
||||
opacity: g.exists ? 1 : 0.6,
|
||||
}}
|
||||
>
|
||||
{g.dir} {!g.exists && '(不存在)'}
|
||||
{g.dir} {!g.exists && t('analyze.notExists')}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1 mt-1 ml-2">
|
||||
{g.exes.map((exe) => (
|
||||
|
||||
@@ -16,9 +16,9 @@ export function ImportDialog({ open, systemCount, userCount, onSelect, onCancel
|
||||
<Modal open={open} onClose={onCancel}>
|
||||
<h2 className="text-lg font-semibold mb-4">{t('dialog.importTarget')}</h2>
|
||||
<p className="text-sm mb-4 opacity-70">
|
||||
{systemCount > 0 && `系统变量: ${systemCount} 条`}
|
||||
{systemCount > 0 && t('dialog.importSystemCount', { count: systemCount })}
|
||||
{systemCount > 0 && userCount > 0 && ' | '}
|
||||
{userCount > 0 && `用户变量: ${userCount} 条`}
|
||||
{userCount > 0 && t('dialog.importUserCount', { count: userCount })}
|
||||
</p>
|
||||
<div className="flex flex-col gap-2">
|
||||
{systemCount > 0 && <button className="px-4 py-2 text-sm rounded border text-left" style={{ borderColor: 'var(--app-border)' }} onClick={() => onSelect('system')}>{t('dialog.importSystem')}</button>}
|
||||
|
||||
@@ -151,7 +151,7 @@ export function ProfileDialog({ open, onClose }: Props) {
|
||||
<div className="flex-1 p-3 overflow-auto">
|
||||
{!selectedData ? (
|
||||
<div className="text-center py-10 text-sm" style={{ opacity: 0.4 }}>
|
||||
{profiles.length === 0 ? t('profile.noProfiles') : '选择一个配置文件'}
|
||||
{profiles.length === 0 ? t('profile.noProfiles') : t('profile.selectProfile')}
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
@@ -194,7 +194,7 @@ export function ProfileDialog({ open, onClose }: Props) {
|
||||
style={{ backgroundColor: 'var(--app-list-bg)', color: 'var(--app-fg)', borderColor: 'var(--app-border)' }}
|
||||
/>
|
||||
<button className="px-2 py-1 text-xs rounded text-white" style={{ backgroundColor: '#3b82f6' }} onClick={handleRename}>
|
||||
确认
|
||||
{t('button.save')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
@@ -211,16 +211,17 @@ export function ProfileDialog({ open, onClose }: Props) {
|
||||
}
|
||||
|
||||
function PathSection({ title, paths }: { title: string; paths: PathEntry[] }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="mb-2">
|
||||
<div className="text-xs font-medium mb-1" style={{ opacity: 0.7 }}>{title}</div>
|
||||
{paths.length === 0 ? (
|
||||
<div className="text-xs" style={{ opacity: 0.4 }}>(空)</div>
|
||||
<div className="text-xs" style={{ opacity: 0.4 }}>{t('profile.empty')}</div>
|
||||
) : (
|
||||
<div className="space-y-0.5 max-h-48 overflow-auto">
|
||||
{paths.map((e, i) => (
|
||||
{paths.map((e) => (
|
||||
<div
|
||||
key={i}
|
||||
key={e.path}
|
||||
className="text-xs font-mono px-2 py-0.5 rounded flex items-center gap-1.5"
|
||||
style={{
|
||||
backgroundColor: 'var(--app-list-bg)',
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useAppStore } from '@/store/app-store';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { TargetType } from '@/core/undo-redo';
|
||||
@@ -17,6 +18,7 @@ type ValidationState = 'valid' | 'invalid' | 'unknown';
|
||||
const DEFAULT_VALIDATION_STATE: ValidationState = 'valid';
|
||||
|
||||
export function PathTable({ tabId }: PathTableProps) {
|
||||
const { t } = useTranslation();
|
||||
const sysPaths = useAppStore((s) => s.sysPaths);
|
||||
const userPaths = useAppStore((s) => s.userPaths);
|
||||
const searchQuery = useAppStore((s) => s.searchQuery);
|
||||
@@ -35,6 +37,33 @@ export function PathTable({ tabId }: PathTableProps) {
|
||||
const validatedRef = useRef<Set<string>>(new Set());
|
||||
const expandedRef = useRef<Set<string>>(new Set());
|
||||
|
||||
// 清理不再存在的路径缓存
|
||||
useEffect(() => {
|
||||
const currentKeys = new Set(paths.map(p => p.path));
|
||||
setValidationCache(prev => {
|
||||
let changed = false;
|
||||
const next = new Map(prev);
|
||||
for (const key of next.keys()) {
|
||||
if (!currentKeys.has(key)) { next.delete(key); changed = true; }
|
||||
}
|
||||
return changed ? next : prev;
|
||||
});
|
||||
setExpandedCache(prev => {
|
||||
let changed = false;
|
||||
const next = new Map(prev);
|
||||
for (const key of next.keys()) {
|
||||
if (!currentKeys.has(key)) { next.delete(key); changed = true; }
|
||||
}
|
||||
return changed ? next : prev;
|
||||
});
|
||||
for (const key of [...validatedRef.current]) {
|
||||
if (!currentKeys.has(key)) validatedRef.current.delete(key);
|
||||
}
|
||||
for (const key of [...expandedRef.current]) {
|
||||
if (!currentKeys.has(key)) expandedRef.current.delete(key);
|
||||
}
|
||||
}, [paths]);
|
||||
|
||||
// 过滤搜索
|
||||
const filtered = useMemo<PathRow[]>(() => {
|
||||
if (!searchQuery) return paths.map((p, i) => ({ path: p.path, index: i, enabled: p.enabled }));
|
||||
@@ -160,7 +189,7 @@ export function PathTable({ tabId }: PathTableProps) {
|
||||
>
|
||||
<th className="w-8 px-2 py-1">#</th>
|
||||
<th className="w-6 px-1 py-1"></th>
|
||||
<th className="px-2 py-1">路径</th>
|
||||
<th className="px-2 py-1">{t('table.path')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
||||
@@ -6,6 +6,9 @@ export function UndoRedoButtons() {
|
||||
const { t } = useTranslation();
|
||||
const isAdmin = useAppStore((s) => s.isAdmin);
|
||||
const undoRedo = useAppStore((s) => s.undoRedo);
|
||||
// 订阅路径数组长度变化,确保 undoRedo 内部状态变化时触发重渲染
|
||||
useAppStore((s) => s.sysPaths.length);
|
||||
useAppStore((s) => s.userPaths.length);
|
||||
const undo = useAppStore((s) => s.undo);
|
||||
const redo = useAppStore((s) => s.redo);
|
||||
|
||||
|
||||
@@ -117,8 +117,16 @@ export function useAppActions(activeTab: TabId, dialogs: DialogState) {
|
||||
URL.revokeObjectURL(url);
|
||||
}, []);
|
||||
|
||||
const handleSave = useCallback(() => {
|
||||
useAppStore.getState().savePaths();
|
||||
const handleSave = useCallback(async () => {
|
||||
const saved = await useAppStore.getState().savePaths();
|
||||
if (!saved && !useAppStore.getState().isSaving) {
|
||||
// 长度超限,需要用户确认
|
||||
const { ask } = await import('@tauri-apps/plugin-dialog');
|
||||
const confirmed = await ask(i18n.t('status.saveWarningLongPaths'), { title: i18n.t('dialog.backupTitle'), kind: 'warning' });
|
||||
if (confirmed) {
|
||||
await useAppStore.getState().savePaths(true);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
// ── 键盘 ──
|
||||
|
||||
@@ -56,11 +56,6 @@ export function useKeyboard(actions: KeyboardActions) {
|
||||
if (!isAdmin) return;
|
||||
e.preventDefault();
|
||||
a.onDelete();
|
||||
} else if (ctrl && e.key === 'f') {
|
||||
e.preventDefault();
|
||||
const searchInput = document.querySelector<HTMLInputElement>('input[placeholder]');
|
||||
searchInput?.focus();
|
||||
searchInput?.select();
|
||||
} else if (e.key === 'F1') {
|
||||
e.preventDefault();
|
||||
a.onHelp();
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
"user": "User Variables",
|
||||
"merged": "Merge Preview"
|
||||
},
|
||||
"table": {
|
||||
"path": "Path"
|
||||
},
|
||||
"button": {
|
||||
"new": "New",
|
||||
"edit": "Edit",
|
||||
@@ -51,7 +54,8 @@
|
||||
"readonly_label": "Read-only",
|
||||
"light": "Light",
|
||||
"dark": "Dark",
|
||||
"adminWarning": "Running without administrator privileges, some features are disabled"
|
||||
"adminWarning": "Running without administrator privileges, some features are disabled",
|
||||
"saveWarningLongPaths": "PATH length exceeds recommended value. Continue saving?"
|
||||
},
|
||||
"dialog": {
|
||||
"newPath": "New Path",
|
||||
@@ -70,7 +74,9 @@
|
||||
"backupMessage": "Back up registry before saving?",
|
||||
"confirm": "Confirm",
|
||||
"cancel": "Cancel",
|
||||
"search": "Search paths..."
|
||||
"search": "Search paths...",
|
||||
"importSystemCount": "System: {{count}} entries",
|
||||
"importUserCount": "User: {{count}} entries"
|
||||
},
|
||||
"analyze": {
|
||||
"title": "PATH Analysis",
|
||||
@@ -82,7 +88,8 @@
|
||||
"priority": "Prioritized",
|
||||
"shadowed": "Shadowed",
|
||||
"searchPlaceholder": "Search executable name...",
|
||||
"conflictCount": "{{count}} file conflict(s) found"
|
||||
"conflictCount": "{{count}} file conflict(s) found",
|
||||
"notExists": "(not found)"
|
||||
},
|
||||
"profile": {
|
||||
"title": "PATH Profiles",
|
||||
@@ -95,7 +102,9 @@
|
||||
"rename": "Rename",
|
||||
"noProfiles": "No saved profiles",
|
||||
"applyConfirm": "This will overwrite current PATH with profile \"{{name}}\" and write to registry. Confirm?",
|
||||
"deleted": "Profile \"{{name}}\" deleted"
|
||||
"deleted": "Profile \"{{name}}\" deleted",
|
||||
"selectProfile": "Select a profile",
|
||||
"empty": "(empty)"
|
||||
},
|
||||
"help": {
|
||||
"content": "PathEditor v5.0 — Windows System Environment Variable (PATH) Editor\n\nFeatures:\n• Create/Edit/Delete path entries\n• Move Up/Down to adjust priority\n• One-click cleanup of invalid & duplicate paths\n• Import/Export JSON, CSV, TXT formats\n• Full Undo/Redo support\n\nShortcuts:\n• Ctrl+N New\n• Ctrl+S Save\n• Ctrl+Z Undo\n• Ctrl+Y Redo\n• Ctrl+F Search\n• Delete Delete selected\n• F1 Help\n\nAuthor: 刘航宇\nGitHub: https://github.com/LHY0125/PathEditor"
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
"user": "用户变量",
|
||||
"merged": "合并预览"
|
||||
},
|
||||
"table": {
|
||||
"path": "路径"
|
||||
},
|
||||
"button": {
|
||||
"new": "新建",
|
||||
"edit": "编辑",
|
||||
@@ -51,7 +54,8 @@
|
||||
"modified": "已修改",
|
||||
"readonly_label": "只读",
|
||||
"light": "浅色",
|
||||
"dark": "深色"
|
||||
"dark": "深色",
|
||||
"saveWarningLongPaths": "PATH 长度超过建议值,是否继续保存?"
|
||||
},
|
||||
"dialog": {
|
||||
"newPath": "新建路径",
|
||||
@@ -70,7 +74,9 @@
|
||||
"backupMessage": "保存前需要备份注册表吗?",
|
||||
"confirm": "确认",
|
||||
"cancel": "取消",
|
||||
"search": "搜索路径..."
|
||||
"search": "搜索路径...",
|
||||
"importSystemCount": "系统变量: {{count}} 条",
|
||||
"importUserCount": "用户变量: {{count}} 条"
|
||||
},
|
||||
"analyze": {
|
||||
"title": "PATH 分析",
|
||||
@@ -82,7 +88,8 @@
|
||||
"priority": "优先执行",
|
||||
"shadowed": "被遮蔽",
|
||||
"searchPlaceholder": "搜索可执行文件名...",
|
||||
"conflictCount": "发现 {{count}} 个文件冲突"
|
||||
"conflictCount": "发现 {{count}} 个文件冲突",
|
||||
"notExists": "(不存在)"
|
||||
},
|
||||
"profile": {
|
||||
"title": "PATH 配置文件",
|
||||
@@ -95,7 +102,9 @@
|
||||
"rename": "重命名",
|
||||
"noProfiles": "暂无配置文件",
|
||||
"applyConfirm": "将用配置 \"{{name}}\" 覆盖当前 PATH 并写入注册表,确定吗?",
|
||||
"deleted": "已删除配置 \"{{name}}\""
|
||||
"deleted": "已删除配置 \"{{name}}\"",
|
||||
"selectProfile": "选择一个配置文件",
|
||||
"empty": "(空)"
|
||||
},
|
||||
"help": {
|
||||
"content": "PathEditor v5.0 — Windows 系统环境变量 (PATH) 编辑器\n\n功能:\n• 新建/编辑/删除路径条目\n• 上移/下移调整优先级\n• 一键清理无效和重复路径\n• 导入/导出 JSON、CSV、TXT 格式\n• 完整撤销/重做支持\n\n快捷键:\n• Ctrl+N 新建\n• Ctrl+S 保存\n• Ctrl+Z 撤销\n• Ctrl+Y 重做\n• Ctrl+F 搜索\n• Delete 删除选中\n• F1 帮助\n\n作者: 刘航宇\nGitHub: https://github.com/LHY0125/PathEditor"
|
||||
|
||||
+12
-8
@@ -45,7 +45,7 @@ interface AppState {
|
||||
redo: () => void;
|
||||
|
||||
loadPaths: () => Promise<void>;
|
||||
savePaths: () => Promise<void>;
|
||||
savePaths: (force?: boolean) => Promise<boolean>;
|
||||
initialize: () => Promise<void>;
|
||||
|
||||
}
|
||||
@@ -248,7 +248,7 @@ export const useAppStore = create<AppState>((set, get) => {
|
||||
const sysDisabled = sys.filter(e => !e.enabled).map(e => e.path);
|
||||
const usrDisabled = usr.filter(e => !e.enabled).map(e => e.path);
|
||||
invoke('save_disabled_state', { system: sysDisabled, user: usrDisabled })
|
||||
.catch(() => {});
|
||||
.catch((e) => console.warn('保存禁用状态失败:', e));
|
||||
},
|
||||
|
||||
undo: () => {
|
||||
@@ -264,7 +264,7 @@ export const useAppStore = create<AppState>((set, get) => {
|
||||
invoke('save_disabled_state', {
|
||||
system: result[0].filter(e => !e.enabled).map(e => e.path),
|
||||
user: result[1].filter(e => !e.enabled).map(e => e.path),
|
||||
}).catch(() => {});
|
||||
}).catch((e) => console.warn('保存禁用状态失败:', e));
|
||||
}
|
||||
},
|
||||
|
||||
@@ -281,7 +281,7 @@ export const useAppStore = create<AppState>((set, get) => {
|
||||
invoke('save_disabled_state', {
|
||||
system: result[0].filter(e => !e.enabled).map(e => e.path),
|
||||
user: result[1].filter(e => !e.enabled).map(e => e.path),
|
||||
}).catch(() => {});
|
||||
}).catch((e) => console.warn('保存禁用状态失败:', e));
|
||||
}
|
||||
},
|
||||
|
||||
@@ -322,9 +322,9 @@ export const useAppStore = create<AppState>((set, get) => {
|
||||
}
|
||||
},
|
||||
|
||||
savePaths: async () => {
|
||||
savePaths: async (force?: boolean) => {
|
||||
const state = get();
|
||||
if (state.isSaving) return;
|
||||
if (state.isSaving) return false;
|
||||
set({ isSaving: true, statusMessage: i18n.t('status.saving') });
|
||||
|
||||
// 只保存 enabled 的路径到注册表
|
||||
@@ -333,9 +333,11 @@ export const useAppStore = create<AppState>((set, get) => {
|
||||
const sysJoined = sysPaths.join(';');
|
||||
const userJoined = userPaths.join(';');
|
||||
|
||||
// 长度检查:非强制模式下返回警告,由 UI 层确认
|
||||
const { maxSystemLength, maxUserLength, maxCombinedLength } = appConfig.path;
|
||||
if (sysJoined.length > maxSystemLength || userJoined.length > maxUserLength || (sysJoined + userJoined).length > maxCombinedLength) {
|
||||
if (!window.confirm('PATH 长度超过建议值,是否继续保存?')) { set({ isSaving: false }); return; }
|
||||
if (!force && (sysJoined.length > maxSystemLength || userJoined.length > maxUserLength || (sysJoined + userJoined).length > maxCombinedLength)) {
|
||||
set({ isSaving: false, statusMessage: i18n.t('status.saveWarningLongPaths') });
|
||||
return false;
|
||||
}
|
||||
|
||||
// 备份当前注册表(保存前备份旧值,失败仅警告不中断)
|
||||
@@ -357,12 +359,14 @@ export const useAppStore = create<AppState>((set, get) => {
|
||||
set({ isModified: false, isSaving: false,
|
||||
statusMessage: backupFailed ? i18n.t('status.saved_without_backup') : i18n.t('status.saved'),
|
||||
_savedSys: savedSys, _savedUser: savedUser });
|
||||
return true;
|
||||
} else {
|
||||
const sysErr = (!sysOk && sysResult.status === 'rejected') ? String(sysResult.reason) : '';
|
||||
const usrErr = (!userOk && userResult.status === 'rejected') ? String(userResult.reason) : '';
|
||||
const parts = [sysErr, usrErr].filter(Boolean);
|
||||
const msg = sysOk ? '用户 PATH 保存失败' : userOk ? '系统 PATH 保存失败' : `保存失败: ${parts.join('; ')}`;
|
||||
set({ isSaving: false, statusMessage: msg });
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
Reference in New Issue
Block a user