Files
Homelab-manager/server/src/services/metricsTokens.ts
T
bobbanandClaude Sonnet 5.5 c17e9aa140 Add runbooks, backup coverage, inventory, roles from groups, Prometheus metrics and event webhooks
- Runbooks: notes per server/integration, shown next to matching alerts
- Backup coverage page across Proxmox and PBS, with a digest section
- Hardware inventory with warranty, power and running cost
- Authentik group to role mapping with preview and safeguards
- /metrics (bearer token) and signed outgoing event webhooks
- Docs: README, DATABASE, NOTIFICATIONS, ROLES and new API.md

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-17 20:41:00 +02:00

38 lines
2.0 KiB
TypeScript

/**
* Metrics tokens: read-only access to /metrics for Prometheus. Like an agent token or a share link, the secret is shown once, when it is
* made, and only its SHA-256 is kept — so it can't be read back out of the database or a backup.
*/
import { createHash, randomBytes } from "node:crypto";
import { eq } from "drizzle-orm";
import { db } from "../db/client.js";
import { metricsTokens } from "../db/schema.js";
export type MetricsTokenRow = typeof metricsTokens.$inferSelect;
const hash = (token: string) => createHash("sha256").update(token).digest("hex");
/** Use is not recorded more than once in this time, so a scrape every fifteen seconds doesn't write the database each time. */
const USED_WRITE_GAP_MS = 60_000;
export async function createMetricsToken(params: { label: string; createdBy: string }): Promise<{ row: MetricsTokenRow; token: string }> {
const token = `hlm_m_${randomBytes(24).toString("base64url")}`;
const [row] = await db.insert(metricsTokens).values({ label: params.label, tokenHash: hash(token), tokenPrefix: token.slice(0, 12), createdBy: params.createdBy }).returning();
return { row, token };
}
/** The token a secret belongs to, if there is one; notes that it was used. */
export async function resolveMetricsToken(token: string, now: Date = new Date()): Promise<MetricsTokenRow | null> {
if (typeof token !== "string" || token.length < 20 || token.length > 128) return null;
const [row] = await db.select().from(metricsTokens).where(eq(metricsTokens.tokenHash, hash(token))).limit(1);
if (!row) return null;
if (!row.lastUsedAt || now.getTime() - Date.parse(row.lastUsedAt) >= USED_WRITE_GAP_MS) {
await db.update(metricsTokens).set({ lastUsedAt: now.toISOString() }).where(eq(metricsTokens.id, row.id));
}
return row;
}
/** A token as the admin list shows it: everything but the hash. */
export function publicMetricsToken(row: MetricsTokenRow) {
return { id: row.id, label: row.label, tokenPrefix: row.tokenPrefix, createdBy: row.createdBy, createdAt: row.createdAt, lastUsedAt: row.lastUsedAt };
}