This commit is contained in:
LukeGus
2026-05-28 22:29:20 -05:00
parent 33dcde0827
commit 5777351145
238 changed files with 62303 additions and 98955 deletions
+6 -2
View File
@@ -470,7 +470,7 @@ app.post("/dashboard/preferences", async (req, res) => {
});
}
const { cards } = req.body;
const { cards, mainWidthPct } = req.body;
if (!cards || !Array.isArray(cards)) {
return res.status(400).json({
@@ -478,7 +478,11 @@ app.post("/dashboard/preferences", async (req, res) => {
});
}
const layout = JSON.stringify({ cards });
const layoutObj: Record<string, unknown> = { cards };
if (typeof mainWidthPct === "number") {
layoutObj.mainWidthPct = mainWidthPct;
}
const layout = JSON.stringify(layoutObj);
const existing = await getDb()
.select()
+10 -5
View File
@@ -1251,6 +1251,7 @@ app.post(
};
try {
mainDb.$client.exec("PRAGMA foreign_keys = OFF");
try {
const importedHosts = importDb
.prepare("SELECT * FROM ssh_data")
@@ -1561,6 +1562,7 @@ app.post(
);
}
mainDb.$client.exec("PRAGMA foreign_keys = ON");
result.success = true;
try {
@@ -2019,12 +2021,15 @@ httpServer.on("error", (err: NodeJS.ErrnoException) => {
throw err;
});
httpServer.listen(HTTP_PORT, async () => {
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
}
export const serverReady = new Promise<void>((resolve) => {
httpServer.listen(HTTP_PORT, async () => {
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
}
await initializeSecurity();
await initializeSecurity();
resolve();
});
});
const sslConfig = AutoSSLSetup.getSSLConfig();
+49
View File
@@ -710,6 +710,8 @@ const migrateSchema = () => {
addColumnIfNotExists("ssh_credentials", "public_key", "TEXT");
addColumnIfNotExists("ssh_credentials", "detected_key_type", "TEXT");
addColumnIfNotExists("ssh_credentials", "cert_public_key", "TEXT");
addColumnIfNotExists("ssh_credentials", "system_password", "TEXT");
addColumnIfNotExists("ssh_credentials", "system_key", "TEXT");
addColumnIfNotExists("ssh_credentials", "system_key_password", "TEXT");
@@ -782,6 +784,7 @@ const migrateSchema = () => {
addColumnIfNotExists("snippets", "folder", "TEXT");
addColumnIfNotExists("snippets", "order", "INTEGER NOT NULL DEFAULT 0");
addColumnIfNotExists("snippets", "host_filter", "TEXT");
try {
sqlite
@@ -1007,6 +1010,19 @@ const migrateSchema = () => {
}
}
try {
sqlite.prepare("SELECT override_credential_id FROM host_access LIMIT 1").get();
} catch {
try {
sqlite.exec("ALTER TABLE host_access ADD COLUMN override_credential_id INTEGER REFERENCES ssh_credentials(id) ON DELETE SET NULL");
} catch (alterError) {
databaseLogger.warn("Failed to add override_credential_id column", {
operation: "schema_migration",
error: alterError,
});
}
}
try {
sqlite.prepare("SELECT sudo_password FROM ssh_data LIMIT 1").get();
} catch {
@@ -1078,6 +1094,39 @@ const migrateSchema = () => {
}
}
// Copy unencrypted username/domain into protocol-specific columns for old guac hosts.
// Passwords are handled via the legacy field name fallback in lazy-field-encryption.ts.
const usernameDomainBackfills = [
{
protocol: "rdp",
sql: "UPDATE ssh_data SET rdp_user = username, rdp_password = password, rdp_domain = domain WHERE connection_type = 'rdp' AND rdp_user IS NULL AND rdp_password IS NULL",
},
{
protocol: "vnc",
sql: "UPDATE ssh_data SET vnc_user = username, vnc_password = password WHERE connection_type = 'vnc' AND vnc_user IS NULL AND vnc_password IS NULL",
},
{
protocol: "telnet",
sql: "UPDATE ssh_data SET telnet_user = username, telnet_password = password WHERE connection_type = 'telnet' AND telnet_user IS NULL AND telnet_password IS NULL",
},
];
for (const backfill of usernameDomainBackfills) {
try {
const result = sqlite.prepare(backfill.sql).run();
if (result.changes > 0) {
databaseLogger.info(
`Backfilled ${result.changes} ${backfill.protocol} host credential(s)`,
{ operation: "guac_credential_backfill" },
);
}
} catch (e) {
databaseLogger.warn(`Failed to backfill ${backfill.protocol} host credentials`, {
operation: "guac_credential_backfill",
error: e,
});
}
}
try {
sqlite.prepare("SELECT id FROM roles LIMIT 1").get();
} catch {
+7
View File
@@ -256,6 +256,8 @@ export const sshCredentials = sqliteTable("ssh_credentials", {
keyType: text("key_type"),
detectedKeyType: text("detected_key_type"),
certPublicKey: text("cert_public_key", { length: 8192 }),
systemPassword: text("system_password"),
systemKey: text("system_key", { length: 16384 }),
systemKeyPassword: text("system_key_password"),
@@ -302,6 +304,7 @@ export const snippets = sqliteTable("snippets", {
updatedAt: text("updated_at")
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
hostFilter: text("host_filter"),
});
export const snippetFolders = sqliteTable("snippet_folders", {
@@ -461,6 +464,10 @@ export const hostAccess = sqliteTable("host_access", {
.default(sql`CURRENT_TIMESTAMP`),
lastAccessedAt: text("last_accessed_at"),
accessCount: integer("access_count").notNull().default(0),
overrideCredentialId: integer("override_credential_id").references(
() => sshCredentials.id,
{ onDelete: "set null" },
),
});
export const sharedCredentials = sqliteTable("shared_credentials", {
+17 -8
View File
@@ -147,6 +147,7 @@ router.post(
key,
keyPassword,
keyType,
certPublicKey,
} = req.body;
if (!isNonEmptyString(userId) || !isNonEmptyString(name)) {
@@ -230,6 +231,8 @@ router.post(
keyPassword: plainKeyPassword,
keyType: keyType || null,
detectedKeyType: keyInfo?.keyType || null,
certPublicKey:
authType === "key" && certPublicKey ? certPublicKey.trim() : null,
usageCount: 0,
lastUsed: null,
};
@@ -431,15 +434,14 @@ router.get(
if (credential.password) {
output.password = credential.password;
}
if (credential.key) {
output.key = credential.key;
}
if (credential.privateKey) {
output.privateKey = credential.privateKey;
}
output.hasKey = !!credential.key;
output.hasKeyPassword = !!credential.keyPassword;
if (credential.publicKey) {
output.publicKey = credential.publicKey;
}
if (credential.certPublicKey) {
output.certPublicKey = credential.certPublicKey;
}
if (credential.keyPassword) {
output.keyPassword = credential.keyPassword;
}
@@ -572,6 +574,9 @@ router.put(
if (updateData.keyPassword !== undefined) {
updateFields.keyPassword = updateData.keyPassword || null;
}
if (updateData.certPublicKey !== undefined) {
updateFields.certPublicKey = updateData.certPublicKey?.trim() || null;
}
if (Object.keys(updateFields).length === 0) {
const existing = await SimpleDBOps.select(
@@ -947,6 +952,7 @@ function formatCredentialOutput(
authType: credential.authType,
username: credential.username || null,
publicKey: credential.publicKey,
hasCertPublicKey: !!credential.certPublicKey,
keyType: credential.keyType,
detectedKeyType: credential.detectedKeyType,
usageCount: credential.usageCount || 0,
@@ -1445,7 +1451,7 @@ router.post(
const publicKeyString =
typeof publicKeyPem === "string"
? publicKeyPem
: publicKeyPem.toString("utf8");
: (publicKeyPem as Buffer).toString("utf8");
let keyType = "unknown";
const asymmetricKeyType = privateKeyObj.asymmetricKeyType;
@@ -1617,9 +1623,12 @@ async function deploySSHKeyToHost(
const escapedKey = actualPublicKey
.replace(/\\/g, "\\\\")
.replace(/'/g, "'\\''");
const escapedName = credData.name
.replace(/\\/g, "\\\\")
.replace(/'/g, "'\\''");
conn.exec(
`printf '%s\n' '${escapedKey} ${credData.name}@Termix' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys`,
`printf '%s\n' '${escapedKey} ${escapedName}@Termix' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys`,
(err, stream) => {
if (err) {
clearTimeout(addTimeout);
+88 -33
View File
@@ -43,6 +43,8 @@ const router = express.Router();
const upload = multer({ storage: multer.memoryStorage() });
const STATS_SERVER_URL = "http://localhost:30005";
function notifyStatsHostUpdated(
hostId: number,
headers: Pick<Request["headers"], "authorization" | "cookie">,
@@ -50,7 +52,7 @@ function notifyStatsHostUpdated(
): void {
axios
.post(
"http://localhost:30005/host-updated",
`${STATS_SERVER_URL}/host-updated`,
{ hostId },
{
headers: {
@@ -244,26 +246,18 @@ function normalizeImportedHost(
}
const SENSITIVE_FIELDS = [
"password",
"key",
"keyPassword",
"sudoPassword",
"autostartPassword",
"autostartKey",
"autostartKeyPassword",
"socks5Password",
"rdpPassword",
"vncPassword",
"telnetPassword",
];
function stripSensitiveFields(
host: Record<string, unknown>,
): Record<string, unknown> {
const result = { ...host };
result.hasPassword = !!host.password;
result.hasKey = !!host.key;
result.hasSudoPassword = !!host.sudoPassword;
result.hasKeyPassword = !!host.keyPassword;
for (const field of SENSITIVE_FIELDS) {
delete result[field];
}
@@ -291,10 +285,23 @@ function transformHostResponse(
showTunnelInSidebar: !!host.showTunnelInSidebar,
showDockerInSidebar: !!host.showDockerInSidebar,
showServerStatsInSidebar: !!host.showServerStatsInSidebar,
enableSsh: host.enableSsh !== undefined ? !!host.enableSsh : true,
enableRdp: !!host.enableRdp,
enableVnc: !!host.enableVnc,
enableTelnet: !!host.enableTelnet,
// Old hosts only had connection_type set; the per-protocol enable flags didn't exist yet.
// The schema defaults (enableSsh=true, others=false) wrongly mark every old host as SSH.
// Detect this migration case: if no non-SSH protocol is explicitly enabled AND
// connectionType is set to a non-SSH value, fall back to inferring from connectionType.
...(() => {
const ct = host.connectionType;
const rdp = !!host.enableRdp;
const vnc = !!host.enableVnc;
const tel = !!host.enableTelnet;
const isMigratedNonSsh = !rdp && !vnc && !tel && ct && ct !== "ssh";
return {
enableSsh: isMigratedNonSsh ? false : !!host.enableSsh,
enableRdp: isMigratedNonSsh ? ct === "rdp" : rdp,
enableVnc: isMigratedNonSsh ? ct === "vnc" : vnc,
enableTelnet: isMigratedNonSsh ? ct === "telnet" : tel,
};
})(),
sshPort: host.sshPort ?? host.port ?? 22,
rdpPort: host.rdpPort ?? 3389,
vncPort: host.vncPort ?? 5900,
@@ -305,9 +312,6 @@ function transformHostResponse(
rdpIgnoreCert: !!host.rdpIgnoreCert,
vncUser: host.vncUser || undefined,
telnetUser: host.telnetUser || undefined,
hasRdpPassword: !!host.rdpPassword,
hasVncPassword: !!host.vncPassword,
hasTelnetPassword: !!host.telnetPassword,
tunnelConnections: host.tunnelConnections
? JSON.parse(host.tunnelConnections as string)
: [],
@@ -658,15 +662,19 @@ router.post(
authType ||
authMethod ||
(effectiveConnectionType !== "ssh" ? "password" : undefined);
const effectiveUsername =
username || rdpUser || vncUser || telnetUser || "";
const effectiveName =
name || (effectiveUsername ? `${effectiveUsername}@${ip}` : String(ip));
const sshDataObj: Record<string, unknown> = {
userId: userId,
connectionType: effectiveConnectionType,
name,
name: effectiveName,
folder: folder || null,
tags: Array.isArray(tags) ? tags.join(",") : tags || "",
ip,
port,
username,
username: effectiveUsername,
authType: effectiveAuthType,
credentialId: credentialId || null,
overrideCredentialUsername: overrideCredentialUsername ? 1 : 0,
@@ -722,7 +730,7 @@ router.post(
portKnockSequence: portKnockSequence
? JSON.stringify(portKnockSequence)
: null,
enableSsh: enableSsh !== false ? 1 : 0,
enableSsh: enableSsh ? 1 : 0,
enableRdp: enableRdp ? 1 : 0,
enableVnc: enableVnc ? 1 : 0,
enableTelnet: enableTelnet ? 1 : 0,
@@ -1190,14 +1198,18 @@ router.put(
}
const effectiveAuthType = authType || authMethod;
const effectiveUsername =
username || rdpUser || vncUser || telnetUser || "";
const effectiveName =
name || (effectiveUsername ? `${effectiveUsername}@${ip}` : String(ip));
const sshDataObj: Record<string, unknown> = {
connectionType: connectionType || "ssh",
name,
name: effectiveName,
folder,
tags: Array.isArray(tags) ? tags.join(",") : tags || "",
ip,
port,
username,
username: effectiveUsername,
authType: effectiveAuthType,
credentialId: credentialId || null,
overrideCredentialUsername: overrideCredentialUsername ? 1 : 0,
@@ -1253,7 +1265,7 @@ router.put(
portKnockSequence: portKnockSequence
? JSON.stringify(portKnockSequence)
: null,
enableSsh: enableSsh !== false ? 1 : 0,
enableSsh: enableSsh ? 1 : 0,
enableRdp: enableRdp ? 1 : 0,
enableVnc: enableVnc ? 1 : 0,
enableTelnet: enableTelnet ? 1 : 0,
@@ -1566,6 +1578,23 @@ router.get(
guacamoleConfig: hosts.guacamoleConfig,
macAddress: hosts.macAddress,
dockerConfig: hosts.dockerConfig,
enableSsh: hosts.enableSsh,
enableRdp: hosts.enableRdp,
enableVnc: hosts.enableVnc,
enableTelnet: hosts.enableTelnet,
sshPort: hosts.sshPort,
rdpPort: hosts.rdpPort,
vncPort: hosts.vncPort,
telnetPort: hosts.telnetPort,
rdpUser: hosts.rdpUser,
rdpPassword: hosts.rdpPassword,
rdpDomain: hosts.rdpDomain,
rdpSecurity: hosts.rdpSecurity,
rdpIgnoreCert: hosts.rdpIgnoreCert,
vncUser: hosts.vncUser,
vncPassword: hosts.vncPassword,
telnetUser: hosts.telnetUser,
telnetPassword: hosts.telnetPassword,
ownerId: hosts.userId,
isShared: sql<boolean>`${hostAccess.id} IS NOT NULL AND ${hosts.userId} != ${userId}`,
@@ -1891,9 +1920,21 @@ router.get(
const exportData = isRemoteDesktop
? {
...baseExportData,
domain: resolvedHost.domain || null,
security: resolvedHost.security || null,
ignoreCert: !!resolvedHost.ignoreCert,
enableRdp: !!resolvedHost.enableRdp,
enableVnc: !!resolvedHost.enableVnc,
enableTelnet: !!resolvedHost.enableTelnet,
rdpPort: resolvedHost.rdpPort || 3389,
vncPort: resolvedHost.vncPort || 5900,
telnetPort: resolvedHost.telnetPort || 23,
rdpUser: resolvedHost.rdpUser || null,
rdpPassword: resolvedHost.rdpPassword || null,
rdpDomain: resolvedHost.rdpDomain || null,
rdpSecurity: resolvedHost.rdpSecurity || null,
rdpIgnoreCert: !!resolvedHost.rdpIgnoreCert,
vncUser: resolvedHost.vncUser || null,
vncPassword: resolvedHost.vncPassword || null,
telnetUser: resolvedHost.telnetUser || null,
telnetPassword: resolvedHost.telnetPassword || null,
guacamoleConfig: resolvedHost.guacamoleConfig
? JSON.parse(resolvedHost.guacamoleConfig as string)
: null,
@@ -2217,9 +2258,8 @@ router.delete(
try {
const axios = (await import("axios")).default;
const statsPort = 30005;
await axios.post(
`http://localhost:${statsPort}/host-deleted`,
`${STATS_SERVER_URL}/host-deleted`,
{ hostId: numericHostId },
{
headers: {
@@ -3394,11 +3434,10 @@ router.delete(
try {
const axios = (await import("axios")).default;
const statsPort = 30005;
for (const host of hostsToDelete) {
try {
await axios.post(
`http://localhost:${statsPort}/host-deleted`,
`${STATS_SERVER_URL}/host-deleted`,
{ hostId: host.id },
{
headers: {
@@ -3804,6 +3843,10 @@ router.post(
overrideCredentialUsername: hostData.overrideCredentialUsername
? 1
: 0,
enableSsh: hostData.enableSsh ?? false,
enableRdp: hostData.enableRdp ?? false,
enableVnc: hostData.enableVnc ?? false,
enableTelnet: hostData.enableTelnet ?? false,
updatedAt: new Date().toISOString(),
};
@@ -3814,9 +3857,21 @@ router.post(
sshDataObj.key = null;
sshDataObj.keyPassword = null;
sshDataObj.keyType = null;
sshDataObj.domain = hostData.domain || null;
sshDataObj.security = hostData.security || null;
sshDataObj.ignoreCert = hostData.ignoreCert ? 1 : 0;
sshDataObj.rdpUser = hostData.rdpUser || null;
sshDataObj.rdpPassword = hostData.rdpPassword || null;
sshDataObj.rdpDomain = hostData.rdpDomain || null;
sshDataObj.rdpSecurity = hostData.rdpSecurity || null;
sshDataObj.rdpIgnoreCert = hostData.rdpIgnoreCert ? 1 : 0;
sshDataObj.rdpPort = hostData.rdpPort || 3389;
sshDataObj.vncUser = hostData.vncUser || null;
sshDataObj.vncPassword = hostData.vncPassword || null;
sshDataObj.vncPort = hostData.vncPort || 5900;
sshDataObj.telnetUser = hostData.telnetUser || null;
sshDataObj.telnetPassword = hostData.telnetPassword || null;
sshDataObj.telnetPort = hostData.telnetPort || 23;
sshDataObj.enableRdp = hostData.enableRdp ? 1 : 0;
sshDataObj.enableVnc = hostData.enableVnc ? 1 : 0;
sshDataObj.enableTelnet = hostData.enableTelnet ? 1 : 0;
sshDataObj.guacamoleConfig = hostData.guacamoleConfig
? JSON.stringify(hostData.guacamoleConfig)
: null;
+92 -33
View File
@@ -10,6 +10,7 @@ import {
sharedCredentials,
snippets,
snippetAccess,
sshCredentials,
} from "../db/schema.js";
import { eq, and, desc, sql, or, isNull, gte } from "drizzle-orm";
import type { Response } from "express";
@@ -128,10 +129,10 @@ router.post(
return res.status(403).json({ error: "Not host owner" });
}
if (!host[0].credentialId) {
if (!host[0].credentialId && host[0].authType !== "opkssh") {
return res.status(400).json({
error:
"Only hosts using credentials can be shared. Please create a credential and assign it to this host before sharing.",
"Only hosts using credentials or OPKSSH can be shared. Please create a credential and assign it to this host before sharing.",
code: "CREDENTIAL_REQUIRED_FOR_SHARING",
});
}
@@ -203,23 +204,25 @@ router.post(
.delete(sharedCredentials)
.where(eq(sharedCredentials.hostAccessId, existing[0].id));
const { SharedCredentialManager } =
await import("../../utils/shared-credential-manager.js");
const sharedCredManager = SharedCredentialManager.getInstance();
if (targetType === "user") {
await sharedCredManager.createSharedCredentialForUser(
existing[0].id,
host[0].credentialId,
targetUserId!,
userId,
);
} else {
await sharedCredManager.createSharedCredentialsForRole(
existing[0].id,
host[0].credentialId,
targetRoleId!,
userId,
);
if (host[0].credentialId) {
const { SharedCredentialManager } =
await import("../../utils/shared-credential-manager.js");
const sharedCredManager = SharedCredentialManager.getInstance();
if (targetType === "user") {
await sharedCredManager.createSharedCredentialForUser(
existing[0].id,
host[0].credentialId,
targetUserId!,
userId,
);
} else {
await sharedCredManager.createSharedCredentialsForRole(
existing[0].id,
host[0].credentialId,
targetRoleId!,
userId,
);
}
}
databaseLogger.info("Permission granted", {
operation: "rbac_permission_grant",
@@ -249,20 +252,22 @@ router.post(
await import("../../utils/shared-credential-manager.js");
const sharedCredManager = SharedCredentialManager.getInstance();
if (targetType === "user") {
await sharedCredManager.createSharedCredentialForUser(
result.lastInsertRowid as number,
host[0].credentialId,
targetUserId!,
userId,
);
} else {
await sharedCredManager.createSharedCredentialsForRole(
result.lastInsertRowid as number,
host[0].credentialId,
targetRoleId!,
userId,
);
if (host[0].credentialId) {
if (targetType === "user") {
await sharedCredManager.createSharedCredentialForUser(
result.lastInsertRowid as number,
host[0].credentialId,
targetUserId!,
userId,
);
} else {
await sharedCredManager.createSharedCredentialsForRole(
result.lastInsertRowid as number,
host[0].credentialId,
targetRoleId!,
userId,
);
}
}
databaseLogger.success("Host shared successfully", {
operation: "rbac_host_share_success",
@@ -1520,4 +1525,58 @@ router.get(
},
);
router.put(
"/host-access/:hostId/credential",
async (req: express.Request, res: express.Response) => {
try {
const userId = (req as AuthenticatedRequest).userId!;
const hostId = Number.parseInt(String(req.params.hostId), 10);
const { credentialId } = req.body;
if (!hostId || isNaN(hostId)) {
return res.status(400).json({ error: "Invalid host ID" });
}
const access = await db
.select()
.from(hostAccess)
.where(
and(eq(hostAccess.hostId, hostId), eq(hostAccess.userId, userId)),
)
.limit(1);
if (access.length === 0) {
return res.status(403).json({ error: "No access to this host" });
}
if (credentialId) {
const cred = await db
.select({ id: sshCredentials.id })
.from(sshCredentials)
.where(
and(
eq(sshCredentials.id, credentialId),
eq(sshCredentials.userId, userId),
),
)
.limit(1);
if (cred.length === 0) {
return res.status(404).json({ error: "Credential not found" });
}
}
await db
.update(hostAccess)
.set({ overrideCredentialId: credentialId || null })
.where(eq(hostAccess.id, access[0].id));
res.json({ success: true });
} catch (error) {
databaseLogger.error("Failed to set override credential", error);
res.status(500).json({ error: "Failed to update credential" });
}
},
);
export default router;
+8 -1
View File
@@ -93,6 +93,7 @@ async function getAccessibleSnippet(snippetId: number, userId: string) {
order: snippets.order,
createdAt: snippets.createdAt,
updatedAt: snippets.updatedAt,
hostFilter: snippets.hostFilter,
})
.from(snippetAccess)
.innerJoin(snippets, eq(snippetAccess.snippetId, snippets.id))
@@ -1104,7 +1105,7 @@ router.post(
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
const { name, content, description, folder, order } = req.body;
const { name, content, description, folder, order, hostFilter } = req.body;
if (
!isNonEmptyString(userId) ||
@@ -1146,6 +1147,7 @@ router.post(
description: description?.trim() || null,
folder: folder?.trim() || null,
order: snippetOrder,
hostFilter: hostFilter ? JSON.stringify(hostFilter) : null,
};
const result = await db.insert(snippets).values(insertData).returning();
@@ -1238,6 +1240,7 @@ router.put(
description: string | null;
folder: string | null;
order: number;
hostFilter: string | null;
}> = {
updatedAt: sql`CURRENT_TIMESTAMP`,
};
@@ -1251,6 +1254,10 @@ router.put(
if (updateData.folder !== undefined)
updateFields.folder = updateData.folder?.trim() || null;
if (updateData.order !== undefined) updateFields.order = updateData.order;
if (updateData.hostFilter !== undefined)
updateFields.hostFilter = updateData.hostFilter
? JSON.stringify(updateData.hostFilter)
: null;
await db
.update(snippets)
+117 -6
View File
@@ -521,6 +521,7 @@ router.post("/oidc-config", authenticateJWT, async (req, res) => {
name_path,
scopes,
allowed_users,
admin_group,
} = req.body;
const isDisableRequest =
@@ -579,6 +580,7 @@ router.post("/oidc-config", authenticateJWT, async (req, res) => {
name_path,
scopes: scopes || "openid email profile",
allowed_users: allowed_users || "",
admin_group: admin_group || "",
};
let encryptedConfig;
@@ -817,7 +819,7 @@ router.get("/oidc-config/admin", requireAdmin, async (req, res) => {
*/
router.get("/oidc/authorize", async (req, res) => {
try {
const { rememberMe } = req.query;
const { rememberMe, desktopCallbackPort } = req.query;
const origin = getRequestOriginWithForceHTTPS(req);
const backendCallbackUri = `${origin}/users/oidc/callback`;
@@ -840,7 +842,9 @@ router.get("/oidc/authorize", async (req, res) => {
const referer = req.get("Referer");
let frontendOrigin;
if (referer) {
if (desktopCallbackPort) {
frontendOrigin = `http://127.0.0.1:${desktopCallbackPort}/oidc-callback`;
} else if (referer) {
const refererUrl = new URL(referer);
frontendOrigin = `${refererUrl.protocol}//${refererUrl.host}`;
} else {
@@ -949,6 +953,18 @@ router.get("/oidc/callback", async (req, res) => {
config = JSON.parse(
(configRow as Record<string, unknown>).value as string,
);
if (config.client_secret?.startsWith("encrypted:")) {
config.client_secret = Buffer.from(
config.client_secret.substring(10),
"base64",
).toString("utf8");
} else if (config.client_secret?.startsWith("encoded:")) {
config.client_secret = Buffer.from(
config.client_secret.substring(8),
"base64",
).toString("utf8");
}
}
const tokenResponse = await fetch(config.token_url, {
@@ -1150,11 +1166,28 @@ router.get("/oidc/callback", async (req, res) => {
}
}
const oidcAllowRegistration =
(process.env.OIDC_ALLOW_REGISTRATION || "").trim().toLowerCase() ===
"true";
let oidcAutoProvision = false;
try {
const oidcProvRow = db.$client
.prepare(
"SELECT value FROM settings WHERE key = 'oidc_auto_provision'",
)
.get();
if (oidcProvRow) {
oidcAutoProvision =
(oidcProvRow as Record<string, unknown>).value === "true";
}
} catch {
// fall through to env var check
}
if (!isFirstUser && !oidcAllowRegistration) {
if (!oidcAutoProvision) {
oidcAutoProvision =
(process.env.OIDC_ALLOW_REGISTRATION || "").trim().toLowerCase() ===
"true";
}
if (!isFirstUser && !oidcAutoProvision) {
try {
const regRow = db.$client
.prepare(
@@ -1300,6 +1333,25 @@ router.get("/oidc/callback", async (req, res) => {
const userRecord = user[0];
// Sync admin status based on OIDC group membership
if (config.admin_group) {
const groups = (userInfo.groups || userInfo.roles || []) as string[];
const shouldBeAdmin = groups.includes(config.admin_group);
if (!!userRecord.isAdmin !== shouldBeAdmin) {
await db
.update(users)
.set({ isAdmin: shouldBeAdmin })
.where(eq(users.id, userRecord.id));
userRecord.isAdmin = shouldBeAdmin;
authLogger.info("OIDC admin status synced", {
operation: "oidc_admin_group_sync",
userId: userRecord.id,
group: config.admin_group,
isAdmin: shouldBeAdmin,
});
}
}
try {
await authManager.authenticateOIDCUser(userRecord.id, deviceInfo.type);
} catch (setupError) {
@@ -1333,6 +1385,8 @@ router.get("/oidc/callback", async (req, res) => {
const redirectUrl = new URL(frontendOrigin);
redirectUrl.searchParams.set("success", "true");
const isDesktopCallback = frontendOrigin.startsWith("http://127.0.0.1:");
const maxAge =
deviceInfo.type === "desktop" || deviceInfo.type === "mobile"
? 30 * 24 * 60 * 60 * 1000
@@ -1342,6 +1396,11 @@ router.get("/oidc/callback", async (req, res) => {
res.clearCookie("jwt", authManager.getClearCookieOptions(req));
if (isDesktopCallback) {
redirectUrl.searchParams.set("token", token);
return res.redirect(redirectUrl.toString());
}
return res
.cookie("jwt", token, authManager.getSecureCookieOptions(req, maxAge))
.redirect(redirectUrl.toString());
@@ -1883,6 +1942,56 @@ router.patch("/registration-allowed", authenticateJWT, async (req, res) => {
}
});
router.get("/oidc-auto-provision", async (_req, res) => {
try {
const row = db.$client
.prepare("SELECT value FROM settings WHERE key = 'oidc_auto_provision'")
.get();
res.json({
enabled: row ? (row as Record<string, unknown>).value === "true" : false,
});
} catch (err) {
authLogger.error("Failed to get OIDC auto-provision setting", err);
res
.status(500)
.json({ error: "Failed to get OIDC auto-provision setting" });
}
});
router.patch("/oidc-auto-provision", authenticateJWT, async (req, res) => {
const userId = (req as AuthenticatedRequest).userId;
try {
const user = await db.select().from(users).where(eq(users.id, userId));
if (!user || user.length === 0 || !user[0].isAdmin) {
return res.status(403).json({ error: "Not authorized" });
}
const { enabled } = req.body;
if (typeof enabled !== "boolean") {
return res.status(400).json({ error: "Invalid value for enabled" });
}
const existing = db.$client
.prepare("SELECT value FROM settings WHERE key = 'oidc_auto_provision'")
.get();
if (existing) {
db.$client
.prepare(
"UPDATE settings SET value = ? WHERE key = 'oidc_auto_provision'",
)
.run(enabled ? "true" : "false");
} else {
db.$client
.prepare(
"INSERT INTO settings (key, value) VALUES ('oidc_auto_provision', ?)",
)
.run(enabled ? "true" : "false");
}
res.json({ enabled });
} catch (err) {
authLogger.error("Failed to set OIDC auto-provision", err);
res.status(500).json({ error: "Failed to set OIDC auto-provision" });
}
});
/**
* @openapi
* /users/password-login-allowed:
@@ -1954,6 +2063,8 @@ router.patch("/password-login-allowed", authenticateJWT, async (req, res) => {
"INSERT OR REPLACE INTO settings (key, value) VALUES ('allow_password_login', ?)",
)
.run(allowed ? "true" : "false");
const { saveMemoryDatabaseToFile } = await import("../db/index.js");
await saveMemoryDatabaseToFile();
res.json({ allowed });
} catch (err) {
authLogger.error("Failed to set password login allowed", err);
@@ -75,6 +75,7 @@ const clientOptions = {
vnc: {
"swap-red-blue": false,
cursor: "remote",
security: "any",
width: 1280,
height: 720,
},
+214 -23
View File
@@ -7,6 +7,8 @@ import { SimpleDBOps } from "../utils/simple-db-ops.js";
import { getDb } from "../database/db/index.js";
import { hosts } from "../database/db/schema.js";
import { eq } from "drizzle-orm";
import { Client } from "ssh2";
import net from "net";
import type { AuthenticatedRequest } from "../../types/index.js";
const router = express.Router();
@@ -16,18 +18,52 @@ const authManager = AuthManager.getInstance();
router.use(authManager.createAuthMiddleware());
/**
* POST /guacamole/token
* Generate an encrypted connection token for guacamole-lite
*
* Body: {
* type: "rdp" | "vnc" | "telnet",
* hostname: string,
* port?: number,
* username?: string,
* password?: string,
* domain?: string,
* // Additional protocol-specific options
* }
* @openapi
* /guacamole/token:
* post:
* summary: Generate an encrypted Guacamole connection token
* description: Creates an AES-256-CBC encrypted token for guacamole-lite with the given connection parameters
* tags:
* - Guacamole
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - type
* - hostname
* properties:
* type:
* type: string
* enum: [rdp, vnc, telnet]
* hostname:
* type: string
* port:
* type: integer
* username:
* type: string
* password:
* type: string
* domain:
* type: string
* responses:
* 200:
* description: Encrypted connection token
* content:
* application/json:
* schema:
* type: object
* properties:
* token:
* type: string
* 400:
* description: Invalid request
* 500:
* description: Server error
*/
router.post("/token", async (req, res) => {
try {
@@ -108,6 +144,17 @@ router.post("/token", async (req, res) => {
* schema:
* type: integer
* description: Host ID to connect to
* requestBody:
* required: false
* content:
* application/json:
* schema:
* type: object
* properties:
* protocol:
* type: string
* enum: [rdp, vnc, telnet]
* description: Override the host's default connection type
* responses:
* 200:
* description: Connection token generated successfully
@@ -169,13 +216,27 @@ router.post(
}
}
const connectionType = (host.connectionType as string) || "ssh";
const requestedProtocol = req.body?.protocol as string | undefined;
const connectionType =
requestedProtocol || (host.connectionType as string);
if (!["rdp", "vnc", "telnet"].includes(connectionType)) {
return res.status(400).json({
error: `Connection type '${connectionType}' is not supported for remote desktop. Only RDP, VNC, and Telnet are supported.`,
});
}
const protocolEnabledMap: Record<string, boolean> = {
rdp: !!host.enableRdp,
vnc: !!host.enableVnc,
telnet: !!host.enableTelnet,
};
if (!protocolEnabledMap[connectionType]) {
return res.status(400).json({
error: `${connectionType.toUpperCase()} is not enabled for this host.`,
});
}
let guacConfig: Record<string, unknown> = {};
if (host.guacamoleConfig) {
try {
@@ -192,20 +253,149 @@ router.post(
}
}
if (guacConfig.dpi != null) {
const parsed = parseInt(String(guacConfig.dpi), 10);
guacConfig.dpi =
Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
}
let token: string;
const hostname = host.ip as string;
const port = host.port as number;
const username = (host.username as string) || "";
const password = (host.password as string) || "";
const domain = (host.domain as string) || "";
let hostname = host.ip as string;
let port = host.port as number;
let username: string;
let password: string;
switch (connectionType) {
case "rdp":
username =
(host.rdpUser as string) || (host.username as string) || "";
password =
(host.rdpPassword as string) || (host.password as string) || "";
port = (host.rdpPort as number) || port || 3389;
break;
case "vnc":
username = (host.vncUser as string) || "";
password =
(host.vncPassword as string) || (host.password as string) || "";
port = (host.vncPort as number) || port || 5900;
break;
case "telnet":
username = (host.telnetUser as string) || "";
password =
(host.telnetPassword as string) || (host.password as string) || "";
port = (host.telnetPort as number) || port || 23;
break;
default:
username = "";
password = "";
}
const domain =
(host.rdpDomain as string) || (host.domain as string) || "";
// Establish SSH tunnel if jump hosts are configured
let jumpHosts: Array<{ hostId: number }> = [];
if (host.jumpHosts) {
try {
jumpHosts =
typeof host.jumpHosts === "string"
? JSON.parse(host.jumpHosts as string)
: (host.jumpHosts as Array<{ hostId: number }>);
} catch {
jumpHosts = [];
}
}
if (jumpHosts.length > 0) {
try {
const { resolveHostById } = await import("../ssh/host-resolver.js");
const jumpHost = await resolveHostById(jumpHosts[0].hostId, userId);
if (jumpHost) {
const tunnelPort = await new Promise<number>((resolve, reject) => {
const sshClient = new Client();
sshClient.on("ready", () => {
const server = net.createServer((sock) => {
sshClient.forwardOut(
"127.0.0.1",
0,
hostname,
port,
(err, stream) => {
if (err) {
sock.destroy();
return;
}
sock.pipe(stream).pipe(sock);
},
);
});
server.listen(0, "127.0.0.1", () => {
const addr = server.address() as net.AddressInfo;
// Auto-cleanup after 1 hour
setTimeout(
() => {
server.close();
sshClient.end();
},
60 * 60 * 1000,
);
resolve(addr.port);
});
});
sshClient.on("error", reject);
const connectOpts: Record<string, unknown> = {
host: jumpHost.ip,
port: jumpHost.port || 22,
username: jumpHost.username,
readyTimeout: 30000,
};
if (jumpHost.key) {
connectOpts.privateKey = jumpHost.key;
if (jumpHost.keyPassword)
connectOpts.passphrase = jumpHost.keyPassword;
} else if (jumpHost.password) {
connectOpts.password = jumpHost.password;
}
sshClient.connect(connectOpts);
});
hostname = "127.0.0.1";
port = tunnelPort;
guacLogger.info("SSH tunnel established for guacamole", {
operation: "guac_ssh_tunnel",
hostId,
tunnelPort,
});
}
} catch (tunnelError) {
guacLogger.error("Failed to establish SSH tunnel", tunnelError, {
operation: "guac_ssh_tunnel_error",
hostId,
});
return res.status(500).json({
error: "Failed to establish SSH tunnel to remote host",
});
}
}
switch (connectionType) {
case "rdp":
if (guacConfig["enable-drive"] && !guacConfig["drive-path"]) {
guacConfig["drive-path"] = "/drive";
guacConfig["create-drive-path"] = true;
}
token = tokenService.createRdpToken(hostname, username, password, {
port: port || 3389,
port,
domain,
security: (host.security as string) || undefined,
"ignore-cert": (host.ignoreCert as boolean) || false,
security:
(host.rdpSecurity as string) ||
(host.security as string) ||
undefined,
"ignore-cert":
host.rdpIgnoreCert !== undefined
? !!host.rdpIgnoreCert
: host.ignoreCert !== undefined
? !!host.ignoreCert
: true,
...guacConfig,
});
break;
@@ -215,14 +405,15 @@ router.post(
username || undefined,
password,
{
port: port || 5900,
port,
security: "any",
...guacConfig,
},
);
break;
case "telnet":
token = tokenService.createTelnetToken(hostname, username, password, {
port: port || 23,
port,
...guacConfig,
});
break;
+3
View File
@@ -0,0 +1,3 @@
{
"type": "module"
}
+6 -3
View File
@@ -10,6 +10,7 @@ interface ResolvedCredentials {
key?: Buffer;
keyPassword?: string;
authType?: string;
certPublicKey?: string;
}
interface HostConfig {
@@ -76,11 +77,13 @@ export class SSHAuthManager {
resolvedCredentials = {
username: (cred.username as string) || hostConfig.username,
password: (cred.password as string) || undefined,
key: cred.privateKey
? Buffer.from(cred.privateKey as string)
: undefined,
key:
cred.key || cred.privateKey
? Buffer.from((cred.key || cred.privateKey) as string)
: undefined,
keyPassword: (cred.keyPassword as string) || undefined,
authType: (cred.authType as string) || "none",
certPublicKey: (cred.certPublicKey as string) || undefined,
};
}
} else {
+9 -34
View File
@@ -24,39 +24,6 @@ const activeSessions = new Map<string, SSHSession>();
const wss = new WebSocketServer({
host: "0.0.0.0",
port: 30009,
verifyClient: async (info) => {
try {
let token: string | undefined;
const cookieHeader = info.req.headers.cookie;
if (cookieHeader) {
const match = cookieHeader.match(/(?:^|;\s*)jwt=([^;]+)/);
if (match) token = decodeURIComponent(match[1]);
}
if (!token) {
const authHeader = info.req.headers.authorization;
if (authHeader?.startsWith("Bearer ")) {
token = authHeader.slice("Bearer ".length);
}
}
if (!token) {
return false;
}
const authManager = AuthManager.getInstance();
const decoded = await authManager.verifyJWTToken(token);
if (!decoded || !decoded.userId) {
return false;
}
return true;
} catch {
return false;
}
},
});
async function detectShell(
@@ -173,7 +140,9 @@ async function createJumpHostChain(
const credential = credentials[0];
resolvedCredentials = {
password: credential.password as string | undefined,
sshKey: credential.privateKey as string | undefined,
sshKey: (credential.key || credential.privateKey) as
| string
| undefined,
keyPassword: credential.keyPassword as string | undefined,
authType: credential.authType as string | undefined,
};
@@ -257,6 +226,12 @@ wss.on("connection", async (ws: WebSocket, req) => {
}
}
if (!token) {
const urlObj = new URL(req.url || "", "http://localhost");
const qp = urlObj.searchParams.get("token");
if (qp) token = qp;
}
if (!token) {
ws.close(1008, "Authentication required");
return;
+37 -9
View File
@@ -139,10 +139,7 @@ async function resolveJumpHost(
): Promise<JumpHostConfig | null> {
try {
const hostResults = await SimpleDBOps.select(
getDb()
.select()
.from(hosts)
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId))),
getDb().select().from(hosts).where(eq(hosts.id, hostId)),
"ssh_data",
userId,
);
@@ -152,8 +149,37 @@ async function resolveJumpHost(
}
const host = hostResults[0];
const ownerId = (host.userId || userId) as string;
if (host.credentialId) {
if (userId !== ownerId) {
try {
const { SharedCredentialManager } =
await import("../utils/shared-credential-manager.js");
const sharedCredManager = SharedCredentialManager.getInstance();
const sharedCred = await sharedCredManager.getSharedCredentialForUser(
hostId,
userId,
);
if (sharedCred) {
return {
...host,
password: sharedCred.password,
key: sharedCred.key,
keyPassword: sharedCred.keyPassword,
keyType: sharedCred.keyType,
authType: sharedCred.key
? "key"
: sharedCred.password
? "password"
: "none",
} as JumpHostConfig;
}
} catch {
// fall through to owner credential lookup
}
}
const credentials = await SimpleDBOps.select(
getDb()
.select()
@@ -161,11 +187,11 @@ async function resolveJumpHost(
.where(
and(
eq(sshCredentials.id, host.credentialId as number),
eq(sshCredentials.userId, userId),
eq(sshCredentials.userId, ownerId),
),
),
"ssh_credentials",
userId,
ownerId,
);
if (credentials.length > 0) {
@@ -173,7 +199,7 @@ async function resolveJumpHost(
return {
...host,
password: credential.password as string | undefined,
key: credential.privateKey as string | undefined,
key: (credential.key || credential.privateKey) as string | undefined,
keyPassword: credential.keyPassword as string | undefined,
keyType: credential.keyType as string | undefined,
authType: credential.authType as string | undefined,
@@ -714,7 +740,9 @@ app.post("/docker/ssh/connect", async (req, res) => {
const credential = credentials[0];
resolvedCredentials = {
password: credential.password as string | undefined,
sshKey: credential.privateKey as string | undefined,
sshKey: (credential.key || credential.privateKey) as
| string
| undefined,
keyPassword: credential.keyPassword as string | undefined,
authType: credential.authType as string | undefined,
};
@@ -2970,7 +2998,7 @@ app.get("/docker/containers/:sessionId/:containerId/logs", async (req, res) => {
session.activeOperations++;
try {
let command = `docker logs ${containerId}`;
let command = `docker logs ${containerId} 2>&1`;
if (tail && tail > 0) {
command += ` --tail ${Math.floor(tail)}`;
+199 -13
View File
@@ -151,10 +151,7 @@ async function resolveJumpHost(
): Promise<JumpHostConfig | null> {
try {
const hostResults = await SimpleDBOps.select(
getDb()
.select()
.from(hosts)
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId))),
getDb().select().from(hosts).where(eq(hosts.id, hostId)),
"ssh_data",
userId,
);
@@ -164,8 +161,37 @@ async function resolveJumpHost(
}
const host = hostResults[0];
const ownerId = (host.userId || userId) as string;
if (host.credentialId) {
if (userId !== ownerId) {
try {
const { SharedCredentialManager } =
await import("../utils/shared-credential-manager.js");
const sharedCredManager = SharedCredentialManager.getInstance();
const sharedCred = await sharedCredManager.getSharedCredentialForUser(
hostId,
userId,
);
if (sharedCred) {
return {
...host,
password: sharedCred.password,
key: sharedCred.key,
keyPassword: sharedCred.keyPassword,
keyType: sharedCred.keyType,
authType: sharedCred.key
? "key"
: sharedCred.password
? "password"
: "none",
} as JumpHostConfig;
}
} catch {
// fall through to owner credential lookup
}
}
const credentials = await SimpleDBOps.select(
getDb()
.select()
@@ -173,11 +199,11 @@ async function resolveJumpHost(
.where(
and(
eq(sshCredentials.id, host.credentialId as number),
eq(sshCredentials.userId, userId),
eq(sshCredentials.userId, ownerId),
),
),
"ssh_credentials",
userId,
ownerId,
);
if (credentials.length > 0) {
@@ -185,7 +211,7 @@ async function resolveJumpHost(
return {
...host,
password: credential.password as string | undefined,
key: credential.privateKey as string | undefined,
key: (credential.key || credential.privateKey) as string | undefined,
keyPassword: credential.keyPassword as string | undefined,
keyType: credential.keyType as string | undefined,
authType: credential.authType as string | undefined,
@@ -428,21 +454,33 @@ function execWithSudo(
command: string,
sudoPassword: string,
): Promise<{ stdout: string; stderr: string; code: number }> {
return execWithSudoBuffer(session, command, sudoPassword).then((result) => ({
stdout: result.stdout.toString("utf8"),
stderr: result.stderr,
code: result.code,
}));
}
function execWithSudoBuffer(
session: SSHSession,
command: string,
sudoPassword: string,
): Promise<{ stdout: Buffer; stderr: string; code: number }> {
return new Promise((resolve) => {
const escapedPassword = sudoPassword.replace(/'/g, "'\"'\"'");
const sudoCommand = `echo '${escapedPassword}' | sudo -S ${command} 2>&1`;
execChannel(session, sudoCommand, (err, stream) => {
if (err) {
resolve({ stdout: "", stderr: err.message, code: 1 });
resolve({ stdout: Buffer.alloc(0), stderr: err.message, code: 1 });
return;
}
let stdout = "";
const stdoutChunks: Buffer[] = [];
let stderr = "";
stream.on("data", (chunk: Buffer) => {
stdout += chunk.toString();
stdoutChunks.push(chunk);
});
stream.stderr.on("data", (chunk: Buffer) => {
@@ -450,12 +488,22 @@ function execWithSudo(
});
stream.on("close", (code: number) => {
stdout = stdout.replace(/\[sudo\] password for .+?:\s*/g, "");
let stdout = Buffer.concat(stdoutChunks);
const sudoPromptMatch = stdout
.toString("utf8", 0, Math.min(stdout.length, 256))
.match(/^\[sudo\] password for .+?:\s*/);
if (sudoPromptMatch) {
stdout = stdout.subarray(Buffer.byteLength(sudoPromptMatch[0]));
}
resolve({ stdout, stderr, code: code || 0 });
});
stream.on("error", (streamErr: Error) => {
resolve({ stdout, stderr: streamErr.message, code: 1 });
resolve({
stdout: Buffer.concat(stdoutChunks),
stderr: streamErr.message,
code: 1,
});
});
});
});
@@ -862,7 +910,13 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
);
// Resolve credentials server-side when frontend doesn't provide them
let resolvedCredentials = { password, sshKey, keyPassword, authType };
let resolvedCredentials = {
password,
sshKey,
keyPassword,
authType,
sudoPassword: undefined as string | undefined,
};
if (hostId && userId && !password && !sshKey) {
try {
const { resolveHostById } = await import("./host-resolver.js");
@@ -873,6 +927,7 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
sshKey: resolvedHost.key,
keyPassword: resolvedHost.keyPassword,
authType: resolvedHost.authType,
sudoPassword: resolvedHost.sudoPassword as string | undefined,
};
connectionLogs.push(
createConnectionLog(
@@ -900,6 +955,7 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
sshKey: resolvedHost.key,
keyPassword: resolvedHost.keyPassword,
authType: resolvedHost.authType,
sudoPassword: resolvedHost.sudoPassword as string | undefined,
};
connectionLogs.push(
createConnectionLog(
@@ -1194,6 +1250,7 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
activeOperations: 0,
channelOpener: new ChannelOpenSerializer(),
userId,
sudoPassword: resolvedCredentials.sudoPassword,
};
scheduleSessionCleanup(sessionId);
res.json({
@@ -3058,6 +3115,42 @@ app.get("/ssh/file_manager/ssh/readFile", (req, res) => {
stream.on("close", (code) => {
if (code !== 0) {
const isPermissionDenied = errorData
.toLowerCase()
.includes("permission denied");
if (isPermissionDenied && sshConn.sudoPassword) {
execWithSudoBuffer(
sshConn,
`cat '${escapedPath}'`,
sshConn.sudoPassword,
)
.then((result) => {
if (result.code !== 0) {
return res.status(403).json({
error: `Permission denied: ${result.stderr || result.stdout.toString("utf8")}`,
needsSudo: true,
});
}
const sudoData = result.stdout;
const isBinary = detectBinary(sudoData);
res.json({
content: isBinary
? sudoData.toString("base64")
: sudoData.toString("utf8"),
isBinary,
size: sudoData.length,
});
})
.catch(() => {
res
.status(403)
.json({ error: "Permission denied", needsSudo: true });
});
return;
}
fileLogger.error(
`SSH readFile command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
);
@@ -3490,12 +3583,47 @@ app.post("/ssh/file_manager/ssh/writeFile", async (req, res) => {
}
});
} else {
const isPermDenied = errorData
.toLowerCase()
.includes("permission denied");
if (isPermDenied && sshConn.sudoPassword) {
execWithSudo(
sshConn,
`bash -c "echo '${base64Content}' | base64 -d > '${escapedPath}' && echo SUCCESS"`,
sshConn.sudoPassword,
)
.then(({ stdout, code: sudoCode }) => {
if (sudoCode === 0 && stdout.includes("SUCCESS")) {
restoreOriginalMode(null, () => {
if (!res.headersSent) {
res.json({
message: "File written successfully",
path: filePath,
});
}
});
} else if (!res.headersSent) {
res
.status(403)
.json({ error: "Permission denied", needsSudo: true });
}
})
.catch(() => {
if (!res.headersSent) {
res
.status(403)
.json({ error: "Permission denied", needsSudo: true });
}
});
return;
}
fileLogger.error(
`Fallback write failed with code ${code}: ${errorData}`,
);
if (!res.headersSent) {
res.status(500).json({
error: `Write failed: ${errorData}`,
needsSudo: isPermDenied,
toast: { type: "error", message: `Write failed: ${errorData}` },
});
}
@@ -4870,6 +4998,64 @@ app.post("/ssh/file_manager/ssh/downloadFile", async (req, res) => {
});
});
app.post("/ssh/file_manager/ssh/downloadFileStream", async (req, res) => {
const { sessionId, path: filePath } = req.body;
const userId = (req as AuthenticatedRequest).userId;
if (!sessionId || !filePath) {
return res.status(400).json({ error: "Missing download parameters" });
}
const sshConn = sshSessions[sessionId];
if (!sshConn?.isConnected) {
return res
.status(400)
.json({ error: "SSH session not found or not connected" });
}
if (!verifySessionOwnership(sshConn, userId)) {
return res.status(403).json({ error: "Session access denied" });
}
sshConn.lastActive = Date.now();
try {
const sftp = await getSessionSftp(sshConn);
const stats = await new Promise<{ size: number; isFile: () => boolean }>(
(resolve, reject) => {
sftp.stat(filePath, (err, s) => (err ? reject(err) : resolve(s)));
},
);
if (!stats.isFile()) {
return res.status(400).json({ error: "Cannot download directories" });
}
const fileName = filePath.split("/").pop() || "download";
res.setHeader("Content-Type", "application/octet-stream");
res.setHeader(
"Content-Disposition",
`attachment; filename="${encodeURIComponent(fileName)}"`,
);
res.setHeader("Content-Length", String(stats.size));
const readStream = sftp.createReadStream(filePath);
readStream.on("error", (err) => {
if (!res.headersSent) {
res.status(500).json({ error: `Download failed: ${err.message}` });
} else {
res.destroy();
}
});
readStream.pipe(res);
} catch (err) {
if (!res.headersSent) {
res
.status(500)
.json({ error: `Download failed: ${(err as Error).message}` });
}
}
});
/**
* @openapi
* /ssh/file_manager/ssh/copyItem:
+54 -3
View File
@@ -75,8 +75,55 @@ export async function resolveHostById(
if (host.credentialId) {
const ownerId = (host.userId || userId) as string;
try {
// Try shared credential first for non-owner users
// Try user's own override credential first
if (userId !== ownerId) {
try {
const { hostAccess } = await import("../database/db/schema.js");
const accessRecords = await db
.select()
.from(hostAccess)
.where(
and(eq(hostAccess.hostId, hostId), eq(hostAccess.userId, userId)),
)
.limit(1);
const overrideCredId = accessRecords[0]?.overrideCredentialId as
| number
| null;
if (overrideCredId) {
const userCreds = await SimpleDBOps.select(
db
.select()
.from(sshCredentials)
.where(
and(
eq(sshCredentials.id, overrideCredId),
eq(sshCredentials.userId, userId),
),
),
"ssh_credentials",
userId,
);
if (userCreds.length > 0) {
const cred = userCreds[0] as Record<string, unknown>;
host.password = cred.password;
host.key = cred.key;
host.keyPassword = cred.keyPassword;
host.keyType = cred.keyType;
if (!host.overrideCredentialUsername) {
host.username = cred.username;
}
host.authType = cred.key
? "key"
: cred.password
? "password"
: "none";
return host as unknown as SSHHost;
}
}
} catch {
// fall through to shared credential
}
try {
const { SharedCredentialManager } =
await import("../utils/shared-credential-manager.js");
@@ -126,13 +173,17 @@ export async function resolveHostById(
if (credentials.length > 0) {
const cred = credentials[0] as Record<string, unknown>;
host.password = cred.password;
host.key = cred.key;
// Prefer the normalised private key; fall back to raw key field
host.key = (cred.privateKey || cred.key) as string | null;
host.keyPassword = cred.keyPassword;
host.keyType = cred.keyType;
// CA-signed certificate for cert-based auth
(host as Record<string, unknown>).certPublicKey =
cred.certPublicKey || null;
if (!host.overrideCredentialUsername) {
host.username = cred.username;
}
host.authType = cred.key ? "key" : cred.password ? "password" : "none";
host.authType = host.key ? "key" : host.password ? "password" : "none";
}
} catch (e) {
sshLogger.warn("Failed to resolve credential for host", {
+94 -24
View File
@@ -1,8 +1,11 @@
// OPKSSH certificate authentication workarounds for ssh2.
// SSH certificate authentication workarounds for ssh2.
// ssh2 doesn't support OpenSSH cert auth natively — this module grafts
// the certificate onto the parsed key, wraps ECDSA signing to convert
// DER → SSH wire format, and patches Protocol.authPK to use the base
// algorithm in the signature wrapper (required by OpenSSH's sshkey_check_sigtype).
//
// setupOPKSSHCertAuth: for OPKSSH-issued ephemeral certificates (no passphrase)
// setupCACertAuth: for user-managed CA-signed -cert.pub files (passphrase supported)
import type {
AnyAuthMethod,
@@ -62,44 +65,39 @@ type OPKSSHNextAuthHandler = (
authInfo: AuthenticationType | AnyAuthMethod | false,
) => void;
export async function setupOPKSSHCertAuth(
// ── Internal implementation ──────────────────────────────────────────────────
// Grafts an OpenSSH certificate onto an already-parsed private key object and
// patches the ssh2 client so that certificate-based publickey auth succeeds.
async function _applyCertToConnection(
config: ConnectConfig,
client: Client,
token: OPKSSHToken,
username: string,
privKey: ParsedPrivateKey,
certStr: string,
): Promise<void> {
const { createRequire } = await import("node:module");
const esmRequire = createRequire(import.meta.url);
const {
utils: { parseKey },
} = esmRequire("ssh2");
const parsed = parseKey(Buffer.from(token.privateKey));
if (parsed instanceof Error || !parsed) {
throw new Error("Failed to parse OPKSSH private key");
}
const privKey = (
Array.isArray(parsed) ? parsed[0] : parsed
) as ParsedPrivateKey;
// Extract cert type and blob from the stored certificate
const certParts = token.sshCert.trim().split(/\s+/);
const certParts = certStr.trim().split(/\s+/);
if (certParts.length < 2) {
throw new Error(
"Invalid certificate format: expected '<type> <base64>' string",
);
}
const certType = certParts[0];
privKey.type = certType;
const certBlob = Buffer.from(certParts[1], "base64");
// Replace the internal public SSH blob with the full certificate
// Graft cert type and blob onto the parsed private key
privKey.type = certType;
const pubSSHSym = Object.getOwnPropertySymbols(privKey).find(
(s) => String(s) === "Symbol(Public key SSH)",
);
if (!pubSSHSym) {
throw new Error(
"Cannot find public SSH symbol on parsed key, ssh2 internals may have changed",
"Cannot find public SSH symbol on parsed key; ssh2 internals may have changed",
);
}
privKey[pubSSHSym] = certBlob;
// Wrap sign() for ECDSA cert keys
// Wrap sign() for ECDSA cert keys (DER → SSH wire format)
if (privKey.type.startsWith("ecdsa-")) {
const origSign = privKey.sign.bind(privKey);
privKey.sign = (data: Buffer, algo?: string) => {
@@ -145,7 +143,7 @@ export async function setupOPKSSHCertAuth(
certAuthAttempted = true;
next({
type: "publickey",
username,
username: (config as Record<string, unknown>).username as string,
key: privKey as unknown as PublicKeyAuthMethod["key"],
});
} else {
@@ -296,3 +294,75 @@ export async function setupOPKSSHCertAuth(
return connectedClient;
};
}
// ── Public API ───────────────────────────────────────────────────────────────
/**
* Set up OPKSSH certificate authentication on an ssh2 Client.
* The OPKSSH private key is assumed to be unencrypted (no passphrase).
*/
export async function setupOPKSSHCertAuth(
config: ConnectConfig,
client: Client,
token: OPKSSHToken,
username: string,
): Promise<void> {
const { createRequire } = await import("node:module");
const esmRequire = createRequire(import.meta.url);
const {
utils: { parseKey },
} = esmRequire("ssh2");
// Store username in config so the authHandler can access it
(config as Record<string, unknown>).username = username;
const parsed = parseKey(Buffer.from(token.privateKey));
if (parsed instanceof Error || !parsed) {
throw new Error("Failed to parse OPKSSH private key");
}
const privKey = (
Array.isArray(parsed) ? parsed[0] : parsed
) as ParsedPrivateKey;
await _applyCertToConnection(config, client, privKey, token.sshCert);
}
/**
* Set up CA-signed certificate authentication on an ssh2 Client.
* Supports passphrase-protected private keys.
* The cert content is the full text of the -cert.pub file
* (e.g. "ssh-ed25519-cert-v01@openssh.com AAAA...").
*/
export async function setupCACertAuth(
config: ConnectConfig,
client: Client,
privateKey: Buffer | string,
certPublicKey: string,
username: string,
passphrase?: string,
): Promise<void> {
const { createRequire } = await import("node:module");
const esmRequire = createRequire(import.meta.url);
const {
utils: { parseKey },
} = esmRequire("ssh2");
// Store username in config so the authHandler can access it
(config as Record<string, unknown>).username = username;
const keyBuf = Buffer.isBuffer(privateKey)
? privateKey
: Buffer.from(privateKey, "utf8");
const parsed = passphrase ? parseKey(keyBuf, passphrase) : parseKey(keyBuf);
if (parsed instanceof Error || !parsed) {
const errMsg = parsed instanceof Error ? parsed.message : "unknown error";
throw new Error(`Failed to parse private key for CA cert auth: ${errMsg}`);
}
const privKey = (
Array.isArray(parsed) ? parsed[0] : parsed
) as ParsedPrivateKey;
await _applyCertToConnection(config, client, privKey, certPublicKey);
}
+33 -7
View File
@@ -75,10 +75,7 @@ async function resolveJumpHost(
): Promise<JumpHostConfig | null> {
try {
const hostResults = await SimpleDBOps.select(
getDb()
.select()
.from(hosts)
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId))),
getDb().select().from(hosts).where(eq(hosts.id, hostId)),
"ssh_data",
userId,
);
@@ -88,8 +85,37 @@ async function resolveJumpHost(
}
const host = hostResults[0];
const ownerId = (host.userId || userId) as string;
if (host.credentialId) {
if (userId !== ownerId) {
try {
const { SharedCredentialManager } =
await import("../utils/shared-credential-manager.js");
const sharedCredManager = SharedCredentialManager.getInstance();
const sharedCred = await sharedCredManager.getSharedCredentialForUser(
hostId,
userId,
);
if (sharedCred) {
return {
...host,
password: sharedCred.password,
key: sharedCred.key,
keyPassword: sharedCred.keyPassword,
keyType: sharedCred.keyType,
authType: sharedCred.key
? "key"
: sharedCred.password
? "password"
: "none",
} as JumpHostConfig;
}
} catch {
// fall through to owner credential lookup
}
}
const credentials = await SimpleDBOps.select(
getDb()
.select()
@@ -97,11 +123,11 @@ async function resolveJumpHost(
.where(
and(
eq(sshCredentials.id, host.credentialId as number),
eq(sshCredentials.userId, userId),
eq(sshCredentials.userId, ownerId),
),
),
"ssh_credentials",
userId,
ownerId,
);
if (credentials.length > 0) {
@@ -109,7 +135,7 @@ async function resolveJumpHost(
return {
...host,
password: credential.password as string | undefined,
key: credential.privateKey as string | undefined,
key: (credential.key || credential.privateKey) as string | undefined,
keyPassword: credential.keyPassword as string | undefined,
keyType: credential.keyType as string | undefined,
authType: credential.authType as string | undefined,
+272 -102
View File
@@ -1,5 +1,14 @@
import { WebSocketServer, WebSocket, type RawData } from "ws";
import { Client, type ClientChannel, type PseudoTtyOptions } from "ssh2";
import ssh2Pkg, {
type Client as SSHClientType,
type ClientChannel,
type PseudoTtyOptions,
type ParsedKey,
type SignCallback,
type SigningRequestOptions,
type IdentityCallback,
} from "ssh2";
const { Client, BaseAgent, utils: ssh2Utils } = ssh2Pkg;
import net from "net";
import dgram from "dgram";
import { SSH_ALGORITHMS } from "../utils/ssh-algorithms.js";
@@ -22,9 +31,44 @@ import { sessionManager } from "./terminal-session-manager.js";
import {
detectTmux,
attachOrCreateTmuxSession,
queryNewestTmuxSession,
waitForTmuxSession,
} from "./tmux-helper.js";
class MemoryAgent extends BaseAgent {
private key: ParsedKey;
constructor(key: ParsedKey) {
super();
this.key = key;
}
getIdentities(cb: IdentityCallback<ParsedKey>): void {
cb(null, [this.key]);
}
sign(
pubKey: ParsedKey | Buffer | string,
data: Buffer,
optionsOrCb: SigningRequestOptions | SignCallback,
cb?: SignCallback,
): void {
const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb!;
const options = typeof optionsOrCb === "function" ? {} : optionsOrCb;
try {
const algo =
options.hash === "sha256"
? "rsa-sha2-256"
: options.hash === "sha512"
? "rsa-sha2-512"
: undefined;
const signature = this.key.sign(data, algo);
callback(null, signature);
} catch (err) {
callback(err instanceof Error ? err : new Error(String(err)));
}
}
}
async function performPortKnocking(
host: string,
sequence: Array<{ port: number; protocol?: string; delay?: number }>,
@@ -145,10 +189,7 @@ async function resolveJumpHost(
});
try {
const hostResults = await SimpleDBOps.select(
getDb()
.select()
.from(hosts)
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId))),
getDb().select().from(hosts).where(eq(hosts.id, hostId)),
"ssh_data",
userId,
);
@@ -158,8 +199,37 @@ async function resolveJumpHost(
}
const host = hostResults[0];
const ownerId = (host.userId || userId) as string;
if (host.credentialId) {
if (userId !== ownerId) {
try {
const { SharedCredentialManager } =
await import("../utils/shared-credential-manager.js");
const sharedCredManager = SharedCredentialManager.getInstance();
const sharedCred = await sharedCredManager.getSharedCredentialForUser(
hostId,
userId,
);
if (sharedCred) {
return {
...host,
password: sharedCred.password,
key: sharedCred.key,
keyPassword: sharedCred.keyPassword,
keyType: sharedCred.keyType,
authType: sharedCred.key
? "key"
: sharedCred.password
? "password"
: "none",
} as JumpHostConfig;
}
} catch {
// fall through to owner credential lookup
}
}
const credentials = await SimpleDBOps.select(
getDb()
.select()
@@ -167,11 +237,11 @@ async function resolveJumpHost(
.where(
and(
eq(sshCredentials.id, host.credentialId as number),
eq(sshCredentials.userId, userId),
eq(sshCredentials.userId, ownerId),
),
),
"ssh_credentials",
userId,
ownerId,
);
if (credentials.length > 0) {
@@ -179,7 +249,7 @@ async function resolveJumpHost(
return {
...host,
password: credential.password as string | undefined,
key: credential.privateKey as string | undefined,
key: (credential.key || credential.privateKey) as string | undefined,
keyPassword: credential.keyPassword as string | undefined,
keyType: credential.keyType as string | undefined,
authType: credential.authType as string | undefined,
@@ -202,13 +272,13 @@ async function createJumpHostChain(
jumpHosts: Array<{ hostId: number }>,
userId: string,
socks5Config?: SOCKS5Config | null,
): Promise<Client | null> {
): Promise<SSHClientType | null> {
if (!jumpHosts || jumpHosts.length === 0) {
return null;
}
let currentClient: Client | null = null;
const clients: Client[] = [];
let currentClient: SSHClientType | null = null;
const clients: SSHClientType[] = [];
try {
const jumpHostConfigs = await Promise.all(
@@ -364,52 +434,6 @@ async function createJumpHostChain(
const wss = new WebSocketServer({
port: 30002,
verifyClient: async (info) => {
try {
let token: string | undefined;
const cookieHeader = info.req.headers.cookie;
if (cookieHeader) {
const match = cookieHeader.match(/(?:^|;\s*)jwt=([^;]+)/);
if (match) token = decodeURIComponent(match[1]);
}
if (!token) {
const authHeader = info.req.headers.authorization;
if (authHeader?.startsWith("Bearer ")) {
token = authHeader.slice("Bearer ".length);
}
}
if (!token) {
return false;
}
const payload = await authManager.verifyJWTToken(token);
if (!payload) {
return false;
}
if (payload.pendingTOTP) {
return false;
}
const existingConnections = userConnections.get(payload.userId);
if (existingConnections && existingConnections.size >= 10) {
return false;
}
return true;
} catch (error) {
sshLogger.error("WebSocket authentication error", error, {
operation: "websocket_auth_error",
ip: info.req.socket.remoteAddress,
});
return false;
}
},
});
wss.on("connection", async (ws: WebSocket, req) => {
@@ -432,6 +456,12 @@ wss.on("connection", async (ws: WebSocket, req) => {
}
}
if (!token) {
const urlObj = new URL(req.url || "", "http://localhost");
const qp = urlObj.searchParams.get("token");
if (qp) token = qp;
}
if (!token) {
ws.close(1008, "Authentication required");
return;
@@ -483,9 +513,9 @@ wss.on("connection", async (ws: WebSocket, req) => {
});
let currentSessionId: string | null = null;
let sshConn: Client | null = null;
let sshConn: SSHClientType | null = null;
let sshStream: ClientChannel | null = null;
let lastJumpClient: Client | null = null;
let lastJumpClient: SSHClientType | null = null;
let keyboardInteractiveFinish: ((responses: string[]) => void) | null = null;
let totpPromptSent = false;
let totpTimeout: NodeJS.Timeout | null = null;
@@ -806,8 +836,8 @@ wss.on("connection", async (ws: WebSocket, req) => {
: null;
if (session?.sshStream) {
const existingName = tmuxData.sessionName || undefined;
attachOrCreateTmuxSession(session.sshStream, existingName);
if (existingName) {
attachOrCreateTmuxSession(session.sshStream, existingName);
session.tmuxSessionName = existingName;
sshLogger.info("User selected tmux session to attach", {
operation: "tmux_user_attach",
@@ -821,30 +851,51 @@ wss.on("connection", async (ws: WebSocket, req) => {
}),
);
} else {
// New session from picker -- query name after startup
const newName = `termix-${session.hostId}-${Date.now().toString(36).slice(-4)}`;
attachOrCreateTmuxSession(session.sshStream, undefined, newName);
const sshConn = session.sshConn;
setTimeout(async () => {
const sessionName = sshConn
? await queryNewestTmuxSession(sshConn)
: null;
session.tmuxSessionName = sessionName;
sshLogger.info("User requested new tmux session", {
operation: "tmux_user_create",
sessionName,
hostId: session.hostId,
});
ws.send(
JSON.stringify({
type: "tmux_session_created",
sessionName,
}),
);
}, 500);
if (sshConn) {
(async () => {
const confirmed = await waitForTmuxSession(sshConn, newName);
session.tmuxSessionName = confirmed;
sshLogger.info("User requested new tmux session", {
operation: "tmux_user_create",
sessionName: confirmed,
hostId: session.hostId,
});
ws.send(
JSON.stringify({
type: "tmux_session_created",
sessionName: confirmed,
}),
);
})();
}
}
}
break;
}
case "tmux_detach": {
const session = currentSessionId
? sessionManager.getSession(currentSessionId)
: null;
if (session?.sshConn && session.tmuxSessionName) {
const tmuxName = session.tmuxSessionName;
session.sshStream?.write("\x02d");
session.tmuxSessionName = null;
sshLogger.info("User detached from tmux session", {
operation: "tmux_user_detach",
sessionName: tmuxName,
hostId: session.hostId,
});
ws.send(
JSON.stringify({ type: "tmux_detached", sessionName: tmuxName }),
);
}
break;
}
case "totp_response": {
const totpData = data as TOTPResponseData;
if (keyboardInteractiveFinish && totpData?.code) {
@@ -1239,6 +1290,7 @@ wss.on("connection", async (ws: WebSocket, req) => {
keyPassword,
keyType,
authType,
certPublicKey: undefined as string | undefined,
};
const authMethodNotAvailable = false;
if (id && userId && !password && !key) {
@@ -1253,6 +1305,8 @@ wss.on("connection", async (ws: WebSocket, req) => {
keyPassword: keyPassword || resolvedHost.keyPassword,
keyType: resolvedHost.keyType,
authType: resolvedHost.authType,
certPublicKey: (resolvedHost as unknown as Record<string, unknown>)
.certPublicKey as string | undefined,
};
sendLog(
"auth",
@@ -1280,6 +1334,8 @@ wss.on("connection", async (ws: WebSocket, req) => {
keyPassword: keyPassword || resolvedHost.keyPassword,
keyType: resolvedHost.keyType,
authType: resolvedHost.authType,
certPublicKey: (resolvedHost as unknown as Record<string, unknown>)
.certPublicKey as string | undefined,
};
}
} catch (error) {
@@ -1580,6 +1636,7 @@ wss.on("connection", async (ws: WebSocket, req) => {
JSON.stringify({
type: "disconnected",
message: "Connection lost",
graceful: true,
}),
);
}
@@ -1645,31 +1702,27 @@ wss.on("connection", async (ws: WebSocket, req) => {
"tmux is not installed on the remote host. Falling back to standard shell.",
}),
);
// tmux unavailable, run commands in plain shell
runPostShellCommands(0);
} else if (detection.sessions.length === 0) {
attachOrCreateTmuxSession(stream);
// Query the name tmux assigned after a short delay
setTimeout(async () => {
const sessionName = await queryNewestTmuxSession(conn);
const session = sessionManager.getSession(boundSessionId);
if (session) {
session.tmuxSessionName = sessionName;
}
sshLogger.info("Created new tmux session", {
operation: "tmux_new_session",
sessionName,
hostId: id,
});
ws.send(
JSON.stringify({
type: "tmux_session_created",
sessionName,
}),
);
}, 500);
// Wait for tmux to start before running commands inside it
runPostShellCommands(500);
const newName = `termix-${id}-${Date.now().toString(36).slice(-4)}`;
attachOrCreateTmuxSession(stream, undefined, newName);
const confirmed = await waitForTmuxSession(conn, newName);
const session = sessionManager.getSession(boundSessionId);
if (session) {
session.tmuxSessionName = confirmed;
}
sshLogger.info("Created new tmux session", {
operation: "tmux_new_session",
sessionName: confirmed,
hostId: id,
});
ws.send(
JSON.stringify({
type: "tmux_session_created",
sessionName: confirmed,
}),
);
runPostShellCommands(0);
} else if (detection.sessions.length === 1) {
attachOrCreateTmuxSession(stream, detection.sessions[0].name);
const sessionName = detection.sessions[0].name;
@@ -2233,6 +2286,45 @@ wss.on("connection", async (ws: WebSocket, req) => {
if (resolvedCredentials.password) {
connectConfig.password = resolvedCredentials.password;
}
// Apply CA-signed certificate if one is stored in the credential
if (
resolvedCredentials.certPublicKey &&
resolvedCredentials.certPublicKey.trim()
) {
try {
const { setupCACertAuth } = await import("./opkssh-cert-auth.js");
await setupCACertAuth(
connectConfig,
sshConn,
connectConfig.privateKey as Buffer,
resolvedCredentials.certPublicKey,
username,
resolvedCredentials.keyPassword,
);
sendLog("auth", "info", "CA certificate authentication configured");
sshLogger.info("CA cert auth configured", {
operation: "ca_cert_auth_configured",
userId,
hostId: id,
});
} catch (certError) {
sendLog(
"auth",
"warning",
"CA certificate setup failed falling back to key-only auth",
);
sshLogger.warn("CA cert auth setup failed", {
operation: "ca_cert_auth_setup_failed",
userId,
hostId: id,
error:
certError instanceof Error
? certError.message
: String(certError),
});
}
}
} catch (keyError) {
sshLogger.error("SSH key format error: " + keyError.message);
ws.send(
@@ -2312,6 +2404,28 @@ wss.on("connection", async (ws: WebSocket, req) => {
return;
}
if (
hostConfig.terminalConfig?.agentForwarding &&
connectConfig.privateKey
) {
try {
const parsed = ssh2Utils.parseKey(
connectConfig.privateKey as Buffer,
connectConfig.passphrase as string | undefined,
);
if (parsed && !(parsed instanceof Error)) {
connectConfig.agent = new MemoryAgent(parsed);
connectConfig.agentForward = true;
sendLog("auth", "info", "SSH agent forwarding enabled");
}
} catch {
sshLogger.warn("Failed to set up agent forwarding", {
operation: "agent_forward_setup",
hostId: id,
});
}
}
if (
hostConfig.portKnockSequence &&
hostConfig.portKnockSequence.length > 0
@@ -2350,6 +2464,62 @@ wss.on("connection", async (ws: WebSocket, req) => {
hostConfig.jumpHosts.length > 0 &&
hostConfig.userId;
// Cloudflare Tunnel: connect via WebSocket proxy
const cfConfig = hostConfig.terminalConfig as
| Record<string, unknown>
| undefined;
if (cfConfig?.cfAccessClientId && cfConfig?.cfAccessClientSecret) {
try {
const WebSocket = (await import("ws")).default;
const cfHostname = (cfConfig.cfTunnelHostname as string) || ip;
const wsUrl = `wss://${cfHostname}/cdn-cgi/access/ssh-connect`;
const cfWs = new WebSocket(wsUrl, {
headers: {
"CF-Access-Client-Id": cfConfig.cfAccessClientId as string,
"CF-Access-Client-Secret": cfConfig.cfAccessClientSecret as string,
},
});
await new Promise<void>((resolve, reject) => {
cfWs.on("open", () => resolve());
cfWs.on("error", (err) => reject(err));
setTimeout(
() => reject(new Error("Cloudflare tunnel timeout")),
30000,
);
});
const { Duplex } = await import("stream");
const duplexStream = new Duplex({
read() {},
write(chunk, _encoding, callback) {
cfWs.send(chunk, callback);
},
});
cfWs.on("message", (data) => duplexStream.push(data));
cfWs.on("close", () => duplexStream.push(null));
connectConfig.sock =
duplexStream as unknown as typeof connectConfig.sock;
sendLog("handshake", "info", "Connected via Cloudflare Tunnel");
} catch (cfError) {
sshLogger.error("Cloudflare tunnel connection failed", cfError, {
operation: "cf_tunnel_connect",
hostId: id,
});
ws.send(
JSON.stringify({
type: "error",
message:
"Cloudflare tunnel connection failed: " +
(cfError instanceof Error ? cfError.message : "Unknown error"),
}),
);
cleanupAuthState(connectionTimeout);
return;
}
}
if (hasJumpHosts) {
try {
const jumpClient = await createJumpHostChain(
+30 -1
View File
@@ -103,6 +103,7 @@ const TMUX_OPTS =
`set -gq mouse on` +
` \\; set -gq history-limit 50000` +
` \\; set -gq set-clipboard on` +
` \\; set -gq aggressive-resize on` +
` \\; set -gq mode-keys vi` +
` \\; bind-key -T copy-mode-vi MouseDragEnd1Pane send-keys -X stop-selection` +
` \\; bind-key -T copy-mode-vi Enter send-keys -X copy-selection-and-cancel` +
@@ -110,6 +111,32 @@ const TMUX_OPTS =
` 'if -F "#{pane_in_mode}"` +
` "display-message -d 2500 \\"Adjust selection and press Enter to copy\\""'`;
/**
* Wait for a tmux session to appear by polling via exec channel.
* Returns the session name once found, or null on timeout.
*/
export async function waitForTmuxSession(
conn: Client,
sessionName: string,
timeoutMs = 5000,
intervalMs = 100,
): Promise<string | null> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
await execCommand(
conn,
`tmux has-session -t ${shellEscape(sessionName)} 2>/dev/null`,
);
return sessionName;
} catch {
// session not ready yet
}
await new Promise((resolve) => setTimeout(resolve, intervalMs));
}
return null;
}
/**
* Write tmux attach or new-session command to the interactive shell stream.
* Uses && exit so the shell only closes if tmux started successfully.
@@ -117,12 +144,14 @@ const TMUX_OPTS =
export function attachOrCreateTmuxSession(
stream: ClientChannel,
existingSessionName?: string,
newSessionName?: string,
): void {
let command: string;
if (existingSessionName) {
command = `tmux ${TMUX_OPTS} \\; attach-session -t ${shellEscape(existingSessionName)} && exit\r`;
} else {
command = `tmux ${TMUX_OPTS} \\; new-session && exit\r`;
const nameFlag = newSessionName ? ` -s ${shellEscape(newSessionName)}` : "";
command = `tmux ${TMUX_OPTS} \\; new-session${nameFlag} && exit\r`;
}
sshLogger.info("Writing tmux command to shell", {
+19 -4
View File
@@ -1674,7 +1674,9 @@ async function connectSSHTunnel(
const credential = credentials[0];
resolvedEndpointCredentials = {
password: credential.password as string | undefined,
sshKey: credential.privateKey as string | undefined,
sshKey: (credential.key || credential.privateKey) as
| string
| undefined,
keyPassword: credential.keyPassword as string | undefined,
keyType: credential.keyType as string | undefined,
authMethod: credential.authType as string,
@@ -2695,9 +2697,22 @@ app.post(
res.json({ message: "Connection request received", tunnelName });
operation.finally(() => {
pendingTunnelOperations.delete(tunnelName);
});
operation
.catch((err) => {
tunnelLogger.error("Tunnel operation failed", err, {
operation: "tunnel_operation_failed",
tunnelName,
});
broadcastTunnelStatus(tunnelName, {
connected: false,
status: CONNECTION_STATES.FAILED,
reason: err instanceof Error ? err.message : "Unknown error",
});
tunnelConnecting.delete(tunnelName);
})
.finally(() => {
pendingTunnelOperations.delete(tunnelName);
});
} catch (error) {
tunnelLogger.error("Failed to process tunnel connect", error, {
operation: "tunnel_connect",
+22 -19
View File
@@ -137,7 +137,8 @@ import {
},
);
await import("./database/database.js");
const dbServer = await import("./database/database.js");
await (dbServer as unknown as { serverReady: Promise<void> }).serverReady;
await import("./ssh/terminal.js");
await import("./ssh/tunnel.js");
await import("./ssh/file-manager.js");
@@ -194,29 +195,31 @@ import {
duration: Date.now() - initStartTime,
});
process.on("SIGINT", () => {
systemLogger.info(
"Received SIGINT signal, initiating graceful shutdown...",
{ operation: "shutdown" },
);
const gracefulShutdown = async (signal: string) => {
systemLogger.info(`Received ${signal}, initiating graceful shutdown...`, {
operation: "shutdown",
});
try {
const { saveMemoryDatabaseToFile } =
await import("./database/db/index.js");
await saveMemoryDatabaseToFile();
systemLogger.info("Database saved to disk before exit", {
operation: "shutdown_db_saved",
});
} catch (error) {
systemLogger.error("Failed to save database during shutdown", error, {
operation: "shutdown_db_save_failed",
});
}
process.exit(0);
});
};
process.on("SIGTERM", () => {
systemLogger.info(
"Received SIGTERM signal, initiating graceful shutdown...",
{ operation: "shutdown" },
);
process.exit(0);
});
process.on("SIGINT", () => gracefulShutdown("SIGINT"));
process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
process.on("message", (msg: { type?: string }) => {
if (msg?.type === "shutdown") {
systemLogger.info(
"Received IPC shutdown, initiating graceful shutdown...",
{ operation: "shutdown" },
);
process.exit(0);
gracefulShutdown("IPC shutdown");
}
});
+155
View File
@@ -0,0 +1,155 @@
import swaggerJSDoc from "swagger-jsdoc";
import path from "path";
import { fileURLToPath } from "url";
import { promises as fs } from "fs";
import { systemLogger } from "./utils/logger.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const swaggerOptions: swaggerJSDoc.Options = {
definition: {
openapi: "3.0.3",
info: {
title: "Termix API",
version: "0.0.0",
description: "Termix Backend API Reference",
},
servers: [
{
url: "http://localhost:30001",
description: "Main database and authentication server",
},
{
url: "http://localhost:30003",
description: "SSH tunnel management server",
},
{
url: "http://localhost:30004",
description: "SSH file manager server",
},
{
url: "http://localhost:30005",
description: "Server statistics and monitoring server",
},
{
url: "http://localhost:30006",
description: "Dashboard server",
},
{
url: "http://localhost:30007",
description: "Docker management server",
},
],
components: {
securitySchemes: {
bearerAuth: {
type: "http",
scheme: "bearer",
bearerFormat: "JWT",
},
},
schemas: {
Error: {
type: "object",
properties: {
error: { type: "string" },
details: { type: "string" },
},
},
},
},
security: [
{
bearerAuth: [],
},
],
tags: [
{
name: "Alerts",
description: "System alerts and notifications management",
},
{
name: "Credentials",
description: "SSH credential management",
},
{
name: "Network Topology",
description: "Network topology visualization and management",
},
{
name: "RBAC",
description: "Role-based access control for host sharing",
},
{
name: "Snippets",
description: "Command snippet management",
},
{
name: "Terminal",
description: "Terminal command history",
},
{
name: "Users",
description: "User management and authentication",
},
{
name: "Dashboard",
description: "Dashboard statistics and activity",
},
{
name: "Docker",
description: "Docker container management",
},
{
name: "SSH Tunnels",
description: "SSH tunnel connection management",
},
{
name: "Server Stats",
description: "Server status monitoring and metrics collection",
},
{
name: "File Manager",
description: "SSH file management operations",
},
],
},
apis: [
path.join(__dirname, "database", "routes", "*.js").replace(/\\/g, "/"),
path.join(__dirname, "dashboard.js").replace(/\\/g, "/"),
path.join(__dirname, "ssh", "*.js").replace(/\\/g, "/"),
path.join(__dirname, "guacamole", "routes.js").replace(/\\/g, "/"),
],
};
async function generateOpenAPISpec() {
try {
systemLogger.info("Generating OpenAPI specification", {
operation: "openapi_generate_start",
});
const swaggerSpec = swaggerJSDoc(swaggerOptions);
const outputPath = path.join(__dirname, "..", "..", "..", "openapi.json");
await fs.writeFile(
outputPath,
JSON.stringify(swaggerSpec, null, 2),
"utf-8",
);
systemLogger.success("OpenAPI specification generated", {
operation: "openapi_generate_success",
});
} catch (error) {
systemLogger.error("Failed to generate OpenAPI specification", error, {
operation: "openapi_generation",
});
process.exit(1);
}
}
generateOpenAPISpec();
export { swaggerOptions, generateOpenAPISpec };
@@ -1,5 +1,5 @@
import { db } from "../database/db/index.js";
import { sshCredentials } from "../database/db/schema.js";
import { sshCredentials, sharedCredentials } from "../database/db/schema.js";
import { eq, and, or, isNull } from "drizzle-orm";
import { DataCrypto } from "./data-crypto.js";
import { SystemCrypto } from "./system-crypto.js";
@@ -64,7 +64,7 @@ export class CredentialSystemEncryptionMigration {
cred.keyPassword,
userDEK,
cred.id.toString(),
"key_password",
"keyPassword",
)
: null;
@@ -105,6 +105,11 @@ export class CredentialSystemEncryptionMigration {
})
.where(eq(sshCredentials.id, cred.id));
await db
.update(sharedCredentials)
.set({ needsReEncryption: true })
.where(eq(sharedCredentials.originalCredentialId, cred.id));
migrated++;
} catch (error) {
databaseLogger.warn(
@@ -103,6 +103,27 @@ export class LazyFieldEncryption {
}
}
// Guac hosts migrated from single-protocol: rdpPassword/vncPassword/telnetPassword
// columns were populated by copying the encrypted `password` blob. Try decrypting
// under the original field name before giving up.
if (
fieldName === "rdpPassword" ||
fieldName === "vncPassword" ||
fieldName === "telnetPassword"
) {
try {
const decrypted = FieldCrypto.decryptField(
fieldValue,
userKEK,
recordId,
"password",
);
return decrypted;
} catch {
// not encrypted as "password" either
}
}
const sensitiveFields = [
"totpSecret",
"totpBackupCodes",
+24 -3
View File
@@ -1,7 +1,9 @@
import crypto from "crypto";
import type { ConnectConfig, CipherAlgorithm } from "ssh2";
// Maps SSH cipher names to their OpenSSL equivalents (as used by ssh2 internally)
const availableCiphers = new Set(crypto.getCiphers());
// Maps SSH cipher names to their OpenSSL equivalents
const SSH_CIPHER_SSL_NAME: Partial<Record<CipherAlgorithm, string>> = {
"chacha20-poly1305@openssh.com": "chacha20",
"aes256-gcm@openssh.com": "aes-256-gcm",
@@ -15,12 +17,31 @@ const SSH_CIPHER_SSL_NAME: Partial<Record<CipherAlgorithm, string>> = {
"3des-cbc": "des-ede3-cbc",
};
const availableCiphers = new Set(crypto.getCiphers());
// Check if ssh2's native crypto binding is available (needed for chacha20-poly1305)
let ssh2BindingAvailable = false;
try {
require("ssh2/lib/protocol/crypto/build/Release/sshcrypto.node");
ssh2BindingAvailable = true;
} catch {
try {
// ESM fallback: check if chacha20 works via OpenSSL createCipheriv
crypto.createCipheriv("chacha20", Buffer.alloc(32), Buffer.alloc(16));
ssh2BindingAvailable = true;
} catch {
ssh2BindingAvailable = false;
}
}
function filterCiphers(list: CipherAlgorithm[]): CipherAlgorithm[] {
return list.filter((name) => {
const sslName = SSH_CIPHER_SSL_NAME[name];
return !sslName || availableCiphers.has(sslName);
if (!sslName) return true;
if (!availableCiphers.has(sslName)) return false;
// chacha20-poly1305 requires either native binding or working OpenSSL chacha20
if (name === "chacha20-poly1305@openssh.com" && !ssh2BindingAvailable) {
return false;
}
return true;
});
}
+21
View File
@@ -103,6 +103,27 @@ function detectKeyTypeFromContent(keyContent: string): string {
function detectPublicKeyTypeFromContent(publicKeyContent: string): string {
const content = publicKeyContent.trim();
// OpenSSH certificate types (must be checked before plain key types)
if (content.startsWith("ssh-ed25519-cert-v01@openssh.com ")) {
return "ssh-ed25519-cert-v01@openssh.com";
}
if (content.startsWith("ssh-rsa-cert-v01@openssh.com ")) {
return "ssh-rsa-cert-v01@openssh.com";
}
if (content.startsWith("ecdsa-sha2-nistp256-cert-v01@openssh.com ")) {
return "ecdsa-sha2-nistp256-cert-v01@openssh.com";
}
if (content.startsWith("ecdsa-sha2-nistp384-cert-v01@openssh.com ")) {
return "ecdsa-sha2-nistp384-cert-v01@openssh.com";
}
if (content.startsWith("ecdsa-sha2-nistp521-cert-v01@openssh.com ")) {
return "ecdsa-sha2-nistp521-cert-v01@openssh.com";
}
if (content.startsWith("sk-ssh-ed25519-cert-v01@openssh.com ")) {
return "sk-ssh-ed25519-cert-v01@openssh.com";
}
// Plain public keys
if (content.startsWith("ssh-rsa ")) {
return "ssh-rsa";
}