Self-hosted, plugin-based server management.
TypeScript dockerhomelabpluginsrdpremote-desktopself-hostedserver-managementsftpsshterminaltermixvnc
/**
* HTTP for plugins: one mount point, one set of middleware, no ports.
*
* A plugin calls ctx.http.router() and gets an Express Router that core mounts
* at /plugin-api/<id>/. Everything a route needs in front of it runs here
* rather than in the plugin:
*
* 1. auth, unless the path was declared public;
* 2. the actor, so ctx and core APIs know who is calling;
* 3. an enabled check, so a disabled plugin answers 503 rather than 404;
* 4. body limits;
* 5. an error wrapper that logs against the plugin and leaks nothing.
*
* The wrapper never touches the response body, so SSE, file downloads and
* multipart uploads stream through untouched.
*/
import express, {
type NextFunction,
type Request,
type Response,
type Router,
} from "express";
import type {
PluginMiddleware,
PluginRouterOptions,
} from "@termix-ssh/plugin-sdk/backend";
import type { PluginManifest } from "@termix-ssh/plugin-sdk/manifest";
import { pluginLogger } from "../utils/logger.js";
import { AuthManager } from "../utils/auth-manager.js";
import { runAsActor } from "./actor.js";
import { hasCapability } from "./permissions.js";
import { declaredPermissions, resolvePermission } from "./rbac.js";
/** Matches what core's own routes accept, so moving a route changes nothing. */
const DEFAULT_BODY_LIMIT = "2mb";
/** Routers by plugin id, read by the dispatcher in plugin-api-routes.ts. */
const routers = new Map<string, Router>();
/**
* Requests per minute one address may make to one plugin's public routes.
* They run without a login, so they are the cheap way to hammer a plugin.
*/
const MAX_PLUGIN_PUBLIC_RATE_LIMIT = 10_000;
/** The admin's limit when set, else the plugin's own, else 120. */
function publicRateLimit(pluginLimit?: number): number {
const parsed = Number(process.env.TERMIX_PLUGIN_PUBLIC_RATE_LIMIT);
if (Number.isFinite(parsed) && parsed > 0) return parsed;
if (Number.isFinite(pluginLimit) && (pluginLimit as number) > 0) {
return Math.min(pluginLimit as number, MAX_PLUGIN_PUBLIC_RATE_LIMIT);
}
return 120;
}
const PUBLIC_RATE_WINDOW_MS = 60_000;
const publicHits = new Map<string, { count: number; resetAt: number }>();
/** True when this request is over the public route limit. */
export function overPublicRateLimit(
pluginId: string,
ip: string,
now = Date.now(),
pluginLimit?: number,
): boolean {
if (publicHits.size > 10_000) {
for (const [hitKey, entry] of publicHits) {
if (entry.resetAt <= now) publicHits.delete(hitKey);
}
}
const hitKey = `${pluginId}|${ip}`;
const entry = publicHits.get(hitKey);
if (!entry || entry.resetAt <= now) {
publicHits.set(hitKey, { count: 1, resetAt: now + PUBLIC_RATE_WINDOW_MS });
return false;
}
entry.count++;
return entry.count > publicRateLimit(pluginLimit);
}
/** Test seam. */
export function resetPublicRateLimits(): void {
publicHits.clear();
}
/** Declared public paths by plugin id, for the admin plugin details. */
const publicRoutes = new Map<string, string[]>();
export function getPluginPublicHttpRoutes(pluginId: string): string[] {
return [...(publicRoutes.get(pluginId) ?? [])];
}
export function getPluginRouter(pluginId: string): Router | undefined {
return routers.get(pluginId);
}
export function unregisterPluginHttp(pluginId: string): void {
publicRoutes.delete(pluginId);
if (!routers.delete(pluginId)) return;
pluginLogger.info(`Unmounted /plugin-api/${pluginId}`, {
operation: "plugin_http_unmount",
});
}
/**
* Whether the plugin is currently running.
*
* Injected rather than imported so this module does not depend on the loader,
* which imports ctx.ts, which would close a cycle.
*/
type IsEnabled = (pluginId: string) => boolean;
let isPluginEnabled: IsEnabled = () => true;
export function setPluginEnabledCheck(check: IsEnabled): void {
isPluginEnabled = check;
}
/**
* Whether a plugin with this id is installed at all, running or not. A
* disabled plugin has no router or socket routes left, so this is what tells
* "disabled" (503) apart from "no such plugin" (404).
*/
let isInstalled: IsEnabled = () => false;
export function setPluginInstalledCheck(check: IsEnabled): void {
isInstalled = check;
}
export function isPluginInstalled(pluginId: string): boolean {
return isInstalled(pluginId);
}
/** Test seam, so one test's stub does not leak into the next. */
export function resetPluginHttp(): void {
routers.clear();
publicRoutes.clear();
isPluginEnabled = () => true;
isInstalled = () => false;
}
function normalizePublicPath(path: string): string {
const trimmed = path.trim();
const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
return withSlash.length > 1 && withSlash.endsWith("/")
? withSlash.slice(0, -1)
: withSlash;
}
/**
* Compiles a declared public path into a matcher.
*
* Express-style ":param" segments are supported, because the routes that have
* to be public are usually keyed by a token ("/webhook/:token"). A parameter
* matches exactly one segment and never a slash, so ":token" cannot swallow
* the rest of the path and turn one declared route into a prefix hole.
*
* A trailing "/*" is the one deliberate prefix: it matches the path itself and
* anything below it, for a proxied page that loads its own subpaths.
*/
function compilePublicPath(path: string): RegExp {
const prefix = path.endsWith("/*");
const escaped = (prefix ? path.slice(0, -2) : path)
.split("/")
.map((segment) => {
if (segment.startsWith(":")) return "[^/]+";
return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
})
.join("/");
return new RegExp(prefix ? `^${escaped}(?:/.*)?$` : `^${escaped}$`);
}
interface PublicPath {
declared: string;
pattern: RegExp;
}
interface RouterLayer {
route?: {
path?: unknown;
_handlesMethod?: (method: string) => boolean;
};
match?: (path: string) => boolean;
}
function segments(path: string): string[] {
return normalizePublicPath(path).split("/").slice(1);
}
/**
* Whether a declared public path names this registered route: literal
* segments must be equal and a ":param" must sit where the route has one, so
* "/webhook/:token" never covers a sibling "/webhook/config".
*/
function declaredCoversRoute(declared: string, routePath: string): boolean {
const prefix = declared.endsWith("/*");
const want = segments(prefix ? declared.slice(0, -2) : declared);
const have = segments(routePath);
if (prefix ? have.length < want.length : have.length !== want.length) {
return false;
}
return want.every((segment, index) =>
segment.startsWith(":")
? have[index].startsWith(":")
: segment.toLowerCase() === have[index].toLowerCase(),
);
}
/**
* Whether the request is for a declared public path.
*
* Full-path match only, and only for the route that will actually answer:
* the first route in the plugin's router that matches the path and method
* has to be the one the declaration names. So a public "/webhook/:token"
* registered for POST does not open GET, and does not open a literal sibling
* route registered next to it. A trailing "/*" may also be served by
* router.use(), which has no route to compare against.
*/
function isPublicRequest(
req: Request,
publicPaths: PublicPath[],
inner: Router,
): boolean {
if (publicPaths.length === 0) return false;
const path = normalizePublicPath(req.path || "/");
const candidates = publicPaths.filter(({ pattern }) => pattern.test(path));
if (candidates.length === 0) return false;
const stack = (inner as unknown as { stack?: RouterLayer[] }).stack ?? [];
for (const layer of stack) {
if (!layer.match?.(req.path || "/")) continue;
if (!layer.route) {
if (candidates.some(({ declared }) => declared.endsWith("/*"))) {
return true;
}
continue;
}
if (!layer.route._handlesMethod?.(req.method)) continue;
const routePath = layer.route.path;
return (
typeof routePath === "string" &&
candidates.some(({ declared }) =>
declaredCoversRoute(declared, routePath),
)
);
}
return false;
}
export interface CreatePluginRouterArgs {
manifest: PluginManifest;
options?: PluginRouterOptions;
/** Records a runtime error against the plugin's error budget. */
reportError: (error: unknown) => void;
}
export function createPluginRouter({
manifest,
options,
reportError,
}: CreatePluginRouterArgs): Router {
const pluginId = manifest.id;
if (routers.has(pluginId)) {
throw new Error(
`Plugin ${pluginId} already has a router; call ctx.http.router() once`,
);
}
const declaredPublic = (options?.public ?? []).map((path) =>
normalizePublicPath(path),
);
const publicPaths = declaredPublic.map((declared) => ({
declared,
pattern: compilePublicPath(declared),
}));
publicRoutes.set(pluginId, declaredPublic);
if (declaredPublic.length > 0) {
// Audited once at registration: the set of unauthenticated routes a plugin
// has is worth seeing even if nobody ever calls them.
pluginLogger.warn(
`Plugin ${pluginId} serves ${declaredPublic.length} route(s) without authentication: ${declaredPublic.join(", ")}`,
{ operation: "plugin_http_public" },
);
void writePublicRouteAudit(manifest, declaredPublic);
}
const outer = express.Router();
const inner = express.Router();
outer.use((req: Request, res: Response, next: NextFunction) => {
if (isPluginEnabled(pluginId)) {
next();
return;
}
res.status(503).json({ error: "This feature is not available", pluginId });
});
// The grant lives in the database, so it cannot be checked in the
// synchronous router() call a plugin makes inside activate. Checked per
// request instead: a plugin whose network:serve was revoked keeps its mount
// point and refuses every request through it, which is the same outcome a
// revoke should have and takes effect without a restart.
outer.use((req: Request, res: Response, next: NextFunction) => {
void (async () => {
try {
const granted = await hasCapability(
pluginId,
"network:serve",
manifest.capabilities,
);
if (!granted) {
res.status(403).json({
error: "Plugin is not granted the network:serve capability",
pluginId,
});
return;
}
next();
} catch (error) {
next(error);
}
})();
});
const authenticate = AuthManager.getInstance().createAuthMiddleware();
outer.use((req: Request, res: Response, next: NextFunction) => {
if (isPublicRequest(req, publicPaths, inner)) {
const ip = req.ip || req.socket?.remoteAddress || "unknown";
if (
overPublicRateLimit(pluginId, ip, Date.now(), options?.publicRateLimit)
) {
res.status(429).json({ error: "Too many requests" });
return;
}
pluginLogger.info(`Unauthenticated request to ${pluginId}${req.path}`, {
operation: "plugin_http_public_request",
});
next();
return;
}
authenticate(req, res, next);
});
if (!options?.rawBody) {
const limit = options?.bodyLimit ?? DEFAULT_BODY_LIMIT;
// Both parsers ignore a body they do not claim, so multipart still reaches
// multer untouched. database.ts skips its own global parser for
// /plugin-api so this limit is the one that actually applies.
outer.use(express.json({ limit }));
outer.use(express.urlencoded({ limit, extended: true }));
}
// After auth, so the actor is the user core authenticated rather than
// whatever the request claimed.
outer.use((req: Request, _res: Response, next: NextFunction) => {
const { userId, sessionId } = req as Request & {
userId?: string;
sessionId?: string;
};
if (!userId) {
next();
return;
}
runAsActor(userId, "request", () => next(), sessionId);
});
outer.use(inner);
outer.use(
(
error: unknown,
req: Request,
res: Response,
_next: NextFunction,
): void => {
void _next;
const status = clientErrorStatus(error);
const authenticated = !!(req as Request & { userId?: string }).userId;
// A bad body or a 4xx is the caller's fault, and an anonymous caller
// must never be able to spend the plugin's error budget: five junk
// requests to a public route would otherwise switch the plugin off.
if (status === null && authenticated) reportError(error);
if (status !== null) {
if (!res.headersSent) {
res.status(status).json({ error: "Invalid request" });
} else {
res.end();
}
return;
}
pluginLogger.error(
`Plugin ${pluginId} route ${req.method} ${req.path} failed`,
error instanceof Error ? error : new Error(String(error)),
{ operation: "plugin_http_error" },
);
if (res.headersSent) {
// Mid-stream: the only honest thing left is to end it.
res.end();
return;
}
res.status(500).json({ error: "Plugin request failed" });
},
);
routers.set(pluginId, outer);
pluginLogger.info(`Mounted /plugin-api/${pluginId}`, {
operation: "plugin_http_mount",
});
return inner;
}
/** The status of an error that is the caller's fault, or null. */
function clientErrorStatus(error: unknown): number | null {
const status =
(error as { status?: unknown; statusCode?: unknown } | null)?.status ??
(error as { statusCode?: unknown } | null)?.statusCode;
return typeof status === "number" && status >= 400 && status < 500
? status
: null;
}
async function writePublicRouteAudit(
manifest: PluginManifest,
paths: string[],
): Promise<void> {
try {
const { logAudit } = await import("../utils/audit-logger.js");
await logAudit({
userId: null,
username: `plugin:${manifest.id}`,
action: "plugin_http_public_routes",
resourceType: "plugin",
resourceId: manifest.id,
resourceName: manifest.name,
details: `unauthenticated routes: ${paths.join(", ")}`,
success: true,
});
} catch {
// Auditing must never stop a plugin starting.
}
}
/**
* Builds ctx.rbac.require.
*
* A plugin may only gate on a permission it declares itself. Without that a
* route could require admin.users.manage and borrow someone else's authority,
* which is the escalation shape the manifest validator already blocks for
* role defaults.
*
* The 401/403 bodies match requirePermission(), so a plugin route denies the
* same way a core route does and a client needs one code path.
*/
export function createRbacMiddleware(
manifest: PluginManifest,
permission: string,
): PluginMiddleware {
const required = resolvePermission(manifest, permission);
const declared = declaredPermissions(manifest);
if (!declared.has(required)) {
throw new Error(
`Plugin ${manifest.id} cannot require permission "${permission}": it is not declared in contributes.permissions`,
);
}
return ((req: Request, res: Response, next: NextFunction) => {
void (async () => {
const userId = (req as Request & { userId?: string }).userId;
if (!userId) {
res.status(401).json({ error: "Not authenticated" });
return;
}
try {
const { PermissionManager } =
await import("../utils/permission-manager.js");
const allowed = await PermissionManager.getInstance().hasPermission(
userId,
required,
);
if (!allowed) {
res.status(403).json({ error: "Insufficient permissions", required });
return;
}
next();
} catch (error) {
next(error);
}
})();
}) as unknown as PluginMiddleware;
}