From 4dcb06d39b0de4d57df8cf762c539e4da76703e8 Mon Sep 17 00:00:00 2001 From: Zheng Liu Date: Wed, 24 Jun 2026 14:17:47 +0800 Subject: [PATCH] feat: add app lock system auth bridge --- electron/bridges/appLockSystemAuthBridge.cjs | 171 ++++++++++++++++++ .../bridges/appLockSystemAuthBridge.test.cjs | 131 ++++++++++++++ .../appLockWindowsHelloHelper.test.cjs | 31 ++++ .../NetcattyWindowsHello.cpp | 141 +++++++++++++-- scripts/build-windows-hello-helper.cjs | 1 + 5 files changed, 459 insertions(+), 16 deletions(-) create mode 100644 electron/bridges/appLockSystemAuthBridge.cjs create mode 100644 electron/bridges/appLockSystemAuthBridge.test.cjs create mode 100644 electron/bridges/appLockWindowsHelloHelper.test.cjs diff --git a/electron/bridges/appLockSystemAuthBridge.cjs b/electron/bridges/appLockSystemAuthBridge.cjs new file mode 100644 index 000000000..56b62765b --- /dev/null +++ b/electron/bridges/appLockSystemAuthBridge.cjs @@ -0,0 +1,171 @@ +const path = require("node:path"); +const { execFile: defaultExecFile } = require("node:child_process"); + +const SYSTEM_AUTH_TIMEOUT_MS = 15000; +const UNAVAILABLE_ERRORS = new Set([ + "DeviceNotPresent", + "NotConfiguredForUser", + "DisabledByPolicy", + "DeviceBusy", + "unavailable", +]); +const CANCELLED_ERRORS = new Set([ + "Canceled", + "cancelled", + "RetriesExhausted", +]); + +function unsupportedStatus() { + return { + supported: false, + available: false, + platform: "unsupported", + label: null, + reason: null, + }; +} + +function normalizeSystemAuthStatus(input, platform = "unsupported") { + if (!input || typeof input !== "object") return unsupportedStatus(); + const normalizedPlatform = platform === "darwin" || platform === "win32" ? platform : "unsupported"; + if (normalizedPlatform === "unsupported") return unsupportedStatus(); + return { + supported: input.supported === true, + available: input.available === true, + platform: normalizedPlatform, + label: normalizedPlatform === "darwin" ? "Touch ID" : "Windows Hello", + reason: typeof input.reason === "string" && input.reason ? input.reason : null, + }; +} + +function normalizeSystemAuthUnlockResult(input) { + if (input && typeof input === "object" && input.ok === true) { + return { ok: true }; + } + const error = input && typeof input === "object" ? input.error : null; + if (typeof error === "string") { + if (CANCELLED_ERRORS.has(error)) return { ok: false, error: "cancelled" }; + if (UNAVAILABLE_ERRORS.has(error)) return { ok: false, error: "unavailable" }; + if (error === "unsupported") return { ok: false, error: "unsupported" }; + if (error === "failed") return { ok: false, error: "failed" }; + } + return { ok: false, error: "failed" }; +} + +function parseHelperJson(stdout) { + try { + return JSON.parse(String(stdout || "").trim()); + } catch { + return null; + } +} + +function nativeWindowHandleToDecimal(handle) { + if (!Buffer.isBuffer(handle) || handle.length === 0) return null; + let value = 0n; + const byteCount = Math.min(handle.length, 8); + for (let index = byteCount - 1; index >= 0; index -= 1) { + value = (value << 8n) + BigInt(handle[index]); + } + return value > 0n ? value.toString(10) : null; +} + +function runHelper(execFile, helperPath, args) { + return new Promise((resolve) => { + if (!helperPath) { + resolve({ ok: false, error: "unavailable" }); + return; + } + execFile(helperPath, args, { + encoding: "utf8", + timeout: SYSTEM_AUTH_TIMEOUT_MS, + windowsHide: true, + maxBuffer: 1024 * 1024, + }, (error, stdout) => { + if (error) { + resolve({ ok: false, error: "failed" }); + return; + } + resolve(parseHelperJson(stdout)); + }); + }); +} + +function resolveDefaultHelperPath() { + if (process.platform !== "win32") return null; + if (process.resourcesPath) { + return path.join(process.resourcesPath, "windowsHello", "NetcattyWindowsHello.exe"); + } + return path.join(__dirname, "windowsHelloHelper", "build", "NetcattyWindowsHello.exe"); +} + +function createAppLockSystemAuthBridge({ + platform = process.platform, + systemPreferences = null, + execFile = defaultExecFile, + helperPath = resolveDefaultHelperPath(), + getNativeWindowHandle = () => null, +} = {}) { + async function getMacStatus() { + const canPrompt = typeof systemPreferences?.canPromptTouchID === "function" + ? systemPreferences.canPromptTouchID() + : false; + return normalizeSystemAuthStatus({ + supported: true, + available: canPrompt === true, + reason: canPrompt === true ? null : "unavailable", + }, "darwin"); + } + + async function requestMacUnlock() { + if (typeof systemPreferences?.promptTouchID !== "function") { + return { ok: false, error: "unavailable" }; + } + try { + 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" }; + } + } + + async function getWindowsStatus() { + const result = await runHelper(execFile, helperPath, ["status"]); + return normalizeSystemAuthStatus({ + supported: true, + available: result?.available === true, + reason: typeof result?.reason === "string" ? result.reason : null, + }, "win32"); + } + + 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"]); + return normalizeSystemAuthUnlockResult(result); + } + + return { + async getStatus() { + if (platform === "darwin") return getMacStatus(); + if (platform === "win32") return getWindowsStatus(); + return unsupportedStatus(); + }, + async requestUnlock() { + if (platform === "darwin") return requestMacUnlock(); + if (platform === "win32") return requestWindowsUnlock(); + return { ok: false, error: "unsupported" }; + }, + }; +} + +module.exports = { + createAppLockSystemAuthBridge, + nativeWindowHandleToDecimal, + normalizeSystemAuthStatus, + normalizeSystemAuthUnlockResult, + resolveDefaultHelperPath, +}; diff --git a/electron/bridges/appLockSystemAuthBridge.test.cjs b/electron/bridges/appLockSystemAuthBridge.test.cjs new file mode 100644 index 000000000..402748de4 --- /dev/null +++ b/electron/bridges/appLockSystemAuthBridge.test.cjs @@ -0,0 +1,131 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + createAppLockSystemAuthBridge, + normalizeSystemAuthStatus, + normalizeSystemAuthUnlockResult, +} = require("./appLockSystemAuthBridge.cjs"); + +test("normalizes unsupported status", () => { + assert.deepEqual(normalizeSystemAuthStatus(null), { + supported: false, + available: false, + platform: "unsupported", + label: null, + reason: null, + }); +}); + +test("macOS status and unlock use Touch ID systemPreferences", async () => { + let promptReason = null; + const bridge = createAppLockSystemAuthBridge({ + platform: "darwin", + systemPreferences: { + canPromptTouchID: () => true, + promptTouchID: async (reason) => { + promptReason = reason; + }, + }, + }); + + assert.deepEqual(await bridge.getStatus(), { + supported: true, + available: true, + platform: "darwin", + label: "Touch ID", + reason: null, + }); + assert.deepEqual(await bridge.requestUnlock(), { ok: true }); + assert.equal(promptReason, "Unlock Netcatty"); +}); + +test("macOS cancellation maps to cancelled", async () => { + const bridge = createAppLockSystemAuthBridge({ + platform: "darwin", + systemPreferences: { + canPromptTouchID: () => true, + promptTouchID: async () => { + throw new Error("User canceled"); + }, + }, + }); + + assert.deepEqual(await bridge.requestUnlock(), { ok: false, error: "cancelled" }); +}); + +test("Windows status and unlock call helper with HWND", async () => { + const calls = []; + const bridge = createAppLockSystemAuthBridge({ + platform: "win32", + helperPath: "C:\\NetcattyWindowsHello.exe", + getNativeWindowHandle: () => Buffer.from("8877665544332211", "hex"), + execFile: (file, args, options, callback) => { + calls.push({ file, args, options }); + const command = args[0]; + const stdout = command === "status" + ? '{"supported":true,"available":true,"reason":null}' + : '{"ok":true}'; + callback(null, stdout, ""); + }, + }); + + assert.deepEqual(await bridge.getStatus(), { + supported: true, + available: true, + platform: "win32", + label: "Windows Hello", + reason: null, + }); + assert.deepEqual(await bridge.requestUnlock(), { ok: true }); + assert.equal(calls[0].file, "C:\\NetcattyWindowsHello.exe"); + assert.deepEqual(calls[0].args, ["status"]); + 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"]); +}); + +test("Windows helper maps unavailable and cancelled states", async () => { + const bridge = createAppLockSystemAuthBridge({ + platform: "win32", + helperPath: "helper.exe", + getNativeWindowHandle: () => Buffer.from("0100000000000000", "hex"), + execFile: (_file, args, _options, callback) => { + const stdout = args[0] === "status" + ? '{"supported":true,"available":false,"reason":"DisabledByPolicy"}' + : '{"ok":false,"error":"RetriesExhausted"}'; + callback(null, stdout, ""); + }, + }); + + assert.deepEqual(await bridge.getStatus(), { + supported: true, + available: false, + platform: "win32", + label: "Windows Hello", + reason: "DisabledByPolicy", + }); + assert.deepEqual(await bridge.requestUnlock(), { ok: false, error: "cancelled" }); +}); + +test("Windows helper failure maps to failed", async () => { + const bridge = createAppLockSystemAuthBridge({ + platform: "win32", + helperPath: "helper.exe", + getNativeWindowHandle: () => Buffer.from("0100000000000000", "hex"), + execFile: (_file, _args, _options, callback) => { + callback(new Error("boom"), "", "boom"); + }, + }); + + assert.deepEqual(await bridge.requestUnlock(), { ok: false, error: "failed" }); +}); + +test("normalizes Windows helper result enums", () => { + assert.deepEqual(normalizeSystemAuthUnlockResult({ ok: true }), { ok: true }); + assert.deepEqual(normalizeSystemAuthUnlockResult({ ok: false, error: "Canceled" }), { ok: false, error: "cancelled" }); + assert.deepEqual(normalizeSystemAuthUnlockResult({ ok: false, error: "RetriesExhausted" }), { ok: false, error: "cancelled" }); + assert.deepEqual(normalizeSystemAuthUnlockResult({ ok: false, error: "DeviceBusy" }), { ok: false, error: "unavailable" }); + assert.deepEqual(normalizeSystemAuthUnlockResult({ ok: false, error: "NotConfiguredForUser" }), { ok: false, error: "unavailable" }); + assert.deepEqual(normalizeSystemAuthUnlockResult({ ok: false, error: "unexpected" }), { ok: false, error: "failed" }); +}); diff --git a/electron/bridges/appLockWindowsHelloHelper.test.cjs b/electron/bridges/appLockWindowsHelloHelper.test.cjs new file mode 100644 index 000000000..f400fe651 --- /dev/null +++ b/electron/bridges/appLockWindowsHelloHelper.test.cjs @@ -0,0 +1,31 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); + +const helperSource = fs.readFileSync( + path.join(__dirname, "windowsHelloHelper", "NetcattyWindowsHello.cpp"), + "utf8", +); + +test("Windows Hello helper uses desktop HWND interop", () => { + assert.match(helperSource, /IUserConsentVerifierInterop/); + assert.match(helperSource, /RequestVerificationForWindowAsync/); + assert.match(helperSource, /--hwnd/); + assert.doesNotMatch(helperSource, /UserConsentVerifier::RequestVerificationAsync/); +}); + +test("Windows Hello helper maps all expected verifier states", () => { + for (const state of [ + "Available", + "DeviceNotPresent", + "NotConfiguredForUser", + "DisabledByPolicy", + "DeviceBusy", + "RetriesExhausted", + "Canceled", + "Verified", + ]) { + assert.match(helperSource, new RegExp(state)); + } +}); diff --git a/electron/bridges/windowsHelloHelper/NetcattyWindowsHello.cpp b/electron/bridges/windowsHelloHelper/NetcattyWindowsHello.cpp index 5774cc4fd..2d6b022a0 100644 --- a/electron/bridges/windowsHelloHelper/NetcattyWindowsHello.cpp +++ b/electron/bridges/windowsHelloHelper/NetcattyWindowsHello.cpp @@ -6,28 +6,137 @@ #include #include -// This helper is intentionally small: Netcatty's Electron main process owns -// policy; the helper only invokes the desktop HWND-bound Windows Hello API. +#include +#include +#include + +using winrt::Windows::Security::Credentials::UI::UserConsentVerificationResult; +using winrt::Windows::Security::Credentials::UI::UserConsentVerifier; +using winrt::Windows::Security::Credentials::UI::UserConsentVerifierAvailability; + +struct __declspec(uuid("39E050C3-4E74-441A-8DC0-B81104DF949C")) IUserConsentVerifierInterop : IInspectable { + virtual HRESULT __stdcall RequestVerificationForWindowAsync( + HWND appWindow, + HSTRING message, + REFIID riid, + void** asyncOperation) = 0; +}; + +std::wstring jsonEscape(const std::wstring& value) { + std::wstring escaped; + for (wchar_t ch : value) { + if (ch == L'\\' || ch == L'"') { + escaped.push_back(L'\\'); + escaped.push_back(ch); + } else if (ch == L'\n') { + escaped += L"\\n"; + } else if (ch == L'\r') { + escaped += L"\\r"; + } else { + escaped.push_back(ch); + } + } + return escaped; +} + +const wchar_t* availabilityName(UserConsentVerifierAvailability value) { + switch (value) { + case UserConsentVerifierAvailability::Available: return L"Available"; + case UserConsentVerifierAvailability::DeviceNotPresent: return L"DeviceNotPresent"; + case UserConsentVerifierAvailability::NotConfiguredForUser: return L"NotConfiguredForUser"; + case UserConsentVerifierAvailability::DisabledByPolicy: return L"DisabledByPolicy"; + case UserConsentVerifierAvailability::DeviceBusy: return L"DeviceBusy"; + default: return L"Unknown"; + } +} + +const wchar_t* verificationName(UserConsentVerificationResult value) { + switch (value) { + case UserConsentVerificationResult::Verified: return L"Verified"; + case UserConsentVerificationResult::DeviceNotPresent: return L"DeviceNotPresent"; + case UserConsentVerificationResult::NotConfiguredForUser: return L"NotConfiguredForUser"; + case UserConsentVerificationResult::DisabledByPolicy: return L"DisabledByPolicy"; + case UserConsentVerificationResult::DeviceBusy: return L"DeviceBusy"; + case UserConsentVerificationResult::RetriesExhausted: return L"RetriesExhausted"; + case UserConsentVerificationResult::Canceled: return L"Canceled"; + default: return L"Unknown"; + } +} + +void printError(const std::wstring& error) { + std::wcout << L"{\"ok\":false,\"error\":\"" << jsonEscape(error) << L"\"}\n"; +} + +HWND parseHwnd(const std::wstring& value) { + try { + unsigned long long raw = std::stoull(value, nullptr, 10); + return reinterpret_cast(static_cast(raw)); + } catch (...) { + return nullptr; + } +} + +std::wstring argValue(int argc, wchar_t* argv[], const std::wstring& name) { + for (int index = 2; index + 1 < argc; index += 1) { + if (std::wstring(argv[index]) == name) return argv[index + 1]; + } + return L""; +} int wmain(int argc, wchar_t* argv[]) { if (argc < 2) { - std::wcout << L"{\"ok\":false,\"error\":\"missing-command\"}\n"; + printError(L"missing-command"); return 1; } - const std::wstring command = argv[1]; - if (command == L"status") { - // Placeholder implementation for the packaging batch. The bridge batch - // replaces this with the WinRT UserConsentVerifier implementation. - std::wcout << L"{\"supported\":true,\"available\":false,\"reason\":\"helper-not-built\"}\n"; - return 0; - } + try { + winrt::init_apartment(winrt::apartment_type::single_threaded); + const std::wstring command = argv[1]; - if (command == L"verify") { - std::wcout << L"{\"ok\":false,\"error\":\"unavailable\"}\n"; - return 0; - } + if (command == L"status") { + const auto availability = UserConsentVerifier::CheckAvailabilityAsync().get(); + std::wcout + << L"{\"supported\":true,\"available\":" + << (availability == UserConsentVerifierAvailability::Available ? L"true" : L"false") + << L",\"reason\":\"" << availabilityName(availability) << L"\"}\n"; + return 0; + } - std::wcout << L"{\"ok\":false,\"error\":\"unknown-command\"}\n"; - return 1; + if (command == L"verify") { + const HWND hwnd = parseHwnd(argValue(argc, argv, L"--hwnd")); + const std::wstring message = argValue(argc, argv, L"--message").empty() + ? L"Unlock Netcatty" + : argValue(argc, argv, L"--message"); + if (!hwnd) { + printError(L"DeviceNotPresent"); + return 0; + } + + auto interop = winrt::get_activation_factory(); + winrt::Windows::Foundation::IAsyncOperation operation{ nullptr }; + winrt::hstring hMessage(message); + winrt::check_hresult(interop->RequestVerificationForWindowAsync( + hwnd, + static_cast(winrt::get_abi(hMessage)), + winrt::guid_of>(), + winrt::put_abi(operation))); + + const auto result = operation.get(); + if (result == UserConsentVerificationResult::Verified) { + std::wcout << L"{\"ok\":true}\n"; + } else { + std::wcout << L"{\"ok\":false,\"error\":\"" << verificationName(result) << L"\"}\n"; + } + return 0; + } + + printError(L"unknown-command"); + return 1; + } catch (const winrt::hresult_error& err) { + printError(err.message().c_str()); + return 1; + } catch (const std::exception& err) { + std::wcout << L"{\"ok\":false,\"error\":\"" << jsonEscape(winrt::to_hstring(err.what()).c_str()) << L"\"}\n"; + return 1; + } } diff --git a/scripts/build-windows-hello-helper.cjs b/scripts/build-windows-hello-helper.cjs index b08c560fa..dd1df4f08 100644 --- a/scripts/build-windows-hello-helper.cjs +++ b/scripts/build-windows-hello-helper.cjs @@ -31,6 +31,7 @@ function buildWindowsHelloHelper({ sourcePath, "/Fe:" + outputPath, "runtimeobject.lib", + "windowsapp.lib", ], { cwd: projectDir, stdio: "inherit",