mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-28 06:05:24 +00:00
feat(hosts): add instance-wide predefined tag suggestions (#1548)
* feat(hosts): add shared predefined tag suggestions * style(hosts): format tag catalog routes
This commit is contained in:
1 parent
94a9f815c9
commit
b00551c394
9 files changed
+274
-7
No files matched your search
@@ -0,0 +1,40 @@
|
||||
import type { RequestHandler, Router } from "express";
|
||||
import { createCurrentSettingsRepository } from "../repositories/factory.js";
|
||||
|
||||
const CATALOG_KEY = "host_tag_catalog";
|
||||
|
||||
export function registerHostTagRoutes(
|
||||
router: Router,
|
||||
authenticate: RequestHandler,
|
||||
requireAdmin: RequestHandler,
|
||||
): void {
|
||||
router.get("/tags", authenticate, async (_req, res) => {
|
||||
const value = await createCurrentSettingsRepository().get(CATALOG_KEY);
|
||||
res.json({ tags: value ? JSON.parse(value) : [] });
|
||||
});
|
||||
|
||||
router.put("/tags", authenticate, requireAdmin, async (req, res) => {
|
||||
const tags: unknown = req.body?.tags;
|
||||
if (
|
||||
!Array.isArray(tags) ||
|
||||
tags.length > 500 ||
|
||||
tags.some(
|
||||
(tag) =>
|
||||
typeof tag !== "string" || !tag.trim() || tag.trim().length > 100,
|
||||
)
|
||||
) {
|
||||
res.status(400).json({
|
||||
error: "Expected up to 500 non-empty tags of at most 100 characters",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const normalized = [
|
||||
...new Set((tags as string[]).map((tag) => tag.trim())),
|
||||
];
|
||||
await createCurrentSettingsRepository().set(
|
||||
CATALOG_KEY,
|
||||
JSON.stringify(normalized),
|
||||
);
|
||||
res.json({ tags: normalized });
|
||||
});
|
||||
}
|
||||
@@ -53,6 +53,7 @@ import { registerHostFolderRoutes } from "./host-folder-routes.js";
|
||||
import { registerHostNetworkRoutes } from "./host-network-routes.js";
|
||||
import { registerHostBulkRoutes } from "./host-bulk-routes.js";
|
||||
import { registerHostDefaultsRoutes } from "./host-defaults-routes.js";
|
||||
import { registerHostTagRoutes } from "./host-tag-routes.js";
|
||||
import { registerHostStatusRoutes } from "./host-status-routes.js";
|
||||
import {
|
||||
applyHostEnrollmentDefaults,
|
||||
@@ -136,6 +137,12 @@ const permissionManager = PermissionManager.getInstance();
|
||||
const authenticateJWT = authManager.createAuthMiddleware();
|
||||
const requireDataAccess = authManager.createDataAccessMiddleware();
|
||||
|
||||
registerHostTagRoutes(
|
||||
router,
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("admin.settings.manage"),
|
||||
);
|
||||
|
||||
registerHostStatusRoutes(router, {
|
||||
authenticateJWT,
|
||||
requireAdmin: authManager.createAdminMiddleware(),
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
|
||||
const settings = vi.hoisted(() => new Map<string, string>());
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentSettingsRepository: () => ({
|
||||
get: async (key: string) => settings.get(key) ?? null,
|
||||
set: async (key: string, value: string) => {
|
||||
settings.set(key, value);
|
||||
},
|
||||
}),
|
||||
}));
|
||||
import { registerHostTagRoutes } from "../../../database/routes/host-tag-routes.js";
|
||||
|
||||
function app() {
|
||||
const server = express();
|
||||
server.use(express.json());
|
||||
registerHostTagRoutes(
|
||||
server,
|
||||
(req, res, next) =>
|
||||
req.headers.authorization ? next() : void res.sendStatus(401),
|
||||
(req, res, next) =>
|
||||
req.headers.authorization === "admin" ? next() : void res.sendStatus(403),
|
||||
);
|
||||
return server;
|
||||
}
|
||||
|
||||
beforeEach(() => settings.clear());
|
||||
describe("instance host tag catalog", () => {
|
||||
it("allows authenticated users to read the same admin-managed catalog", async () => {
|
||||
const server = app();
|
||||
await request(server)
|
||||
.put("/tags")
|
||||
.set("Authorization", "admin")
|
||||
.send({ tags: [" Linux ", "Domain Controller", "Linux"] })
|
||||
.expect(200, { tags: ["Linux", "Domain Controller"] });
|
||||
await request(server)
|
||||
.get("/tags")
|
||||
.set("Authorization", "member")
|
||||
.expect(200, { tags: ["Linux", "Domain Controller"] });
|
||||
});
|
||||
it("rejects anonymous reads and non-admin writes", async () => {
|
||||
await request(app()).get("/tags").expect(401);
|
||||
await request(app())
|
||||
.put("/tags")
|
||||
.set("Authorization", "member")
|
||||
.send({ tags: ["test"] })
|
||||
.expect(403);
|
||||
expect(settings.size).toBe(0);
|
||||
});
|
||||
it.each([null, [42], [" "], ["x".repeat(101)], Array(501).fill("tag")])(
|
||||
"rejects invalid catalogs",
|
||||
async (tags) => {
|
||||
await request(app())
|
||||
.put("/tags")
|
||||
.set("Authorization", "admin")
|
||||
.send({ tags })
|
||||
.expect(400);
|
||||
expect(settings.size).toBe(0);
|
||||
},
|
||||
);
|
||||
it("allows clearing suggestions without modifying hosts", async () => {
|
||||
settings.set("host_tag_catalog", '["Linux"]');
|
||||
await request(app())
|
||||
.put("/tags")
|
||||
.set("Authorization", "admin")
|
||||
.send({ tags: [] })
|
||||
.expect(200, { tags: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { hostApi } from "@/main-axios";
|
||||
|
||||
export async function getHostTags(): Promise<string[]> {
|
||||
return (await hostApi.get<{ tags: string[] }>("/tags")).data.tags;
|
||||
}
|
||||
|
||||
export async function saveHostTags(tags: string[]): Promise<string[]> {
|
||||
return (await hostApi.put<{ tags: string[] }>("/tags", { tags })).data.tags;
|
||||
}
|
||||
@@ -1504,7 +1504,11 @@
|
||||
"sslIssuer": "Issued by {{issuer}}",
|
||||
"sslNames": "Covers {{names}}",
|
||||
"sslManualTitle": "Upload a certificate",
|
||||
"updateExternalAutoProvisionFailed": "Failed to update the auto-create setting"
|
||||
"updateExternalAutoProvisionFailed": "Failed to update the auto-create setting",
|
||||
"hostTags": "Predefined host tags",
|
||||
"hostTagsDesc": "One tag per line, available to all users. Editing this list changes suggestions only; tags already assigned to hosts are kept.",
|
||||
"hostTagsSaved": "Host tag suggestions saved.",
|
||||
"hostTagsError": "Could not load or save host tag suggestions."
|
||||
},
|
||||
"newUi": {
|
||||
"sidebar": {
|
||||
|
||||
@@ -1502,7 +1502,11 @@
|
||||
"sslIssuer": "Issued by {{issuer}}",
|
||||
"sslNames": "Covers {{names}}",
|
||||
"sslManualTitle": "Upload a certificate",
|
||||
"updateExternalAutoProvisionFailed": "Failed to update the auto-create setting"
|
||||
"updateExternalAutoProvisionFailed": "Failed to update the auto-create setting",
|
||||
"hostTags": "预定义主机标签",
|
||||
"hostTagsDesc": "每行一个标签,供所有用户使用。编辑此列表仅修改建议项,不会更改主机已有的标签。",
|
||||
"hostTagsSaved": "主机标签建议已保存。",
|
||||
"hostTagsError": "无法加载或保存主机标签建议。"
|
||||
},
|
||||
"newUi": {
|
||||
"sidebar": {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/button";
|
||||
import { getHostTags, saveHostTags } from "@/api/host-tags-api";
|
||||
|
||||
export function AdminHostTags() {
|
||||
const { t } = useTranslation();
|
||||
const [value, setValue] = useState("");
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
getHostTags()
|
||||
.then((tags) => {
|
||||
if (cancelled) return;
|
||||
setValue(tags.join("\n"));
|
||||
setLoaded(true);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setMessage(t("admin.hostTagsError"));
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [t]);
|
||||
|
||||
async function save() {
|
||||
setSaving(true);
|
||||
setMessage("");
|
||||
try {
|
||||
const tags = await saveHostTags(
|
||||
value
|
||||
.split("\n")
|
||||
.map((tag) => tag.trim())
|
||||
.filter(Boolean),
|
||||
);
|
||||
setValue(tags.join("\n"));
|
||||
setMessage(t("admin.hostTagsSaved"));
|
||||
window.dispatchEvent(new Event("termix:host-tags-changed"));
|
||||
} catch {
|
||||
setMessage(t("admin.hostTagsError"));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 border-t border-border py-3">
|
||||
<label htmlFor="global-host-tags" className="text-xs font-medium">
|
||||
{t("admin.hostTags")}
|
||||
</label>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
{t("admin.hostTagsDesc")}
|
||||
</p>
|
||||
<textarea
|
||||
id="global-host-tags"
|
||||
rows={5}
|
||||
disabled={!loaded || saving}
|
||||
value={value}
|
||||
onChange={(event) => setValue(event.target.value)}
|
||||
className="w-full border border-border bg-background p-2 text-xs"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
disabled={!loaded || saving}
|
||||
onClick={() => void save()}
|
||||
>
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
{message && (
|
||||
<p role="status" className="text-xs">
|
||||
{message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { Input } from "@/components/input";
|
||||
import { SettingRow } from "@/components/section-card";
|
||||
import { Database, Lock, RefreshCw, Server, Settings } from "lucide-react";
|
||||
import { AccordionSection, AdminToggle } from "./AdminSettingsShared";
|
||||
import { AdminHostTags } from "./AdminHostTags";
|
||||
import type { TlsStatus } from "@/api/tls-api";
|
||||
|
||||
type GeneralSettingsSectionProps = {
|
||||
@@ -68,6 +69,7 @@ export function AdminGeneralSettingsSection({
|
||||
onToggle={onToggle}
|
||||
>
|
||||
<div className="flex flex-col gap-0 pt-2">
|
||||
<AdminHostTags />
|
||||
<div className="flex flex-col gap-1.5 py-2">
|
||||
<span className="text-xs font-medium">
|
||||
{t("admin.notificationPrivateEndpoints")}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React from "react";
|
||||
import { getHostTags } from "@/api/host-tags-api";
|
||||
import type { ProxyNode } from "@/types/index";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/button";
|
||||
@@ -47,6 +48,39 @@ export function HostEditorGeneralTab({
|
||||
const { t } = useTranslation();
|
||||
const syncLinked = !!useSyncStatus()?.linked;
|
||||
const pluginProtocols = useHostProtocols();
|
||||
const [predefinedTags, setPredefinedTags] = React.useState<string[]>([]);
|
||||
React.useEffect(() => {
|
||||
let cancelled = false;
|
||||
const load = () => {
|
||||
void getHostTags()
|
||||
.then((tags) => {
|
||||
if (!cancelled) setPredefinedTags(tags);
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
load();
|
||||
window.addEventListener("termix:host-tags-changed", load);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.removeEventListener("termix:host-tags-changed", load);
|
||||
};
|
||||
}, []);
|
||||
const suggestedTags = [
|
||||
...new Set([
|
||||
...predefinedTags,
|
||||
...hosts.flatMap((item) => item.tags ?? []),
|
||||
]),
|
||||
].filter(
|
||||
(tag) =>
|
||||
!form.tags.includes(tag) &&
|
||||
tag
|
||||
.toLocaleLowerCase()
|
||||
.includes(form.tagInput.trim().toLocaleLowerCase()),
|
||||
);
|
||||
const addTag = (tag: string) => {
|
||||
if (!form.tags.includes(tag)) setField("tags", [...form.tags, tag]);
|
||||
setField("tagInput", "");
|
||||
};
|
||||
|
||||
// Tracks which picker is shown, independent of whether a value is set yet
|
||||
// -- switching to "parent host" mode with nothing picked shouldn't bounce
|
||||
@@ -283,14 +317,12 @@ export function HostEditorGeneralTab({
|
||||
onChange={(e) => setField("tagInput", e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (
|
||||
(e.key === " " || e.key === "Enter") &&
|
||||
e.key === "Enter" &&
|
||||
!e.nativeEvent.isComposing &&
|
||||
form.tagInput.trim()
|
||||
) {
|
||||
e.preventDefault();
|
||||
const tag = form.tagInput.trim();
|
||||
if (!form.tags.includes(tag))
|
||||
setField("tags", [...form.tags, tag]);
|
||||
setField("tagInput", "");
|
||||
addTag(form.tagInput.trim());
|
||||
} else if (
|
||||
e.key === "Backspace" &&
|
||||
!form.tagInput &&
|
||||
@@ -302,6 +334,24 @@ export function HostEditorGeneralTab({
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{suggestedTags.length > 0 && (
|
||||
<div
|
||||
className="col-span-2 flex flex-wrap gap-1 max-h-24 overflow-y-auto"
|
||||
aria-label={t("admin.hostTags")}
|
||||
>
|
||||
{suggestedTags.map((tag) => (
|
||||
<Button
|
||||
type="button"
|
||||
key={tag}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => addTag(tag)}
|
||||
>
|
||||
{tag}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col gap-1.5 col-span-2">
|
||||
<label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
|
||||
{t("hosts.privateNotes")}
|
||||
|
||||
Reference in new issue
Block a user