Servers and the agent, backend (2.1.0): join, jobs, schedules, port list, stats, alerts

- Agent API /api/agent/v1: join with a one-time token, then poll, stats,
  report and export upload, all signed with the server's Ed25519 key.
- Jobs signed with a separate job key (HUB_JOB_SIGNING_KEY_FILE) when
  delivered, config sealed to the server; one at a time per server;
  missed when not picked up in their window.
- New install (licence, ports, preflight against the release's env
  template), Proxy done with public URL checks, scheduled / emergency
  (2FA, reason) / batch updates with email and banner, uninstall with
  an encrypted export first (the key is never stored), adopt and
  linking existing installs, purge after 30 days.
- Port list, install defaults, server configuration (encrypted), stats
  per minute / hour with roll-up, server alerts. contracts 1.3.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 13:12:28 +02:00
co-authored by Claude Opus 5.5
parent 9aa06ae894
commit 041461f2b5
20 changed files with 2237 additions and 47 deletions
@@ -0,0 +1,217 @@
-- 2.1.0: servers and the agent (crosscode-platform docs/AGENT-1.0-PLAN.md): servers, join tokens,
-- stats, server alerts, deployments, signed jobs, the port list and exports. Only new tables.
-- CreateEnum
CREATE TYPE "ServerMode" AS ENUM ('church', 'central');
-- CreateEnum
CREATE TYPE "StatGranularity" AS ENUM ('minute', 'hour');
-- CreateEnum
CREATE TYPE "DeploymentStatus" AS ENUM ('installing', 'waiting_for_proxy', 'live', 'failed', 'uninstalling', 'removed');
-- CreateEnum
CREATE TYPE "JobStatus" AS ENUM ('scheduled', 'queued', 'delivered', 'succeeded', 'failed', 'rolled_back', 'refused', 'expired', 'missed', 'cancelled');
-- CreateTable
CREATE TABLE "Server" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"mode" "ServerMode" NOT NULL DEFAULT 'church',
"hostname" TEXT,
"ed25519Key" TEXT NOT NULL,
"x25519Key" TEXT NOT NULL,
"config" TEXT,
"agentVersion" TEXT,
"lastSeenAt" TIMESTAMP(3),
"lastStats" JSONB,
"joinedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"removedAt" TIMESTAMP(3),
"notes" TEXT,
CONSTRAINT "Server_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ServerJoinToken" (
"id" TEXT NOT NULL,
"tokenHash" TEXT NOT NULL,
"name" TEXT NOT NULL,
"mode" "ServerMode" NOT NULL DEFAULT 'church',
"expiresAt" TIMESTAMP(3) NOT NULL,
"usedAt" TIMESTAMP(3),
"serverId" TEXT,
"createdById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ServerJoinToken_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ServerStat" (
"id" TEXT NOT NULL,
"serverId" TEXT NOT NULL,
"at" TIMESTAMP(3) NOT NULL,
"granularity" "StatGranularity" NOT NULL DEFAULT 'minute',
"cpuPercent" DOUBLE PRECISION NOT NULL,
"cpuPeak" DOUBLE PRECISION NOT NULL,
"ramUsedPercent" DOUBLE PRECISION NOT NULL,
"ramPeak" DOUBLE PRECISION NOT NULL,
"ramUsedBytes" BIGINT NOT NULL,
"ramTotalBytes" BIGINT NOT NULL,
"diskUsedPercent" DOUBLE PRECISION NOT NULL,
"load1" DOUBLE PRECISION NOT NULL,
CONSTRAINT "ServerStat_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ServerAlert" (
"id" TEXT NOT NULL,
"serverId" TEXT NOT NULL,
"type" TEXT NOT NULL,
"level" "EventLevel" NOT NULL DEFAULT 'warning',
"message" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"resolvedAt" TIMESTAMP(3),
CONSTRAINT "ServerAlert_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Deployment" (
"id" TEXT NOT NULL,
"serverId" TEXT NOT NULL,
"customerId" TEXT NOT NULL,
"licenceId" TEXT,
"installId" TEXT,
"product" "Product" NOT NULL DEFAULT 'events',
"shortName" TEXT NOT NULL,
"domain" TEXT NOT NULL,
"webPort" INTEGER NOT NULL,
"apiPort" INTEGER NOT NULL,
"timezone" TEXT,
"adminName" TEXT,
"adminEmail" TEXT,
"status" "DeploymentStatus" NOT NULL DEFAULT 'installing',
"version" TEXT,
"liveAt" TIMESTAMP(3),
"removedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Deployment_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Job" (
"id" TEXT NOT NULL,
"serverId" TEXT NOT NULL,
"deploymentId" TEXT,
"type" TEXT NOT NULL,
"args" JSONB NOT NULL,
"status" "JobStatus" NOT NULL DEFAULT 'queued',
"notBefore" TIMESTAMP(3) NOT NULL,
"expiresAt" TIMESTAMP(3) NOT NULL,
"scheduled" BOOLEAN NOT NULL DEFAULT false,
"emergency" BOOLEAN NOT NULL DEFAULT false,
"reason" TEXT,
"batchId" TEXT,
"batchOrder" INTEGER,
"noticeId" TEXT,
"remindedAt" TIMESTAMP(3),
"createdById" TEXT,
"deliveredAt" TIMESTAMP(3),
"finishedAt" TIMESTAMP(3),
"report" JSONB,
"message" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Job_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Port" (
"port" INTEGER NOT NULL,
"serverId" TEXT,
"deploymentId" TEXT,
"role" TEXT NOT NULL,
"note" TEXT,
"releasedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Port_pkey" PRIMARY KEY ("port")
);
-- CreateTable
CREATE TABLE "Export" (
"id" TEXT NOT NULL,
"deploymentId" TEXT,
"data" BYTEA,
"bytes" INTEGER NOT NULL DEFAULT 0,
"expiresAt" TIMESTAMP(3) NOT NULL,
"extended" BOOLEAN NOT NULL DEFAULT false,
"downloadedAt" TIMESTAMP(3),
"deletedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Export_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "ServerJoinToken_tokenHash_key" ON "ServerJoinToken"("tokenHash");
-- CreateIndex
CREATE INDEX "ServerStat_serverId_granularity_at_idx" ON "ServerStat"("serverId", "granularity", "at");
-- CreateIndex
CREATE INDEX "ServerAlert_serverId_resolvedAt_idx" ON "ServerAlert"("serverId", "resolvedAt");
-- CreateIndex
CREATE UNIQUE INDEX "Deployment_installId_key" ON "Deployment"("installId");
-- CreateIndex
CREATE INDEX "Deployment_serverId_idx" ON "Deployment"("serverId");
-- CreateIndex
CREATE UNIQUE INDEX "Deployment_shortName_product_key" ON "Deployment"("shortName", "product");
-- CreateIndex
CREATE INDEX "Job_serverId_status_notBefore_idx" ON "Job"("serverId", "status", "notBefore");
-- CreateIndex
CREATE INDEX "Job_batchId_idx" ON "Job"("batchId");
-- CreateIndex
CREATE INDEX "Job_status_expiresAt_idx" ON "Job"("status", "expiresAt");
-- CreateIndex
CREATE INDEX "Port_serverId_idx" ON "Port"("serverId");
-- AddForeignKey
ALTER TABLE "ServerStat" ADD CONSTRAINT "ServerStat_serverId_fkey" FOREIGN KEY ("serverId") REFERENCES "Server"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ServerAlert" ADD CONSTRAINT "ServerAlert_serverId_fkey" FOREIGN KEY ("serverId") REFERENCES "Server"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Deployment" ADD CONSTRAINT "Deployment_serverId_fkey" FOREIGN KEY ("serverId") REFERENCES "Server"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Deployment" ADD CONSTRAINT "Deployment_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "Customer"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Deployment" ADD CONSTRAINT "Deployment_installId_fkey" FOREIGN KEY ("installId") REFERENCES "Install"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Job" ADD CONSTRAINT "Job_serverId_fkey" FOREIGN KEY ("serverId") REFERENCES "Server"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Job" ADD CONSTRAINT "Job_deploymentId_fkey" FOREIGN KEY ("deploymentId") REFERENCES "Deployment"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Port" ADD CONSTRAINT "Port_serverId_fkey" FOREIGN KEY ("serverId") REFERENCES "Server"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Export" ADD CONSTRAINT "Export_deploymentId_fkey" FOREIGN KEY ("deploymentId") REFERENCES "Deployment"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+244 -30
View File
@@ -26,55 +26,56 @@ model AdminUser {
}
model Customer {
id String @id @default(uuid())
name String
contactName String?
email String?
phone String?
notes String?
id String @id @default(uuid())
name String
contactName String?
email String?
phone String?
notes String?
// Billing (1.7.0). Invoices go to billingEmail, else the site's admin contact, else email.
billingEmail String?
billingEmail String?
// The postal address printed on invoices and statements.
billingAddress String?
billingAddress String?
// A founding church pays the founding price on every tier (35% less) while it stays.
founding Boolean @default(false)
foundingSince DateTime? @db.Date
foundingNote String?
founding Boolean @default(false)
foundingSince DateTime? @db.Date
foundingNote String?
// Hub 2.0: one invoice per customer per period for all its products (moved from Licence).
// none = not invoiced. Invoices are in advance: each covers the period starting on its date.
billingCycle BillingCycle @default(none)
billingCycle BillingCycle @default(none)
// The day billing started; its day of the month is the billing day.
billingStart DateTime? @db.Date
billingStart DateTime? @db.Date
// The start of the next period to invoice (the draft is made 14 days before).
nextInvoiceDate DateTime? @db.Date
nextInvoiceDate DateTime? @db.Date
// The next annual tier review: the first invoice for a period starting on or after it uses
// what each product reports (Events: 12-month event income; App: active members).
reviewDate DateTime? @db.Date
reviewDate DateTime? @db.Date
// Hub 2.0: the church's address, one for all its products (ROADMAP-v3 §10), billed once per
// invoice and never discounted. own_domain R0 · crosscode (<church>.crosscode.co.za) R10 ·
// included (a domain registered in the church's name and renewed by Cross Code) R25.
addressType AddressType @default(own_domain)
addressType AddressType @default(own_domain)
// The domain: hopefamily.co.za, or hopefamily.crosscode.co.za for a Cross Code address.
domain String?
domain String?
// A price per month instead of the option's (e.g. a .com charged at cost), in cents.
addressCustomCents Int?
addressCustomCents Int?
// Domain included: when it's next due for renewal, and the renewal date Joshua was last
// reminded about (30 days before), so he's reminded once per renewal.
domainRenewsOn DateTime? @db.Date
domainRemindedFor DateTime? @db.Date
domainRenewsOn DateTime? @db.Date
domainRemindedFor DateTime? @db.Date
// Hub 2.0 (moved from Licence): the monthly AI spend cap in cents (rand), counted in charged
// rand over all the church's installs. 0 = AI off. And the markup on the real cost, in %; null =
// the Hub default (Settings → AI).
aiMonthlyCapCents Int @default(0)
aiMarkupPercent Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
licences Licence[]
installs Install[]
invoices Invoice[]
payments Payment[]
licenceChanges LicenceChange[]
billingEmails BillingEmail[]
aiMonthlyCapCents Int @default(0)
aiMarkupPercent Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
licences Licence[]
installs Install[]
invoices Invoice[]
payments Payment[]
licenceChanges LicenceChange[]
billingEmails BillingEmail[]
deployments Deployment[]
}
enum LicenceStatus {
@@ -169,6 +170,7 @@ model Install {
heartbeats Heartbeat[]
events InstallEvent[]
aiUsage AiUsage[]
deployment Deployment?
@@index([lastHeartbeatAt])
}
@@ -451,3 +453,215 @@ model DocumentCounter {
key String @id
value Int @default(0)
}
// ─── Servers and the agent (2.1.0, crosscode-platform docs/AGENT-1.0-PLAN.md) ──────────────────
enum ServerMode {
church
central
}
// A server running the crosscode agent. It joined with a one-time token and its two public keys:
// Ed25519 (checks its requests) and X25519 (config is sealed to it). The agent polls; the Hub
// never connects to a server.
model Server {
id String @id
name String
mode ServerMode @default(church)
hostname String?
ed25519Key String
x25519Key String
// Server configuration (§5): database host, port and admin, TRUST_PROXY, … AES-GCM encrypted
// JSON (utils/crypto.js); sealed to the server's key in each job that needs it.
config String?
agentVersion String?
lastSeenAt DateTime?
// The latest stats (crosscode.agent-stats/1), for the Servers page.
lastStats Json?
joinedAt DateTime @default(now())
removedAt DateTime?
notes String?
stats ServerStat[]
jobs Job[]
deployments Deployment[]
ports Port[]
alerts ServerAlert[]
}
// One-time join tokens (Servers → Add server), valid an hour. Only the hash is kept.
model ServerJoinToken {
id String @id @default(uuid())
tokenHash String @unique
name String
mode ServerMode @default(church)
expiresAt DateTime
usedAt DateTime?
serverId String?
createdById String?
createdAt DateTime @default(now())
}
enum StatGranularity {
minute
hour
}
// Server stats: one row a minute for 7 days, then one an hour (average and peak) for 90 days.
model ServerStat {
id String @id @default(uuid())
serverId String
server Server @relation(fields: [serverId], references: [id], onDelete: Cascade)
at DateTime
granularity StatGranularity @default(minute)
cpuPercent Float
cpuPeak Float
ramUsedPercent Float
ramPeak Float
ramUsedBytes BigInt
ramTotalBytes BigInt
diskUsedPercent Float
load1 Float
@@index([serverId, granularity, at])
}
// Open problems on a server (agent silent, disk, RAM, a process restarting, frpc, the central
// checks). Emailed once when they start and once when they clear.
model ServerAlert {
id String @id @default(uuid())
serverId String
server Server @relation(fields: [serverId], references: [id], onDelete: Cascade)
type String
level EventLevel @default(warning)
message String
createdAt DateTime @default(now())
resolvedAt DateTime?
@@index([serverId, resolvedAt])
}
enum DeploymentStatus {
installing
waiting_for_proxy
live
failed
uninstalling
removed
}
// A product installed on a server through the agent (or an existing install linked to it): the
// church's short name, domain and tunnel ports. Linked to its Install once the site registers.
model Deployment {
id String @id @default(uuid())
serverId String
server Server @relation(fields: [serverId], references: [id], onDelete: Restrict)
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
licenceId String?
installId String? @unique
install Install? @relation(fields: [installId], references: [id], onDelete: SetNull)
product Product @default(events)
// Folders, PM2, database and tunnel names on the server: hope → /var/www/sites/hope/events.
shortName String
domain String
webPort Int
apiPort Int
timezone String?
// The church's site admin, for the welcome and update emails.
adminName String?
adminEmail String?
status DeploymentStatus @default(installing)
// The release it runs (from reports and heartbeats).
version String?
liveAt DateTime?
removedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
jobs Job[]
exports Export[]
@@unique([shortName, product])
@@index([serverId])
}
enum JobStatus {
// Waiting for its time (a scheduled update, or a batch's later installs).
scheduled
// Due: handed to the agent on its next poll.
queued
delivered
succeeded
failed
rolled_back
refused
expired
// Its time passed before the agent picked it up: nothing ran.
missed
cancelled
}
// A signed job for a server's agent (crosscode.agent-job/1) and its report.
model Job {
id String @id
serverId String
server Server @relation(fields: [serverId], references: [id], onDelete: Restrict)
deploymentId String?
deployment Deployment? @relation(fields: [deploymentId], references: [id], onDelete: SetNull)
type String
args Json
status JobStatus @default(queued)
notBefore DateTime
expiresAt DateTime
// An update with notice to the church (§8); emergency = at least 15 minutes, with a reason.
scheduled Boolean @default(false)
emergency Boolean @default(false)
reason String?
// A batch runs its jobs one at a time and stops at the first failure.
batchId String?
batchOrder Int?
// The notice (banner) for a scheduled job, removed when it's done or cancelled.
noticeId String?
remindedAt DateTime?
createdById String?
deliveredAt DateTime?
finishedAt DateTime?
// crosscode.agent-report/1 (without the export key).
report Json?
message String?
createdAt DateTime @default(now())
@@index([serverId, status, notBefore])
@@index([batchId])
@@index([status, expiresAt])
}
// The port list (§6): every port frps opens on the central server, unique across servers.
model Port {
port Int @id
serverId String?
server Server? @relation(fields: [serverId], references: [id], onDelete: SetNull)
deploymentId String?
// web, api, or taken (found in use / reserved by hand).
role String
note String?
// Free again 30 days after an uninstall.
releasedAt DateTime?
createdAt DateTime @default(now())
@@index([serverId])
}
// A church's data when it leaves (§9): encrypted on the server with a key only in the emailed
// link, so the Hub stores it but can't read it. Deleted after 30 days (extendable once).
model Export {
id String @id
deploymentId String?
deployment Deployment? @relation(fields: [deploymentId], references: [id], onDelete: SetNull)
data Bytes?
bytes Int @default(0)
expiresAt DateTime
extended Boolean @default(false)
downloadedAt DateTime?
deletedAt DateTime?
createdAt DateTime @default(now())
}