- Servers can say what they run on (or it is worked out from the Proxmox node); when the host is down the guests' offline alerts fold under it: held back, not counted, not notified, still recorded. - Recurring maintenance schedules made into ordinary windows a week ahead (maintenance_schedules). - Run a Semaphore template limited to a server from its page or an alert, and watch the run. - Agents report pending updates (apt, dnf, zypper, Windows Update); an Updates page lists them. - Migrations 0024 and 0025. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
981 lines
35 KiB
TypeScript
981 lines
35 KiB
TypeScript
import { Router, type Request, type Response } from "express";
|
|
import { eq } from "drizzle-orm";
|
|
import { z } from "zod";
|
|
import { db } from "../db/client.js";
|
|
import { integrations, integrationCredentials, integrationTypes, servers } from "../db/schema.js";
|
|
import { requireAuth, requireRole } from "../auth/middleware.js";
|
|
import { recordAudit } from "../services/audit.js";
|
|
import { encryptSecret } from "../crypto.js";
|
|
import {
|
|
INTEGRATION_FIELDS,
|
|
resolveBaseUrl,
|
|
splitIntegrationConfig,
|
|
validateIntegrationConfig,
|
|
} from "../integrations/fieldSchemas.js";
|
|
import { createIntegrationAdapter } from "../integrations/registry.js";
|
|
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
|
import { createTailscaleAdapter, isKeyExpiringSoon } from "../integrations/tailscale/adapter.js";
|
|
import { createGiteaAdapter } from "../integrations/gitea/adapter.js";
|
|
import { createDockhandAdapter } from "../integrations/dockhand/adapter.js";
|
|
import { createSemaphoreAdapter } from "../integrations/semaphore/adapter.js";
|
|
import { createProxmoxAdapter, guestsWithoutBackupCoverage } from "../integrations/proxmox/adapter.js";
|
|
import { createSynologyAdapter } from "../integrations/synology/adapter.js";
|
|
import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js";
|
|
import { createPbsAdapter } from "../integrations/pbs/adapter.js";
|
|
import { createOsTicketAdapter } from "../integrations/osticket/adapter.js";
|
|
import { attachMatchedServers, summarizeMonitors, toMatchableServers } from "../services/uptimeKumaMatch.js";
|
|
import { getSourceStatus } from "../services/integrationHealthMonitor.js";
|
|
import { asyncHandler } from "../utils/asyncHandler.js";
|
|
import { ID_PATTERNS, isValidId } from "../utils/pathSegment.js";
|
|
|
|
export const integrationsRouter = Router();
|
|
|
|
integrationsRouter.use(requireAuth);
|
|
|
|
const IMPLEMENTED_TYPES = Object.keys(INTEGRATION_FIELDS) as (keyof typeof INTEGRATION_FIELDS)[];
|
|
|
|
integrationsRouter.get("/fields", (_req, res) => {
|
|
res.json({ fields: INTEGRATION_FIELDS });
|
|
});
|
|
|
|
integrationsRouter.get("/", asyncHandler(async (_req, res) => {
|
|
const rows = await db
|
|
.select({
|
|
id: integrations.id,
|
|
type: integrations.type,
|
|
name: integrations.name,
|
|
baseUrl: integrations.baseUrl,
|
|
enabled: integrations.enabled,
|
|
createdAt: integrations.createdAt,
|
|
})
|
|
.from(integrations);
|
|
// How each one has been doing lately. Calls are logged under the integration's type, so a second integration of the same type shares its streak.
|
|
res.json({
|
|
integrations: rows.map((r) => ({
|
|
...r,
|
|
health: r.enabled ? getSourceStatus(r.type) : { status: "disabled" as const, consecutiveFailures: 0 },
|
|
})),
|
|
});
|
|
}));
|
|
|
|
const configValueSchema = z.union([z.string(), z.boolean()]);
|
|
|
|
const createIntegrationSchema = z.object({
|
|
type: z.enum(integrationTypes),
|
|
name: z.string().min(1).max(200),
|
|
config: z.record(configValueSchema),
|
|
});
|
|
|
|
integrationsRouter.post("/", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const parsed = createIntegrationSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
|
|
}
|
|
const { type, name, config } = parsed.data;
|
|
|
|
if (!IMPLEMENTED_TYPES.includes(type)) {
|
|
return res.status(400).json({ error: "not_implemented", message: `Integration type "${type}" isn't available yet.` });
|
|
}
|
|
|
|
const missing = validateIntegrationConfig(type, config);
|
|
if (missing.length > 0) {
|
|
return res.status(400).json({ error: "missing_fields", fields: missing });
|
|
}
|
|
|
|
const { secretFields, nonSecretFields } = splitIntegrationConfig(type, config);
|
|
|
|
let credentialId: number | null = null;
|
|
if (Object.keys(secretFields).length > 0) {
|
|
const [cred] = await db
|
|
.insert(integrationCredentials)
|
|
.values({ name: `${type}:${name}`, encryptedSecret: encryptSecret(JSON.stringify(secretFields)) })
|
|
.returning();
|
|
credentialId = cred.id;
|
|
}
|
|
|
|
const [created] = await db
|
|
.insert(integrations)
|
|
.values({
|
|
type,
|
|
name,
|
|
baseUrl: resolveBaseUrl(type, nonSecretFields),
|
|
credentialId,
|
|
config: JSON.stringify(nonSecretFields),
|
|
enabled: true,
|
|
})
|
|
.returning();
|
|
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "integration",
|
|
action: "create",
|
|
targetType: "integration",
|
|
targetId: created.id,
|
|
detail: { type, name },
|
|
});
|
|
|
|
res.status(201).json({
|
|
integration: {
|
|
id: created.id,
|
|
type: created.type,
|
|
name: created.name,
|
|
baseUrl: created.baseUrl,
|
|
enabled: created.enabled,
|
|
createdAt: created.createdAt,
|
|
},
|
|
});
|
|
}));
|
|
|
|
const updateIntegrationSchema = z.object({
|
|
name: z.string().min(1).max(200).optional(),
|
|
enabled: z.boolean().optional(),
|
|
config: z.record(configValueSchema).optional(),
|
|
});
|
|
|
|
integrationsRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const id = Number(req.params.id);
|
|
const parsed = updateIntegrationSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
|
|
}
|
|
|
|
const [existing] = await db.select().from(integrations).where(eq(integrations.id, id)).limit(1);
|
|
if (!existing) {
|
|
return res.status(404).json({ error: "not_found" });
|
|
}
|
|
|
|
let credentialId = existing.credentialId;
|
|
let configJson = existing.config;
|
|
let baseUrl = existing.baseUrl;
|
|
// For the audit entry: what this edit actually changed. Names only for settings (operators can read the audit
|
|
// log but not an integration's config), and never anything about the credentials beyond "they were replaced".
|
|
let credentialsReplaced = false;
|
|
let fieldsChanged: string[] = [];
|
|
|
|
if (parsed.data.config) {
|
|
const loaded = await loadIntegrationConfig(id);
|
|
const { secretFields, nonSecretFields } = splitIntegrationConfig(existing.type, parsed.data.config);
|
|
credentialsReplaced = Object.keys(secretFields).length > 0;
|
|
fieldsChanged = Object.keys(nonSecretFields).filter(
|
|
(key) => String(loaded?.config[key] ?? "") !== String(nonSecretFields[key] ?? ""),
|
|
);
|
|
const mergedNonSecret = { ...(loaded?.config ?? {}), ...nonSecretFields };
|
|
for (const field of INTEGRATION_FIELDS[existing.type] ?? []) {
|
|
if (field.secret) delete (mergedNonSecret as Record<string, unknown>)[field.key];
|
|
}
|
|
configJson = JSON.stringify(mergedNonSecret);
|
|
baseUrl = resolveBaseUrl(existing.type, mergedNonSecret);
|
|
|
|
if (Object.keys(secretFields).length > 0) {
|
|
const existingSecrets: Record<string, string | boolean> = {};
|
|
const fields = (INTEGRATION_FIELDS[existing.type] ?? []).filter((f) => f.secret);
|
|
for (const f of fields) {
|
|
if (loaded?.config[f.key] !== undefined) existingSecrets[f.key] = loaded.config[f.key]!;
|
|
}
|
|
const mergedSecrets = { ...existingSecrets, ...secretFields };
|
|
const encrypted = encryptSecret(JSON.stringify(mergedSecrets));
|
|
if (existing.credentialId) {
|
|
await db.update(integrationCredentials).set({ encryptedSecret: encrypted }).where(eq(integrationCredentials.id, existing.credentialId));
|
|
} else {
|
|
const [cred] = await db
|
|
.insert(integrationCredentials)
|
|
.values({ name: `${existing.type}:${existing.name}`, encryptedSecret: encrypted })
|
|
.returning();
|
|
credentialId = cred.id;
|
|
}
|
|
}
|
|
}
|
|
|
|
const [updated] = await db
|
|
.update(integrations)
|
|
.set({
|
|
name: parsed.data.name ?? existing.name,
|
|
enabled: parsed.data.enabled ?? existing.enabled,
|
|
credentialId,
|
|
config: configJson,
|
|
baseUrl,
|
|
})
|
|
.where(eq(integrations.id, id))
|
|
.returning();
|
|
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "integration",
|
|
action: "update",
|
|
targetType: "integration",
|
|
targetId: id,
|
|
detail: {
|
|
name: updated.name,
|
|
...(existing.name !== updated.name ? { renamedFrom: existing.name } : {}),
|
|
...(existing.enabled !== updated.enabled ? { enabled: updated.enabled } : {}),
|
|
credentialsReplaced,
|
|
fieldsChanged,
|
|
},
|
|
});
|
|
|
|
res.json({
|
|
integration: {
|
|
id: updated.id,
|
|
type: updated.type,
|
|
name: updated.name,
|
|
baseUrl: updated.baseUrl,
|
|
enabled: updated.enabled,
|
|
createdAt: updated.createdAt,
|
|
},
|
|
});
|
|
}));
|
|
|
|
integrationsRouter.get("/:id/config", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const id = Number(req.params.id);
|
|
const loaded = await loadIntegrationConfig(id);
|
|
if (!loaded) {
|
|
return res.status(404).json({ error: "not_found" });
|
|
}
|
|
|
|
// Never return secret fields (API tokens/passwords) to the browser — the edit
|
|
// form pre-fills only non-secret fields and leaves secret inputs blank.
|
|
const nonSecretConfig: Record<string, string | boolean | undefined> = { ...loaded.config };
|
|
for (const field of INTEGRATION_FIELDS[loaded.integration.type] ?? []) {
|
|
if (field.secret) delete nonSecretConfig[field.key];
|
|
}
|
|
|
|
res.json({
|
|
integration: {
|
|
id: loaded.integration.id,
|
|
type: loaded.integration.type,
|
|
name: loaded.integration.name,
|
|
enabled: loaded.integration.enabled,
|
|
},
|
|
config: nonSecretConfig,
|
|
});
|
|
}));
|
|
|
|
const testExistingIntegrationSchema = z.object({ config: z.record(configValueSchema).optional() });
|
|
|
|
integrationsRouter.post("/:id/test", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const id = Number(req.params.id);
|
|
const parsed = testExistingIntegrationSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
|
|
}
|
|
|
|
const loaded = await loadIntegrationConfig(id);
|
|
if (!loaded) {
|
|
return res.status(404).json({ error: "not_found" });
|
|
}
|
|
|
|
// Merge any freshly-typed fields (e.g. a replacement token) over the
|
|
// already-stored, decrypted config — lets "Test connection" work during an
|
|
// edit without ever sending the current secret value back to the browser.
|
|
const mergedConfig = { ...loaded.config, ...(parsed.data.config ?? {}) };
|
|
const adapter = createIntegrationAdapter(loaded.integration.type, mergedConfig);
|
|
const result = await adapter.ping();
|
|
res.json(result);
|
|
}));
|
|
|
|
integrationsRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const id = Number(req.params.id);
|
|
const [existing] = await db.select().from(integrations).where(eq(integrations.id, id)).limit(1);
|
|
if (!existing) {
|
|
return res.status(404).json({ error: "not_found" });
|
|
}
|
|
|
|
// servers.proxmox_integration_id was meant to clear itself, but the database only has a plain REFERENCES on it (see
|
|
// DATABASE.md), so a linked server would block the delete. Clear the whole link here — the four columns go together.
|
|
const unlinked = await db
|
|
.update(servers)
|
|
.set({ proxmoxIntegrationId: null, proxmoxNode: null, proxmoxGuestType: null, proxmoxVmid: null })
|
|
.where(eq(servers.proxmoxIntegrationId, id))
|
|
.returning({ id: servers.id });
|
|
|
|
await db.delete(integrations).where(eq(integrations.id, id));
|
|
if (existing.credentialId) {
|
|
await db.delete(integrationCredentials).where(eq(integrationCredentials.id, existing.credentialId));
|
|
}
|
|
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "integration",
|
|
action: "delete",
|
|
targetType: "integration",
|
|
targetId: id,
|
|
detail: { name: existing.name, ...(unlinked.length > 0 ? { unlinkedServers: unlinked.length } : {}) },
|
|
});
|
|
|
|
res.status(204).end();
|
|
}));
|
|
|
|
const testIntegrationSchema = z.object({
|
|
type: z.enum(integrationTypes),
|
|
config: z.record(configValueSchema),
|
|
});
|
|
|
|
integrationsRouter.post("/test", requireRole("admin"), asyncHandler(async (req, res) => {
|
|
const parsed = testIntegrationSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
|
|
}
|
|
if (!IMPLEMENTED_TYPES.includes(parsed.data.type)) {
|
|
return res.status(400).json({ error: "not_implemented" });
|
|
}
|
|
const adapter = createIntegrationAdapter(parsed.data.type, parsed.data.config);
|
|
const result = await adapter.ping();
|
|
res.json(result);
|
|
}));
|
|
|
|
// IDs taken from the URL end up in the request made to the connected system, under the integration's own credential. They're
|
|
// checked here (clear 400, nothing sent) and again inside each adapter (see utils/pathSegment.ts) — either alone would do.
|
|
function rejectInvalidId(res: Response, what: string) {
|
|
return res.status(400).json({ error: "invalid_id", message: `That isn't a valid ${what}.` });
|
|
}
|
|
|
|
// ─── Tailscale ───────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Loads the integration row and checks its type BEFORE constructing an
|
|
* adapter — createIntegrationAdapter() throws for any not-yet-implemented
|
|
* type, and that must never happen for an existing non-tailscale row (e.g. a
|
|
* Proxmox row someone points at these Tailscale-only routes).
|
|
*/
|
|
async function requireTailscaleAdapter(req: Request, res: Response) {
|
|
const id = Number(req.params.id);
|
|
const loaded = await loadIntegrationConfig(id);
|
|
if (!loaded) {
|
|
res.status(404).json({ error: "not_found" });
|
|
return null;
|
|
}
|
|
if (loaded.integration.type !== "tailscale") {
|
|
res.status(400).json({ error: "wrong_type" });
|
|
return null;
|
|
}
|
|
if (!loaded.integration.enabled) {
|
|
res.status(400).json({ error: "integration_disabled" });
|
|
return null;
|
|
}
|
|
return { integration: loaded.integration, adapter: createTailscaleAdapter(loaded.config as any) };
|
|
}
|
|
|
|
integrationsRouter.get("/:id/tailscale/devices", asyncHandler(async (req, res) => {
|
|
const found = await requireTailscaleAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const devices = await found.adapter.listDevices();
|
|
res.json({
|
|
devices,
|
|
summary: {
|
|
total: devices.length,
|
|
online: devices.filter((d) => d.online).length,
|
|
unauthorized: devices.filter((d) => !d.authorized).length,
|
|
expiringSoon: devices.filter((d) => isKeyExpiringSoon(d)).length,
|
|
},
|
|
});
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
const authorizeSchema = z.object({ authorized: z.boolean() });
|
|
|
|
integrationsRouter.post(
|
|
"/:id/tailscale/devices/:deviceId/authorize",
|
|
requireRole("operator"),
|
|
asyncHandler(async (req, res) => {
|
|
const found = await requireTailscaleAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
if (!isValidId(req.params.deviceId, ID_PATTERNS.tailscaleDevice)) return rejectInvalidId(res, "device ID");
|
|
|
|
const parsed = authorizeSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
|
|
}
|
|
|
|
try {
|
|
await found.adapter.setAuthorized(req.params.deviceId, parsed.data.authorized);
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "integration",
|
|
action: parsed.data.authorized ? "authorize_device" : "deauthorize_device",
|
|
targetType: "tailscale_device",
|
|
targetId: req.params.deviceId,
|
|
detail: { integrationId: found.integration.id },
|
|
});
|
|
res.status(204).end();
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}),
|
|
);
|
|
|
|
integrationsRouter.delete(
|
|
"/:id/tailscale/devices/:deviceId",
|
|
requireRole("operator"),
|
|
asyncHandler(async (req, res) => {
|
|
const found = await requireTailscaleAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
if (!isValidId(req.params.deviceId, ID_PATTERNS.tailscaleDevice)) return rejectInvalidId(res, "device ID");
|
|
|
|
try {
|
|
await found.adapter.deleteDevice(req.params.deviceId);
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "integration",
|
|
action: "remove_device",
|
|
targetType: "tailscale_device",
|
|
targetId: req.params.deviceId,
|
|
detail: { integrationId: found.integration.id },
|
|
});
|
|
res.status(204).end();
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}),
|
|
);
|
|
|
|
// ─── Gitea ───────────────────────────────────────────────────────────────────
|
|
|
|
async function requireGiteaAdapter(req: Request, res: Response) {
|
|
const id = Number(req.params.id);
|
|
const loaded = await loadIntegrationConfig(id);
|
|
if (!loaded) {
|
|
res.status(404).json({ error: "not_found" });
|
|
return null;
|
|
}
|
|
if (loaded.integration.type !== "gitea") {
|
|
res.status(400).json({ error: "wrong_type" });
|
|
return null;
|
|
}
|
|
if (!loaded.integration.enabled) {
|
|
res.status(400).json({ error: "integration_disabled" });
|
|
return null;
|
|
}
|
|
return { integration: loaded.integration, adapter: createGiteaAdapter(loaded.config as any) };
|
|
}
|
|
|
|
integrationsRouter.get("/:id/gitea/repos", asyncHandler(async (req, res) => {
|
|
const found = await requireGiteaAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const repos = await found.adapter.listReposWithStatus();
|
|
res.json({ repos });
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
integrationsRouter.post(
|
|
"/:id/gitea/repos/:owner/:repo/runs/:runId/rerun-failed",
|
|
requireRole("operator"),
|
|
asyncHandler(async (req, res) => {
|
|
const found = await requireGiteaAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
if (!isValidId(req.params.owner, ID_PATTERNS.giteaName)) return rejectInvalidId(res, "repository owner");
|
|
if (!isValidId(req.params.repo, ID_PATTERNS.giteaName)) return rejectInvalidId(res, "repository name");
|
|
|
|
const runId = Number(req.params.runId);
|
|
if (!Number.isInteger(runId)) {
|
|
return res.status(400).json({ error: "invalid_run_id" });
|
|
}
|
|
|
|
try {
|
|
await found.adapter.rerunFailedJobs(req.params.owner, req.params.repo, runId);
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "integration",
|
|
action: "rerun_failed_jobs",
|
|
targetType: "gitea_workflow_run",
|
|
targetId: `${req.params.owner}/${req.params.repo}#${runId}`,
|
|
detail: { integrationId: found.integration.id },
|
|
});
|
|
res.status(204).end();
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}),
|
|
);
|
|
|
|
// ─── Dockhand ────────────────────────────────────────────────────────────────
|
|
|
|
async function requireDockhandAdapter(req: Request, res: Response) {
|
|
const id = Number(req.params.id);
|
|
const loaded = await loadIntegrationConfig(id);
|
|
if (!loaded) {
|
|
res.status(404).json({ error: "not_found" });
|
|
return null;
|
|
}
|
|
if (loaded.integration.type !== "dockhand") {
|
|
res.status(400).json({ error: "wrong_type" });
|
|
return null;
|
|
}
|
|
if (!loaded.integration.enabled) {
|
|
res.status(400).json({ error: "integration_disabled" });
|
|
return null;
|
|
}
|
|
return { integration: loaded.integration, adapter: createDockhandAdapter(loaded.config as any) };
|
|
}
|
|
|
|
integrationsRouter.get("/:id/dockhand/containers", asyncHandler(async (req, res) => {
|
|
const found = await requireDockhandAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const containers = await found.adapter.listContainers();
|
|
res.json({
|
|
containers,
|
|
summary: {
|
|
total: containers.length,
|
|
running: containers.filter((c) => c.state === "running").length,
|
|
},
|
|
});
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
integrationsRouter.post(
|
|
"/:id/dockhand/check-updates",
|
|
requireRole("operator"),
|
|
asyncHandler(async (req, res) => {
|
|
const found = await requireDockhandAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const result = await found.adapter.checkForUpdates();
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "integration",
|
|
action: "check_updates",
|
|
targetType: "dockhand_integration",
|
|
targetId: found.integration.id,
|
|
detail: result,
|
|
});
|
|
res.json(result);
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}),
|
|
);
|
|
|
|
const dockhandActions = ["start", "stop", "restart"] as const;
|
|
|
|
for (const action of dockhandActions) {
|
|
integrationsRouter.post(
|
|
`/:id/dockhand/environments/:envId/containers/:containerId/${action}`,
|
|
requireRole("operator"),
|
|
asyncHandler(async (req, res) => {
|
|
const found = await requireDockhandAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
if (!isValidId(req.params.containerId, ID_PATTERNS.container)) return rejectInvalidId(res, "container ID");
|
|
|
|
const envId = Number(req.params.envId);
|
|
if (!Number.isInteger(envId)) {
|
|
return res.status(400).json({ error: "invalid_environment_id" });
|
|
}
|
|
|
|
try {
|
|
await found.adapter[`${action}Container`](envId, req.params.containerId);
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "integration",
|
|
action: `${action}_container`,
|
|
targetType: "dockhand_container",
|
|
targetId: req.params.containerId,
|
|
detail: { integrationId: found.integration.id, environmentId: envId },
|
|
});
|
|
res.status(204).end();
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}),
|
|
);
|
|
}
|
|
|
|
// ─── Semaphore ───────────────────────────────────────────────────────────────
|
|
|
|
async function requireSemaphoreAdapter(req: Request, res: Response) {
|
|
const id = Number(req.params.id);
|
|
const loaded = await loadIntegrationConfig(id);
|
|
if (!loaded) {
|
|
res.status(404).json({ error: "not_found" });
|
|
return null;
|
|
}
|
|
if (loaded.integration.type !== "semaphore") {
|
|
res.status(400).json({ error: "wrong_type" });
|
|
return null;
|
|
}
|
|
if (!loaded.integration.enabled) {
|
|
res.status(400).json({ error: "integration_disabled" });
|
|
return null;
|
|
}
|
|
return { integration: loaded.integration, adapter: createSemaphoreAdapter(loaded.config as any) };
|
|
}
|
|
|
|
integrationsRouter.get("/:id/semaphore/templates", asyncHandler(async (req, res) => {
|
|
const found = await requireSemaphoreAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const templates = await found.adapter.listTemplatesWithStatus();
|
|
res.json({
|
|
templates,
|
|
summary: {
|
|
total: templates.length,
|
|
failing: templates.filter((t) => t.lastTask?.status === "error").length,
|
|
},
|
|
});
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
// Which hosts a run may be limited to: names, addresses and ansible patterns (commas, colons, wildcards) — and nothing that could be
|
|
// taken for an option. Semaphore hands the value to ansible as an argument, but it is still only ever shown the characters a host has.
|
|
const runBodySchema = z
|
|
.object({
|
|
limit: z.union([z.literal(""), z.string().trim().regex(/^[A-Za-z0-9][A-Za-z0-9._,:*\-]{0,199}$/, "Use host names or patterns like web01,db*")]).optional(),
|
|
})
|
|
.default({});
|
|
|
|
integrationsRouter.post(
|
|
"/:id/semaphore/projects/:projectId/templates/:templateId/run",
|
|
requireRole("operator"),
|
|
asyncHandler(async (req, res) => {
|
|
const found = await requireSemaphoreAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
const projectId = Number(req.params.projectId);
|
|
const templateId = Number(req.params.templateId);
|
|
if (!Number.isInteger(projectId) || !Number.isInteger(templateId)) {
|
|
return res.status(400).json({ error: "invalid_id" });
|
|
}
|
|
const body = runBodySchema.safeParse(req.body ?? {});
|
|
if (!body.success) {
|
|
return res.status(400).json({ error: "invalid_body", message: "The hosts to limit it to can only be host names or patterns like web01,db*.", details: body.error.flatten() });
|
|
}
|
|
|
|
try {
|
|
const actor = req.currentUser!;
|
|
const limit = body.data.limit || undefined;
|
|
const task = await found.adapter.runTemplate(projectId, templateId, {
|
|
limit,
|
|
message: `Started in Homelab Manager by ${actor.name ?? actor.email ?? actor.oidcSub}${limit ? ` (limited to ${limit})` : ""}`,
|
|
});
|
|
await recordAudit({
|
|
actor,
|
|
category: "integration",
|
|
action: "run_template",
|
|
targetType: "semaphore_template",
|
|
targetId: templateId,
|
|
detail: { integrationId: found.integration.id, projectId, taskId: task.id, ...(limit ? { limit } : {}) },
|
|
});
|
|
res.status(201).json({ task });
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}),
|
|
);
|
|
|
|
// How a run is getting on: waiting, running, success or error.
|
|
integrationsRouter.get("/:id/semaphore/projects/:projectId/tasks/:taskId", asyncHandler(async (req, res) => {
|
|
const found = await requireSemaphoreAdapter(req, res);
|
|
if (!found) return;
|
|
const projectId = Number(req.params.projectId);
|
|
const taskId = Number(req.params.taskId);
|
|
if (!Number.isInteger(projectId) || !Number.isInteger(taskId)) return res.status(400).json({ error: "invalid_id" });
|
|
try {
|
|
res.json({ task: await found.adapter.getTask(projectId, taskId) });
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
// ─── Proxmox ─────────────────────────────────────────────────────────────────
|
|
|
|
async function requireProxmoxAdapter(req: Request, res: Response) {
|
|
const id = Number(req.params.id);
|
|
const loaded = await loadIntegrationConfig(id);
|
|
if (!loaded) {
|
|
res.status(404).json({ error: "not_found" });
|
|
return null;
|
|
}
|
|
if (loaded.integration.type !== "proxmox") {
|
|
res.status(400).json({ error: "wrong_type" });
|
|
return null;
|
|
}
|
|
if (!loaded.integration.enabled) {
|
|
res.status(400).json({ error: "integration_disabled" });
|
|
return null;
|
|
}
|
|
return { integration: loaded.integration, adapter: createProxmoxAdapter(loaded.config as any) };
|
|
}
|
|
|
|
integrationsRouter.get("/:id/proxmox/guests", asyncHandler(async (req, res) => {
|
|
const found = await requireProxmoxAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const guests = await found.adapter.listGuests();
|
|
res.json({
|
|
guests,
|
|
summary: {
|
|
total: guests.length,
|
|
running: guests.filter((g) => g.status === "running").length,
|
|
},
|
|
});
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
integrationsRouter.get("/:id/proxmox/nodes", asyncHandler(async (req, res) => {
|
|
const found = await requireProxmoxAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const nodes = await found.adapter.listNodeStats();
|
|
res.json({ nodes });
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
integrationsRouter.get("/:id/proxmox/backups", asyncHandler(async (req, res) => {
|
|
const found = await requireProxmoxAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const [jobs, tasks, guests] = await Promise.all([
|
|
found.adapter.listBackupJobs(),
|
|
found.adapter.listRecentBackupTasks(),
|
|
found.adapter.listGuests(),
|
|
]);
|
|
res.json({ jobs, tasks, uncoveredGuests: guestsWithoutBackupCoverage(guests, jobs) });
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
const proxmoxActions = ["start", "stop", "restart", "shutdown"] as const;
|
|
|
|
for (const action of proxmoxActions) {
|
|
integrationsRouter.post(
|
|
`/:id/proxmox/nodes/:node/:type/:vmid/${action}`,
|
|
requireRole("operator"),
|
|
asyncHandler(async (req, res) => {
|
|
const found = await requireProxmoxAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
if (!isValidId(req.params.node, ID_PATTERNS.proxmoxNode)) return rejectInvalidId(res, "node name");
|
|
|
|
const vmid = Number(req.params.vmid);
|
|
if (!Number.isInteger(vmid)) {
|
|
return res.status(400).json({ error: "invalid_vmid" });
|
|
}
|
|
const type = req.params.type;
|
|
if (type !== "qemu" && type !== "lxc") {
|
|
return res.status(400).json({ error: "invalid_type" });
|
|
}
|
|
|
|
try {
|
|
await found.adapter[`${action}Guest`](req.params.node, type, vmid);
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "integration",
|
|
action: `${action}_guest`,
|
|
targetType: "proxmox_guest",
|
|
targetId: vmid,
|
|
detail: { integrationId: found.integration.id, node: req.params.node, guestType: type },
|
|
});
|
|
res.status(204).end();
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}),
|
|
);
|
|
}
|
|
|
|
// ─── Synology ────────────────────────────────────────────────────────────────
|
|
// Read-only per the delivery plan — no start/stop/etc actions.
|
|
|
|
async function requireSynologyAdapter(req: Request, res: Response) {
|
|
const id = Number(req.params.id);
|
|
const loaded = await loadIntegrationConfig(id);
|
|
if (!loaded) {
|
|
res.status(404).json({ error: "not_found" });
|
|
return null;
|
|
}
|
|
if (loaded.integration.type !== "synology") {
|
|
res.status(400).json({ error: "wrong_type" });
|
|
return null;
|
|
}
|
|
if (!loaded.integration.enabled) {
|
|
res.status(400).json({ error: "integration_disabled" });
|
|
return null;
|
|
}
|
|
return { integration: loaded.integration, adapter: createSynologyAdapter(loaded.config as any) };
|
|
}
|
|
|
|
integrationsRouter.get("/:id/synology/storage", asyncHandler(async (req, res) => {
|
|
const found = await requireSynologyAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const info = await found.adapter.getStorageInfo();
|
|
res.json({
|
|
...info,
|
|
summary: {
|
|
volumeCount: info.volumes.length,
|
|
volumesNotNormal: info.volumes.filter((v) => v.status !== "normal").length,
|
|
diskCount: info.disks.length,
|
|
disksNotNormal: info.disks.filter((d) => d.status !== "normal").length,
|
|
},
|
|
});
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
integrationsRouter.get("/:id/synology/system", asyncHandler(async (req, res) => {
|
|
const found = await requireSynologyAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const info = await found.adapter.getSystemInfo();
|
|
res.json(info);
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
// ─── Uptime Kuma ─────────────────────────────────────────────────────────────
|
|
|
|
async function requireUptimeKumaAdapter(req: Request, res: Response) {
|
|
const id = Number(req.params.id);
|
|
const loaded = await loadIntegrationConfig(id);
|
|
if (!loaded) {
|
|
res.status(404).json({ error: "not_found" });
|
|
return null;
|
|
}
|
|
if (loaded.integration.type !== "uptimekuma") {
|
|
res.status(400).json({ error: "wrong_type" });
|
|
return null;
|
|
}
|
|
if (!loaded.integration.enabled) {
|
|
res.status(400).json({ error: "integration_disabled" });
|
|
return null;
|
|
}
|
|
return { integration: loaded.integration, adapter: createUptimeKumaAdapter(loaded.config as any) };
|
|
}
|
|
|
|
integrationsRouter.get("/:id/uptimekuma/monitors", asyncHandler(async (req, res) => {
|
|
const found = await requireUptimeKumaAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const monitors = await found.adapter.listMonitors();
|
|
const serverRows = await db.select({ id: servers.id, name: servers.name, hostname: servers.hostname, ips: servers.ipAddresses }).from(servers);
|
|
const withServers = attachMatchedServers(monitors, toMatchableServers(serverRows));
|
|
res.json({ monitors: withServers, summary: summarizeMonitors(monitors) });
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
// ─── Proxmox Backup Server ───────────────────────────────────────────────────
|
|
// Read-only — no destructive actions (pruning/GC/deleting snapshots) are exposed.
|
|
|
|
async function requirePbsAdapter(req: Request, res: Response) {
|
|
const id = Number(req.params.id);
|
|
const loaded = await loadIntegrationConfig(id);
|
|
if (!loaded) {
|
|
res.status(404).json({ error: "not_found" });
|
|
return null;
|
|
}
|
|
if (loaded.integration.type !== "pbs") {
|
|
res.status(400).json({ error: "wrong_type" });
|
|
return null;
|
|
}
|
|
if (!loaded.integration.enabled) {
|
|
res.status(400).json({ error: "integration_disabled" });
|
|
return null;
|
|
}
|
|
return { integration: loaded.integration, adapter: createPbsAdapter(loaded.config as any) };
|
|
}
|
|
|
|
integrationsRouter.get("/:id/pbs/datastores", asyncHandler(async (req, res) => {
|
|
const found = await requirePbsAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const datastores = await found.adapter.listDatastores();
|
|
res.json({
|
|
datastores,
|
|
summary: {
|
|
datastoreCount: datastores.length,
|
|
failedSnapshotCount: datastores.reduce((sum, d) => sum + d.failedCount, 0),
|
|
unverifiedSnapshotCount: datastores.reduce((sum, d) => sum + d.unverifiedCount, 0),
|
|
},
|
|
});
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
integrationsRouter.get("/:id/pbs/status", asyncHandler(async (req, res) => {
|
|
const found = await requirePbsAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const status = await found.adapter.getNodeStatus();
|
|
res.json(status);
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|
|
|
|
// ─── osTicket ────────────────────────────────────────────────────────────────
|
|
// Read-only, and the only integration that reads a database directly rather
|
|
// than an HTTP API — see server/src/integrations/osticket/adapter.ts for why.
|
|
|
|
async function requireOsTicketAdapter(req: Request, res: Response) {
|
|
const id = Number(req.params.id);
|
|
const loaded = await loadIntegrationConfig(id);
|
|
if (!loaded) {
|
|
res.status(404).json({ error: "not_found" });
|
|
return null;
|
|
}
|
|
if (loaded.integration.type !== "osticket") {
|
|
res.status(400).json({ error: "wrong_type" });
|
|
return null;
|
|
}
|
|
if (!loaded.integration.enabled) {
|
|
res.status(400).json({ error: "integration_disabled" });
|
|
return null;
|
|
}
|
|
return { integration: loaded.integration, adapter: createOsTicketAdapter(loaded.config as any) };
|
|
}
|
|
|
|
integrationsRouter.get("/:id/osticket/tickets", asyncHandler(async (req, res) => {
|
|
const found = await requireOsTicketAdapter(req, res);
|
|
if (!found) return;
|
|
|
|
try {
|
|
const tickets = await found.adapter.listOpenTickets();
|
|
res.json({
|
|
tickets,
|
|
summary: {
|
|
total: tickets.length,
|
|
overdue: tickets.filter((t) => t.isOverdue).length,
|
|
awaitingReply: tickets.filter((t) => !t.isAnswered).length,
|
|
},
|
|
});
|
|
} catch (err) {
|
|
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
|
}
|
|
}));
|