Files
Homelab-manager/server/src/db/schema.ts
T
bobbanandClaude Sonnet 5.5 3b31b16796 Service-level targets with error budgets, and quarterly and annual reports
Monitoring -> Service levels: a target (99.9 %) on an endpoint check, a server or an
integration, measured over calendar months. Shows the figure, downtime used, the
error budget left, and how the last six months went. 80 % of the budget used is a
warning and an overspent budget a critical alert. Endpoints are measured day by day,
servers and integrations to the minute from the audit log.

The report page gains Quarter and Year (same figures, with a Service levels section),
and two settings send the quarterly and annual report after the month that ends them.

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

1387 lines
71 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { sql } from "drizzle-orm";
import { sqliteTable, text, integer, real, uniqueIndex, index, primaryKey } from "drizzle-orm/sqlite-core";
// ─── Users & roles ──────────────────────────────────────────────────────────
export const userRoles = ["admin", "operator", "viewer"] as const;
export type UserRole = (typeof userRoles)[number];
export const users = sqliteTable("users", {
id: integer("id").primaryKey({ autoIncrement: true }),
oidcSub: text("oidc_sub").notNull().unique(),
email: text("email"),
name: text("name"),
role: text("role").$type<UserRole>().notNull().default("viewer"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
lastLoginAt: text("last_login_at"),
// The pages this person pinned to the top of their menu, as a JSON array of paths ("/servers", "/alerts"). It follows them to any browser.
favorites: text("favorites"),
// When this person last pressed "Got it" on the dashboard summary of what changed; the next summary starts from here (ISO).
lastLookedAt: text("last_looked_at"),
// The groups the identity provider said this person was in at their last sign-in, as a JSON array — shown on the Users page so the group
// names can be matched to roles (Settings → Sign-in). Null until they have signed in with groups available.
groups: text("groups"),
// How this person arranged the dashboard: a JSON object with the cards they hid ("hidden": ["Gitea"]) and the order of the others
// ("order": {"DNS": 0, "Secrets": 1}). Follows them to any browser; null is the default layout.
dashboardLayout: text("dashboard_layout"),
// The address of the picture the identity provider gave for this person (the OIDC "picture" claim), as of their last sign-in. Only an address:
// nothing is fetched from it unless Settings → Sign-in → Profile pictures allows it, and then only by this server, never by the browser.
pictureUrl: text("picture_url"),
});
// ─── Audit log ──────────────────────────────────────────────────────────────
export const auditLog = sqliteTable("audit_log", {
id: integer("id").primaryKey({ autoIncrement: true }),
actorUserId: integer("actor_user_id").references(() => users.id, { onDelete: "set null" }),
actorLabel: text("actor_label"), // denormalized name/email snapshot, survives user deletion
category: text("category").notNull(), // 'secret' | 'ipam' | 'dns' | 'user' | 'integration' | 'task' | ...
action: text("action").notNull(), // 'create' | 'update' | 'delete' | 'start' | 'stop' | ...
targetType: text("target_type"),
targetId: text("target_id"),
detail: text("detail"), // JSON-encoded free-form context
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Diagnostic log — every outbound call to a DNS provider or integration ──
export const diagLog = sqliteTable("diag_log", {
id: integer("id").primaryKey({ autoIncrement: true }),
source: text("source").notNull(), // e.g. 'cloudflare' | 'tailscale' | 'proxmox' | ...
operation: text("operation").notNull(), // adapter method name, e.g. 'listZones' | 'listDevices'
ok: integer("ok", { mode: "boolean" }).notNull(),
latencyMs: integer("latency_ms").notNull(),
error: text("error"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Notification queue — pending notifications held during quiet hours ────
export const notificationQueue = sqliteTable("notification_queue", {
id: integer("id").primaryKey({ autoIncrement: true }),
title: text("title").notNull(),
message: text("message").notNull(),
/** JSON: who it is for (the channels and browsers a routing rule picked); null = everyone, as before routing existed. */
audience: text("audience"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Maintenance windows — alerts about a target are silenced until endsAt ──
export const maintenanceTargetTypes = ["server", "integration", "dns_provider", "device"] as const;
export type MaintenanceTargetType = (typeof maintenanceTargetTypes)[number];
export const maintenanceWindows = sqliteTable("maintenance_windows", {
id: integer("id").primaryKey({ autoIncrement: true }),
targetType: text("target_type").$type<MaintenanceTargetType>().notNull(),
targetId: integer("target_id").notNull(), // polymorphic — no FK; a deleted target's window is simply ignored
reason: text("reason"),
startedAt: text("started_at").notNull(), // ISO
endsAt: text("ends_at").notNull(), // ISO — required: a forgotten open-ended window would silence real problems forever
createdBy: text("created_by"),
// Set on windows mirrored from another system (`kuma:<integration id>:<maintenance id>`), so a later sync can find and adjust them. NULL = started by hand.
source: text("source"),
});
// An address that Uptime Kuma's monitors use for a thing this app knows by another address (a Tailscale IP for a host added by its LAN
// address, say), so a maintenance window in Uptime Kuma lands on the right server, integration or DNS provider. The address is stored as a
// bare lowercase host.
export const maintenanceAliases = sqliteTable(
"maintenance_aliases",
{
id: integer("id").primaryKey({ autoIncrement: true }),
address: text("address").notNull(),
targetType: text("target_type").$type<MaintenanceTargetType>().notNull(),
targetId: integer("target_id").notNull(), // polymorphic, like maintenance_windows — no FK; an alias whose target was deleted is ignored
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
},
(table) => [uniqueIndex("maintenance_aliases_unique_idx").on(table.address, table.targetType, table.targetId)],
);
// A browser or phone that asked for push notifications (one row per device). The endpoint is the browser's push service address, which is
// itself a secret: whoever has it with the keys can write to that device. Removed when the push service says it is gone, or the user signs out of it.
export const pushSubscriptions = sqliteTable("push_subscriptions", {
id: integer("id").primaryKey({ autoIncrement: true }),
userId: integer("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
endpoint: text("endpoint").notNull().unique(),
p256dh: text("p256dh").notNull(),
auth: text("auth").notNull(),
/** What the person calls it, or the browser it is. */
label: text("label"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
lastSuccessAt: text("last_success_at"),
/** This browser only wants alerts at least this bad ("warning" or "critical"); null = every severity. */
minSeverity: text("min_severity"),
/** JSON string[] of the kinds of alert it wants; null = every kind. */
categories: text("categories"),
});
// A web address, TCP port or TLS certificate the app asks about every few minutes — see services/endpointChecks.ts. The last answer is kept on the row;
// every answer is also one row in endpoint_results (kept two weeks), for uptime and answer times.
export const endpointChecks = sqliteTable("endpoint_checks", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(),
kind: text("kind").notNull(), // http | tcp | tls
target: text("target").notNull(), // http: the web address; tcp and tls: the host
port: integer("port"), // tcp and tls
expectStatus: text("expect_status"), // http: "200-299, 301"; null = 200-399
keyword: text("keyword"), // http: text the page must contain
insecure: integer("insecure", { mode: "boolean" }).notNull().default(false), // accept a certificate that isn't trusted (self-signed, a private CA)
valuePath: text("value_path"), // http: where in a JSON answer the value to judge is ("data.result[0].value[1]")
valueOp: text("value_op"), // http: "<" "<=" ">" ">=" "=" "!=" "contains" "exists"
valueExpected: text("value_expected"), // http: what it is compared with (a number, or text for "=", "!=" and "contains")
valueUnit: text("value_unit"), // http: shown after the value ("W", "%", "°C")
headerName: text("header_name"), // http: a header to send with the request ("Authorization")
headerValue: text("header_value"), // its value, encrypted at rest like the notification channels' secrets; never returned by the API
lastValue: text("last_value"), // http: what was read the last time, as text
intervalMinutes: integer("interval_minutes").notNull().default(5),
timeoutSeconds: integer("timeout_seconds").notNull().default(10),
failuresBeforeAlert: integer("failures_before_alert").notNull().default(2),
warnDays: integer("warn_days").notNull().default(14), // warn this long before a certificate expires
serverId: integer("server_id"), // soft reference: the server this is about, so its maintenance silences the alerts
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
lastCheckedAt: text("last_checked_at"),
lastOk: integer("last_ok", { mode: "boolean" }),
lastMessage: text("last_message"),
lastResponseMs: integer("last_response_ms"),
certExpiresAt: text("cert_expires_at"), // ISO
consecutiveFailures: integer("consecutive_failures").notNull().default(0),
lastChangeAt: text("last_change_at"), // when it last went from working to failing or back
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
export const endpointResults = sqliteTable(
"endpoint_results",
{
id: integer("id").primaryKey({ autoIncrement: true }),
checkId: integer("check_id")
.notNull()
.references(() => endpointChecks.id, { onDelete: "cascade" }),
at: text("at").notNull(), // ISO
ok: integer("ok", { mode: "boolean" }).notNull(),
ms: integer("ms"),
message: text("message"),
value: real("value"), // the number read from the answer, for a check that judges a value
},
(t) => [index("endpoint_results_check_idx").on(t.checkId, t.at)],
);
// One time somebody tried to restore a backup, and how it went — see services/restoreTests.ts. History is kept; the newest per subject is what counts.
export const restoreTests = sqliteTable(
"restore_tests",
{
id: integer("id").primaryKey({ autoIncrement: true }),
subjectKey: text("subject_key").notNull(), // guest:<integration id>:<vmid> for a Proxmox guest, custom:<slug> for anything else
label: text("label").notNull(),
testedAt: text("tested_at").notNull(), // YYYY-MM-DD
result: text("result").notNull(), // ok | partial | failed | not_needed
note: text("note"),
testedBy: text("tested_by"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
},
(t) => [index("restore_tests_subject_idx").on(t.subjectKey, t.testedAt)],
);
// A job that reports in: a cron job or backup script calls its address when it finishes, and the app speaks up when the call doesn't come in time —
// see services/heartbeats.ts. The token is part of the address (/api/heartbeat/<token>) and is all the access a ping needs.
export const heartbeats = sqliteTable("heartbeats", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(),
token: text("token").notNull().unique(),
periodMinutes: integer("period_minutes").notNull(), // how often it should report
graceMinutes: integer("grace_minutes").notNull().default(10), // how much later than that is still fine
serverId: integer("server_id"), // soft reference: the server it runs on, so its maintenance silences the alerts
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
notes: text("notes"),
lastPingAt: text("last_ping_at"), // ISO; the last report of an end (success or failure)
lastStatus: text("last_status"), // ok | fail
lastMessage: text("last_message"),
lastDurationMs: integer("last_duration_ms"), // when it said it had started first
lastStartAt: text("last_start_at"), // ISO; the last "started" call
pingCount: integer("ping_count").notNull().default(0),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// The recent calls to each heartbeat, for its history; kept two weeks.
export const heartbeatPings = sqliteTable(
"heartbeat_pings",
{
id: integer("id").primaryKey({ autoIncrement: true }),
heartbeatId: integer("heartbeat_id")
.notNull()
.references(() => heartbeats.id, { onDelete: "cascade" }),
at: text("at").notNull(), // ISO
kind: text("kind").notNull(), // ok | fail | start
durationMs: integer("duration_ms"),
message: text("message"),
},
(t) => [index("heartbeat_pings_idx").on(t.heartbeatId, t.at)],
);
// "A needs B", for things that can be down: a server or an integration each. Polymorphic like maintenance_windows (no foreign key); an edge whose
// end was deleted is ignored. When B is down, A's alert is folded under B's — see services/dependencies.ts.
export const dependencies = sqliteTable(
"dependencies",
{
id: integer("id").primaryKey({ autoIncrement: true }),
fromType: text("from_type").notNull(), // server | integration
fromId: integer("from_id").notNull(),
toType: text("to_type").notNull(),
toId: integer("to_id").notNull(),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
},
(table) => [uniqueIndex("dependencies_edge_idx").on(table.fromType, table.fromId, table.toType, table.toId)],
);
// A short history of each agent-reported server's load, memory and disk use, in percent — see services/serverMetrics.ts.
// `metric` is "cpu", "mem" or "disk:<mount point>".
export const serverMetrics = sqliteTable(
"server_metrics",
{
id: integer("id").primaryKey({ autoIncrement: true }),
serverId: integer("server_id")
.notNull()
.references(() => servers.id, { onDelete: "cascade" }),
metric: text("metric").notNull(),
value: real("value").notNull(),
recordedAt: text("recorded_at").notNull(), // ISO
},
(table) => [index("server_metrics_lookup_idx").on(table.serverId, table.metric, table.recordedAt)],
);
// The same figures, kept longer and coarser: one row per server, figure and hour (grain "h", kept a few months) or day (grain "d", kept for years), with what is
// needed to draw them — the sum and count (so the average can be worked out as more samples arrive), and the lowest and highest. `at` is the start of the hour
// or day, as ISO. Written as each sample is recorded; see services/serverMetrics.ts.
export const serverMetricsRollup = sqliteTable(
"server_metrics_rollup",
{
serverId: integer("server_id")
.notNull()
.references(() => servers.id, { onDelete: "cascade" }),
metric: text("metric").notNull(),
grain: text("grain").$type<"h" | "d">().notNull(),
at: text("at").notNull(),
sum: real("sum").notNull(),
n: integer("n").notNull(),
min: real("min").notNull(),
max: real("max").notNull(),
},
(t) => [primaryKey({ columns: [t.serverId, t.metric, t.grain, t.at] })],
);
// ─── Settings (key/value) ───────────────────────────────────────────────────
export const settings = sqliteTable("settings", {
key: text("key").primaryKey(),
value: text("value").notNull(),
updatedAt: text("updated_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Secrets expiry tracker (ported from Sloth Manager) ────────────────────
export const secretTypes = ["api_token", "ssl_certificate", "password", "generic"] as const;
export type SecretType = (typeof secretTypes)[number];
export const secrets = sqliteTable("secrets", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(),
type: text("type").$type<SecretType>().notNull().default("generic"),
description: text("description"),
expiryDate: text("expiry_date"), // ISO date, e.g. 2026-03-01. NULL = never expires (no status, no reminders).
warnDays: integer("warn_days").notNull().default(30),
notes: text("notes"),
// ssl_certificate secrets only: when set, expiryDate is read from the live certificate on this host:port instead of typed in.
checkHost: text("check_host"),
checkPort: integer("check_port"),
lastCheckedAt: text("last_checked_at"),
lastCheckError: text("last_check_error"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
updatedAt: text("updated_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── IPAM (ported from Sloth Manager) ───────────────────────────────────────
export const ipamEntries = sqliteTable("ipam_entries", {
id: integer("id").primaryKey({ autoIncrement: true }),
ipAddress: text("ip_address").notNull().unique(),
label: text("label"),
vendor: text("vendor"),
location: text("location"),
notes: text("notes"),
source: text("source"), // null = entered manually; "tailscale" = auto-synced from a Tailscale integration
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
updatedAt: text("updated_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Integration credentials (encrypted API tokens) ─────────────────────────
export const integrationCredentials = sqliteTable("integration_credentials", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(),
encryptedSecret: text("encrypted_secret").notNull(), // AES-256-GCM, see src/crypto.ts
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── DNS providers + record cache (ported from Sloth Manager) ──────────────
export const dnsProviderTypes = [
"cloudflare",
"loopia",
"pihole",
"azure",
"cpanel",
"technitium",
] as const;
export type DnsProviderType = (typeof dnsProviderTypes)[number];
export const dnsProviders = sqliteTable("dns_providers", {
id: integer("id").primaryKey({ autoIncrement: true }),
providerType: text("provider_type").$type<DnsProviderType>().notNull(),
name: text("name").notNull(),
credentialId: integer("credential_id").references(() => integrationCredentials.id, {
onDelete: "set null",
}),
config: text("config"), // JSON: non-secret provider config (base URL, zone list, etc.)
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
export const dnsZonesCache = sqliteTable(
"dns_zones_cache",
{
id: integer("id").primaryKey({ autoIncrement: true }),
providerId: integer("provider_id")
.notNull()
.references(() => dnsProviders.id, { onDelete: "cascade" }),
zoneId: text("zone_id").notNull(), // provider-specific zone identifier
zoneName: text("zone_name").notNull(),
syncedAt: text("synced_at"),
},
(table) => [uniqueIndex("dns_zones_cache_provider_zone_idx").on(table.providerId, table.zoneId)],
);
export const dnsRecordsCache = sqliteTable("dns_records_cache", {
id: integer("id").primaryKey({ autoIncrement: true }),
providerId: integer("provider_id")
.notNull()
.references(() => dnsProviders.id, { onDelete: "cascade" }),
zoneId: text("zone_id").notNull(),
recordId: text("record_id").notNull(), // provider-specific record identifier
type: text("type").notNull(), // A, AAAA, CNAME, TXT, MX, ...
name: text("name").notNull(),
content: text("content").notNull(),
ttl: integer("ttl"),
priority: integer("priority"),
proxied: integer("proxied", { mode: "boolean" }),
});
// ─── Servers & scheduled tasks (ported from Schedule Task Manager) ─────────
export const proxmoxGuestTypes = ["qemu", "lxc"] as const;
export type ProxmoxGuestTypeCol = (typeof proxmoxGuestTypes)[number];
export const servers = sqliteTable("servers", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(),
hostname: text("hostname"),
osType: text("os_type").notNull().default("linux"),
description: text("description"),
apiTokenHash: text("api_token_hash").notNull(),
apiTokenPrefix: text("api_token_prefix").notNull(),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
lastSeenAt: text("last_seen_at"),
// Agent-reported hardware/network snapshot — updated on every agent report.
ipAddresses: text("ip_addresses"), // JSON string[]
cpuModel: text("cpu_model"),
cpuCores: integer("cpu_cores"),
cpuLoadPercent: real("cpu_load_percent"),
memTotalBytes: integer("mem_total_bytes"),
memUsedBytes: integer("mem_used_bytes"),
disks: text("disks"), // JSON string: {mount, sizeBytes, usedBytes}[]
listeningPorts: text("listening_ports"), // JSON string: {protocol, port, address, process}[] — what the agent sees bound on the host
lastPortScan: text("last_port_scan"), // JSON string: summary of the most recent network scan from this app
tags: text("tags"), // JSON string: string[] — free-form labels for grouping and filtering, normalized by services/serverTags
// Optional link to a Proxmox VM/LXC — set by an admin, not the agent. The "set null" below is what this file asks for,
// but migration 0001 created the column without it, so the database itself has no ON DELETE rule here: deleting an
// integration clears these columns in routes/integrations.ts instead. (See DATABASE.md.)
proxmoxIntegrationId: integer("proxmox_integration_id").references(() => integrations.id, {
onDelete: "set null",
}),
proxmoxNode: text("proxmox_node"),
proxmoxGuestType: text("proxmox_guest_type").$type<ProxmoxGuestTypeCol>(),
proxmoxVmid: integer("proxmox_vmid"),
// Not every server is a Proxmox guest (bare-metal boxes, other hosts) — an
// admin can hide the "Proxmox link" card on this server's detail page
// rather than seeing an irrelevant option on every server. Ignored (the
// card always shows) once a server IS actually linked, so unlinking stays
// reachable.
hideProxmoxLink: integer("hide_proxmox_link", { mode: "boolean" }).notNull().default(false),
// The server this one runs on (a VM on its host), set by an admin. Null means "work it out": a guest linked to a Proxmox node runs on
// the server named after that node. When the parent stops reporting, this server's own offline alert is folded under the parent's.
parentServerId: integer("parent_server_id"),
// An admin said this server runs on nothing, so the automatic guess from its Proxmox node is not used for it.
noParent: integer("no_parent", { mode: "boolean" }).notNull().default(false),
// What the agent says is waiting to be installed, as JSON: {manager, count, security, rebootRequired, reportedAt}. Null until it reports.
pendingUpdates: text("pending_updates"),
// When updates were first seen waiting (and none were before) — how long the oldest has been waiting. Null when none are.
updatesPendingSince: text("updates_pending_since"),
// What the agent says about the machine's own health, as JSON: {failedUnits, smart, zfs, reportedAt} — see services/hostHealth.ts. Null until it says.
hostHealth: text("host_health"),
// What the agent says it could not collect, as JSON: {items: [{check, status, reason?, detail?}], reportedAt} — see services/agentDiagnostics.ts. Null until an agent that can say so has.
agentDiagnostics: text("agent_diagnostics"),
// The ports this server was listening on when its agent first said so, as a JSON array like ["tcp:22","tcp:443"]. A port that is listening later and is
// not in this list, and not noted on the Ports page, is a "new port" (services/newPorts.ts). Null until the first report that carries ports.
portBaseline: text("port_baseline"),
// What the machine runs, as its agent says (agent 7 and later): the distribution's id ("ubuntu", "debian", "proxmox-ve", "windows"), its pretty name and its release
// (for Windows, the build number). What services/osLifecycle.ts works out when its support ends from.
osId: text("os_id"),
osName: text("os_name"),
osVersion: text("os_version"),
// What the machine is, as its firmware says (agents report it): maker, model and serial number. Used to fill in the inventory.
hwManufacturer: text("hw_manufacturer"),
hwModel: text("hw_model"),
hwSerial: text("hw_serial"),
// This server's own alert thresholds, as JSON: {serverOfflineMinutes, diskUsagePercent, diskForecastDays, backupStaleHours, mounts: {"/data": {percent, ignore}}} — see
// services/serverThresholds.ts. Whatever isn't there follows Settings. Null when it follows Settings entirely.
thresholds: text("thresholds"),
// Which version of the agent script is running on it, as the agent says in each report (see agent/*/report-tasks.*). Null until it says:
// an agent that predates the number being reported is version 1.
agentVersion: integer("agent_version"),
});
export const scheduledTasks = sqliteTable("scheduled_tasks", {
id: integer("id").primaryKey({ autoIncrement: true }),
serverId: integer("server_id")
.notNull()
.references(() => servers.id, { onDelete: "cascade" }),
scheduleType: text("schedule_type").notNull(), // 'cron' | 'systemd_timer' | 'windows_task' | 'docker' | 'backup' | 'update' | 'n8n_workflow' | 'manual'
origin: text("origin").notNull().default("agent"), // 'agent' | 'manual' — manual rows are never touched by agent sync
name: text("name").notNull(),
command: text("command"),
scheduleExpression: text("schedule_expression"),
source: text("source"),
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
nextRunAt: text("next_run_at"),
rawMetadata: text("raw_metadata"),
isStale: integer("is_stale", { mode: "boolean" }).notNull().default(false),
firstSeenAt: text("first_seen_at")
.notNull()
.default(sql`(current_timestamp)`),
lastSeenAt: text("last_seen_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Server links — admin-page bookmarks per server (Dockge, Webmin, Cockpit, etc.) ─
export const serverLinks = sqliteTable("server_links", {
id: integer("id").primaryKey({ autoIncrement: true }),
serverId: integer("server_id")
.notNull()
.references(() => servers.id, { onDelete: "cascade" }),
label: text("label").notNull(),
url: text("url").notNull(),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Live integrations (Proxmox, Synology, Semaphore, Tailscale, Gitea, Dockhand) ─
export const integrationTypes = [
"proxmox",
"synology",
"semaphore",
"tailscale",
"gitea",
"dockhand",
"uptimekuma",
"phpipam",
"pbs",
"osticket",
"unifi",
"npm",
"homeassistant",
"ups",
] as const;
export type IntegrationType = (typeof integrationTypes)[number];
export const integrations = sqliteTable("integrations", {
id: integer("id").primaryKey({ autoIncrement: true }),
type: text("type").$type<IntegrationType>().notNull(),
name: text("name").notNull(),
baseUrl: text("base_url").notNull(),
credentialId: integer("credential_id").references(() => integrationCredentials.id, {
onDelete: "set null",
}),
config: text("config"), // JSON: per-type non-secret config (tailnet name, node name, etc.)
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// Network equipment read from a UniFi controller (switches, access points, gateways), refreshed every few minutes by services/unifiSync.ts. A device is a node
// in the dependency map ("device:<id>"), like a server, and raises an "offline" alert when the controller has not seen it online for a while.
export const networkDevices = sqliteTable(
"network_devices",
{
id: integer("id").primaryKey({ autoIncrement: true }),
integrationId: integer("integration_id")
.notNull()
.references(() => integrations.id, { onDelete: "cascade" }),
externalId: text("external_id").notNull(), // the MAC address, lower case: the one thing both of UniFi's APIs give for every device
siteName: text("site_name"),
name: text("name").notNull(),
model: text("model"),
kind: text("kind").$type<"gateway" | "switch" | "access_point" | "other">().notNull().default("other"),
ip: text("ip"),
mac: text("mac"),
state: text("state").$type<"online" | "offline" | "updating" | "pending" | "other">().notNull().default("other"),
uptimeSeconds: integer("uptime_seconds"),
firmware: text("firmware"),
firmwareUpdatable: integer("firmware_updatable", { mode: "boolean" }).notNull().default(false),
uplinkExternalId: text("uplink_external_id"), // the MAC of the device this one is connected through, when the controller says
// When the controller first stopped seeing it online, kept until it is online again; the offline alert counts from here.
offlineSince: text("offline_since"),
lastOnlineAt: text("last_online_at"),
firstSeenAt: text("first_seen_at").notNull(),
updatedAt: text("updated_at").notNull(),
},
(t) => [uniqueIndex("network_devices_unique").on(t.integrationId, t.externalId)],
);
// Which server is plugged into which network device, worked out on every read from what the controller says is connected (matched by the server's IP address).
// A server needs the device it is connected through, as far as the dependency map is concerned.
export const networkServerLinks = sqliteTable(
"network_server_links",
{
id: integer("id").primaryKey({ autoIncrement: true }),
integrationId: integer("integration_id")
.notNull()
.references(() => integrations.id, { onDelete: "cascade" }),
serverId: integer("server_id")
.notNull()
.references(() => servers.id, { onDelete: "cascade" }),
deviceExternalId: text("device_external_id").notNull(), // the MAC of the switch or access point
clientMac: text("client_mac").notNull(),
port: integer("port"), // the switch port, when the controller says (the classic API does)
wired: integer("wired", { mode: "boolean" }).notNull().default(true),
updatedAt: text("updated_at").notNull(),
},
(t) => [uniqueIndex("network_server_links_unique").on(t.integrationId, t.serverId, t.clientMac)],
);
// The networks (VLANs) and Wi-Fi names (SSIDs) a UniFi controller has set up, kept beside the devices. Passphrases are never read.
export const networkSegments = sqliteTable(
"network_segments",
{
id: integer("id").primaryKey({ autoIncrement: true }),
integrationId: integer("integration_id")
.notNull()
.references(() => integrations.id, { onDelete: "cascade" }),
kind: text("kind").$type<"network" | "ssid">().notNull(),
externalId: text("external_id").notNull(),
siteName: text("site_name"),
name: text("name").notNull(),
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
vlanId: integer("vlan_id"),
subnet: text("subnet"), // a network's address range, e.g. 192.168.10.1/24
purpose: text("purpose"), // a network: corporate, guest, …
security: text("security"), // an SSID: wpa2, wpa3, open, …
networkName: text("network_name"), // an SSID: the network its clients land on
updatedAt: text("updated_at").notNull(),
},
(t) => [uniqueIndex("network_segments_unique").on(t.integrationId, t.kind, t.externalId)],
);
// A port on a server that's either been seen open (by a scan or the agent) or that someone wrote a note about.
// Rows exist only while they carry information: an open port, or one with a label/comment ("reserved").
export const serverPorts = sqliteTable(
"server_ports",
{
id: integer("id").primaryKey({ autoIncrement: true }),
serverId: integer("server_id")
.notNull()
.references(() => servers.id, { onDelete: "cascade" }),
port: integer("port").notNull(),
protocol: text("protocol").$type<"tcp" | "udp">().notNull().default("tcp"),
label: text("label"),
comment: text("comment"),
// True when the last network scan connected to it. The agent's view is stored on the server row instead.
open: integer("open", { mode: "boolean" }).notNull().default(false),
lastSeenOpenAt: text("last_seen_open_at"),
updatedAt: text("updated_at")
.notNull()
.default(sql`(current_timestamp)`),
},
(t) => [uniqueIndex("server_ports_unique").on(t.serverId, t.port, t.protocol)],
);
// A manually-recorded port opening on something this app doesn't monitor directly — a router's port forward, an
// edge firewall rule, a cloud provider's security group, etc. Distinct from serverPorts (which is what a server
// itself, or a scan of it, reports): this is what someone tells the app is open further out on the network path,
// for the same reason people keep a spreadsheet of "what did I open on the router and why."
export const portForwards = sqliteTable("port_forwards", {
id: integer("id").primaryKey({ autoIncrement: true }),
label: text("label").notNull(),
externalPort: integer("external_port").notNull(),
protocol: text("protocol").$type<"tcp" | "udp">().notNull().default("tcp"),
// Optional link to a tracked server this forward points at; "destination" covers anything else (a bare IP,
// an untracked device) or extra detail alongside a linked server.
serverId: integer("server_id").references(() => servers.id, { onDelete: "set null" }),
destination: text("destination"),
// The port it's actually forwarded to, when NAT changes it (a router forwarding external 8443 to internal 443).
internalPort: integer("internal_port"),
// Free text: where this rule actually lives ("Home router", "OPNsense WAN rule", "Cloudflare Tunnel") — this
// app has no integration with any firewall/router, so it can't verify or manage the rule, only record it.
source: text("source"),
comment: text("comment"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
updatedAt: text("updated_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Domain registrations ───────────────────────────────────────────────────
export const domainOrigins = ["manual", "zone"] as const;
export type DomainOrigin = (typeof domainOrigins)[number];
// A registered domain whose expiry we track. "zone" rows are created from the DNS zones already synced from the
// providers (and removed again when the zone goes away); "manual" rows were typed in — for domains whose DNS lives elsewhere.
export const domains = sqliteTable("domains", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull().unique(), // the registrable domain, lowercase ASCII
origin: text("origin").$type<DomainOrigin>().notNull().default("manual"),
expiresAt: text("expires_at"), // YYYY-MM-DD (UTC), as reported by the registry
registrar: text("registrar"),
lookupSource: text("lookup_source"), // "rdap" | "whois"
lastCheckedAt: text("last_checked_at"),
lastCheckedOkAt: text("last_checked_ok_at"),
lastCheckError: text("last_check_error"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Consistency report ─────────────────────────────────────────────────────
// Findings someone has looked at and decided are fine (a DNS record that intentionally points elsewhere, a Docker bridge
// address, ...). Keyed by the finding's stable key so it stays ignored across runs.
export const consistencyIgnores = sqliteTable("consistency_ignores", {
id: integer("id").primaryKey({ autoIncrement: true }),
key: text("key").notNull().unique(),
title: text("title").notNull(), // what the finding said when it was ignored, so the list still makes sense once it's gone
reason: text("reason"),
createdBy: text("created_by"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Tag catalogue ──────────────────────────────────────────────────────────
// Tags themselves live on the servers that carry them (servers.tags). A row here adds two things a server can't: a tag
// that exists before anything uses it (so it's offered when tagging), and a chosen colour. A defined tag is kept until an
// admin deletes it, even with no server using it; a tag with no row is simply one that's in use and has an automatic colour.
export const tagDefinitions = sqliteTable("tag_definitions", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull().unique(), // normalised, as in services/serverTags
color: text("color"), // "#rrggbb"; null = automatic
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Tickets opened for alerts ──────────────────────────────────────────────
export const alertTicketStatuses = ["pending", "open", "baseline"] as const;
export type AlertTicketStatus = (typeof alertTicketStatuses)[number];
// What the ticket feature remembers about each problem it has seen, so one problem opens one ticket however many checks see it.
// A row is one *occurrence*: when the alert clears and later returns, that is a new row. Alert ids (e.g. "disk:server:3:/") are the
// stable keys the Alerts page already uses, so they aren't a foreign key to anything.
export const alertTickets = sqliteTable(
"alert_tickets",
{
id: integer("id").primaryKey({ autoIncrement: true }),
alertKey: text("alert_key").notNull(),
// pending = seen, but not yet in enough checks in a row to open a ticket (so a blip that fixes itself never does)
// open = a ticket was opened for it (ticket_number says which)
// baseline = it was already there when the feature was switched on and "existing problems" is set to be left alone
status: text("status").$type<AlertTicketStatus>().notNull(),
seenCount: integer("seen_count").notNull().default(1),
integrationId: integer("integration_id").references(() => integrations.id, { onDelete: "set null" }),
ticketNumber: text("ticket_number"), // osTicket's own ticket number; null unless status is "open"
grouped: integer("grouped", { mode: "boolean" }).notNull().default(false), // part of a summary ticket covering several alerts
severity: text("severity").notNull(),
message: text("message").notNull(), // what the alert said when it was first recorded
firstSeenAt: text("first_seen_at").notNull(), // ISO
lastSeenAt: text("last_seen_at").notNull(), // ISO
ticketedAt: text("ticketed_at"), // ISO; when the ticket was opened
clearedAt: text("cleared_at"), // ISO; null while the alert is still active
},
(t) => [index("alert_tickets_key_idx").on(t.alertKey)],
);
// ─── Share links: a read-only status board anyone with the address can open ─
export const shareLinkDetails = ["summary", "names"] as const;
export type ShareLinkDetail = (typeof shareLinkDetails)[number];
// What a link opens: the wall display (how things are, for a TV), a status page (is each of the things I chose working, for people at home), or
// a calendar feed (what is coming up, for a phone's calendar to subscribe to).
export const shareLinkKinds = ["wall", "status", "calendar"] as const;
export type ShareLinkKind = (typeof shareLinkKinds)[number];
// A link to the wall display that needs no sign-in, for a TV in the hall or someone who only wants to know if things are up. Only a hash
// of the secret part of the address is kept (like an agent token), so it can't be read back out of the database or a backup.
export const shareLinks = sqliteTable("share_links", {
id: integer("id").primaryKey({ autoIncrement: true }),
label: text("label").notNull(), // what it is for, e.g. "Hall TV"
tokenHash: text("token_hash").notNull().unique(),
tokenPrefix: text("token_prefix").notNull(), // the first characters, to tell links apart in the list
// summary = how things are, in numbers; names = also the names of what is wrong, in maintenance, and the integrations
detail: text("detail").$type<ShareLinkDetail>().notNull().default("summary"),
kind: text("kind").$type<ShareLinkKind>().notNull().default("wall"),
// A status page's own heading and an optional announcement under it ("Movies are being updated tonight"). Unused by a wall.
title: text("title"),
message: text("message"),
createdBy: text("created_by"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
expiresAt: text("expires_at"), // ISO; null = never
lastUsedAt: text("last_used_at"), // ISO
});
// What a status page shows, in order: each with the name people will recognise, and what it points at.
export const statusItemKinds = ["server", "integration", "monitor"] as const;
export type StatusItemKind = (typeof statusItemKinds)[number];
export const statusItems = sqliteTable(
"status_items",
{
id: integer("id").primaryKey({ autoIncrement: true }),
linkId: integer("link_id")
.notNull()
.references(() => shareLinks.id, { onDelete: "cascade" }),
position: integer("position").notNull().default(0),
label: text("label").notNull(),
kind: text("kind").$type<StatusItemKind>().notNull(),
targetId: integer("target_id").notNull(), // the server, the integration, or the Uptime Kuma a monitor belongs to — a plain reference, not a foreign key
monitorId: text("monitor_id"), // Uptime Kuma's id for the monitor (kind = monitor)
},
(t) => [index("status_items_link_idx").on(t.linkId, t.position)],
);
// ─── Recurring maintenance ──────────────────────────────────────────────────
// "Every Sunday 02:00–04:00 on these servers": a schedule kept here, turned into ordinary maintenance windows a week ahead (each marked
// `schedule:<id>:<date>` in maintenance_windows.source). The windows are what silence alerts; the schedule only says when they come.
export const maintenanceSchedules = sqliteTable("maintenance_schedules", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(), // e.g. "Patch night"
reason: text("reason"),
// JSON: {type: "server" | "integration" | "dns_provider", id: number}[] — polymorphic, so no foreign key; a deleted target is skipped.
targets: text("targets").notNull(),
days: text("days").notNull(), // JSON: weekdays it happens on, 0 = Sunday … 6 = Saturday
startTime: text("start_time").notNull(), // "HH:MM" on the clock of `timezone`
durationMinutes: integer("duration_minutes").notNull(),
timezone: text("timezone").notNull(), // IANA name, so "02:00" stays 02:00 across summer and winter time
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
createdBy: text("created_by"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Runbooks: what to do when something is wrong ───────────────────────────
// Notes attached to a server, integration or DNS provider — "if this is down, check the UPS first" — shown on its page and next to alerts
// about it. A runbook can be for one kind of alert only (`category`, an alert category such as "disk"), or for everything about the thing.
export const runbooks = sqliteTable(
"runbooks",
{
id: integer("id").primaryKey({ autoIncrement: true }),
targetType: text("target_type").$type<MaintenanceTargetType>().notNull(),
targetId: integer("target_id").notNull(), // polymorphic, like maintenance_windows — no FK; one whose target was deleted is simply not shown
title: text("title").notNull(),
body: text("body").notNull(),
category: text("category"), // null = any alert about the target
updatedBy: text("updated_by"),
createdAt: text("created_at").notNull(), // ISO
updatedAt: text("updated_at").notNull(), // ISO
},
(t) => [index("runbooks_target_idx").on(t.targetType, t.targetId)],
);
// ─── Acknowledgements and incidents ─────────────────────────────────────────
// "I'm on it" for one alert — see services/alertAcks.ts. Keyed by the alert's stable id (not a foreign key to anything); gone once the alert has been.
export const alertAcks = sqliteTable(
"alert_acks",
{
id: integer("id").primaryKey({ autoIncrement: true }),
alertKey: text("alert_key").notNull(),
note: text("note").notNull().default(""),
assigneeUserId: integer("assignee_user_id").references(() => users.id, { onDelete: "set null" }),
assigneeName: text("assignee_name"), // as it was when handed over, so it still reads if the user is removed
ackedBy: text("acked_by").notNull(),
ackedAt: text("acked_at").notNull(), // ISO
until: text("until"), // ISO; null = until the alert is gone
lastSeenAt: text("last_seen_at").notNull(), // ISO; the last time the alert was there
},
(t) => [uniqueIndex("alert_acks_key_idx").on(t.alertKey)],
);
// One time an alert was raised and later went away — see services/incidents.ts. When the same alert comes back it is a new row.
export const alertIncidents = sqliteTable(
"alert_incidents",
{
id: integer("id").primaryKey({ autoIncrement: true }),
alertKey: text("alert_key").notNull(),
severity: text("severity").notNull(), // as it is now (or was when it ended)
peakSeverity: text("peak_severity").notNull(),
category: text("category").notNull(),
source: text("source").notNull(),
message: text("message").notNull(), // the latest wording
link: text("link"),
targetType: text("target_type"), // server | integration | dns_provider, when the alert is about one of those
targetId: integer("target_id"),
targetName: text("target_name"),
causedBy: text("caused_by"), // the host whose outage this was folded under
openedAt: text("opened_at").notNull(), // ISO
resolvedAt: text("resolved_at"), // ISO; null while it is open
lastSeenAt: text("last_seen_at").notNull(), // ISO
missingSince: text("missing_since"), // ISO; set while it has been absent from the last look(s), before it is called over
escalatedStep: integer("escalated_step").notNull().default(0), // the highest escalation step already sent for this incident (0 = none)
escalatedAt: text("escalated_at"), // ISO; when that was
},
(t) => [index("alert_incidents_key_idx").on(t.alertKey), index("alert_incidents_opened_idx").on(t.openedAt), index("alert_incidents_target_idx").on(t.targetType, t.targetId)],
);
export const incidentNotes = sqliteTable(
"incident_notes",
{
id: integer("id").primaryKey({ autoIncrement: true }),
incidentId: integer("incident_id")
.notNull()
.references(() => alertIncidents.id, { onDelete: "cascade" }),
author: text("author").notNull(),
body: text("body").notNull(),
createdAt: text("created_at").notNull(), // ISO
},
(t) => [index("incident_notes_incident_idx").on(t.incidentId)],
);
// ─── Update runs: apply a server's updates and see it through ──────────────
// A playbook run in Semaphore for one server, wrapped in a maintenance window and followed until the server reports again — see
// services/updateRuns.ts. status: running | waiting_for_host | done | failed | cancelled.
export const updateRuns = sqliteTable(
"update_runs",
{
id: integer("id").primaryKey({ autoIncrement: true }),
serverId: integer("server_id")
.notNull()
.references(() => servers.id, { onDelete: "cascade" }),
integrationId: integer("integration_id").notNull(), // the Semaphore integration; no FK — one removed later leaves the history readable
projectId: integer("project_id").notNull(),
templateId: integer("template_id").notNull(),
templateName: text("template_name").notNull(),
hostLimit: text("host_limit").notNull(), // ansible's --limit
taskId: integer("task_id"),
taskStatus: text("task_status"), // Semaphore's own word for the run
windowId: integer("window_id"), // the maintenance window put round it
windowCreated: integer("window_created", { mode: "boolean" }).notNull().default(false), // false if it only extended one that was already there (which is then left alone)
status: text("status").notNull(),
message: text("message"),
startedBy: text("started_by"),
startedAt: text("started_at").notNull(), // ISO
taskEndedAt: text("task_ended_at"), // ISO — when the playbook finished
hostReportedAt: text("host_reported_at"), // ISO — the report that came after it
finishedAt: text("finished_at"), // ISO
updatesBefore: integer("updates_before"),
updatesAfter: integer("updates_after"),
rebootRequired: integer("reboot_required", { mode: "boolean" }).notNull().default(false),
pollErrors: integer("poll_errors").notNull().default(0),
},
(t) => [index("update_runs_server_idx").on(t.serverId, t.startedAt), index("update_runs_status_idx").on(t.status)],
);
// ─── Patch plans: updates, on a schedule, one server at a time ─────────────
// "Sundays at 02:00, the servers tagged lab, one at a time, stop at the first failure." A plan only says when, to whom and how; each server is updated by an
// ordinary update run (services/updateRuns.ts), and the plan waits for it to finish before the next — see services/patchPlans.ts.
export const patchPlans = sqliteTable("patch_plans", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(),
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
days: text("days").notNull(), // JSON: weekdays, 0 = Sunday … 6 = Saturday
startTime: text("start_time").notNull(), // "HH:MM" on the clock of `timezone`
timezone: text("timezone").notNull(),
tags: text("tags").notNull().default("[]"), // JSON string[]: servers that have any of these tags
serverIds: text("server_ids").notNull().default("[]"), // JSON number[]: and these servers by name, whatever their tags
integrationId: integer("integration_id").notNull(), // the Semaphore integration; no FK, like update runs
projectId: integer("project_id").notNull(),
templateId: integer("template_id").notNull(),
templateName: text("template_name").notNull(),
limitFrom: text("limit_from").notNull().default("name"), // what ansible's --limit is for a server: its name here, or its host name
stopOnFailure: integer("stop_on_failure", { mode: "boolean" }).notNull().default(true),
onlyWithUpdates: integer("only_with_updates", { mode: "boolean" }).notNull().default(true), // leave out a server that has nothing waiting
silenceDependents: integer("silence_dependents", { mode: "boolean" }).notNull().default(true), // what depends on a server is silenced while it is updated
windowMinutes: integer("window_minutes").notNull().default(90), // at most this long under maintenance per server
lastRunDate: text("last_run_date"), // the local day (YYYY-MM-DD) it last started on — so it starts once a day, even if the app is restarted
createdBy: text("created_by"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// One time a plan ran, and how it went for each server: items is JSON [{serverId, name, status, updateRunId, message, windowIds}].
export const patchPlanRuns = sqliteTable(
"patch_plan_runs",
{
id: integer("id").primaryKey({ autoIncrement: true }),
planId: integer("plan_id")
.notNull()
.references(() => patchPlans.id, { onDelete: "cascade" }),
planName: text("plan_name").notNull(), // as it was, so a renamed plan's history still reads right
trigger: text("trigger").notNull(), // schedule | manual
startedBy: text("started_by"),
status: text("status").notNull(), // running | done | failed | cancelled
message: text("message"),
items: text("items").notNull().default("[]"),
startedAt: text("started_at").notNull(), // ISO
finishedAt: text("finished_at"), // ISO
},
(t) => [index("patch_plan_runs_plan_idx").on(t.planId, t.startedAt), index("patch_plan_runs_status_idx").on(t.status)],
);
// ─── The monthly report's long memory ───────────────────────────────────────
// One row per endpoint check per day: how many times it was asked, how many answered, and the answer times — kept for years, where the individual
// results are kept for two weeks. What the monthly report's availability is worked from (services/endpointChecks.ts).
export const endpointDaily = sqliteTable(
"endpoint_daily",
{
checkId: integer("check_id")
.notNull()
.references(() => endpointChecks.id, { onDelete: "cascade" }),
day: text("day").notNull(), // YYYY-MM-DD, UTC
total: integer("total").notNull().default(0),
ok: integer("ok").notNull().default(0),
msSum: integer("ms_sum").notNull().default(0), // of the answers that were good and timed
msCount: integer("ms_count").notNull().default(0),
},
(t) => [primaryKey({ columns: [t.checkId, t.day] })],
);
// The same, by the hour: how many times a check was asked in that hour, how many answered, and the answer times — kept a few months, between the individual
// results (two weeks) and the daily figures (years), so an answer-time chart can reach back beyond two weeks without a point for every check.
export const endpointHourly = sqliteTable(
"endpoint_hourly",
{
checkId: integer("check_id")
.notNull()
.references(() => endpointChecks.id, { onDelete: "cascade" }),
hour: text("hour").notNull(), // ISO, the start of the hour (UTC)
total: integer("total").notNull().default(0),
ok: integer("ok").notNull().default(0),
msSum: integer("ms_sum").notNull().default(0),
msCount: integer("ms_count").notNull().default(0),
msMax: integer("ms_max").notNull().default(0),
},
(t) => [primaryKey({ columns: [t.checkId, t.hour] })],
);
// A certificate, domain registration or secret whose expiry moved later: it was renewed. Written when the app sees it happen, so it only goes back
// as far as the version that began watching (services/renewals.ts).
export const renewals = sqliteTable(
"renewals",
{
id: integer("id").primaryKey({ autoIncrement: true }),
kind: text("kind").notNull(), // certificate | domain | secret
subject: text("subject").notNull(), // its name, as it was
at: text("at").notNull(), // ISO — when it was seen
fromDate: text("from_date").notNull(), // YYYY-MM-DD — the expiry before
toDate: text("to_date").notNull(), // YYYY-MM-DD — and after
},
(t) => [index("renewals_at_idx").on(t.at)],
);
// ─── Inventory: the hardware behind it all ──────────────────────────────────
export const assetKinds = ["server", "storage", "network", "power", "client", "other"] as const;
export type AssetKind = (typeof assetKinds)[number];
// A piece of hardware: what it is, when it was bought, how long it is covered, where it sits and what it draws. Optionally the server it is.
export const assets = sqliteTable("assets", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(),
kind: text("kind").$type<AssetKind>().notNull().default("other"),
manufacturer: text("manufacturer"),
model: text("model"),
serial: text("serial"),
purchaseDate: text("purchase_date"), // YYYY-MM-DD
purchasePrice: real("purchase_price"), // in the currency set under Settings → Inventory
warrantyUntil: text("warranty_until"), // YYYY-MM-DD
endOfSupport: text("end_of_support"), // YYYY-MM-DD — when the maker stops patching it, or you plan to retire it; what the lifecycle report goes by
replacementCost: real("replacement_cost"), // what replacing it is expected to cost, in the same currency; the lifecycle report falls back to the purchase price
location: text("location"), // room, rack, shelf
rackUnit: text("rack_unit"), // e.g. "U12" or "U12-13"
powerWatts: integer("power_watts"), // typical draw, for the running cost
serverId: integer("server_id"), // the server this is, if it is one — a plain reference (no FK); one whose server is gone shows as unlinked
notes: text("notes"),
createdAt: text("created_at").notNull(), // ISO
updatedAt: text("updated_at").notNull(), // ISO
});
// ─── Metrics tokens: read-only access to /metrics for Prometheus ────────────
// Only a hash of the secret is kept (like an agent token or a share link), so it can't be read back out of the database or a backup.
export const metricsTokens = sqliteTable("metrics_tokens", {
id: integer("id").primaryKey({ autoIncrement: true }),
label: text("label").notNull(), // e.g. "Prometheus"
tokenHash: text("token_hash").notNull().unique(),
tokenPrefix: text("token_prefix").notNull(),
createdBy: text("created_by"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
lastUsedAt: text("last_used_at"), // ISO
});
// ─── Home Assistant: the few things somebody chose to watch ─────────────────
// An entity (a sensor, a binary sensor, a battery, a UPS) that somebody chose to watch on a Home Assistant integration, and the limits that make it an alert.
export const haWatched = sqliteTable(
"ha_watched",
{
id: integer("id").primaryKey({ autoIncrement: true }),
integrationId: integer("integration_id")
.notNull()
.references(() => integrations.id, { onDelete: "cascade" }),
entityId: text("entity_id").notNull(), // "sensor.ups_battery"
name: text("name"), // what to call it here; the entity's own friendly name when null
above: real("above"), // an alert when a numeric value is above this
below: real("below"), // …or below this
createdAt: text("created_at").notNull(),
},
(t) => [uniqueIndex("ha_watched_unique").on(t.integrationId, t.entityId)],
);
// What the last read said about each watched entity. `unavailableSince` is when it was first seen "unavailable" or "unknown", kept until it is not.
export const haEntities = sqliteTable(
"ha_entities",
{
integrationId: integer("integration_id")
.notNull()
.references(() => integrations.id, { onDelete: "cascade" }),
entityId: text("entity_id").notNull(),
friendlyName: text("friendly_name"),
state: text("state").notNull(),
value: real("value"), // the state as a number, when it is one
unit: text("unit"),
deviceClass: text("device_class"),
lastChanged: text("last_changed"),
unavailableSince: text("unavailable_since"),
updatedAt: text("updated_at").notNull(),
},
(t) => [primaryKey({ columns: [t.integrationId, t.entityId] })],
);
// A numeric value of a watched entity at a moment, for the chart: one every few minutes, kept 35 days.
export const haReadings = sqliteTable(
"ha_readings",
{
id: integer("id").primaryKey({ autoIncrement: true }),
integrationId: integer("integration_id")
.notNull()
.references(() => integrations.id, { onDelete: "cascade" }),
entityId: text("entity_id").notNull(),
at: text("at").notNull(), // ISO
value: real("value").notNull(),
},
(t) => [index("ha_readings_lookup_idx").on(t.integrationId, t.entityId, t.at)],
);
// ─── Service-level targets ──────────────────────────────────────────────────
// "99.9 % for Gitea": a target on an endpoint check, a server or an integration, measured over calendar months (services/serviceLevels.ts). The thing measured is a
// plain reference (type and id), not a foreign key: one whose subject is removed is shown as having nothing to measure.
export const serviceLevels = sqliteTable("service_levels", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(),
subjectType: text("subject_type").notNull(), // endpoint | server | integration
subjectId: integer("subject_id").notNull(),
target: real("target").notNull(), // percent, 90–99.999
alert: integer("alert", { mode: "boolean" }).notNull().default(true), // warn when most of the month's error budget is used, and when it is overspent
createdBy: text("created_by"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── UPS ────────────────────────────────────────────────────────────────────
// How a UPS (an integration of type "ups", read over NUT or SNMP by services/upsSync.ts) is right now: one row each, replaced at every read. `updatedAt` is the last
// read that worked; `onBatterySince` is when mains power was lost, kept until it is back.
export const upsState = sqliteTable("ups_state", {
integrationId: integer("integration_id")
.primaryKey()
.references(() => integrations.id, { onDelete: "cascade" }),
model: text("model"),
manufacturer: text("manufacturer"),
statusText: text("status_text").notNull(),
onBattery: integer("on_battery", { mode: "boolean" }).notNull().default(false),
lowBattery: integer("low_battery", { mode: "boolean" }).notNull().default(false),
replaceBattery: integer("replace_battery", { mode: "boolean" }).notNull().default(false),
overload: integer("overload", { mode: "boolean" }).notNull().default(false),
charge: real("charge"),
runtimeSeconds: integer("runtime_seconds"),
loadPercent: real("load_percent"),
inputVoltage: real("input_voltage"),
outputVoltage: real("output_voltage"),
onBatterySince: text("on_battery_since"), // ISO
updatedAt: text("updated_at").notNull(), // ISO
});
// A UPS at a moment, for the charts: one every five minutes, and every minute while it runs on battery. Kept 35 days.
export const upsReadings = sqliteTable(
"ups_readings",
{
id: integer("id").primaryKey({ autoIncrement: true }),
integrationId: integer("integration_id")
.notNull()
.references(() => integrations.id, { onDelete: "cascade" }),
at: text("at").notNull(), // ISO
charge: real("charge"),
runtimeSeconds: integer("runtime_seconds"),
loadPercent: real("load_percent"),
inputVoltage: real("input_voltage"),
onBattery: integer("on_battery", { mode: "boolean" }).notNull().default(false),
},
(t) => [index("ups_readings_lookup_idx").on(t.integrationId, t.at)],
);
// ─── Notes and the to-do list ───────────────────────────────────────────────
// Free-form notes about a server or a network device — what is it, where does it sit, what did I do to it last time — one text per thing, drawn with the same small
// formatting as a runbook. Polymorphic like runbooks and maintenance windows, so no foreign key: the note of something removed is simply not shown.
export const notes = sqliteTable(
"notes",
{
id: integer("id").primaryKey({ autoIncrement: true }),
targetType: text("target_type").$type<"server" | "device">().notNull(),
targetId: integer("target_id").notNull(),
body: text("body").notNull(),
updatedBy: text("updated_by"),
updatedAt: text("updated_at").notNull(), // ISO
},
(t) => [uniqueIndex("notes_target_idx").on(t.targetType, t.targetId)],
);
// Things to do: the small jobs of a homelab ("replace the UPS battery", "move the NAS to the new switch"), with a day they are due and optionally a person and
// a thing they are about. Open ones with a due day are in Coming up; the ones handed to someone are in My work.
export const todos = sqliteTable("todos", {
id: integer("id").primaryKey({ autoIncrement: true }),
title: text("title").notNull(),
detail: text("detail"),
dueDate: text("due_date"), // YYYY-MM-DD
assigneeUserId: integer("assignee_user_id").references(() => users.id, { onDelete: "set null" }),
assigneeName: text("assignee_name"), // as it was when handed over, so it still reads if the person is removed
targetType: text("target_type").$type<"server" | "device">(),
targetId: integer("target_id"),
createdBy: text("created_by"),
createdAt: text("created_at").notNull(), // ISO
doneAt: text("done_at"), // ISO; null while open
doneBy: text("done_by"),
});
// ─── Personal API tokens: read-only access to /api/v1 for scripts and Home Assistant ─────
// One person's own: made by them, shown to them once, and gone when they are. Only a hash of the secret is kept. A token only ever reads (the API has no other verbs),
// and sees what any signed-in person sees.
export const apiTokens = sqliteTable("api_tokens", {
id: integer("id").primaryKey({ autoIncrement: true }),
userId: integer("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
label: text("label").notNull(), // e.g. "Home Assistant"
tokenHash: text("token_hash").notNull().unique(),
tokenPrefix: text("token_prefix").notNull(),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
lastUsedAt: text("last_used_at"), // ISO
expiresAt: text("expires_at"), // ISO; null = until removed
});
// ─── Event webhooks: tell another system when something happens ─────────────
export const webhookEvents = ["alert.opened", "alert.resolved", "maintenance.started", "maintenance.ended"] as const;
export type WebhookEvent = (typeof webhookEvents)[number];
// A URL that gets a signed JSON message for the events it subscribes to — for Home Assistant, n8n, a status board. Separate from the
// chat-style webhook under Settings → Notifications, which carries the same text a person would read.
export const eventWebhooks = sqliteTable("event_webhooks", {
id: integer("id").primaryKey({ autoIncrement: true }),
label: text("label").notNull(),
url: text("url").notNull(),
secret: text("secret"), // encrypted at rest; signs each message (HMAC-SHA256 in X-HLM-Signature)
events: text("events").notNull(), // JSON: WebhookEvent[]
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
createdBy: text("created_by"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
lastAttemptAt: text("last_attempt_at"), // ISO
lastResult: text("last_result"), // "200", or what went wrong
});
// ─── Your own alert rules, storage history and snoozes ──────────────────────
export const alertRuleMetrics = ["cpu", "mem", "disk", "disk_temp"] as const;
export type AlertRuleMetric = (typeof alertRuleMetrics)[number];
// "CPU above 90% for 15 minutes", "a disk is warmer than 55 °C": a limit of the administrator's own, judged for every server (or one, or those with a tag) on the
// same pass as the built-in checks, so it alerts, recovers, flaps, is silenced by maintenance and is routed like them — see services/alertRules.ts.
export const alertRules = sqliteTable("alert_rules", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(),
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
metric: text("metric").$type<AlertRuleMetric>().notNull(),
mount: text("mount"), // for "disk": one mount point; null = every one
operator: text("operator").$type<"above" | "below">().notNull().default("above"),
threshold: real("threshold").notNull(), // percent, or °C for disk_temp
forMinutes: integer("for_minutes").notNull().default(0), // how long it must have held (0 = right now); not used for disk_temp, which is only known as of the last report
severity: text("severity").$type<"warning" | "critical">().notNull().default("warning"),
serverId: integer("server_id"), // one server; null = see tag. A plain reference: a rule for a server that is gone judges nothing.
tag: text("tag"), // servers with this tag; null with a null server = every server
createdBy: text("created_by"),
createdAt: text("created_at").notNull(), // ISO
});
// What each pool of an integration (a Proxmox storage, a Synology volume) looked like, one reading an hour, so it can be forecast the way an agent server's disk is.
export const storageSeries = sqliteTable(
"storage_series",
{
id: integer("id").primaryKey({ autoIncrement: true }),
integrationId: integer("integration_id")
.notNull()
.references(() => integrations.id, { onDelete: "cascade" }),
key: text("key").notNull(), // "proxmox:<node>:storage:<id>", "proxmox:shared:<id>", "proxmox:<node>:rootfs", "synology:<volume>"
label: text("label").notNull(), // "Storage local-lvm on pve1"
latestPercent: real("latest_percent").notNull(),
usedBytes: integer("used_bytes"),
totalBytes: integer("total_bytes"),
updatedAt: text("updated_at").notNull(), // ISO; the last reading
},
(t) => [uniqueIndex("storage_series_key_idx").on(t.integrationId, t.key)],
);
export const storageSamples = sqliteTable(
"storage_samples",
{
id: integer("id").primaryKey({ autoIncrement: true }),
seriesId: integer("series_id")
.notNull()
.references(() => storageSeries.id, { onDelete: "cascade" }),
at: text("at").notNull(), // ISO
value: real("value").notNull(), // percent used
},
(t) => [index("storage_samples_series_idx").on(t.seriesId, t.at)],
);
// "Remind me tomorrow at 09:00": an alert hidden until a time, and announced again then if it is still there — see services/alertSnoozes.ts. Keyed like an acknowledgement.
export const alertSnoozes = sqliteTable(
"alert_snoozes",
{
id: integer("id").primaryKey({ autoIncrement: true }),
alertId: text("alert_id").notNull(), // the alert's id on the Alerts page
conditionKey: text("condition_key").notNull(), // the key behind it, which the notifications carry
message: text("message").notNull(), // what it said, for the reminder
until: text("until").notNull(), // ISO
snoozedBy: text("snoozed_by").notNull(),
snoozedAt: text("snoozed_at").notNull(), // ISO
lastSeenAt: text("last_seen_at").notNull(), // ISO; the last time the alert was there
},
(t) => [uniqueIndex("alert_snoozes_alert_idx").on(t.alertId)],
);
// ─── What each event webhook was sent, and how it went ──────────────────────
// One row per message to one webhook (the try and its one retry together), with the exact body so it can be sent again by hand. The last 100 per webhook and no more than two weeks.
export const webhookDeliveries = sqliteTable(
"webhook_deliveries",
{
id: integer("id").primaryKey({ autoIncrement: true }),
webhookId: integer("webhook_id")
.notNull()
.references(() => eventWebhooks.id, { onDelete: "cascade" }),
event: text("event").notNull(),
deliveryId: text("delivery_id").notNull(), // the message's id, which a receiver can use to ignore a repeat
attempts: integer("attempts").notNull().default(1),
ok: integer("ok", { mode: "boolean" }).notNull(),
result: text("result").notNull(), // "200", or what went wrong
body: text("body").notNull(), // the exact JSON that was sent (what the signature covers)
retryOf: integer("retry_of"), // the delivery this one repeats, when somebody pressed Retry
createdAt: text("created_at").notNull(), // ISO
},
(t) => [index("webhook_deliveries_webhook_idx").on(t.webhookId, t.createdAt)],
);