mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-28 06:05:24 +00:00
feat: give plugins their own settings and one settings screen
This commit is contained in:
1 parent
cc15559ea1
commit
49f0286a14
66 files changed
+36497
-451
No files matched your search
@@ -27,7 +27,34 @@
|
||||
"titleKey": "permissions.devices.view.title",
|
||||
"descriptionKey": "permissions.devices.view.description"
|
||||
}
|
||||
]
|
||||
],
|
||||
"settings": {
|
||||
"admin": [
|
||||
{
|
||||
"key": "apiKey",
|
||||
"type": "secret",
|
||||
"labelKey": "settings.apiKey.label",
|
||||
"descriptionKey": "settings.apiKey.description",
|
||||
"placeholderKey": "settings.apiKey.placeholder",
|
||||
"group": "settings.group.api"
|
||||
},
|
||||
{
|
||||
"key": "apiBaseUrl",
|
||||
"type": "string",
|
||||
"labelKey": "settings.apiBaseUrl.label",
|
||||
"descriptionKey": "settings.apiBaseUrl.description",
|
||||
"placeholderKey": "settings.apiBaseUrl.placeholder",
|
||||
"default": "",
|
||||
"group": "settings.group.api"
|
||||
},
|
||||
{
|
||||
"key": "devices",
|
||||
"type": "custom",
|
||||
"component": "devices",
|
||||
"group": "settings.group.devices"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"locales": "locales",
|
||||
"platforms": ["linux", "win32", "darwin"]
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { PluginContext } from "@termix/plugin-sdk/backend";
|
||||
import { startTailscaleService, stopTailscaleService } from "./routes.js";
|
||||
|
||||
export async function activate(ctx: PluginContext) {
|
||||
startTailscaleService(ctx.http.router());
|
||||
startTailscaleService(ctx.http.router(), ctx);
|
||||
ctx.log.info("Tailscale routes mounted at /plugin-api/tailscale");
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ 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 type { PluginContext } from "@termix/plugin-sdk/backend";
|
||||
|
||||
interface TailscaleDevice {
|
||||
id: string;
|
||||
@@ -33,6 +33,12 @@ 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();
|
||||
|
||||
@@ -85,13 +91,17 @@ router.get(
|
||||
requireDeviceAccess,
|
||||
async (_req, res) => {
|
||||
try {
|
||||
const settingsRepo = createCurrentSettingsRepository();
|
||||
const apiKey = (await settingsRepo.get("tailscale_api_key")) ?? "";
|
||||
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 settingsRepo.get("tailscale_api_base_url"),
|
||||
(await context.settings.get<string>("apiBaseUrl")) ?? null,
|
||||
);
|
||||
|
||||
const url = `${apiBase}/tailnet/-/devices?fields=all`;
|
||||
@@ -148,12 +158,18 @@ router.get(
|
||||
|
||||
/** Called from activate(). Mounts this router at /tailscale via the shared
|
||||
* dispatcher. */
|
||||
export function startTailscaleService(mountOn: Router): void {
|
||||
export function startTailscaleService(
|
||||
mountOn: Router,
|
||||
ctx: PluginContext,
|
||||
): void {
|
||||
context = ctx;
|
||||
mountOn.use(router);
|
||||
}
|
||||
|
||||
/** Called from deactivate(). /tailscale/* falls back to 404 until
|
||||
* reactivated. */
|
||||
export function stopTailscaleService(): void {
|
||||
// Unmounted by the runtime when the plugin deactivates.
|
||||
// Dropped so a request arriving mid-teardown cannot read settings through a
|
||||
// context the runtime has already torn down.
|
||||
context = null;
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,39 +1,11 @@
|
||||
// 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).
|
||||
// The API key and base URL are this plugin's own settings now, read and
|
||||
// written through the generic /plugins/tailscale/settings/admin routes that
|
||||
// core renders from the manifest. Only the device list is left here, because
|
||||
// it is this plugin's own route.
|
||||
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { parseManifest } from "@termix/plugin-sdk/manifest";
|
||||
import { createMockCtx } from "@termix/plugin-sdk/testing";
|
||||
|
||||
/**
|
||||
* The API key and base URL are this plugin's own settings now.
|
||||
*
|
||||
* They used to live in the core `settings` table behind a core route that
|
||||
* existed only for this plugin, with the key stored in plaintext. These tests
|
||||
* pin the shape core renders the page from, and that reading a plugin's own
|
||||
* settings needs no capability.
|
||||
*/
|
||||
const manifest = parseManifest(
|
||||
JSON.parse(
|
||||
fs.readFileSync(
|
||||
path.resolve(import.meta.dirname, "../../manifest.json"),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("tailscale settings contribution", () => {
|
||||
it("parses cleanly", () => {
|
||||
expect(manifest.errors).toEqual([]);
|
||||
});
|
||||
|
||||
it("declares the API key as a secret, so it is encrypted and redacted", () => {
|
||||
const apiKey = manifest.manifest?.contributes?.settings?.admin?.find(
|
||||
(field) => field.key === "apiKey",
|
||||
);
|
||||
|
||||
expect(apiKey?.type).toBe("secret");
|
||||
});
|
||||
|
||||
it("declares the base URL as plain text, because it is not a secret", () => {
|
||||
const baseUrl = manifest.manifest?.contributes?.settings?.admin?.find(
|
||||
(field) => field.key === "apiBaseUrl",
|
||||
);
|
||||
|
||||
expect(baseUrl?.type).toBe("string");
|
||||
expect(baseUrl?.default).toBe("");
|
||||
});
|
||||
|
||||
it("puts both fields on the admin scope, not the user one", () => {
|
||||
const settings = manifest.manifest?.contributes?.settings;
|
||||
|
||||
expect(settings?.admin?.map((field) => field.key)).toContain("apiKey");
|
||||
expect(settings?.user).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps settings:read-core, which it still holds for core keys", () => {
|
||||
expect(manifest.manifest?.capabilities).toContain("settings:read-core");
|
||||
});
|
||||
});
|
||||
|
||||
describe("reading its own settings", () => {
|
||||
it("needs no capability", async () => {
|
||||
// Nothing granted at all: a plugin reading its own configuration must not
|
||||
// have to declare anything for it.
|
||||
const { ctx } = createMockCtx({
|
||||
pluginId: "tailscale",
|
||||
capabilities: [],
|
||||
settings: { apiKey: "tskey-api-test", apiBaseUrl: "" },
|
||||
});
|
||||
|
||||
await expect(ctx.settings.get("apiKey")).resolves.toBe("tskey-api-test");
|
||||
});
|
||||
|
||||
it("can write and read a value back", async () => {
|
||||
const { ctx } = createMockCtx({ pluginId: "tailscale", capabilities: [] });
|
||||
|
||||
await ctx.settings.set("apiBaseUrl", "https://headscale.example");
|
||||
|
||||
await expect(ctx.settings.get("apiBaseUrl")).resolves.toBe(
|
||||
"https://headscale.example",
|
||||
);
|
||||
});
|
||||
|
||||
it("still needs settings:read-core to reach a core key", async () => {
|
||||
const { ctx } = createMockCtx({ pluginId: "tailscale", capabilities: [] });
|
||||
|
||||
await expect(ctx.settings.readCore("app_name")).rejects.toThrow(
|
||||
/settings:read-core/,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,62 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user