Add Servers & Tasks module ported from Schedule Task Manager
Ports cron/systemd task tracking across Debian/Raspbian servers, including the Linux push agent (install/report/uninstall scripts, rebranded from "schedule-task-manager-agent" to "homelab-manager-agent") and the manual-task-entry flow for things an agent can't see (Docker jobs, backups). The schema (servers/scheduled_tasks tables) was already in place from the foundation pass, so this is mostly a straight port of the original's services/routes. Deliberate change from the original: server/token management (which mints agent credentials) is now admin-only rather than open to any logged-in user, and manual task CRUD is gated to operator+ — consistent with how Secrets, IPAM, and DNS already split "configure credentials" from "everyday edits" across roles. All mutations are audit-logged. - server/src/services/tokens.ts, taskSync.ts: ported near-verbatim (agent token hashing, the agent-sync-marks-missing-as-stale-not-deleted logic). - server/src/routes/servers.ts, tasks.ts, agentReport.ts: same contract as the original (agent auth is a per-server bearer token, independent of the session-based requireAuth used everywhere else). - web: a single Servers & Tasks page (filter bar, task table grouped by server/schedule type, manual task form, and an admin-only server management panel with token reveal + copyable install/uninstall commands), replacing the original's two separate pages/apps. Verified: full build passes; a scripted HTTP test against a running server covers unauthenticated access, role gating at each tier (admin-only server mgmt, operator+ task mgmt), agent bearer-token auth (valid/invalid/rotated), manual-vs-agent task edit protection, stale-marking on re-sync, and cascade delete — 22/22 checks passing. Real agent installation on an actual Debian/Raspbian host still needs to be tried on the user's network. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ac3feb935d
commit
9712d611a6
17 files changed
+1616
-1
No files matched your search
@@ -0,0 +1,92 @@
|
||||
import { and, eq, notInArray } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { scheduledTasks, servers } from "../db/schema.js";
|
||||
|
||||
export interface IncomingTask {
|
||||
scheduleType: "cron" | "systemd_timer";
|
||||
name: string;
|
||||
command?: string;
|
||||
scheduleExpression?: string;
|
||||
source?: string;
|
||||
enabled?: boolean;
|
||||
nextRunAt?: string;
|
||||
metadata?: unknown;
|
||||
}
|
||||
|
||||
export interface AgentReport {
|
||||
hostname?: string;
|
||||
tasks: IncomingTask[];
|
||||
}
|
||||
|
||||
export async function syncServerTasks(serverId: number, report: AgentReport) {
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const existing = await db.query.scheduledTasks.findMany({
|
||||
where: and(eq(scheduledTasks.serverId, serverId), eq(scheduledTasks.origin, "agent")),
|
||||
});
|
||||
|
||||
const seenIds: number[] = [];
|
||||
|
||||
for (const task of report.tasks) {
|
||||
const match = existing.find(
|
||||
(t) =>
|
||||
t.scheduleType === task.scheduleType &&
|
||||
t.name === task.name &&
|
||||
(t.source ?? "") === (task.source ?? ""),
|
||||
);
|
||||
|
||||
if (match) {
|
||||
const [updated] = await db
|
||||
.update(scheduledTasks)
|
||||
.set({
|
||||
command: task.command,
|
||||
scheduleExpression: task.scheduleExpression,
|
||||
enabled: task.enabled ?? true,
|
||||
nextRunAt: task.nextRunAt,
|
||||
rawMetadata: task.metadata ? JSON.stringify(task.metadata) : null,
|
||||
isStale: false,
|
||||
lastSeenAt: now,
|
||||
})
|
||||
.where(eq(scheduledTasks.id, match.id))
|
||||
.returning({ id: scheduledTasks.id });
|
||||
seenIds.push(updated.id);
|
||||
} else {
|
||||
const [created] = await db
|
||||
.insert(scheduledTasks)
|
||||
.values({
|
||||
serverId,
|
||||
scheduleType: task.scheduleType,
|
||||
origin: "agent",
|
||||
name: task.name,
|
||||
command: task.command,
|
||||
scheduleExpression: task.scheduleExpression,
|
||||
source: task.source,
|
||||
enabled: task.enabled ?? true,
|
||||
nextRunAt: task.nextRunAt,
|
||||
rawMetadata: task.metadata ? JSON.stringify(task.metadata) : null,
|
||||
firstSeenAt: now,
|
||||
lastSeenAt: now,
|
||||
})
|
||||
.returning({ id: scheduledTasks.id });
|
||||
seenIds.push(created.id);
|
||||
}
|
||||
}
|
||||
|
||||
// Anything agent-sourced for this server that wasn't in this report is now stale,
|
||||
// rather than deleted, so a bad/partial agent run doesn't wipe history. Manually
|
||||
// entered tasks (origin = 'manual') are never touched by agent sync.
|
||||
const agentScope = and(eq(scheduledTasks.serverId, serverId), eq(scheduledTasks.origin, "agent"));
|
||||
if (seenIds.length > 0) {
|
||||
await db
|
||||
.update(scheduledTasks)
|
||||
.set({ isStale: true })
|
||||
.where(and(agentScope, notInArray(scheduledTasks.id, seenIds)));
|
||||
} else {
|
||||
await db.update(scheduledTasks).set({ isStale: true }).where(agentScope);
|
||||
}
|
||||
|
||||
await db
|
||||
.update(servers)
|
||||
.set({ lastSeenAt: now, ...(report.hostname ? { hostname: report.hostname } : {}) })
|
||||
.where(eq(servers.id, serverId));
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { randomBytes, createHash, timingSafeEqual } from "node:crypto";
|
||||
|
||||
const TOKEN_PREFIX_LENGTH = 8;
|
||||
|
||||
export function generateApiToken(): { token: string; prefix: string; hash: string } {
|
||||
const token = `hlm_${randomBytes(24).toString("hex")}`;
|
||||
const prefix = token.slice(0, TOKEN_PREFIX_LENGTH);
|
||||
return { token, prefix, hash: hashToken(token) };
|
||||
}
|
||||
|
||||
export function hashToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
export function tokensMatch(hashA: string, hashB: string): boolean {
|
||||
const bufA = Buffer.from(hashA, "hex");
|
||||
const bufB = Buffer.from(hashB, "hex");
|
||||
if (bufA.length !== bufB.length) return false;
|
||||
return timingSafeEqual(bufA, bufB);
|
||||
}
|
||||
Reference in new issue
Block a user