Check a value, not just "is it up": JSON value checks on web endpoints
A web check can read a value out of a JSON answer (power.now, state, data.result[0].value[1]) and judge it: below, above, equal to, contains, is there. The value read is shown on the Endpoints page, charted under History, exported as homelab_endpoint_value and in the read API. A check can also send one header (a token), stored encrypted, never returned, and not forwarded to another host on a redirect. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e114567d64
commit
3cb3e4988f
21 files changed
+6804
-47
No files matched your search
@@ -6,7 +6,9 @@ import { endpointChecks, servers } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { invalidateAlertsCache } from "../services/alerts.js";
|
||||
import { CHECK_KINDS, getEndpointHistory, isStatusSpec, loadStats, runCheck } from "../services/endpointChecks.js";
|
||||
import { CHECK_KINDS, getEndpointHistory, isStatusSpec, loadStats, runCheck, type CheckRow } from "../services/endpointChecks.js";
|
||||
import { sealSecret } from "../services/sealed.js";
|
||||
import { VALUE_OPS, valueProblem } from "../services/valueCheck.js";
|
||||
import { loadDismissed, loadSuggestions, saveDismissed } from "../services/endpointSuggestions.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
@@ -16,6 +18,17 @@ endpointsRouter.use(requireAuth);
|
||||
|
||||
const MAX_CHECKS = 100;
|
||||
|
||||
/** A blank text field is no value. */
|
||||
function blank(v: string | null | undefined): string | null {
|
||||
return v === undefined || v === null || v.trim() === "" ? null : v.trim();
|
||||
}
|
||||
|
||||
/** A check as the API shows it: the header's value is never sent back, only that there is one. */
|
||||
function publicCheck(row: CheckRow) {
|
||||
const { headerValue, ...rest } = row;
|
||||
return { ...rest, hasHeader: !!row.headerName && !!headerValue };
|
||||
}
|
||||
|
||||
const checkSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(100),
|
||||
@@ -24,6 +37,13 @@ const checkSchema = z
|
||||
port: z.number().int().min(1).max(65535).nullable().optional(),
|
||||
expectStatus: z.string().trim().max(60).nullable().optional(),
|
||||
keyword: z.string().max(200).nullable().optional(),
|
||||
valuePath: z.string().trim().max(200).nullable().optional(),
|
||||
valueOp: z.enum(VALUE_OPS).nullable().optional(),
|
||||
valueExpected: z.string().max(200).nullable().optional(),
|
||||
valueUnit: z.string().trim().max(12).nullable().optional(),
|
||||
headerName: z.string().trim().max(100).nullable().optional(),
|
||||
/** Left out or blank on an edit keeps the one already saved. */
|
||||
headerValue: z.string().max(2000).nullable().optional(),
|
||||
insecure: z.boolean().optional(),
|
||||
intervalMinutes: z.number().int().min(1).max(1440).optional(),
|
||||
timeoutSeconds: z.number().int().min(1).max(60).optional(),
|
||||
@@ -43,14 +63,17 @@ const checkSchema = z
|
||||
}
|
||||
if (!ok) ctx.addIssue({ code: "custom", path: ["target"], message: "A web check needs an address that starts with http:// or https://." });
|
||||
if (v.expectStatus && !isStatusSpec(v.expectStatus)) ctx.addIssue({ code: "custom", path: ["expectStatus"], message: "Use status codes like 200, or ranges like 200-299, separated by commas." });
|
||||
const problem = valueProblem(blank(v.valuePath), v.valueOp ?? null, blank(v.valueExpected));
|
||||
if (problem) ctx.addIssue({ code: "custom", path: ["valuePath"], message: problem });
|
||||
const name = blank(v.headerName);
|
||||
if (name && !/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(name)) ctx.addIssue({ code: "custom", path: ["headerName"], message: "A header name is letters, digits and dashes, like Authorization." });
|
||||
if (name && /^(host|content-length|transfer-encoding|connection)$/i.test(name)) ctx.addIssue({ code: "custom", path: ["headerName"], message: `${name} is set by the app and can't be changed.` });
|
||||
} else {
|
||||
if (v.port == null) ctx.addIssue({ code: "custom", path: ["port"], message: v.kind === "tcp" ? "A port check needs a port." : "A certificate check needs a port (usually 443)." });
|
||||
if (/[/\s]/.test(v.target)) ctx.addIssue({ code: "custom", path: ["target"], message: "Give just the host name or address, without http:// or a path." });
|
||||
}
|
||||
});
|
||||
|
||||
/** A blank text field is no value. */
|
||||
const blank = (v: string | null | undefined) => (v === undefined || v === null || v.trim() === "" ? null : v.trim());
|
||||
|
||||
// Everyone signed in can see how things are doing, like the pages the same information appears on.
|
||||
endpointsRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
@@ -58,7 +81,7 @@ endpointsRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
const stats = await loadStats(rows.map((r) => r.id));
|
||||
const serverNames = new Map((await db.select({ id: servers.id, name: servers.name }).from(servers)).map((s) => [s.id, s.name]));
|
||||
res.json({
|
||||
checks: rows.map((r) => ({ ...r, server: r.serverId !== null && serverNames.has(r.serverId) ? { id: r.serverId, name: serverNames.get(r.serverId)! } : null, stats: stats.get(r.id) })),
|
||||
checks: rows.map((r) => ({ ...publicCheck(r), server: r.serverId !== null && serverNames.has(r.serverId) ? { id: r.serverId, name: serverNames.get(r.serverId)! } : null, stats: stats.get(r.id) })),
|
||||
servers: [...serverNames].map(([id, name]) => ({ id, name })).sort((a, b) => a.name.localeCompare(b.name)),
|
||||
});
|
||||
}));
|
||||
@@ -74,8 +97,19 @@ endpointsRouter.get("/:id/history", asyncHandler(async (req, res) => {
|
||||
res.json({ check, ...(await getEndpointHistory(id, days)) });
|
||||
}));
|
||||
|
||||
function valuesOf(d: z.infer<typeof checkSchema>) {
|
||||
function valuesOf(d: z.infer<typeof checkSchema>, before?: CheckRow) {
|
||||
const http = d.kind === "http";
|
||||
const hasValue = http && !!blank(d.valuePath);
|
||||
const headerName = http ? blank(d.headerName) : null;
|
||||
// What is already saved stays unless a new value is given; clearing the name removes the header.
|
||||
const headerValue = !headerName ? null : blank(d.headerValue) !== null ? sealSecret(d.headerValue!.trim()) : (before?.headerValue ?? null);
|
||||
return {
|
||||
valuePath: hasValue ? blank(d.valuePath) : null,
|
||||
valueOp: hasValue ? (d.valueOp ?? null) : null,
|
||||
valueExpected: hasValue && d.valueOp !== "exists" ? blank(d.valueExpected) : null,
|
||||
valueUnit: hasValue ? blank(d.valueUnit) : null,
|
||||
headerName,
|
||||
headerValue,
|
||||
name: d.name,
|
||||
kind: d.kind,
|
||||
target: d.target,
|
||||
@@ -142,15 +176,21 @@ endpointsRouter.post("/suggestions/restore", requireRole("admin"), asyncHandler(
|
||||
res.json(await loadSuggestions());
|
||||
}));
|
||||
|
||||
/** A header named with nothing to send, and nothing saved to send either. */
|
||||
function v0HeaderMissing(d: z.infer<typeof checkSchema>, before?: CheckRow): boolean {
|
||||
return d.kind === "http" && !!blank(d.headerName) && blank(d.headerValue) === null && !before?.headerValue;
|
||||
}
|
||||
|
||||
// Asking things on the network is an administrator's to set up.
|
||||
endpointsRouter.post("/",requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
const parsed = checkSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That isn't a check.", details: parsed.error.flatten() });
|
||||
if (v0HeaderMissing(parsed.data)) return res.status(400).json({ error: "invalid_body", message: "Give the header a value." });
|
||||
if ((await db.select({ id: endpointChecks.id }).from(endpointChecks)).length >= MAX_CHECKS) return res.status(409).json({ error: "too_many", message: `At most ${MAX_CHECKS} checks.` });
|
||||
if (!(await serverExists(parsed.data.serverId))) return res.status(400).json({ error: "unknown_server", message: "That server doesn't exist." });
|
||||
const [row] = await db.insert(endpointChecks).values(valuesOf(parsed.data)).returning();
|
||||
await recordAudit({ actor: req.currentUser!, category: "endpoint", action: "create", targetType: "endpoint", targetId: row.id, detail: { name: row.name, kind: row.kind, target: row.target } });
|
||||
res.status(201).json({ check: row });
|
||||
res.status(201).json({ check: publicCheck(row) });
|
||||
}));
|
||||
|
||||
endpointsRouter.put("/:id", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
@@ -160,13 +200,15 @@ endpointsRouter.put("/:id", requireRole("admin"), asyncHandler(async (req, res)
|
||||
const [before] = await db.select().from(endpointChecks).where(eq(endpointChecks.id, id)).limit(1);
|
||||
if (!before) return res.status(404).json({ error: "not_found" });
|
||||
if (!(await serverExists(parsed.data.serverId))) return res.status(400).json({ error: "unknown_server", message: "That server doesn't exist." });
|
||||
const v = valuesOf(parsed.data);
|
||||
if (v0HeaderMissing(parsed.data, before)) return res.status(400).json({ error: "invalid_body", message: "Give the header a value." });
|
||||
const v = valuesOf(parsed.data, before);
|
||||
// What is asked changed, so what was last found out about it no longer stands.
|
||||
const reset = v.kind !== before.kind || v.target !== before.target || v.port !== before.port ? { lastCheckedAt: null, lastOk: null, lastMessage: null, lastResponseMs: null, certExpiresAt: null, consecutiveFailures: 0 } : {};
|
||||
const changed = v.kind !== before.kind || v.target !== before.target || v.port !== before.port || v.valuePath !== before.valuePath || v.valueOp !== before.valueOp || v.valueExpected !== before.valueExpected || v.headerName !== before.headerName;
|
||||
const reset = changed ? { lastCheckedAt: null, lastOk: null, lastMessage: null, lastResponseMs: null, lastValue: null, certExpiresAt: null, consecutiveFailures: 0 } : {};
|
||||
const [row] = await db.update(endpointChecks).set({ ...v, ...reset }).where(eq(endpointChecks.id, id)).returning();
|
||||
await recordAudit({ actor: req.currentUser!, category: "endpoint", action: "update", targetType: "endpoint", targetId: id, detail: { name: row.name, kind: row.kind, target: row.target } });
|
||||
invalidateAlertsCache();
|
||||
res.json({ check: row });
|
||||
res.json({ check: publicCheck(row) });
|
||||
}));
|
||||
|
||||
endpointsRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
|
||||
Reference in new issue
Block a user