Files
Netcatty/domain/sshAuth.ts
T
陈大猫andnetcatty-bot 48f1a1cecf feat(ssh): restore FIDO2 security key support (#2823)
* feat(ssh): restore FIDO2 security key support (#2308)

Consolidate the restored feature and its review fixes before rebasing onto current main. Original PR head: 5d0a0c6c9a550364d3ec5c2331395cedfc9ea7ae.

* fix(ssh): verify and repair FIDO authentication with simulated hardware

Preserve complete OpenSSH SK signature payloads, classify combined PIN/presence prompts correctly, expand IdentityFile tokens, retain certificate selectors, and route shared-agent signing prompts to their originating window. Dismiss prompts when notification helpers exit. Add a software SK provider and opt-in real OpenSSH integration coverage for both algorithms, certificates, SFTP, forwarding, and concurrent windows.

* refactor(ui): refine security key forms and authentication motion

Use shared Select and Switch controls, concise localized copy and compact token-based dialogs. Add scoped enter/exit, field transition and presence animations with reduced-motion support. Preserve raw prompt details and visible PIN errors.

* fix(ssh): align security key prompts with hardware presence and verify Docker logins

* fix(ui): keep security key dialog above its remounted overlay

* fix: address Codex review on PR #2823

* feat(ssh): guide security key recovery and explicit authentication fallback

* test(ssh): exercise security key authentication on native Windows

* test(ssh): verify Windows fixture signatures and explicit fallback

* test(ssh): configure Windows OpenSSH toolchain and document coverage

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-10-17 21:53:44 +08:00

425 lines
13 KiB
TypeScript

import type { GroupConfig, Host, HostAuthMethod, Identity, SSHKey } from "./models";
import { sanitizeCredentialValue } from "./credentials";
import { applyGroupDefaults } from "./groupConfig";
import { isSshAgentNoneValue } from "./sshAgentSettings";
import { requiresFidoSshAgentAuth } from "./fidoSsh";
type HostAuthOverride = {
authMethod?: HostAuthMethod;
username?: string;
password?: string;
keyId?: string;
passphrase?: string;
};
type ResolvedHostAuth = {
identity?: Identity;
authMethod: HostAuthMethod;
username: string;
password?: string;
keyId?: string;
key?: SSHKey;
passphrase?: string;
identityFilePath?: string;
};
const hasAgentEnablingDirectives = (
host: Pick<Host, "addKeysToAgent" | "useKeychain">,
identityAgent?: string,
): boolean => Boolean(
identityAgent
|| (
typeof host.addKeysToAgent === "string"
&& host.addKeysToAgent.trim().length > 0
&& host.addKeysToAgent.trim().toLowerCase() !== "no"
)
|| host.useKeychain === true,
);
export const resolveHostAuthMethodSelection = (
host: Pick<Host, "authMethod" | "authPolicyVersion" | "identityFileId" | "identityFilePaths" | "password" | "useSshAgent">,
): HostAuthMethod => host.authMethod || (
host.useSshAgent === true
? "auto"
: host.identityFileId || host.identityFilePaths?.length
? "key"
: host.password && host.authPolicyVersion !== 1
? "password"
: "auto"
);
export const applyHostAuthMethodSelection = <T extends Host>(
host: T,
authMethod: HostAuthMethod,
previousMethod: HostAuthMethod = resolveHostAuthMethodSelection(host),
): T => {
if (previousMethod === authMethod) {
return {
...host,
authMethod,
authPolicyVersion: 1,
};
}
const isAutomatic = authMethod === "auto";
const automaticIdentityAgent = isAutomatic && isSshAgentNoneValue(host.identityAgent)
? undefined
: host.identityAgent;
const hasAutomaticAgentSettings = hasAgentEnablingDirectives(host, automaticIdentityAgent);
return {
...host,
authMethod,
authPolicyVersion: 1,
identityId: "",
identityFileId: undefined,
identityFilePaths: undefined,
...(isAutomatic
? { identityAgent: automaticIdentityAgent, identitiesOnly: undefined }
: {}),
useSshAgent: isAutomatic
? (hasAutomaticAgentSettings ? true : undefined)
: authMethod === "key" && previousMethod === "key"
? host.useSshAgent
: false,
};
};
export const resolveSshAgentToggleUpdate = (
host: Pick<Host, "identityAgent" | "addKeysToAgent" | "useKeychain">,
authMethod: HostAuthMethod,
enabling: boolean,
): Pick<Host, "useSshAgent" | "identityAgent"> => {
const identityAgent = enabling && isSshAgentNoneValue(host.identityAgent)
? undefined
: host.identityAgent;
const hasExplicitAgentSettings = hasAgentEnablingDirectives(host, identityAgent);
return {
useSshAgent: enabling
? (authMethod === "auto" && !hasExplicitAgentSettings ? undefined : true)
: false,
identityAgent,
};
};
const inferAuthMethod = (opts: {
explicit?: HostAuthMethod;
keyId?: string;
password?: string;
hostAuthMethod?: HostAuthMethod;
key?: SSHKey;
}): HostAuthMethod => {
if (opts.explicit) return opts.explicit;
if (opts.hostAuthMethod === "auto") return "auto";
if (opts.keyId) {
if (opts.hostAuthMethod === "key" || opts.hostAuthMethod === "certificate") {
return opts.hostAuthMethod;
}
return opts.key?.certificate ? "certificate" : "key";
}
if (opts.hostAuthMethod) return opts.hostAuthMethod;
if (opts.password) return "password";
return "auto";
};
export const resolveHostAuth = (args: {
host: Host;
keys: SSHKey[];
identities?: Identity[];
override?: HostAuthOverride | null;
}): ResolvedHostAuth => {
const { host, keys, identities = [], override } = args;
const identity = host.identityId
? identities.find((i) => i.id === host.identityId)
: undefined;
const username =
override?.username?.trim() ||
identity?.username?.trim() ||
host.username?.trim() ||
"";
const selectedAuthMethod = (
override?.authMethod ||
identity?.authMethod ||
host.authMethod ||
(
host.useSshAgent === true
? "auto"
: host.identityFilePaths?.length
? "key"
: host.authPolicyVersion === 1 && !host.identityFileId
? "auto"
: undefined
)
) as HostAuthMethod | undefined;
// Don't load key when password auth is selected.
// This ensures the user's auth method selection is strictly respected.
const keyId = selectedAuthMethod === "password"
? undefined
: (override?.keyId || identity?.keyId || host.identityFileId || undefined);
const key = keyId ? keys.find((k) => k.id === keyId) : undefined;
const password = override?.password ?? identity?.password ?? host.password;
const authMethod = inferAuthMethod({
explicit: override?.authMethod,
hostAuthMethod: selectedAuthMethod,
keyId,
password,
key,
});
const passphrase = override?.passphrase || key?.passphrase || undefined;
const identityFilePath = key?.source === 'reference' && key.filePath
? key.filePath
: undefined;
return {
identity,
authMethod,
username,
password,
keyId,
key,
passphrase,
identityFilePath,
};
};
export const resolveHostAuthMethodForPersistence = (args: {
host: Host;
keys: SSHKey[];
identities?: Identity[];
groupDefaults?: Partial<GroupConfig>;
}): HostAuthMethod | undefined => {
const { host, keys, identities, groupDefaults } = args;
if (host.authMethod) return host.authMethod;
const resolveEffectiveMethod = (candidate: Host) => resolveHostAuth({
host: groupDefaults ? applyGroupDefaults(candidate, groupDefaults) : candidate,
keys,
identities,
}).authMethod;
const methodBeforeSave = resolveEffectiveMethod(host);
const methodAfterSave = resolveEffectiveMethod(
host.savePassword === false ? { ...host, password: undefined } : host,
);
return methodBeforeSave === methodAfterSave ? undefined : methodBeforeSave;
};
/**
* Resolve the password to use for sudo/su autofill the same way SSH login does
* (through resolveHostAuth), so a password stored in a referenced Keychain
* identity (host.identityId) is found — not just host.password (issue #1284).
* Returns undefined when the host opts out of saving its password, or none is
* available (pure key auth, or an undecryptable placeholder).
* Used for both sudo and su confirm-to-fill hints (#2156).
*/
export const resolveHostAutofillPassword = (args: {
host: Host;
keys: SSHKey[];
identities?: Identity[];
}): string | undefined => {
if (args.host.savePassword === false) return undefined;
return sanitizeCredentialValue(resolveHostAuth(args).password) || undefined;
};
export const resolveBridgeKeyAuth = (args: {
key?: SSHKey | null;
fallbackIdentityFilePaths?: string[];
passphrase?: string;
}): {
privateKey?: string;
identityFilePaths?: string[];
passphrase?: string;
} => {
const { key, fallbackIdentityFilePaths, passphrase } = args;
const isFidoSk = requiresFidoSshAgentAuth({
type: key?.type,
publicKey: key?.publicKey,
privateKey: key?.privateKey,
});
const identityFilePaths = key?.source === "reference" && key.filePath
? [key.filePath]
: fallbackIdentityFilePaths;
// SK private material is an OpenSSH key *handle*. Pass it through so the
// main process can load it into the system agent; never use it for local
// software signing (startSession routes SK handles to ssh-add).
if (isFidoSk) {
return {
privateKey: key?.source === "reference"
? undefined
: sanitizeCredentialValue(key?.privateKey),
identityFilePaths: key?.source === "reference" && key.filePath
? [key.filePath]
: identityFilePaths,
passphrase: sanitizeCredentialValue(passphrase ?? key?.passphrase),
};
}
return {
privateKey: key?.source === "reference" ? undefined : sanitizeCredentialValue(key?.privateKey),
identityFilePaths,
passphrase: sanitizeCredentialValue(passphrase ?? key?.passphrase),
};
};
/** Preferred agent identity blobs for IdentitiesOnly selection. */
const resolveAgentPublicKeys = (
key?: Pick<SSHKey, "publicKey" | "certificate">,
): string[] | undefined => {
const keys: string[] = [];
const publicKey = key?.publicKey?.trim();
const certificate = key?.certificate?.trim();
if (publicKey) keys.push(publicKey);
// ssh-add -L lists the bare key and certificate as distinct identities; when
// the vault stores them separately, both must be selectable under IdentitiesOnly.
if (certificate && certificate !== publicKey) keys.push(certificate);
return keys.length > 0 ? keys : undefined;
};
export const resolveBridgeSshAgentAuth = (
host: Pick<Host, "authMethod" | "useSshAgent" | "identityAgent" | "identityFilePaths" | "identitiesOnly" | "addKeysToAgent" | "useKeychain" | "agentForwarding">,
key?: Pick<SSHKey, "certificate" | "publicKey" | "source" | "filePath" | "type" | "privateKey">,
authMethod?: HostAuthMethod,
): {
useSshAgent?: boolean;
identityAgent?: string;
identitiesOnly?: boolean;
addKeysToAgent?: string;
useKeychain?: boolean;
agentPublicKeys?: string[];
} => {
const forwardingAgent = host.agentForwarding
&& host.identityAgent !== undefined
&& !isSshAgentNoneValue(host.identityAgent)
? { identityAgent: host.identityAgent }
: {};
const isFidoSk = requiresFidoSshAgentAuth({
type: key?.type,
publicKey: key?.publicKey,
privateKey: key?.privateKey,
});
const hasAgentSelector = Boolean(
key?.publicKey?.trim()
|| (key?.source === "reference" && key.filePath?.trim())
|| host.identityFilePaths?.some((filePath) => filePath.trim())
// Inline imported sk private key handle still needs agent; selection uses
// the public key when present, otherwise the agent is used non-strictly.
|| (isFidoSk && key?.privateKey?.trim()),
);
// FIDO2 SK keys always require the system agent (hardware signs via
// ssh-sk-helper), whether selected explicitly or via a CA certificate
// wrapping the SK public key.
const fidoAgentAuth = () => {
if (!hasAgentSelector && !key?.privateKey?.trim()) {
return { useSshAgent: false };
}
const agentPublicKeys = resolveAgentPublicKeys(key);
return {
useSshAgent: true,
identityAgent: host.identityAgent,
identitiesOnly: Boolean(key?.publicKey?.trim() || (key?.source === "reference" && key.filePath)),
addKeysToAgent: host.addKeysToAgent ?? "yes",
useKeychain: host.useKeychain,
...(agentPublicKeys ? { agentPublicKeys } : {}),
};
};
if (authMethod === "password") {
return { useSshAgent: false, ...forwardingAgent };
}
if (authMethod === "certificate" || key?.certificate?.trim()) {
// A certificate over an SK public key still needs the agent for hardware
// signing; only non-FIDO certificate auth bypasses the agent entirely.
if (isFidoSk) {
return fidoAgentAuth();
}
return { useSshAgent: false, ...forwardingAgent };
}
if (authMethod === "key" || isFidoSk) {
// Explicit key auth without agent only works for soft keys; FIDO SK
// material is routed through the agent regardless of authMethod.
if (isFidoSk) {
return fidoAgentAuth();
}
if (host.useSshAgent !== true || !hasAgentSelector) {
return { useSshAgent: false, ...forwardingAgent };
}
const agentPublicKeys = resolveAgentPublicKeys(key);
return {
useSshAgent: true,
identityAgent: host.identityAgent,
identitiesOnly: true,
addKeysToAgent: host.addKeysToAgent,
useKeychain: host.useKeychain,
...(agentPublicKeys ? { agentPublicKeys } : {}),
};
}
if (host.useSshAgent !== true) {
return authMethod === "auto" && host.useSshAgent !== false
? forwardingAgent
: { useSshAgent: false, ...forwardingAgent };
}
const agentPublicKeys = resolveAgentPublicKeys(key);
return {
useSshAgent: true,
identityAgent: host.identityAgent,
identitiesOnly: host.identitiesOnly,
addKeysToAgent: host.addKeysToAgent,
useKeychain: host.useKeychain,
...(agentPublicKeys ? { agentPublicKeys } : {}),
};
};
export const hasRequiredHostAuthCredential = (args: {
host: Host;
keys: SSHKey[];
identities?: Identity[];
}): boolean => {
if (args.host.protocol && args.host.protocol !== "ssh") return true;
if (args.host.identityId && !args.identities?.some((identity) => identity.id === args.host.identityId)) {
return false;
}
const resolved = resolveHostAuth(args);
if (resolved.authMethod === "key") {
return Boolean(resolved.key || args.host.identityFilePaths?.some((value) => value.trim()));
}
if (resolved.authMethod === "certificate") {
return Boolean(resolved.key?.certificate?.trim());
}
return true;
};
export const hasMacKeychainAgentDirectives = (
host: Pick<Host, "addKeysToAgent" | "useKeychain">,
): boolean => host.useKeychain === true
&& host.addKeysToAgent?.toLowerCase() === "yes";
export const hasBridgeSshCredentials = (auth: {
authMethod?: HostAuthMethod;
password?: string;
privateKey?: string;
identityFilePaths?: string[];
useSshAgent?: boolean;
}): boolean => Boolean(
auth.authMethod === "auto" ||
auth.password ||
auth.privateKey ||
auth.identityFilePaths?.length ||
auth.useSshAgent,
);