diff --git a/electron/bridges/fidoPromptHandler.cjs b/electron/bridges/fidoPromptHandler.cjs index ffcaf05ff..46f28386d 100644 --- a/electron/bridges/fidoPromptHandler.cjs +++ b/electron/bridges/fidoPromptHandler.cjs @@ -5,59 +5,24 @@ * Mirrors passphraseHandler: main requests → renderer modal → respond IPC. */ -const { randomUUID } = require("node:crypto"); - -/** @type {Map void, - * sender: Electron.WebContents, - * webContentsId: number, - * kind: string, - * leaseId: string, - * createdAt: number, - * timeoutId: NodeJS.Timeout, - * }>} */ -const fidoPromptRequests = new Map(); +const { createIpcPromptRegistry } = require("./ipcPromptRegistry.cjs"); const REQUEST_TTL_MS = 3 * 60 * 1000; +const registry = createIpcPromptRegistry({ + prefix: "fido", + ttlMs: REQUEST_TTL_MS, + cancelChannel: "netcatty:fido-prompt-cancelled", + logTag: "[FidoPrompt]", + notifyBeforeResolve: true, +}); + function generateRequestId(prefix = "fido") { - return `${prefix}-${randomUUID()}`; -} - -function settleRequest(requestId, result, notification) { - const pending = fidoPromptRequests.get(requestId); - if (!pending) return false; - - if (pending.timeoutId) clearTimeout(pending.timeoutId); - pending.abortCleanup?.(); - fidoPromptRequests.delete(requestId); - - if (notification) { - try { - if (!pending.sender?.isDestroyed?.()) { - pending.sender?.send?.(notification.channel, { - requestId, - ...(notification.payload || {}), - }); - } - } catch (err) { - console.warn(`[FidoPrompt] Failed to send ${notification.channel}:`, err.message); - } - } - - pending.resolveCallback(result); - return true; + return registry.generateRequestId(prefix); } function cancelFidoPromptRequest(requestId, reason = "cancelled") { - return settleRequest( - requestId, - { cancelled: true }, - { - channel: "netcatty:fido-prompt-cancelled", - payload: { reason }, - }, - ); + return registry.cancel(requestId, reason, { cancelled: true }); } /** @@ -68,13 +33,11 @@ function cancelFidoPromptRequest(requestId, reason = "cancelled") { */ function cancelFidoPromptRequestsForLease(leaseId, reason = "lease-released", notificationsOnly = false) { if (typeof leaseId !== "string" || !leaseId) return 0; - let cancelled = 0; - for (const [requestId, pending] of [...fidoPromptRequests.entries()]) { - if (pending.leaseId !== leaseId) continue; - if (notificationsOnly && !pending.notificationOnly) continue; - if (cancelFidoPromptRequest(requestId, reason)) cancelled += 1; - } - return cancelled; + return registry.cancelWhere( + (pending) => pending.leaseId === leaseId && (!notificationsOnly || pending.notificationOnly), + reason, + { cancelled: true }, + ); } /** @@ -103,34 +66,33 @@ function requestFidoPrompt(sender, options = {}) { const kind = ["touch", "confirm", "recovery"].includes(options.kind) ? options.kind : "pin"; const leaseId = typeof options.leaseId === "string" ? options.leaseId : ""; const requestId = generateRequestId(kind); - const timeoutId = setTimeout(() => { - settleRequest( - requestId, - { cancelled: true }, - { channel: "netcatty:fido-prompt-timeout" }, - ); - }, REQUEST_TTL_MS); - fidoPromptRequests.set(requestId, { - resolveCallback: resolve, - sender, - webContentsId: sender.id, - kind, - leaseId, - notificationOnly: options.notificationOnly === true, - createdAt: Date.now(), - timeoutId, - }); + const { abortedImmediately } = registry.register( + requestId, + { + resolveCallback: resolve, + sender, + webContentsId: sender.id, + kind, + leaseId, + notificationOnly: options.notificationOnly === true, + }, + { + onTimeout: (id) => { + registry.settle( + id, + { cancelled: true }, + { channel: "netcatty:fido-prompt-timeout" }, + ); + }, + signal: options.signal, + onAbort: (id) => cancelFidoPromptRequest(id, "helper-exited"), + triggerIfAborted: true, + }, + ); - if (options.signal) { - const onAbort = () => cancelFidoPromptRequest(requestId, "helper-exited"); - const pending = fidoPromptRequests.get(requestId); - pending.abortCleanup = () => options.signal.removeEventListener("abort", onAbort); - options.signal.addEventListener("abort", onAbort, { once: true }); - if (options.signal.aborted) { - onAbort(); - return; - } + if (abortedImmediately) { + return; } try { @@ -146,24 +108,21 @@ function requestFidoPrompt(sender, options = {}) { }); } catch (err) { console.error("[FidoPrompt] Failed to send request:", err); - settleRequest(requestId, null); + registry.settle(requestId, null); } }); } function handleResponse(_event, payload = {}) { const { requestId, response, cancelled } = payload; - const pending = fidoPromptRequests.get(requestId); - if (!pending) { - return { success: false, error: "Request not found" }; - } - if (_event?.sender?.id !== pending.webContentsId) { - return { success: false, error: "Wrong sender" }; + const verification = registry.verifySender(_event, requestId); + if (!verification.ok) { + return { success: false, error: verification.error }; } if (cancelled) { - settleRequest(requestId, { cancelled: true }); + registry.settle(requestId, { cancelled: true }); } else { - settleRequest(requestId, { response: typeof response === "string" ? response : "" }); + registry.settle(requestId, { response: typeof response === "string" ? response : "" }); } return { success: true }; } @@ -173,7 +132,7 @@ function registerHandler(ipcMain) { } function getRequests() { - return fidoPromptRequests; + return registry.getMap(); } /** diff --git a/electron/bridges/ipcPromptRegistry.cjs b/electron/bridges/ipcPromptRegistry.cjs new file mode 100644 index 000000000..6d89ffa1d --- /dev/null +++ b/electron/bridges/ipcPromptRegistry.cjs @@ -0,0 +1,179 @@ +"use strict"; + +const { randomUUID } = require("node:crypto"); + +/** + * Shared pending-request lifecycle registry for interactive SSH IPC prompts + * (FIDO2 PIN/touch, encrypted key passphrases, keyboard-interactive auth). + * + * Each prompt handler keeps its own IPC channel names, payload schema, and + * domain semantics (timeout result, pre-aborted signal behavior, resolve vs. + * notify ordering, and delivery-failure handling). + * + * @param {{ + * prefix: string, + * ttlMs: number, + * cancelChannel: string, + * logTag: string, + * notifyBeforeResolve?: boolean, + * buildCancelPayload?: (pending: object, requestId: string, reason: string) => object, + * }} config + */ +function createIpcPromptRegistry({ + prefix, + ttlMs, + cancelChannel, + logTag, + notifyBeforeResolve = true, + buildCancelPayload = (_pending, _requestId, reason) => ({ reason }), +}) { + const requests = new Map(); + + function generateRequestId(customPrefix = prefix) { + return `${customPrefix}-${randomUUID()}`; + } + + function sendNotification(pending, requestId, notification) { + if (!notification) return; + try { + if (!pending.sender?.isDestroyed?.()) { + pending.sender?.send?.(notification.channel, { + requestId, + ...(notification.payload || {}), + }); + } + } catch (err) { + console.warn(`${logTag} Failed to send ${notification.channel}:`, err.message); + } + } + + function removeEntry(requestId) { + const pending = requests.get(requestId); + if (!pending) return null; + + if (pending.timeoutId) { + clearTimeout(pending.timeoutId); + pending.timeoutId = null; + } + pending.abortCleanup?.(); + pending.abortCleanup = null; + requests.delete(requestId); + return pending; + } + + function register( + requestId, + entry, + { onTimeout, signal, onAbort, triggerIfAborted = false } = {}, + ) { + const timeoutId = setTimeout(() => { + if (!requests.has(requestId)) return; + onTimeout?.(requestId); + }, ttlMs); + + const record = { + ...entry, + createdAt: entry.createdAt ?? Date.now(), + timeoutId, + abortCleanup: null, + }; + requests.set(requestId, record); + + if (signal && typeof onAbort === "function") { + const abortHandler = () => onAbort(requestId); + record.abortCleanup = () => signal.removeEventListener("abort", abortHandler); + signal.addEventListener("abort", abortHandler, { once: true }); + if (triggerIfAborted && signal.aborted) { + abortHandler(); + return { record, abortedImmediately: true }; + } + } + + return { record, abortedImmediately: false }; + } + + function settle(requestId, result, notification, options = {}) { + const pending = removeEntry(requestId); + if (!pending) return false; + + const shouldNotifyFirst = options.notifyBeforeResolve ?? notifyBeforeResolve; + const invokeResolve = () => { + if (options.catchResolveError) { + try { + pending.resolveCallback(result); + } catch (err) { + console.warn( + `${logTag} ${options.resolveErrorMessage || `Failed to settle request ${requestId}:`}`, + err?.message, + ); + } + } else { + pending.resolveCallback(result); + } + }; + + if (shouldNotifyFirst) { + sendNotification(pending, requestId, notification); + invokeResolve(); + } else { + invokeResolve(); + sendNotification(pending, requestId, notification); + } + return true; + } + + function cancel(requestId, reason = "cancelled", result = { cancelled: true }, options = {}) { + const pending = requests.get(requestId); + if (!pending) return false; + return settle( + requestId, + result, + { + channel: cancelChannel, + payload: buildCancelPayload(pending, requestId, reason), + }, + options, + ); + } + + function cancelWhere(predicate, reason = "cancelled", result = { cancelled: true }, options = {}) { + let cancelled = 0; + for (const [requestId, pending] of [...requests.entries()]) { + if (!predicate(pending, requestId)) continue; + const didCancel = options.cancelEntry + ? options.cancelEntry(requestId, reason) + : cancel(requestId, reason, result, options); + if (didCancel) cancelled += 1; + } + return cancelled; + } + + function verifySender(event, requestId) { + const pending = requests.get(requestId); + if (!pending) { + return { ok: false, error: "Request not found" }; + } + if (event?.sender?.id !== pending.webContentsId) { + return { ok: false, error: "Wrong sender" }; + } + return { ok: true, pending }; + } + + function getMap() { + return requests; + } + + return { + generateRequestId, + register, + removeEntry, + sendNotification, + settle, + cancel, + cancelWhere, + verifySender, + getMap, + }; +} + +module.exports = { createIpcPromptRegistry }; diff --git a/electron/bridges/ipcPromptRegistry.test.cjs b/electron/bridges/ipcPromptRegistry.test.cjs new file mode 100644 index 000000000..e03c5e22d --- /dev/null +++ b/electron/bridges/ipcPromptRegistry.test.cjs @@ -0,0 +1,252 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { createIpcPromptRegistry } = require("./ipcPromptRegistry.cjs"); +const fidoPromptHandler = require("./fidoPromptHandler.cjs"); +const passphraseHandler = require("./passphraseHandler.cjs"); +const keyboardInteractiveHandler = require("./keyboardInteractiveHandler.cjs"); + +function withPatchedTimeouts(run) { + const originalSetTimeout = global.setTimeout; + const originalClearTimeout = global.clearTimeout; + let nextId = 1; + const timeouts = new Map(); + + global.setTimeout = (fn, delay, ...args) => { + const id = nextId++; + timeouts.set(id, { fn: () => fn(...args), delay }); + return id; + }; + global.clearTimeout = (id) => { + timeouts.delete(id); + }; + + return Promise.resolve() + .then(() => + run({ + getPendingTimeouts: () => [...timeouts.values()], + fireAllTimeouts: () => { + const items = [...timeouts.entries()]; + timeouts.clear(); + for (const [, item] of items) item.fn(); + }, + })) + .finally(() => { + global.setTimeout = originalSetTimeout; + global.clearTimeout = originalClearTimeout; + }); +} + +test("createIpcPromptRegistry enforces sender verification, ordering, TTL cleanup, and idempotent settlement", async () => { + await withPatchedTimeouts(({ getPendingTimeouts, fireAllTimeouts }) => { + const events = []; + const registry = createIpcPromptRegistry({ + prefix: "test", + ttlMs: 5000, + cancelChannel: "netcatty:test-cancelled", + logTag: "[TestPrompt]", + notifyBeforeResolve: true, + }); + + const id = registry.generateRequestId(); + assert.match(id, /^test-/); + + const sender = { + id: 7, + isDestroyed: () => false, + send: (channel, payload) => events.push({ kind: "send", channel, payload }), + }; + + registry.register( + id, + { + resolveCallback: (result) => events.push({ kind: "resolve", result }), + sender, + webContentsId: 7, + }, + { + onTimeout: (timedOutId) => registry.cancel(timedOutId, "timeout", { timedOut: true }), + }, + ); + + assert.equal(getPendingTimeouts().length, 1); + assert.equal(getPendingTimeouts()[0].delay, 5000); + assert.deepEqual(registry.verifySender({ sender: { id: 99 } }, id), { + ok: false, + error: "Wrong sender", + }); + assert.deepEqual(registry.verifySender({ sender: { id: 7 } }, "missing"), { + ok: false, + error: "Request not found", + }); + assert.equal(registry.verifySender({ sender: { id: 7 } }, id).ok, true); + + fireAllTimeouts(); + assert.equal(registry.getMap().size, 0); + assert.deepEqual(events, [ + { kind: "send", channel: "netcatty:test-cancelled", payload: { requestId: id, reason: "timeout" } }, + { kind: "resolve", result: { timedOut: true } }, + ]); + + // Settling again is a safe no-op. + assert.equal(registry.settle(id, { second: true }), false); + }); +}); + +test("handler timeout semantics stay distinct across FIDO, passphrase, and keyboard-interactive", async (t) => { + t.mock.method(console, "warn", () => {}); + t.mock.method(console, "log", () => {}); + + await withPatchedTimeouts(async ({ fireAllTimeouts }) => { + const fidoSent = []; + const fidoPromise = fidoPromptHandler.requestFidoPrompt( + { id: 1, isDestroyed: () => false, send: (ch, p) => fidoSent.push({ ch, p }) }, + { kind: "pin", message: "PIN" }, + ); + + const ppSent = []; + const ppPromise = passphraseHandler.requestPassphrase( + { id: 2, isDestroyed: () => false, send: (ch, p) => ppSent.push({ ch, p }) }, + "/tmp/id_ed25519", + "id_ed25519", + "host.example", + false, + ); + + const kiEvents = []; + const kiId = keyboardInteractiveHandler.generateRequestId(); + keyboardInteractiveHandler.storeRequest( + kiId, + (responses) => kiEvents.push({ kind: "finish", responses }), + 3, + "session-ki-timeout", + { + isDestroyed: () => false, + send: (ch, p) => kiEvents.push({ kind: "send", ch, p }), + }, + ); + + fireAllTimeouts(); + + // 1. FIDO resolves { cancelled: true } and sends fido-prompt-timeout. + assert.deepEqual(await fidoPromise, { cancelled: true }); + assert.ok(fidoSent.some((m) => m.ch === "netcatty:fido-prompt-timeout")); + + // 2. Passphrase resolves null and sends passphrase-timeout. + assert.equal(await ppPromise, null); + assert.ok(ppSent.some((m) => m.ch === "netcatty:passphrase-timeout")); + + // 3. Keyboard-interactive invokes finishCallback([]) STRICTLY BEFORE sending cancel IPC. + assert.deepEqual(kiEvents, [ + { kind: "finish", responses: [] }, + { + kind: "send", + ch: "netcatty:keyboard-interactive-cancelled", + p: { requestId: kiId, sessionId: "session-ki-timeout", reason: "timeout" }, + }, + ]); + }); +}); + +test("pre-aborted AbortSignal preserves differing cancel-IPC semantics between passphrase and FIDO", async (t) => { + t.mock.method(console, "log", () => {}); + + const abortedController = new AbortController(); + abortedController.abort(); + + // Passphrase resolves { cancelled: true } immediately WITHOUT sending cancel IPC. + const ppSent = []; + const ppResult = await passphraseHandler.requestPassphrase( + { id: 10, isDestroyed: () => false, send: (ch, p) => ppSent.push({ ch, p }) }, + "/tmp/id_rsa", + "id_rsa", + "host", + false, + { signal: abortedController.signal }, + ); + assert.deepEqual(ppResult, { cancelled: true }); + assert.deepEqual(ppSent, []); + assert.equal(passphraseHandler.getRequests().size, 0); + + // FIDO sends netcatty:fido-prompt-cancelled with reason "helper-exited" and resolves { cancelled: true }. + const fidoSent = []; + const fidoResult = await fidoPromptHandler.requestFidoPrompt( + { id: 11, isDestroyed: () => false, send: (ch, p) => fidoSent.push({ ch, p }) }, + { kind: "touch", signal: abortedController.signal }, + ); + assert.deepEqual(fidoResult, { cancelled: true }); + assert.equal(fidoSent.length, 1); + assert.equal(fidoSent[0].ch, "netcatty:fido-prompt-cancelled"); + assert.equal(fidoSent[0].p.reason, "helper-exited"); + assert.equal(fidoPromptHandler.getRequests().size, 0); +}); + +test("passphraseHandler respects bootEpoch scoping and skipped/cancelled/response settlement", async (t) => { + t.mock.method(console, "log", () => {}); + const sent = []; + const sender = { + id: 21, + isDestroyed: () => false, + send: (ch, p) => sent.push({ ch, p }), + }; + + const p1 = passphraseHandler.requestPassphrase(sender, "/k1", "k1", "h", false, { + sessionId: "sess-1", + bootEpoch: 2, + }); + const reqId1 = sent.at(-1).p.requestId; + + // Stale bootEpoch (1 < 2) must NOT cancel the newer prompt. + assert.equal(passphraseHandler.cancelPassphraseRequestsForSession("sess-1", "session-closed", 1), 0); + assert.equal(passphraseHandler.getRequests().has(reqId1), true); + + // Matching bootEpoch (2) cancels it. + assert.equal(passphraseHandler.cancelPassphraseRequestsForSession("sess-1", "session-closed", 2), 1); + assert.deepEqual(await p1, { cancelled: true }); + assert.equal(sent.at(-1).ch, "netcatty:passphrase-cancelled"); + assert.equal(sent.at(-1).p.reason, "session-closed"); + + // Skipped and passphrase responses settle cleanly. + const p2 = passphraseHandler.requestPassphrase(sender, "/k2", "k2", "h", false); + const reqId2 = sent.at(-1).p.requestId; + assert.deepEqual( + passphraseHandler.handleResponse({ sender: { id: 21 } }, { requestId: reqId2, skipped: true }), + { success: true }, + ); + assert.deepEqual(await p2, { skipped: true }); + + const p3 = passphraseHandler.requestPassphrase(sender, "/k3", "k3", "h", false); + const reqId3 = sent.at(-1).p.requestId; + assert.deepEqual( + passphraseHandler.handleResponse({ sender: { id: 21 } }, { requestId: reqId3, passphrase: "secret" }), + { success: true }, + ); + assert.deepEqual(await p3, { passphrase: "secret" }); +}); + +test("keyboardInteractiveHandler invokes finishCallback before notifying cancellation on session cancel", () => { + const order = []; + const requestId = keyboardInteractiveHandler.generateRequestId("order"); + keyboardInteractiveHandler.storeRequest( + requestId, + (responses) => order.push({ step: "finish", responses }), + 55, + "sess-order", + { + isDestroyed: () => false, + send: (ch, p) => order.push({ step: "notify", ch, p }), + }, + ); + + assert.equal(keyboardInteractiveHandler.cancelRequestsForSession("sess-order", "closed"), 1); + assert.deepEqual(order, [ + { step: "finish", responses: [] }, + { + step: "notify", + ch: "netcatty:keyboard-interactive-cancelled", + p: { requestId, sessionId: "sess-order", reason: "closed" }, + }, + ]); +}); diff --git a/electron/bridges/keyboardInteractiveHandler.cjs b/electron/bridges/keyboardInteractiveHandler.cjs index 2a4d2a25e..212e093ed 100644 --- a/electron/bridges/keyboardInteractiveHandler.cjs +++ b/electron/bridges/keyboardInteractiveHandler.cjs @@ -4,80 +4,84 @@ * used by SSH, SFTP, and Port Forwarding bridges. */ -// Keyboard-interactive authentication pending requests -// Map of requestId -> { finishCallback, webContentsId, sessionId, createdAt, timeoutId } -const { randomUUID } = require("node:crypto"); - -const keyboardInteractiveRequests = new Map(); +const { createIpcPromptRegistry } = require("./ipcPromptRegistry.cjs"); // TTL for abandoned requests (5 minutes) const REQUEST_TTL_MS = 5 * 60 * 1000; +const CANCEL_CHANNEL = "netcatty:keyboard-interactive-cancelled"; + +const registry = createIpcPromptRegistry({ + prefix: "ki", + ttlMs: REQUEST_TTL_MS, + cancelChannel: CANCEL_CHANNEL, + logTag: "[KeyboardInteractive]", + notifyBeforeResolve: false, + buildCancelPayload: (pending, _requestId, reason) => ({ + sessionId: pending.sessionId, + reason, + }), +}); /** * Generate a unique request ID for keyboard-interactive requests */ -function generateRequestId(prefix = 'ki') { - return `${prefix}-${randomUUID()}`; +function generateRequestId(prefix = "ki") { + return registry.generateRequestId(prefix); } /** * Store a keyboard-interactive request with TTL cleanup */ function storeRequest(requestId, finishCallback, webContentsId, sessionId, sender) { - // Set up TTL timeout to clean up abandoned requests - const timeoutId = setTimeout(() => { - const pending = keyboardInteractiveRequests.get(requestId); - if (pending) { - console.warn(`[KeyboardInteractive] Request ${requestId} timed out after ${REQUEST_TTL_MS / 1000}s, cleaning up`); - keyboardInteractiveRequests.delete(requestId); - // Call finish with empty responses to abort the authentication - try { - pending.finishCallback([]); - } catch (err) { - console.warn(`[KeyboardInteractive] Failed to call finishCallback for timed out request:`, err.message); - } - notifyCancellation(pending, requestId, "timeout"); - } - }, REQUEST_TTL_MS); - - keyboardInteractiveRequests.set(requestId, { - finishCallback, - webContentsId, - sessionId, - sender, - createdAt: Date.now(), - timeoutId, - }); + registry.register( + requestId, + { + finishCallback, + resolveCallback: finishCallback, + webContentsId, + sessionId, + sender, + }, + { + onTimeout: (id) => { + console.warn(`[KeyboardInteractive] Request ${id} timed out after ${REQUEST_TTL_MS / 1000}s, cleaning up`); + // Call finish with empty responses to abort the authentication before notifying renderer. + registry.cancel(id, "timeout", [], { + catchResolveError: true, + resolveErrorMessage: "Failed to call finishCallback for timed out request:", + }); + }, + }, + ); } /** * Handle keyboard-interactive authentication response from renderer */ function handleResponse(_event, payload) { - console.log(`[KeyboardInteractive] handleResponse called`, { + console.log("[KeyboardInteractive] handleResponse called", { requestId: payload?.requestId, cancelled: Boolean(payload?.cancelled), responsesCount: Array.isArray(payload?.responses) ? payload.responses.length : 0, }); const { requestId, responses, cancelled } = payload; - const pending = keyboardInteractiveRequests.get(requestId); + const requests = registry.getMap(); + const verification = registry.verifySender(_event, requestId); - console.log(`[KeyboardInteractive] Looking for request ${requestId}, found:`, !!pending); - console.log(`[KeyboardInteractive] Current pending requests:`, Array.from(keyboardInteractiveRequests.keys())); + console.log(`[KeyboardInteractive] Looking for request ${requestId}, found:`, requests.has(requestId)); + console.log("[KeyboardInteractive] Current pending requests:", Array.from(requests.keys())); - if (!pending) { - console.warn(`[KeyboardInteractive] No pending request for ${requestId}`); - return { success: false, error: 'Request not found' }; + if (!verification.ok) { + if (verification.error === "Request not found") { + console.warn(`[KeyboardInteractive] No pending request for ${requestId}`); + } else { + console.warn(`[KeyboardInteractive] Wrong sender for request ${requestId}`); + } + return { success: false, error: verification.error }; } - if (_event?.sender?.id !== pending.webContentsId) { - console.warn(`[KeyboardInteractive] Wrong sender for request ${requestId}`); - return { success: false, error: 'Wrong sender' }; - } - - if (pending.timeoutId) clearTimeout(pending.timeoutId); - keyboardInteractiveRequests.delete(requestId); + const pending = registry.removeEntry(requestId); try { if (cancelled) { @@ -89,7 +93,13 @@ function handleResponse(_event, payload) { } } catch (err) { console.warn(`[KeyboardInteractive] Failed to deliver response for ${requestId}:`, err?.message); - notifyCancellation(pending, requestId, "delivery-failed"); + registry.sendNotification(pending, requestId, { + channel: CANCEL_CHANNEL, + payload: { + sessionId: pending.sessionId, + reason: "delivery-failed", + }, + }); return { success: false, error: "Failed to deliver response" }; } @@ -99,44 +109,23 @@ function handleResponse(_event, payload) { /** * Cancel every pending request owned by a session or external operation. */ -function notifyCancellation(pending, requestId, reason) { - try { - if (!pending.sender?.isDestroyed?.()) { - pending.sender?.send?.("netcatty:keyboard-interactive-cancelled", { - requestId, - sessionId: pending.sessionId, - reason, - }); - } - } catch (err) { - console.warn(`[KeyboardInteractive] Failed to notify cancellation for ${requestId}:`, err.message); - } -} - function cancelRequestsForSession(sessionId, reason = "cancelled") { - let cancelled = 0; - for (const [requestId, pending] of keyboardInteractiveRequests) { - if (pending.sessionId !== sessionId) continue; - if (pending.timeoutId) { - clearTimeout(pending.timeoutId); - } - keyboardInteractiveRequests.delete(requestId); - try { - pending.finishCallback([]); - } catch (err) { - console.warn(`[KeyboardInteractive] Failed to cancel request ${requestId}:`, err.message); - } - notifyCancellation(pending, requestId, reason); - cancelled += 1; - } - return cancelled; + return registry.cancelWhere( + (pending) => pending.sessionId === sessionId, + reason, + [], + { + catchResolveError: true, + resolveErrorMessage: "Failed to cancel request:", + }, + ); } /** * Get the requests map (for debugging/testing) */ function getRequests() { - return keyboardInteractiveRequests; + return registry.getMap(); } /** diff --git a/electron/bridges/passphraseHandler.cjs b/electron/bridges/passphraseHandler.cjs index bbe7a8057..ab83bd49f 100644 --- a/electron/bridges/passphraseHandler.cjs +++ b/electron/bridges/passphraseHandler.cjs @@ -4,20 +4,54 @@ * when encountering encrypted default SSH keys in ~/.ssh */ -// Passphrase request pending map -// Map of requestId -> { resolveCallback, webContentsId, keyPath, createdAt, timeoutId, sender, signal, abortHandler } -const { randomUUID } = require("node:crypto"); - -const passphraseRequests = new Map(); +const { createIpcPromptRegistry } = require("./ipcPromptRegistry.cjs"); // TTL for abandoned requests (2 minutes) const REQUEST_TTL_MS = 2 * 60 * 1000; +const registry = createIpcPromptRegistry({ + prefix: "pp", + ttlMs: REQUEST_TTL_MS, + cancelChannel: "netcatty:passphrase-cancelled", + logTag: "[Passphrase]", + notifyBeforeResolve: true, +}); + /** * Generate a unique request ID for passphrase requests */ -function generateRequestId(prefix = 'pp') { - return `${prefix}-${randomUUID()}`; +function generateRequestId(prefix = "pp") { + return registry.generateRequestId(prefix); +} + +function cancelPassphraseRequest(requestId, reason = "cancelled") { + const cancelled = registry.cancel(requestId, reason, { cancelled: true }); + if (cancelled) { + console.log(`[Passphrase] Request ${requestId} cancelled by ${reason}`); + } + return cancelled; +} + +function cancelPassphraseRequestsForSession(sessionId, reason = "session-closed", bootEpoch) { + if (!sessionId) return 0; + const requestedEpoch = Number.isFinite(bootEpoch) ? Number(bootEpoch) : undefined; + return registry.cancelWhere( + (pending) => { + if (pending.sessionId !== sessionId) return false; + // A stale close for an older boot must not cancel a newer reconnect's prompt. + if ( + requestedEpoch !== undefined + && Number.isFinite(pending.bootEpoch) + && pending.bootEpoch > requestedEpoch + ) { + return false; + } + return true; + }, + reason, + { cancelled: true }, + { cancelEntry: cancelPassphraseRequest }, + ); } /** @@ -28,74 +62,10 @@ function generateRequestId(prefix = 'pp') { * @param {string} [hostname] - Optional hostname for context * @returns {Promise<{ passphrase?: string, cancelled?: boolean, skipped?: boolean } | null>} */ -function settleRequest(requestId, result, notification) { - const pending = passphraseRequests.get(requestId); - if (!pending) return false; - - if (pending.timeoutId) { - clearTimeout(pending.timeoutId); - } - if (pending.signal && pending.abortHandler) { - pending.signal.removeEventListener("abort", pending.abortHandler); - } - - passphraseRequests.delete(requestId); - - if (notification) { - try { - if (!pending.sender?.isDestroyed?.()) { - pending.sender?.send?.(notification.channel, { - requestId, - ...(notification.payload || {}), - }); - } - } catch (err) { - console.warn(`[Passphrase] Failed to send ${notification.channel} notification:`, err.message); - } - } - - pending.resolveCallback(result); - return true; -} - -function cancelPassphraseRequest(requestId, reason = "cancelled") { - const cancelled = settleRequest( - requestId, - { cancelled: true }, - { - channel: "netcatty:passphrase-cancelled", - payload: { reason }, - } - ); - if (cancelled) { - console.log(`[Passphrase] Request ${requestId} cancelled by ${reason}`); - } - return cancelled; -} - -function cancelPassphraseRequestsForSession(sessionId, reason = "session-closed", bootEpoch) { - if (!sessionId) return 0; - const requestedEpoch = Number.isFinite(bootEpoch) ? Number(bootEpoch) : undefined; - let cancelled = 0; - for (const [requestId, pending] of [...passphraseRequests.entries()]) { - if (pending.sessionId !== sessionId) continue; - // A stale close for an older boot must not cancel a newer reconnect's prompt. - if ( - requestedEpoch !== undefined - && Number.isFinite(pending.bootEpoch) - && pending.bootEpoch > requestedEpoch - ) { - continue; - } - if (cancelPassphraseRequest(requestId, reason)) cancelled += 1; - } - return cancelled; -} - function requestPassphrase(sender, keyPath, keyName, hostname, passphraseInvalid, options = {}) { return new Promise((resolve) => { if (!sender || sender.isDestroyed()) { - console.warn('[Passphrase] Sender is destroyed, cannot request passphrase'); + console.warn("[Passphrase] Sender is destroyed, cannot request passphrase"); resolve(null); return; } @@ -105,47 +75,35 @@ function requestPassphrase(sender, keyPath, keyName, hostname, passphraseInvalid resolve({ cancelled: true }); return; } - + const requestId = generateRequestId(); - - // Set up TTL timeout to clean up abandoned requests - const timeoutId = setTimeout(() => { - if (passphraseRequests.has(requestId)) { - console.warn(`[Passphrase] Request ${requestId} timed out after ${REQUEST_TTL_MS / 1000}s`); - settleRequest( - requestId, - null, - { channel: "netcatty:passphrase-timeout" } - ); - } - }, REQUEST_TTL_MS); - const abortHandler = () => { - cancelPassphraseRequest(requestId, "external-cancel"); - }; - - passphraseRequests.set(requestId, { - resolveCallback: resolve, - sender, - webContentsId: sender.id, - keyPath, - keyName, - sessionId: typeof options.sessionId === "string" ? options.sessionId : undefined, - bootEpoch: Number.isFinite(options.bootEpoch) ? Number(options.bootEpoch) : undefined, - createdAt: Date.now(), - timeoutId, - signal, - abortHandler: signal ? abortHandler : null, - }); + registry.register( + requestId, + { + resolveCallback: resolve, + sender, + webContentsId: sender.id, + keyPath, + keyName, + sessionId: typeof options.sessionId === "string" ? options.sessionId : undefined, + bootEpoch: Number.isFinite(options.bootEpoch) ? Number(options.bootEpoch) : undefined, + }, + { + onTimeout: (id) => { + console.warn(`[Passphrase] Request ${id} timed out after ${REQUEST_TTL_MS / 1000}s`); + registry.settle(id, null, { channel: "netcatty:passphrase-timeout" }); + }, + signal, + onAbort: (id) => cancelPassphraseRequest(id, "external-cancel"), + triggerIfAborted: false, + }, + ); - if (signal) { - signal.addEventListener("abort", abortHandler, { once: true }); - } - console.log(`[Passphrase] Requesting passphrase for ${keyName} (${requestId})`); - + try { - sender.send('netcatty:passphrase-request', { + sender.send("netcatty:passphrase-request", { requestId, keyPath, keyName, @@ -155,8 +113,8 @@ function requestPassphrase(sender, keyPath, keyName, hostname, passphraseInvalid ...(Number.isFinite(options.bootEpoch) ? { bootEpoch: Number(options.bootEpoch) } : {}), }); } catch (err) { - console.error('[Passphrase] Failed to send passphrase request:', err); - settleRequest(requestId, null); + console.error("[Passphrase] Failed to send passphrase request:", err); + registry.settle(requestId, null); } }); } @@ -166,31 +124,30 @@ function requestPassphrase(sender, keyPath, keyName, hostname, passphraseInvalid */ function handleResponse(_event, payload) { const { requestId, passphrase, cancelled, skipped } = payload; - const pending = passphraseRequests.get(requestId); - - if (!pending) { - console.warn(`[Passphrase] No pending request for ${requestId}`); - return { success: false, error: 'Request not found' }; + const verification = registry.verifySender(_event, requestId); + + if (!verification.ok) { + if (verification.error === "Request not found") { + console.warn(`[Passphrase] No pending request for ${requestId}`); + } else { + console.warn(`[Passphrase] Wrong sender for request ${requestId}`); + } + return { success: false, error: verification.error }; } - if (_event?.sender?.id !== pending.webContentsId) { - console.warn(`[Passphrase] Wrong sender for request ${requestId}`); - return { success: false, error: 'Wrong sender' }; - } - if (cancelled) { // User clicked Cancel - stop the entire passphrase flow console.log(`[Passphrase] Request ${requestId} cancelled by user`); - settleRequest(requestId, { cancelled: true }); + registry.settle(requestId, { cancelled: true }); } else if (skipped) { // User clicked Skip - skip this key but continue with others console.log(`[Passphrase] Request ${requestId} skipped by user`); - settleRequest(requestId, { skipped: true }); + registry.settle(requestId, { skipped: true }); } else { console.log(`[Passphrase] Received passphrase for ${requestId}`); - settleRequest(requestId, { passphrase: passphrase || null }); + registry.settle(requestId, { passphrase: passphrase || null }); } - + return { success: true }; } @@ -198,14 +155,14 @@ function handleResponse(_event, payload) { * Register IPC handler for passphrase responses */ function registerHandler(ipcMain) { - ipcMain.handle('netcatty:passphrase:respond', handleResponse); + ipcMain.handle("netcatty:passphrase:respond", handleResponse); } /** * Get pending requests (for debugging) */ function getRequests() { - return passphraseRequests; + return registry.getMap(); } module.exports = {