mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-02 19:42:51 +08:00
refactor: share admin contracts and isolate page styles
This commit is contained in:
1 parent
e2f0a43762
commit
f0712fa3fc
26 files changed
+2231
-1733
No files matched your search
@@ -0,0 +1,95 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { AdminApiError, createAdminApi } from "./admin-api.js";
|
||||
import { adminResponses } from "../../../src/shared/admin-responses.js";
|
||||
import { strToU8, zipSync } from "fflate";
|
||||
|
||||
const json = (value: unknown, status = 200) => new Response(JSON.stringify(value), { status });
|
||||
|
||||
test("admin mutations read the current CSRF token and encode resource IDs", async () => {
|
||||
let token = "first-test-token";
|
||||
const calls: Array<{ url: string; init: RequestInit }> = [];
|
||||
const api = createAdminApi({ csrfToken: () => token, fetch: async (url, init = {}) => {
|
||||
calls.push({ url: String(url), init });
|
||||
return json({ ok: true });
|
||||
} });
|
||||
await api.changePassword("test-password");
|
||||
token = "replacement-test-token";
|
||||
await api.revokeInvite("a/b ?");
|
||||
assert.equal(new Headers(calls[0].init.headers).get("x-csrf-token"), "first-test-token");
|
||||
assert.equal(new Headers(calls[1].init.headers).get("x-csrf-token"), token);
|
||||
assert.equal(calls[1].url, "/api/admin/invites/a%2Fb%20%3F/revoke");
|
||||
assert.equal(calls[0].init.body, JSON.stringify({ newPassword: "test-password" }));
|
||||
});
|
||||
|
||||
test("skin uploads preserve the binary body, validate the package and honor replacement cancellation", async () => {
|
||||
const skin = { schemaVersion: 1, id: "api-test-skin", name: "Test", version: "1.0.0", author: "Test", license: "MIT", minAppVersion: "0.2.4", entry: "skin.css" };
|
||||
const file = new File([zipSync({ "manifest.json": strToU8(JSON.stringify(skin)), "skin.css": strToU8('[data-ws-part="home"] { color: #123456; }') })], "test.wskin");
|
||||
let requests = 0;
|
||||
const api = createAdminApi({ csrfToken: () => "upload-test-token", fetch: async (url, init) => {
|
||||
requests++;
|
||||
assert.equal(url, "/api/admin/skins/api-test-skin");
|
||||
assert.equal(init?.body, file);
|
||||
assert.equal(new Headers(init.headers).get("content-type"), "application/octet-stream");
|
||||
assert.equal(new Headers(init.headers).get("x-csrf-token"), "upload-test-token");
|
||||
return json({ ok: true, skin: { ...skin, installedAt: 1 } });
|
||||
} });
|
||||
assert.equal(await api.uploadSkin(file, () => false), null);
|
||||
assert.equal(requests, 0);
|
||||
assert.equal((await api.uploadSkin(file))?.id, skin.id);
|
||||
assert.equal(requests, 1);
|
||||
await assert.rejects(api.uploadSkin(new File(["not a zip"], "broken.wskin")));
|
||||
assert.equal(requests, 1);
|
||||
});
|
||||
|
||||
test("backup downloads use the common expired-session path and retain binary data", async () => {
|
||||
let expired = 0;
|
||||
const api = createAdminApi({ csrfToken: () => "", onUnauthorized: () => expired++, fetch: async () => new Response("Expired", { status: 401 }) });
|
||||
await assert.rejects(api.backup(), error => error instanceof AdminApiError && error.status === 401);
|
||||
assert.equal(expired, 1);
|
||||
const binary = createAdminApi({ csrfToken: () => "", fetch: async (_url, init) => {
|
||||
assert.equal(new Headers(init?.headers).get("accept"), "application/octet-stream");
|
||||
return new Response(new Uint8Array([0, 1, 255]));
|
||||
} });
|
||||
assert.deepEqual(new Uint8Array(await (await binary.backup()).arrayBuffer()), new Uint8Array([0, 1, 255]));
|
||||
});
|
||||
|
||||
test("login errors retain their code without expiring an unrelated session or sending CSRF", async () => {
|
||||
let expired = 0;
|
||||
const api = createAdminApi({ csrfToken: () => "private-test-token", onUnauthorized: () => expired++, fetch: async (_url, init) => {
|
||||
assert.equal(new Headers(init?.headers).has("x-csrf-token"), false);
|
||||
return json({ code: "INVALID_PASSWORD" }, 401);
|
||||
} });
|
||||
await assert.rejects(api.login("admin", "incorrect"), error => error instanceof AdminApiError && error.code === "INVALID_PASSWORD" && error.status === 401);
|
||||
assert.equal(expired, 0);
|
||||
});
|
||||
|
||||
test("expired sessions notify the page even when the error response is not JSON", async () => {
|
||||
let expired = 0;
|
||||
const api = createAdminApi({ csrfToken: () => "", onUnauthorized: () => expired++, fetch: async () => new Response("Proxy authentication required", { status: 401 }) });
|
||||
await assert.rejects(api.overview(), error => error instanceof AdminApiError && error.status === 401);
|
||||
assert.equal(expired, 1);
|
||||
});
|
||||
|
||||
test("successful HTTP status cannot turn an incomplete settings or login response into success", async () => {
|
||||
for (const value of [{}, null, [], { ok: true }, { ok: true, settings: { target: "voice.example:9987" } }]) {
|
||||
const api = createAdminApi({ csrfToken: () => "", fetch: async () => json(value) });
|
||||
await assert.rejects(api.settings(), error => error instanceof AdminApiError && error.code === "INVALID_ADMIN_RESPONSE");
|
||||
await assert.rejects(api.login("admin", "test"), error => error instanceof AdminApiError && error.code === "INVALID_ADMIN_RESPONSE");
|
||||
}
|
||||
assert.throws(() => adminResponses.session({ authenticated: true, mustChangePassword: false }), /INVALID_ADMIN_RESPONSE/);
|
||||
assert.deepEqual(adminResponses.session({ authenticated: false }), { authenticated: false, mustChangePassword: undefined, csrfToken: undefined });
|
||||
});
|
||||
|
||||
test("nested malformed list entries are rejected before replacing the current page snapshot", async () => {
|
||||
const api = createAdminApi({ csrfToken: () => "", fetch: async () => json({ sessions: [{ id: "incomplete" }] }) });
|
||||
await assert.rejects(api.sessions(), error => error instanceof AdminApiError && error.code === "INVALID_ADMIN_RESPONSE");
|
||||
assert.throws(() => adminResponses.logs({ available: true, sessions: [], entries: [{ timestamp: null, level: "INFO", message: "test", context: { nested: {} } }] }), /INVALID_ADMIN_RESPONSE/);
|
||||
});
|
||||
|
||||
test("HTTP failures and network failures are normalized without exposing arbitrary response text", async () => {
|
||||
const failed = createAdminApi({ csrfToken: () => "", fetch: async () => json({ code: "WEBRTC_PORT_LOCKED" }, 409) });
|
||||
await assert.rejects(failed.dismissLegacyNotice(), error => error instanceof AdminApiError && error.code === "WEBRTC_PORT_LOCKED");
|
||||
const offline = createAdminApi({ csrfToken: () => "", fetch: async () => { throw new Error("private network details"); } });
|
||||
await assert.rejects(offline.overview(), error => error instanceof AdminApiError && error.message === "REQUEST_FAILED");
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { adminResponses, type AdminResponseReader } from "../../../src/shared/admin-responses.js";
|
||||
import type { AdminSettingsInput, ManagedInviteInput } from "../../../src/shared/admin-inputs.js";
|
||||
|
||||
export class AdminApiError extends Error {
|
||||
constructor(readonly code: string, readonly status = 0, message = code) {
|
||||
super(message);
|
||||
this.name = "AdminApiError";
|
||||
}
|
||||
}
|
||||
|
||||
interface AdminApiOptions {
|
||||
csrfToken(): string;
|
||||
onUnauthorized?(): void;
|
||||
fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
export function createAdminApi(options: AdminApiOptions) {
|
||||
const fetcher = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
|
||||
async function transport(path: string, init: RequestInit = {}, authenticated = true): Promise<Response> {
|
||||
const headers = new Headers(init.headers);
|
||||
if (!headers.has("accept")) headers.set("accept", "application/json");
|
||||
if (init.method && init.method !== "GET") {
|
||||
const token = authenticated ? options.csrfToken() : "";
|
||||
if (token) headers.set("x-csrf-token", token);
|
||||
}
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetcher(`/api/admin${path}`, { ...init, headers });
|
||||
} catch {
|
||||
throw new AdminApiError("REQUEST_FAILED");
|
||||
}
|
||||
// Notify even if a proxy returned HTML instead of a JSON error body.
|
||||
if (response.status === 401 && authenticated) options.onUnauthorized?.();
|
||||
if (!response.ok) {
|
||||
const value: unknown = await response.json().catch(() => undefined);
|
||||
const code = value && typeof value === "object" && "code" in value && typeof value.code === "string" && value.code
|
||||
? value.code : "REQUEST_FAILED";
|
||||
const message = value && typeof value === "object" && "message" in value && typeof value.message === "string" ? value.message : code;
|
||||
throw new AdminApiError(code, response.status, message);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
async function decode<T>(response: Response, read: AdminResponseReader<T>): Promise<T> {
|
||||
const value: unknown = await response.json().catch(() => undefined);
|
||||
try { return read(value); }
|
||||
catch { throw new AdminApiError("INVALID_ADMIN_RESPONSE", response.status); }
|
||||
}
|
||||
async function request<T>(path: string, read: AdminResponseReader<T>, method = "GET", body?: unknown, authenticated = true): Promise<T> {
|
||||
const response = await transport(path, {
|
||||
method, ...(body === undefined ? {} : { body: JSON.stringify(body), headers: { "content-type": "application/json" } }),
|
||||
}, authenticated);
|
||||
return decode(response, read);
|
||||
}
|
||||
|
||||
return {
|
||||
session: () => request("/session", adminResponses.session),
|
||||
login: (username: string, password: string) => request("/login", adminResponses.login, "POST", { username, password }, false),
|
||||
changePassword: (newPassword: string) => request("/change-password", adminResponses.ok, "POST", { newPassword }),
|
||||
logout: () => request("/logout", adminResponses.ok, "POST", {}),
|
||||
overview: () => request("/overview", adminResponses.overview),
|
||||
settings: () => request("/server", adminResponses.settings),
|
||||
saveSettings: (body: AdminSettingsInput) => request("/server", adminResponses.savedSettings, "PUT", body),
|
||||
probe: (body: Pick<AdminSettingsInput, "target" | "serverPassword" | "passwordAction">) => request("/server/test", adminResponses.probe, "POST", body),
|
||||
sessions: () => request("/sessions", adminResponses.sessions),
|
||||
terminateSession: (id: string) => request(`/sessions/${encodeURIComponent(id)}/terminate`, adminResponses.ok, "POST", {}),
|
||||
invites: () => request("/invites", adminResponses.invites),
|
||||
createInvite: (body: ManagedInviteInput) => request("/invites", adminResponses.createdInvite, "POST", body),
|
||||
revokeInvite: (id: string) => request(`/invites/${encodeURIComponent(id)}/revoke`, adminResponses.ok, "POST", {}),
|
||||
diagnostics: () => request("/diagnostics", adminResponses.diagnostics),
|
||||
logs: () => request("/logs?limit=100", adminResponses.logs),
|
||||
audit: () => request("/audit?limit=50", adminResponses.audit),
|
||||
skins: () => request("/skins", adminResponses.skins),
|
||||
setDefaultSkin: (id: string) => request("/skins/default", adminResponses.defaultSkin, "PUT", { id }),
|
||||
setSkinEnabled: (id: string, enabled: boolean) => request(`/skins/${encodeURIComponent(id)}/enabled`, adminResponses.updatedSkin, "PUT", { enabled }),
|
||||
deleteSkin: (id: string) => request(`/skins/${encodeURIComponent(id)}`, adminResponses.ok, "DELETE", {}),
|
||||
async uploadSkin(file: File, confirmReplace?: (id: string) => boolean) {
|
||||
const { importSkinPack } = await import("./skin-pack.js");
|
||||
const skin = await importSkinPack(file);
|
||||
if (confirmReplace && !confirmReplace(skin.id)) return null;
|
||||
const response = await transport(`/skins/${encodeURIComponent(skin.id)}`, {
|
||||
method: "PUT", headers: { "content-type": "application/octet-stream" }, body: file,
|
||||
});
|
||||
return (await decode(response, adminResponses.uploadedSkin)).skin;
|
||||
},
|
||||
async backup() { return (await transport("/backup", { headers: { accept: "application/octet-stream" } })).blob(); },
|
||||
dismissLegacyNotice: () => request("/legacy-import/dismiss", adminResponses.ok, "POST", {}),
|
||||
};
|
||||
}
|
||||
@@ -104,29 +104,3 @@ export async function listPublicSkins(): Promise<SkinCatalogEntry[]> {
|
||||
return BUILTIN_SKIN_CATALOG;
|
||||
}
|
||||
}
|
||||
|
||||
export async function uploadSkinPackage(file: File, csrfToken: string, confirmReplace?: (id: string) => boolean): Promise<SkinCatalogEntry | null> {
|
||||
const { importSkinPack } = await import("./skin-pack.js");
|
||||
const skin = await importSkinPack(file);
|
||||
if (confirmReplace && !confirmReplace(skin.id)) return null;
|
||||
const response = await fetch(`/api/admin/skins/${encodeURIComponent(skin.id)}`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/octet-stream", "x-csrf-token": csrfToken, accept: "application/json" },
|
||||
body: file,
|
||||
});
|
||||
const payload = await response.json().catch(() => null) as { skin?: SkinCatalogEntry; message?: string; code?: string } | null;
|
||||
if (!response.ok || !payload?.skin) throw new Error(payload?.message || payload?.code || `HTTP_${response.status}`);
|
||||
return payload.skin;
|
||||
}
|
||||
|
||||
export async function deleteSkinPackage(id: string, csrfToken: string): Promise<void> {
|
||||
const response = await fetch(`/api/admin/skins/${encodeURIComponent(id)}`, {
|
||||
method: "DELETE",
|
||||
headers: { "content-type": "application/json", "x-csrf-token": csrfToken, accept: "application/json" },
|
||||
body: "{}",
|
||||
});
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null) as { code?: string } | null;
|
||||
throw new Error(payload?.code || `HTTP_${response.status}`);
|
||||
}
|
||||
}
|
||||
@@ -78,15 +78,16 @@ test("community skins use a scoped light fallback instead of inheriting the nigh
|
||||
});
|
||||
|
||||
test("all public skin parts are documented and the admin console is outside skin scope", async () => {
|
||||
const [webClient, demo, skinSwitcher, languageSwitcher, admin, documentation] = await Promise.all([
|
||||
const [webClient, header, demo, skinSwitcher, languageSwitcher, admin, documentation] = await Promise.all([
|
||||
readFile(new URL("../views/WebClient.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../components/web-client/WebClientHeader.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../views/DemoView.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../components/SkinSwitcher.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../components/LanguageSwitcher.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../views/AdminView.vue", import.meta.url), "utf8"),
|
||||
readFile(new URL("../../../docs/SKIN_DEVELOPMENT.md", import.meta.url), "utf8"),
|
||||
]);
|
||||
const publicParts = new Set([...`${webClient}\n${demo}\n${skinSwitcher}\n${languageSwitcher}`.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1]));
|
||||
const publicParts = new Set([...`${webClient}\n${header}\n${demo}\n${skinSwitcher}\n${languageSwitcher}`.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1]));
|
||||
for (const part of publicParts) assert.ok(documentation.includes(`\`${part}\``), `Undocumented skin part: ${part}`);
|
||||
assert.match(skinSwitcher, /data-ws-skin-id/);
|
||||
assert.match(skinSwitcher, /data-ws-state/);
|
||||
|
||||
Reference in new issue
Block a user