feat: move tailscale device discovery and settings into a plugin

Adds plugins/tailscale/ with a devices sidebar tab, admin settings
section, and re-auth dialog. Host Metrics tailscale manager card and
SSH re-auth banner parsing stay in core.
This commit is contained in:
LukeGus committed 2026-09-22 10:45:15 -05:00
1 parent 5fbd5fb7e2
commit 8742c5d381
27 files changed
+850 -266

No files matched your search

+69
View File
@@ -0,0 +1,69 @@
/**
* Tailscale - first-party, in-process plugin.
*
* This plugin runs on the main thread rather than in a worker for the same
* reason fleets and proxmox do (see src/backend/plugins/first-party.ts): it
* does not own a live transport of its own (no WebSocket server, no
* dedicated port), so it registers its Express router with the
* always-mounted /tailscale dispatcher in
* src/backend/database/routes/tailscale-dispatch.ts instead of getting its
* own port.
*
* routes.ts is what used to be src/backend/database/routes/tailscale-routes.ts,
* moved here and rewritten from a direct app.use() call into
* startTailscaleService()/stopTailscaleService(), called from
* activate()/deactivate() below.
*
* tailscale-check.ts (SSH re-auth banner parsing) stays in core, at
* src/backend/hosts/tailscale-check.ts, and is NOT part of this plugin.
* It is imported directly by src/backend/hosts/terminal/index.ts (owned by
* ssh-terminal), which type-checks under tsconfig.node.json's rootDir of
* src/ -- a plugin .ts file physically outside that root cannot be a static
* import target for core code (see scripts/copy-bundled-plugins.cjs's own
* comment: plugin backends import core, never the reverse, anywhere in this
* codebase). Moving the file into plugins/tailscale/backend/ would require
* either widening tsconfig.node.json's rootDir for every other plugin's
* dist path-rewriting, or switching terminal/index.ts to a dynamic import
* inside its banner handler -- both bigger changes than this plugin
* warrants. The banner/ready wiring and retry state already live in
* ssh-terminal's connection handler regardless, so this stays exactly where
* that coupling already lives.
*
* The /users/tailscale-settings GET/PATCH routes stay in core
* (src/backend/database/routes/user-settings-routes.ts) -- they are general
* user-settings infrastructure, not Tailscale-specific plumbing, and this
* plugin's frontend calls them the same way core code does.
*/
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.startTailscaleService();
ctx.log.info("Tailscale router registered at /tailscale");
}
export async function deactivate() {
if (routesModule) {
routesModule.stopTailscaleService();
routesModule = null;
}
}
+142
View File
@@ -0,0 +1,142 @@
// Was src/backend/database/routes/tailscale-routes.ts, moved here and
// rewritten to register itself via the shared /tailscale dispatcher
// (src/backend/database/routes/tailscale-dispatch.ts) instead of taking a
// direct reference to the app instance, the same way fleets does.
import { Router } from "express";
import { AuthManager } from "../../../src/backend/utils/auth-manager.js";
import { apiLogger } from "../../../src/backend/utils/logger.js";
import { fetchWithProxy } from "../../../src/backend/utils/proxy-agent.js";
import { createCurrentSettingsRepository } from "../../../src/backend/database/repositories/factory.js";
import {
registerTailscaleRouter,
unregisterTailscaleRouter,
} from "../../../src/backend/database/routes/tailscale-dispatch.js";
interface TailscaleDevice {
id: string;
name: string;
hostname: string;
addresses: string[];
os: string;
lastSeen: string;
}
interface TailscaleAPIDevice {
id: string;
name: string;
hostname: string;
addresses: string[];
os: string;
lastSeen: string;
nodeId?: string;
}
const DEFAULT_TAILSCALE_API_BASE = "https://api.tailscale.com/api/v2";
export const router = Router();
const authManager = AuthManager.getInstance();
const authenticateJWT = authManager.createAuthMiddleware();
function normalizeApiBase(raw: string | null): string {
const trimmed = (raw ?? "").trim().replace(/\/+$/, "");
return trimmed || DEFAULT_TAILSCALE_API_BASE;
}
/**
* @openapi
* /tailscale/devices:
* get:
* summary: List Tailscale devices
* description: Returns the list of devices in the configured tailnet using the stored API key.
* tags:
* - Tailscale
* responses:
* 200:
* description: List of tailnet devices.
* content:
* application/json:
* schema:
* type: object
* properties:
* devices:
* type: array
* items:
* type: object
* 500:
* description: Failed to fetch Tailscale devices.
*/
router.get("/devices", authenticateJWT, async (_req, res) => {
try {
const settingsRepo = createCurrentSettingsRepository();
const apiKey = (await settingsRepo.get("tailscale_api_key")) ?? "";
if (!apiKey) {
return res.json({ devices: [], hasApiKey: false });
}
const apiBase = normalizeApiBase(
await settingsRepo.get("tailscale_api_base_url"),
);
const url = `${apiBase}/tailnet/-/devices?fields=all`;
const response = await fetchWithProxy(url, {
headers: {
Authorization: `Bearer ${apiKey}`,
"User-Agent": "Termix/1.0",
},
});
if (!response.ok) {
apiLogger.warn("Tailscale API returned non-OK status", {
operation: "tailscale_devices",
status: response.status,
});
if (response.status === 401 || response.status === 403) {
return res.status(401).json({
error: "Invalid Tailscale API key",
devices: [],
hasApiKey: true,
});
}
return res.status(502).json({
error: "Tailscale API error",
devices: [],
hasApiKey: true,
});
}
const data = (await response.json()) as { devices: TailscaleAPIDevice[] };
const devices: TailscaleDevice[] = (data.devices ?? []).map((d) => ({
id: d.id,
name: d.name,
hostname: d.hostname,
addresses: d.addresses ?? [],
os: d.os,
lastSeen: d.lastSeen,
}));
res.json({ devices, hasApiKey: true });
} catch (err) {
apiLogger.error("Failed to fetch Tailscale devices", err, {
operation: "tailscale_devices",
});
res.status(500).json({
error: "Failed to fetch Tailscale devices",
devices: [],
hasApiKey: true,
});
}
});
/** Called from activate(). Mounts this router at /tailscale via the shared
* dispatcher. */
export function startTailscaleService(): void {
registerTailscaleRouter(router);
}
/** Called from deactivate(). /tailscale/* falls back to 404 until
* reactivated. */
export function stopTailscaleService(): void {
unregisterTailscaleRouter();
}
@@ -0,0 +1,93 @@
import type { Dispatch, SetStateAction } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/button";
import { Input } from "@/components/input";
import { Network } from "lucide-react";
import { AccordionSection } from "@/sidebar/AdminSettingsShared";
// Was inline in AdminGeneralSettingsSection (src/ui/sidebar/AdminSettingsSections.tsx),
// moved here into its own accordion section as part of the Tailscale plugin.
// The backing routes (GET/PATCH /users/tailscale-settings) stay in core -
// they are general user-settings infrastructure this plugin calls, not
// something it owns.
type AdminTailscaleSectionProps = {
open: boolean;
onToggle: () => void;
tailscaleApiKey: string;
setTailscaleApiKey: Dispatch<SetStateAction<string>>;
tailscaleApiBaseUrl: string;
setTailscaleApiBaseUrl: Dispatch<SetStateAction<string>>;
handleSaveTailscaleApiKey: () => void;
};
export function AdminTailscaleSection({
open,
onToggle,
tailscaleApiKey,
setTailscaleApiKey,
tailscaleApiBaseUrl,
setTailscaleApiBaseUrl,
handleSaveTailscaleApiKey,
}: AdminTailscaleSectionProps) {
const { t } = useTranslation();
return (
<AccordionSection
label={t("admin.sectionTailscale")}
icon={<Network className="size-3.5" />}
open={open}
onToggle={onToggle}
>
<div className="flex flex-col gap-2 pt-2">
<div className="flex flex-col gap-0.5">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
{t("admin.tailscaleApiKey")}
</span>
<span className="text-[10px] text-muted-foreground">
{t("admin.tailscaleApiKeyDescription")}{" "}
<a
href="https://docs.termix.site/features/networking/tailscale"
target="_blank"
rel="noreferrer"
className="text-accent-brand hover:underline"
>
{t("admin.tailscaleApiKeyDocsLink")}
</a>
</span>
</div>
<div className="flex items-center gap-2">
<Input
type="password"
value={tailscaleApiKey}
onChange={(e) => setTailscaleApiKey(e.target.value)}
placeholder="tskey-api-... / hskey-api-..."
className="text-sm"
/>
<Button
variant="outline"
size="sm"
className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand h-7 shrink-0"
onClick={handleSaveTailscaleApiKey}
>
{t("common.save")}
</Button>
</div>
<div className="flex flex-col gap-1.5 mt-1">
<label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
{t("admin.tailscaleApiBaseUrl")}
</label>
<span className="text-[10px] text-muted-foreground">
{t("admin.tailscaleApiBaseUrlDescription")}
</span>
<Input
value={tailscaleApiBaseUrl}
onChange={(e) => setTailscaleApiBaseUrl(e.target.value)}
placeholder="https://api.tailscale.com/api/v2"
className="text-sm"
/>
</div>
</div>
</AccordionSection>
);
}
@@ -0,0 +1,89 @@
import React from "react";
import { Button } from "@/components/button.tsx";
import { Shield, ExternalLink, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
interface TailscaleCheckDialogProps {
isOpen: boolean;
authUrl: string;
message?: string;
stage: "prompt" | "waiting";
onCancel: () => void;
onOpenUrl: () => void;
backgroundColor?: string;
}
export function TailscaleCheckDialog({
isOpen,
authUrl,
message,
stage,
onCancel,
onOpenUrl,
backgroundColor,
}: TailscaleCheckDialogProps) {
const { t } = useTranslation();
if (!isOpen) return null;
return (
<div className="absolute inset-0 flex items-center justify-center z-500 animate-in fade-in duration-200">
<div
className="absolute inset-0 bg-canvas rounded-md"
style={{ backgroundColor: backgroundColor || undefined }}
/>
<div className="bg-card border border-border w-full max-w-md mx-4 relative z-10 animate-in fade-in zoom-in-95 duration-200">
<div className="p-4 border-b border-border">
<div className="flex items-center gap-2">
<Shield className="size-4 text-accent-brand" />
<h3 className="text-xs font-bold uppercase tracking-widest">
{t("terminal.tailscaleCheckRequired")}
</h3>
</div>
<p className="text-[10px] font-bold uppercase tracking-tight text-muted-foreground mt-1">
{t("terminal.tailscaleCheckDescription")}
</p>
</div>
<div className="p-4 flex flex-col gap-4">
{message && (
<p className="text-xs text-muted-foreground whitespace-pre-wrap break-words">
{message}
</p>
)}
{stage === "prompt" && authUrl && (
<Button
type="button"
variant="outline"
onClick={onOpenUrl}
className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 rounded-none text-[10px] font-bold uppercase tracking-widest w-full flex items-center gap-2"
>
<ExternalLink className="size-3.5" />
{t("terminal.tailscaleCheckOpenBrowser")}
</Button>
)}
{stage === "waiting" && (
<div className="flex items-center gap-3 py-2">
<Loader2 className="size-4 animate-spin text-accent-brand shrink-0" />
<p className="text-xs text-muted-foreground">
{t("terminal.tailscaleCheckWaiting")}
</p>
</div>
)}
<div className="flex justify-end">
<Button
type="button"
variant="ghost"
onClick={onCancel}
className="rounded-none text-[10px] font-bold uppercase tracking-widest"
>
{t("common.cancel")}
</Button>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,160 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Loader2, RefreshCw, Terminal } from "lucide-react";
import { Button } from "@/components/button";
import { Input } from "@/components/input";
import type { Host } from "@/types/ui-types";
import { getTailscaleDevices } from "./tailscale-api";
import { createQuickConnectHost } from "../../../src/ui/sidebar/quick-connect-host";
interface TailscaleDevice {
id: string;
name: string;
hostname: string;
addresses: string[];
os: string;
lastSeen: string;
}
interface TailscaleDevicesPanelProps {
onConnect: (host: Host, type: "terminal") => void;
}
function deviceIp(device: TailscaleDevice): string {
return (
device.addresses.find((a) => a.startsWith("100.")) ??
device.addresses[0] ??
""
);
}
export function TailscaleDevicesPanel({
onConnect,
}: TailscaleDevicesPanelProps) {
const { t } = useTranslation();
const [devices, setDevices] = useState<TailscaleDevice[]>([]);
const [hasApiKey, setHasApiKey] = useState(true);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const [usernames, setUsernames] = useState<Record<string, string>>({});
function load() {
setLoading(true);
setError(false);
getTailscaleDevices()
.then((res) => {
setDevices(res.devices);
setHasApiKey(res.hasApiKey);
})
.catch(() => setError(true))
.finally(() => setLoading(false));
}
useEffect(load, []);
function connect(device: TailscaleDevice) {
const ip = deviceIp(device);
if (!ip) return;
const username = usernames[device.id]?.trim() || "root";
const host = createQuickConnectHost({
ip,
port: 22,
username,
authType: "tailscale",
});
onConnect(host, "terminal");
}
return (
<div className="flex flex-col flex-1 min-h-0 overflow-y-auto">
<div className="flex items-center justify-between px-3 py-2 border-b border-border">
<span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
{t("nav.tailscale")}
</span>
<Button
variant="ghost"
size="icon"
className="size-6 text-muted-foreground hover:text-foreground"
onClick={load}
disabled={loading}
>
<RefreshCw className={`size-3 ${loading ? "animate-spin" : ""}`} />
</Button>
</div>
<div className="flex flex-col gap-2 p-3">
{loading && (
<div className="flex items-center gap-2 text-[10px] text-muted-foreground">
<Loader2 className="size-3.5 animate-spin" />
{t("hosts.tailscaleLoadingDevices")}
</div>
)}
{!loading && !hasApiKey && (
<p className="text-[10px] text-muted-foreground">
{t("hosts.tailscaleNoApiKey")}
</p>
)}
{!loading && hasApiKey && error && (
<p className="text-[10px] text-muted-foreground">
{t("hosts.tailscaleDeviceLoadFailed")}
</p>
)}
{!loading && hasApiKey && !error && devices.length === 0 && (
<p className="text-[10px] text-muted-foreground">
{t("hosts.tailscaleNoDevices")}
</p>
)}
{!loading &&
hasApiKey &&
!error &&
devices.map((device) => {
const ip = deviceIp(device);
return (
<div
key={device.id}
className="flex flex-col gap-1.5 border border-border p-2"
>
<div className="flex flex-col gap-0.5">
<span className="text-xs font-semibold">
{device.hostname || device.name}
</span>
<span className="text-[10px] text-muted-foreground">
{ip} {device.os ? `· ${device.os}` : ""}
</span>
</div>
<Input
placeholder={t("newUi.sidebar.quickConnect.usernameLabel")}
value={usernames[device.id] ?? "root"}
onChange={(e) =>
setUsernames((prev) => ({
...prev,
[device.id]: e.target.value,
}))
}
onKeyDown={(e) => {
if (e.key === "Enter") connect(device);
}}
className="h-7 text-xs"
/>
<Button
onClick={() => connect(device)}
disabled={!ip}
className="flex items-center justify-center gap-1.5 h-7 w-full border border-accent-brand/40 bg-accent-brand/10 text-accent-brand text-xs font-semibold hover:bg-accent-brand/20 transition-colors"
variant="outline"
>
<Terminal className="size-3.5" />
{t("newUi.sidebar.quickConnect.connectToTerminal")}
</Button>
</div>
);
})}
</div>
</div>
);
}
export default TailscaleDevicesPanel;
+40
View File
@@ -0,0 +1,40 @@
/**
* Frontend half of the tailscale plugin.
*
* TailscaleDevicesPanel is a left-sidebar railView panel (opened from the
* rail, not a Tab), the same shape as FleetsPanel/QuickConnectPanel. None of
* those go through registerRailItem/registerTabComponent either -- per
* src/ui/shell/pluginLoader.ts's own comment, a rail-view panel like this is
* rendered directly by AppShell.tsx rather than registered at runtime.
* TailscaleDevicesPanel is reached today through a direct relative import in
* AppShell.tsx (../../plugins/tailscale/frontend/TailscaleDevicesPanel), not
* through register() below.
*
* 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 -- see plugins/ssh-terminal/frontend/index.mjs and
* src/ui/tests/sidebar/plugin-extension-seam.test.tsx, which says outright
* "there is no plugin loader yet".
*
* TailscaleCheckDialog is not registered here at all: it is rendered
* directly by src/ui/features/terminal/Terminal.tsx (owned by ssh-terminal),
* driven by raw WS message types on the terminal socket. There is no
* dialog-registration extension point for that today, so this plugin ships
* the component as a plain module ssh-terminal imports by path.
*/
export const id = "tailscale";
export const railViewId = "tailscale";
export async function register({ registerRailItem, icons }) {
registerRailItem?.({
id: railViewId,
icon: icons.Radar,
labelKey: "nav.tailscale",
separatorAfter: true,
});
}
export async function unregister({ unregisterRailItem }) {
unregisterRailItem?.(railViewId);
}
@@ -0,0 +1,71 @@
// Was part of src/ui/api/settings-api.ts, moved here with the rest of the
// Tailscale plugin. The backing routes stay in place: /users/tailscale-settings
// is general user-settings infrastructure in core, and /tailscale/devices is
// this plugin's own route (plugins/tailscale/backend/routes.ts).
import axios from "axios";
import { authApi, handleApiError } from "@/main-axios";
export async function getTailscaleSettings(): Promise<{
apiKey: string;
hasApiKey: boolean;
apiBaseUrl: string;
}> {
try {
const response = await authApi.get("/users/tailscale-settings");
return response.data;
} catch (error) {
handleApiError(error, "fetch Tailscale settings");
}
}
export async function updateTailscaleSettings(
apiKey: string,
apiBaseUrl?: string,
): Promise<{ hasApiKey: boolean }> {
try {
const response = await authApi.patch("/users/tailscale-settings", {
apiKey,
apiBaseUrl,
});
return response.data;
} catch (error) {
handleApiError(error, "update Tailscale settings");
}
}
export async function getTailscaleDevices(): Promise<{
devices: Array<{
id: string;
name: string;
hostname: string;
addresses: string[];
os: string;
lastSeen: string;
}>;
hasApiKey: boolean;
error?: string;
}> {
try {
const response = await authApi.get("/tailscale/devices");
return response.data;
} catch (error) {
if (axios.isAxiosError(error)) {
const data = error.response?.data;
if (
data &&
typeof data === "object" &&
"hasApiKey" in data &&
typeof data.hasApiKey === "boolean"
) {
return data as {
devices: [];
hasApiKey: boolean;
error?: string;
};
}
}
handleApiError(error, "fetch Tailscale devices");
throw error;
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"id": "tailscale",
"name": "Tailscale",
"version": "1.0.0",
"description": "Browse and connect to tailnet devices, manage the Tailscale API key, and show the Tailscale SSH re-authentication dialog.",
"author": { "name": "Termix" },
"license": "MIT",
"repository": "https://github.com/Termix-SSH/Termix",
"category": "Networking",
"icon": "Network",
"engine": { "termix": ">=2.9.0", "api": "1" },
"capabilities": {
"backend": true,
"frontend": true,
"electron": true,
"platforms": ["linux", "win32", "darwin"]
},
"permissions": ["process:transport-owner"],
"sidecars": []
}