fix(settings): harden persisted settings and update checks

This commit is contained in:
NimBold
2026-07-15 02:25:53 +03:30
parent e35b1af731
commit 45bbca0515
7 changed files with 388 additions and 54 deletions
+7 -6
View File
@@ -6,7 +6,7 @@ import { usePlatformInfo } from '../utils/platform';
export const KeychainPermissionModal: React.FC = () => {
const showKeychainModal = useSettingsStore(state => state.showKeychainModal);
const setShowKeychainModal = useSettingsStore(state => state.setShowKeychainModal);
const dismissKeychainPrompt = useSettingsStore(state => state.dismissKeychainPrompt);
const platform = usePlatformInfo();
const [isGranting, setIsGranting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -14,11 +14,11 @@ export const KeychainPermissionModal: React.FC = () => {
useEffect(() => {
if (!showKeychainModal || isGranting) return;
const handleEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape') setShowKeychainModal(false);
if (event.key === 'Escape') dismissKeychainPrompt();
};
window.addEventListener('keydown', handleEscape);
return () => window.removeEventListener('keydown', handleEscape);
}, [isGranting, setShowKeychainModal, showKeychainModal]);
}, [dismissKeychainPrompt, isGranting, showKeychainModal]);
if (!showKeychainModal) {
return null;
@@ -53,9 +53,10 @@ export const KeychainPermissionModal: React.FC = () => {
useSettingsStore.setState({
keychainAccessGranted: true,
extensionPairingToken: result.token,
isPairingTokenPersistent: true
isPairingTokenPersistent: true,
keychainPromptDismissed: false,
showKeychainModal: false
});
setShowKeychainModal(false);
} else {
setError(result.error || `${storeName} is unavailable.`);
}
@@ -67,7 +68,7 @@ export const KeychainPermissionModal: React.FC = () => {
};
const handleLater = () => {
setShowKeychainModal(false);
dismissKeychainPrompt();
};
return (
+46 -8
View File
@@ -28,6 +28,7 @@ import {
subfolderFromDerivedCategoryPath
} from '../utils/downloadLocations';
import { usePlatformInfo } from '../utils/platform';
import { isTrustedFirelinkReleaseUrl } from '../utils/releaseUrls';
const settingsTabs: { type: SettingsTab; label: string; icon: typeof Download }[] = [
{ type: 'downloads', label: 'Downloads', icon: Download },
@@ -275,7 +276,7 @@ const [engineStatus, setEngineStatus] = useState<EngineStatusItem[] | null>(null
const [expandedEngine, setExpandedEngine] = useState<string | null>(null);
const [isRecheckingEngines, setIsRecheckingEngines] = useState(false);
const engineRunId = useRef(0);
const [appVersion, setAppVersion] = useState('1.0.1');
const [appVersion, setAppVersion] = useState('Unknown');
const [extensionServerPort, setExtensionServerPort] = useState<number | null>(null);
// Local state for adding site login
@@ -283,6 +284,11 @@ const [extensionServerPort, setExtensionServerPort] = useState<number | null>(nu
const [loginUser, setLoginUser] = useState('');
const [loginPass, setLoginPass] = useState('');
const [loginError, setLoginError] = useState('');
const [loginFieldErrors, setLoginFieldErrors] = useState<{
pattern?: string;
username?: string;
password?: string;
}>({});
// Toast notifications
const { addToast } = useToast();
@@ -431,6 +437,9 @@ runEngineChecks(false);
localVersion: result.local_version
});
} else if (result.type === 'UpdateAvailable') {
if (!isTrustedFirelinkReleaseUrl(result.update.release_url)) {
throw new Error('The update check returned an untrusted release URL.');
}
setManualUpdateStatus({
type: 'update-available',
version: result.update.version,
@@ -512,10 +521,24 @@ runEngineChecks(false);
};
const handleAddLogin = async () => {
if (!loginPattern.trim() || !loginUser.trim()) {
setLoginError("Please enter a URL pattern and a username.");
const fieldErrors: typeof loginFieldErrors = {};
if (!loginPattern.trim()) {
fieldErrors.pattern = 'URL pattern is required.';
} else if (/\s/.test(loginPattern.trim())) {
fieldErrors.pattern = 'URL pattern cannot contain whitespace.';
}
if (!loginUser.trim()) {
fieldErrors.username = 'Username is required.';
}
if (!loginPass) {
fieldErrors.password = 'Password is required.';
}
if (Object.keys(fieldErrors).length > 0) {
setLoginFieldErrors(fieldErrors);
setLoginError('');
return;
}
setLoginFieldErrors({});
const id = crypto.randomUUID();
if (loginPass) {
@@ -1057,10 +1080,15 @@ runEngineChecks(false);
<input
type="text"
value={loginPattern}
onChange={(e) => setLoginPattern(e.target.value)}
onChange={(e) => {
setLoginPattern(e.target.value);
setLoginFieldErrors(current => ({ ...current, pattern: undefined }));
}}
placeholder="e.g. *.example.com or example.com/downloads"
aria-invalid={Boolean(loginFieldErrors.pattern)}
className="bg-bg-input border border-border-modal rounded-md px-3 py-1.5 w-full text-text-primary focus:outline-none"
/>
{loginFieldErrors.pattern && <p className="text-red-500 text-xs mt-1">{loginFieldErrors.pattern}</p>}
</div>
<div className="grid grid-cols-[150px_1fr] items-center gap-4 text-[13px]">
@@ -1068,10 +1096,15 @@ runEngineChecks(false);
<input
type="text"
value={loginUser}
onChange={(e) => setLoginUser(e.target.value)}
onChange={(e) => {
setLoginUser(e.target.value);
setLoginFieldErrors(current => ({ ...current, username: undefined }));
}}
placeholder="Username"
aria-invalid={Boolean(loginFieldErrors.username)}
className="bg-bg-input border border-border-modal rounded-md px-3 py-1.5 w-full text-text-primary focus:outline-none"
/>
{loginFieldErrors.username && <p className="text-red-500 text-xs mt-1">{loginFieldErrors.username}</p>}
</div>
<div className="grid grid-cols-[150px_1fr] items-center gap-4 text-[13px]">
@@ -1079,10 +1112,15 @@ runEngineChecks(false);
<input
type="password"
value={loginPass}
onChange={(e) => setLoginPass(e.target.value)}
onChange={(e) => {
setLoginPass(e.target.value);
setLoginFieldErrors(current => ({ ...current, password: undefined }));
}}
placeholder="Password"
aria-invalid={Boolean(loginFieldErrors.password)}
className="bg-bg-input border border-border-modal rounded-md px-3 py-1.5 w-full text-text-primary focus:outline-none"
/>
{loginFieldErrors.password && <p className="text-red-500 text-xs mt-1">{loginFieldErrors.password}</p>}
</div>
<div className="flex justify-end pt-2">
@@ -1215,12 +1253,12 @@ className="app-button px-3 py-1.5 text-[12px] flex items-center gap-1.5 disabled
</div>
<div className="flex-1">
<h4 className="text-sm font-semibold text-green-500 m-0">
{platform.portable ? 'Portable Pairing Enabled' : 'Credential Storage Available'}
{platform.portable ? 'Portable Pairing Enabled' : 'Pairing Token Persisted'}
</h4>
<p className="text-xs text-text-secondary m-0 mt-0.5">
{platform.portable
? 'Your pairing token is stored with this portable Firelink folder and will persist when the folder is moved. Treat the folder as sensitive.'
: "Your pairing token is securely saved in this system's credential store and will persist across restarts."}
: 'Your pairing token is persisted in Firelink settings and will persist across restarts.'}
</p>
</div>
</div>
+127 -13
View File
@@ -22,6 +22,50 @@ let settingsSave = Promise.resolve();
const DEFAULT_SCHEDULER_QUEUE_ID = '00000000-0000-0000-0000-000000000001';
export const DEFAULT_SPEED_LIMIT_PRESET_VALUES = [1, 5, 10];
const THEME_VALUES = ['system', 'light', 'dark', 'dracula', 'nord'] as const;
const APP_FONT_SIZE_VALUES = ['small', 'standard', 'large'] as const;
const LIST_ROW_DENSITY_VALUES = ['compact', 'standard', 'relaxed'] as const;
const PROXY_MODE_VALUES = ['none', 'system', 'custom'] as const;
const MEDIA_COOKIE_SOURCE_VALUES = [
'none', 'safari', 'chrome', 'chromium', 'firefox', 'edge', 'brave', 'opera', 'vivaldi', 'whale'
] as const;
const SETTINGS_TAB_VALUES = [
'downloads', 'lookandfeel', 'network', 'locations', 'sitelogins', 'power', 'engine', 'integrations', 'about'
] as const;
type PersistedSettingsSnapshot = PersistedSettings & {
keychainPromptDismissed: boolean;
};
const clampSettingInteger = (
value: unknown,
minimum: number,
maximum: number,
fallback: number
) => {
const numeric = typeof value === 'number' ? value : Number(value);
if (!Number.isFinite(numeric)) return fallback;
return Math.min(maximum, Math.max(minimum, Math.trunc(numeric)));
};
const isAllowedSetting = <T extends string>(values: readonly T[], value: unknown): value is T =>
typeof value === 'string' && values.includes(value as T);
const isRecord = (value: unknown): value is Record<string, unknown> =>
value !== null && typeof value === 'object' && !Array.isArray(value);
const sanitizeSiteLogins = (value: unknown): SiteLogin[] => {
if (!Array.isArray(value)) return [];
return value.filter(isRecord).filter((login): login is SiteLogin =>
typeof login.id === 'string'
&& typeof login.urlPattern === 'string'
&& typeof login.username === 'string'
);
};
const persistedBoolean = (value: unknown, fallback: boolean) =>
typeof value === 'boolean' ? value : fallback;
const tauriStorage: StateStorage = {
getItem: async (name: string): Promise<string | null> => {
if (name === 'firelink-settings') {
@@ -113,6 +157,7 @@ export interface SettingsState {
extensionPairingToken: string;
isPairingTokenPersistent: boolean;
keychainAccessGranted: boolean;
keychainPromptDismissed: boolean;
autoCheckUpdates: boolean;
showKeychainModal: boolean;
@@ -158,6 +203,7 @@ export interface SettingsState {
setAutoCheckUpdates: (autoCheckUpdates: boolean) => void;
hydratePairingToken: () => Promise<boolean>;
setShowKeychainModal: (show: boolean) => void;
dismissKeychainPrompt: () => void;
}
const generateSecureToken = () => {
@@ -188,7 +234,7 @@ const generateSecureToken = () => {
export const useSettingsStore = create<SettingsState>()(
persist(
(set, _get) => ({
(set, get) => ({
theme: 'system',
baseDownloadFolder: '~/Downloads',
categorySubfoldersEnabled: true,
@@ -236,8 +282,9 @@ export const useSettingsStore = create<SettingsState>()(
mediaCookieSource: 'none',
siteLogins: [],
extensionPairingToken: '',
isPairingTokenPersistent: true,
isPairingTokenPersistent: false,
keychainAccessGranted: false,
keychainPromptDismissed: false,
autoCheckUpdates: true,
showKeychainModal: false,
@@ -257,7 +304,9 @@ export const useSettingsStore = create<SettingsState>()(
},
setMaxConcurrentDownloads: (max) => {
info('Settings updated: maxConcurrentDownloads');
set({ maxConcurrentDownloads: max });
set({
maxConcurrentDownloads: clampSettingInteger(max, 1, 12, 3)
});
},
setGlobalSpeedLimit: (limit) => {
info('Settings updated: globalSpeedLimit');
@@ -275,8 +324,12 @@ export const useSettingsStore = create<SettingsState>()(
setLastCustomSpeedLimitKiB: (lastCustomSpeedLimitKiB) => set({ lastCustomSpeedLimitKiB }),
toggleSidebar: () => set((state) => ({ isSidebarVisible: !state.isSidebarVisible })),
setPerServerConnections: (perServerConnections) => set({ perServerConnections }),
setMaxAutomaticRetries: (maxAutomaticRetries) => set({ maxAutomaticRetries }),
setPerServerConnections: (perServerConnections) => set({
perServerConnections: clampSettingInteger(perServerConnections, 1, 16, 16)
}),
setMaxAutomaticRetries: (maxAutomaticRetries) => set({
maxAutomaticRetries: clampSettingInteger(maxAutomaticRetries, 0, 10, 3)
}),
setShowNotifications: (showNotifications) => set({ showNotifications }),
setPlayCompletionSound: (playCompletionSound) => set({ playCompletionSound }),
setAppFontSize: (appFontSize) => set({ appFontSize }),
@@ -344,15 +397,17 @@ export const useSettingsStore = create<SettingsState>()(
const result = await invoke('hydrate_extension_pairing_token');
set({
extensionPairingToken: result.token,
isPairingTokenPersistent: result.persistent
isPairingTokenPersistent: result.persistent,
showKeychainModal: !result.persistent && !get().keychainPromptDismissed
});
if (!result.persistent) {
set({ showKeychainModal: true });
}
return result.tokenChanged;
},
setAutoCheckUpdates: (autoCheckUpdates: boolean) => set({ autoCheckUpdates }),
setShowKeychainModal: (show: boolean) => set({ showKeychainModal: show }),
dismissKeychainPrompt: () => set({
keychainPromptDismissed: true,
showKeychainModal: false
}),
}),
{
name: 'firelink-settings',
@@ -391,7 +446,7 @@ export const useSettingsStore = create<SettingsState>()(
logsEnabled: persisted.logsEnabled === true
} as SettingsState;
},
partialize: (state): PersistedSettings => ({
partialize: (state): PersistedSettingsSnapshot => ({
theme: state.theme,
baseDownloadFolder: state.baseDownloadFolder,
categorySubfoldersEnabled: state.categorySubfoldersEnabled,
@@ -429,6 +484,7 @@ export const useSettingsStore = create<SettingsState>()(
siteLogins: state.siteLogins,
extensionPairingToken: state.extensionPairingToken,
keychainAccessGranted: state.keychainAccessGranted,
keychainPromptDismissed: state.keychainPromptDismissed,
autoCheckUpdates: state.autoCheckUpdates
}),
merge: (persistedState: unknown, currentState) => {
@@ -440,6 +496,66 @@ export const useSettingsStore = create<SettingsState>()(
...currentState,
...persisted,
...locations,
theme: isAllowedSetting(THEME_VALUES, persisted.theme)
? persisted.theme
: currentState.theme,
appFontSize: isAllowedSetting(APP_FONT_SIZE_VALUES, persisted.appFontSize)
? persisted.appFontSize
: currentState.appFontSize,
listRowDensity: isAllowedSetting(LIST_ROW_DENSITY_VALUES, persisted.listRowDensity)
? persisted.listRowDensity
: currentState.listRowDensity,
proxyMode: isAllowedSetting(PROXY_MODE_VALUES, persisted.proxyMode)
? persisted.proxyMode
: currentState.proxyMode,
mediaCookieSource: isAllowedSetting(MEDIA_COOKIE_SOURCE_VALUES, persisted.mediaCookieSource)
? persisted.mediaCookieSource
: 'none',
activeSettingsTab: isAllowedSetting(SETTINGS_TAB_VALUES, persisted.activeSettingsTab)
? persisted.activeSettingsTab
: currentState.activeSettingsTab,
extensionPairingToken: typeof persisted.extensionPairingToken === 'string'
? persisted.extensionPairingToken
: currentState.extensionPairingToken,
showNotifications: persistedBoolean(persisted.showNotifications, currentState.showNotifications),
playCompletionSound: persistedBoolean(persisted.playCompletionSound, currentState.playCompletionSound),
showDockBadge: persistedBoolean(persisted.showDockBadge, currentState.showDockBadge),
showMenuBarIcon: persistedBoolean(persisted.showMenuBarIcon, currentState.showMenuBarIcon),
askWhereToSaveEachFile: persistedBoolean(
persisted.askWhereToSaveEachFile,
currentState.askWhereToSaveEachFile
),
preventsSleepWhileDownloading: persistedBoolean(
persisted.preventsSleepWhileDownloading,
currentState.preventsSleepWhileDownloading
),
keychainAccessGranted: persistedBoolean(
persisted.keychainAccessGranted,
currentState.keychainAccessGranted
),
keychainPromptDismissed: persistedBoolean(
persisted.keychainPromptDismissed,
currentState.keychainPromptDismissed
),
autoCheckUpdates: persistedBoolean(persisted.autoCheckUpdates, currentState.autoCheckUpdates),
maxConcurrentDownloads: clampSettingInteger(
persisted.maxConcurrentDownloads,
1,
12,
currentState.maxConcurrentDownloads
),
perServerConnections: clampSettingInteger(
persisted.perServerConnections,
1,
16,
currentState.perServerConnections
),
maxAutomaticRetries: clampSettingInteger(
persisted.maxAutomaticRetries,
0,
10,
currentState.maxAutomaticRetries
),
speedLimitPresetValues: Array.isArray(persisted.speedLimitPresetValues)
? persisted.speedLimitPresetValues
: currentState.speedLimitPresetValues,
@@ -455,10 +571,8 @@ export const useSettingsStore = create<SettingsState>()(
? persisted.scheduler.selectedQueueIds
: currentState.scheduler.selectedQueueIds
},
appFontSize: persisted.appFontSize || currentState.appFontSize,
listRowDensity: persisted.listRowDensity || currentState.listRowDensity,
siteLogins: Array.isArray(persisted.siteLogins)
? persisted.siteLogins
? sanitizeSiteLogins(persisted.siteLogins)
: currentState.siteLogins
});
}
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, it } from 'vitest';
import { isTrustedFirelinkReleaseUrl } from './releaseUrls';
describe('Firelink release URLs', () => {
it('accepts the repository release page and exact release tags', () => {
expect(isTrustedFirelinkReleaseUrl('https://github.com/nimbold/Firelink/releases')).toBe(true);
expect(isTrustedFirelinkReleaseUrl('https://github.com/nimbold/Firelink/releases/tag/v1.0.5')).toBe(true);
});
it('rejects lookalike paths and URLs with authority or path tricks', () => {
expect(isTrustedFirelinkReleaseUrl('https://github.com/nimbold/Firelink/releases-evil')).toBe(false);
expect(isTrustedFirelinkReleaseUrl('https://github.com/nimbold/Firelink/releases%2F..%2Fother')).toBe(false);
expect(isTrustedFirelinkReleaseUrl('https://github.com/nimbold/Firelink/releases/tag/v1.0.5%5C..%5Cuser%5Crepo')).toBe(false);
expect(isTrustedFirelinkReleaseUrl('https://github.com.evil.example/nimbold/Firelink/releases')).toBe(false);
expect(isTrustedFirelinkReleaseUrl('https://github.com/nimbold/Firelink/releases/tag/v1.0.5?redirect=evil')).toBe(false);
});
});
+27
View File
@@ -0,0 +1,27 @@
const FIRELINK_RELEASES_PATH = '/nimbold/Firelink/releases';
const FIRELINK_RELEASE_TAG_PATTERN = new RegExp(
`^${FIRELINK_RELEASES_PATH}/tag/[A-Za-z0-9._-]+$`
);
export const isTrustedFirelinkReleaseUrl = (value: string) => {
try {
const parsed = new URL(value);
if (
parsed.protocol !== 'https:'
|| parsed.hostname !== 'github.com'
|| parsed.port
|| parsed.username
|| parsed.password
|| parsed.search
|| parsed.hash
) {
return false;
}
const pathname = decodeURIComponent(parsed.pathname);
return pathname === FIRELINK_RELEASES_PATH
|| FIRELINK_RELEASE_TAG_PATTERN.test(pathname);
} catch {
return false;
}
};