feat: move the terminal fully into the ssh-terminal plugin (B9)

This commit is contained in:
LukeGus committed 2026-09-23 21:41:22 -05:00
1 parent 535126fd1b
commit 79d77678c9
309 files changed
+41789 -14958

No files matched your search

+19
View File
@@ -21,7 +21,9 @@ import type {
PluginShareableRole,
} from "@termix/plugin-sdk/backend";
import type { PluginManifest } from "@termix/plugin-sdk/manifest";
import { PluginCapabilityError } from "@termix/plugin-sdk/backend";
import { assertCapability } from "./permissions.js";
import { hostSessionStatus } from "../hosts/host-session-status.js";
import { getActor } from "./actor.js";
type AuditFn = (
@@ -392,5 +394,22 @@ export function createPluginHosts({ manifest, audit }: Deps): PluginHosts {
.filter((r) => !r.isSystem)
.map((r) => ({ id: r.id, name: r.name, displayName: r.displayName }));
},
// Synchronous so a transport can call it from an ssh2 "ready" handler, so
// only the declaration is checked here, like ctx.http.router.
trackSession: (hostId: number) => {
if (!declared.includes("hosts:read")) {
throw new PluginCapabilityError(pluginId, "hosts:read");
}
return hostSessionStatus.register(hostId);
},
recordActivity: async (hostId, type, hostName) => {
await requireRead();
const userId = actingUser();
const { recordRecentActivity } =
await import("../services/recent-activity.js");
await recordRecentActivity(userId, { type, hostId, hostName });
},
};
}
+93 -3
View File
@@ -13,12 +13,16 @@ import type {
PluginSshHost,
} from "@termix/plugin-sdk/backend";
import type { PluginManifest } from "@termix/plugin-sdk/manifest";
import { PluginCapabilityError } from "@termix/plugin-sdk/backend";
import {
PluginCapabilityError,
PluginSshInteractionError,
} from "@termix/plugin-sdk/backend";
import { assertCapability } from "./permissions.js";
import { getActor } from "./actor.js";
import type { DisposableBag } from "./disposables.js";
import {
getSshAuthProvider,
listSshAuthProviders,
registerKeyboardInteractiveInterceptor,
registerSshAuthProvider,
} from "../hosts/connect/auth-provider-registry.js";
@@ -55,6 +59,7 @@ const PLUGIN_PURPOSES = new Set<SshConnectPurpose>([
"tunnel",
"file-manager",
"file-transfer",
"terminal",
]);
function purposeOf(options?: PluginSshConnectOptions): SshConnectPurpose {
@@ -222,6 +227,21 @@ export function createPluginSsh({ manifest, bag, audit }: Deps): PluginSsh {
poolKey,
resolveHost: async (hostId, options) => {
await checkSsh(true);
const userId = actingUser(hostId);
const { resolveHostById, resolveHostBySyncId } =
await import("../hosts/host-resolver.js");
const resolved = options?.syncId
? await resolveHostBySyncId(options.syncId, userId)
: await resolveHostById(hostId, userId);
await audit("ssh_resolve_host", describeHost(hostId), {
success: !!resolved,
errorMessage: resolved ? undefined : "Host not found",
});
return (resolved as unknown as PluginSshHost | null) ?? null;
},
prepare: async (host, options) => {
await checkSsh(true);
const { buildConnectConfig } =
@@ -232,22 +252,38 @@ export function createPluginSsh({ manifest, bag, audit }: Deps): PluginSsh {
client: options.client as never,
serverHostId: options.serverHostId,
log: options.log,
interactive: options.interactive,
hostKeySocket: (options.hostKeySocket ?? null) as never,
});
await audit("ssh_prepare", describeHost(host), {
success: built.outcome.status === "ready",
errorMessage:
built.outcome.status === "ready" ? undefined : built.outcome.message,
});
return { config: built.config, outcome: built.outcome };
const provider = built.provider;
const target = host as SshConnectHost;
return {
config: built.config,
outcome: built.outcome,
authType: provider?.type ?? null,
onBanner: provider?.onBanner
? (banner: string) =>
provider.onBanner!(banner, target, built.env) as never
: undefined,
onAuthFailed: provider?.onAuthFailed
? (context) => provider.onAuthFailed!(target, built.env, context)
: undefined,
};
},
openTransport: async (host, config) => {
openTransport: async (host, config, transportOptions) => {
await checkSsh(false);
const { openSshTransport } =
await import("../hosts/connect/transport.js");
const opened = await openSshTransport(
host as SshConnectHost,
config as MutableConnectConfig,
transportOptions,
);
if (opened.jumpClient) {
const jumpClient = opened.jumpClient;
@@ -261,6 +297,60 @@ export function createPluginSsh({ manifest, bag, audit }: Deps): PluginSsh {
return opened;
},
startInteraction: async (interaction, request) => {
await checkSsh(true);
const userId = actingUser(request.hostId);
ensureCoreSshAuthProviders();
const { createCurrentHostResolutionRepository } =
await import("../database/repositories/factory.js");
const host = await createCurrentHostResolutionRepository().findHostById(
request.hostId,
userId,
);
if (!host) throw new PluginSshInteractionError("Host not found");
const own = getSshAuthProvider(host.authType as string);
const provider =
own?.interaction === interaction && own.startInteraction
? own
: listSshAuthProviders().find(
(candidate) =>
candidate.interaction === interaction &&
candidate.startInteraction,
);
if (!provider?.startInteraction) {
throw new PluginSshInteractionError(
`No enabled provider handles ${interaction} sign-in`,
);
}
await audit("ssh_start_interaction", describeHost(request.hostId), {
success: true,
});
await provider.startInteraction({
userId,
hostId: request.hostId,
host: {
name: host.name as string | null,
ip: host.ip as string,
username: host.username as string,
},
socket: request.socket as never,
requestOrigin: request.requestOrigin,
payload: request.payload ?? {},
});
},
cancelInteraction: async (interaction, request) => {
await checkSsh(false);
const userId = actingUser(request.hostId ?? 0);
ensureCoreSshAuthProviders();
for (const provider of listSshAuthProviders()) {
if (provider.interaction !== interaction) continue;
if (!provider.cancelInteraction) continue;
await provider.cancelInteraction({ userId, ...request });
}
},
classifyKeyboardInteractive: (round, host) => {
ensureCoreSshAuthProviders();
return classifyKeyboardInteractive(round, host as SshConnectHost);
+23
View File
@@ -640,6 +640,29 @@ export function createPluginContext(
openIsolatedWindow: (request) => desktopOpenIsolatedWindow(request),
},
audit: {
// Attribution comes from the runtime: the actor, never a plugin value.
record: async (entry) => {
try {
const { logAudit } = await import("../utils/audit-logger.js");
const actor = getActor() ?? "system";
await logAudit({
userId: actor,
username: actor,
action: entry.action,
resourceType: entry.resourceType ?? "plugin",
resourceId: entry.resourceId ?? pluginId,
resourceName: entry.resourceName ?? manifest.name,
details: entry.details ?? `via plugin ${pluginId}`,
success: entry.success,
errorMessage: entry.errorMessage,
});
} catch {
// Auditing must never break the caller.
}
},
},
/**
* Background work acts as a named user. Always audited, because "this ran
* as someone" is exactly the thing an operator needs to be able to see.
+19
View File
@@ -166,6 +166,25 @@ export function getRegistration(
return services.get(service);
}
/**
* A plugin service as core itself calls it, or undefined while no plugin
* provides a compatible version.
*
* Core is not a plugin and already authorized the request it is serving, so
* this skips the per-call permission check a plugin's handle runs. It is the
* same object plugins get. Session sharing reaching the terminal's live
* sessions is the first caller.
*/
export function getServiceImplementation<T extends object>(
service: string,
versionRange: string,
): T | undefined {
const registration = services.get(service);
if (!registration) return undefined;
if (!semver.satisfies(registration.version, versionRange)) return undefined;
return registration.implementation as T;
}
export function listServices(): ServiceRegistration[] {
return [...services.values()];
}
+14 -1
View File
@@ -159,6 +159,8 @@ export async function handlePluginUpgrade(
return true;
}
userId = resolved;
} else if (route.options.optionalAuth) {
userId = (await verifyToken(request)) ?? "";
}
if (route.rawHandler) {
@@ -175,6 +177,17 @@ export async function handlePluginUpgrade(
return true;
}
const { getClientIp, getRequestOrigin } =
await import("../utils/request-origin.js");
const { DataCrypto } = await import("../utils/data-crypto.js");
const connection = {
userId,
request,
clientIp: getClientIp(request as never),
requestOrigin: getRequestOrigin(request as never),
isDataUnlocked: () => !!userId && !!DataCrypto.getUserDataKey(userId),
};
server.handleUpgrade(request, socket, head, (ws: WebSocket) => {
const handler = route.handler;
if (!handler) {
@@ -182,7 +195,7 @@ export async function handlePluginUpgrade(
return;
}
runAsActor(userId || "anonymous", "request", () => {
void Promise.resolve(handler({ userId, request, socket: ws })).catch(
void Promise.resolve(handler({ ...connection, socket: ws })).catch(
(error) => {
pluginLogger.error(
`Plugin ${route.pluginId} socket ${route.path} failed`,