feat: move network topology into a first-party plugin

This commit is contained in:
LukeGus committed 2026-09-22 10:45:15 -05:00
1 parent e372b0eda7
commit 5fbd5fb7e2
16 files changed
+447 -24

No files matched your search

@@ -0,0 +1,60 @@
/**
* Network Topology - first-party, in-process plugin.
*
* Unlike the other first-party plugins (see src/backend/plugins/first-party.ts),
* this one does not own a transport or touch the shared SSH pool -- its two
* routes are plain per-user JSON CRUD against a single repository. It runs
* in-process anyway to keep its existing /network-topology URL and its
* existing dedicated table (network_topology, keyed by userId) rather than
* moving onto /plugin-api/network-topology/* and the generic key-value
* ctx.storage the worker tier would require, matching how fleets/proxmox/
* automations were migrated in place rather than reworked around the worker
* ctx boundary.
*
* Like fleets and proxmox, this plugin does not get its own port -- it
* registers its Express router with the always-mounted /network-topology
* dispatcher in src/backend/database/routes/network-topology-dispatch.ts.
*
* routes.ts is what used to be
* src/backend/database/routes/network-topology.ts, moved here and rewritten
* from `export default router` into
* startNetworkTopologyService()/stopNetworkTopologyService(), called from
* activate()/deactivate() below. The network_topology table and its
* repository stay in core (src/backend/database/db/schema.ts,
* src/backend/database/repositories/network-topology-repository.ts) -- this
* plugin system has no owned-table migration mechanism of its own, and the
* table carries an FK into core's users table.
*/
import path from "node:path";
import { fileURLToPath } from "node:url";
/**
* Loads a module by its path relative to this file's own directory.
*
* The plugin ships beside dist/backend, so in a built server the compiled
* .js for routes.js sits right next to this .mjs. Under vitest/dev nothing
* imports this plugin directly (the loader loads in-process plugins with a
* plain dynamic import, no tsx loader involved), so the only layout that
* needs to resolve here is the built one.
*/
async function loadRelative(relativePath) {
const here = path.dirname(fileURLToPath(import.meta.url));
const target = path.join(here, `${relativePath}.js`);
return import(new URL(`file://${target.replace(/\\/g, "/")}`).href);
}
let routesModule = null;
export async function activate(ctx) {
routesModule = await loadRelative("routes");
routesModule.startNetworkTopologyService();
ctx.log.info("Network Topology router registered at /network-topology");
}
export async function deactivate() {
if (routesModule) {
routesModule.stopNetworkTopologyService();
routesModule = null;
}
}
+188
View File
@@ -0,0 +1,188 @@
import express from "express";
import { AuthManager } from "../../../src/backend/utils/auth-manager.js";
import type { AuthenticatedRequest } from "../../../src/types/index.js";
import { databaseLogger } from "../../../src/backend/utils/logger.js";
import { createCurrentNetworkTopologyRepository } from "../../../src/backend/database/repositories/factory.js";
import {
registerNetworkTopologyRouter,
unregisterNetworkTopologyRouter,
} from "../../../src/backend/database/routes/network-topology-dispatch.js";
export const router = express.Router();
const authManager = AuthManager.getInstance();
const authenticateJWT = authManager.createAuthMiddleware();
/**
* @openapi
* /network-topology:
* get:
* summary: Get network topology for authenticated user
* description: Retrieves the saved network topology graph (nodes and edges) for the current user. Returns null if no topology exists.
* tags:
* - Network Topology
* security:
* - bearerAuth: []
* responses:
* 200:
* description: Network topology retrieved successfully
* content:
* application/json:
* schema:
* type: object
* nullable: true
* properties:
* nodes:
* type: array
* description: Array of graph nodes (hosts and groups)
* items:
* type: object
* properties:
* data:
* type: object
* description: Node data including id, label, type, etc.
* position:
* type: object
* description: Node position coordinates
* properties:
* x:
* type: number
* y:
* type: number
* edges:
* type: array
* description: Array of graph edges (connections)
* items:
* type: object
* properties:
* data:
* type: object
* description: Edge data including source and target node ids
* 401:
* description: User not authenticated
* 500:
* description: Server error
*/
router.get(
"/",
authenticateJWT,
async (req: express.Request, res: express.Response) => {
try {
const userId = (req as AuthenticatedRequest).userId;
if (!userId) {
return res.status(401).json({ error: "User not authenticated" });
}
const record =
await createCurrentNetworkTopologyRepository().findByUserId(userId);
if (record) {
const topologyStr = record.topology;
const topology = topologyStr ? JSON.parse(topologyStr) : null;
return res.json(topology);
} else {
return res.json(null);
}
} catch (error) {
databaseLogger.error("Failed to fetch network topology", error, {
operation: "network_topology_fetch",
userId: (req as AuthenticatedRequest).userId,
});
return res.status(500).json({
error: "Failed to fetch network topology",
details: (error as Error).message,
});
}
},
);
/**
* @openapi
* /network-topology:
* post:
* summary: Save network topology for authenticated user
* description: Saves or updates the network topology graph. Uses upsert logic - creates new record if none exists, updates existing record otherwise.
* tags:
* - Network Topology
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - topology
* properties:
* topology:
* type: object
* description: Network topology data containing nodes and edges
* properties:
* nodes:
* type: array
* description: Array of graph nodes (hosts and groups)
* edges:
* type: array
* description: Array of graph edges (connections)
* responses:
* 200:
* description: Topology saved successfully
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* 400:
* description: Invalid topology data
* 401:
* description: User not authenticated
* 500:
* description: Server error
*/
router.post(
"/",
authenticateJWT,
async (req: express.Request, res: express.Response) => {
try {
const userId = (req as AuthenticatedRequest).userId;
if (!userId) {
return res.status(401).json({ error: "User not authenticated" });
}
const { topology } = req.body;
if (!topology) {
return res.status(400).json({ error: "Topology data is required" });
}
const topologyStr =
typeof topology === "string" ? topology : JSON.stringify(topology);
await createCurrentNetworkTopologyRepository().upsertForUser(
userId,
topologyStr,
);
return res.json({ success: true });
} catch (error) {
databaseLogger.error("Failed to save network topology", error, {
operation: "network_topology_save",
userId: (req as AuthenticatedRequest).userId,
});
return res.status(500).json({
error: "Failed to save network topology",
details: (error as Error).message,
});
}
},
);
export function startNetworkTopologyService(): void {
registerNetworkTopologyRouter(router);
}
export function stopNetworkTopologyService(): void {
unregisterNetworkTopologyRouter();
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,37 @@
/**
* Frontend half of the network-topology plugin.
*
* NetworkGraphCard renders in two modes: as a full tab (network_graph) and
* embedded as a dashboard card. Both usages are wired today through the
* existing tabUtils.tsx / DashboardTab.tsx switch statements the same way
* fleet-inventory's tab is, not through register() below -- per
* src/ui/shell/pluginLoader.ts's own comment, "there is no plugin loader
* yet" for the frontend half.
*
* register()/unregister() still follow the same shape every other plugin's
* frontend entry does, so this is ready the moment a real frontend plugin
* loader exists.
*/
export const id = "network-topology";
export const tabId = "network_graph";
export async function register({ registerRailItem, registerTabComponent, icons }) {
registerTabComponent?.(tabId, () =>
import("./NetworkGraphCard.tsx").then((m) => ({
default: m.NetworkGraphCard,
})),
);
registerRailItem?.({
id: tabId,
icon: icons.Network,
labelKey: "nav.networkGraph",
kind: "tab",
});
}
export async function unregister({ unregisterRailItem, unregisterTabComponent }) {
unregisterRailItem?.(tabId);
unregisterTabComponent?.(tabId);
}
+33
View File
@@ -0,0 +1,33 @@
{
"id": "network-topology",
"name": "Network Topology",
"version": "1.0.0",
"description": "Visualize hosts and their connections as an interactive graph, saved per user.",
"author": { "name": "Termix" },
"license": "MIT",
"repository": "https://github.com/Termix-SSH/Termix",
"category": "Infrastructure",
"icon": "Network",
"engine": { "termix": ">=2.9.0", "api": "1" },
"capabilities": {
"backend": true,
"frontend": true,
"electron": true,
"platforms": ["linux", "win32", "darwin"]
},
"permissions": ["process:transport-owner"],
"contributes": {
"tabs": [
{
"id": "network_graph",
"titleKey": "nav.networkGraph",
"icon": "Network",
"openFrom": ["rail", "palette"]
}
],
"dashboardCards": [
{ "id": "network_graph", "titleKey": "dashboard.networkGraph" }
]
},
"sidecars": []
}