mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-29 22:55:24 +00:00
feat: move workspaces into a first-party plugin
This commit is contained in:
1 parent
8742c5d381
commit
6f0dff58a3
19 files changed
+275
-32
No files matched your search
@@ -11,7 +11,7 @@ import alertRoutes from "./routes/alerts.js";
|
||||
import credentialsRoutes from "./routes/credentials.js";
|
||||
import snippetsRoutes from "./routes/snippets.js";
|
||||
import fleetsDispatch from "./routes/fleet-dispatch.js";
|
||||
import workspaceRoutes from "./routes/workspaces.js";
|
||||
import workspaceDispatch from "./routes/workspace-dispatch.js";
|
||||
import c2sTunnelPresetRoutes from "./routes/c2s-tunnel-presets.js";
|
||||
import terminalRoutes from "./routes/terminal.js";
|
||||
import sessionLogRoutes from "./routes/session-log-routes.js";
|
||||
@@ -1754,7 +1754,7 @@ app.use("/alerts", alertRoutes);
|
||||
app.use("/credentials", credentialsRoutes);
|
||||
app.use("/snippets", snippetsRoutes);
|
||||
app.use("/fleets", fleetsDispatch);
|
||||
app.use("/workspaces", workspaceRoutes);
|
||||
app.use("/workspaces", workspaceDispatch);
|
||||
app.use("/c2s-tunnel-presets", c2sTunnelPresetRoutes);
|
||||
app.use("/terminal", terminalRoutes);
|
||||
app.use("/session_logs", sessionLogRoutes);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// Mounted at /workspaces. Workspaces ships as a first-party in-process
|
||||
// plugin (plugins/workspaces) rather than a route file imported directly
|
||||
// here, so this module exists to keep /workspaces/* working at its original
|
||||
// path without handing the plugin a reference to the shared app instance.
|
||||
// The plugin runtime registers its router via registerWorkspacesRouter when
|
||||
// it activates, and clears it on deactivate, so a disabled plugin falls back
|
||||
// to the 404 below.
|
||||
//
|
||||
// Unlike /plugin-api, this dispatcher applies no auth of its own: it forwards
|
||||
// to exactly one first-party router (the Workspaces plugin's own), and every
|
||||
// route in that router already applies authenticateJWT itself, the same as
|
||||
// every other router mounted alongside it here (/users, /host, /snippets,
|
||||
// ...). /plugin-api gates at the mount point because it forwards to arbitrary
|
||||
// third-party plugin code that cannot be assumed to gate itself; that
|
||||
// reasoning does not apply to a single first-party router that already does.
|
||||
|
||||
import type { Request, Response, NextFunction, Router } from "express";
|
||||
import { databaseLogger } from "../../utils/logger.js";
|
||||
|
||||
let activeRouter: Router | null = null;
|
||||
|
||||
export function registerWorkspacesRouter(router: Router): void {
|
||||
activeRouter = router;
|
||||
databaseLogger.info("Registered Workspaces plugin router", {
|
||||
operation: "workspaces_dispatch_register",
|
||||
});
|
||||
}
|
||||
|
||||
export function unregisterWorkspacesRouter(): void {
|
||||
if (!activeRouter) return;
|
||||
activeRouter = null;
|
||||
databaseLogger.info("Unregistered Workspaces plugin router", {
|
||||
operation: "workspaces_dispatch_register",
|
||||
});
|
||||
}
|
||||
|
||||
export default function workspaceDispatch(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
): void {
|
||||
if (!activeRouter) {
|
||||
res.status(404).json({ error: "Workspaces is not available" });
|
||||
return;
|
||||
}
|
||||
activeRouter(req, res, next);
|
||||
}
|
||||
@@ -1,638 +0,0 @@
|
||||
import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import express, { type Request, type Response } from "express";
|
||||
import { databaseLogger } from "../../utils/logger.js";
|
||||
import { AuthManager } from "../../utils/auth-manager.js";
|
||||
import { createCurrentWorkspaceRepository } from "../repositories/factory.js";
|
||||
import type { WorkspaceRecord } from "../repositories/workspace-repository.js";
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const authManager = AuthManager.getInstance();
|
||||
const authenticateJWT = authManager.createAuthMiddleware();
|
||||
const requireDataAccess = authManager.createDataAccessMiddleware();
|
||||
|
||||
function isNonEmptyString(val: unknown): val is string {
|
||||
return typeof val === "string" && val.trim().length > 0;
|
||||
}
|
||||
|
||||
function parseWorkspaceId(raw: unknown): number | null {
|
||||
const id = typeof raw === "string" ? parseInt(raw, 10) : NaN;
|
||||
return Number.isInteger(id) ? id : null;
|
||||
}
|
||||
|
||||
function isValidPayload(val: unknown): val is Record<string, unknown> {
|
||||
return (
|
||||
typeof val === "object" &&
|
||||
val !== null &&
|
||||
Array.isArray((val as Record<string, unknown>).tabs)
|
||||
);
|
||||
}
|
||||
|
||||
function serialize(record: WorkspaceRecord) {
|
||||
let payload: unknown;
|
||||
try {
|
||||
payload = JSON.parse(record.payload || "{}");
|
||||
} catch {
|
||||
payload = { version: 1, tabs: [] };
|
||||
}
|
||||
const tabs = Array.isArray((payload as { tabs?: unknown[] })?.tabs)
|
||||
? (payload as { tabs: unknown[] }).tabs
|
||||
: [];
|
||||
|
||||
return {
|
||||
...record,
|
||||
payload,
|
||||
tabCount: tabs.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /workspaces:
|
||||
* get:
|
||||
* summary: List the current user's saved workspaces
|
||||
* description: Returns every manual workspace plus the single auto-maintained "Last Session" workspace, each with a computed tabCount.
|
||||
* tags:
|
||||
* - Workspaces
|
||||
* responses:
|
||||
* 200:
|
||||
* description: List of workspaces.
|
||||
*/
|
||||
router.get(
|
||||
"/",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
try {
|
||||
const records =
|
||||
await createCurrentWorkspaceRepository().listByUser(userId);
|
||||
res.json(records.map(serialize));
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to list workspaces", err, {
|
||||
operation: "workspace_list_failed",
|
||||
userId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to list workspaces" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /workspaces:
|
||||
* post:
|
||||
* summary: Save the current tab arrangement as a new named workspace
|
||||
* tags:
|
||||
* - Workspaces
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* name:
|
||||
* type: string
|
||||
* color:
|
||||
* type: string
|
||||
* icon:
|
||||
* type: string
|
||||
* payload:
|
||||
* type: object
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Workspace created.
|
||||
* 400:
|
||||
* description: Invalid request body.
|
||||
*/
|
||||
router.post(
|
||||
"/",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { name, color, icon, payload } = req.body ?? {};
|
||||
|
||||
if (!isNonEmptyString(name)) {
|
||||
return res.status(400).json({ error: "Workspace name is required" });
|
||||
}
|
||||
if (!isValidPayload(payload)) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "payload with a tabs array is required" });
|
||||
}
|
||||
|
||||
try {
|
||||
const created = await createCurrentWorkspaceRepository().create(userId, {
|
||||
name: name.trim(),
|
||||
color: isNonEmptyString(color) ? color : null,
|
||||
icon: isNonEmptyString(icon) ? icon : null,
|
||||
payload: JSON.stringify(payload),
|
||||
});
|
||||
res.json(serialize(created));
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to create workspace", err, {
|
||||
operation: "workspace_create_failed",
|
||||
userId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to create workspace" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /workspaces/last-session:
|
||||
* get:
|
||||
* summary: Fetch the auto-maintained "Last Session" workspace
|
||||
* description: Returns null if the current session has never been auto-saved yet.
|
||||
* tags:
|
||||
* - Workspaces
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The Last Session workspace, or null.
|
||||
*/
|
||||
router.get(
|
||||
"/last-session",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
try {
|
||||
const record =
|
||||
await createCurrentWorkspaceRepository().findLastSession(userId);
|
||||
res.json(record ? serialize(record) : null);
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to fetch last session workspace", err, {
|
||||
operation: "workspace_last_session_get_failed",
|
||||
userId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to fetch last session workspace" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /workspaces/last-session:
|
||||
* put:
|
||||
* summary: Upsert the auto-maintained "Last Session" workspace
|
||||
* description: Always overwrites the single Last Session row for the caller - never creates a second one. Called by the frontend's debounced auto-save effect.
|
||||
* tags:
|
||||
* - Workspaces
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* payload:
|
||||
* type: object
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Last Session workspace saved.
|
||||
* 400:
|
||||
* description: Invalid request body.
|
||||
*/
|
||||
router.put(
|
||||
"/last-session",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { payload } = req.body ?? {};
|
||||
|
||||
if (!isValidPayload(payload)) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "payload with a tabs array is required" });
|
||||
}
|
||||
|
||||
try {
|
||||
const saved = await createCurrentWorkspaceRepository().upsertLastSession(
|
||||
userId,
|
||||
JSON.stringify(payload),
|
||||
);
|
||||
res.json(serialize(saved));
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to save last session workspace", err, {
|
||||
operation: "workspace_last_session_save_failed",
|
||||
userId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to save last session workspace" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /workspaces/{id}:
|
||||
* patch:
|
||||
* summary: Rename or recolor a workspace
|
||||
* description: Does not accept a payload - use PUT /workspaces/{id}/content to overwrite a workspace's saved tab arrangement. Rejects the Last Session workspace.
|
||||
* tags:
|
||||
* - Workspaces
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Workspace updated.
|
||||
* 400:
|
||||
* description: Invalid request, or target is the Last Session workspace.
|
||||
* 404:
|
||||
* description: Workspace not found.
|
||||
*/
|
||||
router.patch(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const id = parseWorkspaceId(req.params.id);
|
||||
if (id === null) {
|
||||
return res.status(400).json({ error: "Invalid workspace ID" });
|
||||
}
|
||||
|
||||
const { name, color, icon } = req.body ?? {};
|
||||
if (name !== undefined && !isNonEmptyString(name)) {
|
||||
return res.status(400).json({ error: "Workspace name cannot be empty" });
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await createCurrentWorkspaceRepository().update(
|
||||
userId,
|
||||
id,
|
||||
{
|
||||
name: name !== undefined ? name.trim() : undefined,
|
||||
color,
|
||||
icon,
|
||||
},
|
||||
);
|
||||
|
||||
if (!updated) {
|
||||
return res.status(404).json({ error: "Workspace not found" });
|
||||
}
|
||||
res.json(serialize(updated));
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to update workspace", err, {
|
||||
operation: "workspace_update_failed",
|
||||
userId,
|
||||
workspaceId: id,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to update workspace" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /workspaces/{id}/content:
|
||||
* put:
|
||||
* summary: Overwrite a workspace's saved tab arrangement with a new payload
|
||||
* description: Used by "Update with current" in the Workspaces panel. Rejects the Last Session workspace.
|
||||
* tags:
|
||||
* - Workspaces
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* payload:
|
||||
* type: object
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Workspace content updated.
|
||||
* 400:
|
||||
* description: Invalid request body.
|
||||
* 404:
|
||||
* description: Workspace not found.
|
||||
*/
|
||||
router.put(
|
||||
"/:id/content",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const id = parseWorkspaceId(req.params.id);
|
||||
if (id === null) {
|
||||
return res.status(400).json({ error: "Invalid workspace ID" });
|
||||
}
|
||||
|
||||
const { payload } = req.body ?? {};
|
||||
if (!isValidPayload(payload)) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "payload with a tabs array is required" });
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await createCurrentWorkspaceRepository().updateContent(
|
||||
userId,
|
||||
id,
|
||||
JSON.stringify(payload),
|
||||
);
|
||||
|
||||
if (!updated) {
|
||||
return res.status(404).json({ error: "Workspace not found" });
|
||||
}
|
||||
res.json(serialize(updated));
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to update workspace content", err, {
|
||||
operation: "workspace_content_update_failed",
|
||||
userId,
|
||||
workspaceId: id,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to update workspace content" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /workspaces/{id}/duplicate:
|
||||
* post:
|
||||
* summary: Duplicate a workspace's content and color/icon under a new name
|
||||
* tags:
|
||||
* - Workspaces
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* name:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: New workspace created from the duplicate.
|
||||
* 404:
|
||||
* description: Workspace not found.
|
||||
*/
|
||||
router.post(
|
||||
"/:id/duplicate",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const id = parseWorkspaceId(req.params.id);
|
||||
const { name } = req.body ?? {};
|
||||
if (id === null) {
|
||||
return res.status(400).json({ error: "Invalid workspace ID" });
|
||||
}
|
||||
if (!isNonEmptyString(name)) {
|
||||
return res.status(400).json({ error: "Workspace name is required" });
|
||||
}
|
||||
|
||||
try {
|
||||
const repository = createCurrentWorkspaceRepository();
|
||||
const source = await repository.findById(userId, id);
|
||||
if (!source) {
|
||||
return res.status(404).json({ error: "Workspace not found" });
|
||||
}
|
||||
|
||||
const created = await repository.create(userId, {
|
||||
name: name.trim(),
|
||||
color: source.color,
|
||||
icon: source.icon,
|
||||
payload: source.payload,
|
||||
});
|
||||
res.json(serialize(created));
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to duplicate workspace", err, {
|
||||
operation: "workspace_duplicate_failed",
|
||||
userId,
|
||||
workspaceId: id,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to duplicate workspace" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /workspaces/{id}/set-default:
|
||||
* post:
|
||||
* summary: Mark a workspace as the restore-on-login default
|
||||
* description: Clears isDefault on any other workspace for the caller. Idempotent if the target is already the default. Rejects the Last Session workspace.
|
||||
* tags:
|
||||
* - Workspaces
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Workspace set as default.
|
||||
* 404:
|
||||
* description: Workspace not found.
|
||||
*/
|
||||
router.post(
|
||||
"/:id/set-default",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const id = parseWorkspaceId(req.params.id);
|
||||
if (id === null) {
|
||||
return res.status(400).json({ error: "Invalid workspace ID" });
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await createCurrentWorkspaceRepository().setDefault(
|
||||
userId,
|
||||
id,
|
||||
);
|
||||
if (!updated) {
|
||||
return res.status(404).json({ error: "Workspace not found" });
|
||||
}
|
||||
res.json(serialize(updated));
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to set default workspace", err, {
|
||||
operation: "workspace_set_default_failed",
|
||||
userId,
|
||||
workspaceId: id,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to set default workspace" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /workspaces/{id}/unset-default:
|
||||
* post:
|
||||
* summary: Remove a workspace as the restore-on-login default
|
||||
* description: Idempotent if the target is not currently the default. Rejects the Last Session workspace.
|
||||
* tags:
|
||||
* - Workspaces
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Workspace unset as default.
|
||||
* 404:
|
||||
* description: Workspace not found.
|
||||
*/
|
||||
router.post(
|
||||
"/:id/unset-default",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const id = parseWorkspaceId(req.params.id);
|
||||
if (id === null) {
|
||||
return res.status(400).json({ error: "Invalid workspace ID" });
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await createCurrentWorkspaceRepository().unsetDefault(
|
||||
userId,
|
||||
id,
|
||||
);
|
||||
if (!updated) {
|
||||
return res.status(404).json({ error: "Workspace not found" });
|
||||
}
|
||||
res.json(serialize(updated));
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to unset default workspace", err, {
|
||||
operation: "workspace_unset_default_failed",
|
||||
userId,
|
||||
workspaceId: id,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to unset default workspace" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /workspaces/{id}/apply:
|
||||
* post:
|
||||
* summary: Fetch a workspace to apply and mark it as just used
|
||||
* description: Returns the full workspace with its payload parsed, and touches lastUsedAt server-side so the caller does not need a second round trip.
|
||||
* tags:
|
||||
* - Workspaces
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The workspace to apply.
|
||||
* 404:
|
||||
* description: Workspace not found.
|
||||
*/
|
||||
router.post(
|
||||
"/:id/apply",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const id = parseWorkspaceId(req.params.id);
|
||||
if (id === null) {
|
||||
return res.status(400).json({ error: "Invalid workspace ID" });
|
||||
}
|
||||
|
||||
try {
|
||||
const repository = createCurrentWorkspaceRepository();
|
||||
const record = await repository.findById(userId, id);
|
||||
if (!record) {
|
||||
return res.status(404).json({ error: "Workspace not found" });
|
||||
}
|
||||
|
||||
await repository.touchLastUsed(userId, id);
|
||||
res.json(serialize(record));
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to apply workspace", err, {
|
||||
operation: "workspace_apply_failed",
|
||||
userId,
|
||||
workspaceId: id,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to apply workspace" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /workspaces/{id}:
|
||||
* delete:
|
||||
* summary: Delete a workspace
|
||||
* description: Rejects the Last Session workspace, which is not user-deletable.
|
||||
* tags:
|
||||
* - Workspaces
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Workspace deleted.
|
||||
* 404:
|
||||
* description: Workspace not found.
|
||||
*/
|
||||
router.delete(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const id = parseWorkspaceId(req.params.id);
|
||||
if (id === null) {
|
||||
return res.status(400).json({ error: "Invalid workspace ID" });
|
||||
}
|
||||
|
||||
try {
|
||||
const deleted = await createCurrentWorkspaceRepository().delete(
|
||||
userId,
|
||||
id,
|
||||
);
|
||||
if (!deleted) {
|
||||
return res.status(404).json({ error: "Workspace not found" });
|
||||
}
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to delete workspace", err, {
|
||||
operation: "workspace_delete_failed",
|
||||
userId,
|
||||
workspaceId: id,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to delete workspace" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export default router;
|
||||
@@ -98,6 +98,14 @@
|
||||
* The worker ctx has no fetch primitive at all (ctx.fetch is notImplemented
|
||||
* in SDK v1, see worker-bootstrap.ts), so there is currently no way for a
|
||||
* worker-tier plugin to make an outbound HTTP request.
|
||||
*
|
||||
* workspaces is here for the same reason network-topology is: its routes are
|
||||
* plain per-user JSON CRUD against a single repository, and would fit the
|
||||
* worker ctx fine on their own. It stays in-process to keep its existing
|
||||
* /workspaces URL and its existing dedicated table (user_workspaces, keyed
|
||||
* by userId) rather than moving onto /plugin-api/workspaces/* and the
|
||||
* generic key-value ctx.storage the worker tier would require -- a URL and
|
||||
* storage-model change, not a capability gap.
|
||||
*/
|
||||
export const FIRST_PARTY_PLUGIN_IDS: ReadonlySet<string> = new Set([
|
||||
"ssh-terminal",
|
||||
@@ -110,6 +118,7 @@ export const FIRST_PARTY_PLUGIN_IDS: ReadonlySet<string> = new Set([
|
||||
"automations",
|
||||
"network-topology",
|
||||
"tailscale",
|
||||
"workspaces",
|
||||
]);
|
||||
|
||||
export const TRANSPORT_OWNER_CAPABILITY = "process:transport-owner";
|
||||
|
||||
+10
-10
@@ -295,16 +295,16 @@ async function provisionLocalDesktopUserIfNeeded(): Promise<void> {
|
||||
// ssh-terminal, docker and host-metrics plugins start their own servers,
|
||||
// so disabling any of them stops its WS/HTTP server. See
|
||||
// plugins/ssh-terminal, plugins/docker and plugins/host-metrics.
|
||||
// AI, Proxmox, Remote Desktop, Fleets, Automations and Network Topology
|
||||
// are also absent for the same reason: each plugin registers its router
|
||||
// with its own dispatcher in database.ts on activate (/ai, /proxmox,
|
||||
// /guacamole, /fleets, /automations, /network-topology), so disabling
|
||||
// any of them makes its routes 404 instead of leaving a dead import
|
||||
// here. Automations' scheduler (due schedules, dwell rechecks,
|
||||
// docker-event polling, history pruning) also starts from its own
|
||||
// activate() rather than here. See plugins/ai, plugins/proxmox,
|
||||
// plugins/remote-desktop, plugins/fleets, plugins/automations and
|
||||
// plugins/network-topology.
|
||||
// AI, Proxmox, Remote Desktop, Fleets, Automations, Network Topology and
|
||||
// Workspaces are also absent for the same reason: each plugin registers
|
||||
// its router with its own dispatcher in database.ts on activate (/ai,
|
||||
// /proxmox, /guacamole, /fleets, /automations, /network-topology,
|
||||
// /workspaces), so disabling any of them makes its routes 404 instead of
|
||||
// leaving a dead import here. Automations' scheduler (due schedules,
|
||||
// dwell rechecks, docker-event polling, history pruning) also starts
|
||||
// from its own activate() rather than here. See plugins/ai,
|
||||
// plugins/proxmox, plugins/remote-desktop, plugins/fleets,
|
||||
// plugins/automations, plugins/network-topology and plugins/workspaces.
|
||||
await import("./hosts/tunnel/index.js");
|
||||
await import("./hosts/file-manager/index.js");
|
||||
await import("./hosts/tmux/index.js");
|
||||
|
||||
@@ -374,3 +374,44 @@ describe("bundled network-topology plugin", () => {
|
||||
expect(source).toMatch(/export async function deactivate/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bundled workspaces plugin", () => {
|
||||
it("ships a directory with a manifest and both entry points", () => {
|
||||
const dir = path.join(getBundledPluginsDir(), "workspaces");
|
||||
|
||||
expect(fs.existsSync(path.join(dir, "manifest.json"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, "backend", "index.mjs"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, "frontend", "index.mjs"))).toBe(true);
|
||||
});
|
||||
|
||||
it("has a manifest that passes the real validator", () => {
|
||||
const { manifest, errors } = parseManifest(
|
||||
readBundledManifest("workspaces"),
|
||||
);
|
||||
|
||||
expect(errors).toEqual([]);
|
||||
expect(manifest?.id).toBe("workspaces");
|
||||
expect(manifest?.category).toBe("Productivity");
|
||||
});
|
||||
|
||||
it("declares the transport-owner capability and qualifies for the tier", () => {
|
||||
const { manifest } = parseManifest(readBundledManifest("workspaces"));
|
||||
|
||||
expect(manifest?.permissions).toContain(TRANSPORT_OWNER_CAPABILITY);
|
||||
expect(isFirstParty("workspaces")).toBe(true);
|
||||
expect(runsInProcess("workspaces", manifest!.permissions)).toBe(true);
|
||||
});
|
||||
|
||||
it("exports activate and deactivate from its backend entry", () => {
|
||||
const entry = path.join(
|
||||
getBundledPluginsDir(),
|
||||
"workspaces",
|
||||
"backend",
|
||||
"index.mjs",
|
||||
);
|
||||
const source = fs.readFileSync(entry, "utf8");
|
||||
|
||||
expect(source).toMatch(/export async function activate/);
|
||||
expect(source).toMatch(/export async function deactivate/);
|
||||
});
|
||||
});
|
||||
@@ -39,7 +39,7 @@ function manifest(overrides: Record<string, unknown> = {}) {
|
||||
}
|
||||
|
||||
describe("first-party allowlist", () => {
|
||||
it("contains only ssh-terminal, docker, host-metrics, ai, proxmox, remote-desktop, fleets, automations, network-topology and tailscale", () => {
|
||||
it("contains only ssh-terminal, docker, host-metrics, ai, proxmox, remote-desktop, fleets, automations, network-topology, tailscale and workspaces", () => {
|
||||
expect([...FIRST_PARTY_PLUGIN_IDS].sort()).toEqual([
|
||||
"ai",
|
||||
"automations",
|
||||
@@ -51,10 +51,11 @@ describe("first-party allowlist", () => {
|
||||
"remote-desktop",
|
||||
"ssh-terminal",
|
||||
"tailscale",
|
||||
"workspaces",
|
||||
]);
|
||||
});
|
||||
|
||||
it("recognises ssh-terminal, docker, host-metrics, ai, proxmox, remote-desktop, fleets, automations, network-topology and tailscale and nothing else", () => {
|
||||
it("recognises ssh-terminal, docker, host-metrics, ai, proxmox, remote-desktop, fleets, automations, network-topology, tailscale and workspaces and nothing else", () => {
|
||||
expect(isFirstParty("ssh-terminal")).toBe(true);
|
||||
expect(isFirstParty("docker")).toBe(true);
|
||||
expect(isFirstParty("host-metrics")).toBe(true);
|
||||
@@ -65,6 +66,7 @@ describe("first-party allowlist", () => {
|
||||
expect(isFirstParty("automations")).toBe(true);
|
||||
expect(isFirstParty("network-topology")).toBe(true);
|
||||
expect(isFirstParty("tailscale")).toBe(true);
|
||||
expect(isFirstParty("workspaces")).toBe(true);
|
||||
expect(isFirstParty("ssh-terminal-pro")).toBe(false);
|
||||
expect(isFirstParty("community-plugin")).toBe(false);
|
||||
expect(isFirstParty("")).toBe(false);
|
||||
@@ -93,6 +95,9 @@ describe("runsInProcess", () => {
|
||||
runsInProcess("network-topology", [TRANSPORT_OWNER_CAPABILITY]),
|
||||
).toBe(true);
|
||||
expect(runsInProcess("tailscale", [TRANSPORT_OWNER_CAPABILITY])).toBe(true);
|
||||
expect(runsInProcess("workspaces", [TRANSPORT_OWNER_CAPABILITY])).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
// On the list but not asking for it: stays in a worker, so the manifest
|
||||
// remains an honest description of what the plugin does.
|
||||
@@ -106,6 +111,7 @@ describe("runsInProcess", () => {
|
||||
expect(runsInProcess("automations", ["hosts.read"])).toBe(false);
|
||||
expect(runsInProcess("network-topology", ["hosts.read"])).toBe(false);
|
||||
expect(runsInProcess("tailscale", ["hosts.read"])).toBe(false);
|
||||
expect(runsInProcess("workspaces", ["hosts.read"])).toBe(false);
|
||||
|
||||
// Asking for it but not on the list.
|
||||
expect(
|
||||
@@ -233,6 +239,18 @@ describe("manifest gate on the reserved capability", () => {
|
||||
expect(parsed?.id).toBe("tailscale");
|
||||
});
|
||||
|
||||
it("allows it for workspaces", () => {
|
||||
const { manifest: parsed, errors } = parseManifest(
|
||||
manifest({
|
||||
id: "workspaces",
|
||||
permissions: [TRANSPORT_OWNER_CAPABILITY],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(errors).toEqual([]);
|
||||
expect(parsed?.id).toBe("workspaces");
|
||||
});
|
||||
|
||||
it("still accepts an ordinary manifest that never mentions it", () => {
|
||||
const { manifest: parsed, errors } = parseManifest(
|
||||
manifest({ permissions: ["hosts.read"] }),
|
||||
|
||||
+7
-2
@@ -161,8 +161,13 @@ vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
const { default: router } =
|
||||
await import("../../../database/routes/workspaces.js");
|
||||
vi.mock("../../../database/routes/workspace-dispatch.js", () => ({
|
||||
registerWorkspacesRouter: vi.fn(),
|
||||
unregisterWorkspacesRouter: vi.fn(),
|
||||
}));
|
||||
|
||||
const { router } =
|
||||
await import("../../../../../plugins/workspaces/backend/routes.js");
|
||||
|
||||
function findLayer(method: string, path: string) {
|
||||
const stack = (router as unknown as Router).stack as Array<{
|
||||
Reference in new issue
Block a user