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

+1 -18
View File
@@ -168,7 +168,6 @@
"firewallPersist": "Persist rules",
"firewallPersisted": "Firewall rules persisted",
"wireguard": "WireGuard",
"tailscale": "Tailscale",
"wgNotInstalled": "WireGuard is not installed on this host",
"wgNoInterfaces": "No WireGuard interfaces configured",
"wgInterfaceUp": "Bring up",
@@ -183,23 +182,7 @@
"wgAllowedIPs": "Allowed IPs",
"wgLastHandshake": "Last handshake",
"wgHandshakeNever": "Never",
"wgTransfer": "Transfer",
"tsNotInstalled": "Tailscale is not installed on this host",
"tsRunning": "Running",
"tsStopped": "Stopped",
"tsEnable": "Connect",
"tsDisable": "Disconnect",
"tsEnabling": "Connecting to Tailscale...",
"tsDisabling": "Disconnecting from Tailscale...",
"tsEnabled": "Tailscale connected",
"tsDisabled": "Tailscale disconnected",
"tsIPs": "Tailscale IPs",
"tsPeers": "Peers",
"tsOnline": "Online",
"tsOffline": "Offline",
"tsExitNode": "Exit node",
"tsExitNodeActive": "Exit node active",
"tsHostname": "Hostname"
"wgTransfer": "Transfer"
}
},
"metricsHistory": {
+7 -1
View File
@@ -49,7 +49,13 @@
"component": "retention"
}
]
}
},
"actionSlots": [
{
"id": "host-metrics.managers",
"accepts": ["component"]
}
]
},
"locales": "locales",
"platforms": ["linux", "win32", "darwin"]
@@ -13,7 +13,6 @@ import { registerUserRoutes } from "./users.js";
import { registerHealthRoutes } from "./health.js";
import { registerLogRoutes } from "./logs.js";
import { registerWireGuardRoutes } from "./wireguard.js";
import { registerTailscaleRoutes } from "./tailscale.js";
/**
* Registers every Host Metrics manager route under the `/host-metrics/managers`
@@ -61,5 +60,4 @@ export function registerManagerRoutes(
registerHealthRoutes(app, deps);
registerLogRoutes(app, deps);
registerWireGuardRoutes(app, deps);
registerTailscaleRoutes(app, deps);
}
@@ -1,177 +0,0 @@
import type { Express } from "express";
import { execCommand } from "../../../../../src/backend/hosts/metrics-shared/common-utils.js";
import { execElevated } from "../../../../../src/backend/hosts/metrics-shared/exec-elevated.js";
import { managerHandler, ManagerInputError } from "./route-helpers.js";
import type { ManagerRoutesDeps } from "./types.js";
import { isValidTailscaleAction } from "../../../../../src/backend/hosts/metrics-shared/validation.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;
// Strip the installation probe line to get the raw JSON
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,
};
}
}
export function registerTailscaleRoutes(
app: Express,
{ validateHostId, runOnHost }: ManagerRoutesDeps,
): void {
/**
* @openapi
* /host-metrics/managers/tailscale/{id}:
* get:
* summary: Get Tailscale status and IPs
* tags:
* - Host Metrics
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Tailscale installation status, running state, IPs, and peer count.
*/
app.get(
"/host-metrics/managers/tailscale/:id",
validateHostId,
managerHandler(runOnHost, "connect", "tailscale_read", async (client) => {
const { stdout } = await execCommand(client, PROBE_CMD, 15000);
return parseTailscaleData(stdout);
}),
);
/**
* @openapi
* /host-metrics/managers/tailscale/{id}/action:
* post:
* summary: Connect or disconnect Tailscale
* tags:
* - Host Metrics
* 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.
*/
app.post(
"/host-metrics/managers/tailscale/:id/action",
validateHostId,
managerHandler(
runOnHost,
"connect",
"tailscale_action",
async (client, host, req) => {
const { action } = req.body as { action: unknown };
if (!isValidTailscaleAction(action)) {
throw new ManagerInputError("Invalid action, must be 'up' or 'down'");
}
const result = await execElevated(
client,
`tailscale ${action}`,
host.sudoPassword,
{ forceSudo: false, timeoutMs: 30000 },
);
return {
success: result.code === 0,
output: (result.stdout + result.stderr).trim(),
};
},
),
);
}
@@ -32,7 +32,10 @@ function hasSnippetInputs(content: string): boolean {
}
import { TOTPDialog } from "@/ssh/dialogs/TOTPDialog.tsx";
import { useTabsSafe } from "@/shell/TabContext.tsx";
import { useTranslation } from "@termix/plugin-sdk/frontend";
import {
useTranslation,
useSlotContributions,
} from "@termix/plugin-sdk/frontend";
import { toast } from "sonner";
import {
type StatsConfig,
@@ -61,6 +64,7 @@ import {
CARD_DEFINITIONS,
IMPLEMENTED_CARD_IDS,
getCardDefinition,
definitionsFromSlot,
defaultColSpanFor,
defaultHeightFor,
type MetricCardHistories,
@@ -177,38 +181,57 @@ function HostMetricsInner({
);
}, [layout, statsConfig.enabledWidgets, metricsPrefs.columns]);
// Manager cards other plugins contribute (tailscale's, say), merged in next
// to the ones this plugin ships. A contribution for a slot that never
// arrives (its plugin is off) just never appears here.
const managerContributions = useSlotContributions("host-metrics.managers");
const pluginManagerDefs = React.useMemo(
() => definitionsFromSlot(managerContributions),
[managerContributions],
);
// Only render/keep cards that are implemented (metric cards in Phase A).
const visibleSlots = React.useMemo(
() => effectiveLayout.slots.filter((s) => getCardDefinition(s.id)),
[effectiveLayout.slots],
() =>
effectiveLayout.slots.filter((s) =>
getCardDefinition(s.id, pluginManagerDefs),
),
[effectiveLayout.slots, pluginManagerDefs],
);
const cardCatalog: GridCardCatalogEntry[] = React.useMemo(
() =>
IMPLEMENTED_CARD_IDS.map((id) => ({
() => [
...IMPLEMENTED_CARD_IDS.map((id) => ({
id,
label: t(CARD_DEFINITIONS[id].labelKey),
defaultColSpan: defaultColSpanFor(id),
defaultHeight: defaultHeightFor(id),
})),
[t],
...Object.values(pluginManagerDefs).map((def) => ({
id: def.id,
label: t(def.labelKey),
defaultColSpan: defaultColSpanFor(def.id),
defaultHeight: defaultHeightFor(def.id),
})),
],
[t, pluginManagerDefs],
);
const cardLabel = React.useCallback(
(id: string) => {
const def = getCardDefinition(id);
const def = getCardDefinition(id, pluginManagerDefs);
return def ? t(def.labelKey) : id;
},
[t],
[t, pluginManagerDefs],
);
const renderCard = React.useCallback(
(id: string) => {
const def = getCardDefinition(id);
const def = getCardDefinition(id, pluginManagerDefs);
if (!def) return null;
return def.render({ metrics, histories, hostId });
},
[metrics, histories, hostId],
[metrics, histories, hostId, pluginManagerDefs],
);
React.useEffect(() => {
@@ -33,7 +33,6 @@ import {
DiskBreakdownCard,
} from "./managers/SimpleManagerCards";
import { WireGuardManagerCard } from "./managers/WireGuardManagerCard";
import { TailscaleManagerCard } from "./managers/TailscaleManagerCard";
export interface MetricCardHistories {
cpu: number[];
@@ -208,20 +207,46 @@ export const CARD_DEFINITIONS: Record<string, CardDefinition> = {
"hostMetrics.managers.wireguard",
WireGuardManagerCard,
),
tailscale_manager: managerCard(
"tailscale_manager",
"hostMetrics.managers.tailscale",
TailscaleManagerCard,
),
};
/** All card ids implemented and available in the Add tray. */
/**
* Manager cards other plugins contribute to "host-metrics.managers" (a
* component slot), keyed by contribution actionId. Built once per render from
* useSlotContributions and merged with CARD_DEFINITIONS below, so a plugin
* like tailscale can add its own manager card without host-metrics knowing it
* exists.
*/
export function definitionsFromSlot(
contributions: Array<{
actionId: string;
titleKey: string;
component?: ComponentType<Record<string, unknown>>;
}>,
): Record<string, CardDefinition> {
const out: Record<string, CardDefinition> = {};
for (const contribution of contributions) {
if (!contribution.component) continue;
const Comp = contribution.component;
out[contribution.actionId] = {
id: contribution.actionId as HostMetricsCardId,
labelKey: contribution.titleKey,
kind: "manager",
render: ({ hostId }) => <Comp hostId={hostId} />,
};
}
return out;
}
/** All card ids built into this plugin and available in the Add tray. */
export const IMPLEMENTED_CARD_IDS = Object.keys(
CARD_DEFINITIONS,
) as HostMetricsCardId[];
export function getCardDefinition(id: string): CardDefinition | undefined {
return CARD_DEFINITIONS[id];
export function getCardDefinition(
id: string,
extra?: Record<string, CardDefinition>,
): CardDefinition | undefined {
return CARD_DEFINITIONS[id] ?? extra?.[id];
}
export { defaultColSpanFor, defaultHeightFor };
@@ -158,4 +158,9 @@ export function activate(app: TermixApp): void {
descriptionKey: "onboarding.feature_metrics_desc",
icon: Activity as ComponentType<{ className?: string }>,
});
app.declareActionSlot({
id: "host-metrics.managers",
accepts: ["component"],
});
}
+19
View File
@@ -50,5 +50,24 @@
"tailscaleCheckOpenBrowser": "Open Browser to Authenticate",
"tailscaleCheckWaiting": "Waiting for Tailscale authentication...",
"tailscaleCheckTimeout": "Tailscale authentication timed out. Please try again."
},
"manager": {
"title": "Tailscale",
"refresh": "Refresh",
"retry": "Retry",
"sudoHint": "Set a sudo password for this host to allow elevated actions.",
"noData": "No data available",
"filter": "Filter...",
"tsNotInstalled": "Tailscale is not installed on this host",
"tsRunning": "Running",
"tsStopped": "Stopped",
"tsEnable": "Connect",
"tsDisable": "Disconnect",
"tsEnabling": "Connecting to Tailscale...",
"tsDisabling": "Disconnecting from Tailscale...",
"tsEnabled": "Tailscale connected",
"tsDisabled": "Tailscale disconnected",
"tsExitNode": "Exit node",
"tsExitNodeActive": "Exit node active"
}
}
+11 -1
View File
@@ -18,8 +18,14 @@
"settings:read-core",
"network:outbound",
"network:serve",
"auth:provide",
"ssh:connect",
"credentials:use",
"ui:surface"
],
"optionalDependencies": {
"host-metrics": "^1.0.0"
},
"contributes": {
"panels": [
{
@@ -32,9 +38,13 @@
{
"name": "devices.view",
"titleKey": "permissions.devices.view.title",
"descriptionKey": "permissions.devices.view.description"
"descriptionKey": "permissions.devices.view.description",
"defaultRoles": ["admin"]
}
],
"auth": {
"sshAuthTypes": ["tailscale"]
},
"settings": {
"admin": [
{
@@ -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);
}
@@ -1,9 +1,11 @@
import { useState } from "react";
import { Power } from "lucide-react";
import { useTranslation } from "@termix/plugin-sdk/frontend";
import { useManagerData, useManagerAction } from "./useManagerData";
import { ManagerCardShell } from "./ManagerCardShell";
import { ManagerSearch } from "./ManagerToolbar";
import { useTailscaleData, useTailscaleAction } from "./useTailscaleManager";
import {
TailscaleManagerShell,
TailscaleManagerSearch,
} from "./TailscaleManagerShell";
interface TailscalePeer {
hostname: string;
@@ -23,30 +25,23 @@ interface TailscaleData {
export function TailscaleManagerCard({ hostId }: { hostId: number | null }) {
const { t } = useTranslation();
const { data, loading, error, refresh } = useManagerData<TailscaleData>(
hostId,
"tailscale",
);
const { busy, run } = useManagerAction(hostId);
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(
"tailscale",
{ action },
{
action: "action",
loadingMsg: data.running
? t("hostMetrics.managers.tsDisabling")
: t("hostMetrics.managers.tsEnabling"),
successMsg: data.running
? t("hostMetrics.managers.tsDisabled")
: t("hostMetrics.managers.tsEnabled"),
onDone: refresh,
},
);
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(
@@ -59,14 +54,14 @@ export function TailscaleManagerCard({ hostId }: { hostId: number | null }) {
const isNotInstalled = data && !data.installed;
return (
<ManagerCardShell
title={t("hostMetrics.managers.tailscale")}
<TailscaleManagerShell
title={t("manager.title")}
icon={<Power className="size-3.5" />}
loading={loading}
error={error}
onRefresh={refresh}
empty={!!isNotInstalled}
emptyMessage={t("hostMetrics.managers.tsNotInstalled")}
emptyMessage={t("manager.tsNotInstalled")}
>
{data && (
<div className="flex flex-col">
@@ -79,8 +74,8 @@ export function TailscaleManagerCard({ hostId }: { hostId: number | null }) {
<div className="flex min-w-0 flex-col">
<span className="text-xs font-semibold">
{data.running
? t("hostMetrics.managers.tsRunning")
: t("hostMetrics.managers.tsStopped")}
? t("manager.tsRunning")
: t("manager.tsStopped")}
</span>
{data.hostname && (
<span className="truncate font-mono text-[10px] text-muted-foreground">
@@ -102,9 +97,7 @@ export function TailscaleManagerCard({ hostId }: { hostId: number | null }) {
onClick={handleToggle}
disabled={busy || !data.installed}
title={
data.running
? t("hostMetrics.managers.tsDisable")
: t("hostMetrics.managers.tsEnable")
data.running ? t("manager.tsDisable") : t("manager.tsEnable")
}
className={`flex size-6 items-center justify-center transition-colors disabled:opacity-40 ${
data.running
@@ -121,14 +114,14 @@ export function TailscaleManagerCard({ hostId }: { hostId: number | null }) {
{data.exitNodeInUse && (
<div className="border-b border-border/50 px-0 py-1.5">
<span className="text-[10px] text-blue-500">
{t("hostMetrics.managers.tsExitNodeActive")}
{t("manager.tsExitNodeActive")}
</span>
</div>
)}
{/* Peers */}
{(data.peers?.length ?? 0) > 5 && (
<ManagerSearch
<TailscaleManagerSearch
value={query}
onChange={setQuery}
count={filteredPeers.length}
@@ -159,13 +152,13 @@ export function TailscaleManagerCard({ hostId }: { hostId: number | null }) {
</div>
{peer.isExitNode && (
<span className="shrink-0 text-[10px] text-blue-500">
{t("hostMetrics.managers.tsExitNode")}
{t("manager.tsExitNode")}
</span>
)}
</div>
))}
</div>
)}
</ManagerCardShell>
</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 };
}
@@ -0,0 +1,55 @@
import { describe, it, expect } from "vitest";
import { parseTailscaleData } from "../../src/backend/host-metrics-manager.js";
describe("parseTailscaleData", () => {
it("reports not installed when the probe finds no binary", () => {
const result = parseTailscaleData("ts_installed=0\n");
expect(result.installed).toBe(false);
expect(result.running).toBe(false);
});
it("parses a running tailscale status", () => {
const status = JSON.stringify({
BackendState: "Running",
Self: { HostName: "my-server", TailscaleIPs: ["100.1.2.3"] },
Peer: {
abc: {
HostName: "peer-1",
TailscaleIPs: ["100.1.2.4"],
Online: true,
ExitNode: false,
},
},
CurrentExitNode: "",
});
const result = parseTailscaleData(`ts_installed=1\n${status}`);
expect(result.installed).toBe(true);
expect(result.running).toBe(true);
expect(result.hostname).toBe("my-server");
expect(result.tailscaleIPs).toEqual(["100.1.2.3"]);
expect(result.peers).toHaveLength(1);
expect(result.peers[0]).toMatchObject({
hostname: "peer-1",
online: true,
});
expect(result.exitNodeInUse).toBe(false);
});
it("reports installed but not running on malformed JSON", () => {
const result = parseTailscaleData("ts_installed=1\nnot json");
expect(result.installed).toBe(true);
expect(result.running).toBe(false);
});
it("detects an active exit node", () => {
const status = JSON.stringify({
BackendState: "Running",
Self: {},
Peer: {},
CurrentExitNode: "abc123",
});
const result = parseTailscaleData(`ts_installed=1\n${status}`);
expect(result.exitNodeInUse).toBe(true);
});
});
@@ -43,12 +43,12 @@ describe("tailscale permissions", () => {
}
});
// No wildcard covered tailscale in SYSTEM_ROLE_DEFAULTS, so nothing is
// granted by default and an admin has to opt in.
it("grants nothing by default", () => {
for (const permission of manifest.manifest?.contributes?.permissions ??
[]) {
expect(permission.defaultRoles).toBeUndefined();
}
// The device list is a full tailnet inventory, so only admins get it by
// default; everyone else needs an explicit grant.
it("grants devices.view to admins by default", () => {
const devicesView = manifest.manifest?.contributes?.permissions?.find(
(permission) => permission.name === "devices.view",
);
expect(devicesView?.defaultRoles).toEqual(["admin"]);
});
});
@@ -0,0 +1,181 @@
import { describe, it, expect } from "vitest";
import { createFakeContext } from "@termix/plugin-sdk/testing";
import { registerTailscaleSshAuth } from "../../src/backend/ssh-auth-provider.js";
import { TAILSCALE_CHECK_TIMEOUT_MS } from "../../src/backend/tailscale-check.js";
function register() {
const { ctx, auth } = createFakeContext({ pluginId: "tailscale" });
registerTailscaleSshAuth(ctx);
return auth.sshAuthProviders.find(
(provider) => provider.type === "tailscale",
)!;
}
describe("tailscale SSH auth provider", () => {
it("registers as type tailscale", () => {
expect(register()).toBeTruthy();
});
it("turns off keyboard-interactive, with a long timeout for the terminal", () => {
const provider = register();
const terminal = provider.connectOptions?.(
{ id: 1, ip: "100.1.1.1", port: 22, username: "root" },
"terminal",
);
expect(terminal).toMatchObject({
tryKeyboard: false,
readyTimeout: TAILSCALE_CHECK_TIMEOUT_MS,
timeout: TAILSCALE_CHECK_TIMEOUT_MS,
});
const fleet = provider.connectOptions?.(
{ id: 1, ip: "100.1.1.1", port: 22, username: "root" },
"fleet",
);
expect(fleet).toEqual({ tryKeyboard: false });
});
it("prepare always reports ready", async () => {
const provider = register();
const outcome = await provider.prepare(
{},
{ id: 1, ip: "100.1.1.1", port: 22, username: "root" },
{
client: {},
userId: "u1",
hostId: 1,
purpose: "terminal",
interactive: true,
log: () => {},
},
);
expect(outcome).toEqual({ status: "ready" });
});
describe("onBanner", () => {
it("holds the connection when the banner carries a check URL", () => {
const provider = register();
const decision = provider.onBanner?.(
"# Tailscale SSH requires an additional check.\n# To authenticate, visit: https://login.tailscale.com/a/abc123\n",
{ id: 1, ip: "100.1.1.1", port: 22, username: "root" },
{
client: {},
userId: "u1",
hostId: 1,
purpose: "terminal",
interactive: true,
log: () => {},
},
);
expect(decision).toMatchObject({
action: "hold",
details: { url: "https://login.tailscale.com/a/abc123" },
});
});
it("releases the hold on the completion banner", () => {
const provider = register();
const decision = provider.onBanner?.(
"Authentication checked with Tailscale SSH.",
{ id: 1, ip: "100.1.1.1", port: 22, username: "root" },
{
client: {},
userId: "u1",
hostId: 1,
purpose: "terminal",
interactive: true,
log: () => {},
},
);
expect(decision).toEqual({ action: "release" });
});
it("ignores an ordinary MOTD banner", () => {
const provider = register();
const decision = provider.onBanner?.(
"Welcome to Ubuntu 24.04 LTS\n",
{ id: 1, ip: "100.1.1.1", port: 22, username: "root" },
{
client: {},
userId: "u1",
hostId: 1,
purpose: "terminal",
interactive: true,
log: () => {},
},
);
expect(decision).toBeUndefined();
});
});
describe("onAuthFailed", () => {
it("retries once in forced password mode", () => {
const provider = register();
const outcome = provider.onAuthFailed?.(
{ id: 1, ip: "100.1.1.1", port: 22, username: "root" },
{
client: {},
userId: "u1",
hostId: 1,
purpose: "terminal",
interactive: true,
log: () => {},
},
{
error: new Error("All configured authentication methods failed"),
retries: 0,
canRetry: true,
methodNotAvailable: false,
},
);
expect(outcome).toMatchObject({
status: "retry",
patch: { username: "root+password" },
});
});
it("fails after a retry has already happened", () => {
const provider = register();
const outcome = provider.onAuthFailed?.(
{ id: 1, ip: "100.1.1.1", port: 22, username: "root" },
{
client: {},
userId: "u1",
hostId: 1,
purpose: "terminal",
interactive: true,
log: () => {},
},
{
error: new Error("All configured authentication methods failed"),
retries: 1,
canRetry: true,
methodNotAvailable: false,
},
);
expect(outcome).toMatchObject({ status: "error", code: "failed" });
});
it("does nothing for an unrelated failure", () => {
const provider = register();
const outcome = provider.onAuthFailed?.(
{ id: 1, ip: "100.1.1.1", port: 22, username: "root" },
{
client: {},
userId: "u1",
hostId: 1,
purpose: "terminal",
interactive: true,
log: () => {},
},
{
error: new Error("connection reset"),
retries: 0,
canRetry: true,
methodNotAvailable: false,
},
);
expect(outcome).toBeUndefined();
});
});
});
@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest";
import {
parseTailscaleCheckBanner,
isTailscaleCheckCompleteBanner,
} from "../../../../src/backend/hosts/tailscale-check.js";
} from "../../src/backend/tailscale-check.js";
describe("parseTailscaleCheckBanner", () => {
it("extracts the login URL from a real check-mode banner", () => {