diff --git a/.gitignore b/.gitignore index 0e109ce4c..3d089d34a 100755 --- a/.gitignore +++ b/.gitignore @@ -115,6 +115,7 @@ coverage !/build/icons !/build/installer.nsh /electron/native/**/build +/electron/bridges/windowsHelloHelper/build/ /release /out /public/monaco diff --git a/application/app/AppShell.architecture.test.ts b/application/app/AppShell.architecture.test.ts index 1f0305e50..f293a1572 100644 --- a/application/app/AppShell.architecture.test.ts +++ b/application/app/AppShell.architecture.test.ts @@ -10,6 +10,7 @@ const appSource = readFileSync(join(here, '../../App.tsx'), 'utf8'); const vaultPublisherSource = readFileSync(join(here, 'publishers/VaultPublisher.tsx'), 'utf8'); const sessionPublisherSource = readFileSync(join(here, 'publishers/SessionPublisher.tsx'), 'utf8'); const settingsPublisherSource = readFileSync(join(here, 'publishers/SettingsPublisher.tsx'), 'utf8'); +const appLockGateSource = readFileSync(join(here, '../../components/AppLockGate.tsx'), 'utf8'); const hostsDir = join(here, 'hosts'); const hostFiles = existsSync(hostsDir) @@ -79,10 +80,12 @@ test('App.tsx does not subscribe to vault/session/settings runtimes or mega hook assert.match(appSource, / { +test('publishers and the app-lock gate own the mega hooks and store fan-out', () => { assert.match(vaultPublisherSource, /\buseVaultState\s*\(/); assert.match(sessionPublisherSource, /\buseSessionState\s*\(/); - assert.match(settingsPublisherSource, /\buseSettingsState\s*\(/); + assert.match(appLockGateSource, /\buseSettingsState\s*\(/); + assert.doesNotMatch(settingsPublisherSource, /\buseSettingsState\s*\(/); + assert.match(settingsPublisherSource, /registerAppSettingsRuntime\(settings\)/); assert.match(vaultPublisherSource, /publishVaultSnapshot\(/); assert.match(vaultPublisherSource, /registerVaultSnapshotActions\(/); assert.match(vaultPublisherSource, /registerVaultSnapshotActions\(null\)/); diff --git a/application/app/strictModeIdempotency.test.ts b/application/app/strictModeIdempotency.test.ts index 40ec2bebe..8c0b2106d 100644 --- a/application/app/strictModeIdempotency.test.ts +++ b/application/app/strictModeIdempotency.test.ts @@ -20,6 +20,10 @@ const portForwardingAutoStartSource = readFileSync( new URL('../state/usePortForwardingAutoStart.ts', import.meta.url), 'utf8', ); +const appLockBridgeSource = readFileSync( + new URL('../state/useAppLockBridge.ts', import.meta.url), + 'utf8', +); test('every renderer root mounts under StrictMode', () => { assert.match(indexSource, /import \{ StrictMode, Suspense, lazy \} from 'react'/); @@ -58,10 +62,10 @@ test('clone-session payload is consumed once even if the effect re-runs', () => }); test('rendererReady is notified once per renderer process', () => { - assert.match(appSource, /^let rendererReadySent = false;$/m); - const guardAt = appSource.indexOf('if (!rendererReadySent) {'); + assert.match(appLockBridgeSource, /^let rendererReadySent = false;$/m); + const guardAt = appLockBridgeSource.indexOf('if (rendererReadySent) return;'); assert.notEqual(guardAt, -1); - const guarded = appSource.slice(guardAt, guardAt + 200); + const guarded = appLockBridgeSource.slice(guardAt, guardAt + 200); assert.match(guarded, /rendererReadySent = true;/); assert.match(guarded, /netcattyBridge\.get\(\)\?\.rendererReady\?\.\(\)/); assert.ok( diff --git a/application/state/appLockSettingsStorage.test.ts b/application/state/appLockSettingsStorage.test.ts deleted file mode 100644 index c36df82a9..000000000 --- a/application/state/appLockSettingsStorage.test.ts +++ /dev/null @@ -1,149 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; - -import { - createAppLockPasswordVerifier, - verifyAppLockPassword, - type AppLockSettings, -} from "../../domain/appLock.ts"; -import { - applyAppLockEnabledChange, - replaceAppLockPassword, -} from "./appLockSettingsStorage.ts"; - -test("applyAppLockEnabledChange enables only when a verifier exists", async () => { - const verifier = await createAppLockPasswordVerifier("secret"); - const disabled: AppLockSettings = { - enabled: false, - timeoutMinutes: 15, - systemUnlockEnabled: false, - systemUnlockAutoPromptEnabled: false, - passwordVerifier: verifier, - }; - - assert.deepEqual( - await applyAppLockEnabledChange(disabled, true), - { - enabled: true, - timeoutMinutes: 15, - systemUnlockEnabled: false, - systemUnlockAutoPromptEnabled: false, - passwordVerifier: verifier, - }, - ); - - assert.deepEqual( - await applyAppLockEnabledChange({ ...disabled, passwordVerifier: null }, true), - { - enabled: false, - timeoutMinutes: 15, - systemUnlockEnabled: false, - systemUnlockAutoPromptEnabled: false, - passwordVerifier: null, - }, - ); -}); - -test("applyAppLockEnabledChange requires current password before disabling an existing lock", async () => { - const verifier = await createAppLockPasswordVerifier("secret"); - const enabled: AppLockSettings = { - enabled: true, - timeoutMinutes: 30, - systemUnlockEnabled: true, - systemUnlockAutoPromptEnabled: true, - passwordVerifier: verifier, - }; - - assert.deepEqual( - await applyAppLockEnabledChange(enabled, false, "wrong"), - { ok: false, error: "incorrect" }, - ); - - assert.deepEqual( - await applyAppLockEnabledChange(enabled, false, "secret"), - { - enabled: false, - timeoutMinutes: 30, - systemUnlockEnabled: false, - systemUnlockAutoPromptEnabled: false, - passwordVerifier: null, - }, - ); -}); - -test("replaceAppLockPassword requires current password when replacing an existing verifier", async () => { - const verifier = await createAppLockPasswordVerifier("old secret"); - const enabled: AppLockSettings = { - enabled: true, - timeoutMinutes: 5, - systemUnlockEnabled: true, - systemUnlockAutoPromptEnabled: true, - passwordVerifier: verifier, - }; - - assert.deepEqual( - await replaceAppLockPassword(enabled, { - currentPassword: "", - nextPassword: "new secret", - }), - { ok: false, error: "empty-current" }, - ); - assert.deepEqual( - await replaceAppLockPassword(enabled, { - currentPassword: "wrong", - nextPassword: "new secret", - }), - { ok: false, error: "incorrect" }, - ); - - const replaced = await replaceAppLockPassword(enabled, { - currentPassword: "old secret", - nextPassword: "new secret", - }); - - assert.equal("ok" in replaced, false); - assert.equal(replaced.enabled, true); - assert.equal(replaced.timeoutMinutes, 5); - assert.equal(replaced.systemUnlockEnabled, true); - assert.equal(replaced.systemUnlockAutoPromptEnabled, true); - assert.notEqual(replaced.passwordVerifier?.hash, verifier.hash); - assert.equal(await verifyAppLockPassword("new secret", replaced.passwordVerifier), true); -}); - -test("replaceAppLockPassword rejects empty new passwords", async () => { - const settings: AppLockSettings = { - enabled: false, - timeoutMinutes: 60, - systemUnlockEnabled: false, - systemUnlockAutoPromptEnabled: false, - passwordVerifier: null, - }; - - assert.deepEqual( - await replaceAppLockPassword(settings, { - nextPassword: " ", - }), - { ok: false, error: "empty-next" }, - ); -}); - -test("replaceAppLockPassword enables app lock when creating the first password", async () => { - const settings: AppLockSettings = { - enabled: false, - timeoutMinutes: 15, - systemUnlockEnabled: false, - systemUnlockAutoPromptEnabled: false, - passwordVerifier: null, - }; - - const saved = await replaceAppLockPassword(settings, { - nextPassword: "first secret", - }); - - assert.equal("ok" in saved, false); - assert.equal(saved.enabled, true); - assert.equal(saved.timeoutMinutes, 15); - assert.equal(saved.systemUnlockEnabled, false); - assert.equal(saved.systemUnlockAutoPromptEnabled, false); - assert.equal(await verifyAppLockPassword("first secret", saved.passwordVerifier), true); -}); diff --git a/application/state/appLockSettingsStorage.ts b/application/state/appLockSettingsStorage.ts deleted file mode 100644 index 848ec6369..000000000 --- a/application/state/appLockSettingsStorage.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { - createAppLockPasswordVerifier, - normalizeAppLockSettings, - normalizeAppLockPasswordVerifier, - normalizeAppLockTimeoutMinutes, - verifyAppLockPassword, - type AppLockSettings, -} from '../../domain/appLock'; - -export type AppLockSettingsChangeError = - | 'empty-current' - | 'empty-next' - | 'incorrect'; - -export type AppLockSettingsChangeResult = - | AppLockSettings - | { ok: false; error: AppLockSettingsChangeError }; - -export async function applyAppLockEnabledChange( - settings: AppLockSettings, - enabled: boolean, - currentPassword?: string, -): Promise { - const timeoutMinutes = normalizeAppLockTimeoutMinutes(settings.timeoutMinutes); - const passwordVerifier = normalizeAppLockPasswordVerifier(settings.passwordVerifier); - const systemUnlockEnabled = settings.systemUnlockEnabled === true && settings.enabled === true && passwordVerifier !== null; - const systemUnlockAutoPromptEnabled = settings.systemUnlockAutoPromptEnabled === true && systemUnlockEnabled; - if (enabled) { - return passwordVerifier - ? { enabled: true, timeoutMinutes, systemUnlockEnabled, systemUnlockAutoPromptEnabled, passwordVerifier } - : { - enabled: false, - timeoutMinutes, - systemUnlockEnabled: false, - systemUnlockAutoPromptEnabled: false, - passwordVerifier: null, - }; - } - - if (passwordVerifier) { - if (!currentPassword) return { ok: false, error: 'empty-current' }; - const verified = await verifyAppLockPassword(currentPassword, passwordVerifier); - if (!verified) return { ok: false, error: 'incorrect' }; - } - - return { - enabled: false, - timeoutMinutes, - systemUnlockEnabled: false, - systemUnlockAutoPromptEnabled: false, - passwordVerifier: null, - }; -} - -export async function replaceAppLockPassword( - settings: AppLockSettings, - input: { - currentPassword?: string; - nextPassword: string; - }, -): Promise { - const normalized = normalizeAppLockSettings(settings); - if (!input.nextPassword.trim()) return { ok: false, error: 'empty-next' }; - - if (normalized.passwordVerifier) { - if (!input.currentPassword) return { ok: false, error: 'empty-current' }; - const verified = await verifyAppLockPassword(input.currentPassword, normalized.passwordVerifier); - if (!verified) return { ok: false, error: 'incorrect' }; - } - - return { - enabled: normalized.enabled || !normalized.passwordVerifier, - timeoutMinutes: normalized.timeoutMinutes, - systemUnlockEnabled: normalized.systemUnlockEnabled, - systemUnlockAutoPromptEnabled: normalized.systemUnlockAutoPromptEnabled, - passwordVerifier: await createAppLockPasswordVerifier(input.nextPassword), - }; -} diff --git a/application/state/sessionRestoreSettings.test.ts b/application/state/sessionRestoreSettings.test.ts index b52a9f281..bc63f3a2a 100644 --- a/application/state/sessionRestoreSettings.test.ts +++ b/application/state/sessionRestoreSettings.test.ts @@ -129,9 +129,9 @@ test("session peer windows do not run main-window startup effects", () => { // AppLockGate owns useSettingsState; App forwards the gate's instance into // SettingsPublisher so the runtime slot/context still publish it. assert.match(appRootSource, //); - assert.match( + assert.doesNotMatch( readFileSync(new URL("../app/publishers/SettingsPublisher.tsx", import.meta.url), "utf8"), - /useSettingsState\(\{ enableSettingsSync, enableSystemEffects \}\)/, + /useSettingsState\(/, ); assert.match(appSource, /useAppStartupEffects\(\{[^}]*enabled: !isPeerSessionWindow/s); assert.match(appSource, /useUpdateCheck\(\{[^}]*enabled: !isPeerSessionWindow/s); diff --git a/application/state/settingsIpcSync.ts b/application/state/settingsIpcSync.ts index 95494dc71..882f1d399 100644 --- a/application/state/settingsIpcSync.ts +++ b/application/state/settingsIpcSync.ts @@ -1,6 +1,5 @@ import { useEffect, type Dispatch, type SetStateAction } from 'react'; import type { CustomKeyBindings, HotkeyScheme, SessionLogFormat, TerminalSettings, UILanguage } from '../../domain/models'; -import type { AppLockSettings } from '../../domain/appLock'; import { parseCustomKeyBindingsStorageRecord } from '../../domain/customKeyBindings'; import { resolveSupportedLocale } from '../../infrastructure/config/i18n'; import { @@ -77,7 +76,6 @@ interface UseSettingsIpcSyncParams { setFollowAppTerminalThemeState: Dispatch>; setTerminalFontFamilyId: Dispatch>; setTerminalFontSize: (raw: unknown) => void; - setAppLockSettingsState: Dispatch>; mergeIncomingTerminalSettings: (incoming: Partial) => void; setEditorWordWrapState: Dispatch>; setSessionLogsEnabled: Dispatch>; @@ -123,7 +121,6 @@ export function useSettingsIpcSync({ setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize, - setAppLockSettingsState, mergeIncomingTerminalSettings, setEditorWordWrapState, setSessionLogsEnabled, @@ -335,7 +332,6 @@ export function useSettingsIpcSync({ setAutoUpdateEnabled, setHttpNetworkProxy, setEditorWordWrapState, - setAppLockSettingsState, setFollowAppTerminalThemeState, setGlobalHotkeyEnabled, setWindowOpacity, diff --git a/application/state/settingsStorageSync.ts b/application/state/settingsStorageSync.ts index d2a8c993c..34a505953 100644 --- a/application/state/settingsStorageSync.ts +++ b/application/state/settingsStorageSync.ts @@ -1,6 +1,5 @@ import { useEffect, useRef, type Dispatch, type SetStateAction } from 'react'; import type { CustomKeyBindings, HotkeyScheme, SessionLogFormat, TerminalSettings, UILanguage } from '../../domain/models'; -import type { AppLockSettings } from '../../domain/appLock'; import { parseCustomKeyBindingsStorageRecord } from '../../domain/customKeyBindings'; import { resolveSupportedLocale } from '../../infrastructure/config/i18n'; import { @@ -80,7 +79,6 @@ interface UseSettingsStorageSyncParams { followAppTerminalTheme: boolean; terminalFontFamilyId: string; terminalFontSize: number; - appLockSettings: AppLockSettings; sftpDoubleClickBehavior: 'open' | 'transfer'; sftpAutoSync: boolean; sftpShowHiddenFiles: boolean; @@ -130,7 +128,6 @@ interface UseSettingsStorageSyncParams { setFollowAppTerminalThemeState: Dispatch>; setTerminalFontFamilyId: Dispatch>; setTerminalFontSize: (raw: unknown) => void; - setAppLockSettingsState: Dispatch>; setSftpDoubleClickBehavior: Dispatch>; setSftpAutoSync: Dispatch>; setSftpShowHiddenFiles: Dispatch>; @@ -177,7 +174,6 @@ export function useSettingsStorageSync({ theme, lightUiThemeId, darkUiThemeId, accentMode, customAccent, customAccentVersion, customCSS, uiFontFamilyId, hotkeyScheme, uiLanguage, terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize, - appLockSettings, sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding, @@ -187,7 +183,6 @@ export function useSettingsStorageSync({ setCustomCSS, setUiFontFamilyId, setHotkeyScheme, setUiLanguage, setTerminalThemeId, setTerminalThemeDarkId, setTerminalThemeLightId, setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize, - setAppLockSettingsState, setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles, setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode, setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState, @@ -203,7 +198,6 @@ export function useSettingsStorageSync({ theme, lightUiThemeId, darkUiThemeId, accentMode, customAccent, customAccentVersion, customCSS, uiFontFamilyId, hotkeyScheme, uiLanguage, terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize, - appLockSettings, sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding, @@ -214,7 +208,6 @@ export function useSettingsStorageSync({ theme, lightUiThemeId, darkUiThemeId, accentMode, customAccent, customAccentVersion, customCSS, uiFontFamilyId, hotkeyScheme, uiLanguage, terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize, - appLockSettings, sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding, @@ -547,7 +540,6 @@ export function useSettingsStorageSync({ applyIncomingCustomKeyBindings, mergeIncomingTerminalSettings, setAccentMode, - setAppLockSettingsState, setAutoUpdateEnabled, applyIncomingCustomAccent, setCustomCSS, diff --git a/application/state/useAppLockBridge.ts b/application/state/useAppLockBridge.ts index 4181b0e65..b711e5d72 100644 --- a/application/state/useAppLockBridge.ts +++ b/application/state/useAppLockBridge.ts @@ -3,6 +3,8 @@ import { useCallback } from 'react'; import { netcattyBridge } from '../../infrastructure/services/netcattyBridge'; import type { RuntimeAppLockReason } from './useAppLockRuntime'; +let rendererReadySent = false; + export function useAppLockBridge() { const getRuntimeState = useCallback(async () => { return netcattyBridge.get()?.getAppLockRuntimeState?.(); @@ -45,6 +47,8 @@ export function useAppLockBridge() { }, []); const notifyRendererReady = useCallback(() => { + if (rendererReadySent) return; + rendererReadySent = true; try { netcattyBridge.get()?.rendererReady?.(); } catch { diff --git a/application/state/useAppLockState.test.ts b/application/state/useAppLockState.test.ts index b9f9f2417..1046c12c3 100644 --- a/application/state/useAppLockState.test.ts +++ b/application/state/useAppLockState.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createAppLockPasswordVerifier, type AppLockSettings } from "../../domain/appLock.ts"; +import type { AppLockPasswordVerifier, AppLockSettings } from "../../domain/appLock.ts"; import { createOptimisticUnlockedRuntimeState, DEFAULT_APP_LOCK_SYSTEM_UNLOCK_STATUS, @@ -13,8 +13,15 @@ import { } from "./useAppLockState.ts"; import { selectPreferredRuntimeAppLockState } from "./useAppLockRuntime.ts"; -test("shouldLockOnStartup locks only when enabled with a verifier", async () => { - const verifier = await createAppLockPasswordVerifier("secret"); +const verifier: AppLockPasswordVerifier = { + version: 1, + algorithm: "PBKDF2-SHA256", + iterations: 210000, + salt: Buffer.alloc(16, 1).toString("base64"), + hash: Buffer.alloc(32, 2).toString("base64"), +}; + +test("shouldLockOnStartup locks only when enabled with a verifier", () => { const enabled: AppLockSettings = { enabled: true, timeoutMinutes: 15, @@ -28,8 +35,7 @@ test("shouldLockOnStartup locks only when enabled with a verifier", async () => assert.equal(shouldLockOnStartup({ ...enabled, passwordVerifier: null }), false); }); -test("shouldLockAfterIdle honors the configured timeout", async () => { - const verifier = await createAppLockPasswordVerifier("secret"); +test("shouldLockAfterIdle honors the configured timeout", () => { const settings: AppLockSettings = { enabled: true, timeoutMinutes: 5, @@ -45,8 +51,7 @@ test("shouldLockAfterIdle honors the configured timeout", async () => { assert.equal(shouldLockAfterIdle({ ...settings, passwordVerifier: null }, 1_000, 1_000 + 60 * 60_000), false); }); -test("getIdleLockDelayMs schedules the next check after remaining idle time", async () => { - const verifier = await createAppLockPasswordVerifier("secret"); +test("getIdleLockDelayMs schedules the next check after remaining idle time", () => { const settings: AppLockSettings = { enabled: true, timeoutMinutes: 5, @@ -158,8 +163,6 @@ test("normalizes app lock system unlock bridge status and results", () => { test("resolveUnlockAttempt validates empty, incorrect, and correct passwords", async () => { const originalWindow = globalThis.window; - const verifier = await createAppLockPasswordVerifier("secret"); - void verifier; globalThis.window = { netcatty: { requestAppLockUnlock: async (password: string) => diff --git a/application/state/useSettingsState.ts b/application/state/useSettingsState.ts index fbd1b203d..fc6e97a86 100644 --- a/application/state/useSettingsState.ts +++ b/application/state/useSettingsState.ts @@ -1198,7 +1198,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable setStartupLandingState, setSftpTransferConcurrencyState, setSshTransportIdleTtlMsState, - setAppLockSettingsState, }); useEffect(() => { @@ -1244,7 +1243,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable customAccentVersion: customAccentRecord.version, customCSS, uiFontFamilyId, hotkeyScheme, uiLanguage, terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize, - appLockSettings, sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding, @@ -1255,7 +1253,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable setCustomCSS, setUiFontFamilyId, setHotkeyScheme, setUiLanguage, setTerminalThemeId, setTerminalThemeDarkId, setTerminalThemeLightId, setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize: applyIncomingTerminalFontSize, - setAppLockSettingsState, setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles, setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode, setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState, diff --git a/components/AppLockRouteOwnership.test.ts b/components/AppLockRouteOwnership.test.ts index b2c4b3866..2ec878e07 100644 --- a/components/AppLockRouteOwnership.test.ts +++ b/components/AppLockRouteOwnership.test.ts @@ -23,3 +23,11 @@ test("settings, tray, and terminal popup routes do not create fallback settings assert.doesNotMatch(terminalPopupPage, /settings\?:\s*SettingsState/); assert.doesNotMatch(terminalPopupPage, /providedSettings\s*\?\?/); }); + +test("terminal popups wait for app-lock initialization before starting a terminal", () => { + const indexSource = readComponentSource("../index.tsx"); + assert.match( + indexSource, + /allowTerminalStart=\{appLock\.initialized\s*&&\s*!appLock\.locked\}/, + ); +}); diff --git a/components/TerminalPopupPage.test.ts b/components/TerminalPopupPage.test.ts index 7d7d0b5ad..16cac8924 100644 --- a/components/TerminalPopupPage.test.ts +++ b/components/TerminalPopupPage.test.ts @@ -149,7 +149,7 @@ test('popup provider tree mounts the plugin authentication host', () => { assert.match(source, /import \{ PluginAuthenticationHost \} from '\.\/plugins\/PluginAuthenticationHost';/); assert.match( source, - /\s+\s+\s+<\/I18nProvider>/, + /\s+\s+\s+<\/I18nProvider>/, ); }); diff --git a/components/settings/tabs/SettingsSystemTab.tsx b/components/settings/tabs/SettingsSystemTab.tsx index 851bb2d1e..2d1dc3476 100644 --- a/components/settings/tabs/SettingsSystemTab.tsx +++ b/components/settings/tabs/SettingsSystemTab.tsx @@ -4,9 +4,8 @@ import { ChevronDown, ChevronRight, Download, ExternalLink, FolderOpen, RefreshCw, RotateCcw, Trash2 } from "lucide-react"; import React, { useCallback, useEffect, useState } from "react"; import { useI18n } from "../../../application/i18n/I18nProvider"; -import type { AppLockSettingsChangeError } from "../../../application/state/appLockSettingsStorage"; import type { AppLockSystemUnlockStatus } from "../../../application/state/useAppLockState"; -import type { AppLockSettings, AppLockTimeoutMinutes } from "../../../domain/appLock"; +import type { AppLockSettings, AppLockSettingsChangeError, AppLockTimeoutMinutes } from "../../../domain/appLock"; import { APP_LOCK_TIMEOUT_OPTIONS_MINUTES } from "../../../domain/appLock"; import { getCredentialProtectionAvailability } from "../../../infrastructure/services/credentialProtection"; import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"; diff --git a/domain/appLock.test.ts b/domain/appLock.test.ts index bb57c0477..52c43e112 100644 --- a/domain/appLock.test.ts +++ b/domain/appLock.test.ts @@ -4,11 +4,8 @@ import test from "node:test"; import { APP_LOCK_TIMEOUT_OPTIONS_MINUTES, DEFAULT_APP_LOCK_SETTINGS, - canEnableAppLock, - createAppLockPasswordVerifier, normalizeAppLockSettings, normalizeAppLockTimeoutMinutes, - verifyAppLockPassword, } from "./appLock.ts"; test("normalizeAppLockTimeoutMinutes accepts only supported timeout options", () => { @@ -105,27 +102,3 @@ test("normalizeAppLockSettings disables auto prompt unless system unlock is enab assert.equal(normalized.systemUnlockEnabled, false); assert.equal(normalized.systemUnlockAutoPromptEnabled, false); }); - -test("createAppLockPasswordVerifier stores a verifier and verifies password attempts", async () => { - const verifier = await createAppLockPasswordVerifier("correct horse battery staple"); - - assert.equal(verifier.version, 1); - assert.equal(verifier.algorithm, "PBKDF2-SHA256"); - assert.ok(verifier.iterations >= 100000); - assert.notEqual(verifier.salt, ""); - assert.notEqual(verifier.hash, ""); - assert.ok(!verifier.hash.includes("correct horse battery staple")); - - assert.equal(canEnableAppLock({ enabled: false, timeoutMinutes: 15, passwordVerifier: verifier }), true); - assert.equal(await verifyAppLockPassword("correct horse battery staple", verifier), true); - assert.equal(await verifyAppLockPassword("wrong password", verifier), false); - assert.equal(await verifyAppLockPassword("", verifier), false); - assert.equal(await verifyAppLockPassword("correct horse battery staple", null), false); -}); - -test("createAppLockPasswordVerifier rejects empty passwords", async () => { - await assert.rejects( - () => createAppLockPasswordVerifier(" "), - /password/i, - ); -}); diff --git a/domain/appLock.ts b/domain/appLock.ts index e715249ad..dc9ef1e40 100644 --- a/domain/appLock.ts +++ b/domain/appLock.ts @@ -17,6 +17,11 @@ export interface AppLockSettings { passwordVerifier: AppLockPasswordVerifier | null; } +export type AppLockSettingsChangeError = + | 'empty-current' + | 'empty-next' + | 'incorrect'; + export const DEFAULT_APP_LOCK_SETTINGS: AppLockSettings = { enabled: false, timeoutMinutes: 15, @@ -27,20 +32,9 @@ export const DEFAULT_APP_LOCK_SETTINGS: AppLockSettings = { const APP_LOCK_VERIFIER_VERSION = 1; const APP_LOCK_ALGORITHM = 'PBKDF2-SHA256'; -const APP_LOCK_HASH_ITERATIONS = 210000; const APP_LOCK_SALT_BYTES = 16; const APP_LOCK_HASH_BYTES = 32; -const textEncoder = new TextEncoder(); - -function bytesToBase64(bytes: Uint8Array): string { - let binary = ''; - for (const byte of bytes) { - binary += String.fromCharCode(byte); - } - return btoa(binary); -} - function base64ToBytes(value: string): Uint8Array | null { try { const binary = atob(value); @@ -54,18 +48,6 @@ function base64ToBytes(value: string): Uint8Array | null { } } -function timingSafeEqualBase64(a: string, b: string): boolean { - const aBytes = base64ToBytes(a); - const bBytes = base64ToBytes(b); - if (!aBytes || !bBytes || aBytes.length !== bBytes.length) return false; - - let diff = 0; - for (let i = 0; i < aBytes.length; i += 1) { - diff |= aBytes[i] ^ bBytes[i]; - } - return diff === 0; -} - function isRecord(value: unknown): value is Record { return Boolean(value && typeof value === 'object' && !Array.isArray(value)); } @@ -117,61 +99,3 @@ export function normalizeAppLockSettings(input: unknown): AppLockSettings { passwordVerifier, }; } - -async function derivePasswordHash( - password: string, - salt: Uint8Array, - iterations: number, -): Promise { - const keyMaterial = await crypto.subtle.importKey( - 'raw', - textEncoder.encode(password), - 'PBKDF2', - false, - ['deriveBits'], - ); - const bits = await crypto.subtle.deriveBits( - { - name: 'PBKDF2', - hash: 'SHA-256', - salt, - iterations, - }, - keyMaterial, - APP_LOCK_HASH_BYTES * 8, - ); - return bytesToBase64(new Uint8Array(bits)); -} - -export async function createAppLockPasswordVerifier(password: string): Promise { - if (!password.trim()) { - throw new Error('App lock password is required'); - } - - const salt = crypto.getRandomValues(new Uint8Array(APP_LOCK_SALT_BYTES)); - return { - version: APP_LOCK_VERIFIER_VERSION, - algorithm: APP_LOCK_ALGORITHM, - iterations: APP_LOCK_HASH_ITERATIONS, - salt: bytesToBase64(salt), - hash: await derivePasswordHash(password, salt, APP_LOCK_HASH_ITERATIONS), - }; -} - -export async function verifyAppLockPassword( - password: string, - verifier: AppLockPasswordVerifier | null, -): Promise { - const normalized = normalizeAppLockPasswordVerifier(verifier); - if (!password || !normalized) return false; - - const salt = base64ToBytes(normalized.salt); - if (!salt) return false; - - const candidate = await derivePasswordHash(password, salt, normalized.iterations); - return timingSafeEqualBase64(candidate, normalized.hash); -} - -export function canEnableAppLock(settings: AppLockSettings): boolean { - return normalizeAppLockPasswordVerifier(settings.passwordVerifier) !== null; -} diff --git a/electron-builder.config.cjs b/electron-builder.config.cjs index e2039adcf..f70071458 100644 --- a/electron-builder.config.cjs +++ b/electron-builder.config.cjs @@ -54,6 +54,9 @@ module.exports = { files: [ 'dist/**/*', 'electron/**/*', + // The Windows Hello helper is shipped once through win.extraResources. + // Exclude local per-arch build output from app.asar on every platform. + '!electron/bridges/windowsHelloHelper/build/**/*', // Runtime smoke fixtures are built test packages, not host resources. // Keep them out of production ASARs so no example plugin can be // mistaken for an installed or host-trusted package. diff --git a/electron/bridges/appLockRuntimeBridge.cjs b/electron/bridges/appLockRuntimeBridge.cjs index 8f49393cd..a53e338ac 100644 --- a/electron/bridges/appLockRuntimeBridge.cjs +++ b/electron/bridges/appLockRuntimeBridge.cjs @@ -245,6 +245,7 @@ function createAppLockController({ getSettingsWindow = () => null, getTrayPanelWindow = () => null, getTerminalPopupWindows = () => [], + waitForUnlockFailureDelay = (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)), }) { if (!settingsStore || typeof settingsStore.getSnapshot !== "function" || typeof settingsStore.save !== "function") { throw new Error("createAppLockController requires a settingsStore"); @@ -257,6 +258,10 @@ function createAppLockController({ let settingsMutationChain = Promise.resolve(); // Single in-flight system-auth prompt shared across windows (Codex P2). let systemUnlockInFlight = null; + let passwordUnlockInFlight = null; + let passwordUnlockFailureCount = 0; + const lockedWindowTitles = new Map(); + const protectedWindows = new WeakSet(); function syncIdleTimer() { const settings = getSettings(); @@ -308,6 +313,83 @@ function createAppLockController({ } } + function enforceWindowProtection(win) { + if (!win || win.isDestroyed?.() || getRuntimeState()?.locked !== true) return; + try { + if (typeof win.getTitle === "function") { + const currentTitle = win.getTitle(); + if (currentTitle && currentTitle !== "Netcatty") { + lockedWindowTitles.set(win, currentTitle); + } + } + win.setTitle?.("Netcatty"); + if (win.webContents?.isDevToolsOpened?.()) { + win.webContents.closeDevTools?.(); + } + } catch { + // ignore per-window failures during lock transitions + } + } + + function protectWindow(win) { + if (!win || win.isDestroyed?.()) return; + if (!protectedWindows.has(win)) { + protectedWindows.add(win); + const enforce = () => enforceWindowProtection(win); + try { win.on?.("show", enforce); } catch { /* ignore */ } + try { win.on?.("focus", enforce); } catch { /* ignore */ } + try { win.webContents?.on?.("devtools-opened", enforce); } catch { /* ignore */ } + try { + win.webContents?.on?.("did-finish-load", () => { + queueMicrotask(enforce); + }); + } catch { + // ignore + } + } + enforceWindowProtection(win); + } + + function setWindowTitle(win, title) { + if (!win || win.isDestroyed?.()) return false; + const nextTitle = typeof title === "string" && title.trim() ? title.trim() : "Netcatty"; + try { + if (getRuntimeState()?.locked === true) { + lockedWindowTitles.set(win, nextTitle); + win.setTitle?.("Netcatty"); + return false; + } + win.setTitle?.(nextTitle); + return true; + } catch { + return false; + } + } + + function protectWindowsForRuntimeState(nextState) { + if (nextState?.locked === true) { + for (const win of getWindowsForBroadcast()) protectWindow(win); + return; + } + + for (const [win, title] of lockedWindowTitles) { + try { + if (!win.isDestroyed?.() && win.getTitle?.() === "Netcatty") { + win.setTitle?.(title || "Netcatty"); + } + } catch { + // ignore disposed windows during unlock + } + } + lockedWindowTitles.clear(); + } + + // Runtime transitions are the single lock boundary. Idle, background, + // startup, and manual locks all pass through this subscription. + runtimeBridge.subscribe?.(protectWindowsForRuntimeState); + // initialize() can lock the runtime before the controller exists. + protectWindowsForRuntimeState(runtimeBridge.getState()); + function getSettings() { return settingsStore.getSnapshot(); } @@ -463,30 +545,43 @@ function createAppLockController({ } async function requestPasswordChange(input = {}) { - const current = getSettings(); const nextPassword = typeof input.nextPassword === "string" ? input.nextPassword : ""; const currentPassword = typeof input.currentPassword === "string" ? input.currentPassword : ""; + const hadVerifierAtRequest = Boolean(getSettings().passwordVerifier); if (nextPassword.trim() === "") { return { ok: false, error: "empty-next" }; } - if (current.passwordVerifier) { - if (!currentPassword) { - return { ok: false, error: "empty-current" }; + let fail = null; + let enablingFromNoVerifier = false; + const saved = await mutateSettings(async (current) => { + // A password-change request must not turn into a first-time enable if a + // disable/reset queued ahead of it removed the verifier. + if (hadVerifierAtRequest && !current.passwordVerifier) { + fail = { ok: false, error: "incorrect" }; + return null; } - const verified = await verifyAppLockPassword(currentPassword, current.passwordVerifier); - if (!verified) { - return { ok: false, error: "incorrect" }; + if (current.passwordVerifier) { + if (!currentPassword) { + fail = { ok: false, error: "empty-current" }; + return null; + } + const verified = await verifyAppLockPassword(currentPassword, current.passwordVerifier); + if (!verified) { + fail = { ok: false, error: "incorrect" }; + return null; + } } - } - const passwordVerifier = await createAppLockPasswordVerifier(nextPassword); - const enablingFromNoVerifier = !current.passwordVerifier; - const saved = await mutateSettings(async (latest) => ({ - ...latest, - enabled: latest.enabled || !latest.passwordVerifier, - passwordVerifier, - })); + enablingFromNoVerifier = !current.passwordVerifier; + const passwordVerifier = await createAppLockPasswordVerifier(nextPassword); + return { + ...current, + enabled: current.enabled || enablingFromNoVerifier, + passwordVerifier, + }; + }); + if (fail) return fail; // While lock was disabled the renderer never reported activity. Re-arming // the idle timer on enable would schedule an immediate lock if Netcatty // has been open longer than the timeout. Record fresh activity first @@ -572,28 +667,33 @@ function createAppLockController({ } const nextState = runtimeBridge.lock(reason); syncIdleTimer(); - // Close DevTools that were open before lock — menu guard only blocks new - // toggles, not already-open consoles (Codex P1). - try { - for (const win of getWindowsForBroadcast()) { - try { - if (win?.webContents?.isDevToolsOpened?.()) { - win.webContents.closeDevTools(); - } - } catch { - // ignore per-window failures - } - } - } catch { - // ignore - } broadcast("netcatty:appLock:runtimeStateChanged", nextState); return nextState; } - async function requestUnlock(password) { + function isSamePasswordVerifier(a, b) { + return Boolean( + a + && b + && a.version === b.version + && a.algorithm === b.algorithm + && a.iterations === b.iterations + && a.salt === b.salt + && a.hash === b.hash + ); + } + + async function rejectPasswordUnlockAttempt() { + passwordUnlockFailureCount += 1; + const delayMs = 250 * (2 ** Math.min(passwordUnlockFailureCount - 1, 3)); + await waitForUnlockFailureDelay(delayMs); + return { ok: false, error: "incorrect" }; + } + + async function requestUnlockAttempt(password, requestContext) { const current = getSettings(); if (!canLockFromSettings(current)) { + passwordUnlockFailureCount = 0; const nextState = runtimeBridge.unlock(); syncIdleTimer(); broadcast("netcatty:appLock:runtimeStateChanged", nextState); @@ -603,17 +703,53 @@ function createAppLockController({ return { ok: false, error: "empty" }; } - const verified = await verifyAppLockPassword(password, current.passwordVerifier); - if (!verified) { - return { ok: false, error: "incorrect" }; + const lockAtAttempt = requestContext.lockState; + if ( + lockAtAttempt.locked !== true + || !isSamePasswordVerifier(requestContext.passwordVerifier, current.passwordVerifier) + ) { + return rejectPasswordUnlockAttempt(); + } + const verified = await verifyAppLockPassword(password, requestContext.passwordVerifier); + const latest = getSettings(); + const lockAfterVerify = runtimeBridge.getState(); + const staleAttempt = !isSamePasswordVerifier(requestContext.passwordVerifier, latest.passwordVerifier) + || lockAfterVerify.locked !== true + || lockAfterVerify.version !== lockAtAttempt.version; + if (!verified || staleAttempt) { + return rejectPasswordUnlockAttempt(); } + passwordUnlockFailureCount = 0; const nextState = runtimeBridge.unlock(); syncIdleTimer(); broadcast("netcatty:appLock:runtimeStateChanged", nextState); return { ok: true }; } + function requestUnlock(password) { + const current = getSettings(); + const requestContext = { + lockState: runtimeBridge.getState(), + passwordVerifier: current.passwordVerifier, + }; + if (!canLockFromSettings(current)) { + return requestUnlockAttempt(password, requestContext); + } + // Calls made while unlocked must never enter a queue that can delay a + // later legitimate unlock after idle/background locking. + if (requestContext.lockState.locked !== true) { + return Promise.resolve({ ok: false, error: "incorrect" }); + } + // At most one expensive password attempt may be active. Concurrent IPC + // calls share it instead of creating an unbounded PBKDF/backoff queue. + if (passwordUnlockInFlight) return passwordUnlockInFlight; + passwordUnlockInFlight = requestUnlockAttempt(password, requestContext); + return passwordUnlockInFlight.finally(() => { + passwordUnlockInFlight = null; + }); + } + async function requestSystemUnlock() { if (systemUnlockInFlight) { return systemUnlockInFlight; @@ -711,6 +847,8 @@ function createAppLockController({ setSystemUnlockEnabled, requestSystemUnlock, reportActivity, + protectWindow, + setWindowTitle, registerHandlers, syncIdleTimer, }; diff --git a/electron/bridges/appLockRuntimeBridge.test.cjs b/electron/bridges/appLockRuntimeBridge.test.cjs index 070a2e742..ca03981d8 100644 --- a/electron/bridges/appLockRuntimeBridge.test.cjs +++ b/electron/bridges/appLockRuntimeBridge.test.cjs @@ -1,5 +1,6 @@ const test = require("node:test"); const assert = require("node:assert/strict"); +const { EventEmitter } = require("node:events"); const { createAppLockController, @@ -229,22 +230,49 @@ test("runtime bridge unreferences the shared idle timer handle when supported", function createWindowCollector(name) { const sent = []; - return { - name, - sent, + let devToolsOpened = false; + let devToolsCloseCount = 0; + let title = `${name}@host`; + const win = new EventEmitter(); + const webContents = new EventEmitter(); + Object.assign(webContents, { + id: `${name}-${Math.random()}`, isDestroyed() { return false; }, - webContents: { - id: `${name}-${Math.random()}`, - isDestroyed() { - return false; - }, - send(channel, payload) { - sent.push([channel, payload]); - }, + send(channel, payload) { + sent.push([channel, payload]); }, - }; + isDevToolsOpened() { + return devToolsOpened; + }, + closeDevTools() { + devToolsOpened = false; + devToolsCloseCount += 1; + }, + }); + Object.assign(win, { + name, + sent, + openDevToolsForTest() { + devToolsOpened = true; + webContents.emit("devtools-opened"); + }, + getDevToolsCloseCount() { + return devToolsCloseCount; + }, + getTitle() { + return title; + }, + setTitle(nextTitle) { + title = nextTitle; + }, + isDestroyed() { + return false; + }, + webContents, + }); + return win; } function createIpcMainHarness() { @@ -257,7 +285,7 @@ function createIpcMainHarness() { }; } -async function createControllerHarness() { +async function createControllerHarness(options = {}) { const settingsStore = createAppLockSettingsStore({ filePath: "/tmp/app-lock-settings.json", readFile: async () => { @@ -304,6 +332,7 @@ async function createControllerHarness() { return { ok: true }; }, }; + const unlockFailureDelays = []; const controller = createAppLockController({ settingsStore, @@ -316,6 +345,9 @@ async function createControllerHarness() { getSettingsWindow: () => settingsWindow, getTrayPanelWindow: () => trayPanelWindow, getTerminalPopupWindows: () => [popupWindowA, popupWindowB], + waitForUnlockFailureDelay: options.waitForUnlockFailureDelay ?? (async (delayMs) => { + unlockFailureDelays.push(delayMs); + }), }); return { @@ -324,6 +356,7 @@ async function createControllerHarness() { settingsStore, systemAuthBridge, systemAuthCalls, + unlockFailureDelays, windows: [ mainWindowA, mainWindowB, @@ -450,6 +483,115 @@ test("unlock request verifies against the latest persisted password verifier", a }); }); +test("incorrect password attempts back off and a successful unlock resets the delay", async () => { + const { controller, unlockFailureDelays } = await createControllerHarness(); + await controller.requestPasswordChange({ nextPassword: "alpha" }); + controller.setLocked("manual"); + + assert.deepEqual(await controller.requestUnlock("wrong-1"), { ok: false, error: "incorrect" }); + assert.deepEqual(await controller.requestUnlock("wrong-2"), { ok: false, error: "incorrect" }); + assert.deepEqual(unlockFailureDelays, [250, 500]); + + assert.deepEqual(await controller.requestUnlock("alpha"), { ok: true }); + controller.setLocked("manual"); + assert.deepEqual(await controller.requestUnlock("wrong-3"), { ok: false, error: "incorrect" }); + assert.deepEqual(unlockFailureDelays, [250, 500, 250]); +}); + +test("parallel password attempts share one bounded in-flight verification", async () => { + const delays = []; + let releaseFirstDelay; + const { controller } = await createControllerHarness({ + waitForUnlockFailureDelay: async (delayMs) => { + delays.push(delayMs); + if (delays.length === 1) { + await new Promise((resolve) => { + releaseFirstDelay = resolve; + }); + } + }, + }); + await controller.requestPasswordChange({ nextPassword: "alpha" }); + controller.setLocked("manual"); + + const first = controller.requestUnlock("wrong-1"); + const second = controller.requestUnlock("wrong-2"); + const deadline = Date.now() + 1000; + while (!releaseFirstDelay && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 5)); + } + assert.ok(releaseFirstDelay, "first attempt should reach backoff"); + assert.deepEqual(delays, [250], "second attempt must not start another backoff"); + + releaseFirstDelay(); + assert.deepEqual(await Promise.all([first, second]), [ + { ok: false, error: "incorrect" }, + { ok: false, error: "incorrect" }, + ]); + assert.deepEqual(delays, [250]); +}); + +test("password unlock result is discarded after a newer lock transition", async () => { + const { controller, runtimeBridge } = await createControllerHarness(); + await controller.requestPasswordChange({ nextPassword: "alpha" }); + controller.setLocked("manual"); + + const pending = controller.requestUnlock("alpha"); + await Promise.resolve(); + controller.setLocked("background"); + + assert.deepEqual(await pending, { ok: false, error: "incorrect" }); + assert.equal(runtimeBridge.getState().locked, true); + assert.equal(runtimeBridge.getState().reason, "background"); +}); + +test("an unlock request started while unlocked cannot unlock a later background lock", async () => { + const { controller, runtimeBridge } = await createControllerHarness(); + await controller.requestPasswordChange({ nextPassword: "alpha" }); + await controller.requestUnlock("alpha"); + assert.equal(runtimeBridge.getState().locked, false); + + const pending = controller.requestUnlock("alpha"); + controller.setLocked("background"); + + assert.deepEqual(await pending, { ok: false, error: "incorrect" }); + assert.equal(runtimeBridge.getState().locked, true); + assert.equal(runtimeBridge.getState().reason, "background"); +}); + +test("unlocked requests cannot queue ahead of a later legitimate unlock", async () => { + const { controller, runtimeBridge, unlockFailureDelays } = await createControllerHarness(); + await controller.requestPasswordChange({ nextPassword: "alpha" }); + await controller.requestUnlock("alpha"); + + const staleCalls = Array.from({ length: 20 }, () => controller.requestUnlock("garbage")); + controller.setLocked("background"); + assert.deepEqual(await controller.requestUnlock("alpha"), { ok: true }); + assert.equal(runtimeBridge.getState().locked, false); + assert.deepEqual(await Promise.all(staleCalls), Array.from( + { length: 20 }, + () => ({ ok: false, error: "incorrect" }), + )); + assert.deepEqual(unlockFailureDelays, []); +}); + +test("password unlock result is discarded after the verifier changes", async () => { + const { controller, runtimeBridge, settingsStore } = await createControllerHarness(); + await controller.requestPasswordChange({ nextPassword: "alpha" }); + controller.setLocked("manual"); + const replacementVerifier = await createAppLockPasswordVerifier("bravo"); + + const pending = controller.requestUnlock("alpha"); + await Promise.resolve(); + await settingsStore.save({ + ...settingsStore.getSnapshot(), + passwordVerifier: replacementVerifier, + }); + + assert.deepEqual(await pending, { ok: false, error: "incorrect" }); + assert.equal(runtimeBridge.getState().locked, true); +}); + test("stale renderer cannot overwrite the latest verifier with a whole-object settings write", async () => { const { controller, settingsStore } = await createControllerHarness(); await controller.requestPasswordChange({ nextPassword: "alpha" }); @@ -578,6 +720,76 @@ test("activity reported from any window postpones the shared idle lock", async ( }); }); +test("idle lock closes DevTools in every app window", async () => { + await withPatchedTimers(async ({ flushDueTimers }) => { + await withPatchedDateNow(1000, async ({ setNow }) => { + const { controller, runtimeBridge, windows } = await createControllerHarness(); + + await controller.requestPasswordChange({ nextPassword: "alpha" }); + await controller.setTimeoutMinutes(1); + await controller.requestUnlock("alpha"); + windows.forEach((win) => win.openDevToolsForTest()); + + setNow(61000); + assert.equal(flushDueTimers(), 1); + assert.equal(runtimeBridge.getState().locked, true); + assert.equal(runtimeBridge.getState().reason, "idle"); + windows.forEach((win) => { + assert.equal(win.getDevToolsCloseCount(), 1, `${win.name} DevTools should close on idle lock`); + }); + }); + }); +}); + +test("startup lock immediately protects existing and newly opened windows", async () => { + const existingWindow = createWindowCollector("existing"); + existingWindow.openDevToolsForTest(); + const settingsStore = createAppLockSettingsStore({ + filePath: "/tmp/app-lock-startup-window.json", + readFile: async () => { + const err = new Error("ENOENT"); + err.code = "ENOENT"; + throw err; + }, + writeFile: async () => {}, + }); + await settingsStore.load(); + const runtimeBridge = createAppLockRuntimeBridge(); + runtimeBridge.initialize({ locked: true, reason: "startup", lastActivityAt: 1000 }); + const controller = createAppLockController({ + settingsStore, + runtimeBridge, + getMainWindows: () => [existingWindow], + }); + + assert.equal(existingWindow.getTitle(), "Netcatty"); + assert.equal(existingWindow.getDevToolsCloseCount(), 1); + + const newWindow = createWindowCollector("new-session"); + controller.protectWindow(newWindow); + assert.equal(newWindow.getTitle(), "Netcatty"); + newWindow.openDevToolsForTest(); + assert.equal(newWindow.getDevToolsCloseCount(), 1); + + controller.setWindowTitle(newWindow, "new@host"); + assert.equal(newWindow.getTitle(), "Netcatty"); + runtimeBridge.unlock(); + assert.equal(newWindow.getTitle(), "new@host"); +}); + +test("lock redacts window titles and unlock restores them", async () => { + const { controller, windows } = await createControllerHarness(); + await controller.requestPasswordChange({ nextPassword: "alpha" }); + await controller.requestUnlock("alpha"); + const originalTitles = windows.map((win) => win.getTitle()); + + controller.setLocked("manual"); + assert.deepEqual(windows.map((win) => win.getTitle()), windows.map(() => "Netcatty")); + + await controller.requestUnlock("alpha"); + assert.deepEqual(windows.map((win) => win.getTitle()), originalTitles); +}); + test("disabling app lock clears the shared idle timer", async () => { await withPatchedTimers(async ({ getPendingTimerCount }) => { const { controller, runtimeBridge } = await createControllerHarness(); @@ -658,3 +870,19 @@ test("creating the first app lock password enables app lock", async () => { assert.equal(saved.enabled, true); assert.equal(typeof saved.passwordVerifier?.hash, "string"); }); + +test("a queued password change cannot revive a concurrently disabled lock", async () => { + const { controller } = await createControllerHarness(); + await controller.requestPasswordChange({ nextPassword: "alpha" }); + + const disable = controller.requestDisable("alpha"); + const passwordChange = controller.requestPasswordChange({ + currentPassword: "alpha", + nextPassword: "beta", + }); + await Promise.all([passwordChange, disable]); + + const settings = controller.getSettings(); + assert.equal(settings.enabled, false); + assert.equal(settings.passwordVerifier, null); +}); diff --git a/electron/bridges/appLockSettingsStore.cjs b/electron/bridges/appLockSettingsStore.cjs index 4eb65161d..247e0edb2 100644 --- a/electron/bridges/appLockSettingsStore.cjs +++ b/electron/bridges/appLockSettingsStore.cjs @@ -1,5 +1,5 @@ const { - pbkdf2Sync, + pbkdf2, randomBytes, timingSafeEqual, } = require("node:crypto"); @@ -98,7 +98,15 @@ function normalizeAppLockPasswordVerifier(input) { } function derivePasswordHash(password, saltBytes, iterations) { - return pbkdf2Sync(password, saltBytes, iterations, APP_LOCK_HASH_BYTES, "sha256").toString("base64"); + return new Promise((resolve, reject) => { + pbkdf2(password, saltBytes, iterations, APP_LOCK_HASH_BYTES, "sha256", (error, derivedKey) => { + if (error) { + reject(error); + return; + } + resolve(derivedKey.toString("base64")); + }); + }); } function normalizeAppLockSettings(input) { @@ -135,7 +143,7 @@ async function createAppLockPasswordVerifier(password) { algorithm: APP_LOCK_ALGORITHM, iterations: APP_LOCK_HASH_ITERATIONS, salt: saltBytes.toString("base64"), - hash: derivePasswordHash(password, saltBytes, APP_LOCK_HASH_ITERATIONS), + hash: await derivePasswordHash(password, saltBytes, APP_LOCK_HASH_ITERATIONS), }; } @@ -150,7 +158,7 @@ async function verifyAppLockPassword(password, verifier) { if (!saltBytes || !hashBytes) return false; const candidateBytes = Buffer.from( - derivePasswordHash(password, saltBytes, normalized.iterations), + await derivePasswordHash(password, saltBytes, normalized.iterations), "base64", ); if (candidateBytes.length !== hashBytes.length) return false; diff --git a/electron/bridges/appLockSettingsStore.test.cjs b/electron/bridges/appLockSettingsStore.test.cjs index 0c55005c2..29475d00d 100644 --- a/electron/bridges/appLockSettingsStore.test.cjs +++ b/electron/bridges/appLockSettingsStore.test.cjs @@ -7,6 +7,15 @@ const { canLockFromSettings, verifyAppLockPassword, } = require("./appLockSettingsStore.cjs"); +const fs = require("node:fs"); +const path = require("node:path"); + +const settingsStoreSource = fs.readFileSync(path.join(__dirname, "appLockSettingsStore.cjs"), "utf8"); + +test("password hashing uses the asynchronous crypto API", () => { + assert.doesNotMatch(settingsStoreSource, /pbkdf2Sync/); + assert.match(settingsStoreSource, /\bpbkdf2\b/); +}); const VALID_VERIFIER = { version: 1, diff --git a/electron/bridges/appLockSystemAuthBridge.cjs b/electron/bridges/appLockSystemAuthBridge.cjs index 95b9f92f5..b05a0549c 100644 --- a/electron/bridges/appLockSystemAuthBridge.cjs +++ b/electron/bridges/appLockSystemAuthBridge.cjs @@ -1,7 +1,8 @@ const path = require("node:path"); const { execFile: defaultExecFile } = require("node:child_process"); -const SYSTEM_AUTH_TIMEOUT_MS = 15000; +const SYSTEM_AUTH_STATUS_TIMEOUT_MS = 15000; +const SYSTEM_AUTH_VERIFY_TIMEOUT_MS = 120000; const UNAVAILABLE_ERRORS = new Set([ "DeviceNotPresent", "NotConfiguredForUser", @@ -70,7 +71,7 @@ function nativeWindowHandleToDecimal(handle) { return value > 0n ? value.toString(10) : null; } -function runHelper(execFile, helperPath, args) { +function runHelper(execFile, helperPath, args, timeout) { return new Promise((resolve) => { if (!helperPath) { resolve({ ok: false, error: "unavailable" }); @@ -78,7 +79,7 @@ function runHelper(execFile, helperPath, args) { } execFile(helperPath, args, { encoding: "utf8", - timeout: SYSTEM_AUTH_TIMEOUT_MS, + timeout, windowsHide: true, maxBuffer: 1024 * 1024, }, (error, stdout) => { @@ -91,12 +92,17 @@ function runHelper(execFile, helperPath, args) { }); } -function resolveDefaultHelperPath() { - if (process.platform !== "win32") return null; - if (process.resourcesPath) { - return path.join(process.resourcesPath, "windowsHello", "NetcattyWindowsHello.exe"); +function resolveDefaultHelperPath({ + platform = process.platform, + arch = process.arch, + isPackaged = false, + resourcesPath = process.resourcesPath, +} = {}) { + if (platform !== "win32") return null; + if (isPackaged) { + return path.win32.join(resourcesPath, "windowsHello", "NetcattyWindowsHello.exe"); } - return path.join(__dirname, "windowsHelloHelper", "build", process.arch, "NetcattyWindowsHello.exe"); + return path.join(__dirname, "windowsHelloHelper", "build", arch, "NetcattyWindowsHello.exe"); } function createAppLockSystemAuthBridge({ @@ -125,15 +131,16 @@ function createAppLockSystemAuthBridge({ await systemPreferences.promptTouchID("Unlock Netcatty"); return { ok: true }; } catch (err) { - const message = String(err?.message || err || ""); - return /cancel/i.test(message) - ? { ok: false, error: "cancelled" } - : { ok: false, error: "failed" }; + // Electron exposes only a localized rejection message here. Since the + // status check already established availability, a rejected prompt is a + // user-visible cancellation regardless of system language. + void err; + return { ok: false, error: "cancelled" }; } } async function getWindowsStatus() { - const result = await runHelper(execFile, helperPath, ["status"]); + const result = await runHelper(execFile, helperPath, ["status"], SYSTEM_AUTH_STATUS_TIMEOUT_MS); return normalizeSystemAuthStatus({ supported: true, available: result?.available === true, @@ -144,7 +151,12 @@ function createAppLockSystemAuthBridge({ async function requestWindowsUnlock() { const hwnd = nativeWindowHandleToDecimal(getNativeWindowHandle()); if (!hwnd) return { ok: false, error: "unavailable" }; - const result = await runHelper(execFile, helperPath, ["verify", "--hwnd", hwnd, "--message", "Unlock Netcatty"]); + const result = await runHelper( + execFile, + helperPath, + ["verify", "--hwnd", hwnd, "--message", "Unlock Netcatty"], + SYSTEM_AUTH_VERIFY_TIMEOUT_MS, + ); return normalizeSystemAuthUnlockResult(result); } diff --git a/electron/bridges/appLockSystemAuthBridge.test.cjs b/electron/bridges/appLockSystemAuthBridge.test.cjs index 9dba72394..c44afe0cd 100644 --- a/electron/bridges/appLockSystemAuthBridge.test.cjs +++ b/electron/bridges/appLockSystemAuthBridge.test.cjs @@ -84,6 +84,7 @@ test("Windows status and unlock call helper with HWND", async () => { assert.equal(calls[0].options.windowsHide, true); assert.equal(calls[0].options.timeout, 15000); assert.deepEqual(calls[1].args, ["verify", "--hwnd", "1234605616436508552", "--message", "Unlock Netcatty"]); + assert.equal(calls[1].options.timeout, 120000); }); test("Windows dev helper path follows the architecture-specific build output", () => { @@ -93,7 +94,10 @@ test("Windows dev helper path follows the architecture-specific build output", ( Object.defineProperty(process, "arch", { value: "x64" }); try { - const helperPath = resolveDefaultHelperPath(); + const helperPath = resolveDefaultHelperPath({ + isPackaged: false, + resourcesPath: "C:\\fake-electron-resources", + }); assert.match(helperPath, /windowsHelloHelper[\\/]build[\\/]x64[\\/]NetcattyWindowsHello\.exe$/); } finally { Object.defineProperty(process, "platform", originalPlatform); @@ -101,6 +105,32 @@ test("Windows dev helper path follows the architecture-specific build output", ( } }); +test("Windows packaged helper path uses the app resources directory", () => { + assert.equal( + resolveDefaultHelperPath({ + platform: "win32", + isPackaged: true, + resourcesPath: "C:\\Netcatty\\resources", + arch: "x64", + }), + "C:\\Netcatty\\resources\\windowsHello\\NetcattyWindowsHello.exe", + ); +}); + +test("macOS localized prompt rejection maps to cancelled", async () => { + const bridge = createAppLockSystemAuthBridge({ + platform: "darwin", + systemPreferences: { + canPromptTouchID: () => true, + promptTouchID: async () => { + throw new Error("用户已取消认证"); + }, + }, + }); + + assert.deepEqual(await bridge.requestUnlock(), { ok: false, error: "cancelled" }); +}); + test("Windows helper maps unavailable and cancelled states", async () => { const bridge = createAppLockSystemAuthBridge({ platform: "win32", diff --git a/electron/bridges/appLockWindowsHelloHelper.test.cjs b/electron/bridges/appLockWindowsHelloHelper.test.cjs index f400fe651..3a363e023 100644 --- a/electron/bridges/appLockWindowsHelloHelper.test.cjs +++ b/electron/bridges/appLockWindowsHelloHelper.test.cjs @@ -29,3 +29,8 @@ test("Windows Hello helper maps all expected verifier states", () => { assert.match(helperSource, new RegExp(state)); } }); + +test("Windows Hello helper uses a multi-threaded apartment for blocking waits", () => { + assert.match(helperSource, /init_apartment\(winrt::apartment_type::multi_threaded\)/); + assert.doesNotMatch(helperSource, /init_apartment\(winrt::apartment_type::single_threaded\)/); +}); diff --git a/electron/bridges/globalShortcutBridge.test.cjs b/electron/bridges/globalShortcutBridge.test.cjs index 73ccd9cfb..bc2b89aab 100644 --- a/electron/bridges/globalShortcutBridge.test.cjs +++ b/electron/bridges/globalShortcutBridge.test.cjs @@ -267,7 +267,11 @@ async function withPlatform(platform, run) { } async function enableCloseToTray(bridge, electronModule = createElectronStub(), extraDeps = {}) { - bridge.init({ electronModule, ...extraDeps }); + bridge.init({ + electronModule, + getMainWindow: () => electronModule.BrowserWindow.getAllWindows()[0] ?? null, + ...extraDeps, + }); const ipcMain = createIpcMainStub(); bridge.registerHandlers(ipcMain); await ipcMain.handlers.get("netcatty:tray:setCloseToTray")(null, { enabled: true }); @@ -504,6 +508,7 @@ test("tray session menu reveal cancels a pending fullscreen hide before focusing electronModule.BrowserWindow.getAllWindows = () => [win]; bridge.init({ electronModule, + getMainWindow: () => win, getAppLockController: () => appLockController, }); const ipcMain = createIpcMainStub(); @@ -525,6 +530,7 @@ test("tray session menu reveal cancels a pending fullscreen hide before focusing .filter((item) => typeof item.click === "function") .find((item) => String(item.label).includes("dev.example")); sessionItem.click(); + await Promise.resolve(); assert.equal(win.showCalls, 1); assert.equal(getPendingTimerCount(), 0); @@ -754,15 +760,17 @@ test("tray icon event registration is platform-dependent", async () => { const win = new FakeWindow(); win.minimized = true; - bridge.init({ - electronModule: { + const initializedElectronModule = { ...createElectronStub(), BrowserWindow: { getAllWindows() { return [win]; }, }, - }, + }; + bridge.init({ + electronModule: initializedElectronModule, + getMainWindow: () => win, getAppLockController: () => null, }); await ipcMain.handlers.get("netcatty:tray:updateMenuData")(null, { @@ -774,6 +782,7 @@ test("tray icon event registration is platform-dependent", async () => { const portForwardItem = clickableItems.find((item) => String(item.label).includes("ssh")); sessionItem.click(); + await Promise.resolve(); assert.deepEqual(win.sentMessages.slice(0, 2), [ ["netcatty:app-lock:reopen"], ["netcatty:tray:focusSession", "s1"], @@ -791,18 +800,20 @@ test("tray icon event registration is platform-dependent", async () => { // Locked runtime defers the toggle until unlock, while still reopening the window. await withPlatform("linux", async () => { const bridge = loadBridge(); - const appLockController = createAppLockControllerStub({ locked: true, reason: "background" }); + const appLockController = createAppLockControllerStub(); const win = new FakeWindow(); win.minimized = true; - bridge.init({ - electronModule: { + const initializedElectronModule = { ...createElectronStub(), BrowserWindow: { getAllWindows() { return [win]; }, }, - }, + }; + bridge.init({ + electronModule: initializedElectronModule, + getMainWindow: () => win, getAppLockController: () => appLockController, }); const ipcMain = createIpcMainStub(); @@ -823,6 +834,7 @@ test("tray icon event registration is platform-dependent", async () => { const portForwardItem = bridge.getTray().contextMenu.template .filter((item) => typeof item.click === "function") .find((item) => String(item.label).includes("ssh")); + appLockController.setLocked("background"); portForwardItem.click(); assert.deepEqual(win.sentMessages, [ @@ -884,11 +896,10 @@ test("native tray sends an explicit stop for a runtime-present error rule", asyn ); assert.ok(ruleItem); ruleItem.click(); - assert.deepEqual(sentMessages, [[ - "netcatty:tray:togglePortForward", - "cleanup-failed-rule", - false, - ]]); + assert.deepEqual(sentMessages, [ + ["netcatty:app-lock:reopen"], + ["netcatty:tray:togglePortForward", "cleanup-failed-rule", false], + ]); bridge.cleanup(); }); }); @@ -932,7 +943,10 @@ test("mac dock menu lists saved hosts and forwards connect actions", async () => await connectionMenu.submenu[0].click(); - assert.deepEqual(sentMessages, [["netcatty:trayPanel:connectToHost", "pinned"]]); + assert.deepEqual(sentMessages, [ + ["netcatty:app-lock:reopen"], + ["netcatty:trayPanel:connectToHost", "pinned"], + ]); }); }); @@ -972,7 +986,10 @@ test("mac dock host click creates a main window when none exists", async () => { await connectionMenu.submenu[0].click(); assert.equal(createCalls, 1); - assert.deepEqual(sentMessages, [["netcatty:trayPanel:connectToHost", "target"]]); + assert.deepEqual(sentMessages, [ + ["netcatty:app-lock:reopen"], + ["netcatty:trayPanel:connectToHost", "target"], + ]); }); }); @@ -1018,12 +1035,15 @@ test("mac dock host click waits for a newly created main window to be ready", as for (let i = 0; i < 5 && !releaseReady; i += 1) { await Promise.resolve(); } - assert.deepEqual(sentMessages, []); + assert.deepEqual(sentMessages, [["netcatty:app-lock:reopen"]]); releaseReady(); await clickPromise; - assert.deepEqual(sentMessages, [["netcatty:trayPanel:connectToHost", "target"]]); + assert.deepEqual(sentMessages, [ + ["netcatty:app-lock:reopen"], + ["netcatty:trayPanel:connectToHost", "target"], + ]); }); }); @@ -1075,12 +1095,15 @@ test("mac dock host click waits for a tracked main window to be ready", async () await Promise.resolve(); } assert.equal(createCalls, 0); - assert.deepEqual(sentMessages, []); + assert.deepEqual(sentMessages, [["netcatty:app-lock:reopen"]]); releaseReady(); await clickPromise; - assert.deepEqual(sentMessages, [["netcatty:trayPanel:connectToHost", "target"]]); + assert.deepEqual(sentMessages, [ + ["netcatty:app-lock:reopen"], + ["netcatty:trayPanel:connectToHost", "target"], + ]); }); }); diff --git a/electron/bridges/windowManager.cjs b/electron/bridges/windowManager.cjs index 0cb016459..89469ceb2 100644 --- a/electron/bridges/windowManager.cjs +++ b/electron/bridges/windowManager.cjs @@ -1108,6 +1108,13 @@ function registerWindowHandlers(ipcMain, nativeTheme) { ipcMain.handle("netcatty:window:setTitle", (event, title) => { const win = getWindowForIpcEvent(event); if (!win || win.isDestroyed()) return false; + try { + if (typeof menuDeps?.setAppLockWindowTitle === "function") { + return menuDeps.setAppLockWindowTitle(win, title) === true; + } + } catch { + // Ignore title-guard failures and keep normal title behavior. + } const value = typeof title === "string" ? title.trim() : ""; try { win.setTitle(value || "Netcatty"); @@ -1251,6 +1258,11 @@ function buildAppMenu(Menu, app, isMac, language = currentLanguage, options = {} isAppLocked: typeof options.isAppLocked === "function" ? options.isAppLocked : (typeof menuDeps?.isAppLocked === "function" ? menuDeps.isAppLocked : undefined), + setAppLockWindowTitle: typeof options.setAppLockWindowTitle === "function" + ? options.setAppLockWindowTitle + : (typeof menuDeps?.setAppLockWindowTitle === "function" + ? menuDeps.setAppLockWindowTitle + : undefined), }; const closeFocusedWindow = (_menuItem, browserWindow) => { // Block native Close while app lock is visible so popups/sessions are not diff --git a/electron/bridges/windowManagerReadiness.test.cjs b/electron/bridges/windowManagerReadiness.test.cjs index 2e06b2974..3ebc81a78 100644 --- a/electron/bridges/windowManagerReadiness.test.cjs +++ b/electron/bridges/windowManagerReadiness.test.cjs @@ -2118,6 +2118,7 @@ test("window IPC handlers target the sender owner window", async () => { }; const calls = []; const titles = []; + const guardedTitles = []; const win = { isDestroyed() { return false; @@ -2166,6 +2167,17 @@ test("window IPC handlers target the sender owner window", async () => { }, }; + buildAppMenu({ + buildFromTemplate(template) { + return { template }; + }, + }, { name: "Netcatty" }, false, "en", { + setAppLockWindowTitle(target, title) { + guardedTitles.push([target, title]); + target.setTitle(title); + return true; + }, + }); registerWindowHandlers(ipcMain, { themeSource: "light" }); const result = await handlers.get("netcatty:window:focus")({ @@ -2190,6 +2202,7 @@ test("window IPC handlers target the sender owner window", async () => { assert.equal(titleResult, true); assert.deepEqual(titles, ["Prod SSH"]); + assert.deepEqual(guardedTitles, [[win, "Prod SSH"]]); const opacityCalls = []; registerMainWindow({ diff --git a/electron/bridges/windowsHelloHelper/NetcattyWindowsHello.cpp b/electron/bridges/windowsHelloHelper/NetcattyWindowsHello.cpp index 2d6b022a0..236594bbe 100644 --- a/electron/bridges/windowsHelloHelper/NetcattyWindowsHello.cpp +++ b/electron/bridges/windowsHelloHelper/NetcattyWindowsHello.cpp @@ -90,7 +90,7 @@ int wmain(int argc, wchar_t* argv[]) { } try { - winrt::init_apartment(winrt::apartment_type::single_threaded); + winrt::init_apartment(winrt::apartment_type::multi_threaded); const std::wstring command = argv[1]; if (command == L"status") { diff --git a/electron/main.cjs b/electron/main.cjs index 8aa442261..f4805807f 100644 --- a/electron/main.cjs +++ b/electron/main.cjs @@ -1212,7 +1212,7 @@ if (!gotLock) { platform: process.platform, systemPreferences: electronModule.systemPreferences, execFile, - helperPath: resolveDefaultHelperPath(), + helperPath: resolveDefaultHelperPath({ isPackaged: app.isPackaged }), getNativeWindowHandle: getAppLockNativeWindowHandle, }); appLockController = createAppLockController({ @@ -1329,6 +1329,7 @@ if (!gotLock) { try { const menu = getWindowManager().buildAppMenu(Menu, app, isMac, undefined, { isAppLocked: () => Boolean(appLockRuntimeBridge?.getState?.()?.locked), + setAppLockWindowTitle: (win, title) => appLockController?.setWindowTitle?.(win, title), }); Menu.setApplicationMenu(menu); } catch (err) { @@ -1340,6 +1341,7 @@ if (!gotLock) { app.on("browser-window-created", (_event, win) => { try { + appLockController?.protectWindow?.(win); const windowManager = getWindowManager(); const mainWin = windowManager.getMainWindow(); const settingsWin = windowManager.getSettingsWindow(); diff --git a/electron/main/registerBridges.appLock.test.cjs b/electron/main/registerBridges.appLock.test.cjs new file mode 100644 index 000000000..220dd9a97 --- /dev/null +++ b/electron/main/registerBridges.appLock.test.cjs @@ -0,0 +1,45 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + createCloudSyncSessionPasswordReader, +} = require("./registerBridges.cjs"); + +test("cloud sync session password is hidden while the app is locked", async () => { + let persistedReads = 0; + const readPassword = createCloudSyncSessionPasswordReader({ + getAppLockController: () => ({ + getRuntimeState: () => ({ locked: true }), + }), + getCachedPassword: () => "cached-secret", + setCachedPassword: () => { + throw new Error("locked reads must not update the cache"); + }, + readPersistedPassword: () => { + persistedReads += 1; + return "persisted-secret"; + }, + }); + + assert.equal(await readPassword(), null); + assert.equal(persistedReads, 0); +}); + +test("cloud sync session password remains available after unlock", async () => { + let cachedPassword = null; + const readPassword = createCloudSyncSessionPasswordReader({ + getAppLockController: () => ({ + getRuntimeState: () => ({ locked: false }), + }), + getCachedPassword: () => cachedPassword, + setCachedPassword: (password) => { + cachedPassword = password; + }, + readPersistedPassword: () => "persisted-secret", + }); + + assert.equal(await readPassword(), "persisted-secret"); + assert.equal(cachedPassword, "persisted-secret"); +}); diff --git a/electron/main/registerBridges.cjs b/electron/main/registerBridges.cjs index 2d6ac7716..e4aed5456 100644 --- a/electron/main/registerBridges.cjs +++ b/electron/main/registerBridges.cjs @@ -43,6 +43,25 @@ function waitForApplicationSpawn(child, requireCleanLauncherExit = false) { }); } +function createCloudSyncSessionPasswordReader({ + getAppLockController, + getCachedPassword, + setCachedPassword, + readPersistedPassword, +}) { + return async function readCloudSyncSessionPassword() { + const controller = getAppLockController?.(); + if (controller?.getRuntimeState?.()?.locked === true) { + return null; + } + const cached = getCachedPassword(); + if (cached) return cached; + const persisted = readPersistedPassword(); + setCachedPassword(persisted); + return persisted; + }; +} + function createBridgeRegistrar(context) { const { electronModule, @@ -691,10 +710,15 @@ function createBridgeRegistrar(context) { registerAsMainWindow: false, onRegisterBridge: registerBridges, }); - try { - win.setTitle(title); - } catch { - // ignore + const appLockController = getAppLockController?.(); + if (typeof appLockController?.setWindowTitle === "function") { + appLockController.setWindowTitle(win, title); + } else { + try { + win.setTitle(title); + } catch { + // ignore + } } const delivery = await getWindowManager().sendWhenRendererReady( win, @@ -771,12 +795,14 @@ function createBridgeRegistrar(context) { return true; }); - ipcMain.handle("netcatty:cloudSync:session:getPassword", async () => { - if (cloudSyncSessionPassword) return cloudSyncSessionPassword; - const persisted = readPersistedCloudSyncPassword(); - cloudSyncSessionPassword = persisted; - return persisted; - }); + ipcMain.handle("netcatty:cloudSync:session:getPassword", createCloudSyncSessionPasswordReader({ + getAppLockController, + getCachedPassword: () => cloudSyncSessionPassword, + setCachedPassword: (password) => { + cloudSyncSessionPassword = password; + }, + readPersistedPassword: readPersistedCloudSyncPassword, + })); ipcMain.handle("netcatty:cloudSync:session:clearPassword", async () => { cloudSyncSessionPassword = null; @@ -1152,6 +1178,7 @@ function createBridgeRegistrar(context) { } module.exports = { + createCloudSyncSessionPasswordReader, createBridgeRegistrar, filterExcludedFigSpecs, isExcludedFigSpec, diff --git a/index.tsx b/index.tsx index 8d986d6aa..cfe5d6641 100755 --- a/index.tsx +++ b/index.tsx @@ -215,7 +215,7 @@ const renderApp = () => { locked; defer starting the terminal until unlock (Codex P2). */} )} diff --git a/infrastructure/config/storageKeys.ts b/infrastructure/config/storageKeys.ts index c8d4a5c17..91cc437c7 100644 --- a/infrastructure/config/storageKeys.ts +++ b/infrastructure/config/storageKeys.ts @@ -29,7 +29,6 @@ export const STORAGE_KEY_CUSTOM_KEY_BINDINGS = 'netcatty_custom_key_bindings_v1' export const STORAGE_KEY_HOTKEY_RECORDING = 'netcatty_hotkey_recording_v1'; export const STORAGE_KEY_CUSTOM_CSS = 'netcatty_custom_css_v1'; export const STORAGE_KEY_UI_LANGUAGE = 'netcatty_ui_language_v1'; -export const STORAGE_KEY_APP_LOCK_SETTINGS = 'netcatty_app_lock_settings_v1'; export const STORAGE_KEY_PORT_FORWARDING = 'netcatty_port_forwarding_v1'; /** Width (px) shared by port forwarding edit, wizard, and host picker panels. */ export const STORAGE_KEY_PORT_FORWARDING_PANEL_WIDTH = 'netcatty_port_forwarding_panel_width_v1'; diff --git a/scripts/electron-builder-config.test.cjs b/scripts/electron-builder-config.test.cjs index 712ea9e27..869d18777 100644 --- a/scripts/electron-builder-config.test.cjs +++ b/scripts/electron-builder-config.test.cjs @@ -108,6 +108,10 @@ test("Windows packaging includes the Windows Hello helper executable", () => { )), "Windows package must include the Windows Hello helper executable for the target arch", ); + assert.ok( + config.files.includes("!electron/bridges/windowsHelloHelper/build/**/*"), + "Windows Hello build output must not also be copied into app.asar", + ); }); test("Windows package arch is controlled by pack script CLI flags", () => {