feat: finish the tailscale plugin, including SSH auth (B3)

This commit is contained in:
LukeGus committed 2026-09-23 09:41:20 -05:00
1 parent c77301577f
commit d2ff5fc78f
35 files changed
+1251 -526

No files matched your search

@@ -0,0 +1,269 @@
import type { Router } from "express";
import type { Request, Response } from "express";
import type { PluginContext } from "@termix/plugin-sdk/backend";
import type { AuthenticatedRequest } from "../../../../src/types/index.js";
import { DataCrypto } from "../../../../src/backend/utils/data-crypto.js";
import { PermissionManager } from "../../../../src/backend/utils/permission-manager.js";
import { resolveHostById } from "../../../../src/backend/hosts/host-resolver.js";
import { execCommand } from "../../../../src/backend/hosts/metrics-shared/common-utils.js";
import { execElevated } from "../../../../src/backend/hosts/metrics-shared/exec-elevated.js";
import { isValidTailscaleAction } from "../../../../src/backend/hosts/metrics-shared/validation.js";
import { withSshConnection } from "./ssh.js";
export interface TailscalePeer {
hostname: string;
tailscaleIPs: string[];
online: boolean;
isExitNode: boolean;
}
export interface TailscaleData {
installed: boolean;
running: boolean;
tailscaleIPs: string[];
hostname: string | null;
peers: TailscalePeer[];
exitNodeInUse: boolean;
}
const PROBE_CMD = [
"command -v tailscale >/dev/null 2>&1 && echo ts_installed=1 || echo ts_installed=0",
"tailscale status --json 2>/dev/null",
].join("; ");
export function parseTailscaleData(output: string): TailscaleData {
const notInstalled: TailscaleData = {
installed: false,
running: false,
tailscaleIPs: [],
hostname: null,
peers: [],
exitNodeInUse: false,
};
if (output.includes("ts_installed=0")) return notInstalled;
const lines = output.split("\n");
const jsonLines = lines.filter(
(l) => !l.startsWith("ts_installed=") && l.trim() !== "",
);
const jsonStr = jsonLines.join("\n");
try {
const parsed = JSON.parse(jsonStr) as {
BackendState?: string;
Self?: { HostName?: string; TailscaleIPs?: string[] };
Peer?: Record<
string,
{
HostName?: string;
TailscaleIPs?: string[];
Online?: boolean;
ExitNode?: boolean;
}
>;
CurrentExitNode?: string;
};
const peers: TailscalePeer[] = Object.values(parsed.Peer ?? {}).map(
(p) => ({
hostname: p.HostName ?? "",
tailscaleIPs: p.TailscaleIPs ?? [],
online: p.Online ?? false,
isExitNode: p.ExitNode ?? false,
}),
);
return {
installed: true,
running: parsed.BackendState === "Running",
tailscaleIPs: parsed.Self?.TailscaleIPs ?? [],
hostname: parsed.Self?.HostName ?? null,
peers,
exitNodeInUse:
typeof parsed.CurrentExitNode === "string" &&
parsed.CurrentExitNode !== "",
};
} catch {
return {
installed: true,
running: false,
tailscaleIPs: [],
hostname: null,
peers: [],
exitNodeInUse: false,
};
}
}
class AccessDeniedError extends Error {
constructor(message = "No access to this host") {
super(message);
this.name = "AccessDeniedError";
}
}
class ManagerInputError extends Error {
constructor(message: string) {
super(message);
this.name = "ManagerInputError";
}
}
interface ManagerHost {
id: number;
userId: string;
sudoPassword?: string;
}
async function resolveManagerHost(
hostId: number,
userId: string,
): Promise<ManagerHost> {
const access = await PermissionManager.getInstance().canAccessHost(
userId,
hostId,
"connect",
);
if (!access.hasAccess) throw new AccessDeniedError();
if (DataCrypto.getUserDataKey(userId) === null) {
throw new AccessDeniedError();
}
const host = await resolveHostById(hostId, userId);
if (!host) throw new AccessDeniedError("Host not found");
let sudoPassword = (host as { sudoPassword?: string }).sudoPassword;
const ownerId = (host as { userId?: string }).userId;
if (ownerId && ownerId !== userId) {
const ownerHost = await resolveHostById(hostId, ownerId);
sudoPassword = (ownerHost as { sudoPassword?: string } | null)
?.sudoPassword;
}
return { id: hostId, userId, sudoPassword };
}
function managerErrorResponse(
res: Response,
operation: string,
error: unknown,
) {
if (error instanceof ManagerInputError) {
return res.status(400).json({ error: error.message });
}
if (error instanceof AccessDeniedError) {
return res.status(403).json({ error: error.message });
}
const message = error instanceof Error ? error.message : String(error);
return res.status(500).json({ error: message || `${operation} failed` });
}
export function registerTailscaleHostMetricsManager(
router: Router,
ctx: PluginContext,
): void {
/**
* @openapi
* /plugin-api/tailscale/host-metrics-manager/{id}:
* get:
* summary: Get Tailscale status and IPs for a host
* tags:
* - Tailscale
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Tailscale installation status, running state, IPs, and peer count.
*/
router.get(
"/host-metrics-manager/:id",
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
const hostId = parseInt(String(req.params.id), 10);
try {
const host = await resolveManagerHost(hostId, userId);
const data = await withSshConnection(
host.id,
{ pool: "tailscale", purpose: "metrics" },
async (client) => {
const { stdout } = await execCommand(client, PROBE_CMD, 15000);
return parseTailscaleData(stdout);
},
);
res.json(data);
} catch (error) {
ctx.log.error(
"Failed to read Tailscale status",
error instanceof Error ? error : undefined,
);
managerErrorResponse(res, "tailscale_read", error);
}
},
);
/**
* @openapi
* /plugin-api/tailscale/host-metrics-manager/{id}/action:
* post:
* summary: Connect or disconnect Tailscale on a host
* tags:
* - Tailscale
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* action:
* type: string
* enum: [up, down]
* responses:
* 200:
* description: Action result.
*/
router.post(
"/host-metrics-manager/:id/action",
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
const hostId = parseInt(String(req.params.id), 10);
try {
const host = await resolveManagerHost(hostId, userId);
const { action } = req.body as { action: unknown };
if (!isValidTailscaleAction(action)) {
throw new ManagerInputError("Invalid action, must be 'up' or 'down'");
}
const result = await withSshConnection(
host.id,
{ pool: "tailscale", purpose: "metrics" },
(client) =>
execElevated(client, `tailscale ${action}`, host.sudoPassword, {
forceSudo: false,
timeoutMs: 30000,
}),
);
res.json({
success: result.code === 0,
output: (result.stdout + result.stderr).trim(),
});
} catch (error) {
ctx.log.error(
"Failed to run Tailscale action",
error instanceof Error ? error : undefined,
);
managerErrorResponse(res, "tailscale_action", error);
}
},
);
}
+10 -1
View File
@@ -1,11 +1,20 @@
import type { Router } from "express";
import type { PluginContext } from "@termix/plugin-sdk/backend";
import { startTailscaleService, stopTailscaleService } from "./routes.js";
import { registerTailscaleSshAuth } from "./ssh-auth-provider.js";
import { registerTailscaleHostMetricsManager } from "./host-metrics-manager.js";
import { setPluginSsh } from "./ssh.js";
export async function activate(ctx: PluginContext) {
startTailscaleService(ctx.http.router(), ctx);
const router = ctx.http.router<Router>();
startTailscaleService(router, ctx);
registerTailscaleHostMetricsManager(router, ctx);
setPluginSsh(ctx.ssh);
registerTailscaleSshAuth(ctx);
ctx.log.info("Tailscale routes mounted at /plugin-api/tailscale");
}
export async function deactivate() {
setPluginSsh(null);
stopTailscaleService();
}
+105 -130
View File
@@ -1,11 +1,4 @@
// 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 { PermissionManager } from "../../../../src/backend/utils/permission-manager.js";
import { apiLogger } from "../../../../src/backend/utils/logger.js";
import { fetchWithProxy } from "../../../../src/backend/utils/proxy-agent.js";
import type { PluginContext } from "@termix/plugin-sdk/backend";
@@ -31,145 +24,127 @@ interface TailscaleAPIDevice {
const DEFAULT_TAILSCALE_API_BASE = "https://api.tailscale.com/api/v2";
export const router = Router();
/**
* Set by activate(). The API key and base URL are this plugin's own settings
* now, read through ctx rather than out of the core settings table.
*/
let context: PluginContext | null = null;
const authManager = AuthManager.getInstance();
const authenticateJWT = authManager.createAuthMiddleware();
/**
* Listing the tailnet uses the admin-stored API key, so it needs more than a
* session. Writing the key is already admin-only and reading it back is
* masked, but using it to enumerate every device was open to any logged-in
* user, which handed out an internal network inventory.
*/
const requireDeviceAccess = PermissionManager.getInstance().requirePermission(
"tailscale.devices.view",
);
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 devices in the configured tailnet using the stored admin
* API key. Requires the tailscale.devices.view permission, because the
* response is a full inventory of the tailnet.
* tags:
* - Tailscale
* responses:
* 200:
* description: List of tailnet devices.
* 403:
* description: The caller lacks tailscale.devices.view.
* content:
* application/json:
* schema:
* type: object
* properties:
* devices:
* type: array
* items:
* type: object
* 500:
* description: Failed to fetch Tailscale devices.
* Set by activate(). Dropped on deactivate so a request arriving mid-teardown
* cannot read settings through a context the runtime has already torn down.
*/
router.get(
"/devices",
authenticateJWT,
requireDeviceAccess,
async (_req, res) => {
try {
if (!context) {
return res
.status(503)
.json({ error: "Plugin is not running", devices: [] });
}
const apiKey = (await context.settings.get<string>("apiKey")) ?? "";
if (!apiKey) {
return res.json({ devices: [], hasApiKey: false });
}
const apiBase = normalizeApiBase(
(await context.settings.get<string>("apiBaseUrl")) ?? null,
);
let context: PluginContext | null = null;
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. */
/** Called from activate(). Mounts the plugin's routes on ctx.http.router(). */
export function startTailscaleService(
mountOn: Router,
ctx: PluginContext,
): void {
context = ctx;
mountOn.use(router);
/**
* @openapi
* /plugin-api/tailscale/devices:
* get:
* summary: List Tailscale devices
* description: >
* Returns the devices in the configured tailnet using the stored admin
* API key. Requires the tailscale.devices.view permission, because the
* response is a full inventory of the tailnet.
* tags:
* - Tailscale
* responses:
* 200:
* description: List of tailnet devices.
* 403:
* description: The caller lacks tailscale.devices.view.
* content:
* application/json:
* schema:
* type: object
* properties:
* devices:
* type: array
* items:
* type: object
* 500:
* description: Failed to fetch Tailscale devices.
*/
mountOn.get(
"/devices",
ctx.rbac.require("devices.view") as never,
async (_req, res) => {
try {
if (!context) {
return res
.status(503)
.json({ error: "Plugin is not running", devices: [] });
}
const apiKey = (await context.settings.get<string>("apiKey")) ?? "";
if (!apiKey) {
return res.json({ devices: [], hasApiKey: false });
}
const apiBase = normalizeApiBase(
(await context.settings.get<string>("apiBaseUrl")) ?? null,
);
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 deactivate(). /tailscale/* falls back to 404 until
/** Called from deactivate(). /plugin-api/tailscale/* falls back to 404 until
* reactivated. */
export function stopTailscaleService(): void {
// Dropped so a request arriving mid-teardown cannot read settings through a
// context the runtime has already torn down.
context = null;
}
@@ -0,0 +1,74 @@
import type {
PluginContext,
PluginSshAuthProvider,
} from "@termix/plugin-sdk/backend";
import {
isTailscaleCheckCompleteBanner,
parseTailscaleCheckBanner,
TAILSCALE_CHECK_TIMEOUT_MS,
} from "./tailscale-check.js";
const AUTH_FAILED_PATTERN = /All configured authentication methods failed/i;
export const tailscaleSshAuthProvider: PluginSshAuthProvider = {
type: "tailscale",
labelKey: "hosts.filterAuthTailscale",
connectOptions: (_host, purpose) =>
purpose === "terminal"
? {
tryKeyboard: false,
readyTimeout: TAILSCALE_CHECK_TIMEOUT_MS,
// The socket sits idle while a check-mode login is pending.
timeout: TAILSCALE_CHECK_TIMEOUT_MS,
}
: { tryKeyboard: false },
prepare: async (_config, _host, env) => {
env.log("info", "Using Tailscale SSH");
return { status: "ready" };
},
onBanner: (banner) => {
const check = parseTailscaleCheckBanner(banner);
if (check) {
return {
action: "hold",
timeoutMs: TAILSCALE_CHECK_TIMEOUT_MS,
message: `Tailscale SSH requires an additional check. Waiting for browser authentication at ${check.url}`,
details: { url: check.url, message: check.message },
};
}
if (isTailscaleCheckCompleteBanner(banner)) {
return { action: "release" };
}
return undefined;
},
onAuthFailed: (host, _env, context) => {
const failed =
context.methodNotAvailable ||
AUTH_FAILED_PATTERN.test(context.error.message);
if (!failed) return;
// Tailscale documents the "+password" suffix for clients that mishandle a
// successful "none" reply. The password value is ignored.
if (context.retries === 0 && context.canRetry) {
return {
status: "retry",
message: "Retrying Tailscale SSH in forced password mode",
patch: {
username: `${host.username}+password`,
password: "termix",
tryKeyboard: false,
},
};
}
return {
status: "error",
code: "failed",
message: `Tailscale SSH authentication failed for user "${host.username}". Ensure Tailscale is running on the server, SSH is advertised (tailscale set --ssh), and your ACL policy grants the "${host.username}" user to your identity. If your Tailscale identity maps to a different Unix user, update the username on this host.`,
};
},
};
export function registerTailscaleSshAuth(ctx: PluginContext): void {
ctx.auth.registerSshAuthProvider(tailscaleSshAuthProvider);
}
+27
View File
@@ -0,0 +1,27 @@
import type { Client } from "ssh2";
import type {
PluginSsh,
PluginSshConnectOptions,
PluginSshHost,
} from "@termix/plugin-sdk/backend";
let current: PluginSsh | null = null;
/** Set in activate, cleared on deactivate. */
export function setPluginSsh(ssh: PluginSsh | null): void {
current = ssh;
}
export function pluginSsh(): PluginSsh {
if (!current) throw new Error("The plugin is not active");
return current;
}
/** withConnection with ssh2's Client type filled in. */
export function withSshConnection<T>(
host: number | PluginSshHost,
options: PluginSshConnectOptions & { pool: string },
fn: (client: Client) => Promise<T>,
): Promise<T> {
return pluginSsh().withConnection<T, Client>(host, options, fn);
}
@@ -0,0 +1,45 @@
// Tailscale SSH "check mode" sends its re-authentication prompt as an SSH auth
// banner during the "none" auth method, then long-polls its control plane while
// the connection stays open. The banner text itself comes from the control plane
// (it is not in the tailscaled source), so match on the login URL rather than the
// surrounding wording, which can change without notice.
const TAILSCALE_CHECK_URL = /https:\/\/login\.tailscale\.com\/a\/[A-Za-z0-9]+/;
const CHECK_COMPLETE = /authentication checked/i;
/** How long a Tailscale check-mode login may sit waiting for approval. */
export const TAILSCALE_CHECK_TIMEOUT_MS = 1_800_000;
export interface TailscaleCheckBanner {
url: string;
message: string;
}
function stripCommentMarkers(banner: string): string {
return banner
.split(/\r?\n/)
.map((line) => line.replace(/^\s*#\s?/, "").trim())
.filter((line) => line.length > 0)
.join("\n")
.trim();
}
export function parseTailscaleCheckBanner(
banner: string,
): TailscaleCheckBanner | null {
if (!banner) return null;
const match = banner.match(TAILSCALE_CHECK_URL);
if (!match) return null;
return {
url: match[0],
message: stripCommentMarkers(banner),
};
}
export function isTailscaleCheckCompleteBanner(banner: string): boolean {
if (!banner) return false;
return CHECK_COMPLETE.test(banner);
}
@@ -0,0 +1,164 @@
import { useState } from "react";
import { Power } from "lucide-react";
import { useTranslation } from "@termix/plugin-sdk/frontend";
import { useTailscaleData, useTailscaleAction } from "./useTailscaleManager";
import {
TailscaleManagerShell,
TailscaleManagerSearch,
} from "./TailscaleManagerShell";
interface TailscalePeer {
hostname: string;
tailscaleIPs: string[];
online: boolean;
isExitNode: boolean;
}
interface TailscaleData {
installed: boolean;
running: boolean;
tailscaleIPs: string[];
hostname: string | null;
peers: TailscalePeer[];
exitNodeInUse: boolean;
}
export function TailscaleManagerCard({ hostId }: { hostId: number | null }) {
const { t } = useTranslation();
const { data, loading, error, refresh } =
useTailscaleData<TailscaleData>(hostId);
const { busy, run } = useTailscaleAction(hostId);
const [query, setQuery] = useState("");
const handleToggle = async () => {
if (!data) return;
const action = data.running ? "down" : "up";
await run(action, {
loadingMsg: data.running
? t("manager.tsDisabling")
: t("manager.tsEnabling"),
successMsg: data.running
? t("manager.tsDisabled")
: t("manager.tsEnabled"),
onDone: refresh,
});
};
const filteredPeers = (data?.peers ?? []).filter(
(p) =>
!query ||
p.hostname.toLowerCase().includes(query.toLowerCase()) ||
p.tailscaleIPs.some((ip) => ip.includes(query)),
);
const isNotInstalled = data && !data.installed;
return (
<TailscaleManagerShell
title={t("manager.title")}
icon={<Power className="size-3.5" />}
loading={loading}
error={error}
onRefresh={refresh}
empty={!!isNotInstalled}
emptyMessage={t("manager.tsNotInstalled")}
>
{data && (
<div className="flex flex-col">
{/* Status + toggle row */}
<div className="flex items-center justify-between border-b border-border/50 py-1.5">
<div className="flex min-w-0 items-center gap-2">
<span
className={`size-1.5 shrink-0 rounded-full ${data.running ? "bg-accent-brand" : "bg-muted-foreground/40"}`}
/>
<div className="flex min-w-0 flex-col">
<span className="text-xs font-semibold">
{data.running
? t("manager.tsRunning")
: t("manager.tsStopped")}
</span>
{data.hostname && (
<span className="truncate font-mono text-[10px] text-muted-foreground">
{data.hostname}
</span>
)}
{data.tailscaleIPs.map((ip) => (
<span
key={ip}
className="truncate font-mono text-[10px] text-muted-foreground/60"
>
{ip}
</span>
))}
</div>
</div>
<div className="flex shrink-0 items-center">
<button
onClick={handleToggle}
disabled={busy || !data.installed}
title={
data.running ? t("manager.tsDisable") : t("manager.tsEnable")
}
className={`flex size-6 items-center justify-center transition-colors disabled:opacity-40 ${
data.running
? "text-accent-brand hover:bg-muted hover:text-destructive"
: "text-muted-foreground hover:bg-muted hover:text-accent-brand"
}`}
>
<Power className="size-3.5" />
</button>
</div>
</div>
{/* Exit node badge */}
{data.exitNodeInUse && (
<div className="border-b border-border/50 px-0 py-1.5">
<span className="text-[10px] text-blue-500">
{t("manager.tsExitNodeActive")}
</span>
</div>
)}
{/* Peers */}
{(data.peers?.length ?? 0) > 5 && (
<TailscaleManagerSearch
value={query}
onChange={setQuery}
count={filteredPeers.length}
/>
)}
{filteredPeers.map((peer) => (
<div
key={peer.hostname}
className="flex items-center justify-between gap-2 border-b border-border/50 py-1.5 last:border-0"
>
<div className="flex min-w-0 items-center gap-2">
<span
className={`size-1.5 shrink-0 rounded-full ${peer.online ? "bg-accent-brand" : "bg-muted-foreground/40"}`}
/>
<div className="flex min-w-0 flex-col">
<span className="truncate text-xs font-semibold">
{peer.hostname}
</span>
{peer.tailscaleIPs.map((ip) => (
<span
key={ip}
className="truncate font-mono text-[10px] text-muted-foreground"
>
{ip}
</span>
))}
</div>
</div>
{peer.isExitNode && (
<span className="shrink-0 text-[10px] text-blue-500">
{t("manager.tsExitNode")}
</span>
)}
</div>
))}
</div>
)}
</TailscaleManagerShell>
);
}
@@ -0,0 +1,110 @@
import type { ReactNode } from "react";
import { RefreshCw, AlertTriangle, Search } from "lucide-react";
import { useTranslation } from "@termix/plugin-sdk/frontend";
import { Button } from "@/components/button";
import { MetricCard } from "@/components/metric-card";
import type { ManagerError } from "./useTailscaleManager";
/**
* Local copy of host-metrics' ManagerCardShell, kept in step with it by eye.
* A shared component belongs in the SDK once a second plugin needs it.
*/
export function TailscaleManagerShell({
title,
icon,
loading,
error,
onRefresh,
empty,
emptyMessage,
children,
headerExtra,
}: {
title: string;
icon: ReactNode;
loading: boolean;
error: ManagerError | null;
onRefresh: () => void;
empty?: boolean;
emptyMessage?: string;
children: ReactNode;
headerExtra?: ReactNode;
}) {
const { t } = useTranslation();
return (
<MetricCard
title={title}
icon={icon}
scroll
action={
<div className="flex items-center gap-1">
{headerExtra}
<button
onClick={onRefresh}
className="flex size-6 items-center justify-center text-muted-foreground transition-colors hover:text-foreground"
title={t("manager.refresh")}
>
<RefreshCw className={`size-3 ${loading ? "animate-spin" : ""}`} />
</button>
</div>
}
>
{error ? (
<div className="flex flex-col items-center gap-2 py-6 text-center">
<AlertTriangle className="size-6 text-yellow-500" />
<span className="text-xs text-muted-foreground">{error.message}</span>
{error.code === "SUDO_REQUIRED" && (
<span className="text-[10px] text-muted-foreground">
{t("manager.sudoHint")}
</span>
)}
<Button
variant="outline"
size="sm"
onClick={onRefresh}
className="mt-1"
>
{t("manager.retry")}
</Button>
</div>
) : empty ? (
<div className="flex items-center justify-center py-8 text-xs text-muted-foreground/50">
{emptyMessage ?? t("manager.noData")}
</div>
) : (
children
)}
</MetricCard>
);
}
/** Local copy of host-metrics' ManagerSearch. */
export function TailscaleManagerSearch({
value,
onChange,
count,
}: {
value: string;
onChange: (v: string) => void;
count?: number;
}) {
const { t } = useTranslation();
return (
<div className="mb-2 flex items-center gap-1.5">
<div className="relative flex-1">
<Search className="pointer-events-none absolute left-2 top-1/2 size-3 -translate-y-1/2 text-muted-foreground/60" />
<input
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={t("manager.filter")}
className="h-7 w-full border border-border bg-background pl-7 pr-2 text-xs outline-none focus:ring-1 focus:ring-ring"
/>
</div>
{count != null && (
<span className="shrink-0 text-[10px] tabular-nums text-muted-foreground">
{count}
</span>
)}
</div>
);
}
+11
View File
@@ -6,6 +6,7 @@ import { TailscaleDevicesPanel } from "./TailscaleDevicesPanel";
import { TailscaleDevicesStatus } from "./TailscaleDevicesStatus";
import { TailscaleAuthEditor } from "./TailscaleAuthEditor";
import { TailscaleCheckOverlay } from "./TailscaleCheckOverlay";
import { TailscaleManagerCard } from "./TailscaleManagerCard";
function Panel({ shell }: PanelProps) {
return (
@@ -49,4 +50,14 @@ export function activate(app: TermixApp): void {
Record<string, unknown>
>,
});
// The Host Metrics manager card, present only when host-metrics is running.
app.registerSlotContribution("host-metrics.managers", {
actionId: "tailscale_manager",
titleKey: "manager.title",
kind: "component",
component: TailscaleManagerCard as unknown as ComponentType<
Record<string, unknown>
>,
});
}
@@ -0,0 +1,105 @@
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { usePluginApi } from "@termix/plugin-sdk/frontend";
export interface ManagerError {
message: string;
code?: string;
}
function extractError(err: unknown): ManagerError {
const e = err as {
response?: { data?: { error?: string; code?: string } };
message?: string;
};
return {
message: e?.response?.data?.error || e?.message || "Request failed",
code: e?.response?.data?.code,
};
}
/** Fetch the Tailscale manager card's status on mount + manual refresh. */
export function useTailscaleData<T>(hostId: number | null) {
const api = usePluginApi();
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<ManagerError | null>(null);
const refresh = useCallback(async () => {
if (hostId == null) return;
setLoading(true);
setError(null);
try {
const res = await api.get<T>(`/host-metrics-manager/${hostId}`);
setData(res.data);
} catch (err) {
setError(extractError(err));
} finally {
setLoading(false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hostId]);
useEffect(() => {
refresh();
}, [refresh]);
return { data, loading, error, refresh };
}
interface ActionResult {
success: boolean;
output?: string;
}
/** Runs the Tailscale manager card's up/down action with toast feedback. */
export function useTailscaleAction(hostId: number | null) {
const api = usePluginApi();
const [busy, setBusy] = useState(false);
const run = useCallback(
async (
action: "up" | "down",
opts: {
loadingMsg?: string;
successMsg?: string;
failMsg?: string;
onDone?: () => void;
} = {},
): Promise<ActionResult | null> => {
if (hostId == null) return null;
const id = `tailscale-manager-${hostId}`;
setBusy(true);
if (opts.loadingMsg) toast.loading(opts.loadingMsg, { id });
try {
const res = await api.post<ActionResult>(
`/host-metrics-manager/${hostId}/action`,
{ action },
);
if (res.data.success) {
if (opts.successMsg)
toast.success(opts.successMsg, {
id,
description: res.data.output?.slice(-200),
});
else toast.dismiss(id);
opts.onDone?.();
} else {
toast.error(opts.failMsg ?? res.data.output ?? "Action failed", {
id,
description: res.data.output?.slice(-200),
});
}
return res.data;
} catch (err) {
toast.error(extractError(err).message, { id });
return null;
} finally {
setBusy(false);
}
},
[hostId],
);
return { busy, run };
}