mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-29 14:45:24 +00:00
feat: convert file manager into a plugin
This commit is contained in:
1 parent
b76da9ab52
commit
c85c1fdb86
259 files changed
+54155
-16791
No files matched your search
@@ -0,0 +1,91 @@
|
||||
import http from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import express, { type Router } from "express";
|
||||
import {
|
||||
createMockCtx,
|
||||
createTestDb,
|
||||
type MockPluginContext,
|
||||
type TestDb,
|
||||
} from "@termix/plugin-sdk/testing";
|
||||
import type { PluginManifest } from "@termix/plugin-sdk/manifest";
|
||||
import manifestJson from "../../manifest.json";
|
||||
|
||||
export const pluginDir = fileURLToPath(new URL("../..", import.meta.url));
|
||||
export const manifest = manifestJson as unknown as PluginManifest;
|
||||
|
||||
export interface TestServer {
|
||||
db: TestDb;
|
||||
mock: MockPluginContext;
|
||||
request: (
|
||||
method: string,
|
||||
path: string,
|
||||
options?: { user?: string; body?: unknown },
|
||||
// Route bodies vary per test; asserting on them is the point.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
) => Promise<{ status: number; body: any }>;
|
||||
close: () => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The plugin activated against a real in-memory database, its router mounted
|
||||
* on an express app the way core mounts it: JSON parsed, the acting user set
|
||||
* from the request, everything else left to the plugin.
|
||||
*/
|
||||
export async function startServer(
|
||||
options: { permissions?: string[]; users?: string[] } = {},
|
||||
): Promise<TestServer> {
|
||||
const db = await createTestDb(pluginDir);
|
||||
for (const user of options.users ?? ["user-1", "user-2"]) {
|
||||
db.sqlite
|
||||
.prepare("INSERT INTO users (id, username) VALUES (?, ?)")
|
||||
.run(user, user);
|
||||
}
|
||||
|
||||
let router: Router | null = null;
|
||||
const mock = createMockCtx({
|
||||
pluginId: manifest.id,
|
||||
manifest,
|
||||
capabilities: manifest.capabilities,
|
||||
db: db.database,
|
||||
router: () => (router = express.Router()),
|
||||
permissions: options.permissions ?? ["file-manager.use"],
|
||||
});
|
||||
|
||||
const { activate } = await import("../../src/backend/index.js");
|
||||
await activate(mock.ctx);
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
mock.setActor(req.header("x-test-user") ?? undefined);
|
||||
next();
|
||||
});
|
||||
app.use((req, res, next) => router!(req, res, next));
|
||||
|
||||
const server = http.createServer(app);
|
||||
await new Promise<void>((resolve) => server.listen(0, resolve));
|
||||
const { port } = server.address() as AddressInfo;
|
||||
|
||||
return {
|
||||
db,
|
||||
mock,
|
||||
async request(method, path, { user = "user-1", body: given } = {}) {
|
||||
const body = method === "GET" ? undefined : given;
|
||||
const response = await fetch(`http://127.0.0.1:${port}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
"x-test-user": user,
|
||||
...(body !== undefined ? { "content-type": "application/json" } : {}),
|
||||
},
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
const text = await response.text();
|
||||
return { status: response.status, body: text ? JSON.parse(text) : null };
|
||||
},
|
||||
async close() {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { createTestDb, type TestDb } from "@termix/plugin-sdk/testing";
|
||||
import { pluginDir } from "./helpers.js";
|
||||
|
||||
// file_manager_recent, file_manager_pinned, file_manager_shortcuts and
|
||||
// transfer_recent as core's SQLite bootstrap created them before 2.9.0.
|
||||
const LEGACY_DDL = `
|
||||
CREATE TABLE file_manager_recent (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
host_id INTEGER NOT NULL REFERENCES ssh_data(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
last_opened TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX idx_file_manager_recent_user ON file_manager_recent (user_id, host_id);
|
||||
|
||||
CREATE TABLE file_manager_pinned (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
host_id INTEGER NOT NULL REFERENCES ssh_data(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
pinned_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX idx_file_manager_pinned_user ON file_manager_pinned (user_id, host_id);
|
||||
|
||||
CREATE TABLE file_manager_shortcuts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
host_id INTEGER NOT NULL REFERENCES ssh_data(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX idx_file_manager_shortcuts_user ON file_manager_shortcuts (user_id, host_id);
|
||||
|
||||
CREATE TABLE transfer_recent (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
source_host_id INTEGER NOT NULL REFERENCES ssh_data(id) ON DELETE CASCADE,
|
||||
dest_host_id INTEGER NOT NULL REFERENCES ssh_data(id) ON DELETE CASCADE,
|
||||
dest_path TEXT NOT NULL,
|
||||
dest_path_label TEXT NOT NULL,
|
||||
last_used TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX idx_transfer_recent_user ON transfer_recent (user_id);
|
||||
`;
|
||||
|
||||
let db: TestDb | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
db?.close();
|
||||
db = null;
|
||||
});
|
||||
|
||||
const tableExists = (name: string) =>
|
||||
!!db!.sqlite
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?")
|
||||
.get(name);
|
||||
|
||||
const indexOn = (table: string) =>
|
||||
(
|
||||
db!.sqlite
|
||||
.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND name NOT LIKE 'sqlite_%'",
|
||||
)
|
||||
.all(table) as { name: string }[]
|
||||
).map((row) => row.name);
|
||||
|
||||
describe("adopting the four file-manager tables", () => {
|
||||
it("keeps every existing row when the legacy tables are there", async () => {
|
||||
db = await createTestDb(pluginDir, {
|
||||
before: (sqlite) => {
|
||||
sqlite.exec(
|
||||
"INSERT INTO users (id, username) VALUES ('user-1', 'user-1')",
|
||||
);
|
||||
sqlite.exec("INSERT INTO ssh_data (id) VALUES (1), (2)");
|
||||
sqlite.exec(LEGACY_DDL);
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO file_manager_recent (user_id, host_id, name, path) VALUES (?, ?, ?, ?)",
|
||||
)
|
||||
.run("user-1", 1, "notes.txt", "/home/user/notes.txt");
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO file_manager_pinned (user_id, host_id, name, path) VALUES (?, ?, ?, ?)",
|
||||
)
|
||||
.run("user-1", 1, "logs", "/var/log");
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO file_manager_shortcuts (user_id, host_id, name, path) VALUES (?, ?, ?, ?)",
|
||||
)
|
||||
.run("user-1", 1, "Home", "/home/user");
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO transfer_recent (user_id, source_host_id, dest_host_id, dest_path, dest_path_label) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.run("user-1", 1, 2, "/backups", "Backups");
|
||||
},
|
||||
});
|
||||
|
||||
expect(db.applied).toEqual(["0001_adopt_file_manager_tables"]);
|
||||
|
||||
for (const legacy of [
|
||||
"file_manager_recent",
|
||||
"file_manager_pinned",
|
||||
"file_manager_shortcuts",
|
||||
"transfer_recent",
|
||||
]) {
|
||||
expect(tableExists(legacy)).toBe(false);
|
||||
}
|
||||
for (const adopted of [
|
||||
"p_file_manager_recent",
|
||||
"p_file_manager_pinned",
|
||||
"p_file_manager_shortcuts",
|
||||
"p_file_manager_transfer_recent",
|
||||
]) {
|
||||
expect(tableExists(adopted)).toBe(true);
|
||||
}
|
||||
|
||||
expect(
|
||||
db.sqlite.prepare("SELECT name, path FROM p_file_manager_recent").all(),
|
||||
).toEqual([{ name: "notes.txt", path: "/home/user/notes.txt" }]);
|
||||
expect(
|
||||
db.sqlite.prepare("SELECT name, path FROM p_file_manager_pinned").all(),
|
||||
).toEqual([{ name: "logs", path: "/var/log" }]);
|
||||
expect(
|
||||
db.sqlite
|
||||
.prepare("SELECT name, path FROM p_file_manager_shortcuts")
|
||||
.all(),
|
||||
).toEqual([{ name: "Home", path: "/home/user" }]);
|
||||
expect(
|
||||
db.sqlite
|
||||
.prepare(
|
||||
"SELECT dest_path, dest_path_label FROM p_file_manager_transfer_recent",
|
||||
)
|
||||
.all(),
|
||||
).toEqual([{ dest_path: "/backups", dest_path_label: "Backups" }]);
|
||||
|
||||
expect(indexOn("p_file_manager_recent")).toEqual([
|
||||
"idx_file_manager_recent_user",
|
||||
]);
|
||||
expect(indexOn("p_file_manager_pinned")).toEqual([
|
||||
"idx_file_manager_pinned_user",
|
||||
]);
|
||||
expect(indexOn("p_file_manager_shortcuts")).toEqual([
|
||||
"idx_file_manager_shortcuts_user",
|
||||
]);
|
||||
expect(indexOn("p_file_manager_transfer_recent")).toEqual([
|
||||
"idx_transfer_recent_user",
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates the tables fresh when there is no legacy one", async () => {
|
||||
db = await createTestDb(pluginDir);
|
||||
|
||||
expect(tableExists("file_manager_recent")).toBe(false);
|
||||
expect(tableExists("p_file_manager_recent")).toBe(true);
|
||||
expect(tableExists("p_file_manager_pinned")).toBe(true);
|
||||
expect(tableExists("p_file_manager_shortcuts")).toBe(true);
|
||||
expect(tableExists("p_file_manager_transfer_recent")).toBe(true);
|
||||
expect(
|
||||
db.sqlite.prepare("SELECT * FROM p_file_manager_recent").all(),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { startServer, type TestServer } from "./helpers.js";
|
||||
|
||||
let server: TestServer;
|
||||
|
||||
beforeEach(async () => {
|
||||
server = await startServer();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await server.close();
|
||||
});
|
||||
|
||||
describe("recent/pinned/shortcuts", () => {
|
||||
it("round-trips a recent file", async () => {
|
||||
server.db.sqlite.exec("INSERT INTO ssh_data (id) VALUES (1)");
|
||||
|
||||
const add = await server.request("POST", "/recent", {
|
||||
body: { hostId: 1, path: "/etc/hosts", name: "hosts" },
|
||||
});
|
||||
expect(add.status).toBe(200);
|
||||
|
||||
const list = await server.request("GET", "/recent?hostId=1");
|
||||
expect(list.status).toBe(200);
|
||||
expect(list.body).toEqual([
|
||||
expect.objectContaining({ name: "hosts", path: "/etc/hosts" }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("refuses to pin the same path twice", async () => {
|
||||
server.db.sqlite.exec("INSERT INTO ssh_data (id) VALUES (1)");
|
||||
|
||||
const first = await server.request("POST", "/pinned", {
|
||||
body: { hostId: 1, path: "/var/log", name: "logs" },
|
||||
});
|
||||
expect(first.status).toBe(200);
|
||||
|
||||
const second = await server.request("POST", "/pinned", {
|
||||
body: { hostId: 1, path: "/var/log", name: "logs" },
|
||||
});
|
||||
expect(second.status).toBe(409);
|
||||
});
|
||||
});
|
||||
|
||||
describe("file-manager.use", () => {
|
||||
it("refuses every route without it", async () => {
|
||||
await server.close();
|
||||
server = await startServer({ permissions: [] });
|
||||
|
||||
for (const [method, path] of [
|
||||
["GET", "/status?sessionId=x"],
|
||||
["POST", "/connect"],
|
||||
["GET", "/recent?hostId=1"],
|
||||
["POST", "/recent"],
|
||||
["GET", "/pinned?hostId=1"],
|
||||
["POST", "/pinned"],
|
||||
["GET", "/shortcuts?hostId=1"],
|
||||
["POST", "/shortcuts"],
|
||||
["GET", "/activeTransfers"],
|
||||
] as const) {
|
||||
const res = await server.request(method, path, {
|
||||
body: { hostId: 1, path: "/tmp", name: "tmp" },
|
||||
});
|
||||
expect(res.status, `${method} ${path}`).toBe(403);
|
||||
expect(res.body.required).toBe("file-manager.use");
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user