feat: make each plugin an npm workspace built by a termix-plugin CLI

This commit is contained in:
LukeGus committed 2026-09-22 15:09:50 -05:00
1 parent 4758016f41
commit 5796186a1c
448 files changed
+3087 -2003

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
# Changelog
## 1.0.0
Bundled with Termix 2.9.0.
+22
View File
@@ -0,0 +1,22 @@
# Tailscale
Browse and connect to tailnet devices, manage the Tailscale API key, and show the Tailscale SSH re-authentication dialog.
Bundled with Termix and enabled by default.
## Layout
manifest.json id, capabilities and what this plugin contributes
src/backend/ activate(ctx) / deactivate(), plus the routes
src/frontend/ the UI it registers
locales/en.json its strings (English only; the rest are translated)
tests/backend/ vitest, node
tests/frontend/ vitest, jsdom
## Commands
npm run build bundle into dist/
npm run test run this plugin's tests
npm run typecheck
See packages/plugin-sdk/ARCHITECTURE.md for the contract this follows.
-69
View File
@@ -1,69 +0,0 @@
/**
* 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;
}
}
+1
View File
@@ -0,0 +1 @@
{}
-2
View File
@@ -21,8 +21,6 @@
"permissions": ["tailscale.devices.view"]
}
},
"backend": "backend/index.mjs",
"frontend": "frontend/index.mjs",
"locales": "locales",
"platforms": ["linux", "win32", "darwin"]
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "@termix-plugin/tailscale",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "termix-plugin build",
"test": "termix-plugin test",
"typecheck": "tsc -p tsconfig.json",
"validate": "termix-plugin validate"
},
"devDependencies": {
"@termix/plugin-sdk": "*"
}
}
+11
View File
@@ -0,0 +1,11 @@
import type { PluginContext } from "@termix/plugin-sdk/backend";
import { startTailscaleService, stopTailscaleService } from "./routes.js";
export async function activate(ctx: PluginContext) {
startTailscaleService();
ctx.log.info("Tailscale router registered at /tailscale");
}
export async function deactivate() {
stopTailscaleService();
}
@@ -4,15 +4,15 @@
// 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 { createCurrentSettingsRepository } from "../../../src/backend/database/repositories/factory.js";
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 { createCurrentSettingsRepository } from "../../../../src/backend/database/repositories/factory.js";
import {
registerTailscaleRouter,
unregisterTailscaleRouter,
} from "../../../src/backend/database/routes/tailscale-dispatch.js";
} from "../../../../src/backend/database/routes/tailscale-dispatch.js";
interface TailscaleDevice {
id: string;
@@ -5,7 +5,7 @@ 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";
import { createQuickConnectHost } from "../../../../src/ui/sidebar/quick-connect-host";
interface TailscaleDevice {
id: string;
@@ -0,0 +1,76 @@
import { describe, it, expect } from "vitest";
import {
parseTailscaleCheckBanner,
isTailscaleCheckCompleteBanner,
} from "../../../../src/backend/hosts/tailscale-check.js";
describe("parseTailscaleCheckBanner", () => {
it("extracts the login URL from a real check-mode banner", () => {
const banner =
"# Tailscale SSH requires an additional check.\n# To authenticate, visit: https://login.tailscale.com/a/lefcb2f3377403\n";
const result = parseTailscaleCheckBanner(banner);
expect(result).not.toBeNull();
expect(result?.url).toBe("https://login.tailscale.com/a/lefcb2f3377403");
});
it("strips comment markers from the message it returns", () => {
const banner =
"# Tailscale SSH requires an additional check.\n# To authenticate, visit: https://login.tailscale.com/a/abc123\n";
const result = parseTailscaleCheckBanner(banner);
expect(result?.message).toBe(
"Tailscale SSH requires an additional check.\nTo authenticate, visit: https://login.tailscale.com/a/abc123",
);
});
it("returns null for an ordinary MOTD banner", () => {
const banner =
"Welcome to Ubuntu 24.04 LTS\nLast login: Tue Aug 5 09:12:03 2026\n";
expect(parseTailscaleCheckBanner(banner)).toBeNull();
});
it("returns null for a lookalike URL on another host", () => {
const banner =
"# To authenticate, visit: https://login.tailscale.com.evil.example/a/abc123\n";
expect(parseTailscaleCheckBanner(banner)).toBeNull();
});
it("returns null for empty input", () => {
expect(parseTailscaleCheckBanner("")).toBeNull();
});
});
describe("isTailscaleCheckCompleteBanner", () => {
it("recognises the completion banner", () => {
expect(
isTailscaleCheckCompleteBanner(
"# Authentication checked with Tailscale SSH.",
),
).toBe(true);
});
it("recognises the completion banner with a time suffix", () => {
expect(
isTailscaleCheckCompleteBanner(
"Authentication checked with Tailscale SSH. Time since last authentication: 0s",
),
).toBe(true);
});
it("does not match the check-required banner", () => {
expect(
isTailscaleCheckCompleteBanner(
"# Tailscale SSH requires an additional check.",
),
).toBe(false);
});
it("does not match empty input", () => {
expect(isTailscaleCheckCompleteBanner("")).toBe(false);
});
});
@@ -0,0 +1,62 @@
import { describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { AdminTailscaleSection } from "../../src/frontend/AdminTailscaleSection";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
describe("AdminTailscaleSection", () => {
it("renders the API key and base URL fields and saves on click", async () => {
const user = userEvent.setup();
const handleSave = vi.fn();
render(
<AdminTailscaleSection
open
onToggle={vi.fn()}
tailscaleApiKey="tskey-api-abc"
setTailscaleApiKey={vi.fn()}
tailscaleApiBaseUrl="https://api.tailscale.com/api/v2"
setTailscaleApiBaseUrl={vi.fn()}
handleSaveTailscaleApiKey={handleSave}
/>,
);
expect(
(
screen.getByPlaceholderText(
"tskey-api-... / hskey-api-...",
) as HTMLInputElement
).value,
).toBe("tskey-api-abc");
expect(
(
screen.getByPlaceholderText(
"https://api.tailscale.com/api/v2",
) as HTMLInputElement
).value,
).toBe("https://api.tailscale.com/api/v2");
await user.click(screen.getByText("common.save"));
expect(handleSave).toHaveBeenCalledOnce();
});
it("does not render its content when closed", () => {
render(
<AdminTailscaleSection
open={false}
onToggle={vi.fn()}
tailscaleApiKey=""
setTailscaleApiKey={vi.fn()}
tailscaleApiBaseUrl=""
setTailscaleApiBaseUrl={vi.fn()}
handleSaveTailscaleApiKey={vi.fn()}
/>,
);
expect(
screen.queryByPlaceholderText("tskey-api-... / hskey-api-..."),
).toBeNull();
});
});
@@ -0,0 +1,76 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const getTailscaleDevicesMock = vi.hoisted(() => vi.fn());
vi.mock("../../src/frontend/tailscale-api", () => ({
getTailscaleDevices: getTailscaleDevicesMock,
}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
import { TailscaleDevicesPanel } from "../../src/frontend/TailscaleDevicesPanel";
beforeEach(() => {
vi.clearAllMocks();
});
describe("TailscaleDevicesPanel", () => {
it("shows the no-api-key message when hasApiKey is false", async () => {
getTailscaleDevicesMock.mockResolvedValue({
devices: [],
hasApiKey: false,
});
render(<TailscaleDevicesPanel onConnect={vi.fn()} />);
await waitFor(() =>
expect(screen.getByText("hosts.tailscaleNoApiKey")).toBeTruthy(),
);
});
it("shows the empty-devices message when the tailnet has no devices", async () => {
getTailscaleDevicesMock.mockResolvedValue({ devices: [], hasApiKey: true });
render(<TailscaleDevicesPanel onConnect={vi.fn()} />);
await waitFor(() =>
expect(screen.getByText("hosts.tailscaleNoDevices")).toBeTruthy(),
);
});
it("renders devices and connects with an ephemeral tailscale host", async () => {
const user = userEvent.setup();
getTailscaleDevicesMock.mockResolvedValue({
hasApiKey: true,
devices: [
{
id: "d1",
name: "box",
hostname: "box",
addresses: ["100.64.0.1"],
os: "linux",
lastSeen: "2026-01-01T00:00:00Z",
},
],
});
const onConnect = vi.fn();
render(<TailscaleDevicesPanel onConnect={onConnect} />);
await waitFor(() => expect(screen.getByText("box")).toBeTruthy());
await user.click(
screen.getByText("newUi.sidebar.quickConnect.connectToTerminal"),
);
expect(onConnect).toHaveBeenCalledOnce();
const [host, type] = onConnect.mock.calls[0];
expect(type).toBe("terminal");
expect(host.ip).toBe("100.64.0.1");
expect(host.authType).toBe("tailscale");
expect(host.username).toBe("root");
});
});
@@ -0,0 +1,49 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const authApiMock = vi.hoisted(() => ({ get: vi.fn(), patch: vi.fn() }));
const handleApiErrorMock = vi.hoisted(() => vi.fn());
vi.mock("@/main-axios", () => ({
authApi: authApiMock,
statsApi: { get: vi.fn(), patch: vi.fn() },
handleApiError: handleApiErrorMock,
}));
import { getTailscaleDevices } from "../../src/frontend/tailscale-api";
beforeEach(() => {
vi.clearAllMocks();
});
describe("getTailscaleDevices", () => {
it("preserves configured-key state when discovery fails", async () => {
authApiMock.get.mockRejectedValue({
isAxiosError: true,
response: {
data: {
devices: [],
hasApiKey: true,
error: "Failed to fetch Tailscale devices",
},
},
});
await expect(getTailscaleDevices()).resolves.toEqual({
devices: [],
hasApiKey: true,
error: "Failed to fetch Tailscale devices",
});
expect(handleApiErrorMock).not.toHaveBeenCalled();
});
it("uses normal API error handling when no structured state is available", async () => {
const error = { isAxiosError: true, response: { data: {} } };
authApiMock.get.mockRejectedValue(error);
await expect(getTailscaleDevices()).rejects.toBe(error);
expect(handleApiErrorMock).toHaveBeenCalledWith(
error,
"fetch Tailscale devices",
);
});
});
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "@termix/plugin-sdk/tsconfig.plugin.json",
"compilerOptions": {
"paths": {
"@/types/*": ["../../src/types/*"],
"@/*": ["../../src/ui/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.tsx", "tests/**/*.ts", "tests/**/*.tsx"]
}
+3
View File
@@ -0,0 +1,3 @@
import { pluginVitestConfig } from "@termix/plugin-sdk/vitest-preset";
export default pluginVitestConfig(import.meta.url);