mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-29 22:55:24 +00:00
v26.10.3 (#1692)
* feat: shell controller, TabStage, layout and theme plugins with repair view * feat: move the classic layout into its own bundled plugin * feat: move color themes into a bundled themes plugin * fix: plugin tests and type checks work with a linked sdk * fix: home tab, layout switch and missing layout fallbacks for looks * chore: add classic layout and themes to the readme * chore: drop example plugin links from the plugin guide * feat: plugin filters by type, paged browse, hide plugins needing newer termix * feat: move desktop, status, import, audit and branding features into plugins * feat: host lock api so a plugin can load hosts from a config file (#1581) * chore: add hosts config to the plugin table * feat: login policy hook for plugins and optional https redirect (#1584) * chore: add login security to the plugin table * feat: api key socket tickets so a master can open remote sessions (#1654) * feat: sync moves to a plugin, desktop gets multiple accounts (#1580, #1654) * chore: add sync to the plugin table * feat: move the sync screens and wizard out of core into the plugin (#1580) * fix: add a neutral linked desktop hook for plugins (#1580) * fix: show the linked account's name and admin flag in the app (#1580) * feat: ssh transport providers, core ssh relay and plugin folders api * feat: support FIDO2 security keys through ssh agent * feat: add companion panels beside host tabs * feat: mTLS client certificates for desktop server links * feat: native web view for plugins in the desktop app * fix: detect the desktop link window by Electron's default user agent Fixes #1675 * fix: changelog for desktop link fix * fix: keep text primary keys in the plugin data export * fix: ship sharp binaries for Windows arm64 builds * feat: client cert on the sync link types (sdk 1.0.18) * chore: update translations * feat: themed title bar for the desktop app (#1690) * chore: changelog for the themed title bar * fix: draw the title bar in the sidebar color * feat: per host layout for the terminal panel bar * chore: sdk 1.0.19 for the panel bar layout * chore: bundle all 43 plugins for 26.10.3 * chore: update translations --------- Co-authored-by: SirHephaistos <60616553+SirHephaistos@users.noreply.github.com> Co-authored-by: Giovanny Aranda <garanda21@gmail.com>
This commit is contained in:
577 files changed
+76479
-101831
No files matched your search
@@ -5,12 +5,6 @@ import {
|
||||
createCurrentUserRepository,
|
||||
} from "../repositories/factory.js";
|
||||
import { apiLogger } from "../../utils/logger.js";
|
||||
import { exportFilename, toCsv, toNdjson } from "../../utils/audit-export.js";
|
||||
import {
|
||||
logAudit,
|
||||
getAuditUsername,
|
||||
getRequestMeta,
|
||||
} from "../../utils/audit-logger.js";
|
||||
|
||||
async function isAdminUser(userId: string | undefined): Promise<boolean> {
|
||||
if (!userId) return false;
|
||||
@@ -138,125 +132,4 @@ export function registerAuditLogRoutes(
|
||||
.json({ error: "Failed to fetch audit log actions" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /audit-logs/export:
|
||||
* get:
|
||||
* summary: Export audit logs
|
||||
* description: Streams the full filtered result set as CSV or NDJSON. Accepts the same filters as GET /audit-logs. Admin only. The export is itself audited.
|
||||
* tags:
|
||||
* - Audit
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: format
|
||||
* schema: { type: string, enum: [csv, ndjson], default: csv }
|
||||
* - in: query
|
||||
* name: userId
|
||||
* schema: { type: string }
|
||||
* - in: query
|
||||
* name: action
|
||||
* schema: { type: string }
|
||||
* - in: query
|
||||
* name: resourceType
|
||||
* schema: { type: string }
|
||||
* - in: query
|
||||
* name: success
|
||||
* schema: { type: string, enum: [true, false] }
|
||||
* - in: query
|
||||
* name: startDate
|
||||
* schema: { type: string, format: date-time }
|
||||
* - in: query
|
||||
* name: endDate
|
||||
* schema: { type: string, format: date-time }
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Audit log file.
|
||||
* 403:
|
||||
* description: Not authorized.
|
||||
* 500:
|
||||
* description: Failed to export audit logs.
|
||||
*/
|
||||
router.get("/audit-logs/export", authenticateJWT, async (req, res) => {
|
||||
const authReq = req as AuthenticatedRequest;
|
||||
try {
|
||||
if (!(await isAdminUser(authReq.userId))) {
|
||||
return res.status(403).json({ error: "Not authorized" });
|
||||
}
|
||||
|
||||
const format = req.query.format === "ndjson" ? "ndjson" : "csv";
|
||||
const { userId, action, resourceType, success, startDate, endDate } =
|
||||
req.query as Record<string, string | undefined>;
|
||||
const filters = {
|
||||
userId,
|
||||
action,
|
||||
resourceType,
|
||||
success:
|
||||
success !== undefined && success !== ""
|
||||
? success === "true"
|
||||
: undefined,
|
||||
startDate,
|
||||
endDate,
|
||||
};
|
||||
|
||||
res.setHeader(
|
||||
"Content-Type",
|
||||
format === "csv" ? "text/csv; charset=utf-8" : "application/x-ndjson",
|
||||
);
|
||||
res.setHeader(
|
||||
"Content-Disposition",
|
||||
`attachment; filename="${exportFilename(format, new Date())}"`,
|
||||
);
|
||||
|
||||
// Streamed in batches: an export is unbounded by definition, and the
|
||||
// whole point is to move data out before retention drops it.
|
||||
const BATCH = 500;
|
||||
let offset = 0;
|
||||
let exported = 0;
|
||||
|
||||
for (;;) {
|
||||
const rows = await createCurrentAuditLogRepository().listForExport({
|
||||
filters,
|
||||
limit: BATCH,
|
||||
offset,
|
||||
});
|
||||
if (rows.length === 0) break;
|
||||
|
||||
if (format === "csv") {
|
||||
// Header only on the first batch.
|
||||
const chunk = toCsv(rows);
|
||||
res.write(
|
||||
offset === 0 ? chunk : chunk.slice(chunk.indexOf("\n") + 1),
|
||||
);
|
||||
} else {
|
||||
res.write(toNdjson(rows));
|
||||
}
|
||||
|
||||
exported += rows.length;
|
||||
offset += rows.length;
|
||||
if (rows.length < BATCH) break;
|
||||
}
|
||||
|
||||
res.end();
|
||||
|
||||
// Reading the whole trail is itself worth recording.
|
||||
const { ipAddress, userAgent } = getRequestMeta(req);
|
||||
void logAudit({
|
||||
userId: authReq.userId!,
|
||||
username: await getAuditUsername(authReq.userId!),
|
||||
action: "export_audit_logs",
|
||||
resourceType: "audit_log",
|
||||
details: JSON.stringify({ format, exported, filters }),
|
||||
ipAddress,
|
||||
userAgent,
|
||||
success: true,
|
||||
});
|
||||
} catch (err) {
|
||||
apiLogger.error("Failed to export audit logs", err);
|
||||
if (!res.headersSent) {
|
||||
return res.status(500).json({ error: "Failed to export audit logs" });
|
||||
}
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
} from "../../auth/registry.js";
|
||||
import { isTrustedProxyAuthEnabled } from "../../utils/trusted-proxy-auth.js";
|
||||
import { LoginMethodError, type VerifiedIdentity } from "../../auth/types.js";
|
||||
import { rememberDeviceAllowed } from "../../auth/policy.js";
|
||||
|
||||
export interface PublicLoginMethod {
|
||||
id: string;
|
||||
@@ -243,7 +244,7 @@ export function registerAuthRoutes(router: Router): void {
|
||||
* /users/auth/methods:
|
||||
* get:
|
||||
* summary: List login methods
|
||||
* description: Public. The login methods with at least one enabled instance, for the login screen. Carries ids and labels only.
|
||||
* description: Public. The login methods with at least one enabled instance, for the login screen. Carries ids and labels only, plus rememberDevice, false when the login policy turned remember me off.
|
||||
* tags:
|
||||
* - Auth
|
||||
* responses:
|
||||
@@ -252,7 +253,10 @@ export function registerAuthRoutes(router: Router): void {
|
||||
*/
|
||||
router.get("/auth/methods", async (_req, res) => {
|
||||
try {
|
||||
res.json({ methods: await listPublicLoginMethods() });
|
||||
res.json({
|
||||
methods: await listPublicLoginMethods(),
|
||||
rememberDevice: rememberDeviceAllowed(),
|
||||
});
|
||||
} catch (error) {
|
||||
authLogger.error("Failed to list login methods", error);
|
||||
res.status(500).json({ error: "Failed to list login methods" });
|
||||
|
||||
@@ -1,98 +1,9 @@
|
||||
import type { Request, RequestHandler, Response, Router } from "express";
|
||||
import type { Request, Response, Router } from "express";
|
||||
import { databaseLogger } from "../../utils/logger.js";
|
||||
import { createCurrentSettingsRepository } from "../repositories/factory.js";
|
||||
import {
|
||||
BRANDING_KEYS,
|
||||
parseBrandingAppName,
|
||||
parseBrandingLogoDataUrl,
|
||||
parseBrandingTagline,
|
||||
resolveBrandingSettings,
|
||||
} from "./branding-settings.js";
|
||||
import { resolveBrandingSettings } from "./branding-settings.js";
|
||||
|
||||
const PATCHABLE_FIELDS = ["appName", "tagline", "logo"] as const;
|
||||
type PatchableField = (typeof PATCHABLE_FIELDS)[number];
|
||||
|
||||
function invalidField(res: Response, field: string): void {
|
||||
res.status(400).json({
|
||||
error: `Invalid value for ${field}`,
|
||||
code: "BRANDING_SETTINGS_INVALID",
|
||||
field,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a PATCH body and returns the settings-table writes/deletes it
|
||||
* implies, or null after the response has already been failed with a 400.
|
||||
* `logo: null` clears the custom logo (falls back to the bundled default).
|
||||
*/
|
||||
async function buildBrandingWrites(
|
||||
body: unknown,
|
||||
res: Response,
|
||||
): Promise<{
|
||||
writes: Array<{ key: string; value: string }>;
|
||||
deletes: string[];
|
||||
} | null> {
|
||||
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
||||
res.status(400).json({
|
||||
error: "Invalid request body",
|
||||
code: "BRANDING_SETTINGS_INVALID",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const field of Object.keys(body)) {
|
||||
if (!(PATCHABLE_FIELDS as readonly string[]).includes(field)) {
|
||||
res.status(400).json({
|
||||
error: `Unknown setting field: ${field}`,
|
||||
code: "BRANDING_SETTINGS_UNKNOWN_FIELD",
|
||||
field,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const input = body as Partial<Record<PatchableField, unknown>>;
|
||||
const writes: Array<{ key: string; value: string }> = [];
|
||||
const deletes: string[] = [];
|
||||
|
||||
if (input.appName !== undefined) {
|
||||
const appName = parseBrandingAppName(input.appName);
|
||||
if (appName === null) {
|
||||
invalidField(res, "appName");
|
||||
return null;
|
||||
}
|
||||
writes.push({ key: BRANDING_KEYS.appName, value: appName });
|
||||
}
|
||||
|
||||
if (input.tagline !== undefined) {
|
||||
const tagline = parseBrandingTagline(input.tagline);
|
||||
if (tagline === null) {
|
||||
invalidField(res, "tagline");
|
||||
return null;
|
||||
}
|
||||
writes.push({ key: BRANDING_KEYS.tagline, value: tagline });
|
||||
}
|
||||
|
||||
if (input.logo !== undefined) {
|
||||
if (input.logo === null) {
|
||||
deletes.push(BRANDING_KEYS.logo);
|
||||
} else {
|
||||
const logo = await parseBrandingLogoDataUrl(input.logo);
|
||||
if (logo === null) {
|
||||
invalidField(res, "logo");
|
||||
return null;
|
||||
}
|
||||
writes.push({ key: BRANDING_KEYS.logo, value: logo });
|
||||
}
|
||||
}
|
||||
|
||||
return { writes, deletes };
|
||||
}
|
||||
|
||||
export function registerBrandingRoutes(
|
||||
router: Router,
|
||||
requireAdmin: RequestHandler,
|
||||
): void {
|
||||
export function registerBrandingRoutes(router: Router): void {
|
||||
/**
|
||||
* @openapi
|
||||
* /users/branding:
|
||||
@@ -118,48 +29,4 @@ export function registerBrandingRoutes(
|
||||
res.status(500).json({ error: "Failed to load branding settings" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /users/branding:
|
||||
* patch:
|
||||
* summary: Update white-label branding (admin only)
|
||||
* description: Persists a partial update to appName, tagline and/or logo (a PNG/JPEG/WEBP data URL; pass null to clear the logo). Invalid values are rejected with a 400.
|
||||
* tags:
|
||||
* - Users
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated effective branding settings.
|
||||
* 400:
|
||||
* description: Invalid or unknown setting field.
|
||||
* 401:
|
||||
* description: Not authenticated.
|
||||
* 403:
|
||||
* description: Admin access required.
|
||||
* 500:
|
||||
* description: Failed to save branding settings.
|
||||
*/
|
||||
router.patch(
|
||||
"/branding",
|
||||
requireAdmin,
|
||||
async (req: Request, res: Response) => {
|
||||
const result = await buildBrandingWrites(req.body, res);
|
||||
if (result === null) return;
|
||||
|
||||
try {
|
||||
const settings = createCurrentSettingsRepository();
|
||||
if (result.writes.length > 0) {
|
||||
await settings.setMany(result.writes);
|
||||
}
|
||||
for (const key of result.deletes) {
|
||||
await settings.delete(key);
|
||||
}
|
||||
const resolved = await resolveBrandingSettings(settings);
|
||||
res.json(resolved);
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to save branding settings", err);
|
||||
res.status(500).json({ error: "Failed to save branding settings" });
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import sharp from "sharp";
|
||||
import { databaseLogger } from "../../utils/logger.js";
|
||||
import { consumeByName } from "../../plugins/registry.js";
|
||||
|
||||
/**
|
||||
* White-label branding: admin-configurable app name, logo and tagline shown
|
||||
@@ -20,25 +19,33 @@ export const BRANDING_KEYS = {
|
||||
} as const;
|
||||
|
||||
export const BRANDING_DEFAULT_APP_NAME = "Termix";
|
||||
const APP_NAME_MAX_LENGTH = 60;
|
||||
const TAGLINE_MAX_LENGTH = 160;
|
||||
|
||||
/**
|
||||
* Cap applies to the decoded image bytes, not the base64 text. The settings
|
||||
* table is fully cached in memory per backend process (see
|
||||
* settings-cache.ts), so an oversized logo would be permanently resident RAM
|
||||
* on every instance, not just a one-time upload cost.
|
||||
*/
|
||||
export const BRANDING_LOGO_MAX_BYTES = 750 * 1024;
|
||||
const BRANDING_LOGO_MAX_INPUT_PIXELS = 20_000_000;
|
||||
|
||||
interface SettingSource {
|
||||
get(key: string): Promise<string | null>;
|
||||
}
|
||||
|
||||
export const BRANDING_PROVIDER_NAME = "brandingProvider";
|
||||
|
||||
/** A plugin supplies branding by providing "<its id>.brandingProvider". */
|
||||
export type BrandingProvider = () =>
|
||||
Promise<BrandingSettings> | BrandingSettings;
|
||||
|
||||
export async function resolveBrandingSettings(
|
||||
settings: SettingSource,
|
||||
): Promise<BrandingSettings> {
|
||||
const provider = consumeByName<BrandingProvider>(BRANDING_PROVIDER_NAME);
|
||||
if (provider) {
|
||||
try {
|
||||
const provided = await provider();
|
||||
return {
|
||||
appName: provided.appName?.trim() || BRANDING_DEFAULT_APP_NAME,
|
||||
tagline: provided.tagline ?? "",
|
||||
logo: provided.logo || null,
|
||||
};
|
||||
} catch {
|
||||
// A broken provider falls back to the stored settings.
|
||||
}
|
||||
}
|
||||
const [appName, tagline, logo] = await Promise.all([
|
||||
settings.get(BRANDING_KEYS.appName),
|
||||
settings.get(BRANDING_KEYS.tagline),
|
||||
@@ -53,74 +60,3 @@ export async function resolveBrandingSettings(
|
||||
}
|
||||
|
||||
/** Trimmed, 1-60 chars. Falls back to the default when cleared. */
|
||||
export function parseBrandingAppName(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return BRANDING_DEFAULT_APP_NAME;
|
||||
if (trimmed.length > APP_NAME_MAX_LENGTH) return null;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/** Trimmed, 0-160 chars. An empty string means "use the built-in default". */
|
||||
export function parseBrandingTagline(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length > TAGLINE_MAX_LENGTH) return null;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates and re-encodes an uploaded logo. Only raster formats are
|
||||
* accepted (no SVG), sidestepping SVG-script XSS entirely rather than trying
|
||||
* to sanitize markup. The image is always re-encoded to PNG through sharp:
|
||||
* this both proves the payload is a genuine image (not a disguised file
|
||||
* behind a spoofed data-URL prefix) and strips any embedded metadata.
|
||||
*
|
||||
* Returns null on any validation failure; the caller is expected to reject
|
||||
* the request with a 400 without echoing back details of what was rejected.
|
||||
*/
|
||||
export async function parseBrandingLogoDataUrl(
|
||||
value: unknown,
|
||||
): Promise<string | null> {
|
||||
if (typeof value !== "string") return null;
|
||||
const match = value.match(
|
||||
/^data:image\/(png|jpe?g|webp);base64,([a-zA-Z0-9+/]+=*)$/,
|
||||
);
|
||||
if (!match) return null;
|
||||
|
||||
const [, , base64] = match;
|
||||
let buffer: Buffer;
|
||||
try {
|
||||
buffer = Buffer.from(base64, "base64");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (buffer.length === 0 || buffer.length > BRANDING_LOGO_MAX_BYTES * 4) {
|
||||
// Reject wildly oversized input before decoding it with sharp; the final
|
||||
// size check happens below on the re-encoded PNG.
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const source = sharp(buffer, {
|
||||
failOn: "error",
|
||||
limitInputPixels: BRANDING_LOGO_MAX_INPUT_PIXELS,
|
||||
});
|
||||
const metadata = await source.metadata();
|
||||
if (
|
||||
!metadata.format ||
|
||||
!["png", "jpeg", "webp"].includes(metadata.format)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const normalized = await source.rotate().png().toBuffer();
|
||||
if (normalized.length > BRANDING_LOGO_MAX_BYTES) return null;
|
||||
return `data:image/png;base64,${normalized.toString("base64")}`;
|
||||
} catch (err) {
|
||||
databaseLogger.warn("Rejected invalid branding logo upload", {
|
||||
operation: "branding_logo_invalid",
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,436 +0,0 @@
|
||||
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"),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,519 +0,0 @@
|
||||
import { getErrorMessage } from "../../utils/error-message.js";
|
||||
import type { Request, RequestHandler, Response, Router } from "express";
|
||||
import crypto from "crypto";
|
||||
import ssh2Pkg from "ssh2";
|
||||
import { authLogger } from "../../utils/logger.js";
|
||||
import {
|
||||
parsePublicKey,
|
||||
parseSSHKey,
|
||||
validateKeyPair,
|
||||
} from "../../utils/ssh-key-utils.js";
|
||||
import { resolveKeyReferences } from "../../hosts/stored-ssh-key.js";
|
||||
import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
|
||||
const { utils: ssh2Utils } = ssh2Pkg;
|
||||
|
||||
function generateSSHKeyPair(
|
||||
keyType: string,
|
||||
keySize?: number,
|
||||
passphrase?: string,
|
||||
): {
|
||||
success: boolean;
|
||||
privateKey?: string;
|
||||
publicKey?: string;
|
||||
error?: string;
|
||||
} {
|
||||
try {
|
||||
let ssh2Type = keyType;
|
||||
const options: {
|
||||
bits?: number;
|
||||
passphrase?: string;
|
||||
cipher?: string;
|
||||
} = {};
|
||||
|
||||
if (keyType === "ssh-rsa") {
|
||||
ssh2Type = "rsa";
|
||||
options.bits = keySize || 2048;
|
||||
} else if (keyType === "ssh-ed25519") {
|
||||
ssh2Type = "ed25519";
|
||||
} else if (keyType === "ecdsa-sha2-nistp256") {
|
||||
ssh2Type = "ecdsa";
|
||||
options.bits = 256;
|
||||
}
|
||||
|
||||
if (passphrase && passphrase.trim()) {
|
||||
options.passphrase = passphrase;
|
||||
options.cipher = "aes128-cbc";
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const keyPair = ssh2Utils.generateKeyPairSync(ssh2Type as any, options);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
privateKey: keyPair.private,
|
||||
publicKey: keyPair.public,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: getErrorMessage(error, "SSH key generation failed"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function registerCredentialKeyRoutes(
|
||||
router: Router,
|
||||
authenticateJWT: RequestHandler,
|
||||
requireCredentialViewPermission: RequestHandler,
|
||||
requireDataAccess: RequestHandler,
|
||||
): void {
|
||||
/**
|
||||
* @openapi
|
||||
* /credentials/detect-key-type:
|
||||
* post:
|
||||
* summary: Detect SSH key type
|
||||
* description: Detects the type of an SSH private key.
|
||||
* tags:
|
||||
* - Credentials
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* privateKey:
|
||||
* type: string
|
||||
* keyPassword:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Key type detection result.
|
||||
* 400:
|
||||
* description: Private key is required.
|
||||
* 500:
|
||||
* description: Failed to detect key type.
|
||||
*/
|
||||
router.post(
|
||||
"/detect-key-type",
|
||||
authenticateJWT,
|
||||
requireCredentialViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
if (!req.body?.privateKey || typeof req.body.privateKey !== "string") {
|
||||
return res.status(400).json({ error: "Private key is required" });
|
||||
}
|
||||
|
||||
try {
|
||||
const { key: privateKey, passphrase: keyPassword } =
|
||||
await resolveKeyReferences(
|
||||
(req as AuthenticatedRequest).userId,
|
||||
req.body.privateKey,
|
||||
req.body.keyPassword,
|
||||
);
|
||||
const keyInfo = parseSSHKey(privateKey, keyPassword);
|
||||
|
||||
const response = {
|
||||
success: keyInfo.success,
|
||||
keyType: keyInfo.keyType,
|
||||
detectedKeyType: keyInfo.keyType,
|
||||
hasPublicKey: !!keyInfo.publicKey,
|
||||
error: keyInfo.error || null,
|
||||
};
|
||||
|
||||
res.json(response);
|
||||
} catch (error) {
|
||||
authLogger.error("Failed to detect key type", error);
|
||||
res.status(500).json({
|
||||
error: getErrorMessage(error, "Failed to detect key type"),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /credentials/detect-public-key-type:
|
||||
* post:
|
||||
* summary: Detect SSH public key type
|
||||
* description: Detects the type of an SSH public key.
|
||||
* tags:
|
||||
* - Credentials
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* publicKey:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Key type detection result.
|
||||
* 400:
|
||||
* description: Public key is required.
|
||||
* 500:
|
||||
* description: Failed to detect public key type.
|
||||
*/
|
||||
router.post(
|
||||
"/detect-public-key-type",
|
||||
authenticateJWT,
|
||||
requireCredentialViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const { publicKey } = req.body;
|
||||
|
||||
if (!publicKey || typeof publicKey !== "string") {
|
||||
return res.status(400).json({ error: "Public key is required" });
|
||||
}
|
||||
|
||||
try {
|
||||
const keyInfo = parsePublicKey(publicKey);
|
||||
|
||||
const response = {
|
||||
success: keyInfo.success,
|
||||
keyType: keyInfo.keyType,
|
||||
detectedKeyType: keyInfo.keyType,
|
||||
error: keyInfo.error || null,
|
||||
};
|
||||
|
||||
res.json(response);
|
||||
} catch (error) {
|
||||
authLogger.error("Failed to detect public key type", error);
|
||||
res.status(500).json({
|
||||
error: getErrorMessage(error, "Failed to detect public key type"),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /credentials/validate-key-pair:
|
||||
* post:
|
||||
* summary: Validate SSH key pair
|
||||
* description: Validates if a given SSH private key and public key match.
|
||||
* tags:
|
||||
* - Credentials
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* privateKey:
|
||||
* type: string
|
||||
* publicKey:
|
||||
* type: string
|
||||
* keyPassword:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Key pair validation result.
|
||||
* 400:
|
||||
* description: Private key and public key are required.
|
||||
* 500:
|
||||
* description: Failed to validate key pair.
|
||||
*/
|
||||
router.post(
|
||||
"/validate-key-pair",
|
||||
authenticateJWT,
|
||||
requireCredentialViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const { privateKey, publicKey, keyPassword } = req.body;
|
||||
|
||||
if (!privateKey || typeof privateKey !== "string") {
|
||||
return res.status(400).json({ error: "Private key is required" });
|
||||
}
|
||||
|
||||
if (!publicKey || typeof publicKey !== "string") {
|
||||
return res.status(400).json({ error: "Public key is required" });
|
||||
}
|
||||
|
||||
try {
|
||||
const validationResult = validateKeyPair(
|
||||
privateKey,
|
||||
publicKey,
|
||||
keyPassword,
|
||||
);
|
||||
|
||||
const response = {
|
||||
isValid: validationResult.isValid,
|
||||
privateKeyType: validationResult.privateKeyType,
|
||||
publicKeyType: validationResult.publicKeyType,
|
||||
generatedPublicKey: validationResult.generatedPublicKey,
|
||||
error: validationResult.error || null,
|
||||
};
|
||||
|
||||
res.json(response);
|
||||
} catch (error) {
|
||||
authLogger.error("Failed to validate key pair", error);
|
||||
res.status(500).json({
|
||||
error: getErrorMessage(error, "Failed to validate key pair"),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /credentials/generate-key-pair:
|
||||
* post:
|
||||
* summary: Generate new SSH key pair
|
||||
* description: Generates a new SSH key pair.
|
||||
* tags:
|
||||
* - Credentials
|
||||
* requestBody:
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* keyType:
|
||||
* type: string
|
||||
* keySize:
|
||||
* type: integer
|
||||
* passphrase:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The new key pair.
|
||||
* 500:
|
||||
* description: Failed to generate SSH key pair.
|
||||
*/
|
||||
router.post(
|
||||
"/generate-key-pair",
|
||||
authenticateJWT,
|
||||
requireCredentialViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const { keyType = "ssh-ed25519", keySize = 2048, passphrase } = req.body;
|
||||
|
||||
try {
|
||||
const result = generateSSHKeyPair(keyType, keySize, passphrase);
|
||||
|
||||
if (result.success && result.privateKey && result.publicKey) {
|
||||
const response = {
|
||||
success: true,
|
||||
privateKey: result.privateKey,
|
||||
publicKey: result.publicKey,
|
||||
keyType: keyType,
|
||||
format: "ssh",
|
||||
algorithm: keyType,
|
||||
keySize: keyType === "ssh-rsa" ? keySize : undefined,
|
||||
curve: keyType === "ecdsa-sha2-nistp256" ? "nistp256" : undefined,
|
||||
};
|
||||
|
||||
res.json(response);
|
||||
} else {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: result.error || "Failed to generate SSH key pair",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
authLogger.error("Failed to generate key pair", error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: getErrorMessage(error, "Failed to generate key pair"),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /credentials/generate-public-key:
|
||||
* post:
|
||||
* summary: Generate public key from private key
|
||||
* description: Generates a public key from a given private key.
|
||||
* tags:
|
||||
* - Credentials
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* privateKey:
|
||||
* type: string
|
||||
* keyPassword:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The generated public key.
|
||||
* 400:
|
||||
* description: Private key is required.
|
||||
* 500:
|
||||
* description: Failed to generate public key.
|
||||
*/
|
||||
router.post(
|
||||
"/generate-public-key",
|
||||
authenticateJWT,
|
||||
requireCredentialViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
if (!req.body?.privateKey || typeof req.body.privateKey !== "string") {
|
||||
return res.status(400).json({ error: "Private key is required" });
|
||||
}
|
||||
|
||||
try {
|
||||
const { key: privateKey, passphrase: keyPassword } =
|
||||
await resolveKeyReferences(
|
||||
(req as AuthenticatedRequest).userId,
|
||||
req.body.privateKey,
|
||||
req.body.keyPassword,
|
||||
);
|
||||
let privateKeyObj;
|
||||
const parseAttempts = [];
|
||||
|
||||
try {
|
||||
privateKeyObj = crypto.createPrivateKey({
|
||||
key: privateKey,
|
||||
passphrase: keyPassword,
|
||||
});
|
||||
} catch (error) {
|
||||
parseAttempts.push(`Method 1 (with passphrase): ${error.message}`);
|
||||
}
|
||||
|
||||
if (!privateKeyObj) {
|
||||
try {
|
||||
privateKeyObj = crypto.createPrivateKey(privateKey);
|
||||
} catch (error) {
|
||||
parseAttempts.push(
|
||||
`Method 2 (without passphrase): ${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!privateKeyObj) {
|
||||
try {
|
||||
privateKeyObj = crypto.createPrivateKey({
|
||||
key: privateKey,
|
||||
format: "pem",
|
||||
type: "pkcs8",
|
||||
});
|
||||
} catch (error) {
|
||||
parseAttempts.push(`Method 3 (PKCS#8): ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!privateKeyObj &&
|
||||
privateKey.includes("-----BEGIN RSA PRIVATE KEY-----")
|
||||
) {
|
||||
try {
|
||||
privateKeyObj = crypto.createPrivateKey({
|
||||
key: privateKey,
|
||||
format: "pem",
|
||||
type: "pkcs1",
|
||||
});
|
||||
} catch (error) {
|
||||
parseAttempts.push(`Method 4 (PKCS#1): ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!privateKeyObj &&
|
||||
privateKey.includes("-----BEGIN EC PRIVATE KEY-----")
|
||||
) {
|
||||
try {
|
||||
privateKeyObj = crypto.createPrivateKey({
|
||||
key: privateKey,
|
||||
format: "pem",
|
||||
type: "sec1",
|
||||
});
|
||||
} catch (error) {
|
||||
parseAttempts.push(`Method 5 (SEC1): ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!privateKeyObj) {
|
||||
try {
|
||||
const keyInfo = parseSSHKey(privateKey, keyPassword);
|
||||
|
||||
if (keyInfo.success && keyInfo.publicKey) {
|
||||
const publicKeyString = String(keyInfo.publicKey);
|
||||
return res.json({
|
||||
success: true,
|
||||
publicKey: publicKeyString,
|
||||
keyType: keyInfo.keyType,
|
||||
});
|
||||
} else {
|
||||
parseAttempts.push(
|
||||
`SSH2 fallback: ${keyInfo.error || "No public key generated"}`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
parseAttempts.push(`SSH2 fallback exception: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!privateKeyObj) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: "Unable to parse private key. Tried multiple formats.",
|
||||
details: parseAttempts,
|
||||
});
|
||||
}
|
||||
|
||||
const publicKeyObj = crypto.createPublicKey(privateKeyObj);
|
||||
const publicKeyPem = publicKeyObj.export({
|
||||
type: "spki",
|
||||
format: "pem",
|
||||
});
|
||||
|
||||
const publicKeyString =
|
||||
typeof publicKeyPem === "string"
|
||||
? publicKeyPem
|
||||
: (publicKeyPem as Buffer).toString("utf8");
|
||||
|
||||
let keyType = "unknown";
|
||||
const asymmetricKeyType = privateKeyObj.asymmetricKeyType;
|
||||
|
||||
if (asymmetricKeyType === "rsa") {
|
||||
keyType = "ssh-rsa";
|
||||
} else if (asymmetricKeyType === "ed25519") {
|
||||
keyType = "ssh-ed25519";
|
||||
} else if (asymmetricKeyType === "ec") {
|
||||
keyType = "ecdsa-sha2-nistp256";
|
||||
}
|
||||
|
||||
let finalPublicKey = publicKeyString;
|
||||
let formatType = "pem";
|
||||
|
||||
try {
|
||||
const ssh2PrivateKey = ssh2Utils.parseKey(privateKey, keyPassword);
|
||||
if (!(ssh2PrivateKey instanceof Error)) {
|
||||
const publicKeyBuffer = ssh2PrivateKey.getPublicSSH();
|
||||
const base64Data = publicKeyBuffer.toString("base64");
|
||||
finalPublicKey = `${keyType} ${base64Data}`;
|
||||
formatType = "ssh";
|
||||
}
|
||||
} catch {
|
||||
// Ignore validation errors
|
||||
}
|
||||
|
||||
const response = {
|
||||
success: true,
|
||||
publicKey: finalPublicKey,
|
||||
keyType: keyType,
|
||||
format: formatType,
|
||||
};
|
||||
|
||||
res.json(response);
|
||||
} catch (error) {
|
||||
authLogger.error("Failed to generate public key", error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: getErrorMessage(error, "Failed to generate public key"),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -8,8 +8,6 @@ import { authLogger } from "../../utils/logger.js";
|
||||
import { PermissionManager } from "../../utils/permission-manager.js";
|
||||
import { AuthManager } from "../../utils/auth-manager.js";
|
||||
import { parseKeyForStorage } from "../../hosts/stored-ssh-key.js";
|
||||
import { registerCredentialKeyRoutes } from "./credential-key-routes.js";
|
||||
import { registerCredentialDeployRoutes } from "./credential-deploy-routes.js";
|
||||
import { registerCredentialBulkRoutes } from "./credential-bulk-routes.js";
|
||||
import {
|
||||
logAudit,
|
||||
@@ -1211,19 +1209,4 @@ router.put(
|
||||
},
|
||||
);
|
||||
|
||||
registerCredentialKeyRoutes(
|
||||
router,
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.view"),
|
||||
requireDataAccess,
|
||||
);
|
||||
|
||||
registerCredentialDeployRoutes(
|
||||
router,
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.view"),
|
||||
permissionManager.requirePermission("hosts.edit"),
|
||||
requireDataAccess,
|
||||
);
|
||||
|
||||
export default router;
|
||||
@@ -3,8 +3,7 @@ import express, { type Request, type Response } from "express";
|
||||
import { dashboardLogger } from "../../utils/logger.js";
|
||||
import { AuthManager } from "../../utils/auth-manager.js";
|
||||
import { DataCrypto } from "../../utils/data-crypto.js";
|
||||
import { createCurrentRecentActivityRepository } from "../repositories/factory.js";
|
||||
import { recordRecentActivity } from "../../services/recent-activity.js";
|
||||
import { recentActivity } from "../../plugins/activity-provider.js";
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -99,11 +98,7 @@ router.get(
|
||||
|
||||
const limit = Number(req.query.limit) || 20;
|
||||
|
||||
const activities =
|
||||
await createCurrentRecentActivityRepository().listByUserId(
|
||||
userId,
|
||||
limit,
|
||||
);
|
||||
const activities = await recentActivity.list(userId, limit);
|
||||
|
||||
res.json(activities);
|
||||
} catch (err) {
|
||||
@@ -169,7 +164,7 @@ router.post(
|
||||
});
|
||||
}
|
||||
|
||||
const result = await recordRecentActivity(userId, {
|
||||
const result = await recentActivity.record(userId, {
|
||||
type,
|
||||
hostId,
|
||||
hostName,
|
||||
@@ -185,6 +180,11 @@ router.post(
|
||||
message: "Activity already logged recently (rate limited)",
|
||||
});
|
||||
}
|
||||
if (result.status === "unavailable") {
|
||||
return res
|
||||
.status(404)
|
||||
.json({ error: "Recent activity is not available" });
|
||||
}
|
||||
if (result.status === "denied") {
|
||||
return res
|
||||
.status(404)
|
||||
@@ -222,7 +222,7 @@ router.delete(
|
||||
try {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
await createCurrentRecentActivityRepository().deleteByUserId(userId);
|
||||
await recentActivity.deleteByUserId(userId);
|
||||
|
||||
dashboardLogger.success("Recent activity cleared", {
|
||||
operation: "reset_recent_activity",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authLogger } from "../../utils/logger.js";
|
||||
import { recentActivity } from "../../plugins/activity-provider.js";
|
||||
import {
|
||||
createCurrentApiKeyRepository,
|
||||
createCurrentAuditLogRepository,
|
||||
@@ -9,7 +10,6 @@ import {
|
||||
createCurrentCredentialSidebarPreferenceRepository,
|
||||
createCurrentUiPreferenceRepository,
|
||||
createCurrentOpenTabRepository,
|
||||
createCurrentRecentActivityRepository,
|
||||
createCurrentRbacAccessRepository,
|
||||
createCurrentRoleRepository,
|
||||
createCurrentSessionRepository,
|
||||
@@ -64,7 +64,7 @@ export async function deleteUserAndRelatedData(
|
||||
|
||||
await createCurrentSshCredentialUsageRepository().deleteByUserId(userId);
|
||||
|
||||
await createCurrentRecentActivityRepository().deleteByUserId(userId);
|
||||
await recentActivity.deleteByUserId(userId);
|
||||
|
||||
await createCurrentHostFolderRepository().deleteByUserId(userId);
|
||||
|
||||
|
||||
@@ -61,15 +61,23 @@ export function isNativeTokenExportRequest(req: Request): boolean {
|
||||
* during testing, or a household sharing one install) -- a user in that
|
||||
* state deserves to get into the app they installed, not a confusing,
|
||||
* unexplained dead end. So this always returns a single, deterministic
|
||||
* user: the admin account if one exists, else the earliest-registered
|
||||
* account. It never returns null.
|
||||
* user: the account the user switched to if it still exists, else the admin
|
||||
* account if one exists, else the earliest-registered account. It never
|
||||
* returns null when there are users.
|
||||
*/
|
||||
export function resolveDesktopAutoSessionUser(
|
||||
allUsers: UserRecord[],
|
||||
preferredId?: string | null,
|
||||
): UserRecord | null {
|
||||
if (allUsers.length === 0) return null;
|
||||
if (allUsers.length === 1) return allUsers[0];
|
||||
|
||||
// An account the user switched to on purpose, while it still exists.
|
||||
const preferred = preferredId
|
||||
? allUsers.find((user) => user.id === preferredId)
|
||||
: undefined;
|
||||
if (preferred) return preferred;
|
||||
|
||||
const admin = allUsers.find((user) => user.isAdmin);
|
||||
if (admin) return admin;
|
||||
|
||||
|
||||
@@ -1,172 +1,23 @@
|
||||
import {
|
||||
prepareHostImports,
|
||||
remapImportedJumpHosts,
|
||||
} from "./host-import-order.js";
|
||||
import { sshOptionsForWrite } from "../../hosts/ssh-options.js";
|
||||
import {
|
||||
applyDefaultsAfterHostWrites,
|
||||
applyHostDefaultsToWrite,
|
||||
} from "../../hosts/defaults/index.js";
|
||||
import {
|
||||
changeHostOverrides,
|
||||
type OverrideChange,
|
||||
} from "../../hosts/defaults/overrides.js";
|
||||
import { recompute } from "../../hosts/defaults/recompute.js";
|
||||
import { splitDefaultKey } from "../../../types/host-defaults.js";
|
||||
import {
|
||||
keepUsableProtocolCredentials,
|
||||
readProtocolAuthPayload,
|
||||
writeProtocolAuth,
|
||||
} from "../../hosts/protocol-auth/protocol-auth.js";
|
||||
import { getErrorMessage } from "../../utils/error-message.js";
|
||||
|
||||
import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import type { Request, RequestHandler, Response, Router } from "express";
|
||||
import { sshLogger } from "../../utils/logger.js";
|
||||
import { DatabaseSaveTrigger } from "../../utils/database-save-trigger.js";
|
||||
import { pluginEvents, TOPICS } from "../../plugins/events.js";
|
||||
import {
|
||||
createCurrentCredentialRepository,
|
||||
createCurrentHostRepository,
|
||||
createCurrentHostResolutionRepository,
|
||||
createCurrentHostDefaultsRepository,
|
||||
} from "../repositories/factory.js";
|
||||
import { createCurrentHostRepository } from "../repositories/factory.js";
|
||||
import { validateParentHostId } from "./host-parent-validation.js";
|
||||
import {
|
||||
listSshAuthProviders,
|
||||
listSshAuthTypeOwners,
|
||||
} from "../../hosts/connect/auth-provider-registry.js";
|
||||
import {
|
||||
applyPluginHostImportSettings,
|
||||
setHostPluginEnabled,
|
||||
} from "./host-plugin-settings.js";
|
||||
import {
|
||||
isNonEmptyString,
|
||||
isValidPort,
|
||||
normalizeImportedHost,
|
||||
} from "./host-normalizers.js";
|
||||
import { assertHostsUnlocked, sendHostLocked } from "../../hosts/locks.js";
|
||||
|
||||
type SSHConfigHost = {
|
||||
name: string;
|
||||
hostname?: string;
|
||||
user?: string;
|
||||
port?: number;
|
||||
identityFile?: string;
|
||||
proxyJump?: string;
|
||||
};
|
||||
|
||||
type ShareCredential = {
|
||||
alias?: unknown;
|
||||
name?: unknown;
|
||||
description?: unknown;
|
||||
folder?: unknown;
|
||||
tags?: unknown;
|
||||
authType?: unknown;
|
||||
username?: unknown;
|
||||
keyType?: unknown;
|
||||
};
|
||||
|
||||
function textValue(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
function tagString(value: unknown): string {
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
.map((tag) => textValue(tag))
|
||||
.filter((tag): tag is string => !!tag)
|
||||
.join(",");
|
||||
}
|
||||
return textValue(value) || "";
|
||||
}
|
||||
|
||||
function normalizeCredentialAuthType(value: unknown): "password" | "key" {
|
||||
return value === "key" ? "key" : "password";
|
||||
}
|
||||
|
||||
export function parseSSHConfig(content: string): SSHConfigHost[] {
|
||||
const results: SSHConfigHost[] = [];
|
||||
let current: SSHConfigHost | null = null;
|
||||
|
||||
for (const rawLine of content.split("\n")) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith("#")) continue;
|
||||
|
||||
const match = /^(\S+?)(?:\s*=\s*|\s+)(.+)$/.exec(line);
|
||||
if (!match) continue;
|
||||
|
||||
const key = match[1].toLowerCase();
|
||||
const value = match[2];
|
||||
|
||||
if (key === "host") {
|
||||
if (current && current.hostname) results.push(current);
|
||||
// Skip wildcard patterns
|
||||
if (value === "*" || value.includes("*") || value.includes("?")) {
|
||||
current = null;
|
||||
} else {
|
||||
current = { name: value };
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!current) continue;
|
||||
|
||||
switch (key) {
|
||||
case "hostname":
|
||||
current.hostname = value;
|
||||
break;
|
||||
case "user":
|
||||
current.user = value;
|
||||
break;
|
||||
case "port": {
|
||||
const p = Number.parseInt(value, 10);
|
||||
if (p > 0 && p <= 65535) current.port = p;
|
||||
break;
|
||||
}
|
||||
case "identityfile":
|
||||
if (!current.identityFile) current.identityFile = value;
|
||||
break;
|
||||
case "proxyjump":
|
||||
current.proxyJump = value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (current && current.hostname) results.push(current);
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells status checks and other pollers about hosts an import wrote, the way
|
||||
* a single host create or update does.
|
||||
*/
|
||||
export function notifyImportedHosts(
|
||||
userId: string,
|
||||
hostIds: number[],
|
||||
createdHostIds: number[],
|
||||
): void {
|
||||
for (const hostId of createdHostIds) {
|
||||
pluginEvents.emit(TOPICS.hostCreated, { hostId, userId });
|
||||
}
|
||||
for (const hostId of hostIds) {
|
||||
pluginEvents.emit(TOPICS.hostUpdated, { hostId, userId });
|
||||
}
|
||||
}
|
||||
|
||||
export function importedHostUsername(
|
||||
connectionType: string,
|
||||
authType: unknown,
|
||||
username: unknown,
|
||||
): string | null {
|
||||
if (isNonEmptyString(username)) return username;
|
||||
if (connectionType !== "ssh" || authType === "credential") return "";
|
||||
return null;
|
||||
}
|
||||
import { setHostPluginEnabled } from "./host-plugin-settings.js";
|
||||
|
||||
export function registerHostBulkRoutes(
|
||||
router: Router,
|
||||
authenticateJWT: RequestHandler,
|
||||
requireCreatePermission: RequestHandler,
|
||||
requireEditPermission: RequestHandler,
|
||||
requireDataAccess: RequestHandler,
|
||||
): void {
|
||||
@@ -291,6 +142,15 @@ export function registerHostBulkRoutes(
|
||||
);
|
||||
|
||||
const ownedIds = ownedHosts.map((h) => h.id);
|
||||
// Pins stay the user's own on a managed host.
|
||||
if (Object.keys(updates).some((key) => key !== "pin")) {
|
||||
try {
|
||||
assertHostsUnlocked(ownedIds);
|
||||
} catch (error) {
|
||||
if (sendHostLocked(res, error)) return;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const unauthorizedIds = hostIds.filter(
|
||||
(id: number) => !ownedIds.includes(id),
|
||||
);
|
||||
@@ -467,674 +327,6 @@ export function registerHostBulkRoutes(
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/bulk-import",
|
||||
authenticateJWT,
|
||||
requireCreatePermission,
|
||||
requireEditPermission,
|
||||
requireDataAccess,
|
||||
DatabaseSaveTrigger.batched(async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const {
|
||||
hosts: hostsToImport,
|
||||
overwrite,
|
||||
credentials: credentialsToImport,
|
||||
} = req.body;
|
||||
|
||||
if (!Array.isArray(hostsToImport) || hostsToImport.length === 0) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "Hosts array is required and must not be empty" });
|
||||
}
|
||||
|
||||
if (hostsToImport.length > 100) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "Maximum 100 hosts allowed per import" });
|
||||
}
|
||||
|
||||
let orderedHosts: ReturnType<typeof prepareHostImports>;
|
||||
try {
|
||||
orderedHosts = prepareHostImports(hostsToImport);
|
||||
} catch (error) {
|
||||
return res.status(400).json({ error: getErrorMessage(error) });
|
||||
}
|
||||
const importedIds = new Map<unknown, number>();
|
||||
|
||||
const results = {
|
||||
success: 0,
|
||||
updated: 0,
|
||||
skipped: 0,
|
||||
failed: 0,
|
||||
errors: [] as string[],
|
||||
};
|
||||
|
||||
const credentialAliasMap = new Map<string, number>();
|
||||
const addCredentialAlias = (alias: unknown, id: number) => {
|
||||
const key = textValue(alias);
|
||||
if (key) credentialAliasMap.set(key.toLowerCase(), id);
|
||||
};
|
||||
|
||||
try {
|
||||
const credentialRepository = createCurrentCredentialRepository();
|
||||
const existingCredentials =
|
||||
await credentialRepository.listDecryptedByUserId(userId);
|
||||
|
||||
for (const credential of existingCredentials) {
|
||||
addCredentialAlias(credential.name, credential.id as number);
|
||||
}
|
||||
|
||||
if (Array.isArray(credentialsToImport)) {
|
||||
for (const rawCredential of credentialsToImport as ShareCredential[]) {
|
||||
const alias = textValue(rawCredential.alias);
|
||||
const name = textValue(rawCredential.name) || alias;
|
||||
if (!alias || !name) continue;
|
||||
|
||||
const existingId = credentialAliasMap.get(name.toLowerCase());
|
||||
if (existingId) {
|
||||
addCredentialAlias(alias, existingId);
|
||||
continue;
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const created = await credentialRepository.createEncryptedForUser(
|
||||
userId,
|
||||
{
|
||||
userId,
|
||||
name,
|
||||
description:
|
||||
textValue(rawCredential.description) ||
|
||||
"Imported placeholder. Add the secret before connecting.",
|
||||
folder: textValue(rawCredential.folder),
|
||||
tags: tagString(rawCredential.tags),
|
||||
authType: normalizeCredentialAuthType(rawCredential.authType),
|
||||
username: textValue(rawCredential.username),
|
||||
password: null,
|
||||
key: null,
|
||||
privateKey: null,
|
||||
publicKey: null,
|
||||
keyPassword: null,
|
||||
keyType: textValue(rawCredential.keyType),
|
||||
detectedKeyType: null,
|
||||
usageCount: 0,
|
||||
lastUsed: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
);
|
||||
|
||||
const createdCredential = created as Record<string, unknown>;
|
||||
addCredentialAlias(alias, createdCredential.id as number);
|
||||
addCredentialAlias(name, createdCredential.id as number);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
results.errors.push(
|
||||
`Credential placeholders: ${getErrorMessage(error, "failed to prepare credential aliases")}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Loaded for both modes: overwrite updates a match, skip leaves it alone.
|
||||
let existingHostMap: Map<string, { id: number }> | undefined;
|
||||
const hostRepository = createCurrentHostRepository();
|
||||
try {
|
||||
const allHosts =
|
||||
await createCurrentHostResolutionRepository().findHostsByUserId(
|
||||
userId,
|
||||
);
|
||||
existingHostMap = new Map();
|
||||
for (const h of allHosts) {
|
||||
const key = `${h.ip}:${h.port}:${h.username}`;
|
||||
existingHostMap.set(key, { id: h.id as number });
|
||||
}
|
||||
} catch {
|
||||
existingHostMap = undefined;
|
||||
}
|
||||
|
||||
const knownAuthTypes = listKnownAuthTypes();
|
||||
const writtenHostIds: number[] = [];
|
||||
const createdHostIds: number[] = [];
|
||||
for (const { host: hostData, index: i, exportId } of orderedHosts) {
|
||||
try {
|
||||
const effectiveConnectionType = hostData.connectionType || "ssh";
|
||||
|
||||
if (
|
||||
effectiveConnectionType === "ssh" &&
|
||||
hostData.authType === "credential" &&
|
||||
!hostData.credentialId &&
|
||||
hostData.credentialAlias
|
||||
) {
|
||||
hostData.credentialId = credentialAliasMap.get(
|
||||
hostData.credentialAlias.toLowerCase(),
|
||||
);
|
||||
}
|
||||
|
||||
if (!isNonEmptyString(hostData.ip) || !isValidPort(hostData.port)) {
|
||||
results.failed++;
|
||||
results.errors.push(
|
||||
`Host ${i + 1}: Missing required fields (ip, port)`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const username = importedHostUsername(
|
||||
effectiveConnectionType,
|
||||
hostData.authType,
|
||||
hostData.username,
|
||||
);
|
||||
if (username === null) {
|
||||
results.failed++;
|
||||
results.errors.push(
|
||||
`Host ${i + 1}: Username required for SSH connections`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const lookupKey = `${hostData.ip}:${hostData.port}:${hostData.username}`;
|
||||
const existing = existingHostMap?.get(lookupKey);
|
||||
if (existing && !overwrite) {
|
||||
// Hosts that jump through this one still resolve to the kept host.
|
||||
if (exportId !== undefined) importedIds.set(exportId, existing.id);
|
||||
results.skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
effectiveConnectionType === "ssh" &&
|
||||
hostData.authType &&
|
||||
!knownAuthTypes.has(hostData.authType)
|
||||
) {
|
||||
results.failed++;
|
||||
results.errors.push(
|
||||
`Host ${i + 1}: Invalid authType. Must be one of ${[...knownAuthTypes].join(", ")}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
effectiveConnectionType === "ssh" &&
|
||||
hostData.authType === "password" &&
|
||||
!isNonEmptyString(hostData.password)
|
||||
) {
|
||||
results.failed++;
|
||||
results.errors.push(
|
||||
`Host ${i + 1}: Password required for password authentication`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
effectiveConnectionType === "ssh" &&
|
||||
hostData.authType === "key" &&
|
||||
!isNonEmptyString(hostData.key)
|
||||
) {
|
||||
results.failed++;
|
||||
results.errors.push(
|
||||
`Host ${i + 1}: Key required for key authentication`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
effectiveConnectionType === "ssh" &&
|
||||
hostData.authType === "credential" &&
|
||||
!hostData.credentialId
|
||||
) {
|
||||
results.failed++;
|
||||
results.errors.push(
|
||||
`Host ${i + 1}: credentialId required for credential authentication`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
effectiveConnectionType === "ssh" &&
|
||||
hostData.authType === "credential" &&
|
||||
hostData.credentialId
|
||||
) {
|
||||
const credentialRepository = createCurrentCredentialRepository();
|
||||
const cred = await credentialRepository.findByIdForUser(
|
||||
userId,
|
||||
hostData.credentialId,
|
||||
);
|
||||
|
||||
if (!cred) {
|
||||
const fallback = await credentialRepository.listByUserId(userId);
|
||||
|
||||
if (fallback.length > 0) {
|
||||
hostData.credentialId = fallback[0].id;
|
||||
} else if (isNonEmptyString(hostData.key)) {
|
||||
hostData.authType = "key";
|
||||
hostData.credentialId = undefined;
|
||||
} else if (isNonEmptyString(hostData.password)) {
|
||||
hostData.authType = "password";
|
||||
hostData.credentialId = undefined;
|
||||
} else {
|
||||
results.failed++;
|
||||
results.errors.push(
|
||||
`Host ${i + 1}: credentialId ${hostData.credentialId} not found and no fallback credential available`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const jumpHosts = remapImportedJumpHosts(
|
||||
hostData.jumpHosts,
|
||||
importedIds,
|
||||
);
|
||||
const sshDataObj: Record<string, unknown> = {
|
||||
userId: userId,
|
||||
connectionType: effectiveConnectionType,
|
||||
name: hostData.name || `${username}@${hostData.ip}`,
|
||||
folder: hostData.folder || "Default",
|
||||
tags: Array.isArray(hostData.tags) ? hostData.tags.join(",") : "",
|
||||
ip: hostData.ip,
|
||||
port: hostData.port,
|
||||
username,
|
||||
pin: hostData.pin || false,
|
||||
sudoPassword: hostData.sudoPassword || null,
|
||||
jumpHosts: jumpHosts ? JSON.stringify(jumpHosts) : null,
|
||||
...importedStatusCheck(hostData as Record<string, unknown>),
|
||||
// A 2.8 export carries these inside terminalConfig.
|
||||
sshOptions:
|
||||
sshOptionsForWrite({
|
||||
sshOptions: hostData.sshOptions,
|
||||
terminalConfig: hostData.terminalConfig,
|
||||
}) ?? null,
|
||||
forceKeyboardInteractive: hostData.forceKeyboardInteractive
|
||||
? "true"
|
||||
: "false",
|
||||
notes: hostData.notes || null,
|
||||
useSocks5: hostData.useSocks5 ? 1 : 0,
|
||||
socks5Host: hostData.socks5Host || null,
|
||||
socks5Port: hostData.socks5Port || null,
|
||||
socks5Username: hostData.socks5Username || null,
|
||||
socks5Password: hostData.socks5Password || null,
|
||||
socks5ProxyChain: hostData.socks5ProxyChain
|
||||
? JSON.stringify(hostData.socks5ProxyChain)
|
||||
: null,
|
||||
portKnockSequence: hostData.portKnockSequence
|
||||
? JSON.stringify(hostData.portKnockSequence)
|
||||
: null,
|
||||
overrideCredentialUsername: hostData.overrideCredentialUsername
|
||||
? 1
|
||||
: 0,
|
||||
enableSsh: hostData.enableSsh ?? effectiveConnectionType === "ssh",
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
if (effectiveConnectionType !== "ssh") {
|
||||
sshDataObj.password = hostData.password || null;
|
||||
sshDataObj.authType = "password";
|
||||
sshDataObj.credentialId = null;
|
||||
sshDataObj.key = null;
|
||||
sshDataObj.keyPassword = null;
|
||||
sshDataObj.keyType = null;
|
||||
} else {
|
||||
sshDataObj.password =
|
||||
hostData.authType === "password" ? hostData.password : null;
|
||||
sshDataObj.authType = hostData.authType || "password";
|
||||
sshDataObj.credentialId =
|
||||
hostData.authType === "credential" ? hostData.credentialId : null;
|
||||
sshDataObj.key = hostData.authType === "key" ? hostData.key : null;
|
||||
sshDataObj.keyPassword =
|
||||
hostData.authType === "key" ? hostData.keyPassword || null : null;
|
||||
sshDataObj.keyType =
|
||||
hostData.authType === "key" ? hostData.keyType || "auto" : null;
|
||||
}
|
||||
|
||||
await withHostDefaults(
|
||||
userId,
|
||||
existing?.id ?? null,
|
||||
sshDataObj,
|
||||
hostData as Record<string, unknown>,
|
||||
);
|
||||
|
||||
let savedHostId: number;
|
||||
if (existing) {
|
||||
const saved = await hostRepository.updateEncryptedForUser(
|
||||
userId,
|
||||
existing.id,
|
||||
sshDataObj,
|
||||
);
|
||||
if (!saved) throw new Error("Host no longer exists");
|
||||
if (exportId !== undefined) importedIds.set(exportId, existing.id);
|
||||
savedHostId = existing.id;
|
||||
results.updated++;
|
||||
} else {
|
||||
sshDataObj.createdAt = new Date().toISOString();
|
||||
const saved = await hostRepository.createEncryptedForUser(
|
||||
userId,
|
||||
sshDataObj,
|
||||
);
|
||||
if (exportId !== undefined) importedIds.set(exportId, saved.id);
|
||||
savedHostId = saved.id;
|
||||
createdHostIds.push(saved.id);
|
||||
results.success++;
|
||||
}
|
||||
|
||||
const protocolAuth = readProtocolAuthPayload(
|
||||
hostData as Record<string, unknown>,
|
||||
);
|
||||
if (protocolAuth) {
|
||||
await writeProtocolAuth(
|
||||
userId,
|
||||
savedHostId,
|
||||
await keepUsableProtocolCredentials(protocolAuth, userId),
|
||||
{ isOwner: true },
|
||||
);
|
||||
}
|
||||
|
||||
// Every enabled plugin that declares host-scope settings and
|
||||
// registered a hostImportNormalizer validates and writes its own
|
||||
// fields here, so this loop does not need to know which plugins
|
||||
// exist. See host-plugin-settings.ts.
|
||||
await applyPluginHostImportSettings(
|
||||
savedHostId,
|
||||
hostData as Record<string, unknown>,
|
||||
);
|
||||
writtenHostIds.push(savedHostId);
|
||||
} catch (error) {
|
||||
results.failed++;
|
||||
results.errors.push(`Host ${i + 1}: ${getErrorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
await applyDefaultsAfterHostWrites(writtenHostIds);
|
||||
notifyImportedHosts(userId, writtenHostIds, createdHostIds);
|
||||
|
||||
res.json({
|
||||
message: `Import completed: ${results.success} created, ${results.updated} updated, ${results.skipped} skipped, ${results.failed} failed`,
|
||||
success: results.success,
|
||||
updated: results.updated,
|
||||
skipped: results.skipped,
|
||||
failed: results.failed,
|
||||
errors: results.errors,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /host/ssh-config-import:
|
||||
* post:
|
||||
* summary: Import hosts from an OpenSSH config file
|
||||
* description: Parses an OpenSSH ~/.ssh/config file and imports the defined hosts.
|
||||
* tags:
|
||||
* - SSH
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - content
|
||||
* properties:
|
||||
* content:
|
||||
* type: string
|
||||
* description: Raw text content of the SSH config file.
|
||||
* overwrite:
|
||||
* type: boolean
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Import completed.
|
||||
* 400:
|
||||
* description: Invalid request body.
|
||||
*/
|
||||
router.post(
|
||||
"/ssh-config-import",
|
||||
authenticateJWT,
|
||||
requireCreatePermission,
|
||||
requireEditPermission,
|
||||
requireDataAccess,
|
||||
DatabaseSaveTrigger.batched(async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { content, overwrite } = req.body;
|
||||
|
||||
if (!isNonEmptyString(content)) {
|
||||
return res.status(400).json({
|
||||
error: "content is required and must be a non-empty string",
|
||||
});
|
||||
}
|
||||
|
||||
let parsed: SSHConfigHost[];
|
||||
try {
|
||||
parsed = parseSSHConfig(content);
|
||||
} catch {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "Failed to parse SSH config file" });
|
||||
}
|
||||
|
||||
if (parsed.length === 0) {
|
||||
return res.status(400).json({
|
||||
error: "No valid Host entries found in the SSH config file",
|
||||
});
|
||||
}
|
||||
|
||||
if (parsed.length > 100) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "Maximum 100 hosts allowed per import" });
|
||||
}
|
||||
|
||||
const hostsToImport = parsed.map((h) => ({
|
||||
name: h.name,
|
||||
ip: h.hostname,
|
||||
port: h.port ?? 22,
|
||||
username: h.user,
|
||||
authType: h.identityFile ? "key" : undefined,
|
||||
connectionType: "ssh",
|
||||
enableSsh: true,
|
||||
...(h.proxyJump
|
||||
? {
|
||||
jumpHosts: [{ host: h.proxyJump, port: 22 }],
|
||||
}
|
||||
: {}),
|
||||
}));
|
||||
|
||||
const results = {
|
||||
success: 0,
|
||||
updated: 0,
|
||||
skipped: 0,
|
||||
failed: 0,
|
||||
errors: [] as string[],
|
||||
};
|
||||
|
||||
let existingHostMap: Map<string, { id: number }> | undefined;
|
||||
const hostRepository = createCurrentHostRepository();
|
||||
try {
|
||||
const allHosts =
|
||||
await createCurrentHostResolutionRepository().findHostsByUserId(
|
||||
userId,
|
||||
);
|
||||
existingHostMap = new Map();
|
||||
for (const h of allHosts) {
|
||||
const key = `${h.ip}:${h.port}:${h.username}`;
|
||||
existingHostMap.set(key, { id: h.id as number });
|
||||
}
|
||||
} catch {
|
||||
existingHostMap = undefined;
|
||||
}
|
||||
|
||||
const writtenHostIds: number[] = [];
|
||||
const createdHostIds: number[] = [];
|
||||
for (let i = 0; i < hostsToImport.length; i++) {
|
||||
const hostData = normalizeImportedHost(
|
||||
hostsToImport[i] as Record<string, unknown>,
|
||||
);
|
||||
|
||||
try {
|
||||
if (!isNonEmptyString(hostData.ip) || !isValidPort(hostData.port)) {
|
||||
results.failed++;
|
||||
results.errors.push(
|
||||
`Host "${parsed[i].name}": Missing required fields (HostName, Port)`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const lookupKey = `${hostData.ip}:${hostData.port}:${hostData.username}`;
|
||||
const existing = existingHostMap?.get(lookupKey);
|
||||
if (existing && !overwrite) {
|
||||
results.skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const sshDataObj: Record<string, unknown> = {
|
||||
userId,
|
||||
connectionType: "ssh",
|
||||
name: hostData.name || hostData.ip,
|
||||
folder: "Default",
|
||||
tags: "",
|
||||
ip: hostData.ip,
|
||||
port: hostData.port,
|
||||
username: hostData.username || null,
|
||||
authType: hostData.authType || "none",
|
||||
password: null,
|
||||
key: null,
|
||||
keyPassword: null,
|
||||
keyType: null,
|
||||
credentialId: null,
|
||||
pin: false,
|
||||
sudoPassword: null,
|
||||
jumpHosts: hostData.jumpHosts
|
||||
? JSON.stringify(hostData.jumpHosts)
|
||||
: null,
|
||||
statusCheckEnabled: true,
|
||||
statusCheckInterval: null,
|
||||
sshOptions: null,
|
||||
forceKeyboardInteractive: "false",
|
||||
notes: null,
|
||||
useSocks5: 0,
|
||||
socks5Host: null,
|
||||
socks5Port: null,
|
||||
socks5Username: null,
|
||||
socks5Password: null,
|
||||
socks5ProxyChain: null,
|
||||
portKnockSequence: null,
|
||||
overrideCredentialUsername: 0,
|
||||
enableSsh: true,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
await withHostDefaults(
|
||||
userId,
|
||||
existing?.id ?? null,
|
||||
sshDataObj,
|
||||
hostData as unknown as Record<string, unknown>,
|
||||
);
|
||||
|
||||
if (existing) {
|
||||
await hostRepository.updateEncryptedForUser(
|
||||
userId,
|
||||
existing.id,
|
||||
sshDataObj,
|
||||
);
|
||||
writtenHostIds.push(existing.id);
|
||||
results.updated++;
|
||||
} else {
|
||||
sshDataObj.createdAt = new Date().toISOString();
|
||||
const saved = await hostRepository.createEncryptedForUser(
|
||||
userId,
|
||||
sshDataObj,
|
||||
);
|
||||
writtenHostIds.push(saved.id);
|
||||
createdHostIds.push(saved.id);
|
||||
results.success++;
|
||||
}
|
||||
} catch (error) {
|
||||
results.failed++;
|
||||
results.errors.push(
|
||||
`Host "${parsed[i].name}": ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await applyDefaultsAfterHostWrites(writtenHostIds);
|
||||
notifyImportedHosts(userId, writtenHostIds, createdHostIds);
|
||||
|
||||
res.json({
|
||||
message: `Import completed: ${results.success} created, ${results.updated} updated, ${results.skipped} skipped, ${results.failed} failed`,
|
||||
success: results.success,
|
||||
updated: results.updated,
|
||||
skipped: results.skipped,
|
||||
failed: results.failed,
|
||||
errors: results.errors,
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Status check fields from an import row. Exports from before 2.9.0 carried
|
||||
* them inside statsConfig.
|
||||
*/
|
||||
function importedStatusCheck(raw: Record<string, unknown>): {
|
||||
statusCheckEnabled: boolean;
|
||||
statusCheckInterval: number | null;
|
||||
} {
|
||||
const legacy =
|
||||
raw.statsConfig && typeof raw.statsConfig === "object"
|
||||
? (raw.statsConfig as Record<string, unknown>)
|
||||
: {};
|
||||
const enabled = raw.statusCheckEnabled ?? legacy.statusCheckEnabled;
|
||||
const useGlobal = legacy.useGlobalStatusInterval !== false;
|
||||
const interval =
|
||||
raw.statusCheckInterval ?? (useGlobal ? null : legacy.statusCheckInterval);
|
||||
const seconds = Number(interval);
|
||||
return {
|
||||
statusCheckEnabled: enabled !== false && legacy.disableTcpPing !== true,
|
||||
statusCheckInterval:
|
||||
interval != null && Number.isInteger(seconds) && seconds >= 5
|
||||
? seconds
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
const BUILTIN_SSH_AUTH_TYPES = [
|
||||
"password",
|
||||
"key",
|
||||
"credential",
|
||||
"agent",
|
||||
"none",
|
||||
];
|
||||
|
||||
/** Core's own types plus every type a plugin registers or declares. */
|
||||
function listKnownAuthTypes(): Set<string> {
|
||||
return new Set([
|
||||
...BUILTIN_SSH_AUTH_TYPES,
|
||||
...listSshAuthProviders().map((provider) => provider.type),
|
||||
...listSshAuthTypeOwners().map((owner) => owner.type),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Fills an imported host's inherited keys and records what it sets itself. */
|
||||
async function withHostDefaults(
|
||||
userId: string,
|
||||
hostId: number | null,
|
||||
columns: Record<string, unknown>,
|
||||
body: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
const stored =
|
||||
hostId === null
|
||||
? null
|
||||
: ((
|
||||
await createCurrentHostDefaultsRepository().listHosts({
|
||||
hostIds: [hostId],
|
||||
})
|
||||
)[0] ?? null);
|
||||
columns.defaultOverrides = JSON.stringify(
|
||||
await applyHostDefaultsToWrite({
|
||||
ownerId: userId,
|
||||
hostId,
|
||||
columns,
|
||||
body,
|
||||
stored,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** A resetDefaults body as an override change, or null when there is none. */
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
} from "../../hosts/defaults/service.js";
|
||||
import { changeHostOverrides } from "../../hosts/defaults/overrides.js";
|
||||
import { readDefaultsReset } from "./host-bulk-routes.js";
|
||||
import { assertHostsUnlocked, sendHostLocked } from "../../hosts/locks.js";
|
||||
|
||||
type HostDefaultsRoutesDeps = {
|
||||
authenticateJWT: RequestHandler;
|
||||
@@ -678,6 +679,7 @@ export function registerHostDefaultsRoutes(
|
||||
const reset = readDefaultsReset(req.body);
|
||||
if (!reset) return res.status(400).json({ error: "Nothing to reset" });
|
||||
try {
|
||||
assertHostsUnlocked([hostId]);
|
||||
const access = await PermissionManager.getInstance().canAccessHost(
|
||||
userId,
|
||||
hostId,
|
||||
@@ -700,6 +702,7 @@ export function registerHostDefaultsRoutes(
|
||||
await changeHostOverrides([hostId], reset);
|
||||
res.json({ message: "Host reset to its defaults" });
|
||||
} catch (error) {
|
||||
if (sendHostLocked(res, error)) return;
|
||||
databaseLogger.error("Failed to reset host defaults", error);
|
||||
res.status(500).json({ error: "Failed to reset host defaults" });
|
||||
}
|
||||
|
||||
@@ -2,11 +2,11 @@ import type { Request, RequestHandler, Response, Router } from "express";
|
||||
import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import { databaseLogger, sshLogger } from "../../utils/logger.js";
|
||||
import { pluginEvents, TOPICS } from "../../plugins/events.js";
|
||||
import { recentActivity } from "../../plugins/activity-provider.js";
|
||||
import {
|
||||
createCurrentCredentialRepository,
|
||||
createCurrentHostFolderRepository,
|
||||
createCurrentFolderAccessRepository,
|
||||
createCurrentRecentActivityRepository,
|
||||
createCurrentRbacAccessRepository,
|
||||
createCurrentSshCredentialUsageRepository,
|
||||
} from "../repositories/factory.js";
|
||||
@@ -16,6 +16,31 @@ import {
|
||||
folderCredentialIds,
|
||||
setFolderCredentialDefault,
|
||||
} from "../../hosts/defaults/service.js";
|
||||
import {
|
||||
assertHostsUnlocked,
|
||||
hasHostLocks,
|
||||
sendHostLocked,
|
||||
} from "../../hosts/locks.js";
|
||||
|
||||
/** Refuses a folder change that would touch a locked host. */
|
||||
async function folderHostsUnlocked(
|
||||
userId: string,
|
||||
folderName: string,
|
||||
res: Response,
|
||||
): Promise<boolean> {
|
||||
if (!hasHostLocks()) return true;
|
||||
const inFolder = await createCurrentHostFolderRepository().listHostsInFolder(
|
||||
userId,
|
||||
folderName,
|
||||
);
|
||||
try {
|
||||
assertHostsUnlocked(inFolder.map((host) => host.id));
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (sendHostLocked(res, error)) return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
type HostFolderRoutesDeps = {
|
||||
authenticateJWT: RequestHandler;
|
||||
@@ -86,6 +111,7 @@ export function registerHostFolderRoutes(
|
||||
}
|
||||
|
||||
try {
|
||||
if (!(await folderHostsUnlocked(userId, oldName, res))) return;
|
||||
const { updatedHosts, updatedCredentials } =
|
||||
await createCurrentHostFolderRepository().renameFolder(
|
||||
userId,
|
||||
@@ -417,6 +443,7 @@ export function registerHostFolderRoutes(
|
||||
});
|
||||
|
||||
try {
|
||||
if (!(await folderHostsUnlocked(userId, folderName, res))) return;
|
||||
const hostFolderRepository = createCurrentHostFolderRepository();
|
||||
const hostsToDelete = await hostFolderRepository.listHostsInFolder(
|
||||
userId,
|
||||
@@ -432,9 +459,7 @@ export function registerHostFolderRoutes(
|
||||
hostIds,
|
||||
);
|
||||
|
||||
await createCurrentRecentActivityRepository().deleteByHostIds(
|
||||
hostIds,
|
||||
);
|
||||
await recentActivity.deleteByHostIds(hostIds);
|
||||
|
||||
await createCurrentRbacAccessRepository().deleteHostAccessForHosts(
|
||||
hostIds,
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
} from "../../hosts/ssh-options.js";
|
||||
import { listHostProtocols } from "../../hosts/protocol-auth/registry.js";
|
||||
import { sanitizeProtocolAuthForRecipient } from "../../hosts/protocol-auth/summary.js";
|
||||
import { hostLock } from "../../hosts/locks.js";
|
||||
|
||||
export function isNonEmptyString(value: unknown): value is string {
|
||||
return typeof value === "string" && value.trim().length > 0;
|
||||
@@ -337,6 +338,7 @@ const CONNECT_LEVEL_FIELDS = new Set([
|
||||
"sshPort",
|
||||
"protocolAuth",
|
||||
"jumpHosts",
|
||||
"lock",
|
||||
"createdAt",
|
||||
"updatedAt",
|
||||
]);
|
||||
@@ -439,8 +441,10 @@ export function transformHostResponse(
|
||||
host: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const shared = parseSharedSource(host.sharedSource);
|
||||
const lock = typeof host.id === "number" ? hostLock(host.id) : null;
|
||||
return {
|
||||
...host,
|
||||
...(lock ? { lock } : {}),
|
||||
sharedSource: undefined,
|
||||
localOnly: !!host.localOnly,
|
||||
sharedCopy: !!shared,
|
||||
|
||||
@@ -3,13 +3,10 @@ import type { Request, RequestHandler, Response, Router } from "express";
|
||||
import { PermissionManager } from "../../utils/permission-manager.js";
|
||||
import { DataCrypto } from "../../utils/data-crypto.js";
|
||||
import { sshLogger } from "../../utils/logger.js";
|
||||
import { createCurrentSettingsRepository } from "../repositories/factory.js";
|
||||
import {
|
||||
DEFAULT_STATUS_INTERVAL,
|
||||
GLOBAL_STATUS_INTERVAL_KEY,
|
||||
hostStatusService,
|
||||
hostStatus,
|
||||
type HostStatusEntry,
|
||||
} from "../../hosts/status/host-status-service.js";
|
||||
} from "../../plugins/host-status-provider.js";
|
||||
|
||||
interface HostStatusRoutesDeps {
|
||||
authenticateJWT: RequestHandler;
|
||||
@@ -71,7 +68,7 @@ export function registerHostStatusRoutes(
|
||||
return sessionExpired(res);
|
||||
|
||||
const requested = parseStatusHostIds(req.query.hostIds);
|
||||
const statuses = await hostStatusService.statusesFor(userId, requested);
|
||||
const statuses = await hostStatus.statusesFor(userId, requested);
|
||||
|
||||
// One batched permission check: this is polled every few seconds, and a
|
||||
// per-host check made it linear in host count against the database.
|
||||
@@ -110,15 +107,7 @@ export function registerHostStatusRoutes(
|
||||
authenticateJWT,
|
||||
requireAdmin,
|
||||
async (_req: Request, res: Response) => {
|
||||
const value = Number(
|
||||
await createCurrentSettingsRepository().get(GLOBAL_STATUS_INTERVAL_KEY),
|
||||
);
|
||||
res.json({
|
||||
statusCheckInterval:
|
||||
Number.isInteger(value) && value >= 5
|
||||
? value
|
||||
: DEFAULT_STATUS_INTERVAL,
|
||||
});
|
||||
res.json({ statusCheckInterval: await hostStatus.getIntervalSeconds() });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -161,11 +150,7 @@ export function registerHostStatusRoutes(
|
||||
.json({ error: "Status check interval must be 5 to 3600 seconds" });
|
||||
}
|
||||
try {
|
||||
await createCurrentSettingsRepository().set(
|
||||
GLOBAL_STATUS_INTERVAL_KEY,
|
||||
String(seconds),
|
||||
);
|
||||
hostStatusService.retimeAll();
|
||||
await hostStatus.setIntervalSeconds(seconds);
|
||||
res.json({ statusCheckInterval: seconds });
|
||||
} catch (error) {
|
||||
sshLogger.error("Failed to save status check settings", error, {
|
||||
@@ -198,7 +183,7 @@ export function registerHostStatusRoutes(
|
||||
if (DataCrypto.getUserDataKey(userId) === null) {
|
||||
return sessionExpired(res);
|
||||
}
|
||||
await hostStatusService.refresh(userId);
|
||||
await hostStatus.refresh(userId);
|
||||
res.json({ message: "Status checks restarted" });
|
||||
},
|
||||
);
|
||||
@@ -247,9 +232,8 @@ export function registerHostStatusRoutes(
|
||||
return res.status(404).json({ error: "Status not available" });
|
||||
}
|
||||
|
||||
await hostStatusService.statusesFor(userId, null);
|
||||
const entry =
|
||||
hostStatusService.get(id) ?? (await hostStatusService.check(id));
|
||||
await hostStatus.statusesFor(userId, null);
|
||||
const entry = hostStatus.get(id) ?? (await hostStatus.check(id));
|
||||
if (!entry) {
|
||||
return res.status(404).json({ error: "Status not available" });
|
||||
}
|
||||
|
||||
@@ -7,25 +7,21 @@ import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import express, { type Request, type Response } from "express";
|
||||
import multer from "multer";
|
||||
import { sshLogger, databaseLogger } from "../../utils/logger.js";
|
||||
import { resolveHostCredentials } from "../../hosts/resolve-host-credentials.js";
|
||||
import { pluginEvents, TOPICS } from "../../plugins/events.js";
|
||||
import { AuthManager } from "../../utils/auth-manager.js";
|
||||
import { PermissionManager } from "../../utils/permission-manager.js";
|
||||
import { DataCrypto } from "../../utils/data-crypto.js";
|
||||
import { parseKeyForStorage } from "../../hosts/stored-ssh-key.js";
|
||||
import {
|
||||
pickResolvedPassword,
|
||||
pickResolvedUsername,
|
||||
} from "../../hosts/credential-username.js";
|
||||
import { pickResolvedPassword } from "../../hosts/credential-username.js";
|
||||
import { emitInternalEvent } from "../../hosts/internal-events.js";
|
||||
import { deleteOwnedHost } from "../../hosts/delete-host.js";
|
||||
import {
|
||||
createCurrentCredentialRepository,
|
||||
createCurrentRbacAccessRepository,
|
||||
createCurrentRoleRepository,
|
||||
createCurrentHostResolutionRepository,
|
||||
createCurrentHostRepository,
|
||||
createCurrentUserRepository,
|
||||
createCurrentSharedHostAuthOverrideRepository,
|
||||
createCurrentHostDefaultsRepository,
|
||||
} from "../repositories/factory.js";
|
||||
import {
|
||||
@@ -41,7 +37,6 @@ import {
|
||||
OWNER_PRIVATE_AUTH_FIELDS,
|
||||
OWNER_PRIVATE_SSH_OPTION_FIELDS,
|
||||
OWNER_PRIVATE_TERMINAL_CONFIG_FIELDS,
|
||||
hostTerminalExport,
|
||||
sanitizeHostForRecipient,
|
||||
stripSensitiveFields,
|
||||
transformHostResponse,
|
||||
@@ -67,14 +62,8 @@ import {
|
||||
getAuditUsername,
|
||||
getRequestMeta,
|
||||
} from "../../utils/audit-logger.js";
|
||||
import type {
|
||||
HostResolutionCredentialRecord,
|
||||
HostResolutionHostRecord,
|
||||
} from "../repositories/host-resolution-repository.js";
|
||||
import {
|
||||
requiresPersonalHostAuthentication,
|
||||
resolveRecipientSharedHostAuthentication,
|
||||
} from "../../utils/shared-host-auth-resolver.js";
|
||||
import type { HostResolutionCredentialRecord } from "../repositories/host-resolution-repository.js";
|
||||
|
||||
import { rejectSharedCopyWrites } from "../../sync/shared-copy-guard.js";
|
||||
import { sshOptionsForWrite } from "../../hosts/ssh-options.js";
|
||||
import {
|
||||
@@ -91,15 +80,16 @@ import {
|
||||
planProtocolAuthWrite,
|
||||
ProtocolAuthWriteError,
|
||||
readProtocolAuthPayload,
|
||||
toPortableLogins,
|
||||
withProtocolAuth,
|
||||
writeProtocolAuth,
|
||||
type PlannedProtocolAuth,
|
||||
} from "../../hosts/protocol-auth/protocol-auth.js";
|
||||
import { findHostProtocol } from "../../hosts/protocol-auth/registry.js";
|
||||
import {
|
||||
findHostProtocol,
|
||||
listHostProtocols,
|
||||
} from "../../hosts/protocol-auth/registry.js";
|
||||
manualCreateBlockedBy,
|
||||
requireManualCreate,
|
||||
requireUnlockedHost,
|
||||
} from "../../hosts/locks.js";
|
||||
import {
|
||||
mergeStoredSshOptions,
|
||||
parseTerminalConfig,
|
||||
@@ -172,6 +162,7 @@ router.post(
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.create"),
|
||||
requireDataAccess,
|
||||
requireManualCreate,
|
||||
requireHostEnrollmentAccessForPath,
|
||||
upload.single("key"),
|
||||
async (req: Request, res: Response) => {
|
||||
@@ -751,6 +742,7 @@ router.put(
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.edit"),
|
||||
requireDataAccess,
|
||||
requireUnlockedHost,
|
||||
upload.single("key"),
|
||||
async (req: Request, res: Response) => {
|
||||
const hostId = Array.isArray(req.params.id)
|
||||
@@ -1220,6 +1212,27 @@ router.put(
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /host/policy:
|
||||
* get:
|
||||
* summary: Host creation policy
|
||||
* description: Whether hosts can be added by hand, or a plugin manages them all.
|
||||
* tags:
|
||||
* - SSH
|
||||
* responses:
|
||||
* 200:
|
||||
* description: "{ manualCreate, blockedBy? } where blockedBy is the managing plugin's name."
|
||||
*/
|
||||
router.get("/policy", authenticateJWT, (_req: Request, res: Response) => {
|
||||
const blocked = manualCreateBlockedBy();
|
||||
res.json(
|
||||
blocked
|
||||
? { manualCreate: false, blockedBy: blocked.pluginName }
|
||||
: { manualCreate: true },
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /host/db/host:
|
||||
@@ -1688,340 +1701,6 @@ router.get(
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /host/db/host/{id}/export:
|
||||
* get:
|
||||
* summary: Export SSH host
|
||||
* description: Exports a specific SSH host with decrypted credentials.
|
||||
* tags:
|
||||
* - SSH
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The exported SSH host.
|
||||
* 400:
|
||||
* description: Invalid userId or hostId.
|
||||
* 404:
|
||||
* description: SSH host not found.
|
||||
* 500:
|
||||
* description: Failed to export SSH host.
|
||||
*/
|
||||
router.get(
|
||||
"/db/host/:id/export",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const hostId = Array.isArray(req.params.id)
|
||||
? req.params.id[0]
|
||||
: req.params.id;
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
if (!isNonEmptyString(userId) || !hostId) {
|
||||
return res.status(400).json({ error: "Invalid userId or hostId" });
|
||||
}
|
||||
|
||||
try {
|
||||
const host =
|
||||
await createCurrentHostResolutionRepository().findHostByIdForUser(
|
||||
Number(hostId),
|
||||
userId,
|
||||
);
|
||||
|
||||
if (!host) {
|
||||
return res.status(404).json({ error: "SSH host not found" });
|
||||
}
|
||||
|
||||
const resolvedHost = (await resolveHostCredentials(host, userId)) || host;
|
||||
const hostPluginSettings = (
|
||||
await loadHostPluginSettings([Number(hostId)])
|
||||
).get(Number(hostId));
|
||||
|
||||
const exportedConnectionType =
|
||||
(resolvedHost.connectionType as string) || "ssh";
|
||||
const isRemoteDesktop = exportedConnectionType !== "ssh";
|
||||
|
||||
const baseExportData = {
|
||||
exportId: resolvedHost.id,
|
||||
connectionType: exportedConnectionType,
|
||||
name: resolvedHost.name,
|
||||
ip: resolvedHost.ip,
|
||||
port: resolvedHost.port,
|
||||
username: resolvedHost.username,
|
||||
password: resolvedHost.password || null,
|
||||
folder: resolvedHost.folder,
|
||||
tags:
|
||||
typeof resolvedHost.tags === "string"
|
||||
? resolvedHost.tags.split(",").filter(Boolean)
|
||||
: resolvedHost.tags || [],
|
||||
pin: !!resolvedHost.pin,
|
||||
notes: resolvedHost.notes || null,
|
||||
// Every plugin's host settings, secrets redacted, for import to hand back.
|
||||
pluginSettings: hostPluginSettings ?? {},
|
||||
// Each plugin protocol's login, secrets included like the SSH ones.
|
||||
protocolAuth: toPortableLogins(
|
||||
await listProtocolLogins(Number(hostId), userId),
|
||||
),
|
||||
};
|
||||
|
||||
const exportData = isRemoteDesktop
|
||||
? baseExportData
|
||||
: {
|
||||
...baseExportData,
|
||||
authType: resolvedHost.authType,
|
||||
key: resolvedHost.key || null,
|
||||
keyPassword: resolvedHost.keyPassword || null,
|
||||
keyType: resolvedHost.keyType || null,
|
||||
credentialId: resolvedHost.credentialId || null,
|
||||
overrideCredentialUsername:
|
||||
!!resolvedHost.overrideCredentialUsername,
|
||||
sudoPassword: resolvedHost.sudoPassword || null,
|
||||
jumpHosts: resolvedHost.jumpHosts
|
||||
? JSON.parse(resolvedHost.jumpHosts as string)
|
||||
: null,
|
||||
terminalConfig:
|
||||
hostTerminalExport(resolvedHost).terminalConfig ?? null,
|
||||
sshOptions: hostTerminalExport(resolvedHost).sshOptions,
|
||||
forceKeyboardInteractive:
|
||||
resolvedHost.forceKeyboardInteractive === "true",
|
||||
useSocks5: !!resolvedHost.useSocks5,
|
||||
socks5Host: resolvedHost.socks5Host || null,
|
||||
socks5Port: resolvedHost.socks5Port || null,
|
||||
socks5Username: resolvedHost.socks5Username || null,
|
||||
socks5Password: resolvedHost.socks5Password || null,
|
||||
socks5ProxyChain: resolvedHost.socks5ProxyChain
|
||||
? JSON.parse(resolvedHost.socks5ProxyChain as string)
|
||||
: null,
|
||||
portKnockSequence: resolvedHost.portKnockSequence
|
||||
? JSON.parse(resolvedHost.portKnockSequence as string)
|
||||
: null,
|
||||
};
|
||||
|
||||
sshLogger.success("Host exported with decrypted credentials", {
|
||||
operation: "host_export",
|
||||
hostId: parseInt(hostId),
|
||||
userId,
|
||||
});
|
||||
|
||||
res.json(exportData);
|
||||
} catch (err) {
|
||||
sshLogger.error("Failed to export SSH host", err, {
|
||||
operation: "host_export",
|
||||
hostId: parseInt(hostId),
|
||||
userId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to export SSH host" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /host/db/hosts/export:
|
||||
* get:
|
||||
* summary: Export all SSH hosts
|
||||
* description: Exports all SSH hosts for the current user. By default credentials are decrypted and embedded. With `share=1`, secrets are omitted and credential-authenticated hosts instead reference a scrubbed `credentials` array by alias, suitable for handing off to another user.
|
||||
* tags:
|
||||
* - SSH
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: share
|
||||
* required: false
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Set to "1" to export without embedded secrets.
|
||||
* responses:
|
||||
* 200:
|
||||
* description: All exported SSH hosts.
|
||||
* 400:
|
||||
* description: Invalid userId.
|
||||
* 500:
|
||||
* description: Failed to export SSH hosts.
|
||||
*/
|
||||
router.get(
|
||||
"/db/hosts/export",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const shareMode = req.query.share === "1" || req.query.share === "true";
|
||||
|
||||
if (!isNonEmptyString(userId)) {
|
||||
return res.status(400).json({ error: "Invalid userId" });
|
||||
}
|
||||
|
||||
try {
|
||||
const allHosts =
|
||||
await createCurrentHostResolutionRepository().findHostsByUserId(userId);
|
||||
const pluginSettingsByHost = await loadHostPluginSettings(
|
||||
allHosts.map((h) => h.id as number),
|
||||
);
|
||||
|
||||
const exportedHosts = [];
|
||||
const usedCredentialIds = new Set<number>();
|
||||
|
||||
for (const host of allHosts) {
|
||||
const resolvedHost = shareMode
|
||||
? host
|
||||
: (await resolveHostCredentials(host, userId)) || host;
|
||||
const hostPluginSettings = pluginSettingsByHost.get(host.id as number);
|
||||
|
||||
const exportedConnectionType =
|
||||
(resolvedHost.connectionType as string) || "ssh";
|
||||
const isRemoteDesktop = exportedConnectionType !== "ssh";
|
||||
|
||||
const baseExportData = {
|
||||
exportId: resolvedHost.id,
|
||||
connectionType: exportedConnectionType,
|
||||
name: resolvedHost.name,
|
||||
ip: resolvedHost.ip,
|
||||
port: resolvedHost.port,
|
||||
username: resolvedHost.username,
|
||||
password: shareMode ? null : resolvedHost.password || null,
|
||||
folder: resolvedHost.folder,
|
||||
tags:
|
||||
typeof resolvedHost.tags === "string"
|
||||
? resolvedHost.tags.split(",").filter(Boolean)
|
||||
: resolvedHost.tags || [],
|
||||
pin: !!resolvedHost.pin,
|
||||
notes: resolvedHost.notes || null,
|
||||
// Every plugin's host settings, secrets redacted, for import to hand back.
|
||||
pluginSettings: hostPluginSettings ?? {},
|
||||
protocolAuth: shareableLogins(
|
||||
toPortableLogins(
|
||||
await listProtocolLogins(host.id as number, userId),
|
||||
),
|
||||
shareMode,
|
||||
),
|
||||
};
|
||||
|
||||
const exportData = isRemoteDesktop
|
||||
? baseExportData
|
||||
: {
|
||||
...baseExportData,
|
||||
authType: resolvedHost.authType,
|
||||
key: shareMode ? null : resolvedHost.key || null,
|
||||
keyPassword: shareMode ? null : resolvedHost.keyPassword || null,
|
||||
keyType: resolvedHost.keyType || null,
|
||||
credentialId: resolvedHost.credentialId || null,
|
||||
overrideCredentialUsername:
|
||||
!!resolvedHost.overrideCredentialUsername,
|
||||
sudoPassword: shareMode
|
||||
? null
|
||||
: resolvedHost.sudoPassword || null,
|
||||
jumpHosts: resolvedHost.jumpHosts
|
||||
? JSON.parse(resolvedHost.jumpHosts as string)
|
||||
: null,
|
||||
terminalConfig:
|
||||
hostTerminalExport(resolvedHost).terminalConfig ?? null,
|
||||
sshOptions: hostTerminalExport(resolvedHost).sshOptions,
|
||||
forceKeyboardInteractive:
|
||||
resolvedHost.forceKeyboardInteractive === "true",
|
||||
useSocks5: !!resolvedHost.useSocks5,
|
||||
socks5Host: resolvedHost.socks5Host || null,
|
||||
socks5Port: resolvedHost.socks5Port || null,
|
||||
socks5Username: resolvedHost.socks5Username || null,
|
||||
socks5Password: shareMode
|
||||
? null
|
||||
: resolvedHost.socks5Password || null,
|
||||
socks5ProxyChain: resolvedHost.socks5ProxyChain
|
||||
? JSON.parse(resolvedHost.socks5ProxyChain as string)
|
||||
: null,
|
||||
};
|
||||
|
||||
if (
|
||||
shareMode &&
|
||||
!isRemoteDesktop &&
|
||||
resolvedHost.authType === "credential" &&
|
||||
resolvedHost.credentialId
|
||||
) {
|
||||
usedCredentialIds.add(resolvedHost.credentialId as number);
|
||||
}
|
||||
|
||||
exportedHosts.push(exportData);
|
||||
}
|
||||
|
||||
if (!shareMode) {
|
||||
sshLogger.success("All hosts exported with decrypted credentials", {
|
||||
operation: "hosts_export_all",
|
||||
count: exportedHosts.length,
|
||||
userId,
|
||||
});
|
||||
|
||||
return res.json({ hosts: exportedHosts });
|
||||
}
|
||||
|
||||
const exportedCredentials: Record<string, unknown>[] = [];
|
||||
if (usedCredentialIds.size > 0) {
|
||||
const credentialRepository = createCurrentCredentialRepository();
|
||||
const ownedCredentials =
|
||||
await credentialRepository.listDecryptedByUserId(userId);
|
||||
const credentialById = new Map(
|
||||
ownedCredentials.map((credential) => [credential.id, credential]),
|
||||
);
|
||||
|
||||
for (const host of exportedHosts as Record<string, unknown>[]) {
|
||||
const credentialId = host.credentialId as number | null;
|
||||
if (!credentialId) continue;
|
||||
const credential = credentialById.get(credentialId);
|
||||
if (!credential) continue;
|
||||
|
||||
host.credentialAlias = credential.name;
|
||||
|
||||
if (
|
||||
!exportedCredentials.some(
|
||||
(entry) => entry.alias === credential.name,
|
||||
)
|
||||
) {
|
||||
exportedCredentials.push({
|
||||
alias: credential.name,
|
||||
name: credential.name,
|
||||
description: credential.description || null,
|
||||
folder: credential.folder || null,
|
||||
tags:
|
||||
typeof credential.tags === "string"
|
||||
? credential.tags.split(",").filter(Boolean)
|
||||
: [],
|
||||
authType: credential.authType,
|
||||
username: credential.username || null,
|
||||
keyType: credential.keyType || null,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const host of exportedHosts as Record<string, unknown>[]) {
|
||||
delete host.credentialId;
|
||||
}
|
||||
|
||||
sshLogger.success("All hosts exported for sharing without secrets", {
|
||||
operation: "hosts_export_all_share",
|
||||
count: exportedHosts.length,
|
||||
credentialCount: exportedCredentials.length,
|
||||
userId,
|
||||
});
|
||||
|
||||
res.json({
|
||||
version: "1",
|
||||
exportedAt: new Date().toISOString(),
|
||||
credentials: exportedCredentials,
|
||||
hosts: exportedHosts,
|
||||
});
|
||||
} catch (err) {
|
||||
sshLogger.error("Failed to export all SSH hosts", err, {
|
||||
operation: "hosts_export_all",
|
||||
userId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to export SSH hosts" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /host/db/host/{id}:
|
||||
@@ -2051,6 +1730,7 @@ router.delete(
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.delete"),
|
||||
requireDataAccess,
|
||||
requireUnlockedHost,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const hostId = Array.isArray(req.params.id)
|
||||
@@ -2117,231 +1797,6 @@ router.delete(
|
||||
// the file-manager plugin, under /plugin-api/file-manager/, and command
|
||||
// history to the ssh-terminal plugin, under /plugin-api/ssh-terminal/.
|
||||
|
||||
/**
|
||||
* A share export leaves out every secret and credential link, the same as
|
||||
* it does for SSH.
|
||||
*/
|
||||
function shareableLogins(
|
||||
logins: ReturnType<typeof toPortableLogins>,
|
||||
shareMode: boolean,
|
||||
): ReturnType<typeof toPortableLogins> {
|
||||
if (!shareMode) return logins;
|
||||
const out: ReturnType<typeof toPortableLogins> = {};
|
||||
for (const [protocol, login] of Object.entries(logins)) {
|
||||
const declared = findHostProtocol(protocol);
|
||||
const secret = new Set(
|
||||
(declared?.credentialFields ?? [])
|
||||
.filter((field) => field.secret)
|
||||
.map((field) => field.key),
|
||||
);
|
||||
out[protocol] = {
|
||||
authType: login.authType === "credential" ? "direct" : login.authType,
|
||||
credentialId: null,
|
||||
username: login.username,
|
||||
password: null,
|
||||
fields: Object.fromEntries(
|
||||
Object.entries(login.fields).filter(
|
||||
([key]) => declared && !secret.has(key),
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function resolveHostCredentials(
|
||||
host: Record<string, unknown>,
|
||||
requestingUserId?: string,
|
||||
/**
|
||||
* Credentials already fetched for this request, keyed by id. The host list
|
||||
* preloads them in one query; single-host callers omit it and fall back to
|
||||
* fetching the one credential they need.
|
||||
*/
|
||||
preloadedCredentials?: Map<number, HostResolutionCredentialRecord>,
|
||||
): Promise<Record<string, unknown>> {
|
||||
try {
|
||||
const ownerId = (host.ownerId || host.userId) as string | undefined;
|
||||
if (
|
||||
requestingUserId &&
|
||||
ownerId &&
|
||||
requestingUserId !== ownerId &&
|
||||
typeof host.id === "number"
|
||||
) {
|
||||
const authHost = host as unknown as HostResolutionHostRecord;
|
||||
const needsPersonalCredential = requiresPersonalHostAuthentication(
|
||||
authHost,
|
||||
"ssh",
|
||||
);
|
||||
const baseSshOverrideState = {
|
||||
required: needsPersonalCredential,
|
||||
ownerAuthShared: !!host.shareSshAuth,
|
||||
};
|
||||
// Owner auth for the remote desktop protocols is always snapshotted
|
||||
// for recipients; only their own override credential varies per user.
|
||||
const authOverrides: Record<string, unknown> = {
|
||||
ssh: baseSshOverrideState,
|
||||
};
|
||||
const overrideCredentialIds =
|
||||
await createCurrentSharedHostAuthOverrideRepository().listCredentialIds(
|
||||
host.id,
|
||||
requestingUserId,
|
||||
);
|
||||
// Whether a plugin protocol is on is its plugin's host setting; the
|
||||
// client only offers an override for one that is.
|
||||
for (const { id: protocol } of listHostProtocols()) {
|
||||
authOverrides[protocol] = {
|
||||
credentialId: overrideCredentialIds[protocol],
|
||||
required: false,
|
||||
ownerAuthShared: true,
|
||||
};
|
||||
}
|
||||
const recipientHost: Record<string, unknown> = {
|
||||
...host,
|
||||
credentialId: null,
|
||||
password: null,
|
||||
key: null,
|
||||
keyPassword: null,
|
||||
keyType: null,
|
||||
authOverrides,
|
||||
};
|
||||
|
||||
try {
|
||||
const resolution = await resolveRecipientSharedHostAuthentication(
|
||||
authHost,
|
||||
host.id,
|
||||
requestingUserId,
|
||||
"ssh",
|
||||
);
|
||||
|
||||
if (resolution.source === "personal-override") {
|
||||
const credential = resolution.credential;
|
||||
return {
|
||||
...recipientHost,
|
||||
authOverrides: {
|
||||
...authOverrides,
|
||||
ssh: {
|
||||
credentialId: resolution.credentialId,
|
||||
required: false,
|
||||
ownerAuthShared: !!host.shareSshAuth,
|
||||
},
|
||||
},
|
||||
authType:
|
||||
credential.key || credential.privateKey
|
||||
? "key"
|
||||
: credential.password
|
||||
? "password"
|
||||
: "none",
|
||||
username: credential.username || recipientHost.username,
|
||||
password: credential.password,
|
||||
key: credential.privateKey || credential.key,
|
||||
keyPassword: credential.keyPassword,
|
||||
keyType: credential.keyType,
|
||||
};
|
||||
}
|
||||
|
||||
if (resolution.source === "owner-shared") {
|
||||
if (resolution.authType === "agent") {
|
||||
return {
|
||||
...recipientHost,
|
||||
authOverrides: {
|
||||
...authOverrides,
|
||||
ssh: {
|
||||
required: false,
|
||||
ownerAuthShared: true,
|
||||
},
|
||||
},
|
||||
authType: "agent",
|
||||
};
|
||||
}
|
||||
|
||||
const sharedAuth = resolution.secret;
|
||||
if (sharedAuth) {
|
||||
const resolvedUsername = pickResolvedUsername(
|
||||
recipientHost.username,
|
||||
sharedAuth.username,
|
||||
host.overrideCredentialUsername,
|
||||
);
|
||||
return {
|
||||
...recipientHost,
|
||||
authOverrides: {
|
||||
...authOverrides,
|
||||
ssh: {
|
||||
required: false,
|
||||
ownerAuthShared: true,
|
||||
},
|
||||
},
|
||||
authType: sharedAuth.key
|
||||
? "key"
|
||||
: sharedAuth.password
|
||||
? "password"
|
||||
: "none",
|
||||
username: resolvedUsername,
|
||||
password: sharedAuth.password,
|
||||
key: sharedAuth.key,
|
||||
keyPassword: sharedAuth.keyPassword,
|
||||
keyType: sharedAuth.keyType,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (resolution.source === "secretless") {
|
||||
return {
|
||||
...recipientHost,
|
||||
authOverrides: {
|
||||
...authOverrides,
|
||||
ssh: {
|
||||
required: false,
|
||||
ownerAuthShared: !!host.shareSshAuth,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// A missing/deleted override or snapshot behaves like unavailable auth.
|
||||
}
|
||||
|
||||
return recipientHost;
|
||||
}
|
||||
|
||||
if (host.credentialId && (host.userId || host.ownerId)) {
|
||||
const credentialId = host.credentialId as number;
|
||||
const credentialOwnerId = (host.ownerId || host.userId) as string;
|
||||
|
||||
const credential =
|
||||
preloadedCredentials?.get(credentialId) ??
|
||||
(await findUsableCredential(credentialId, credentialOwnerId));
|
||||
|
||||
if (credential) {
|
||||
const resolvedHost: Record<string, unknown> = {
|
||||
...host,
|
||||
password: pickResolvedPassword(host.password, credential.password),
|
||||
key: credential.key,
|
||||
keyPassword: credential.keyPassword,
|
||||
keyType: credential.keyType,
|
||||
};
|
||||
|
||||
const resolvedUsername = pickResolvedUsername(
|
||||
host.username,
|
||||
credential.username,
|
||||
host.overrideCredentialUsername,
|
||||
);
|
||||
if (resolvedUsername !== undefined) {
|
||||
resolvedHost.username = resolvedUsername;
|
||||
}
|
||||
|
||||
return resolvedHost;
|
||||
}
|
||||
}
|
||||
|
||||
return { ...host };
|
||||
} catch (error) {
|
||||
sshLogger.warn(
|
||||
`Failed to resolve credentials for host ${host.id}: ${getErrorMessage(error)}`,
|
||||
);
|
||||
return host;
|
||||
}
|
||||
}
|
||||
|
||||
registerHostFolderRoutes(router, {
|
||||
authenticateJWT,
|
||||
requireViewPermission: permissionManager.requirePermission("hosts.view"),
|
||||
@@ -2355,7 +1810,6 @@ registerHostFolderRoutes(router, {
|
||||
registerHostBulkRoutes(
|
||||
router,
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.create"),
|
||||
permissionManager.requirePermission("hosts.edit"),
|
||||
requireDataAccess,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import express, { type Request, type Response } from "express";
|
||||
import { databaseLogger } from "../../utils/logger.js";
|
||||
import { AuthManager } from "../../utils/auth-manager.js";
|
||||
import { logAudit, getRequestMeta } from "../../utils/audit-logger.js";
|
||||
import {
|
||||
createCurrentSettingsRepository,
|
||||
createCurrentUserPreferenceRepository,
|
||||
createCurrentUserRepository,
|
||||
} from "../repositories/factory.js";
|
||||
import { getPluginRuntime } from "../../plugins/index.js";
|
||||
import {
|
||||
LAYOUT_SETTING,
|
||||
LOOK_ID_PATTERN,
|
||||
THEME_SETTING,
|
||||
installedLayoutIds,
|
||||
resolveDefaultLook,
|
||||
safeLayoutForced,
|
||||
unavailableLooks,
|
||||
} from "../../plugins/looks.js";
|
||||
|
||||
const router = express.Router();
|
||||
const authManager = AuthManager.getInstance();
|
||||
const authenticateJWT = authManager.createAuthMiddleware();
|
||||
|
||||
async function adminDefaults() {
|
||||
const settings = createCurrentSettingsRepository();
|
||||
return {
|
||||
layout: await settings.get(LAYOUT_SETTING),
|
||||
theme: await settings.get(THEME_SETTING),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /user-preferences/look:
|
||||
* get:
|
||||
* summary: Get the layout and theme to show the current user
|
||||
* description: The user's own choice, the admin defaults (a layout no installed plugin brings reads as null), the default look of the bundled plugins, whether TERMIX_SAFE_LAYOUT forces the repair view, and installed layout or theme plugins that could not load. The browser resolves the final look from these.
|
||||
* tags:
|
||||
* - User Preferences
|
||||
* responses:
|
||||
* 200:
|
||||
* description: What the look is chosen from.
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* layoutId:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* themeId:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* defaults:
|
||||
* type: object
|
||||
* description: Admin defaults, null where unset.
|
||||
* properties:
|
||||
* layout:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* theme:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* defaultLook:
|
||||
* type: object
|
||||
* description: The default-look plugin's layout and theme, null where none is installed.
|
||||
* properties:
|
||||
* layout:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* theme:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* safeLayout:
|
||||
* type: boolean
|
||||
* unavailable:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: string
|
||||
* version:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* layouts:
|
||||
* type: array
|
||||
* items:
|
||||
* type: string
|
||||
* themes:
|
||||
* type: array
|
||||
* items:
|
||||
* type: string
|
||||
* error:
|
||||
* type: string
|
||||
*/
|
||||
router.get("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
try {
|
||||
const preferences =
|
||||
await createCurrentUserPreferenceRepository().findByUserId(userId);
|
||||
const { loader } = getPluginRuntime();
|
||||
const installed = installedLayoutIds(loader);
|
||||
const known = (id: string | null | undefined) =>
|
||||
id && installed.has(id) ? id : null;
|
||||
const defaults = await adminDefaults();
|
||||
res.json({
|
||||
layoutId: known(preferences?.layoutId),
|
||||
themeId: preferences?.themeId ?? null,
|
||||
defaults: { ...defaults, layout: known(defaults.layout) },
|
||||
defaultLook: resolveDefaultLook(loader),
|
||||
safeLayout: safeLayoutForced(),
|
||||
unavailable: unavailableLooks(loader),
|
||||
});
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to get the look", error, {
|
||||
operation: "get_look",
|
||||
userId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to get the look" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /user-preferences/look/defaults:
|
||||
* put:
|
||||
* summary: Set the default layout and theme (admin only)
|
||||
* description: What everyone sees until they choose their own. Null clears a default so the default look applies.
|
||||
* tags:
|
||||
* - User Preferences
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* layout:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* theme:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The defaults now in effect.
|
||||
* 400:
|
||||
* description: Not a layout or theme id.
|
||||
* 403:
|
||||
* description: Not an admin.
|
||||
*/
|
||||
router.put(
|
||||
"/defaults",
|
||||
authenticateJWT,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
try {
|
||||
const actor = await createCurrentUserRepository().findById(userId);
|
||||
if (!actor?.isAdmin) {
|
||||
return res.status(403).json({ error: "Not authorized" });
|
||||
}
|
||||
const body = (req.body ?? {}) as { layout?: unknown; theme?: unknown };
|
||||
const changes: Array<[string, unknown]> = [
|
||||
[LAYOUT_SETTING, body.layout],
|
||||
[THEME_SETTING, body.theme],
|
||||
];
|
||||
for (const [key, value] of changes) {
|
||||
if (
|
||||
value !== undefined &&
|
||||
value !== null &&
|
||||
(typeof value !== "string" || !LOOK_ID_PATTERN.test(value))
|
||||
) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: `${key} must be a layout or theme id, or null` });
|
||||
}
|
||||
}
|
||||
const settings = createCurrentSettingsRepository();
|
||||
for (const [key, value] of changes) {
|
||||
if (value === undefined) continue;
|
||||
if (value === null) await settings.delete(key);
|
||||
else await settings.set(key, value as string);
|
||||
}
|
||||
|
||||
const { ipAddress, userAgent } = getRequestMeta(req);
|
||||
await logAudit({
|
||||
userId,
|
||||
username: actor.username ?? userId,
|
||||
action: "update_default_look",
|
||||
resourceType: "setting",
|
||||
details: JSON.stringify({ layout: body.layout, theme: body.theme }),
|
||||
ipAddress,
|
||||
userAgent,
|
||||
success: true,
|
||||
});
|
||||
res.json(await adminDefaults());
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to set the default look", error, {
|
||||
operation: "set_default_look",
|
||||
userId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to set the default look" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export default router;
|
||||
@@ -13,7 +13,9 @@ import {
|
||||
createCurrentPluginRepository,
|
||||
} from "../repositories/factory.js";
|
||||
import { getPluginRuntime } from "../../plugins/index.js";
|
||||
import { resolvePluginDesktopMode } from "@termix-ssh/plugin-sdk/manifest";
|
||||
import { describePluginFrontend } from "../../plugins/assets.js";
|
||||
import { isDefaultLookPlugin } from "../../plugins/bundled-index.js";
|
||||
import { invalidatePluginPermissionCache } from "../../plugins/permissions.js";
|
||||
import { getPluginPublicHttpRoutes } from "../../plugins/http.js";
|
||||
import { getPluginPublicWsRoutes } from "../../plugins/ws.js";
|
||||
@@ -42,6 +44,7 @@ import {
|
||||
validateSettingsSave,
|
||||
type PluginSettingsScope,
|
||||
} from "../../plugins/settings.js";
|
||||
import { assertHostsUnlocked, sendHostLocked } from "../../hosts/locks.js";
|
||||
import {
|
||||
getAuditUsername,
|
||||
getRequestMeta,
|
||||
@@ -296,7 +299,9 @@ router.get("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
let features: string[] = [];
|
||||
let docs: string | undefined;
|
||||
let env: PluginEnvVar[] = [];
|
||||
let desktopMode: unknown = loaded?.manifest.desktop;
|
||||
let desktopMode: unknown = loaded
|
||||
? resolvePluginDesktopMode(loaded.manifest)
|
||||
: undefined;
|
||||
try {
|
||||
const manifest = JSON.parse(record.manifestJson) as {
|
||||
contributes?: unknown;
|
||||
@@ -312,8 +317,12 @@ router.get("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
dependencies?: Record<string, string>;
|
||||
optionalDependencies?: Record<string, string>;
|
||||
desktop?: unknown;
|
||||
runtime?: unknown;
|
||||
};
|
||||
desktopMode = loaded?.manifest.desktop ?? manifest?.desktop;
|
||||
desktopMode = loaded
|
||||
? resolvePluginDesktopMode(loaded.manifest)
|
||||
: (manifest?.desktop ??
|
||||
(manifest?.runtime === "desktop" ? "local" : undefined));
|
||||
contributes = manifest?.contributes ?? null;
|
||||
capabilities = Array.isArray(manifest?.capabilities)
|
||||
? (manifest.capabilities as string[])
|
||||
@@ -352,6 +361,7 @@ router.get("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
dependencies,
|
||||
optionalDependencies,
|
||||
docs,
|
||||
defaultLook: isDefaultLookPlugin(record.id),
|
||||
...describePluginFrontend(loaded),
|
||||
};
|
||||
|
||||
@@ -1869,6 +1879,18 @@ router.put(
|
||||
const inherit = Array.isArray(inheritRaw)
|
||||
? inheritRaw.filter((key): key is string => typeof key === "string")
|
||||
: [];
|
||||
// A managed host keeps its settings; only personal ones stay per user.
|
||||
const changesShared = [...Object.keys(written), ...inherit].some(
|
||||
(key) => !findField(manifest, "host", key)?.personal,
|
||||
);
|
||||
if (changesShared) {
|
||||
try {
|
||||
assertHostsUnlocked([hostId]);
|
||||
} catch (error) {
|
||||
if (sendHostLocked(res, error)) return;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const errors = await applySettings(
|
||||
userId,
|
||||
manifest,
|
||||
@@ -2279,6 +2301,63 @@ router.post(
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugins/{id}/restore-bundled:
|
||||
* post:
|
||||
* summary: Restore the bundled copy of a plugin
|
||||
* description: >
|
||||
* Drops any update downloaded over a plugin that ships with Termix and
|
||||
* loads the copy from the image again, so a broken release can be rolled
|
||||
* back from the layout repair view. The shipped version is pinned so
|
||||
* auto update does not bring the release back. Dependents restart.
|
||||
* tags:
|
||||
* - Plugins
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The restored version and the plugin's state.
|
||||
* 400:
|
||||
* description: Invalid plugin id.
|
||||
* 403:
|
||||
* description: The caller lacks admin.plugins.manage.
|
||||
* 409:
|
||||
* description: The plugin has no bundled copy, or a linked server manages it.
|
||||
*/
|
||||
router.post(
|
||||
"/:id/restore-bundled",
|
||||
authenticateJWT,
|
||||
requireManagePlugins,
|
||||
async (req: Request, res: Response) => {
|
||||
const pluginId = String(req.params.id);
|
||||
if (!ID_PATTERN.test(pluginId)) {
|
||||
res.status(400).json({ error: "Invalid plugin id" });
|
||||
return;
|
||||
}
|
||||
if (await refuseOnLinkedDesktop(res)) return;
|
||||
try {
|
||||
const { restoreBundledPlugin } = await import("../../plugins/manage.js");
|
||||
const result = await restoreBundledPlugin(pluginId);
|
||||
await auditPluginAction(req, "restore_bundled_plugin", pluginId, {
|
||||
version: result.version,
|
||||
});
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
sendManageError(
|
||||
res,
|
||||
error,
|
||||
"Failed to restore the bundled copy",
|
||||
"plugin_restore_bundled",
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugins/{id}:
|
||||
@@ -2306,7 +2385,7 @@ router.post(
|
||||
* 404:
|
||||
* description: No such plugin.
|
||||
* 409:
|
||||
* description: Other running plugins depend on it, or managed by a linked server.
|
||||
* description: Other running plugins depend on it, it is the default look, or a linked server manages it.
|
||||
*/
|
||||
router.delete(
|
||||
"/:id",
|
||||
|
||||
@@ -9,6 +9,12 @@ import {
|
||||
logAudit,
|
||||
} from "../../utils/audit-logger.js";
|
||||
import { isAuthOverrideProtocol } from "../../hosts/protocol-auth/registry.js";
|
||||
import {
|
||||
assertHostsUnlocked,
|
||||
hasHostLocks,
|
||||
requireUnlockedHost,
|
||||
sendHostLocked,
|
||||
} from "../../hosts/locks.js";
|
||||
import {
|
||||
SharedHostAuthOverrideService,
|
||||
SharedHostAuthOverrideServiceError,
|
||||
@@ -229,6 +235,7 @@ router.post(
|
||||
"/host/:id/share",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.share"),
|
||||
requireUnlockedHost,
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
|
||||
const hostId = parseInt(id, 10);
|
||||
@@ -451,6 +458,14 @@ router.post(
|
||||
}
|
||||
|
||||
try {
|
||||
if (hasHostLocks()) {
|
||||
const inFolder =
|
||||
await createCurrentHostFolderRepository().listHostsInFolder(
|
||||
userId,
|
||||
folder,
|
||||
);
|
||||
assertHostsUnlocked(inFolder.map((host) => host.id));
|
||||
}
|
||||
const targets = parseShareTargets(req.body ?? {});
|
||||
if (!targets) {
|
||||
return res.status(400).json({
|
||||
@@ -613,6 +628,7 @@ router.post(
|
||||
hostResults,
|
||||
});
|
||||
} catch (error) {
|
||||
if (sendHostLocked(res, error)) return;
|
||||
databaseLogger.error("Failed to share folder", error, {
|
||||
operation: "share_folder",
|
||||
folder,
|
||||
@@ -786,6 +802,7 @@ router.delete(
|
||||
router.patch(
|
||||
"/host/:id/access/:accessId",
|
||||
authenticateJWT,
|
||||
requireUnlockedHost,
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
|
||||
const accessIdParam = Array.isArray(req.params.accessId)
|
||||
@@ -908,6 +925,7 @@ router.patch(
|
||||
router.delete(
|
||||
"/host/:id/access/:accessId",
|
||||
authenticateJWT,
|
||||
requireUnlockedHost,
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
|
||||
const accessIdParam = Array.isArray(req.params.accessId)
|
||||
|
||||
@@ -2,13 +2,13 @@ import type { Router } from "express";
|
||||
import crypto from "crypto";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { nanoid } from "nanoid";
|
||||
import { recentActivity } from "../../plugins/activity-provider.js";
|
||||
import { AuthManager } from "../../utils/auth-manager.js";
|
||||
import { authLogger } from "../../utils/logger.js";
|
||||
import { loginRateLimiter } from "../../utils/login-rate-limiter.js";
|
||||
import {
|
||||
createCurrentCredentialRepository,
|
||||
createCurrentHostRepository,
|
||||
createCurrentRecentActivityRepository,
|
||||
createCurrentSettingsRepository,
|
||||
createCurrentSshCredentialUsageRepository,
|
||||
createCurrentUserRepository,
|
||||
@@ -68,7 +68,7 @@ export async function resetUserPassword(
|
||||
await userRepository.update(userId, { passwordHash });
|
||||
|
||||
await createCurrentSshCredentialUsageRepository().deleteByUserId(userId);
|
||||
await createCurrentRecentActivityRepository().deleteByUserId(userId);
|
||||
await recentActivity.deleteByUserId(userId);
|
||||
await createCurrentHostRepository().deleteByUserId(userId);
|
||||
await createCurrentCredentialRepository().deleteByUserId(userId);
|
||||
// A plugin holding this user's data (anything keyed by
|
||||
|
||||
@@ -32,8 +32,13 @@ const pickPreferences = (row?: UserPreferenceRecord | null) => ({
|
||||
compactHostView: row?.compactHostView ?? null,
|
||||
statusColorScheme: row?.statusColorScheme ?? null,
|
||||
customKeybindings: row?.customKeybindings ?? null,
|
||||
layoutId: row?.layoutId ?? null,
|
||||
themeId: row?.themeId ?? null,
|
||||
});
|
||||
|
||||
/** Layout and theme ids, the same shape the plugin manifest allows. */
|
||||
const LOOK_ID = /^[a-z][a-z0-9-]{1,39}$/;
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /user-preferences:
|
||||
@@ -104,6 +109,14 @@ const pickPreferences = (row?: UserPreferenceRecord | null) => ({
|
||||
* type: string
|
||||
* nullable: true
|
||||
* description: JSON-encoded array of the user's custom keybindings. An action's type is one of the shell's own or one a plugin declares in contributes.keybindingActions.
|
||||
* layoutId:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* description: The layout this user chose, overriding the admin default. Null follows the default.
|
||||
* themeId:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* description: The theme this user chose, overriding the admin default. Null follows the default.
|
||||
*/
|
||||
router.get("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -165,6 +178,14 @@ router.get("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
* customKeybindings:
|
||||
* type: string
|
||||
* description: JSON-encoded array of the user's custom keybindings. Each action is checked against the shell's own types and the parameters a plugin declares for its type.
|
||||
* layoutId:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* description: A layout id, or null to follow the admin default.
|
||||
* themeId:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* description: A theme id, or null to follow the admin default.
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Preferences updated successfully.
|
||||
@@ -186,6 +207,8 @@ router.put("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
confirmTabClose,
|
||||
hiddenRailTabs,
|
||||
customKeybindings,
|
||||
layoutId,
|
||||
themeId,
|
||||
} = req.body as {
|
||||
reopenTabsOnLogin?: boolean;
|
||||
theme?: string | null;
|
||||
@@ -201,6 +224,8 @@ router.put("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
confirmTabClose?: boolean | null;
|
||||
hiddenRailTabs?: string | null;
|
||||
customKeybindings?: string | null;
|
||||
layoutId?: string | null;
|
||||
themeId?: string | null;
|
||||
};
|
||||
// showHostTags, hostTrayOnClick, compactHostView, statusColorScheme are no
|
||||
// longer writable here -- they moved to /host-sidebar/preferences as of the
|
||||
@@ -258,6 +283,18 @@ router.put("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
}
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries({ layoutId, themeId })) {
|
||||
if (
|
||||
value !== undefined &&
|
||||
value !== null &&
|
||||
(typeof value !== "string" || !LOOK_ID.test(value))
|
||||
) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: `${key} must be a layout or theme id, or null` });
|
||||
}
|
||||
}
|
||||
|
||||
const boolFields: Record<string, boolean | null | undefined> = {
|
||||
commandPaletteEnabled,
|
||||
pinAppRail,
|
||||
@@ -290,6 +327,8 @@ router.put("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
if (confirmTabClose !== undefined) updates.confirmTabClose = confirmTabClose;
|
||||
if (customKeybindings !== undefined)
|
||||
updates.customKeybindings = customKeybindings;
|
||||
if (layoutId !== undefined) updates.layoutId = layoutId;
|
||||
if (themeId !== undefined) updates.themeId = themeId;
|
||||
|
||||
if (Object.keys(updates).length === 1) {
|
||||
return res.status(400).json({ error: "No preferences provided" });
|
||||
|
||||
@@ -6,11 +6,6 @@ import {
|
||||
setGlobalLogLevel,
|
||||
} from "../../utils/logger.js";
|
||||
import { logAudit, getRequestMeta } from "../../utils/audit-logger.js";
|
||||
import {
|
||||
AUDIT_FORWARD_TOKEN_SETTING,
|
||||
AUDIT_FORWARD_URL_ENV,
|
||||
AUDIT_FORWARD_URL_SETTING,
|
||||
} from "../../utils/audit-forwarder.js";
|
||||
import {
|
||||
NOTIFICATION_PRIVATE_ALLOWLIST_KEY,
|
||||
parseNotificationAllowlist,
|
||||
@@ -20,6 +15,8 @@ import {
|
||||
createCurrentUserRepository,
|
||||
} from "../repositories/factory.js";
|
||||
import type { UserRecord } from "../repositories/user-repository.js";
|
||||
import { isForceHttpsEnabled, setForceHttps } from "../../tls/https-policy.js";
|
||||
import { getTlsConfig } from "../../tls/tls-service.js";
|
||||
|
||||
async function getAdminActor(
|
||||
userId: string | undefined,
|
||||
@@ -194,46 +191,39 @@ export function registerUserSettingsRoutes(
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /users/audit-forwarding:
|
||||
* /users/https-settings:
|
||||
* get:
|
||||
* summary: Get audit log forwarding settings (admin only)
|
||||
* summary: Get the HTTPS redirect setting (admin only)
|
||||
* description: Whether plain HTTP is redirected to HTTPS with HSTS, and whether HTTPS is on at all. The redirect only applies while HTTPS is on.
|
||||
* tags:
|
||||
* - Users
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Forwarding target. The token itself is never returned.
|
||||
* description: forceHttps and tlsEnabled.
|
||||
* 403:
|
||||
* description: Not authorized.
|
||||
*/
|
||||
router.get("/audit-forwarding", authenticateJWT, async (req, res) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
router.get("/https-settings", authenticateJWT, async (req, res) => {
|
||||
try {
|
||||
if (!(await getAdminActor(userId))) {
|
||||
if (!(await getAdminActor((req as AuthenticatedRequest).userId))) {
|
||||
return res.status(403).json({ error: "Not authorized" });
|
||||
}
|
||||
const settingsRepository = createCurrentSettingsRepository();
|
||||
const url =
|
||||
(await settingsRepository.get(AUDIT_FORWARD_URL_SETTING)) ?? "";
|
||||
const hasToken = !!(await settingsRepository.get(
|
||||
AUDIT_FORWARD_TOKEN_SETTING,
|
||||
));
|
||||
res.json({
|
||||
url,
|
||||
hasToken,
|
||||
envConfigured: !!process.env[AUDIT_FORWARD_URL_ENV]?.trim(),
|
||||
forceHttps: await isForceHttpsEnabled(),
|
||||
tlsEnabled: getTlsConfig().enabled,
|
||||
});
|
||||
} catch (err) {
|
||||
authLogger.error("Failed to get audit forwarding settings", err);
|
||||
res
|
||||
.status(500)
|
||||
.json({ error: "Failed to get audit forwarding settings" });
|
||||
authLogger.error("Failed to get HTTPS settings", err);
|
||||
res.status(500).json({ error: "Failed to get HTTPS settings" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /users/audit-forwarding:
|
||||
* /users/https-settings:
|
||||
* patch:
|
||||
* summary: Update audit log forwarding settings (admin only)
|
||||
* description: Sets the collector URL audit entries are shipped to. An empty URL disables forwarding and clears the stored token. Omitting token keeps the stored one.
|
||||
* summary: Update the HTTPS redirect setting (admin only)
|
||||
* description: Turns the redirect from HTTP to HTTPS and the HSTS header on or off. Off by default so reverse proxies keep working.
|
||||
* tags:
|
||||
* - Users
|
||||
* requestBody:
|
||||
@@ -243,71 +233,43 @@ export function registerUserSettingsRoutes(
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* url:
|
||||
* type: string
|
||||
* token:
|
||||
* type: string
|
||||
* forceHttps:
|
||||
* type: boolean
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Setting updated.
|
||||
* 400:
|
||||
* description: Invalid value.
|
||||
* 403:
|
||||
* description: Not authorized.
|
||||
*/
|
||||
router.patch("/audit-forwarding", authenticateJWT, async (req, res) => {
|
||||
router.patch("/https-settings", authenticateJWT, async (req, res) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
try {
|
||||
const actor = await getAdminActor(userId);
|
||||
if (!actor) {
|
||||
return res.status(403).json({ error: "Not authorized" });
|
||||
}
|
||||
const { url, token } = req.body ?? {};
|
||||
if (
|
||||
typeof url !== "string" ||
|
||||
(token !== undefined && typeof token !== "string")
|
||||
) {
|
||||
return res.status(400).json({ error: "url must be a string" });
|
||||
const { forceHttps } = req.body ?? {};
|
||||
if (typeof forceHttps !== "boolean") {
|
||||
return res.status(400).json({ error: "forceHttps must be a boolean" });
|
||||
}
|
||||
const trimmedUrl = url.trim();
|
||||
if (trimmedUrl && !/^https?:\/\//i.test(trimmedUrl)) {
|
||||
return res.status(400).json({ error: "url must be http(s)" });
|
||||
}
|
||||
|
||||
const settingsRepository = createCurrentSettingsRepository();
|
||||
if (!trimmedUrl) {
|
||||
await settingsRepository.delete(AUDIT_FORWARD_URL_SETTING);
|
||||
await settingsRepository.delete(AUDIT_FORWARD_TOKEN_SETTING);
|
||||
} else {
|
||||
await settingsRepository.set(AUDIT_FORWARD_URL_SETTING, trimmedUrl);
|
||||
if (token !== undefined) {
|
||||
if (token.trim()) {
|
||||
await settingsRepository.set(
|
||||
AUDIT_FORWARD_TOKEN_SETTING,
|
||||
token.trim(),
|
||||
);
|
||||
} else {
|
||||
await settingsRepository.delete(AUDIT_FORWARD_TOKEN_SETTING);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await setForceHttps(forceHttps);
|
||||
const { ipAddress, userAgent } = getRequestMeta(req);
|
||||
await logAudit({
|
||||
userId,
|
||||
username: actor.username ?? userId,
|
||||
action: "update_audit_forwarding",
|
||||
action: "update_force_https",
|
||||
resourceType: "setting",
|
||||
details: JSON.stringify({ enabled: !!trimmedUrl }),
|
||||
details: JSON.stringify({ forceHttps }),
|
||||
ipAddress,
|
||||
userAgent,
|
||||
success: true,
|
||||
});
|
||||
|
||||
res.json({ url: trimmedUrl, hasToken: !!token?.trim() });
|
||||
res.json({ forceHttps, tlsEnabled: getTlsConfig().enabled });
|
||||
} catch (err) {
|
||||
authLogger.error("Failed to update audit forwarding settings", err);
|
||||
res
|
||||
.status(500)
|
||||
.json({ error: "Failed to update audit forwarding settings" });
|
||||
authLogger.error("Failed to set HTTPS settings", err);
|
||||
res.status(500).json({ error: "Failed to set HTTPS settings" });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -61,4 +61,38 @@ export function registerUserSocketTicketRoutes(
|
||||
res.status(500).json({ error: "Failed to issue a socket ticket" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /users/ws-ticket/api-key:
|
||||
* post:
|
||||
* summary: Get a WebSocket ticket for an API key
|
||||
* description: For another Termix server that manages this one with an API key. Returns a token that is valid for one minute and only opens plugin WebSockets, as the key's user. It cannot call any other route.
|
||||
* tags:
|
||||
* - Users
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The ticket.
|
||||
* 401:
|
||||
* description: The request did not use an API key.
|
||||
* 500:
|
||||
* description: Failed to issue the ticket.
|
||||
*/
|
||||
router.post("/ws-ticket/api-key", authenticateJWT, async (req, res) => {
|
||||
const authReq = req as AuthenticatedRequest;
|
||||
if (!authReq.apiKeyId) {
|
||||
return res.status(401).json({ error: "An API key is required" });
|
||||
}
|
||||
try {
|
||||
const ticket = await authManager.issueApiKeySocketTicket(
|
||||
authReq.userId,
|
||||
authReq.apiKeyId,
|
||||
);
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.json({ ticket });
|
||||
} catch (err) {
|
||||
authLogger.error("Failed to issue an API key socket ticket", err);
|
||||
res.status(500).json({ error: "Failed to issue a socket ticket" });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import { registerUserSettingsRoutes } from "./user-settings-routes.js";
|
||||
import { registerTlsRoutes } from "./tls-routes.js";
|
||||
import { registerUserSessionRoutes } from "./user-session-routes.js";
|
||||
import { registerUserSocketTicketRoutes } from "./user-socket-ticket-routes.js";
|
||||
import { shownIdentity } from "../../sync/shown-identity.js";
|
||||
import { registerUserExternalAccountRoutes } from "./user-external-account-routes.js";
|
||||
import { registerUserPasswordResetRoutes } from "./user-password-reset-routes.js";
|
||||
import { registerUserAdminRoutes } from "./user-admin-routes.js";
|
||||
@@ -61,6 +62,7 @@ import {
|
||||
syncSharedCredentialsForUserRoles,
|
||||
} from "../../auth/session-issuer.js";
|
||||
import { EXTERNAL_AUTO_PROVISION_KEY } from "../../auth/provisioning.js";
|
||||
import { evaluateAuthPolicy } from "../../auth/policy.js";
|
||||
|
||||
const authManager = AuthManager.getInstance();
|
||||
|
||||
@@ -420,9 +422,21 @@ router.post("/proxy-login", async (req, res) => {
|
||||
userRecord.id,
|
||||
"trusted_proxy_login_role_shared_credentials",
|
||||
);
|
||||
// The proxy owns second factors, so only the session length applies.
|
||||
const policy = await evaluateAuthPolicy({
|
||||
userId: userRecord.id,
|
||||
methodId: "proxy",
|
||||
external: true,
|
||||
deviceType: deviceInfo.type,
|
||||
trustedDevice: false,
|
||||
mfaSatisfied: false,
|
||||
secondFactors: [],
|
||||
});
|
||||
const token = await authManager.generateJWTToken(userRecord.id, {
|
||||
deviceType: deviceInfo.type,
|
||||
deviceInfo: deviceInfo.deviceInfo,
|
||||
maxAgeSeconds: policy.maxSessionSeconds,
|
||||
idleTimeoutSeconds: policy.idleTimeoutSeconds,
|
||||
});
|
||||
const payload = await authManager.verifyJWTToken(token);
|
||||
const { ipAddress, userAgent } = getRequestMeta(req);
|
||||
@@ -443,7 +457,16 @@ router.post("/proxy-login", async (req, res) => {
|
||||
});
|
||||
|
||||
return res
|
||||
.cookie("jwt", token, authManager.getSecureCookieOptions(req))
|
||||
.cookie(
|
||||
"jwt",
|
||||
token,
|
||||
authManager.getSecureCookieOptions(
|
||||
req,
|
||||
policy.maxSessionSeconds
|
||||
? Math.min(24 * 60 * 60 * 1000, policy.maxSessionSeconds * 1000)
|
||||
: undefined,
|
||||
),
|
||||
)
|
||||
.json({
|
||||
enabled: true,
|
||||
success: true,
|
||||
@@ -546,30 +569,6 @@ router.post("/logout", authenticateJWT, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* On a desktop linked to a server, the account it is signed in to there.
|
||||
* That account is who the user is; the local profile only mirrors it.
|
||||
*/
|
||||
async function describeDesktopLink(userId: string) {
|
||||
if (process.env.ELECTRON_EMBEDDED !== "true") return null;
|
||||
try {
|
||||
const { getLink } = await import("../../sync/client/link-store.js");
|
||||
const link = await getLink();
|
||||
if (!link || link.userId !== userId) return null;
|
||||
return {
|
||||
serverUrl: link.serverUrl,
|
||||
serverName: link.serverName,
|
||||
username: link.account?.username ?? link.remoteUsername,
|
||||
isAdmin: !!link.account?.isAdmin,
|
||||
roles: link.account?.roles ?? [],
|
||||
permissions: link.account?.permissions ?? [],
|
||||
status: link.status,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /users/me:
|
||||
@@ -602,18 +601,21 @@ router.get("/me", authenticateJWT, async (req: Request, res: Response) => {
|
||||
|
||||
const hasPassword = user.passwordHash && user.passwordHash.trim() !== "";
|
||||
const isDualAuth = hasPassword && isExternalAccount(user);
|
||||
const shown = await shownIdentity(user);
|
||||
|
||||
res.json({
|
||||
userId: user.id,
|
||||
username: user.username,
|
||||
is_admin: !!user.isAdmin,
|
||||
username: shown.username,
|
||||
is_admin: shown.isAdmin,
|
||||
is_external: isExternalAccount(user),
|
||||
is_dual_auth: isDualAuth,
|
||||
// Any second factor; the name is what 2.8 clients read.
|
||||
totp_enabled: await createCurrentUserAuthRepository().hasSecondFactor(
|
||||
user.id,
|
||||
),
|
||||
linked: await describeDesktopLink(user.id),
|
||||
linked: shown.linked,
|
||||
// "second-factor-setup" while the login policy wants a factor set up.
|
||||
restriction: (req as AuthenticatedRequest).sessionRestriction ?? null,
|
||||
});
|
||||
} catch (err) {
|
||||
authLogger.error("Failed to get username", err);
|
||||
@@ -719,7 +721,11 @@ router.post("/internal/auto-session", async (req, res) => {
|
||||
|
||||
const userRepository = createCurrentUserRepository();
|
||||
const allUsers = await userRepository.listAll();
|
||||
const userRecord = resolveDesktopAutoSessionUser(allUsers);
|
||||
const { getSavedActiveUserId } = await import("../../sync/accounts.js");
|
||||
const userRecord = resolveDesktopAutoSessionUser(
|
||||
allUsers,
|
||||
await getSavedActiveUserId(),
|
||||
);
|
||||
if (!userRecord) {
|
||||
return res.status(403).json({
|
||||
error: "No local users exist",
|
||||
@@ -730,10 +736,11 @@ router.post("/internal/auto-session", async (req, res) => {
|
||||
if (existingToken) {
|
||||
const existingPayload = await authManager.verifyJWTToken(existingToken);
|
||||
if (existingPayload?.userId === userRecord.id) {
|
||||
const shownNow = await shownIdentity(userRecord);
|
||||
return res.json({
|
||||
success: true,
|
||||
is_admin: !!userRecord.isAdmin,
|
||||
username: userRecord.username,
|
||||
is_admin: shownNow.isAdmin,
|
||||
username: shownNow.username,
|
||||
token: existingToken,
|
||||
});
|
||||
}
|
||||
@@ -745,10 +752,11 @@ router.post("/internal/auto-session", async (req, res) => {
|
||||
rememberMe: true,
|
||||
});
|
||||
|
||||
const shown = await shownIdentity(userRecord);
|
||||
const response = {
|
||||
success: true,
|
||||
is_admin: !!userRecord.isAdmin,
|
||||
username: userRecord.username,
|
||||
is_admin: shown.isAdmin,
|
||||
username: shown.username,
|
||||
token,
|
||||
};
|
||||
|
||||
@@ -1543,7 +1551,7 @@ registerUserSocketTicketRoutes(router, { authenticateJWT, authManager });
|
||||
registerTlsRoutes(router, authenticateJWT);
|
||||
|
||||
registerUserApiKeyRoutes(router, requireAdmin);
|
||||
registerBrandingRoutes(router, requireAdmin);
|
||||
registerBrandingRoutes(router);
|
||||
|
||||
registerAuthRoutes(router);
|
||||
registerAuthCompatRoutes(router);
|
||||
|
||||
Reference in new issue
Block a user