mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-28 06:05:24 +00:00
* fix(sso): send the PKCE verifier for GitHub login (#1534) * fix(remote-desktop): clip cursor overflow without disabling zoom (#1535) * test(remote-desktop): preserve sessions beyond one hour (#1536) * fix(hosts): expose controls for overflowing editor tabs (#1537) * fix(hosts): expose controls for overflowing editor tabs * test(hosts): mock resize observation in admin panel tests * fix(status): skip TCP probes while host sessions are active (#1538) * fix(database): batch session activity persistence (#1539) * docs(api): describe cookie and API key authentication (#1540) * fix(snippets): repair missing note column on SQLite upgrades (#1541) * fix(docker): retain stored SSH credential association (#1543) * fix(file-manager): render transfer toasts without plugin hooks (#1546) * feat(hosts): keep compact row actions inline (#1547) * fix(auth): allow retrying unavailable second-factor interfaces (#1549) * fix(auth): reject unresolved legacy identity provisioning (#1550) * fix(desktop): ship the plugin SDK inside Mac App Store builds (#1551) * fix(tmux): pass full session info to the terminal's session picker (#1552) The tmux.sessions service reduced detected sessions to bare names, but the picker reads session.name, so every entry rendered blank and selecting one sent an empty name, which created a new session instead of attaching. * fix(ssh): read force keyboard-interactive as a boolean when resolving hosts (#1553) The column holds the text "true"/"false", and the resolver passed it through as-is. The string "false" is truthy, so the password provider treated every saved host as forced keyboard-interactive and left the password out. Jump hops are built straight from the resolved host, so a password hop whose server doesn't offer keyboard-interactive failed with "All configured authentication methods failed". * fix(database): batch database saves for bulk host writes (#1554) * fix(database): yield to the event loop between database saves Each SQLite save serializes and encrypts the whole database into new buffers, which V8 only releases once the event loop turns. Boot migrations and bulk host import write plugin settings per host and per key in an awaited loop, so hundreds of full copies piled up and the container ran out of memory. * fix(database): save once per bulk host write instead of once per row On SQLite every repository write force-saves the whole database. Boot plugin data migrations, host defaults materialization and the bulk host routes write one row per host per setting, so they serialized and encrypted the full database hundreds of times in a row. DatabaseSaveTrigger.batched wraps a function so force saves made while it runs collapse into a single save when it finishes. Nested scopes fold into the outer one, and work that outlives its scope saves normally. * feat(hosts): add instance-wide predefined tag suggestions (#1548) * feat(hosts): add shared predefined tag suggestions * style(hosts): format tag catalog routes * test(database): advance fake timers past the save yield (#1555) * fix(i18n): complete Simplified Chinese core and plugin translations (#1542) * fix(i18n): complete Chinese onboarding and navigation labels * fix(i18n): translate remaining Chinese core and plugin interfaces * fix(i18n): translate host editor tab overflow controls * fix(i18n): use consistent Chinese fleet terminology * fix(i18n): localize hardcoded controls and plugin views * fix(i18n): translate built-in homepage widget catalog * test(homepage): follow translated timezone placeholder * fix(i18n): translate plugin-provided homepage widgets * fix(i18n): localize feature settings section titles * fix: 2.8 oidc accounts unable to sign in after upgrading (#1381) * fix: plugins losing the saved ssh login when copying a host (#1391) * fix: fleets, proxmox and automations not getting the host sudo password * fix: host imports running a defaults pass and metrics restart per host (#1384) * fix: high cpu from status probes and full database saves on every sample (#1300) * fix: user data export freezing the server (#1393) * fix: op:// secret references rejected as ssh keys on credentials (#1394) * fix: slow file deletes from the trash lookups on every delete (#1390) * fix: add openapi docs and error handling to host tag routes * test: compare download stream buffers directly so it stops timing out * chore: drop em dash from host row comment * chore: update release notes for 2.9.1 * fix: restore space to add host tags and redesign predefined tags editor * fix: host key silently accepted when the host is missing from the database (#1397) * fix: clearer host login failed status label and fix its translations (#1396) * chore: add host key and status label fixes to release notes * fix: sso and ldap provider dialogs overflowing the screen and using mismatched toggles * chore: increment ver * fix(audit): store plugin entries with no acting user as a null user_id (#1556) Plugin audit entries written outside a request used the literal "system" as user_id. That column references users.id, so the insert was refused (Postgres logs it as an FK violation) and the entry was silently dropped. Write null instead and keep "system" / plugin:<id> in username. * chore: add sso/ldap dialog and audit log fixes to release notes * fix: tunnels and host settings missing from shared hosts on desktop * fix: remote desktop logins missing from shared hosts on desktop * fix: simplify host status to online/offline and keep it live without a refresh * chore: sync Crowdin translations for 2.9.1 --------- Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com>
437 lines
13 KiB
TypeScript
437 lines
13 KiB
TypeScript
import { getErrorMessage } from "../../utils/error-message.js";
|
|
import type {
|
|
AuthenticatedRequest,
|
|
CredentialBackend,
|
|
} from "../../../types/index.js";
|
|
import type { Request, RequestHandler, Response, Router } from "express";
|
|
import type { Client as SshClient } from "ssh2";
|
|
import { createCurrentHostResolutionRepository } from "../repositories/factory.js";
|
|
import { connectHost } from "../../hosts/connect/connect-host.js";
|
|
import type { SshConnectHost } from "../../hosts/connect/types.js";
|
|
import { resolveHostById } from "../../hosts/host-resolver.js";
|
|
import { isSecretReference } from "../../hosts/external-secrets.js";
|
|
import { resolveKeyReferences } from "../../hosts/stored-ssh-key.js";
|
|
import { parseSSHKey } from "../../utils/ssh-key-utils.js";
|
|
|
|
function describeDeployError(err: unknown): string {
|
|
const message = getErrorMessage(err, "Connection failed");
|
|
if (message.includes("All configured authentication methods failed")) {
|
|
return "Authentication failed. Please check your credentials and ensure the SSH service is running.";
|
|
}
|
|
if (message.includes("ENOTFOUND") || message.includes("ENOENT")) {
|
|
return "Could not resolve hostname or connect to server.";
|
|
}
|
|
if (message.includes("ECONNREFUSED")) {
|
|
return "Connection refused. The server may not be running or the port may be incorrect.";
|
|
}
|
|
if (message.includes("ETIMEDOUT")) {
|
|
return "Connection timed out. Check your network connection and server availability.";
|
|
}
|
|
if (
|
|
message.includes("authentication failed") ||
|
|
message.includes("Permission denied")
|
|
) {
|
|
return "Authentication failed. Please check your username and password/key.";
|
|
}
|
|
if (message === "SSH connection timeout") return "Connection timeout";
|
|
return message;
|
|
}
|
|
|
|
async function deploySSHKeyToHost(
|
|
host: SshConnectHost,
|
|
userId: string,
|
|
credData: CredentialBackend,
|
|
): Promise<{ success: boolean; message?: string; error?: string }> {
|
|
const publicKey = credData.publicKey as string;
|
|
|
|
let conn: SshClient;
|
|
try {
|
|
({ client: conn } = await connectHost(host, {
|
|
userId,
|
|
purpose: "credential-deploy",
|
|
timeoutMs: 120000,
|
|
}));
|
|
} catch (error) {
|
|
return { success: false, error: describeDeployError(error) };
|
|
}
|
|
|
|
return new Promise((resolve) => {
|
|
void (async () => {
|
|
try {
|
|
await new Promise<void>((resolveCmd, rejectCmd) => {
|
|
const cmdTimeout = setTimeout(() => {
|
|
rejectCmd(new Error("mkdir command timeout"));
|
|
}, 10000);
|
|
|
|
conn.exec(
|
|
"test -d ~/.ssh || mkdir -p ~/.ssh; chmod 700 ~/.ssh",
|
|
(err, stream) => {
|
|
if (err) {
|
|
clearTimeout(cmdTimeout);
|
|
return rejectCmd(err);
|
|
}
|
|
|
|
stream.on("close", (code) => {
|
|
clearTimeout(cmdTimeout);
|
|
if (code === 0) {
|
|
resolveCmd();
|
|
} else {
|
|
rejectCmd(
|
|
new Error(`mkdir command failed with code ${code}`),
|
|
);
|
|
}
|
|
});
|
|
|
|
stream.on("data", () => {
|
|
// Ignore output
|
|
});
|
|
},
|
|
);
|
|
});
|
|
|
|
const keyExists = await new Promise<boolean>(
|
|
(resolveCheck, rejectCheck) => {
|
|
const checkTimeout = setTimeout(() => {
|
|
rejectCheck(new Error("Key check timeout"));
|
|
}, 5000);
|
|
|
|
let actualPublicKey = publicKey;
|
|
try {
|
|
const parsed = JSON.parse(publicKey);
|
|
if (parsed.data) {
|
|
actualPublicKey = parsed.data;
|
|
}
|
|
} catch {
|
|
// Ignore parse errors
|
|
}
|
|
|
|
const keyParts = actualPublicKey.trim().split(" ");
|
|
if (keyParts.length < 2) {
|
|
clearTimeout(checkTimeout);
|
|
return rejectCheck(
|
|
new Error(
|
|
"Invalid public key format - must contain at least 2 parts",
|
|
),
|
|
);
|
|
}
|
|
|
|
const keyPattern = keyParts[1];
|
|
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(keyPattern)) {
|
|
clearTimeout(checkTimeout);
|
|
return rejectCheck(new Error("Invalid public key data"));
|
|
}
|
|
|
|
conn.exec(
|
|
`if [ -f ~/.ssh/authorized_keys ]; then grep -F "${keyPattern}" ~/.ssh/authorized_keys >/dev/null 2>&1; echo $?; else echo 1; fi`,
|
|
(err, stream) => {
|
|
if (err) {
|
|
clearTimeout(checkTimeout);
|
|
return rejectCheck(err);
|
|
}
|
|
|
|
let output = "";
|
|
stream.on("data", (data) => {
|
|
output += data.toString();
|
|
});
|
|
|
|
stream.on("close", () => {
|
|
clearTimeout(checkTimeout);
|
|
const exists = output.trim() === "0";
|
|
resolveCheck(exists);
|
|
});
|
|
},
|
|
);
|
|
},
|
|
);
|
|
|
|
if (keyExists) {
|
|
conn.end();
|
|
resolve({ success: true, message: "SSH key already deployed" });
|
|
return;
|
|
}
|
|
|
|
await new Promise<void>((resolveAdd, rejectAdd) => {
|
|
const addTimeout = setTimeout(() => {
|
|
rejectAdd(new Error("Key add timeout"));
|
|
}, 30000);
|
|
|
|
let actualPublicKey = publicKey;
|
|
try {
|
|
const parsed = JSON.parse(publicKey);
|
|
if (parsed.data) {
|
|
actualPublicKey = parsed.data;
|
|
}
|
|
} catch {
|
|
// Ignore parse errors
|
|
}
|
|
|
|
const escapedKey = actualPublicKey
|
|
.replace(/\\/g, "\\\\")
|
|
.replace(/'/g, "'\\''");
|
|
const escapedName = credData.name
|
|
.replace(/\\/g, "\\\\")
|
|
.replace(/'/g, "'\\''");
|
|
|
|
conn.exec(
|
|
`printf '%s\n' '${escapedKey} ${escapedName}@Termix' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys`,
|
|
(err, stream) => {
|
|
if (err) {
|
|
clearTimeout(addTimeout);
|
|
return rejectAdd(err);
|
|
}
|
|
|
|
stream.on("data", () => {
|
|
// Consume output
|
|
});
|
|
|
|
stream.on("close", (code) => {
|
|
clearTimeout(addTimeout);
|
|
if (code === 0) {
|
|
resolveAdd();
|
|
} else {
|
|
rejectAdd(
|
|
new Error(`Key deployment failed with code ${code}`),
|
|
);
|
|
}
|
|
});
|
|
},
|
|
);
|
|
});
|
|
|
|
const verifySuccess = await new Promise<boolean>(
|
|
(resolveVerify, rejectVerify) => {
|
|
const verifyTimeout = setTimeout(() => {
|
|
rejectVerify(new Error("Key verification timeout"));
|
|
}, 5000);
|
|
|
|
let actualPublicKey = publicKey;
|
|
try {
|
|
const parsed = JSON.parse(publicKey);
|
|
if (parsed.data) {
|
|
actualPublicKey = parsed.data;
|
|
}
|
|
} catch {
|
|
// Ignore parse errors
|
|
}
|
|
|
|
const keyParts = actualPublicKey.trim().split(" ");
|
|
if (keyParts.length < 2) {
|
|
clearTimeout(verifyTimeout);
|
|
return rejectVerify(
|
|
new Error(
|
|
"Invalid public key format - must contain at least 2 parts",
|
|
),
|
|
);
|
|
}
|
|
|
|
const keyPattern = keyParts[1];
|
|
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(keyPattern)) {
|
|
clearTimeout(verifyTimeout);
|
|
return rejectVerify(new Error("Invalid public key data"));
|
|
}
|
|
conn.exec(
|
|
`grep -F "${keyPattern}" ~/.ssh/authorized_keys >/dev/null 2>&1; echo $?`,
|
|
(err, stream) => {
|
|
if (err) {
|
|
clearTimeout(verifyTimeout);
|
|
return rejectVerify(err);
|
|
}
|
|
|
|
let output = "";
|
|
stream.on("data", (data) => {
|
|
output += data.toString();
|
|
});
|
|
|
|
stream.on("close", () => {
|
|
clearTimeout(verifyTimeout);
|
|
const verified = output.trim() === "0";
|
|
resolveVerify(verified);
|
|
});
|
|
},
|
|
);
|
|
},
|
|
);
|
|
|
|
conn.end();
|
|
|
|
if (verifySuccess) {
|
|
resolve({ success: true, message: "SSH key deployed successfully" });
|
|
} else {
|
|
resolve({
|
|
success: false,
|
|
error: "Key deployment verification failed",
|
|
});
|
|
}
|
|
} catch (error) {
|
|
conn.end();
|
|
resolve({
|
|
success: false,
|
|
error: getErrorMessage(error, "Deployment failed"),
|
|
});
|
|
}
|
|
})();
|
|
});
|
|
}
|
|
|
|
export function registerCredentialDeployRoutes(
|
|
router: Router,
|
|
authenticateJWT: RequestHandler,
|
|
requireCredentialViewPermission: RequestHandler,
|
|
requireHostEditPermission: RequestHandler,
|
|
requireDataAccess: RequestHandler,
|
|
): void {
|
|
/**
|
|
* @openapi
|
|
* /credentials/{id}/deploy-to-host:
|
|
* post:
|
|
* summary: Deploy SSH key to a host
|
|
* description: Deploys an SSH public key to a target host's authorized_keys file.
|
|
* tags:
|
|
* - Credentials
|
|
* parameters:
|
|
* - in: path
|
|
* name: id
|
|
* required: true
|
|
* schema:
|
|
* type: integer
|
|
* requestBody:
|
|
* required: true
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* properties:
|
|
* targetHostId:
|
|
* type: integer
|
|
* responses:
|
|
* 200:
|
|
* description: SSH key deployed successfully.
|
|
* 400:
|
|
* description: Credential ID and target host ID are required.
|
|
* 401:
|
|
* description: Authentication required.
|
|
* 404:
|
|
* description: Credential or target host not found.
|
|
* 500:
|
|
* description: Failed to deploy SSH key.
|
|
*/
|
|
router.post(
|
|
"/:id/deploy-to-host",
|
|
authenticateJWT,
|
|
requireCredentialViewPermission,
|
|
requireHostEditPermission,
|
|
requireDataAccess,
|
|
async (req: Request, res: Response) => {
|
|
const id = Array.isArray(req.params.id)
|
|
? req.params.id[0]
|
|
: req.params.id;
|
|
const credentialId = parseInt(id);
|
|
const { targetHostId } = req.body;
|
|
|
|
if (!credentialId || !targetHostId) {
|
|
return res.status(400).json({
|
|
success: false,
|
|
error: "Credential ID and target host ID are required",
|
|
});
|
|
}
|
|
|
|
try {
|
|
const userId = (req as AuthenticatedRequest).userId;
|
|
if (!userId) {
|
|
return res.status(401).json({
|
|
success: false,
|
|
error: "Authentication required",
|
|
});
|
|
}
|
|
|
|
const repository = createCurrentHostResolutionRepository();
|
|
const credential = await repository.findCredentialByIdForUser(
|
|
credentialId,
|
|
userId,
|
|
);
|
|
|
|
if (!credential) {
|
|
return res.status(404).json({
|
|
success: false,
|
|
error: "Credential not found",
|
|
});
|
|
}
|
|
|
|
const credData = credential as unknown as CredentialBackend;
|
|
|
|
if (credData.authType !== "key") {
|
|
return res.status(400).json({
|
|
success: false,
|
|
error: "Only SSH key-based credentials can be deployed",
|
|
});
|
|
}
|
|
|
|
let publicKey = credData.publicKey;
|
|
const storedKey = credData.privateKey || credData.key;
|
|
if (!publicKey && isSecretReference(storedKey)) {
|
|
// A key kept in a secret source has no stored public key; derive
|
|
// it from the resolved key.
|
|
const resolved = await resolveKeyReferences(
|
|
userId,
|
|
storedKey,
|
|
(credData as { keyPassword?: string | null }).keyPassword,
|
|
);
|
|
publicKey =
|
|
parseSSHKey(resolved.key, resolved.passphrase).publicKey ||
|
|
undefined;
|
|
}
|
|
if (!publicKey) {
|
|
return res.status(400).json({
|
|
success: false,
|
|
error: "Public key is required for deployment",
|
|
});
|
|
}
|
|
// Writing authorized_keys is an owner action, so ownership is checked
|
|
// before the shared resolver fills in the credentials.
|
|
const hostData = await repository.findHostByIdForUser(
|
|
targetHostId,
|
|
userId,
|
|
);
|
|
|
|
if (!hostData) {
|
|
return res.status(404).json({
|
|
success: false,
|
|
error: "Target host not found",
|
|
});
|
|
}
|
|
|
|
const resolvedHost = await resolveHostById(targetHostId, userId);
|
|
if (!resolvedHost) {
|
|
return res.status(400).json({
|
|
success: false,
|
|
error: "Host credential not found",
|
|
});
|
|
}
|
|
|
|
const deployResult = await deploySSHKeyToHost(
|
|
resolvedHost as unknown as SshConnectHost,
|
|
userId,
|
|
credData,
|
|
);
|
|
|
|
if (deployResult.success) {
|
|
res.json({
|
|
success: true,
|
|
message: deployResult.message || "SSH key deployed successfully",
|
|
});
|
|
} else {
|
|
res.status(500).json({
|
|
success: false,
|
|
error: deployResult.error || "Deployment failed",
|
|
});
|
|
}
|
|
} catch (error) {
|
|
res.status(500).json({
|
|
success: false,
|
|
error: getErrorMessage(error, "Failed to deploy SSH key"),
|
|
});
|
|
}
|
|
},
|
|
);
|
|
}
|