mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-29 14:45:24 +00:00
v26.10.3 (#1692)
* feat: shell controller, TabStage, layout and theme plugins with repair view * feat: move the classic layout into its own bundled plugin * feat: move color themes into a bundled themes plugin * fix: plugin tests and type checks work with a linked sdk * fix: home tab, layout switch and missing layout fallbacks for looks * chore: add classic layout and themes to the readme * chore: drop example plugin links from the plugin guide * feat: plugin filters by type, paged browse, hide plugins needing newer termix * feat: move desktop, status, import, audit and branding features into plugins * feat: host lock api so a plugin can load hosts from a config file (#1581) * chore: add hosts config to the plugin table * feat: login policy hook for plugins and optional https redirect (#1584) * chore: add login security to the plugin table * feat: api key socket tickets so a master can open remote sessions (#1654) * feat: sync moves to a plugin, desktop gets multiple accounts (#1580, #1654) * chore: add sync to the plugin table * feat: move the sync screens and wizard out of core into the plugin (#1580) * fix: add a neutral linked desktop hook for plugins (#1580) * fix: show the linked account's name and admin flag in the app (#1580) * feat: ssh transport providers, core ssh relay and plugin folders api * feat: support FIDO2 security keys through ssh agent * feat: add companion panels beside host tabs * feat: mTLS client certificates for desktop server links * feat: native web view for plugins in the desktop app * fix: detect the desktop link window by Electron's default user agent Fixes #1675 * fix: changelog for desktop link fix * fix: keep text primary keys in the plugin data export * fix: ship sharp binaries for Windows arm64 builds * feat: client cert on the sync link types (sdk 1.0.18) * chore: update translations * feat: themed title bar for the desktop app (#1690) * chore: changelog for the themed title bar * fix: draw the title bar in the sidebar color * feat: per host layout for the terminal panel bar * chore: sdk 1.0.19 for the panel bar layout * chore: bundle all 43 plugins for 26.10.3 * chore: update translations --------- Co-authored-by: SirHephaistos <60616553+SirHephaistos@users.noreply.github.com> Co-authored-by: Giovanny Aranda <garanda21@gmail.com>
This commit is contained in:
577 files changed
+76479
-101831
No files matched your search
@@ -1,5 +1,4 @@
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import sharp from "sharp";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import express, {
|
||||
type NextFunction,
|
||||
type Request,
|
||||
@@ -19,15 +18,6 @@ vi.mock("../../../utils/logger.js", () => ({
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentSettingsRepository: () => ({
|
||||
get: async (key: string) => state.settings[key] ?? null,
|
||||
set: async (key: string, value: string) => {
|
||||
state.settings[key] = value;
|
||||
},
|
||||
setMany: async (writes: Array<{ key: string; value: string }>) => {
|
||||
for (const write of writes) state.settings[write.key] = write.value;
|
||||
},
|
||||
delete: async (key: string) => {
|
||||
delete state.settings[key];
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
@@ -42,25 +32,17 @@ interface RouteLayer {
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs a route's full middleware chain (e.g. requireAdmin, then the handler). */
|
||||
function handlersFor(
|
||||
router: express.Router,
|
||||
pathName: string,
|
||||
method: string,
|
||||
): RequestHandler[] {
|
||||
const layer = (router as unknown as { stack: RouteLayer[] }).stack.find(
|
||||
(candidate) =>
|
||||
candidate.route?.path === pathName && candidate.route.methods[method],
|
||||
);
|
||||
if (!layer) throw new Error(`Route not registered: ${method} ${pathName}`);
|
||||
return layer.route!.stack.map((entry) => entry.handle);
|
||||
function routesOf(router: express.Router) {
|
||||
return (router as unknown as { stack: RouteLayer[] }).stack
|
||||
.filter((layer) => layer.route)
|
||||
.map((layer) => ({
|
||||
path: layer.route!.path,
|
||||
methods: Object.keys(layer.route!.methods),
|
||||
handlers: layer.route!.stack.map((entry) => entry.handle),
|
||||
}));
|
||||
}
|
||||
|
||||
async function invokeChain(
|
||||
handlers: RequestHandler[],
|
||||
body: unknown = {},
|
||||
): Promise<{ statusCode: number; body: unknown }> {
|
||||
const req = { body, headers: {} } as unknown as Request;
|
||||
async function call(handler: RequestHandler) {
|
||||
const result = { statusCode: 200, body: null as unknown };
|
||||
const res = {
|
||||
status(code: number) {
|
||||
@@ -72,67 +54,34 @@ async function invokeChain(
|
||||
return this;
|
||||
},
|
||||
} as unknown as Response;
|
||||
|
||||
for (const handler of handlers) {
|
||||
let proceeded = false;
|
||||
await handler(req, res, ((err?: unknown) => {
|
||||
if (err) throw err;
|
||||
proceeded = true;
|
||||
}) as NextFunction);
|
||||
if (!proceeded) return result;
|
||||
}
|
||||
await handler(
|
||||
{ body: {}, headers: {} } as Request,
|
||||
res,
|
||||
(() => {}) as NextFunction,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Mimics the real requireAdmin: 401 with no session, 403 for a non-admin. */
|
||||
function fakeRequireAdmin(
|
||||
outcome: "unauthenticated" | "not-admin" | "admin",
|
||||
): RequestHandler {
|
||||
return (_req, res, next) => {
|
||||
if (outcome === "unauthenticated") {
|
||||
res.status(401).json({ error: "Missing authentication token" });
|
||||
return;
|
||||
}
|
||||
if (outcome === "not-admin") {
|
||||
res.status(403).json({ error: "Not authorized" });
|
||||
return;
|
||||
}
|
||||
// Must return (not just call) next() so invokeChain's await actually
|
||||
// waits for the downstream async handler to finish before returning.
|
||||
return next();
|
||||
};
|
||||
}
|
||||
|
||||
function buildRouter(requireAdmin: RequestHandler) {
|
||||
const router = express.Router();
|
||||
registerBrandingRoutes(router, requireAdmin);
|
||||
return router;
|
||||
}
|
||||
|
||||
let pngDataUrl: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
const buffer = await sharp({
|
||||
create: { width: 4, height: 4, channels: 3, background: "#112233" },
|
||||
})
|
||||
.png()
|
||||
.toBuffer();
|
||||
pngDataUrl = `data:image/png;base64,${buffer.toString("base64")}`;
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
state.settings = {};
|
||||
});
|
||||
|
||||
describe("GET /users/branding", () => {
|
||||
it("succeeds with no auth at all, since the route registers no auth handler", async () => {
|
||||
// requireAdmin is only ever wired onto PATCH below; GET's own handler chain
|
||||
// has exactly one entry, proving the public route never runs an admin gate.
|
||||
const router = buildRouter(fakeRequireAdmin("unauthenticated"));
|
||||
const handlers = handlersFor(router, "/branding", "get");
|
||||
expect(handlers).toHaveLength(1);
|
||||
it("is the only branding route and has no auth handler", () => {
|
||||
const router = express.Router();
|
||||
registerBrandingRoutes(router);
|
||||
const routes = routesOf(router);
|
||||
|
||||
const response = await invokeChain(handlers);
|
||||
expect(routes).toHaveLength(1);
|
||||
expect(routes[0].path).toBe("/branding");
|
||||
expect(routes[0].methods).toEqual(["get"]);
|
||||
expect(routes[0].handlers).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("answers defaults when nothing is set", async () => {
|
||||
const router = express.Router();
|
||||
registerBrandingRoutes(router);
|
||||
const response = await call(routesOf(router)[0].handlers[0]);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
@@ -142,126 +91,19 @@ describe("GET /users/branding", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reflects persisted branding values", async () => {
|
||||
state.settings.branding_app_name = "Acme Ops";
|
||||
state.settings.branding_tagline = "Ship it";
|
||||
state.settings.branding_logo = pngDataUrl;
|
||||
const router = buildRouter(fakeRequireAdmin("admin"));
|
||||
it("keeps serving the stored branding of an older install", async () => {
|
||||
state.settings = {
|
||||
branding_app_name: "Acme",
|
||||
branding_tagline: "Ops",
|
||||
};
|
||||
const router = express.Router();
|
||||
registerBrandingRoutes(router);
|
||||
const response = await call(routesOf(router)[0].handlers[0]);
|
||||
|
||||
const response = await invokeChain(handlersFor(router, "/branding", "get"));
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
appName: "Acme Ops",
|
||||
tagline: "Ship it",
|
||||
logo: pngDataUrl,
|
||||
appName: "Acme",
|
||||
tagline: "Ops",
|
||||
logo: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("PATCH /users/branding", () => {
|
||||
it("rejects an unauthenticated request and persists nothing", async () => {
|
||||
const router = buildRouter(fakeRequireAdmin("unauthenticated"));
|
||||
|
||||
const response = await invokeChain(
|
||||
handlersFor(router, "/branding", "patch"),
|
||||
{ appName: "Hijacked" },
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(401);
|
||||
expect(state.settings).toEqual({});
|
||||
});
|
||||
|
||||
it("rejects a non-admin request and persists nothing", async () => {
|
||||
const router = buildRouter(fakeRequireAdmin("not-admin"));
|
||||
|
||||
const response = await invokeChain(
|
||||
handlersFor(router, "/branding", "patch"),
|
||||
{ appName: "Hijacked" },
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
expect(state.settings).toEqual({});
|
||||
});
|
||||
|
||||
it("persists only the allowed fields for an admin request", async () => {
|
||||
const router = buildRouter(fakeRequireAdmin("admin"));
|
||||
|
||||
const response = await invokeChain(
|
||||
handlersFor(router, "/branding", "patch"),
|
||||
{ appName: "Acme Ops", tagline: "Ship it", logo: pngDataUrl },
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(state.settings.branding_app_name).toBe("Acme Ops");
|
||||
expect(state.settings.branding_tagline).toBe("Ship it");
|
||||
expect(state.settings.branding_logo).toMatch(/^data:image\/png;base64,/);
|
||||
expect(response.body).toMatchObject({
|
||||
appName: "Acme Ops",
|
||||
tagline: "Ship it",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects unknown fields without writing anything", async () => {
|
||||
const router = buildRouter(fakeRequireAdmin("admin"));
|
||||
|
||||
const response = await invokeChain(
|
||||
handlersFor(router, "/branding", "patch"),
|
||||
{ theme: "dark" },
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.body).toMatchObject({
|
||||
code: "BRANDING_SETTINGS_UNKNOWN_FIELD",
|
||||
});
|
||||
expect(state.settings).toEqual({});
|
||||
});
|
||||
|
||||
it("rejects an app name over the length limit", async () => {
|
||||
const router = buildRouter(fakeRequireAdmin("admin"));
|
||||
|
||||
const response = await invokeChain(
|
||||
handlersFor(router, "/branding", "patch"),
|
||||
{ appName: "x".repeat(61) },
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.body).toMatchObject({
|
||||
code: "BRANDING_SETTINGS_INVALID",
|
||||
field: "appName",
|
||||
});
|
||||
expect(state.settings).toEqual({});
|
||||
});
|
||||
|
||||
it("rejects malformed/non-raster logo data without persisting it", async () => {
|
||||
const router = buildRouter(fakeRequireAdmin("admin"));
|
||||
|
||||
const response = await invokeChain(
|
||||
handlersFor(router, "/branding", "patch"),
|
||||
{
|
||||
logo: `data:image/png;base64,${Buffer.from("not an image").toString("base64")}`,
|
||||
},
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.body).toMatchObject({
|
||||
code: "BRANDING_SETTINGS_INVALID",
|
||||
field: "logo",
|
||||
});
|
||||
expect(state.settings).toEqual({});
|
||||
});
|
||||
|
||||
it("clears the logo when patched with null", async () => {
|
||||
state.settings.branding_logo = pngDataUrl;
|
||||
const router = buildRouter(fakeRequireAdmin("admin"));
|
||||
|
||||
const response = await invokeChain(
|
||||
handlersFor(router, "/branding", "patch"),
|
||||
{ logo: null },
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(state.settings.branding_logo).toBeUndefined();
|
||||
expect(response.body).toMatchObject({ logo: null });
|
||||
});
|
||||
});
|
||||
@@ -1,149 +1,17 @@
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import sharp from "sharp";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
authLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
|
||||
databaseLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
|
||||
}));
|
||||
|
||||
const {
|
||||
BRANDING_DEFAULT_APP_NAME,
|
||||
BRANDING_LOGO_MAX_BYTES,
|
||||
parseBrandingAppName,
|
||||
parseBrandingLogoDataUrl,
|
||||
parseBrandingTagline,
|
||||
resolveBrandingSettings,
|
||||
} = await import("../../../database/routes/branding-settings.js");
|
||||
const { BRANDING_DEFAULT_APP_NAME, resolveBrandingSettings } =
|
||||
await import("../../../database/routes/branding-settings.js");
|
||||
|
||||
function settingSource(values: Record<string, string>) {
|
||||
return { get: async (key: string) => values[key] ?? null };
|
||||
}
|
||||
|
||||
async function toDataUrl(
|
||||
buffer: Buffer,
|
||||
mime: "image/png" | "image/jpeg" | "image/webp",
|
||||
): Promise<string> {
|
||||
return `data:${mime};base64,${buffer.toString("base64")}`;
|
||||
}
|
||||
|
||||
let pngBuffer: Buffer;
|
||||
let jpegBuffer: Buffer;
|
||||
let webpBuffer: Buffer;
|
||||
let oversizedPngBuffer: Buffer;
|
||||
|
||||
beforeAll(async () => {
|
||||
const image = sharp({
|
||||
create: { width: 4, height: 4, channels: 3, background: "#336699" },
|
||||
});
|
||||
pngBuffer = await image.clone().png().toBuffer();
|
||||
jpegBuffer = await image.clone().jpeg().toBuffer();
|
||||
webpBuffer = await image.clone().webp().toBuffer();
|
||||
oversizedPngBuffer = await sharp({
|
||||
create: { width: 1200, height: 1200, channels: 4, background: "#abcdef" },
|
||||
})
|
||||
.png({ compressionLevel: 0 })
|
||||
.toBuffer();
|
||||
});
|
||||
|
||||
describe("parseBrandingAppName", () => {
|
||||
it("trims and accepts a normal name", () => {
|
||||
expect(parseBrandingAppName(" My Company ")).toBe("My Company");
|
||||
});
|
||||
|
||||
it("falls back to the default when cleared", () => {
|
||||
expect(parseBrandingAppName("")).toBe(BRANDING_DEFAULT_APP_NAME);
|
||||
expect(parseBrandingAppName(" ")).toBe(BRANDING_DEFAULT_APP_NAME);
|
||||
});
|
||||
|
||||
it("rejects names over 60 characters", () => {
|
||||
expect(parseBrandingAppName("x".repeat(61))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects non-string values", () => {
|
||||
expect(parseBrandingAppName(42)).toBeNull();
|
||||
expect(parseBrandingAppName(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseBrandingTagline", () => {
|
||||
it("trims and accepts a normal tagline", () => {
|
||||
expect(parseBrandingTagline(" Ship faster ")).toBe("Ship faster");
|
||||
});
|
||||
|
||||
it("accepts an empty tagline (means: use the default)", () => {
|
||||
expect(parseBrandingTagline("")).toBe("");
|
||||
expect(parseBrandingTagline(" ")).toBe("");
|
||||
});
|
||||
|
||||
it("rejects taglines over 160 characters", () => {
|
||||
expect(parseBrandingTagline("x".repeat(161))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects non-string values", () => {
|
||||
expect(parseBrandingTagline(42)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseBrandingLogoDataUrl", () => {
|
||||
it("accepts a PNG data URL and re-encodes it to PNG", async () => {
|
||||
const result = await parseBrandingLogoDataUrl(
|
||||
await toDataUrl(pngBuffer, "image/png"),
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startsWith("data:image/png;base64,")).toBe(true);
|
||||
const decoded = Buffer.from(result!.split(",")[1]!, "base64");
|
||||
expect(decoded.subarray(1, 4).toString()).toBe("PNG");
|
||||
});
|
||||
|
||||
it("accepts a JPEG data URL and normalizes it to PNG", async () => {
|
||||
const result = await parseBrandingLogoDataUrl(
|
||||
await toDataUrl(jpegBuffer, "image/jpeg"),
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startsWith("data:image/png;base64,")).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a WEBP data URL and normalizes it to PNG", async () => {
|
||||
const result = await parseBrandingLogoDataUrl(
|
||||
await toDataUrl(webpBuffer, "image/webp"),
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startsWith("data:image/png;base64,")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a non-image/SVG mime prefix outright", async () => {
|
||||
const svg = Buffer.from('<svg onload="alert(1)"></svg>', "utf8").toString(
|
||||
"base64",
|
||||
);
|
||||
const result = await parseBrandingLogoDataUrl(
|
||||
`data:image/svg+xml;base64,${svg}`,
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects a value that isn't a data URL at all", async () => {
|
||||
expect(await parseBrandingLogoDataUrl("not-a-data-url")).toBeNull();
|
||||
expect(await parseBrandingLogoDataUrl(undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects a spoofed data URL whose bytes aren't a real image", async () => {
|
||||
const fake = Buffer.from("definitely not an image").toString("base64");
|
||||
const result = await parseBrandingLogoDataUrl(
|
||||
`data:image/png;base64,${fake}`,
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects an image that normalizes over the size cap", async () => {
|
||||
// Sanity check the fixture is actually large enough to exceed the cap.
|
||||
expect(oversizedPngBuffer.length).toBeGreaterThan(BRANDING_LOGO_MAX_BYTES);
|
||||
const result = await parseBrandingLogoDataUrl(
|
||||
await toDataUrl(oversizedPngBuffer, "image/png"),
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBrandingSettings", () => {
|
||||
it("returns built-in defaults when nothing is persisted", async () => {
|
||||
const settings = await resolveBrandingSettings(settingSource({}));
|
||||
@@ -169,3 +37,34 @@ describe("resolveBrandingSettings", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("branding provider", () => {
|
||||
it("uses a plugin's branding provider and falls back when it throws", async () => {
|
||||
const registry = await import("../../../plugins/registry.js");
|
||||
const provider = async () => ({
|
||||
appName: " Acme ",
|
||||
tagline: "Hello",
|
||||
logo: "data:image/png;base64,AAAA",
|
||||
});
|
||||
registry.provide("demo.brandingProvider", provider);
|
||||
try {
|
||||
await expect(resolveBrandingSettings(settingSource({}))).resolves.toEqual(
|
||||
{
|
||||
appName: "Acme",
|
||||
tagline: "Hello",
|
||||
logo: "data:image/png;base64,AAAA",
|
||||
},
|
||||
);
|
||||
|
||||
registry.revoke("demo.brandingProvider");
|
||||
registry.provide("demo.brandingProvider", async () => {
|
||||
throw new Error("broken");
|
||||
});
|
||||
await expect(
|
||||
resolveBrandingSettings(settingSource({ branding_app_name: "Stored" })),
|
||||
).resolves.toMatchObject({ appName: "Stored" });
|
||||
} finally {
|
||||
registry.clearRegistry();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -52,12 +52,6 @@ vi.mock("../../../utils/logger.js", () => {
|
||||
};
|
||||
return { authLogger: log, sshLogger: log, databaseLogger: log };
|
||||
});
|
||||
vi.mock("../../../database/routes/credential-key-routes.js", () => ({
|
||||
registerCredentialKeyRoutes: () => {},
|
||||
}));
|
||||
vi.mock("../../../database/routes/credential-deploy-routes.js", () => ({
|
||||
registerCredentialDeployRoutes: () => {},
|
||||
}));
|
||||
vi.mock("../../../database/routes/credential-bulk-routes.js", () => ({
|
||||
registerCredentialBulkRoutes: () => {},
|
||||
}));
|
||||
|
||||
@@ -34,15 +34,12 @@ vi.mock("../../../utils/data-crypto.js", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentRecentActivityRepository: () => ({
|
||||
listByUserId: async () => state.activity,
|
||||
vi.mock("../../../plugins/activity-provider.js", () => ({
|
||||
recentActivity: {
|
||||
list: async () => state.activity,
|
||||
deleteByUserId: async () => {},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../../services/recent-activity.js", () => ({
|
||||
recordRecentActivity: async () => state.recordResult,
|
||||
record: async () => state.recordResult,
|
||||
},
|
||||
}));
|
||||
|
||||
const { default: dashboardRoutes } =
|
||||
|
||||
@@ -136,6 +136,22 @@ describe("isNativeTokenExportRequest", () => {
|
||||
});
|
||||
|
||||
describe("resolveDesktopAutoSessionUser", () => {
|
||||
it("returns the account the user switched to, while it exists", () => {
|
||||
const admin = makeUser({ id: "admin", isAdmin: true });
|
||||
const chosen = makeUser({ id: "chosen" });
|
||||
expect(resolveDesktopAutoSessionUser([admin, chosen], "chosen")).toBe(
|
||||
chosen,
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the usual pick when the chosen account is gone", () => {
|
||||
const admin = makeUser({ id: "admin", isAdmin: true });
|
||||
const other = makeUser({ id: "other" });
|
||||
expect(resolveDesktopAutoSessionUser([admin, other], "deleted")).toBe(
|
||||
admin,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns the sole local user regardless of having a real password", () => {
|
||||
const user = makeUser({ passwordHash: "$2a$10$realbcryptvaluehere" });
|
||||
expect(resolveDesktopAutoSessionUser([user])).toBe(user);
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
importedHostUsername,
|
||||
notifyImportedHosts,
|
||||
parseSSHConfig,
|
||||
} from "../../../database/routes/host-bulk-routes.js";
|
||||
} from "../../../hosts/import/host-import.js";
|
||||
import { pluginEvents, TOPICS } from "../../../plugins/events.js";
|
||||
|
||||
describe("parseSSHConfig", () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import type { Router, RequestHandler, Request, Response } from "express";
|
||||
import type { RequestHandler, Request, Response } from "express";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
create: vi.fn(),
|
||||
@@ -35,23 +35,35 @@ vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
findHostsByUserId: mocks.list,
|
||||
}),
|
||||
}));
|
||||
import { registerHostBulkRoutes } from "../../../database/routes/host-bulk-routes.js";
|
||||
import { buildExportPayload } from "../../../../ui/sidebar/host-export-payload";
|
||||
import {
|
||||
ImportError,
|
||||
importResponse,
|
||||
runBulkImport,
|
||||
runSshConfigImport,
|
||||
} from "../../../hosts/import/host-import.js";
|
||||
import { pluginEvents, TOPICS } from "../../../plugins/events.js";
|
||||
|
||||
let handler: RequestHandler;
|
||||
let sshConfigHandler: RequestHandler;
|
||||
const router = {
|
||||
post: (path: string, ...handlers: RequestHandler[]) => {
|
||||
if (path === "/bulk-import") handler = handlers.at(-1)!;
|
||||
if (path === "/ssh-config-import") sshConfigHandler = handlers.at(-1)!;
|
||||
},
|
||||
put: () => {},
|
||||
patch: () => {},
|
||||
delete: () => {},
|
||||
} as unknown as Router;
|
||||
const pass: RequestHandler = (_req, _res, next) => next();
|
||||
registerHostBulkRoutes(router, pass, pass, pass, pass);
|
||||
// The same wrapping the plugin's routes give the shared import code.
|
||||
const wrap =
|
||||
(run: typeof runBulkImport): RequestHandler =>
|
||||
async (req, res) => {
|
||||
try {
|
||||
const body = (req as unknown as { body: never }).body;
|
||||
res.json(
|
||||
importResponse(
|
||||
await run((req as unknown as { userId: string }).userId, body),
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof ImportError) {
|
||||
res.status(400).json({ error: error.message });
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
const handler = wrap(runBulkImport);
|
||||
const sshConfigHandler = wrap(runSshConfigImport as typeof runBulkImport);
|
||||
const host = {
|
||||
ip: "192.0.2.1",
|
||||
port: 22,
|
||||
@@ -76,12 +88,7 @@ it.each([false, true])(
|
||||
"carries plugin host settings through export selection and import (overwrite=%s)",
|
||||
async (overwrite) => {
|
||||
if (overwrite) mocks.list.mockResolvedValue([{ ...host, id: 19 }]);
|
||||
const payload = buildExportPayload(
|
||||
{ hosts: [host] },
|
||||
null,
|
||||
new Set(["featureFlags", "advanced"]),
|
||||
false,
|
||||
);
|
||||
const payload = { hosts: [host] };
|
||||
expect(payload.hosts[0]).toMatchObject(host);
|
||||
const json = vi.fn();
|
||||
await handler(
|
||||
@@ -130,12 +137,7 @@ it.each([20, "20"])(
|
||||
{ ...host, ip: "192.0.2.2", exportId: 20 },
|
||||
],
|
||||
};
|
||||
const payload = buildExportPayload(
|
||||
raw,
|
||||
null,
|
||||
new Set(["jumpHosts"]),
|
||||
false,
|
||||
);
|
||||
const payload = raw;
|
||||
const res = await importHosts(payload.hosts);
|
||||
expect(res.json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ success: 2, failed: 0 }),
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import express, { type RequestHandler } from "express";
|
||||
import request from "supertest";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
updates: [] as Array<{ ids: number[]; update: Record<string, unknown> }>,
|
||||
renamed: 0,
|
||||
folderHosts: [] as Array<{ id: number }>,
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
databaseLogger: { error: vi.fn(), warn: vi.fn(), info: vi.fn() },
|
||||
sshLogger: { error: vi.fn(), warn: vi.fn(), info: vi.fn() },
|
||||
pluginLogger: { warn: vi.fn() },
|
||||
}));
|
||||
vi.mock("../../../utils/database-save-trigger.js", () => ({
|
||||
DatabaseSaveTrigger: { batched: (fn: RequestHandler) => fn },
|
||||
}));
|
||||
vi.mock("../../../hosts/defaults/overrides.js", () => ({
|
||||
changeHostOverrides: async () => {},
|
||||
}));
|
||||
vi.mock("../../../hosts/defaults/recompute.js", () => ({
|
||||
recompute: async () => ({ changedHostIds: [] }),
|
||||
}));
|
||||
vi.mock("../../../hosts/defaults/service.js", () => ({
|
||||
folderCredentialIds: async () => [],
|
||||
setFolderCredentialDefault: async () => {},
|
||||
}));
|
||||
vi.mock("../../../database/routes/host-plugin-settings.js", () => ({
|
||||
setHostPluginEnabled: async () => true,
|
||||
}));
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentHostRepository: () => ({
|
||||
listBulkUpdateState: async (_userId: string, ids: number[]) =>
|
||||
ids.map((id) => ({ id })),
|
||||
updateManyForUser: async (
|
||||
_userId: string,
|
||||
ids: number[],
|
||||
update: Record<string, unknown>,
|
||||
) => {
|
||||
state.updates.push({ ids, update });
|
||||
},
|
||||
}),
|
||||
createCurrentHostFolderRepository: () => ({
|
||||
listHostsInFolder: async () => state.folderHosts,
|
||||
renameFolder: async () => {
|
||||
state.renamed++;
|
||||
return { updatedHosts: 1, updatedCredentials: 0 };
|
||||
},
|
||||
}),
|
||||
createCurrentFolderAccessRepository: () => ({
|
||||
renameFolder: async () => {},
|
||||
}),
|
||||
}));
|
||||
|
||||
const { registerHostBulkRoutes } =
|
||||
await import("../../../database/routes/host-bulk-routes.js");
|
||||
const { registerHostFolderRoutes } =
|
||||
await import("../../../database/routes/host-folder-routes.js");
|
||||
const { clearHostLocks, provideHostLocks } =
|
||||
await import("../../../hosts/locks.js");
|
||||
|
||||
const pass: RequestHandler = (req, _res, next) => {
|
||||
(req as unknown as { userId: string }).userId = "owner";
|
||||
next();
|
||||
};
|
||||
|
||||
function app() {
|
||||
const router = express.Router();
|
||||
registerHostBulkRoutes(router, pass, pass, pass);
|
||||
registerHostFolderRoutes(router, {
|
||||
authenticateJWT: pass,
|
||||
requireViewPermission: pass,
|
||||
requireEditPermission: pass,
|
||||
requireDeletePermission: pass,
|
||||
requireCredentialEditPermission: pass,
|
||||
requireDataAccess: pass,
|
||||
});
|
||||
const server = express();
|
||||
server.use(express.json());
|
||||
server.use(router);
|
||||
return server;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
state.updates = [];
|
||||
state.renamed = 0;
|
||||
state.folderHosts = [];
|
||||
provideHostLocks("cfg", "Config", {
|
||||
isLocked: (hostId) => hostId === 2,
|
||||
note: () => null,
|
||||
allowManualCreate: () => true,
|
||||
});
|
||||
});
|
||||
afterEach(() => clearHostLocks());
|
||||
|
||||
describe("routes on locked hosts", () => {
|
||||
it("still lets a user pin a locked host", async () => {
|
||||
await request(app())
|
||||
.patch("/bulk-update")
|
||||
.send({ hostIds: [1, 2], updates: { pin: true } })
|
||||
.expect(200);
|
||||
expect(state.updates).toEqual([{ ids: [1, 2], update: { pin: true } }]);
|
||||
});
|
||||
|
||||
it("refuses a bulk change that touches a locked host", async () => {
|
||||
const res = await request(app())
|
||||
.patch("/bulk-update")
|
||||
.send({ hostIds: [1, 2], updates: { folder: "Moved" } })
|
||||
.expect(403);
|
||||
expect(res.body).toMatchObject({ code: "HOST_LOCKED" });
|
||||
expect(state.updates).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses renaming a folder that holds a locked host", async () => {
|
||||
state.folderHosts = [{ id: 1 }, { id: 2 }];
|
||||
await request(app())
|
||||
.put("/folders/rename")
|
||||
.send({ oldName: "Prod", newName: "Live" })
|
||||
.expect(403);
|
||||
expect(state.renamed).toBe(0);
|
||||
|
||||
state.folderHosts = [{ id: 1 }];
|
||||
await request(app())
|
||||
.put("/folders/rename")
|
||||
.send({ oldName: "Prod", newName: "Live" })
|
||||
.expect(200);
|
||||
expect(state.renamed).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -15,7 +15,8 @@ const service = vi.hoisted(() => ({
|
||||
get: vi.fn(),
|
||||
check: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
retimeAll: vi.fn(),
|
||||
getIntervalSeconds: vi.fn(),
|
||||
setIntervalSeconds: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
@@ -35,18 +36,8 @@ vi.mock("../../../utils/permission-manager.js", () => ({
|
||||
}),
|
||||
},
|
||||
}));
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentSettingsRepository: () => ({
|
||||
get: async (key: string) => state.settings[key] ?? null,
|
||||
set: async (key: string, value: string) => {
|
||||
state.settings[key] = value;
|
||||
},
|
||||
}),
|
||||
}));
|
||||
vi.mock("../../../hosts/status/host-status-service.js", () => ({
|
||||
DEFAULT_STATUS_INTERVAL: 60,
|
||||
GLOBAL_STATUS_INTERVAL_KEY: "global_status_check_interval",
|
||||
hostStatusService: service,
|
||||
vi.mock("../../../plugins/host-status-provider.js", () => ({
|
||||
hostStatus: service,
|
||||
}));
|
||||
|
||||
const { registerHostStatusRoutes, parseStatusHostIds } =
|
||||
@@ -83,6 +74,8 @@ async function call(method: string, path: string, body?: unknown) {
|
||||
|
||||
beforeEach(() => {
|
||||
state.settings = {};
|
||||
service.getIntervalSeconds.mockResolvedValue(60);
|
||||
service.setIntervalSeconds.mockResolvedValue(undefined);
|
||||
state.locked = false;
|
||||
state.accessible = new Set([1, 2]);
|
||||
state.statuses = new Map([
|
||||
@@ -149,14 +142,13 @@ describe("status settings", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("saves a new interval and re-times the checks", async () => {
|
||||
it("saves a new interval through the provider", async () => {
|
||||
await start();
|
||||
const { status } = await call("PUT", "/host/status/settings", {
|
||||
statusCheckInterval: 90,
|
||||
});
|
||||
expect(status).toBe(200);
|
||||
expect(state.settings.global_status_check_interval).toBe("90");
|
||||
expect(service.retimeAll).toHaveBeenCalledOnce();
|
||||
expect(service.setIntervalSeconds).toHaveBeenCalledWith(90);
|
||||
});
|
||||
|
||||
it("rejects an interval out of range", async () => {
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import http from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import express from "express";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
userId: "user-1",
|
||||
admins: new Set(["admin-1"]),
|
||||
prefs: null as { layoutId: string | null; themeId: string | null } | null,
|
||||
settings: new Map<string, string>(),
|
||||
audits: [] as unknown[],
|
||||
skipped: [] as unknown[],
|
||||
defaultLookIds: [] as string[],
|
||||
installed: [] as string[],
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
databaseLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
|
||||
}));
|
||||
vi.mock("../../../utils/audit-logger.js", () => ({
|
||||
logAudit: async (entry: unknown) => {
|
||||
state.audits.push(entry);
|
||||
},
|
||||
getRequestMeta: () => ({ ipAddress: "127.0.0.1", userAgent: "test" }),
|
||||
}));
|
||||
vi.mock("../../../utils/auth-manager.js", () => ({
|
||||
AuthManager: {
|
||||
getInstance: () => ({
|
||||
createAuthMiddleware:
|
||||
() => (req: express.Request, _res: unknown, next: () => void) => {
|
||||
(req as unknown as { userId: string }).userId = state.userId;
|
||||
next();
|
||||
},
|
||||
}),
|
||||
},
|
||||
}));
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentUserPreferenceRepository: () => ({
|
||||
findByUserId: async () => state.prefs,
|
||||
}),
|
||||
createCurrentUserRepository: () => ({
|
||||
findById: async (id: string) => ({
|
||||
id,
|
||||
username: id,
|
||||
isAdmin: state.admins.has(id),
|
||||
}),
|
||||
}),
|
||||
createCurrentSettingsRepository: () => ({
|
||||
get: async (key: string) => state.settings.get(key) ?? null,
|
||||
set: async (key: string, value: string) => {
|
||||
state.settings.set(key, value);
|
||||
},
|
||||
delete: async (key: string) => {
|
||||
state.settings.delete(key);
|
||||
},
|
||||
}),
|
||||
}));
|
||||
vi.mock("../../../plugins/index.js", () => ({
|
||||
getPluginRuntime: () => ({
|
||||
loader: {
|
||||
get: (id: string) =>
|
||||
id === "shipped-look"
|
||||
? {
|
||||
manifest: {
|
||||
contributes: {
|
||||
layouts: [
|
||||
{ id: "shipped", label: "Shipped", defaultTheme: "ink" },
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
list: () => [
|
||||
{
|
||||
manifest: {
|
||||
contributes: {
|
||||
layouts: state.installed.map((id) => ({ id, label: id })),
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
skipped: () => state.skipped,
|
||||
},
|
||||
}),
|
||||
}));
|
||||
vi.mock("../../../plugins/bundled-index.js", () => ({
|
||||
defaultLookPluginIds: () => state.defaultLookIds,
|
||||
}));
|
||||
|
||||
const { default: lookRoutes } =
|
||||
await import("../../../database/routes/look.js");
|
||||
|
||||
let server: http.Server;
|
||||
let baseUrl: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
state.userId = "user-1";
|
||||
state.prefs = null;
|
||||
state.settings.clear();
|
||||
state.audits = [];
|
||||
state.skipped = [];
|
||||
state.defaultLookIds = [];
|
||||
state.installed = [];
|
||||
delete process.env.TERMIX_SAFE_LAYOUT;
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use("/user-preferences/look", lookRoutes);
|
||||
server = http.createServer(app);
|
||||
await new Promise<void>((resolve) => server.listen(0, resolve));
|
||||
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
delete process.env.TERMIX_SAFE_LAYOUT;
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
async function getLook() {
|
||||
const res = await fetch(`${baseUrl}/user-preferences/look`);
|
||||
return { status: res.status, body: await res.json() };
|
||||
}
|
||||
|
||||
async function putDefaults(body: unknown) {
|
||||
const res = await fetch(`${baseUrl}/user-preferences/look/defaults`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return { status: res.status, body: await res.json() };
|
||||
}
|
||||
|
||||
describe("GET /user-preferences/look", () => {
|
||||
it("is all empty on a fresh install", async () => {
|
||||
expect((await getLook()).body).toEqual({
|
||||
layoutId: null,
|
||||
themeId: null,
|
||||
defaults: { layout: null, theme: null },
|
||||
defaultLook: { layout: null, theme: null },
|
||||
safeLayout: false,
|
||||
unavailable: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("returns the user's pick, the admin defaults and the default look", async () => {
|
||||
state.prefs = { layoutId: "mine", themeId: "nord" };
|
||||
state.installed = ["mine", "admin-layout"];
|
||||
state.settings.set("ui.layout", "admin-layout");
|
||||
state.settings.set("ui.theme", "gruvbox");
|
||||
state.defaultLookIds = ["shipped-look"];
|
||||
state.skipped = [
|
||||
{
|
||||
id: "broken",
|
||||
version: "1.0.0",
|
||||
layouts: ["b"],
|
||||
themes: [],
|
||||
error: "x",
|
||||
},
|
||||
{ id: "other", version: null, layouts: [], themes: [], error: "y" },
|
||||
];
|
||||
process.env.TERMIX_SAFE_LAYOUT = "1";
|
||||
|
||||
const { body } = await getLook();
|
||||
expect(body).toMatchObject({
|
||||
layoutId: "mine",
|
||||
themeId: "nord",
|
||||
defaults: { layout: "admin-layout", theme: "gruvbox" },
|
||||
defaultLook: { layout: "shipped", theme: "ink" },
|
||||
safeLayout: true,
|
||||
});
|
||||
expect(body.unavailable.map((plugin: { id: string }) => plugin.id)).toEqual(
|
||||
["broken"],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /user-preferences/look with an uninstalled layout", () => {
|
||||
it("drops a choice no installed plugin brings, so the next one applies", async () => {
|
||||
state.prefs = { layoutId: "deleted", themeId: null };
|
||||
state.settings.set("ui.layout", "also-deleted");
|
||||
state.installed = ["kept"];
|
||||
const { body } = await getLook();
|
||||
expect(body.layoutId).toBeNull();
|
||||
expect(body.defaults.layout).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a choice whose plugin failed to load, for the repair view", async () => {
|
||||
state.prefs = { layoutId: "b", themeId: null };
|
||||
state.skipped = [
|
||||
{
|
||||
id: "broken",
|
||||
version: "1.0.0",
|
||||
layouts: ["b"],
|
||||
themes: [],
|
||||
error: "x",
|
||||
},
|
||||
];
|
||||
expect((await getLook()).body.layoutId).toBe("b");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /user-preferences/look/defaults", () => {
|
||||
it("is for admins only", async () => {
|
||||
const { status } = await putDefaults({ layout: "x" });
|
||||
expect(status).toBe(403);
|
||||
expect(state.settings.size).toBe(0);
|
||||
});
|
||||
|
||||
it("sets and clears the defaults, and audits it", async () => {
|
||||
state.userId = "admin-1";
|
||||
let res = await putDefaults({ layout: "fancy", theme: "nord" });
|
||||
expect(res).toEqual({
|
||||
status: 200,
|
||||
body: { layout: "fancy", theme: "nord" },
|
||||
});
|
||||
res = await putDefaults({ layout: null });
|
||||
expect(res.body).toEqual({ layout: null, theme: "nord" });
|
||||
expect(state.audits).toHaveLength(2);
|
||||
expect(state.audits[0]).toMatchObject({ action: "update_default_look" });
|
||||
});
|
||||
|
||||
it("refuses something that is not an id", async () => {
|
||||
state.userId = "admin-1";
|
||||
expect((await putDefaults({ theme: "../evil" })).status).toBe(400);
|
||||
expect((await putDefaults({ layout: 5 })).status).toBe(400);
|
||||
expect(state.settings.size).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -169,6 +169,7 @@ const manageMock = vi.hoisted(() => ({
|
||||
updatePlugin: vi.fn(),
|
||||
updateAllPlugins: vi.fn(),
|
||||
uninstallPlugin: vi.fn(),
|
||||
restoreBundledPlugin: vi.fn(),
|
||||
setPluginOptions: vi.fn(),
|
||||
setAllPluginChannels: vi.fn(),
|
||||
getPluginDataSummary: vi.fn(),
|
||||
@@ -433,6 +434,7 @@ describe("plugins route", () => {
|
||||
"name",
|
||||
"optionalDependencies",
|
||||
"state",
|
||||
"themeVersion",
|
||||
"version",
|
||||
].sort(),
|
||||
);
|
||||
@@ -624,10 +626,12 @@ describe("plugins route", () => {
|
||||
contributes: null,
|
||||
dependencies: {},
|
||||
optionalDependencies: {},
|
||||
defaultLook: false,
|
||||
frontend: false,
|
||||
css: false,
|
||||
assetVersion: null,
|
||||
locales: [],
|
||||
themeVersion: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1138,6 +1142,35 @@ describe("plugins route", () => {
|
||||
expect(manageMock.uninstallPlugin).toHaveBeenCalledWith("docker");
|
||||
});
|
||||
|
||||
it("restores the bundled copy", async () => {
|
||||
manageMock.restoreBundledPlugin.mockResolvedValue({
|
||||
id: "docker",
|
||||
version: "1.0.0",
|
||||
state: "active",
|
||||
});
|
||||
const res = await post("/plugins/docker/restore-bundled");
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({
|
||||
id: "docker",
|
||||
version: "1.0.0",
|
||||
state: "active",
|
||||
});
|
||||
expect(manageMock.restoreBundledPlugin).toHaveBeenCalledWith("docker");
|
||||
});
|
||||
|
||||
it("answers 409 when a plugin has no bundled copy", async () => {
|
||||
manageMock.restoreBundledPlugin.mockRejectedValue(
|
||||
new PluginManageError(
|
||||
"This plugin has no bundled copy",
|
||||
409,
|
||||
"NO_BUNDLED_COPY",
|
||||
),
|
||||
);
|
||||
const res = await post("/plugins/docker/restore-bundled");
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).code).toBe("NO_BUNDLED_COPY");
|
||||
});
|
||||
|
||||
it("refuses changes on a linked desktop", async () => {
|
||||
manageMock.isLinkedDesktop.mockResolvedValue(true);
|
||||
const res = await post("/plugins/docker/install");
|
||||
|
||||
@@ -24,14 +24,12 @@ describe("RBAC coverage for split host routers", () => {
|
||||
it("gates bulk mutations by action and data-access permissions", () => {
|
||||
const router = express.Router();
|
||||
const authenticate = middleware();
|
||||
const requireCreate = middleware();
|
||||
const requireEdit = middleware();
|
||||
const requireDataAccess = middleware();
|
||||
|
||||
registerHostBulkRoutes(
|
||||
router,
|
||||
authenticate,
|
||||
requireCreate,
|
||||
requireEdit,
|
||||
requireDataAccess,
|
||||
);
|
||||
@@ -46,14 +44,6 @@ describe("RBAC coverage for split host routers", () => {
|
||||
requireEdit,
|
||||
requireDataAccess,
|
||||
]);
|
||||
for (const path of ["/bulk-import", "/ssh-config-import"]) {
|
||||
expect(handlers(router, "post", path).slice(0, 4)).toEqual([
|
||||
authenticate,
|
||||
requireCreate,
|
||||
requireEdit,
|
||||
requireDataAccess,
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("gates folder reads and mutations with their matching permissions", () => {
|
||||
|
||||
@@ -28,11 +28,18 @@ vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
}),
|
||||
createCurrentSettingsRepository: () => ({}),
|
||||
createCurrentSshCredentialUsageRepository: deletingRepo("usage"),
|
||||
createCurrentRecentActivityRepository: deletingRepo("activity"),
|
||||
createCurrentHostRepository: deletingRepo("hosts"),
|
||||
createCurrentCredentialRepository: deletingRepo("credentials"),
|
||||
}));
|
||||
|
||||
vi.mock("../../../plugins/activity-provider.js", () => ({
|
||||
recentActivity: {
|
||||
deleteByUserId: async (userId: string) => {
|
||||
calls.deletedFor.push(`activity:${userId}`);
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../../plugins/events.js", () => ({
|
||||
pluginEvents: {
|
||||
emit: (_topic: string, payload: { userId: string }) => {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import http from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import express from "express";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
row: null as Record<string, unknown> | null,
|
||||
upserts: [] as Record<string, unknown>[],
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
databaseLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
|
||||
}));
|
||||
vi.mock("../../../utils/auth-manager.js", () => ({
|
||||
AuthManager: {
|
||||
getInstance: () => ({
|
||||
createAuthMiddleware:
|
||||
() => (req: express.Request, _res: unknown, next: () => void) => {
|
||||
(req as unknown as { userId: string }).userId = "user-1";
|
||||
next();
|
||||
},
|
||||
}),
|
||||
},
|
||||
}));
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentUserPreferenceRepository: () => ({
|
||||
findByUserId: async () => state.row,
|
||||
upsert: async (_userId: string, updates: Record<string, unknown>) => {
|
||||
state.upserts.push(updates);
|
||||
state.row = { ...(state.row ?? {}), ...updates };
|
||||
},
|
||||
}),
|
||||
}));
|
||||
vi.mock("../../../database/routes/keybinding-validation.js", () => ({
|
||||
isValidKeybinding: () => true,
|
||||
}));
|
||||
|
||||
const { default: routes } =
|
||||
await import("../../../database/routes/user-preferences.js");
|
||||
|
||||
let server: http.Server;
|
||||
let baseUrl: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
state.row = null;
|
||||
state.upserts = [];
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use("/user-preferences", routes);
|
||||
server = http.createServer(app);
|
||||
await new Promise<void>((resolve) => server.listen(0, resolve));
|
||||
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
async function put(body: unknown) {
|
||||
const res = await fetch(`${baseUrl}/user-preferences`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return { status: res.status, body: await res.json() };
|
||||
}
|
||||
|
||||
describe("user preferences: layout and theme", () => {
|
||||
it("reads null for both until chosen", async () => {
|
||||
const body = await (await fetch(`${baseUrl}/user-preferences`)).json();
|
||||
expect(body).toMatchObject({ layoutId: null, themeId: null });
|
||||
});
|
||||
|
||||
it("saves a layout and theme id, and null to follow the default", async () => {
|
||||
expect((await put({ layoutId: "fancy", themeId: "nord" })).status).toBe(
|
||||
200,
|
||||
);
|
||||
expect(state.upserts[0]).toMatchObject({
|
||||
layoutId: "fancy",
|
||||
themeId: "nord",
|
||||
});
|
||||
const body = await (await fetch(`${baseUrl}/user-preferences`)).json();
|
||||
expect(body).toMatchObject({ layoutId: "fancy", themeId: "nord" });
|
||||
|
||||
await put({ layoutId: null });
|
||||
expect(state.upserts[1]).toMatchObject({ layoutId: null });
|
||||
expect(state.upserts[1]).not.toHaveProperty("themeId");
|
||||
});
|
||||
|
||||
it("refuses anything that is not an id", async () => {
|
||||
for (const bad of ["Fancy", "../x", "a", 7]) {
|
||||
expect((await put({ themeId: bad })).status).toBe(400);
|
||||
}
|
||||
expect(state.upserts).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,8 @@ vi.mock("../../../utils/audit-logger.js", () => ({
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentSettingsRepository: () => ({
|
||||
get: async (key: string) => state.settings[key] ?? null,
|
||||
getBoolean: async (key: string, fallback: boolean) =>
|
||||
key in state.settings ? state.settings[key] === "true" : fallback,
|
||||
set: async (key: string, value: string) => {
|
||||
state.settings[key] = value;
|
||||
},
|
||||
@@ -39,6 +41,12 @@ vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../../tls/tls-service.js", () => ({
|
||||
getTlsConfig: () => ({ enabled: true, port: 8443 }),
|
||||
}));
|
||||
|
||||
const { resetHttpsPolicyForTests } =
|
||||
await import("../../../tls/https-policy.js");
|
||||
const { registerUserSettingsRoutes } =
|
||||
await import("../../../database/routes/user-settings-routes.js");
|
||||
|
||||
@@ -59,6 +67,7 @@ function app() {
|
||||
beforeEach(() => {
|
||||
state.settings = {};
|
||||
state.admin = true;
|
||||
resetHttpsPolicyForTests();
|
||||
});
|
||||
|
||||
describe("/users/host-defaults", () => {
|
||||
@@ -77,3 +86,35 @@ describe("/users/host-defaults", () => {
|
||||
expect(JSON.parse(state.settings.host_defaults).useSocks5).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("/users/https-settings", () => {
|
||||
it("is off by default and saves a change", async () => {
|
||||
const read = await request(app()).get("/users/https-settings");
|
||||
expect(read.body).toEqual({ forceHttps: false, tlsEnabled: true });
|
||||
|
||||
const write = await request(app())
|
||||
.patch("/users/https-settings")
|
||||
.send({ forceHttps: true });
|
||||
expect(write.status).toBe(200);
|
||||
expect(state.settings.force_https).toBe("true");
|
||||
const after = await request(app()).get("/users/https-settings");
|
||||
expect(after.body.forceHttps).toBe(true);
|
||||
});
|
||||
|
||||
it("is admin only and checks the value", async () => {
|
||||
const bad = await request(app())
|
||||
.patch("/users/https-settings")
|
||||
.send({ forceHttps: "yes" });
|
||||
expect(bad.status).toBe(400);
|
||||
|
||||
state.admin = false;
|
||||
expect((await request(app()).get("/users/https-settings")).status).toBe(
|
||||
403,
|
||||
);
|
||||
const write = await request(app())
|
||||
.patch("/users/https-settings")
|
||||
.send({ forceHttps: true });
|
||||
expect(write.status).toBe(403);
|
||||
expect(state.settings.force_https).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,10 @@ const issueSocketTicket = vi.fn(
|
||||
async (userId: string, sessionId: string) => `ticket:${userId}:${sessionId}`,
|
||||
);
|
||||
|
||||
const issueApiKeySocketTicket = vi.fn(
|
||||
async (userId: string, keyId: string) => `key-ticket:${userId}:${keyId}`,
|
||||
);
|
||||
|
||||
const authenticate: RequestHandler = (req, _res, next) => {
|
||||
Object.assign(req, {
|
||||
userId: "u1",
|
||||
@@ -38,7 +42,10 @@ function app() {
|
||||
const router = express.Router();
|
||||
registerUserSocketTicketRoutes(router, {
|
||||
authenticateJWT: authenticate,
|
||||
authManager: { issueSocketTicket } as unknown as AuthManager,
|
||||
authManager: {
|
||||
issueSocketTicket,
|
||||
issueApiKeySocketTicket,
|
||||
} as unknown as AuthManager,
|
||||
});
|
||||
const server = express();
|
||||
server.use(cookieParser());
|
||||
@@ -50,6 +57,7 @@ beforeEach(() => {
|
||||
state.sessionId = "s1";
|
||||
state.apiKeyId = undefined;
|
||||
issueSocketTicket.mockClear();
|
||||
issueApiKeySocketTicket.mockClear();
|
||||
});
|
||||
|
||||
describe("POST /users/ws-ticket", () => {
|
||||
@@ -98,3 +106,23 @@ describe("POST /users/ws-ticket", () => {
|
||||
expect(issueSocketTicket).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /users/ws-ticket/api-key", () => {
|
||||
it("gives an API key a ticket as its user", async () => {
|
||||
state.sessionId = undefined;
|
||||
state.apiKeyId = "key-1";
|
||||
|
||||
const res = await request(app()).post("/users/ws-ticket/api-key");
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.ticket).toBe("key-ticket:u1:key-1");
|
||||
expect(res.headers["cache-control"]).toBe("no-store");
|
||||
});
|
||||
|
||||
it("refuses a login session, which has its own ticket", async () => {
|
||||
const res = await request(app()).post("/users/ws-ticket/api-key");
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(issueApiKeySocketTicket).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user