Merge branch 'feat/servers-agent'
This commit is contained in:
@@ -16,6 +16,41 @@ versions follow [Semantic Versioning](https://semver.org/).
|
||||
paid, and the statement shows the refund going back out. Void is allowed when no payment on the
|
||||
invoice is left unrefunded. Migration `20261118120000_payment_refunds` (two new columns).
|
||||
|
||||
Planned as 2.1.0 (crosscode-platform `docs/AGENT-1.0-PLAN.md`, phase 1d). **Before deploying, see
|
||||
`deployment.md` → "Upgrading to 2.1"** (a new job-signing key).
|
||||
|
||||
### Added
|
||||
|
||||
- **Servers**: Add server gives a one-time join command (valid an hour) for the server agent. Each
|
||||
server's page shows CPU and RAM over 24 hours, 7 days and 90 days with spikes marked, disks,
|
||||
versions, PM2 processes, its sites, jobs and alerts, and its configuration (database, TRUST_PROXY;
|
||||
stored encrypted and sent only sealed to that server's key). Stats are kept per minute for 7 days
|
||||
and per hour for 90 days.
|
||||
- **Agent API** (`/api/agent/v1`): join, poll, stats, report and export upload, signed with each
|
||||
server's Ed25519 key. Jobs are signed with a separate job key and built when the agent picks them
|
||||
up; each server gets one job at a time; a job not picked up in its window is **missed** and never
|
||||
runs late.
|
||||
- **New install**: customer, short name, domain, site admin and server (with its free RAM, CPU and
|
||||
sites); the Hub makes the licence, picks two ports from the port list, checks the server's
|
||||
configuration against the release's env template, and the agent installs. The report and the
|
||||
FASTPANEL steps come by email; **Proxy done** checks the public addresses and sends the church its
|
||||
welcome email.
|
||||
- **Updates**: scheduled at least 4 hours ahead, or as an emergency (15 minutes, a reason, 2FA),
|
||||
for one install or a batch that runs one at a time and stops at the first failure. Churches get an
|
||||
email with what's new, a banner, a reminder an hour before, and the outcome.
|
||||
- **Link existing** installs, and move 2.1.x ones onto the monorepo (an `adopt` job).
|
||||
- **Uninstall** (2FA and the short name): the church's data is exported first, encrypted on the
|
||||
server with a key that only travels in the emailed link (the Hub passes it on once and doesn't
|
||||
store it), then the site is removed; the final backup is purged after 30 days (put off once).
|
||||
- **Server alerts**: agent silent, disk over 85%, RAM over 90% for 5 minutes, a process restarting,
|
||||
frpc down, and on the central server frps down or `proxy_bind_addr` missing.
|
||||
- Pages: Servers, Installs, Updates, Jobs (each job's steps and log), Ports & defaults, and the
|
||||
public download page that decrypts an export in the browser.
|
||||
|
||||
### Changed
|
||||
|
||||
- `@crosscode/contracts` 1.3.0 (agent jobs, reports, stats, env templates, church export).
|
||||
|
||||
## [2.0.1] - 2026-11-17
|
||||
|
||||
### Added
|
||||
|
||||
@@ -16,6 +16,14 @@ HUB_ENCRYPTION_KEY=change-me-to-32-or-more-random-characters
|
||||
HUB_SIGNING_KEY_FILE=./keys/hub-signing-key.pem
|
||||
# HUB_SIGNING_KEY=
|
||||
|
||||
# Job-signing key for server agents (2.1.0; Ed25519, separate from the licence key). Create with
|
||||
# `npm run generate-keys -- --job`. Agents pin its public key when they join, so replacing it
|
||||
# means every server has to join again.
|
||||
HUB_JOB_SIGNING_KEY_FILE=./keys/hub-job-key.pem
|
||||
# HUB_JOB_SIGNING_KEY=
|
||||
# The Hub's address as servers reach it (shown in Servers → Add server).
|
||||
HUB_PUBLIC_URL=https://hub.crosscode.co.za
|
||||
|
||||
# Behind a reverse proxy (nginx), so rate limits see real client IPs
|
||||
TRUST_PROXY=1
|
||||
|
||||
|
||||
Generated
+4
-4
@@ -10,7 +10,7 @@
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^1.3.0",
|
||||
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.1.0.tgz",
|
||||
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.3.0.tgz",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"bcryptjs": "^2.4.3",
|
||||
@@ -609,9 +609,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@crosscode/contracts": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "file:vendor/crosscode-contracts-1.1.0.tgz",
|
||||
"integrity": "sha512-k/7fFcjNh79B4la+GUxzh/buFtnM6G+5JPxxKvhXNdlIXvon/45VErzEKYsnDnL8pF3fQHldJcfeFtLm52Q47A==",
|
||||
"version": "1.3.0",
|
||||
"resolved": "file:vendor/crosscode-contracts-1.3.0.tgz",
|
||||
"integrity": "sha512-T9RVPg3WDhqvEldqToPfp/6HSce0K26BGNvbM0Ksz8uvteXk/OfdARF3mwlDMcmsrp32pQ4w5D62GMTziuSX8A==",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"zod": "^4.6.7"
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^1.3.0",
|
||||
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.1.0.tgz",
|
||||
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.3.0.tgz",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"bcryptjs": "^2.4.3",
|
||||
|
||||
@@ -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
@@ -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])
|
||||
}
|
||||
@@ -455,3 +457,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())
|
||||
}
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
/**
|
||||
* Create the Hub's licence signing key pair (Ed25519).
|
||||
* Create the Hub's signing key pairs (Ed25519).
|
||||
*
|
||||
* npm run generate-keys → keys/hub-signing-key.pem (refuses to overwrite)
|
||||
* npm run generate-keys -- --force → replace it (every install then needs the new public key!)
|
||||
* npm run generate-keys → keys/hub-signing-key.pem: licences (refuses to overwrite)
|
||||
* npm run generate-keys -- --job → keys/hub-job-key.pem: jobs for server agents (2.1.0)
|
||||
* add --force to replace one: every install then needs the new licence key, or every server
|
||||
* must join again for a new job key (agents pin it when they join).
|
||||
*
|
||||
* The private key stays on the Hub server only — back it up somewhere safe. The public key it
|
||||
* prints goes into Cross Events (backend/src/hub/publicKey.js) so installs can check licences.
|
||||
* The private keys stay on the Hub server only — back them up somewhere safe. The two are
|
||||
* separate, so a leaked job key can't sign licences and the other way round.
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const job = process.argv.includes('--job');
|
||||
const dir = path.join(__dirname, '..', 'keys');
|
||||
const file = path.join(dir, 'hub-signing-key.pem');
|
||||
const file = path.join(dir, job ? 'hub-job-key.pem' : 'hub-signing-key.pem');
|
||||
|
||||
if (fs.existsSync(file) && !process.argv.includes('--force')) {
|
||||
console.error(`${file} already exists. Use --force to replace it (installs would need the new public key).`);
|
||||
console.error(`${file} already exists. Use --force to replace it (${job ? 'every server would have to join again' : 'installs would need the new public key'}).`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
@@ -25,6 +28,10 @@ fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(file, privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600 });
|
||||
|
||||
console.log(`Private key written to ${file} — keep it secret and back it up.`);
|
||||
console.log('Set HUB_SIGNING_KEY_FILE to that path in .env.\n');
|
||||
console.log('Public key (for Cross Events, backend/src/hub/publicKey.js):\n');
|
||||
console.log(publicKey.export({ type: 'spki', format: 'pem' }));
|
||||
if (job) {
|
||||
console.log('Set HUB_JOB_SIGNING_KEY_FILE to that path in .env. Agents receive the public key when they join.');
|
||||
} else {
|
||||
console.log('Set HUB_SIGNING_KEY_FILE to that path in .env.\n');
|
||||
console.log('Public key (for Cross Events, backend/src/hub/publicKey.js):\n');
|
||||
console.log(publicKey.export({ type: 'spki', format: 'pem' }));
|
||||
}
|
||||
|
||||
+4
-1
@@ -10,12 +10,15 @@ app.use(cors({ origin: (process.env.FRONTEND_URL || 'http://localhost:3200').rep
|
||||
|
||||
// Keep the exact bytes: heartbeat signatures are over the raw body. 300 KB fits the largest AI
|
||||
// request the Hub accepts (utils/ai.js MAX_INPUT_TOKENS).
|
||||
app.use(express.json({ limit: '300kb', verify: (req, res, buf) => { req.rawBody = buf.toString('utf8'); } }));
|
||||
app.use(express.json({ limit: '1mb', verify: (req, res, buf) => { req.rawBody = buf.toString('utf8'); } }));
|
||||
|
||||
app.get('/api/health', (req, res) => res.json({ ok: true }));
|
||||
app.use('/api/agent/v1', require('./routes/agentApi'));
|
||||
app.use('/api/exports', require('./routes/exports'));
|
||||
app.use('/api', require('./routes/installApi'));
|
||||
app.use('/api/auth', require('./routes/auth'));
|
||||
app.use('/api/admin/billing', require('./routes/billing'));
|
||||
app.use('/api/admin', require('./routes/servers'));
|
||||
app.use('/api/admin', require('./routes/admin'));
|
||||
|
||||
app.use((req, res) => res.status(404).json({ message: 'Not found', code: 'NOT_FOUND' }));
|
||||
|
||||
@@ -13,6 +13,15 @@ const { runAlerts, rollupHeartbeats } = require('./utils/alerts');
|
||||
const { importSmtpFromEnv } = require('./utils/settings');
|
||||
const { syncReleases } = require('./utils/releaseSync');
|
||||
const { runBilling } = require('./utils/billing');
|
||||
const servers = require('./utils/servers');
|
||||
const jobs = require('./utils/jobs');
|
||||
|
||||
// The job-signing key (2.1.0) is optional until the first server joins; warn if it's missing.
|
||||
try {
|
||||
servers.jobSigningKey();
|
||||
} catch (e) {
|
||||
console.warn(`[hub] ${e.message} Servers can't join until it's set.`);
|
||||
}
|
||||
|
||||
// Fail early if the licence signing key is missing or wrong.
|
||||
try {
|
||||
@@ -38,6 +47,10 @@ if (String(process.env.JOBS_ENABLED || 'true').toLowerCase() !== 'false') {
|
||||
every(15 * 60 * 1000, 'release sync', () => syncReleases());
|
||||
every(24 * 60 * 60 * 1000, 'heartbeat roll-up', () => rollupHeartbeats());
|
||||
every(15 * 60 * 1000, 'billing', () => runBilling());
|
||||
// Servers (2.1.0): the job scheduler (missed jobs, reminders, exports), server alerts, stats roll-up.
|
||||
every(30 * 1000, 'jobs', () => jobs.tick());
|
||||
every(60 * 1000, 'server alerts', () => servers.runServerAlerts());
|
||||
every(24 * 60 * 60 * 1000, 'stats roll-up', () => servers.rollupStats());
|
||||
setTimeout(() => runBilling().catch(e => console.warn('[hub] billing failed:', e?.message || e)), 60 * 1000);
|
||||
setTimeout(() => runAlerts().catch(() => {}), 30 * 1000);
|
||||
setTimeout(() => syncReleases().catch(e => console.warn('[hub] release sync failed:', e?.message || e)), 20 * 1000);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* The agent API (2.1.0, crosscode-platform docs/AGENT-1.0-PLAN.md): servers call these; the Hub
|
||||
* never calls a server. Everything after `join` is signed with the server's Ed25519 key.
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const servers = require('../utils/servers');
|
||||
const jobs = require('../utils/jobs');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const wrap = fn => (req, res) => fn(req, res).catch(e => {
|
||||
const status = e.status || 500;
|
||||
if (status >= 500) console.error('[agent api]', e);
|
||||
res.status(status).json({ code: e.code || 'SERVER_ERROR', message: status >= 500 && !e.status ? 'Server error' : e.message });
|
||||
});
|
||||
|
||||
const joinLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 20, standardHeaders: true, legacyHeaders: false, message: { code: 'RATE_LIMITED', message: 'Too many join attempts.' } });
|
||||
const agentLimiter = rateLimit({ windowMs: 60 * 1000, max: 120, standardHeaders: true, legacyHeaders: false, message: { code: 'RATE_LIMITED', message: 'Too many requests.' } });
|
||||
|
||||
router.post('/join', joinLimiter, wrap(async (req, res) => {
|
||||
res.status(201).json(await servers.join(req.body));
|
||||
}));
|
||||
|
||||
router.post('/poll', agentLimiter, servers.requireAgent, wrap(async (req, res) => {
|
||||
res.json(await jobs.poll(req.server, req.body));
|
||||
}));
|
||||
|
||||
router.post('/stats', agentLimiter, servers.requireAgent, wrap(async (req, res) => {
|
||||
await servers.recordStats(req.server, req.body);
|
||||
res.status(204).end();
|
||||
}));
|
||||
|
||||
router.post('/report', agentLimiter, servers.requireAgent, wrap(async (req, res) => {
|
||||
await jobs.receiveReport(req.server, req.body);
|
||||
res.status(204).end();
|
||||
}));
|
||||
|
||||
// The encrypted export: raw bytes, signed like the rest (the signature covers the bytes).
|
||||
router.put('/exports/:id', agentLimiter, express.raw({ type: 'application/octet-stream', limit: '2gb' }), servers.requireAgent, wrap(async (req, res) => {
|
||||
if (!/^exp_[A-Za-z0-9_-]{8,64}$/.test(req.params.id)) return res.status(404).json({ code: 'NOT_FOUND', message: 'Unknown export.' });
|
||||
await jobs.receiveExport(req.server, req.params.id, req.body);
|
||||
res.status(204).end();
|
||||
}));
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* The public download of a church's export (2.1.0, AGENT-1.0-PLAN §9). The file is encrypted with
|
||||
* a key that's only in the emailed link's #fragment, which browsers never send: the page
|
||||
* downloads these bytes and decrypts them in the browser. So the Hub stores the file but can't
|
||||
* read it, and no login is needed (the id and the key are the secret).
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const prisma = require('../config/db');
|
||||
|
||||
const router = express.Router();
|
||||
router.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 60, standardHeaders: true, legacyHeaders: false, message: { code: 'RATE_LIMITED', message: 'Too many requests.' } }));
|
||||
|
||||
const ID = /^exp_[A-Za-z0-9_-]{8,64}$/;
|
||||
|
||||
async function available(id) {
|
||||
if (!ID.test(id)) return null;
|
||||
const exp = await prisma.export.findUnique({ where: { id } });
|
||||
if (!exp || exp.deletedAt || !exp.data || exp.expiresAt < new Date()) return null;
|
||||
return exp;
|
||||
}
|
||||
|
||||
router.get('/:id', async (req, res, next) => {
|
||||
try {
|
||||
const exp = await available(req.params.id);
|
||||
if (!exp) return res.status(404).json({ code: 'NOT_FOUND', message: 'This download has expired or doesn\'t exist.' });
|
||||
res.json({ bytes: exp.bytes, expiresAt: exp.expiresAt });
|
||||
} catch (e) { next(e); }
|
||||
});
|
||||
|
||||
router.get('/:id/file', async (req, res, next) => {
|
||||
try {
|
||||
const exp = await available(req.params.id);
|
||||
if (!exp) return res.status(404).json({ code: 'NOT_FOUND', message: 'This download has expired or doesn\'t exist.' });
|
||||
if (!exp.downloadedAt) await prisma.export.update({ where: { id: exp.id }, data: { downloadedAt: new Date() } });
|
||||
res.setHeader('content-type', 'application/octet-stream');
|
||||
res.setHeader('cache-control', 'no-store');
|
||||
res.setHeader('x-content-type-options', 'nosniff');
|
||||
res.send(Buffer.from(exp.data));
|
||||
} catch (e) { next(e); }
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -152,6 +152,13 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
|
||||
? await prisma.install.update({ where: { id: licence.install.id }, data })
|
||||
: await prisma.install.create({ data: { ...data, product: licence.product, customerId: licence.customerId, licenceId: licence.id } });
|
||||
await prisma.installEvent.create({ data: { installId: install.id, type: 'registered', level: 'info', message: `${licence.install ? 'Re-registered' : 'Registered'} from ${url} (version ${install.version || '?'})`, resolvedAt: new Date() } });
|
||||
// A site the Hub installed (Servers → New install) is linked to its registration, so its
|
||||
// update and closing banners reach it (found in the VM test: they never did).
|
||||
try {
|
||||
await prisma.deployment.updateMany({ where: { licenceId: licence.id, installId: null }, data: { installId: install.id } });
|
||||
} catch (e) {
|
||||
console.warn('[hub] linking the deployment to its install failed:', e?.message || e);
|
||||
}
|
||||
|
||||
res.status(201).json({
|
||||
installId: install.id,
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
/**
|
||||
* Servers, installs on them, jobs, updates and the port list (2.1.0, admin login required;
|
||||
* crosscode-platform docs/AGENT-1.0-PLAN.md §7–10).
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const prisma = require('../config/db');
|
||||
const { protect } = require('../middleware/auth');
|
||||
const { audit } = require('../utils/audit');
|
||||
const { getSettings, setSettings } = require('../utils/settings');
|
||||
const servers = require('../utils/servers');
|
||||
const jobs = require('../utils/jobs');
|
||||
|
||||
const router = express.Router();
|
||||
router.use(protect);
|
||||
|
||||
const wrap = fn => (req, res) => fn(req, res).catch(e => {
|
||||
const status = e.status || 500;
|
||||
if (status >= 500) console.error('[servers]', e);
|
||||
res.status(status).json({ message: status >= 500 && !e.status ? 'Something went wrong.' : e.message, ...(e.code && e.status ? { code: e.code } : {}) });
|
||||
});
|
||||
const bad = (message, status = 400) => Object.assign(new Error(message), { status });
|
||||
|
||||
const SECRETISH = /(PASSWORD|SECRET|TOKEN|KEY|DSN|_URL)$/;
|
||||
const MASK = '••••••';
|
||||
const masked = config => Object.fromEntries(Object.entries(config).map(([k, v]) => [k, SECRETISH.test(k) ? MASK : v]));
|
||||
const jsonSafe = v => JSON.parse(JSON.stringify(v, (_k, x) => (typeof x === 'bigint' ? Number(x) : x)));
|
||||
|
||||
/** Stats in buckets of `minutes` (0 = as stored): averages, with the peaks kept (§10: spikes marked). */
|
||||
function bucketStats(rows, minutes) {
|
||||
if (!minutes) return rows;
|
||||
const size = minutes * 60 * 1000;
|
||||
const out = new Map();
|
||||
for (const r of rows) {
|
||||
const key = Math.floor(new Date(r.at).getTime() / size) * size;
|
||||
const b = out.get(key) || { at: new Date(key), n: 0, cpu: 0, ram: 0, disk: 0, cpuPeak: 0, ramPeak: 0 };
|
||||
b.n++;
|
||||
b.cpu += r.cpuPercent;
|
||||
b.ram += r.ramUsedPercent;
|
||||
b.disk = Math.max(b.disk, r.diskUsedPercent);
|
||||
b.cpuPeak = Math.max(b.cpuPeak, r.cpuPeak);
|
||||
b.ramPeak = Math.max(b.ramPeak, r.ramPeak);
|
||||
out.set(key, b);
|
||||
}
|
||||
return [...out.values()].map(b => ({ at: b.at, cpuPercent: b.cpu / b.n, cpuPeak: b.cpuPeak, ramUsedPercent: b.ram / b.n, ramPeak: b.ramPeak, diskUsedPercent: b.disk }));
|
||||
}
|
||||
|
||||
function serverSummary(s, now = new Date()) {
|
||||
const st = s.lastStats;
|
||||
const sum = st ? servers.summariseStats(st) : null;
|
||||
return {
|
||||
id: s.id, name: s.name, mode: s.mode, hostname: s.hostname, agentVersion: s.agentVersion, lastSeenAt: s.lastSeenAt, joinedAt: s.joinedAt, removedAt: s.removedAt, notes: s.notes,
|
||||
online: jobs.agentOnline(s, now),
|
||||
ram: st ? { totalBytes: st.ram.totalBytes, availableBytes: st.ram.availableBytes, usedPercent: sum.ram } : null,
|
||||
cpu: st ? { percent: st.cpu.percent, load1: st.cpu.load1, cores: st.cpu.cores } : null,
|
||||
disk: st ? st.disks : [],
|
||||
versions: st?.versions || null,
|
||||
frpcRunning: st?.frpcRunning ?? null,
|
||||
central: st?.central || null,
|
||||
deployments: s.deployments ? s.deployments.filter(d => d.status !== 'removed').length : undefined,
|
||||
alerts: s.alerts ? s.alerts.map(a => ({ type: a.type, level: a.level, message: a.message, createdAt: a.createdAt })) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Servers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
router.get('/servers', wrap(async (req, res) => {
|
||||
const list = await prisma.server.findMany({ where: req.query.removed === 'true' ? {} : { removedAt: null }, orderBy: { name: 'asc' }, include: { deployments: true, alerts: { where: { resolvedAt: null } } } });
|
||||
// Stats over the last day for choosing a server: CPU load averaged, peaks.
|
||||
const since = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
||||
const day = await prisma.serverStat.groupBy({ by: ['serverId'], where: { at: { gt: since } }, _avg: { cpuPercent: true, ramUsedPercent: true }, _max: { cpuPeak: true, ramPeak: true } });
|
||||
const byServer = new Map(day.map(d => [d.serverId, { cpuAvg: d._avg.cpuPercent, ramAvg: d._avg.ramUsedPercent, cpuPeak: d._max.cpuPeak, ramPeak: d._max.ramPeak }]));
|
||||
res.json({ servers: list.map(s => ({ ...serverSummary(s), lastDay: byServer.get(s.id) || null })) });
|
||||
}));
|
||||
|
||||
router.post('/servers/join-token', wrap(async (req, res) => {
|
||||
const t = await servers.createJoinToken({ name: req.body?.name, mode: req.body?.mode || 'church', adminId: req.admin.id });
|
||||
await audit(req, 'server_join_token_created', null, { name: t.name, mode: t.mode });
|
||||
res.status(201).json({ ...t, command: servers.joinCommand(t.token, t.mode) });
|
||||
}));
|
||||
|
||||
router.get('/servers/:id', wrap(async (req, res) => {
|
||||
const s = await prisma.server.findUnique({ where: { id: req.params.id }, include: { deployments: { include: { customer: { select: { id: true, name: true } } }, orderBy: { shortName: 'asc' } }, alerts: { orderBy: { createdAt: 'desc' }, take: 50 }, ports: { orderBy: { port: 'asc' } } } });
|
||||
if (!s) throw bad('Not found.', 404);
|
||||
const range = ['24h', '7d', '90d'].includes(req.query.range) ? req.query.range : '24h';
|
||||
const span = { '24h': 1, '7d': 7, '90d': 90 }[range] * 24 * 60 * 60 * 1000;
|
||||
const rows = await prisma.serverStat.findMany({ where: { serverId: s.id, at: { gt: new Date(Date.now() - span) } }, orderBy: { at: 'asc' }, select: { at: true, cpuPercent: true, cpuPeak: true, ramUsedPercent: true, ramPeak: true, diskUsedPercent: true } });
|
||||
const stats = bucketStats(rows, { '24h': 0, '7d': 60, '90d': 360 }[range]);
|
||||
const recentJobs = await prisma.job.findMany({ where: { serverId: s.id }, orderBy: { createdAt: 'desc' }, take: 25, select: { id: true, type: true, status: true, args: true, notBefore: true, finishedAt: true, message: true, deploymentId: true } });
|
||||
res.json(jsonSafe({
|
||||
server: serverSummary(s),
|
||||
config: masked(servers.serverConfig(s)),
|
||||
processes: s.lastStats?.processes || [],
|
||||
stats: stats.map(x => ({ at: x.at, cpuPercent: x.cpuPercent, cpuPeak: x.cpuPeak, ramUsedPercent: x.ramUsedPercent, ramPeak: x.ramPeak, diskUsedPercent: x.diskUsedPercent })),
|
||||
deployments: s.deployments,
|
||||
jobs: recentJobs,
|
||||
alerts: s.alerts,
|
||||
ports: s.ports,
|
||||
}));
|
||||
}));
|
||||
|
||||
router.patch('/servers/:id', wrap(async (req, res) => {
|
||||
const data = {};
|
||||
if (req.body?.name != null) data.name = String(req.body.name).trim().slice(0, 100) || undefined;
|
||||
if (req.body?.notes !== undefined) data.notes = req.body.notes ? String(req.body.notes).slice(0, 2000) : null;
|
||||
const s = await prisma.server.update({ where: { id: req.params.id }, data });
|
||||
res.json({ server: serverSummary(s) });
|
||||
}));
|
||||
|
||||
// The server's configuration: values shown masked come back masked to keep the saved one.
|
||||
router.put('/servers/:id/config', wrap(async (req, res) => {
|
||||
const s = await prisma.server.findUnique({ where: { id: req.params.id } });
|
||||
if (!s) throw bad('Not found.', 404);
|
||||
const current = servers.serverConfig(s);
|
||||
const next = {};
|
||||
for (const [k, v] of Object.entries(req.body?.values || {})) next[k] = v === MASK ? current[k] : v;
|
||||
const saved = await servers.setServerConfig(s.id, next);
|
||||
await audit(req, 'server_config_changed', s.id, { keys: Object.keys(saved) });
|
||||
res.json({ config: masked(saved) });
|
||||
}));
|
||||
|
||||
router.delete('/servers/:id', wrap(async (req, res) => {
|
||||
const live = await prisma.deployment.count({ where: { serverId: req.params.id, status: { notIn: ['removed', 'failed'] } } });
|
||||
if (live) throw bad(`${live} install(s) are still on this server: uninstall or move them first.`, 409);
|
||||
await prisma.server.update({ where: { id: req.params.id }, data: { removedAt: new Date() } });
|
||||
await audit(req, 'server_removed', req.params.id);
|
||||
res.status(204).end();
|
||||
}));
|
||||
|
||||
router.post('/servers/:id/jobs', wrap(async (req, res) => {
|
||||
const job = await jobs.runNow({ serverId: req.params.id, type: req.body?.type, args: req.body?.args || {}, deploymentId: req.body?.deploymentId || null }, req.admin);
|
||||
await audit(req, 'job_created', job.id, { type: job.type, server: req.params.id });
|
||||
res.status(201).json({ job });
|
||||
}));
|
||||
|
||||
// ─── Installs on servers (deployments) ────────────────────────────────────────
|
||||
|
||||
router.get('/deployments', wrap(async (req, res) => {
|
||||
const where = req.query.status ? { status: String(req.query.status) } : { status: { not: 'removed' } };
|
||||
const list = await prisma.deployment.findMany({ where, orderBy: { shortName: 'asc' }, include: { server: { select: { id: true, name: true } }, customer: { select: { id: true, name: true } }, install: { select: { id: true, version: true, lastHeartbeatAt: true, url: true } } } });
|
||||
res.json({ deployments: list });
|
||||
}));
|
||||
|
||||
router.post('/deployments', wrap(async (req, res) => {
|
||||
const out = await jobs.newInstall(req.body || {}, req.admin);
|
||||
await audit(req, 'install_started', out.deployment.id, { shortName: out.deployment.shortName, server: out.deployment.serverId, domain: out.deployment.domain });
|
||||
res.status(201).json(out);
|
||||
}));
|
||||
|
||||
router.post('/deployments/link', wrap(async (req, res) => {
|
||||
const d = await jobs.linkDeployment(req.body || {}, req.admin);
|
||||
await audit(req, 'install_linked', d.id, { shortName: d.shortName, server: d.serverId, install: d.installId });
|
||||
res.status(201).json({ deployment: d });
|
||||
}));
|
||||
|
||||
router.get('/deployments/:id', wrap(async (req, res) => {
|
||||
const d = await prisma.deployment.findUnique({ where: { id: req.params.id }, include: { server: true, customer: { select: { id: true, name: true } }, install: true, jobs: { orderBy: { createdAt: 'desc' }, take: 50 }, exports: { select: { id: true, bytes: true, expiresAt: true, downloadedAt: true, deletedAt: true, createdAt: true } } } });
|
||||
if (!d) throw bad('Not found.', 404);
|
||||
res.json({ deployment: { ...d, server: serverSummary(d.server) }, fastPanel: await jobs.fastPanelText(d) });
|
||||
}));
|
||||
|
||||
router.post('/deployments/:id/proxy-done', wrap(async (req, res) => {
|
||||
const out = await jobs.proxyDone(req.params.id);
|
||||
await audit(req, 'install_proxy_done', req.params.id, out);
|
||||
res.json(out);
|
||||
}));
|
||||
|
||||
router.post('/deployments/:id/adopt', wrap(async (req, res) => {
|
||||
const job = await jobs.scheduleAdopt({ deploymentId: req.params.id, eventsDir: req.body?.eventsDir, version: req.body?.version, at: req.body?.at }, req.admin);
|
||||
await audit(req, 'adopt_scheduled', req.params.id, { job: job.id, at: job.notBefore });
|
||||
res.status(201).json({ job });
|
||||
}));
|
||||
|
||||
router.post('/deployments/:id/uninstall', wrap(async (req, res) => {
|
||||
const out = await jobs.scheduleUninstall({ deploymentId: req.params.id, at: req.body?.at, totp: req.body?.totp, confirm: req.body?.confirm }, req.admin);
|
||||
await audit(req, 'uninstall_scheduled', req.params.id, { at: out.uninstallJob.notBefore });
|
||||
res.status(201).json(out);
|
||||
}));
|
||||
|
||||
// ─── Updates (§8) ─────────────────────────────────────────────────────────────
|
||||
|
||||
router.post('/updates', wrap(async (req, res) => {
|
||||
const out = await jobs.scheduleUpdate(req.body || {}, req.admin);
|
||||
await audit(req, req.body?.emergency ? 'emergency_update_scheduled' : 'update_scheduled', out.batchId || out.jobs[0]?.id, { deployments: req.body?.deploymentIds, version: req.body?.version, at: req.body?.at, reason: req.body?.reason || null });
|
||||
res.status(201).json(out);
|
||||
}));
|
||||
|
||||
// ─── Jobs ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
router.get('/jobs', wrap(async (req, res) => {
|
||||
const where = {};
|
||||
if (req.query.status) where.status = String(req.query.status);
|
||||
if (req.query.serverId) where.serverId = String(req.query.serverId);
|
||||
if (req.query.upcoming === 'true') where.status = { in: ['queued', 'scheduled', 'delivered'] };
|
||||
const list = await prisma.job.findMany({ where, orderBy: [{ notBefore: 'desc' }], take: 200, include: { server: { select: { id: true, name: true } }, deployment: { select: { id: true, shortName: true, domain: true } } } });
|
||||
res.json({ jobs: list.map(j => ({ ...j, report: undefined, hasReport: !!j.report })) });
|
||||
}));
|
||||
|
||||
router.get('/jobs/:id', wrap(async (req, res) => {
|
||||
const job = await prisma.job.findUnique({ where: { id: req.params.id }, include: { server: { select: { id: true, name: true } }, deployment: { select: { id: true, shortName: true, domain: true } } } });
|
||||
if (!job) throw bad('Not found.', 404);
|
||||
res.json({ job });
|
||||
}));
|
||||
|
||||
router.post('/jobs/:id/cancel', wrap(async (req, res) => {
|
||||
const job = await jobs.cancelJob(req.params.id, req.admin);
|
||||
await audit(req, 'job_cancelled', job.id, { type: job.type });
|
||||
res.json({ job });
|
||||
}));
|
||||
|
||||
// A purge can be put off once, by 30 days (§9.6).
|
||||
router.post('/jobs/:id/extend', wrap(async (req, res) => {
|
||||
const job = await prisma.job.findUnique({ where: { id: req.params.id } });
|
||||
if (!job || job.type !== 'purge' || job.status !== 'queued') throw bad('Only a planned purge can be put off.', 409);
|
||||
if (job.message === 'extended') throw bad('It was already put off once.', 409);
|
||||
const notBefore = new Date(job.notBefore.getTime() + 30 * 24 * 60 * 60 * 1000);
|
||||
const updated = await prisma.job.update({ where: { id: job.id }, data: { notBefore, expiresAt: new Date(job.expiresAt.getTime() + 30 * 24 * 60 * 60 * 1000), remindedAt: null, message: 'extended' } });
|
||||
if (job.deploymentId) await prisma.export.updateMany({ where: { deploymentId: job.deploymentId, deletedAt: null, extended: false }, data: { expiresAt: notBefore, extended: true } });
|
||||
await audit(req, 'purge_extended', job.id);
|
||||
res.json({ job: updated });
|
||||
}));
|
||||
|
||||
// ─── The port list and install defaults ───────────────────────────────────────
|
||||
|
||||
router.get('/ports', wrap(async (req, res) => {
|
||||
const [ports, range] = await Promise.all([prisma.port.findMany({ orderBy: { port: 'asc' }, include: { server: { select: { id: true, name: true } } } }), servers.portRange()]);
|
||||
res.json({ ports, range });
|
||||
}));
|
||||
|
||||
router.post('/ports', wrap(async (req, res) => {
|
||||
const port = parseInt(req.body?.port, 10);
|
||||
if (!(port >= 1 && port <= 65535)) throw bad('A port is 1–65535.');
|
||||
const existing = await prisma.port.findUnique({ where: { port } });
|
||||
if (existing && !existing.releasedAt) throw bad(`Port ${port} is already listed (${existing.role}).`, 409);
|
||||
const row = await prisma.port.upsert({ where: { port }, update: { role: 'taken', note: req.body?.note || null, releasedAt: null, serverId: req.body?.serverId || null, deploymentId: null }, create: { port, role: 'taken', note: req.body?.note || null, serverId: req.body?.serverId || null } });
|
||||
await audit(req, 'port_taken', String(port), { note: row.note });
|
||||
res.status(201).json({ port: row });
|
||||
}));
|
||||
|
||||
router.delete('/ports/:port', wrap(async (req, res) => {
|
||||
const port = parseInt(req.params.port, 10);
|
||||
const row = await prisma.port.findUnique({ where: { port } });
|
||||
if (!row) throw bad('Not found.', 404);
|
||||
if (row.role !== 'taken' && !row.releasedAt) throw bad('That port belongs to an install; uninstall it to free the port.', 409);
|
||||
await prisma.port.delete({ where: { port } });
|
||||
res.status(204).end();
|
||||
}));
|
||||
|
||||
router.get('/install-defaults', wrap(async (req, res) => {
|
||||
const s = await getSettings();
|
||||
res.json({ defaults: await servers.installDefaults(), portRange: await servers.portRange(), centralServerIp: s.central_server_ip || '' });
|
||||
}));
|
||||
|
||||
router.put('/install-defaults', wrap(async (req, res) => {
|
||||
const defaults = servers.cleanEnvValues(req.body?.defaults || {}, 'Install defaults');
|
||||
const update = { install_defaults: JSON.stringify(defaults) };
|
||||
if (req.body?.portRange) {
|
||||
const from = parseInt(req.body.portRange.from, 10);
|
||||
const to = parseInt(req.body.portRange.to, 10);
|
||||
if (!(from >= 1024 && to <= 65535 && to - from >= 10)) throw bad('The port range is at least 10 ports between 1024 and 65535.');
|
||||
update.port_range_start = String(from);
|
||||
update.port_range_end = String(to);
|
||||
}
|
||||
if (req.body?.centralServerIp !== undefined) {
|
||||
const ip = String(req.body.centralServerIp || '').trim();
|
||||
if (ip && !/^(\d{1,3}\.){3}\d{1,3}$/.test(ip)) throw bad('The central server IP looks like 203.0.113.10.');
|
||||
update.central_server_ip = ip;
|
||||
}
|
||||
await setSettings(update);
|
||||
await audit(req, 'install_defaults_changed', null, { keys: Object.keys(defaults) });
|
||||
res.json({ defaults });
|
||||
}));
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* The env template of the release being installed (crosscode.env-template/1,
|
||||
* apps/<product>/env.template.json at its tag), read from git like the release notes. The Hub
|
||||
* refuses to make a job when a required server or defaults value is missing (AGENT-1.0-PLAN §5).
|
||||
* Releases from before templates (events@2.2.0) use the copy kept here, the same one the
|
||||
* crosscode script falls back to.
|
||||
*/
|
||||
|
||||
const { agent } = require('@crosscode/contracts');
|
||||
const { getSettings, releaseRepoToken } = require('./settings');
|
||||
const { PLATFORM_REPO, parseRepoUrl, gitGet } = require('./releaseSync');
|
||||
|
||||
const FALLBACK = { events: require('./envTemplates/events.json') };
|
||||
const cache = new Map();
|
||||
|
||||
async function envTemplate(product, version) {
|
||||
const key = `${product}@${version}`;
|
||||
if (cache.has(key)) return cache.get(key);
|
||||
let template = null;
|
||||
try {
|
||||
const repo = parseRepoUrl(PLATFORM_REPO);
|
||||
const token = await releaseRepoToken().catch(() => '');
|
||||
const text = await gitGet(`${repo.api}/raw/${encodeURIComponent(`apps/${product}`)}/env.template.json?ref=${encodeURIComponent(key)}`, token, { raw: true });
|
||||
if (text) {
|
||||
const parsed = agent.envTemplateSchema.safeParse(JSON.parse(text));
|
||||
if (parsed.success) template = parsed.data;
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(`[env template] ${key}: ${e?.message || e}`);
|
||||
}
|
||||
template = template || (FALLBACK[product] ? agent.envTemplateSchema.parse(FALLBACK[product]) : null);
|
||||
if (template) cache.set(key, template);
|
||||
return template;
|
||||
}
|
||||
|
||||
/** What's missing for a release on a server: { server: [...], defaults: [...] }. */
|
||||
async function missingFor(product, version, serverValues, defaults) {
|
||||
const template = await envTemplate(product, version);
|
||||
if (!template) return { server: [], defaults: [] };
|
||||
return { server: agent.missingRequired(template, 'server', serverValues), defaults: agent.missingRequired(template, 'defaults', defaults) };
|
||||
}
|
||||
|
||||
module.exports = { envTemplate, missingFor, _cache: cache, getSettings };
|
||||
@@ -0,0 +1,114 @@
|
||||
{
|
||||
"schema": "crosscode.env-template/1",
|
||||
"product": "events",
|
||||
"files": {
|
||||
"backend/.env": [
|
||||
{
|
||||
"name": "NODE_ENV",
|
||||
"layer": "generated",
|
||||
"required": true,
|
||||
"description": "production"
|
||||
},
|
||||
{
|
||||
"name": "PORT",
|
||||
"layer": "install",
|
||||
"from": "{apiPort}",
|
||||
"required": true,
|
||||
"description": "The backend's port (from the Hub's port list)"
|
||||
},
|
||||
{
|
||||
"name": "DATABASE_URL",
|
||||
"layer": "generated",
|
||||
"required": true,
|
||||
"description": "Made on the server with a new password; never leaves it"
|
||||
},
|
||||
{
|
||||
"name": "JWT_SECRET",
|
||||
"layer": "generated",
|
||||
"required": true,
|
||||
"description": "Also encrypts stored secrets: never change it"
|
||||
},
|
||||
{
|
||||
"name": "FRONTEND_URL",
|
||||
"layer": "install",
|
||||
"from": "https://{domain}",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "APP_BASE_URL",
|
||||
"layer": "install",
|
||||
"from": "https://{domain}",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "BACKEND_URL",
|
||||
"layer": "install",
|
||||
"from": "https://{domain}",
|
||||
"required": true,
|
||||
"description": "The same address: the backend is under /api (2.2.0+)"
|
||||
},
|
||||
{
|
||||
"name": "TRUST_PROXY",
|
||||
"layer": "server",
|
||||
"required": true,
|
||||
"description": "Behind frp: loopback"
|
||||
},
|
||||
{
|
||||
"name": "APP_TIMEZONE",
|
||||
"layer": "install",
|
||||
"default": "Africa/Johannesburg"
|
||||
},
|
||||
{
|
||||
"name": "HUB_URL",
|
||||
"layer": "defaults",
|
||||
"default": "https://hub.crosscode.co.za"
|
||||
},
|
||||
{
|
||||
"name": "HUB_HEARTBEAT_ENABLED",
|
||||
"layer": "defaults",
|
||||
"default": "true"
|
||||
},
|
||||
{
|
||||
"name": "HUB_PUBLIC_KEY",
|
||||
"layer": "defaults",
|
||||
"description": "Only for a Hub other than hub.crosscode.co.za (staging, a test VM): its licence public key"
|
||||
},
|
||||
{
|
||||
"name": "HUB_LICENCE_KEY",
|
||||
"layer": "install",
|
||||
"description": "With it the site registers with the Hub by itself when it first starts"
|
||||
},
|
||||
{
|
||||
"name": "HUB_ADMIN_NAME",
|
||||
"layer": "install",
|
||||
"description": "The site admin, sent to the Hub on registering"
|
||||
},
|
||||
{
|
||||
"name": "HUB_ADMIN_EMAIL",
|
||||
"layer": "install"
|
||||
},
|
||||
{
|
||||
"name": "BACKUP_ENABLED",
|
||||
"layer": "defaults",
|
||||
"default": "true"
|
||||
},
|
||||
{
|
||||
"name": "DAILY_SUMMARY_ENABLED",
|
||||
"layer": "defaults",
|
||||
"default": "true"
|
||||
},
|
||||
{
|
||||
"name": "SENTRY_DSN",
|
||||
"layer": "defaults"
|
||||
}
|
||||
],
|
||||
"frontend/.env.production": [
|
||||
{
|
||||
"name": "NEXT_PUBLIC_API_URL",
|
||||
"layer": "install",
|
||||
"from": "https://{domain}",
|
||||
"required": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
/**
|
||||
* Jobs for server agents (2.1.0, crosscode-platform docs/AGENT-1.0-PLAN.md §4, §7–9, §11):
|
||||
* installs, scheduled / emergency / batch updates with notice to the church, adopting existing
|
||||
* installs, uninstall with an encrypted export, and the reports that come back.
|
||||
*
|
||||
* A job row is made when it's planned; the signed job (crosscode.agent-job/1, with the config
|
||||
* sealed to the server's key) is only built when the agent picks it up, so it always carries the
|
||||
* current server configuration. Each server gets one job at a time. A job whose time window
|
||||
* passes before the agent picks it up is `missed`: it never runs late without a new notice.
|
||||
*/
|
||||
|
||||
const dns = require('dns').promises;
|
||||
const { agent } = require('@crosscode/contracts');
|
||||
const signing = require('@crosscode/contracts/signing');
|
||||
const prisma = require('../config/db');
|
||||
const { decrypt } = require('./crypto');
|
||||
const { verifyCode } = require('./totp');
|
||||
const { sendMail } = require('./mail');
|
||||
const { getSettings } = require('./settings');
|
||||
const { PRODUCT_NAMES } = require('./products');
|
||||
const { generateLicence } = require('./licences');
|
||||
const { unmetRequirementsFor } = require('./releases');
|
||||
const { compareVersions } = require('./alerts');
|
||||
const servers = require('./servers');
|
||||
const { missingFor } = require('./envTemplates');
|
||||
|
||||
const MIN = 60 * 1000;
|
||||
const HOUR = 60 * MIN;
|
||||
const DAY = 24 * HOUR;
|
||||
const WINDOW_MIN = 15;
|
||||
const SCHEDULE_MIN_HOURS = 4;
|
||||
const EMERGENCY_MIN_MINUTES = 15;
|
||||
const AGENT_ONLINE_MS = 2 * MIN;
|
||||
const EXPORT_DAYS = 30;
|
||||
const SHORT_NAME = /^[a-z][a-z0-9-]{1,30}$/;
|
||||
const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/;
|
||||
|
||||
const fail = (status, code, message) => Object.assign(new Error(message), { status, code });
|
||||
const hubUrl = () => (process.env.FRONTEND_URL || '').replace(/\/$/, '');
|
||||
const sast = d => new Date(d).toLocaleString('en-ZA', { timeZone: 'Africa/Johannesburg', weekday: 'long', day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit' });
|
||||
|
||||
// Report statuses → job statuses.
|
||||
const FINAL = { succeeded: 'succeeded', failed: 'failed', 'rolled-back': 'rolled_back', refused: 'refused', expired: 'expired' };
|
||||
const DONE = ['succeeded', 'failed', 'rolled_back', 'refused', 'expired', 'missed', 'cancelled'];
|
||||
|
||||
// ─── Making jobs ──────────────────────────────────────────────────────────────
|
||||
|
||||
/** Types whose job brings the .env values (sealed to the server). */
|
||||
const NEEDS_CONFIG = new Set(['install', 'deploy', 'adopt', 'add-product']);
|
||||
|
||||
async function makeJob(db, { serverId, type, args, deploymentId = null, notBefore = new Date(), windowMinutes = WINDOW_MIN, status = 'queued', scheduled = false, emergency = false, reason = null, batchId = null, batchOrder = null, noticeId = null, createdById = null }) {
|
||||
const parsed = agent.jobArgsSchemas[type]?.safeParse(args);
|
||||
if (!parsed?.success) throw fail(400, 'BAD_JOB', `The ${type} job's arguments aren't valid: ${parsed?.error.issues[0]?.message || 'unknown type'}.`);
|
||||
return db.job.create({
|
||||
data: {
|
||||
id: servers.newId('job'), serverId, type, args: parsed.data, deploymentId, status, notBefore,
|
||||
expiresAt: new Date(notBefore.getTime() + windowMinutes * MIN), scheduled, emergency, reason, batchId, batchOrder, noticeId, createdById,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** The .env values for a deployment's job, by layer (§5). */
|
||||
async function jobConfig(server, deployment) {
|
||||
const config = { server: servers.serverConfig(server), defaults: await servers.installDefaults(), install: {} };
|
||||
if (deployment) {
|
||||
const licence = deployment.licenceId ? await prisma.licence.findUnique({ where: { id: deployment.licenceId } }) : null;
|
||||
const values = {};
|
||||
if (deployment.timezone) values.APP_TIMEZONE = deployment.timezone;
|
||||
if (licence?.key) values.HUB_LICENCE_KEY = licence.key;
|
||||
if (deployment.adminName) values.HUB_ADMIN_NAME = deployment.adminName;
|
||||
if (deployment.adminEmail) values.HUB_ADMIN_EMAIL = deployment.adminEmail;
|
||||
config.install[deployment.product] = values;
|
||||
}
|
||||
return agent.jobConfigSchema.parse(config);
|
||||
}
|
||||
|
||||
/** The signed job the agent receives. */
|
||||
async function signedJob(job, server) {
|
||||
const deployment = job.deploymentId ? await prisma.deployment.findUnique({ where: { id: job.deploymentId } }) : null;
|
||||
const unsigned = {
|
||||
schema: 'crosscode.agent-job/1', id: job.id, serverId: server.id, type: job.type, args: job.args,
|
||||
config: NEEDS_CONFIG.has(job.type) ? signing.sealConfig(await jobConfig(server, deployment), server.x25519Key) : null,
|
||||
notBefore: job.notBefore.toISOString(), expiresAt: job.expiresAt.toISOString(),
|
||||
};
|
||||
return signing.signJob(unsigned, servers.jobSigningKey().privateKeyPem);
|
||||
}
|
||||
|
||||
// ─── Poll and reports (agent API) ─────────────────────────────────────────────
|
||||
|
||||
/** POST /api/agent/v1/poll: the next job due for this server, one at a time. */
|
||||
async function poll(server, body, now = new Date()) {
|
||||
const parsed = agent.pollRequestSchema.safeParse(body);
|
||||
if (!parsed.success) throw fail(400, 'BAD_REQUEST', 'Not a poll request.');
|
||||
await prisma.server.update({ where: { id: server.id }, data: { lastSeenAt: now, agentVersion: parsed.data.agentVersion } });
|
||||
|
||||
const running = await prisma.job.findFirst({ where: { serverId: server.id, status: 'delivered' } });
|
||||
if (running) {
|
||||
const limit = (agent.JOB_TIME_LIMIT_MINUTES[running.type] || 30) + 10;
|
||||
if (now - running.deliveredAt < limit * MIN) return { jobs: [], pollSeconds: servers.POLL_SECONDS };
|
||||
await finish(running, { status: 'failed', message: `No report within ${limit} minutes of handing it to the agent.` }, now);
|
||||
}
|
||||
const next = await prisma.job.findFirst({
|
||||
where: { serverId: server.id, status: 'queued', notBefore: { lte: new Date(now.getTime() + 30 * 1000) }, expiresAt: { gt: now } },
|
||||
orderBy: [{ notBefore: 'asc' }, { createdAt: 'asc' }],
|
||||
});
|
||||
if (!next) return { jobs: [], pollSeconds: servers.POLL_SECONDS };
|
||||
const claimed = await prisma.job.updateMany({ where: { id: next.id, status: 'queued' }, data: { status: 'delivered', deliveredAt: now } });
|
||||
if (claimed.count !== 1) return { jobs: [], pollSeconds: servers.POLL_SECONDS };
|
||||
return { jobs: [await signedJob(next, server)], pollSeconds: servers.POLL_SECONDS };
|
||||
}
|
||||
|
||||
/** POST /api/agent/v1/report. The export key is used for the email, never stored. */
|
||||
async function receiveReport(server, body, now = new Date()) {
|
||||
const parsed = agent.agentReportSchema.safeParse(body);
|
||||
if (!parsed.success) throw fail(400, 'BAD_REQUEST', 'Not crosscode.agent-report/1.');
|
||||
const report = parsed.data;
|
||||
if (report.serverId !== server.id) throw fail(403, 'WRONG_SERVER', 'That report is for another server.');
|
||||
const job = await prisma.job.findUnique({ where: { id: report.jobId } });
|
||||
if (!job || job.serverId !== server.id) throw fail(404, 'JOB_NOT_FOUND', 'Unknown job.');
|
||||
if (DONE.includes(job.status)) return { ok: true, already: true };
|
||||
const exportKey = typeof report.result?.key === 'string' ? report.result.key : null;
|
||||
const stored = { ...report, result: { ...report.result, key: undefined } };
|
||||
await finish(job, { status: FINAL[report.status] || 'failed', message: report.message || null, report: stored, exportKey }, now);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/** A job is done: record it, then what follows from it. */
|
||||
async function finish(job, { status, message = null, report = null, exportKey = null }, now = new Date()) {
|
||||
const updated = await prisma.job.update({ where: { id: job.id }, data: { status, message, report: report ?? undefined, finishedAt: now } });
|
||||
try {
|
||||
await afterJob(updated, { exportKey }, now);
|
||||
} catch (e) {
|
||||
console.error(`[jobs] after ${job.id} (${job.type}):`, e);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
async function afterJob(job, { exportKey }, now) {
|
||||
const deployment = job.deploymentId ? await prisma.deployment.findUnique({ where: { id: job.deploymentId }, include: { server: true, customer: true, install: true } }) : null;
|
||||
const ok = job.status === 'succeeded';
|
||||
if (job.noticeId) await endNotice(job.noticeId, now);
|
||||
|
||||
switch (job.type) {
|
||||
case 'install':
|
||||
if (!deployment) break;
|
||||
if (ok) {
|
||||
const version = job.report?.result?.versions?.[deployment.product] || null;
|
||||
await prisma.deployment.update({ where: { id: deployment.id }, data: { status: 'waiting_for_proxy', version: version ? String(version).replace(/^.*@/, '') : null } });
|
||||
await queueCentralCheck([deployment.webPort, deployment.apiPort], now);
|
||||
await emailJoshua(`Installed: ${deployment.shortName} (${PRODUCT_NAMES[deployment.product]})`, `${jobReportText(job)}\n\n${await fastPanelText(deployment)}`);
|
||||
} else {
|
||||
await prisma.deployment.update({ where: { id: deployment.id }, data: { status: 'failed' } });
|
||||
await prisma.port.deleteMany({ where: { port: { in: [deployment.webPort, deployment.apiPort] } } });
|
||||
await emailJoshua(`Install failed: ${deployment.shortName}`, jobReportText(job));
|
||||
}
|
||||
break;
|
||||
case 'deploy':
|
||||
case 'adopt': {
|
||||
if (!deployment) break;
|
||||
const target = job.type === 'adopt' ? job.args.version : (job.args.versions || [])[0];
|
||||
if (ok && target) await prisma.deployment.update({ where: { id: deployment.id }, data: { version: target.replace(/^.*@/, ''), status: deployment.status === 'failed' ? 'live' : deployment.status } });
|
||||
if (job.scheduled) {
|
||||
const name = PRODUCT_NAMES[deployment.product];
|
||||
if (ok) await emailSiteAdmin(deployment, `${name} was updated`, `${name} at ${deployment.domain} was updated${target ? ` to ${target.replace(/^.*@/, '')}` : ''}. Everything is running again.`);
|
||||
else await emailSiteAdmin(deployment, `${name} update didn't go through`, `The planned update of ${name} at ${deployment.domain} didn't go through, so the site is running the previous version. Nothing else changed; we'll be in touch about a new time.`);
|
||||
}
|
||||
await emailJoshua(`${job.type === 'adopt' ? 'Adopt' : 'Update'} ${ok ? 'done' : job.status.replace('_', ' ')}: ${deployment.shortName}`, jobReportText(job));
|
||||
break;
|
||||
}
|
||||
case 'export':
|
||||
if (!deployment) break;
|
||||
if (ok && exportKey) {
|
||||
const link = `${hubUrl()}/download/${job.args.exportId}#${exportKey}`;
|
||||
const exp = await prisma.export.findUnique({ where: { id: job.args.exportId } });
|
||||
await emailSiteAdmin(deployment, 'Your church\'s data from Cross Code', [
|
||||
`Here is all of ${deployment.customer?.name || 'your church'}'s data from ${PRODUCT_NAMES[deployment.product]}: events, people, registrations, payments, check-ins and rosters, with the uploaded files.`,
|
||||
'', link, '',
|
||||
`The link works until ${exp ? sast(exp.expiresAt) : `${EXPORT_DAYS} days from now`}. The file is encrypted, and only this link (the part after #) can open it: we can't read it, and we can't send the link again, so keep this email.`,
|
||||
].join('\n'));
|
||||
} else if (!ok) {
|
||||
await emailJoshua(`Export failed: ${deployment.shortName}`, jobReportText(job));
|
||||
}
|
||||
break;
|
||||
case 'uninstall':
|
||||
if (!deployment) break;
|
||||
if (ok) {
|
||||
await prisma.deployment.update({ where: { id: deployment.id }, data: { status: 'removed', removedAt: now } });
|
||||
await prisma.port.updateMany({ where: { port: { in: [deployment.webPort, deployment.apiPort] } }, data: { releasedAt: now, deploymentId: deployment.id } });
|
||||
if (deployment.installId) await prisma.install.update({ where: { id: deployment.installId }, data: { releasedAt: now } });
|
||||
await makeJob(prisma, { serverId: deployment.serverId, type: 'purge', args: { church: deployment.shortName }, deploymentId: deployment.id, notBefore: new Date(now.getTime() + EXPORT_DAYS * DAY), windowMinutes: 3 * 24 * 60 });
|
||||
await emailJoshua(`Uninstalled: ${deployment.shortName}`, `${jobReportText(job)}\n\nRemove the FastPanel site ${deployment.domain} (ports ${deployment.webPort}, ${deployment.apiPort}).\nThe final backup is kept on the server for ${EXPORT_DAYS} days, then purged.`);
|
||||
} else {
|
||||
await prisma.deployment.update({ where: { id: deployment.id }, data: { status: 'live' } });
|
||||
await emailJoshua(`Uninstall failed: ${deployment.shortName}`, jobReportText(job));
|
||||
}
|
||||
break;
|
||||
case 'purge':
|
||||
if (ok && deployment) {
|
||||
const exports = await prisma.export.findMany({ where: { deploymentId: deployment.id, deletedAt: null } });
|
||||
for (const e of exports) await prisma.export.update({ where: { id: e.id }, data: { data: null, deletedAt: now } });
|
||||
}
|
||||
break;
|
||||
case 'check-ports':
|
||||
if (!ok) await emailJoshua('Central server check: ports not ready', `${job.message || ''}\n\n${JSON.stringify(job.report?.result || {}, null, 2)}`);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (job.batchId) await advanceBatch(job, now);
|
||||
}
|
||||
|
||||
// ─── Batches (§8): one at a time, stop at the first failure ───────────────────
|
||||
|
||||
async function advanceBatch(job, now) {
|
||||
const rest = await prisma.job.findMany({ where: { batchId: job.batchId, status: 'scheduled' }, orderBy: { batchOrder: 'asc' }, include: { deployment: { include: { install: true } } } });
|
||||
if (!rest.length) return;
|
||||
if (job.status === 'succeeded') {
|
||||
const next = rest[0];
|
||||
await prisma.job.update({ where: { id: next.id }, data: { status: 'queued', notBefore: now, expiresAt: new Date(now.getTime() + WINDOW_MIN * MIN) } });
|
||||
return;
|
||||
}
|
||||
for (const j of rest) {
|
||||
await prisma.job.update({ where: { id: j.id }, data: { status: 'cancelled', message: `Not run: ${job.id} before it in the same batch didn't succeed.`, finishedAt: now } });
|
||||
if (j.noticeId) await endNotice(j.noticeId, now);
|
||||
if (j.deployment && j.scheduled && j.type === 'deploy') {
|
||||
await emailSiteAdmin(j.deployment, `${PRODUCT_NAMES[j.deployment.product]} update postponed`, `The planned update of ${PRODUCT_NAMES[j.deployment.product]} at ${j.deployment.domain} has been postponed. Your site keeps running as it is; we'll let you know the new time.`);
|
||||
}
|
||||
}
|
||||
await emailJoshua('Batch stopped', `${jobReportText(job)}\n\n${rest.length} job(s) after it were cancelled and their churches told the update is postponed.`);
|
||||
}
|
||||
|
||||
// ─── The scheduler (every 30 s) ───────────────────────────────────────────────
|
||||
|
||||
async function tick(now = new Date()) {
|
||||
// Missed: its window passed before the agent picked it up. Nothing runs late.
|
||||
const missed = await prisma.job.findMany({ where: { status: 'queued', expiresAt: { lte: now } }, include: { server: true } });
|
||||
for (const job of missed) {
|
||||
const updated = await prisma.job.update({ where: { id: job.id }, data: { status: 'missed', message: `The agent on ${job.server.name} didn't pick it up between ${job.notBefore.toISOString()} and ${job.expiresAt.toISOString()}.`, finishedAt: now } });
|
||||
if (job.noticeId) await endNotice(job.noticeId, now);
|
||||
await emailJoshua(`Missed job: ${job.type} on ${job.server.name}`, `${updated.message}\nNothing ran. A new time needs a new notice to the church.\n\n${hubUrl()}/jobs/${job.id}`);
|
||||
if (job.batchId) await advanceBatch(updated, now);
|
||||
if (job.type === 'install' && job.deploymentId) {
|
||||
await prisma.deployment.update({ where: { id: job.deploymentId }, data: { status: 'failed' } });
|
||||
}
|
||||
}
|
||||
// Reminders an hour before a scheduled update.
|
||||
const soon = await prisma.job.findMany({ where: { scheduled: true, remindedAt: null, status: { in: ['queued', 'scheduled'] }, notBefore: { lte: new Date(now.getTime() + HOUR), gt: now } }, include: { deployment: { include: { install: true } } } });
|
||||
for (const job of soon) {
|
||||
await prisma.job.update({ where: { id: job.id }, data: { remindedAt: now } });
|
||||
if (job.deployment && job.type !== 'uninstall') {
|
||||
await emailSiteAdmin(job.deployment, `Reminder: ${PRODUCT_NAMES[job.deployment.product]} update at ${sast(job.notBefore)}`, `A reminder that ${PRODUCT_NAMES[job.deployment.product]} at ${job.deployment.domain} will be updated on ${sast(job.notBefore)}. The site will be unavailable for a few minutes.`);
|
||||
}
|
||||
}
|
||||
// Purges: Joshua is told 3 days before the kept backup is deleted.
|
||||
const purges = await prisma.job.findMany({ where: { type: 'purge', status: 'queued', remindedAt: null, notBefore: { lte: new Date(now.getTime() + 3 * DAY) } }, include: { deployment: true } });
|
||||
for (const job of purges) {
|
||||
await prisma.job.update({ where: { id: job.id }, data: { remindedAt: now } });
|
||||
await emailJoshua(`Purge in 3 days: ${job.args.church}`, `${job.args.church}'s kept backup and its encrypted export will be deleted on ${sast(job.notBefore)}. To keep them 30 days longer, open the job: ${hubUrl()}/jobs/${job.id}`);
|
||||
}
|
||||
// Exports past their date.
|
||||
await prisma.export.updateMany({ where: { deletedAt: null, expiresAt: { lte: now } }, data: { data: null, deletedAt: now } });
|
||||
return { missed: missed.length, reminded: soon.length };
|
||||
}
|
||||
|
||||
// ─── Emails ───────────────────────────────────────────────────────────────────
|
||||
|
||||
async function emailJoshua(subject, text) {
|
||||
const { alert_email: to } = await getSettings();
|
||||
if (to) await sendMail({ to, subject: `Cross Code Hub: ${subject}`, text }).catch(e => console.warn('[jobs] email failed:', e?.message));
|
||||
}
|
||||
|
||||
function siteAdminEmail(deployment) {
|
||||
return deployment.adminEmail || deployment.install?.adminContact?.email || null;
|
||||
}
|
||||
|
||||
async function emailSiteAdmin(deployment, subject, text) {
|
||||
const to = siteAdminEmail(deployment);
|
||||
if (!to) return;
|
||||
const hello = deployment.adminName || deployment.install?.adminContact?.name;
|
||||
await sendMail({ to, subject, text: `${hello ? `Hi ${hello},\n\n` : ''}${text}\n\nCross Code` }).catch(e => console.warn('[jobs] email failed:', e?.message));
|
||||
}
|
||||
|
||||
function jobReportText(job) {
|
||||
const r = job.report || {};
|
||||
const steps = (r.steps || []).map(s => ` ${s.outcome === 'ok' ? '✓' : s.outcome === 'failed' ? '✗' : '•'} ${s.name}${s.detail ? ` (${s.detail})` : ''}`).join('\n');
|
||||
const tail = job.status === 'succeeded' ? '' : `\n\nLast log lines:\n${(r.log || []).slice(-30).join('\n')}`;
|
||||
return `${job.type} ${job.id}: ${job.status}${job.message ? `\n${job.message}` : ''}\n\n${steps}${tail}\n\n${hubUrl()}/jobs/${job.id}`;
|
||||
}
|
||||
|
||||
async function centralIp() {
|
||||
return (await getSettings()).central_server_ip || '';
|
||||
}
|
||||
|
||||
/** Whether the domain's DNS points at the central server: true, false, or null (not known). */
|
||||
async function dnsPointsAtCentral(domain) {
|
||||
const ip = await centralIp();
|
||||
if (!ip) return null;
|
||||
try {
|
||||
return (await dns.resolve4(domain)).includes(ip);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The FastPanel email (§11): what Joshua sets up by hand; nothing is done automatically. */
|
||||
async function fastPanelText(d) {
|
||||
const dnsOk = await dnsPointsAtCentral(d.domain);
|
||||
const ip = await centralIp();
|
||||
return [
|
||||
`Set up in FastPanel: ${d.domain} (${d.customer?.name || d.shortName}, ${PRODUCT_NAMES[d.product]})`,
|
||||
'',
|
||||
`1. Add the site ${d.domain}.`,
|
||||
'2. Proxy:',
|
||||
` /api → http://127.0.0.1:${d.apiPort} (backend)`,
|
||||
` everything else → http://127.0.0.1:${d.webPort} (frontend)`,
|
||||
' Pass the Host header and X-Forwarded-For / X-Forwarded-Proto: https.',
|
||||
' Allow uploads up to 25 MB.',
|
||||
'3. Turn on Let\'s Encrypt for the site.',
|
||||
`4. DNS: ${d.domain} → ${ip || '<central server IP>'} (${dnsOk === true ? 'checked: points there' : dnsOk === false ? 'not yet' : 'not checked: set the central server IP in Settings'})`,
|
||||
`5. Then click "Proxy done" in the Hub: ${hubUrl()}/servers/installs/${d.id}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
// ─── Notices (banners) ────────────────────────────────────────────────────────
|
||||
|
||||
async function addNotice(deployment, { title, message, endsAt, level = 'maintenance' }, now) {
|
||||
let installId = deployment.installId;
|
||||
// Registered before registration made the link (Hub 2.1.0 builds before the VM test).
|
||||
if (!installId && deployment.licenceId) {
|
||||
const install = await prisma.install.findFirst({ where: { licenceId: deployment.licenceId } });
|
||||
if (install) {
|
||||
installId = install.id;
|
||||
await prisma.deployment.update({ where: { id: deployment.id }, data: { installId } }).catch(() => {});
|
||||
}
|
||||
}
|
||||
if (!installId) return null;
|
||||
const n = await prisma.notice.create({ data: { title, message, level, allInstalls: false, installIds: [installId], showBanner: true, startsAt: now, endsAt } });
|
||||
return n.id;
|
||||
}
|
||||
|
||||
async function endNotice(noticeId, now) {
|
||||
await prisma.notice.updateMany({ where: { id: noticeId, OR: [{ endsAt: null }, { endsAt: { gt: now } }] }, data: { endsAt: now } }).catch(() => {});
|
||||
}
|
||||
|
||||
// ─── Admin actions ────────────────────────────────────────────────────────────
|
||||
|
||||
/** 2FA again for uninstalls and emergency updates (§4). */
|
||||
function requireTotp(admin, code) {
|
||||
if (!admin?.totpEnabled || !admin.totpSecret) throw fail(403, 'TOTP_REQUIRED', 'Two-factor isn\'t set up for your account.');
|
||||
if (!verifyCode(decrypt(admin.totpSecret), String(code || '').replace(/\s/g, ''))) throw fail(403, 'BAD_TOTP', 'That two-factor code isn\'t right.');
|
||||
}
|
||||
|
||||
function agentOnline(server, now = new Date()) {
|
||||
return !!server.lastSeenAt && now - new Date(server.lastSeenAt) < AGENT_ONLINE_MS;
|
||||
}
|
||||
|
||||
/** The latest release of a product, or the one asked for (it must exist). */
|
||||
async function releaseFor(product, version) {
|
||||
const releases = await prisma.release.findMany({ where: { product } });
|
||||
if (!releases.length) throw fail(409, 'NO_RELEASE', `There are no ${PRODUCT_NAMES[product]} releases yet (Releases page).`);
|
||||
if (version) {
|
||||
const r = releases.find(x => x.version === version);
|
||||
if (!r) throw fail(400, 'NO_RELEASE', `There's no ${PRODUCT_NAMES[product]} release ${version}.`);
|
||||
return r;
|
||||
}
|
||||
return releases.sort((a, b) => compareVersions(b.version, a.version))[0];
|
||||
}
|
||||
|
||||
/** Checks before a job is made (§7.2): agent online, configuration complete for the release. */
|
||||
async function preflight(server, product, version, now) {
|
||||
if (server.removedAt) throw fail(409, 'SERVER_REMOVED', 'That server was removed.');
|
||||
if (server.mode !== 'church') throw fail(400, 'NOT_A_CHURCH_SERVER', 'Church sites go on church servers, not the central one.');
|
||||
if (!agentOnline(server, now)) throw fail(409, 'AGENT_OFFLINE', `The agent on ${server.name} isn't online (last heard ${server.lastSeenAt ? server.lastSeenAt.toISOString() : 'never'}).`);
|
||||
const missing = await missingFor(product, version, servers.serverConfig(server), await servers.installDefaults());
|
||||
const parts = [];
|
||||
if (missing.server.length) parts.push(`${server.name}'s configuration needs ${missing.server.join(', ')}`);
|
||||
if (missing.defaults.length) parts.push(`Install defaults need ${missing.defaults.join(', ')}`);
|
||||
if (parts.length) throw fail(409, 'CONFIG_MISSING', `${parts.join('; ')} (Servers → ${server.name} → Configuration).`);
|
||||
}
|
||||
|
||||
/** New install (§7): licence, ports, the install job. */
|
||||
async function newInstall(input, admin, now = new Date()) {
|
||||
const product = input.product || 'events';
|
||||
if (product !== 'events') throw fail(400, 'BAD_REQUEST', 'Only Cross Events can be installed so far.');
|
||||
const shortName = String(input.shortName || '').trim();
|
||||
if (!SHORT_NAME.test(shortName)) throw fail(400, 'BAD_REQUEST', 'The short name is 2–31 characters: a-z, 0-9 and -, starting with a letter.');
|
||||
const domain = String(input.domain || '').trim().toLowerCase();
|
||||
if (!DOMAIN.test(domain)) throw fail(400, 'BAD_REQUEST', 'Give the domain the site is served on, like events.hope.co.za.');
|
||||
const adminEmail = String(input.adminEmail || '').trim();
|
||||
if (adminEmail && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(adminEmail)) throw fail(400, 'BAD_REQUEST', 'The site admin\'s email isn\'t valid.');
|
||||
const [customer, server] = await Promise.all([
|
||||
prisma.customer.findUnique({ where: { id: String(input.customerId || '') } }),
|
||||
prisma.server.findUnique({ where: { id: String(input.serverId || '') } }),
|
||||
]);
|
||||
if (!customer) throw fail(404, 'NOT_FOUND', 'Customer not found.');
|
||||
if (!server) throw fail(404, 'NOT_FOUND', 'Server not found.');
|
||||
const release = await releaseFor(product, input.version || null);
|
||||
await preflight(server, product, release.version, now);
|
||||
if (await prisma.deployment.findFirst({ where: { shortName, status: { notIn: ['removed', 'failed'] } } })) throw fail(409, 'SHORT_NAME_TAKEN', `The short name ${shortName} is already used.`);
|
||||
// The name is free again after a failed install (its ports were already freed) or an uninstall.
|
||||
// A failed install's record goes; a removed one keeps its history under another name (the
|
||||
// database allows one install per short name and product). Found in the VM test.
|
||||
await prisma.deployment.deleteMany({ where: { shortName, product, status: 'failed' } });
|
||||
for (const old of await prisma.deployment.findMany({ where: { shortName, product, status: 'removed' } })) {
|
||||
await prisma.deployment.update({ where: { id: old.id }, data: { shortName: `${shortName}~removed-${old.id.slice(0, 8)}` } });
|
||||
}
|
||||
const warnings = [];
|
||||
const dnsOk = await dnsPointsAtCentral(domain);
|
||||
if (dnsOk === false) warnings.push(`${domain} doesn't point at the central server yet (the install still runs).`);
|
||||
|
||||
const deployment = await prisma.$transaction(async tx => {
|
||||
let licence = await tx.licence.findFirst({ where: { customerId: customer.id, product, status: { not: 'revoked' } }, include: { install: true } });
|
||||
if (licence?.install && !licence.install.releasedAt) throw fail(409, 'LICENCE_IN_USE', `${customer.name}'s ${PRODUCT_NAMES[product]} licence is already used by ${licence.install.url}.`);
|
||||
if (!licence) licence = (await generateLicence(tx, { customerId: customer.id, product, now })).licence;
|
||||
const ports = await servers.allocatePorts(tx, server.id, now);
|
||||
const d = await tx.deployment.create({
|
||||
data: { serverId: server.id, customerId: customer.id, licenceId: licence.id, product, shortName, domain, webPort: ports.web, apiPort: ports.api, timezone: input.timezone || null, adminName: input.adminName || null, adminEmail: adminEmail || null, status: 'installing' },
|
||||
});
|
||||
await tx.port.updateMany({ where: { port: { in: [ports.web, ports.api] } }, data: { deploymentId: d.id } });
|
||||
await makeJob(tx, {
|
||||
serverId: server.id, type: 'install', deploymentId: d.id, createdById: admin?.id || null, notBefore: now,
|
||||
args: { church: shortName, products: [product], versions: { [product]: `${product}@${release.version}` }, domains: { [product]: domain }, ports: { [product]: ports } },
|
||||
});
|
||||
return d;
|
||||
});
|
||||
return { deployment, warnings };
|
||||
}
|
||||
|
||||
/** Proxy done (§7.8): check the public addresses, then Live and the welcome email. */
|
||||
async function proxyDone(deploymentId, now = new Date(), fetcher = fetch) {
|
||||
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true, customer: true } });
|
||||
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
|
||||
const problems = [];
|
||||
const get = async url => {
|
||||
try { return await fetcher(url, { redirect: 'manual', signal: AbortSignal.timeout(15000) }); } catch (e) { problems.push(`${url}: ${e?.message || 'no answer'}`); return null; }
|
||||
};
|
||||
const site = await get(`https://${d.domain}/`);
|
||||
if (site && !(site.status >= 200 && site.status < 400)) problems.push(`https://${d.domain}/ answered ${site.status}.`);
|
||||
const health = await get(`https://${d.domain}/api/health`);
|
||||
let reported = null;
|
||||
if (health) {
|
||||
try { reported = await health.json(); } catch { problems.push(`https://${d.domain}/api/health didn't answer with JSON (is /api sent to port ${d.apiPort}?).`); }
|
||||
if (reported && d.version && reported.version !== d.version) problems.push(`The backend reports version ${reported.version}, expected ${d.version}.`);
|
||||
}
|
||||
if (problems.length) return { live: false, problems };
|
||||
await prisma.deployment.update({ where: { id: d.id }, data: { status: 'live', liveAt: now } });
|
||||
await emailSiteAdmin(d, `Your ${PRODUCT_NAMES[d.product]} site is ready`, [
|
||||
`${d.customer?.name || 'Your church'}'s ${PRODUCT_NAMES[d.product]} site is ready at https://${d.domain}.`,
|
||||
'', `To start, open https://${d.domain}/setup: it creates your admin account and walks you through the settings.`,
|
||||
].join('\n'));
|
||||
return { live: true, problems: [] };
|
||||
}
|
||||
|
||||
function scheduleWarnings(at, deployment) {
|
||||
const warnings = [];
|
||||
const local = new Date(at.getTime() + 2 * HOUR);
|
||||
if (local.getUTCDay() === 0 && local.getUTCHours() >= 6 && local.getUTCHours() < 13) warnings.push('That\'s Sunday morning, when churches use their sites most.');
|
||||
const upcoming = deployment.install?.stats?.events?.upcoming;
|
||||
if (upcoming > 0) warnings.push(`${deployment.shortName} has ${upcoming} upcoming event(s): check none runs then.`);
|
||||
return warnings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scheduled, emergency or batch update (§8). One deployment: a single job; several: a batch that
|
||||
* runs them one at a time from `at` and stops at the first failure. Each church gets one email
|
||||
* and a banner now, and a reminder an hour before.
|
||||
*/
|
||||
async function scheduleUpdate({ deploymentIds, version, at, emergency = false, reason = null, totp = null }, admin, now = new Date()) {
|
||||
const when = new Date(at);
|
||||
if (Number.isNaN(when.getTime())) throw fail(400, 'BAD_REQUEST', 'Pick a time.');
|
||||
if (emergency) {
|
||||
if (!reason || !String(reason).trim()) throw fail(400, 'BAD_REQUEST', 'An emergency update needs a reason (it goes in the email and banner).');
|
||||
requireTotp(admin, totp);
|
||||
if (when - now < EMERGENCY_MIN_MINUTES * MIN) throw fail(400, 'TOO_SOON', `An emergency update needs at least ${EMERGENCY_MIN_MINUTES} minutes' notice.`);
|
||||
} else if (when - now < SCHEDULE_MIN_HOURS * HOUR) {
|
||||
throw fail(400, 'TOO_SOON', `Updates are planned at least ${SCHEDULE_MIN_HOURS} hours ahead (or as an emergency update).`);
|
||||
}
|
||||
const ids = [...new Set((deploymentIds || []).map(String))];
|
||||
if (!ids.length) throw fail(400, 'BAD_REQUEST', 'Choose at least one install.');
|
||||
const deployments = await prisma.deployment.findMany({ where: { id: { in: ids } }, include: { server: true, install: true, customer: true } });
|
||||
if (deployments.length !== ids.length) throw fail(404, 'NOT_FOUND', 'One of the installs wasn\'t found.');
|
||||
const products = new Set(deployments.map(d => d.product));
|
||||
if (products.size !== 1) throw fail(400, 'BAD_REQUEST', 'A batch is for one product.');
|
||||
const product = [...products][0];
|
||||
const release = await releaseFor(product, version);
|
||||
const warnings = [];
|
||||
for (const d of deployments) {
|
||||
if (d.status !== 'live') throw fail(409, 'NOT_LIVE', `${d.shortName} isn't live (${d.status}).`);
|
||||
if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', `${d.shortName}'s server was removed.`);
|
||||
if (d.install) {
|
||||
const unmet = await unmetRequirementsFor(d.install, release);
|
||||
if (unmet.length) throw fail(409, 'REQUIREMENT_NOT_MET', `${d.shortName}: ${release.version} needs ${unmet.map(u => `${u.product} ${u.version}`).join(', ')} first.`);
|
||||
}
|
||||
const missing = await missingFor(product, release.version, servers.serverConfig(d.server), await servers.installDefaults());
|
||||
if (missing.server.length || missing.defaults.length) throw fail(409, 'CONFIG_MISSING', `${d.shortName}: set ${[...missing.server, ...missing.defaults].join(', ')} first.`);
|
||||
warnings.push(...scheduleWarnings(when, d));
|
||||
}
|
||||
const batchId = deployments.length > 1 ? servers.newId('batch') : null;
|
||||
const name = PRODUCT_NAMES[product];
|
||||
const jobs = [];
|
||||
for (const [i, d] of deployments.entries()) {
|
||||
const title = emergency ? `Urgent ${name} update` : `Planned ${name} update`;
|
||||
const message = `${name} will be updated on ${sast(when)}. The site will be unavailable for a few minutes.${emergency ? ` Why: ${reason}` : ''}`;
|
||||
const noticeId = await addNotice(d, { title, message, endsAt: new Date(when.getTime() + 2 * HOUR), level: emergency ? 'warning' : 'maintenance' }, now);
|
||||
jobs.push(await makeJob(prisma, {
|
||||
serverId: d.serverId, type: 'deploy', deploymentId: d.id, createdById: admin?.id || null, scheduled: true, emergency, reason,
|
||||
batchId, batchOrder: batchId ? i : null, status: !batchId || i === 0 ? 'queued' : 'scheduled', notBefore: when, noticeId,
|
||||
args: { church: d.shortName, products: [product], versions: [`${product}@${release.version}`] },
|
||||
}));
|
||||
const notes = release.notes ? `\n\nWhat's new in ${release.version}:\n${release.notes}` : '';
|
||||
await emailSiteAdmin(d, `${emergency ? 'Urgent: ' : ''}${name} will be updated on ${sast(when)}`, `${message}${notes}`);
|
||||
}
|
||||
return { jobs, batchId, warnings: [...new Set(warnings)] };
|
||||
}
|
||||
|
||||
/** Cancel a job that hasn't been handed out yet; the church is told and the banner ends. */
|
||||
async function cancelJob(jobId, admin, now = new Date()) {
|
||||
const job = await prisma.job.findUnique({ where: { id: jobId }, include: { deployment: { include: { install: true } } } });
|
||||
if (!job) throw fail(404, 'NOT_FOUND', 'Not found.');
|
||||
if (!['queued', 'scheduled'].includes(job.status)) throw fail(409, 'NOT_CANCELLABLE', `This job is ${job.status}.`);
|
||||
const updated = await prisma.job.update({ where: { id: job.id }, data: { status: 'cancelled', finishedAt: now, message: `Cancelled by ${admin?.name || 'an admin'}.` } });
|
||||
if (job.noticeId) await endNotice(job.noticeId, now);
|
||||
if (job.scheduled && job.deployment && job.type === 'deploy') {
|
||||
await emailSiteAdmin(job.deployment, `${PRODUCT_NAMES[job.deployment.product]} update cancelled`, `The update of ${PRODUCT_NAMES[job.deployment.product]} at ${job.deployment.domain} planned for ${sast(job.notBefore)} is cancelled. Your site keeps running as it is.`);
|
||||
}
|
||||
if (job.batchId) await advanceBatch(updated, now);
|
||||
if (job.type === 'uninstall' && job.deploymentId) await prisma.deployment.update({ where: { id: job.deploymentId }, data: { status: 'live' } });
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstall (§9): 2FA, typing the short name, at least 4 hours ahead. A batch of two: the export
|
||||
* (encrypted, emailed to the site admin), then the uninstall, which only runs if the export worked.
|
||||
*/
|
||||
async function scheduleUninstall({ deploymentId, at, totp, confirm }, admin, now = new Date()) {
|
||||
requireTotp(admin, totp);
|
||||
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true, server: true } });
|
||||
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
|
||||
if (confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to confirm.`);
|
||||
if (['removed', 'uninstalling'].includes(d.status)) throw fail(409, 'ALREADY', `It's already ${d.status}.`);
|
||||
const when = new Date(at || now.getTime() + 7 * DAY);
|
||||
if (when - now < SCHEDULE_MIN_HOURS * HOUR) throw fail(400, 'TOO_SOON', `An uninstall is planned at least ${SCHEDULE_MIN_HOURS} hours ahead.`);
|
||||
const exportId = servers.newId('exp');
|
||||
const batchId = servers.newId('batch');
|
||||
const noticeId = await addNotice(d, { title: `${PRODUCT_NAMES[d.product]} is closing`, message: `This site closes on ${sast(when)}. Your admin gets a download of all your data by email first.`, endsAt: new Date(when.getTime() + 2 * HOUR), level: 'warning' }, now);
|
||||
await prisma.export.create({ data: { id: exportId, deploymentId: d.id, expiresAt: new Date(when.getTime() + EXPORT_DAYS * DAY) } });
|
||||
const exportJob = await makeJob(prisma, { serverId: d.serverId, type: 'export', deploymentId: d.id, createdById: admin.id, scheduled: true, batchId, batchOrder: 0, notBefore: when, args: { church: d.shortName, exportId } });
|
||||
const uninstallJob = await makeJob(prisma, { serverId: d.serverId, type: 'uninstall', deploymentId: d.id, createdById: admin.id, scheduled: true, batchId, batchOrder: 1, status: 'scheduled', notBefore: when, noticeId, args: { church: d.shortName } });
|
||||
await prisma.deployment.update({ where: { id: d.id }, data: { status: 'uninstalling' } });
|
||||
await emailSiteAdmin(d, `${PRODUCT_NAMES[d.product]} at ${d.domain} closes on ${sast(when)}`, `As agreed, ${PRODUCT_NAMES[d.product]} at ${d.domain} will be closed on ${sast(when)}. Shortly before, you'll get an email with a link to download all your data (events, people, registrations, payments and files). The link works for ${EXPORT_DAYS} days.`);
|
||||
return { exportJob, uninstallJob };
|
||||
}
|
||||
|
||||
/** An agent's encrypted export (PUT /api/agent/v1/exports/:id). */
|
||||
async function receiveExport(server, exportId, buffer) {
|
||||
const exp = await prisma.export.findUnique({ where: { id: exportId }, include: { deployment: true } });
|
||||
if (!exp || !exp.deployment || exp.deployment.serverId !== server.id) throw fail(404, 'NOT_FOUND', 'Unknown export.');
|
||||
if (exp.deletedAt) throw fail(410, 'GONE', 'This export was deleted.');
|
||||
if (!buffer?.length || buffer.length > 2 * 1024 ** 3) throw fail(400, 'BAD_REQUEST', 'Empty or too large.');
|
||||
await prisma.export.update({ where: { id: exportId }, data: { data: buffer, bytes: buffer.length } });
|
||||
}
|
||||
|
||||
/** Link an install that's already on a server (crosscode adopt, or installed by hand) (§14.3). */
|
||||
async function linkDeployment(input, admin) {
|
||||
const server = await prisma.server.findUnique({ where: { id: String(input.serverId || '') } });
|
||||
const install = await prisma.install.findUnique({ where: { id: String(input.installId || '') }, include: { deployment: true } });
|
||||
if (!server || !install) throw fail(404, 'NOT_FOUND', 'Server or install not found.');
|
||||
if (install.deployment) throw fail(409, 'ALREADY_LINKED', 'That install is already linked.');
|
||||
const shortName = String(input.shortName || '').trim();
|
||||
if (!SHORT_NAME.test(shortName)) throw fail(400, 'BAD_REQUEST', 'The short name (its folder in /var/www/sites) is a-z, 0-9 and -.');
|
||||
const web = parseInt(input.webPort, 10);
|
||||
const api = parseInt(input.apiPort, 10);
|
||||
if (!(web > 0 && api > 0 && web !== api)) throw fail(400, 'BAD_REQUEST', 'Give the site\'s two ports (web and api).');
|
||||
const domain = new URL(install.url).hostname;
|
||||
return prisma.$transaction(async tx => {
|
||||
const d = await tx.deployment.create({
|
||||
data: { serverId: server.id, customerId: install.customerId, licenceId: install.licenceId, installId: install.id, product: install.product, shortName, domain, webPort: web, apiPort: api, version: install.version, timezone: install.timezone, status: 'live', liveAt: new Date(), adminName: install.adminContact?.name || null, adminEmail: install.adminContact?.email || null },
|
||||
});
|
||||
for (const [port, role] of [[web, 'web'], [api, 'api']]) {
|
||||
await tx.port.upsert({ where: { port }, update: { serverId: server.id, deploymentId: d.id, role, releasedAt: null, note: 'existing install' }, create: { port, serverId: server.id, deploymentId: d.id, role, note: 'existing install' } });
|
||||
}
|
||||
return d;
|
||||
});
|
||||
}
|
||||
|
||||
/** Move a linked 2.1.x install onto the monorepo with `crosscode adopt`, at a time with notice. */
|
||||
async function scheduleAdopt({ deploymentId, eventsDir, version, at }, admin, now = new Date()) {
|
||||
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true, server: true } });
|
||||
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
|
||||
const when = new Date(at);
|
||||
if (Number.isNaN(when.getTime()) || when - now < SCHEDULE_MIN_HOURS * HOUR) throw fail(400, 'TOO_SOON', `Plan it at least ${SCHEDULE_MIN_HOURS} hours ahead.`);
|
||||
const release = await releaseFor(d.product, version || null);
|
||||
const noticeId = await addNotice(d, { title: 'Planned maintenance', message: `${PRODUCT_NAMES[d.product]} will be moved to its new home on ${sast(when)}. The site will be unavailable for a minute or two.`, endsAt: new Date(when.getTime() + 2 * HOUR) }, now);
|
||||
const job = await makeJob(prisma, { serverId: d.serverId, type: 'adopt', deploymentId: d.id, createdById: admin?.id || null, scheduled: true, notBefore: when, noticeId, args: { church: d.shortName, eventsDir: String(eventsDir || ''), version: `${d.product}@${release.version}` } });
|
||||
await emailSiteAdmin(d, `Planned maintenance on ${sast(when)}`, `${PRODUCT_NAMES[d.product]} at ${d.domain} will be moved to its new home on ${sast(when)}. The site will be unavailable for a minute or two; nothing changes for your team.`);
|
||||
return job;
|
||||
}
|
||||
|
||||
/** check-ports on every central server (§7.6). */
|
||||
async function queueCentralCheck(ports, now = new Date()) {
|
||||
const centrals = await prisma.server.findMany({ where: { mode: 'central', removedAt: null } });
|
||||
for (const c of centrals) await makeJob(prisma, { serverId: c.id, type: 'check-ports', args: { ports }, notBefore: now });
|
||||
return centrals.length;
|
||||
}
|
||||
|
||||
/** Any job by hand (status, restart): no notice, runs at once. */
|
||||
async function runNow({ serverId, type, args, deploymentId = null }, admin, now = new Date()) {
|
||||
if (!['status', 'restart', 'check-ports', 'update-agent'].includes(type)) throw fail(400, 'BAD_REQUEST', `${type} jobs are made from their own pages.`);
|
||||
return makeJob(prisma, { serverId, type, args, deploymentId, createdById: admin?.id || null, notBefore: now });
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES,
|
||||
makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch,
|
||||
newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
|
||||
fastPanelText, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail,
|
||||
};
|
||||
@@ -276,4 +276,4 @@ async function syncReleases() {
|
||||
return { sources: counts, added, updated, removed, latest, problems };
|
||||
}
|
||||
|
||||
module.exports = { PLATFORM_REPO, parseRepoUrl, parseNotes, parseRequirements, plainNotes, tagPattern, defaultSources, cleanSources, releaseSources, syncReleases };
|
||||
module.exports = { PLATFORM_REPO, gitGet: get, parseRepoUrl, parseNotes, parseRequirements, plainNotes, tagPattern, defaultSources, cleanSources, releaseSources, syncReleases };
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
/**
|
||||
* Servers and their agents (2.1.0, crosscode-platform docs/AGENT-1.0-PLAN.md): joining with a
|
||||
* one-time token, checking the agent's signed requests, the server's configuration (encrypted),
|
||||
* stats, the port list and server alerts. The agent polls; the Hub never connects to a server.
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { agent } = require('@crosscode/contracts');
|
||||
const signing = require('@crosscode/contracts/signing');
|
||||
const prisma = require('../config/db');
|
||||
const { encrypt, decrypt } = require('./crypto');
|
||||
const { getSettings } = require('./settings');
|
||||
const { sendMail } = require('./mail');
|
||||
|
||||
const JOIN_TOKEN_MINUTES = 60;
|
||||
const POLL_SECONDS = 30;
|
||||
const STATS_SECONDS = 60;
|
||||
const MIN = 60 * 1000;
|
||||
const DAY = 24 * 60 * MIN;
|
||||
|
||||
const fail = (status, code, message) => Object.assign(new Error(message), { status, code });
|
||||
const newId = prefix => `${prefix}_${crypto.randomBytes(12).toString('base64url')}`;
|
||||
const hashToken = token => crypto.createHash('sha256').update(String(token)).digest('hex');
|
||||
|
||||
// ─── The Hub's job-signing key (not the licence key) ─────────────────────────
|
||||
|
||||
let jobKey = null;
|
||||
/** { privateKeyPem, publicKey (raw base64url) } from HUB_JOB_SIGNING_KEY(_FILE). */
|
||||
function jobSigningKey() {
|
||||
if (jobKey) return jobKey;
|
||||
let pem = (process.env.HUB_JOB_SIGNING_KEY || '').replace(/\\n/g, '\n').trim();
|
||||
if (!pem && process.env.HUB_JOB_SIGNING_KEY_FILE) pem = fs.readFileSync(path.resolve(process.env.HUB_JOB_SIGNING_KEY_FILE), 'utf8');
|
||||
if (!pem) throw fail(503, 'NO_JOB_KEY', 'No job-signing key: set HUB_JOB_SIGNING_KEY_FILE (npm run generate-keys -- --job).');
|
||||
if (crypto.createPrivateKey(pem).asymmetricKeyType !== 'ed25519') throw fail(503, 'NO_JOB_KEY', 'The job-signing key must be Ed25519.');
|
||||
jobKey = { privateKeyPem: pem, publicKey: signing.publicKeyOf(pem) };
|
||||
return jobKey;
|
||||
}
|
||||
function resetJobKeyForTests() { jobKey = null; }
|
||||
|
||||
// ─── Joining ──────────────────────────────────────────────────────────────────
|
||||
|
||||
async function createJoinToken({ name, mode = 'church', adminId = null }, now = new Date()) {
|
||||
const clean = String(name || '').trim().slice(0, 100);
|
||||
if (!clean) throw fail(400, 'BAD_REQUEST', 'Give the server a name.');
|
||||
if (!['church', 'central'].includes(mode)) throw fail(400, 'BAD_REQUEST', 'mode is church or central.');
|
||||
jobSigningKey(); // can't join servers without it
|
||||
const token = crypto.randomBytes(32).toString('base64url');
|
||||
const expiresAt = new Date(now.getTime() + JOIN_TOKEN_MINUTES * MIN);
|
||||
await prisma.serverJoinToken.create({ data: { tokenHash: hashToken(token), name: clean, mode, expiresAt, createdById: adminId } });
|
||||
return { token, expiresAt, mode, name: clean };
|
||||
}
|
||||
|
||||
/** The install command shown with a token. */
|
||||
function joinCommand(token, mode, hubUrl = process.env.HUB_PUBLIC_URL || process.env.PUBLIC_URL || 'https://hub.crosscode.co.za') {
|
||||
const script = 'https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/apps/agent/deploy/install.sh';
|
||||
return `curl -fsSL ${script} | sudo bash -s -- --hub ${hubUrl.replace(/\/$/, '')} --token ${token}${mode === 'central' ? ' --central' : ''}`;
|
||||
}
|
||||
|
||||
/** POST /api/agent/v1/join: the token is the proof; it works once, within the hour. */
|
||||
async function join(body, now = new Date()) {
|
||||
const parsed = agent.joinRequestSchema.safeParse(body);
|
||||
if (!parsed.success) throw fail(400, 'BAD_REQUEST', 'Not a join request.');
|
||||
const req = parsed.data;
|
||||
const row = await prisma.serverJoinToken.findUnique({ where: { tokenHash: hashToken(req.token) } });
|
||||
if (!row || row.usedAt || row.expiresAt < now) throw fail(403, 'BAD_TOKEN', 'This join token is unknown, used or expired. Make a new one in the Hub (Servers → Add server).');
|
||||
if (row.mode !== req.mode) throw fail(400, 'WRONG_MODE', `This token is for a ${row.mode} server.`);
|
||||
const { publicKey } = jobSigningKey();
|
||||
const server = await prisma.$transaction(async tx => {
|
||||
const used = await tx.serverJoinToken.updateMany({ where: { id: row.id, usedAt: null }, data: { usedAt: now } });
|
||||
if (used.count !== 1) throw fail(403, 'BAD_TOKEN', 'This join token was just used.');
|
||||
const created = await tx.server.create({ data: { id: newId('srv'), name: row.name, mode: req.mode, hostname: req.hostname, ed25519Key: req.publicKeys.ed25519, x25519Key: req.publicKeys.x25519, agentVersion: req.agentVersion, lastSeenAt: now } });
|
||||
await tx.serverJoinToken.update({ where: { id: row.id }, data: { serverId: created.id } });
|
||||
return created;
|
||||
});
|
||||
return { serverId: server.id, hubJobKey: publicKey, pollSeconds: POLL_SECONDS, statsSeconds: STATS_SECONDS };
|
||||
}
|
||||
|
||||
/**
|
||||
* Express middleware for signed agent requests: the server's Ed25519 key over timestamp + raw body.
|
||||
* Sets req.server. A removed server is refused.
|
||||
*/
|
||||
async function requireAgent(req, res, next) {
|
||||
try {
|
||||
const id = String(req.headers[agent.AGENT_HEADERS.server] || '');
|
||||
const server = /^srv_[A-Za-z0-9_-]{8,64}$/.test(id) ? await prisma.server.findUnique({ where: { id } }) : null;
|
||||
if (!server || server.removedAt) return res.status(404).json({ code: 'SERVER_NOT_FOUND', message: 'This server isn\'t joined to the Hub (or was removed).' });
|
||||
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from(req.rawBody ?? '', 'utf8');
|
||||
const v = signing.verifyAgentRequest({ publicKey: server.ed25519Key, timestamp: req.headers[agent.AGENT_HEADERS.timestamp], signature: req.headers[agent.AGENT_HEADERS.signature], rawBody: raw });
|
||||
if (!v.ok) return res.status(401).json({ code: v.code, message: v.code === 'STALE_REQUEST' ? 'The server\'s clock is more than 5 minutes off.' : 'Bad signature.' });
|
||||
req.server = server;
|
||||
next();
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Configuration (§5) ───────────────────────────────────────────────────────
|
||||
|
||||
const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
||||
|
||||
function serverConfig(server) {
|
||||
if (!server?.config) return {};
|
||||
try { return JSON.parse(decrypt(server.config)); } catch { return {}; }
|
||||
}
|
||||
|
||||
function cleanEnvValues(values, what) {
|
||||
if (!values || typeof values !== 'object' || Array.isArray(values)) throw fail(400, 'BAD_REQUEST', `${what}: expected NAME → value.`);
|
||||
const out = {};
|
||||
for (const [k, v] of Object.entries(values)) {
|
||||
if (!ENV_NAME.test(k)) throw fail(400, 'BAD_REQUEST', `${what}: ${k} isn't a variable name (A-Z, 0-9, _).`);
|
||||
const s = v == null ? '' : String(v);
|
||||
if (/[\r\n]/.test(s) || s.length > 4000) throw fail(400, 'BAD_REQUEST', `${what}: ${k} can't have newlines or be over 4000 characters.`);
|
||||
if (s.trim() !== '') out[k] = s.trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function setServerConfig(serverId, values) {
|
||||
const clean = cleanEnvValues(values, 'Server configuration');
|
||||
if (clean.DB_ADMIN_URL && !/^postgres(ql)?:\/\//.test(clean.DB_ADMIN_URL)) throw fail(400, 'BAD_REQUEST', 'DB_ADMIN_URL is a postgresql:// URL.');
|
||||
await prisma.server.update({ where: { id: serverId }, data: { config: Object.keys(clean).length ? encrypt(JSON.stringify(clean)) : null } });
|
||||
return clean;
|
||||
}
|
||||
|
||||
/** Install defaults (Settings → Install defaults): the same for every install. */
|
||||
async function installDefaults() {
|
||||
const s = await getSettings();
|
||||
try { return JSON.parse(s.install_defaults || '{}'); } catch { return {}; }
|
||||
}
|
||||
|
||||
// ─── Stats (§10) ──────────────────────────────────────────────────────────────
|
||||
|
||||
function summariseStats(stats) {
|
||||
const ram = stats.ram.totalBytes > 0 ? (stats.ram.usedBytes / stats.ram.totalBytes) * 100 : 0;
|
||||
const disk = stats.disks.reduce((m, d) => Math.max(m, d.totalBytes > 0 ? (d.usedBytes / d.totalBytes) * 100 : 0), 0);
|
||||
return { cpu: stats.cpu.percent, ram, disk, load1: stats.cpu.load1 };
|
||||
}
|
||||
|
||||
async function recordStats(server, body, now = new Date()) {
|
||||
const parsed = agent.agentStatsSchema.safeParse(body);
|
||||
if (!parsed.success) throw fail(400, 'BAD_REQUEST', 'Not crosscode.agent-stats/1.');
|
||||
const stats = parsed.data;
|
||||
const s = summariseStats(stats);
|
||||
await prisma.$transaction([
|
||||
prisma.serverStat.create({ data: { serverId: server.id, at: now, granularity: 'minute', cpuPercent: s.cpu, cpuPeak: s.cpu, ramUsedPercent: s.ram, ramPeak: s.ram, ramUsedBytes: BigInt(Math.round(stats.ram.usedBytes)), ramTotalBytes: BigInt(Math.round(stats.ram.totalBytes)), diskUsedPercent: s.disk, load1: s.load1 } }),
|
||||
prisma.server.update({ where: { id: server.id }, data: { lastStats: stats, lastSeenAt: now, agentVersion: stats.versions.agent } }),
|
||||
]);
|
||||
rememberRestarts(server.id, stats, now);
|
||||
}
|
||||
|
||||
/** Minutes older than 7 days become hours (average and peak); hours older than 90 days go. */
|
||||
async function rollupStats(now = new Date(), db = prisma) {
|
||||
const minuteCutoff = new Date(now.getTime() - 7 * DAY);
|
||||
const hourCutoff = new Date(now.getTime() - 90 * DAY);
|
||||
await db.$executeRawUnsafe(`
|
||||
INSERT INTO "ServerStat" ("id", "serverId", "at", "granularity", "cpuPercent", "cpuPeak", "ramUsedPercent", "ramPeak", "ramUsedBytes", "ramTotalBytes", "diskUsedPercent", "load1")
|
||||
SELECT gen_random_uuid()::text, "serverId", date_trunc('hour', "at"), 'hour', avg("cpuPercent"), max("cpuPeak"), avg("ramUsedPercent"), max("ramPeak"),
|
||||
avg("ramUsedBytes")::bigint, max("ramTotalBytes"), max("diskUsedPercent"), avg("load1")
|
||||
FROM "ServerStat" WHERE "granularity" = 'minute' AND "at" < $1
|
||||
GROUP BY "serverId", date_trunc('hour', "at")`, minuteCutoff);
|
||||
const minutes = await db.serverStat.deleteMany({ where: { granularity: 'minute', at: { lt: minuteCutoff } } });
|
||||
const hours = await db.serverStat.deleteMany({ where: { granularity: 'hour', at: { lt: hourCutoff } } });
|
||||
return { minutes: minutes.count, hours: hours.count };
|
||||
}
|
||||
|
||||
// PM2 restart counts seen over the last 10 minutes, per server (the Hub is one process).
|
||||
const restartHistory = new Map();
|
||||
function rememberRestarts(serverId, stats, now) {
|
||||
const list = (restartHistory.get(serverId) || []).filter(e => now - e.at <= 10 * MIN);
|
||||
list.push({ at: now, restarts: Object.fromEntries(stats.processes.map(p => [p.name, p.restarts])) });
|
||||
restartHistory.set(serverId, list);
|
||||
}
|
||||
function restartsInTenMinutes(serverId) {
|
||||
const list = restartHistory.get(serverId) || [];
|
||||
if (list.length < 2) return [];
|
||||
const first = list[0].restarts;
|
||||
const last = list[list.length - 1].restarts;
|
||||
return Object.entries(last).filter(([name, n]) => first[name] != null && n - first[name] > 5).map(([name, n]) => `${name} restarted ${n - first[name]} times in 10 minutes`);
|
||||
}
|
||||
|
||||
// ─── Alerts (§10) ─────────────────────────────────────────────────────────────
|
||||
|
||||
/** The problems a server has now: [{ type, level, message }]. Pure, for tests. */
|
||||
function serverProblems(server, recent, restarts, now = new Date()) {
|
||||
const out = [];
|
||||
if (!server.lastSeenAt || now - new Date(server.lastSeenAt) > 5 * MIN) {
|
||||
out.push({ type: 'agent_silent', level: 'critical', message: server.lastSeenAt ? `The agent hasn't been heard from since ${new Date(server.lastSeenAt).toISOString()}` : 'The agent has never reported' });
|
||||
}
|
||||
const st = server.lastStats;
|
||||
if (st) {
|
||||
for (const d of st.disks || []) {
|
||||
const used = d.totalBytes > 0 ? (d.usedBytes / d.totalBytes) * 100 : 0;
|
||||
if (used > 85) out.push({ type: `disk:${d.mount}`, level: 'warning', message: `Disk ${d.mount} is ${Math.round(used)}% full` });
|
||||
}
|
||||
if (recent.length >= 5 && recent.slice(0, 5).every(r => r.ramUsedPercent > 90)) out.push({ type: 'ram_high', level: 'warning', message: `RAM over 90% for 5 minutes (${Math.round(recent[0].ramUsedPercent)}% now)` });
|
||||
if (server.mode === 'church' && st.frpcRunning === false) out.push({ type: 'frpc_down', level: 'critical', message: 'frpc isn\'t running: the server\'s sites can\'t be reached' });
|
||||
if (server.mode === 'central' && st.central) {
|
||||
if (!st.central.proxyBindAddr || !['127.0.0.1', '::1'].includes(st.central.proxyBindAddr)) out.push({ type: 'proxy_bind_addr', level: 'critical', message: 'frps.ini has no proxy_bind_addr = 127.0.0.1: tunnels can be reached straight from the internet' });
|
||||
if (st.central.frpsRunning === false) out.push({ type: 'frps_down', level: 'critical', message: 'frps isn\'t running: no church site can be reached' });
|
||||
}
|
||||
}
|
||||
for (const r of restarts) out.push({ type: `restarts:${r.split(' ')[0]}`, level: 'warning', message: r });
|
||||
return out;
|
||||
}
|
||||
|
||||
async function runServerAlerts(now = new Date()) {
|
||||
const settings = await getSettings();
|
||||
const servers = await prisma.server.findMany({ where: { removedAt: null }, include: { alerts: { where: { resolvedAt: null } } } });
|
||||
const opened = [];
|
||||
const cleared = [];
|
||||
for (const server of servers) {
|
||||
const recent = await prisma.serverStat.findMany({ where: { serverId: server.id, granularity: 'minute', at: { gt: new Date(now.getTime() - 6 * MIN) } }, orderBy: { at: 'desc' }, take: 5 });
|
||||
const current = serverProblems(server, recent, restartsInTenMinutes(server.id), now);
|
||||
const open = new Map(server.alerts.map(a => [a.type, a]));
|
||||
for (const p of current) {
|
||||
if (open.has(p.type)) continue;
|
||||
await prisma.serverAlert.create({ data: { serverId: server.id, type: p.type, level: p.level, message: p.message, createdAt: now } });
|
||||
opened.push(`• ${server.name}: ${p.message}`);
|
||||
}
|
||||
const types = new Set(current.map(p => p.type));
|
||||
for (const [type, a] of open) {
|
||||
if (types.has(type)) continue;
|
||||
await prisma.serverAlert.update({ where: { id: a.id }, data: { resolvedAt: now } });
|
||||
cleared.push(`• ${server.name}: cleared: ${a.message}`);
|
||||
}
|
||||
}
|
||||
const lines = [...opened, ...cleared];
|
||||
if (lines.length && settings.alert_email) {
|
||||
await sendMail({
|
||||
to: settings.alert_email,
|
||||
subject: `Cross Code Hub: ${opened.length ? `${opened.length} server alert${opened.length === 1 ? '' : 's'}` : 'server alerts cleared'}`,
|
||||
text: `${lines.join('\n')}\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/servers`,
|
||||
}).catch(e => console.warn('[servers] alert email failed:', e?.message));
|
||||
}
|
||||
return { opened: opened.length, cleared: cleared.length };
|
||||
}
|
||||
|
||||
// ─── The port list (§6) ───────────────────────────────────────────────────────
|
||||
|
||||
async function portRange() {
|
||||
const s = await getSettings();
|
||||
const from = parseInt(s.port_range_start, 10) || 20000;
|
||||
const to = parseInt(s.port_range_end, 10) || 29999;
|
||||
return { from, to };
|
||||
}
|
||||
|
||||
/** Two free ports (web, api) for a deployment, in one transaction (unique across all servers). */
|
||||
async function allocatePorts(tx, serverId, now = new Date()) {
|
||||
const { from, to } = await portRange();
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext('hub:ports'))`;
|
||||
const reuseAfter = new Date(now.getTime() - 30 * DAY);
|
||||
const rows = await tx.port.findMany({ where: { port: { gte: from, lte: to } } });
|
||||
const taken = new Set(rows.filter(r => !r.releasedAt || r.releasedAt > reuseAfter).map(r => r.port));
|
||||
const free = [];
|
||||
for (let p = from; p <= to && free.length < 2; p++) if (!taken.has(p)) free.push(p);
|
||||
if (free.length < 2) throw fail(409, 'NO_PORTS', `No free ports left between ${from} and ${to} (Settings → Servers).`);
|
||||
const [web, api] = free;
|
||||
for (const [port, role] of [[web, 'web'], [api, 'api']]) {
|
||||
await tx.port.upsert({ where: { port }, update: { serverId, role, releasedAt: null, deploymentId: null, note: null }, create: { port, serverId, role } });
|
||||
}
|
||||
return { web, api };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
POLL_SECONDS, STATS_SECONDS, newId, hashToken, jobSigningKey, resetJobKeyForTests,
|
||||
createJoinToken, joinCommand, join, requireAgent,
|
||||
serverConfig, setServerConfig, cleanEnvValues, installDefaults,
|
||||
summariseStats, recordStats, rollupStats, serverProblems, runServerAlerts, restartsInTenMinutes,
|
||||
portRange, allocatePorts,
|
||||
};
|
||||
@@ -71,6 +71,13 @@ const DEFAULTS = {
|
||||
invoice_footer: 'Thank you for using Cross Events.',
|
||||
// Replies to billing emails go here (blank: business_email).
|
||||
billing_reply_to: '',
|
||||
// Servers and the agent (2.1.0). The port list hands out ports in this range (match frps's
|
||||
// allow_ports); install_defaults is the .env defaults layer (JSON, NAME → value); the central
|
||||
// server's IP is used to check a new install's DNS.
|
||||
port_range_start: '20000',
|
||||
port_range_end: '29999',
|
||||
install_defaults: '{"HUB_URL":"https://hub.crosscode.co.za"}',
|
||||
central_server_ip: '',
|
||||
};
|
||||
|
||||
// Stored encrypted and never sent to the browser: only "is one saved" (<key>_set).
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* A small in-memory stand-in for the Prisma client, enough for the servers / jobs tests: where
|
||||
* filters (equals, in, notIn, not, lt/lte/gt/gte, OR, AND, nested relation-free), include of the
|
||||
* relations listed in RELATIONS, orderBy, take, create / update / upsert / delete / count and
|
||||
* $transaction. Not a database: no constraints beyond what the code under test checks itself.
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
// model → relation → [target model, kind, localKey, foreignKey]
|
||||
const RELATIONS = {
|
||||
job: { server: ['server', 'one', 'serverId', 'id'], deployment: ['deployment', 'one', 'deploymentId', 'id'] },
|
||||
deployment: { server: ['server', 'one', 'serverId', 'id'], customer: ['customer', 'one', 'customerId', 'id'], install: ['install', 'one', 'installId', 'id'], jobs: ['job', 'many', 'id', 'deploymentId'], exports: ['export', 'many', 'id', 'deploymentId'] },
|
||||
server: { alerts: ['serverAlert', 'many', 'id', 'serverId'], deployments: ['deployment', 'many', 'id', 'serverId'], ports: ['port', 'many', 'id', 'serverId'] },
|
||||
licence: { install: ['install', 'oneBack', 'id', 'licenceId'] },
|
||||
install: { deployment: ['deployment', 'oneBack', 'id', 'installId'] },
|
||||
port: { server: ['server', 'one', 'serverId', 'id'] },
|
||||
export: { deployment: ['deployment', 'one', 'deploymentId', 'id'] },
|
||||
};
|
||||
const KEYS = { port: 'port', setting: 'key' };
|
||||
|
||||
const cmp = (a, b) => (a instanceof Date ? a.getTime() : a) - (b instanceof Date ? b.getTime() : b);
|
||||
|
||||
function matches(row, where = {}) {
|
||||
for (const [k, cond] of Object.entries(where || {})) {
|
||||
if (k === 'OR') { if (!cond.some(c => matches(row, c))) return false; continue; }
|
||||
if (k === 'AND') { if (!cond.every(c => matches(row, c))) return false; continue; }
|
||||
const v = row[k];
|
||||
if (cond === null) { if (v != null) return false; continue; }
|
||||
if (cond instanceof Date || typeof cond !== 'object') {
|
||||
if (cond instanceof Date ? !(v instanceof Date && v.getTime() === cond.getTime()) : v !== cond) return false;
|
||||
continue;
|
||||
}
|
||||
if ('in' in cond && !cond.in.includes(v)) return false;
|
||||
if ('notIn' in cond && cond.notIn.includes(v)) return false;
|
||||
if ('not' in cond && (cond.not === null ? v == null : v === cond.not)) return false;
|
||||
if ('lt' in cond && !(v != null && cmp(v, cond.lt) < 0)) return false;
|
||||
if ('lte' in cond && !(v != null && cmp(v, cond.lte) <= 0)) return false;
|
||||
if ('gt' in cond && !(v != null && cmp(v, cond.gt) > 0)) return false;
|
||||
if ('gte' in cond && !(v != null && cmp(v, cond.gte) >= 0)) return false;
|
||||
if ('equals' in cond && v !== cond.equals) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function createFakeDb() {
|
||||
const tables = {};
|
||||
const t = name => (tables[name] ||= []);
|
||||
const keyOf = name => KEYS[name] || 'id';
|
||||
|
||||
function include(name, row, inc) {
|
||||
if (!inc || !row) return row;
|
||||
const out = { ...row };
|
||||
for (const [rel, spec] of Object.entries(inc)) {
|
||||
if (!spec) continue;
|
||||
const [target, kind, local, foreign] = RELATIONS[name]?.[rel] || [];
|
||||
// A plain field in a `select` (rows are returned whole), or an unknown relation.
|
||||
if (!target) { if (spec === true && rel in row) continue; throw new Error(`fakeDb: no relation ${name}.${rel}`); }
|
||||
const opts = spec === true ? {} : spec;
|
||||
if (kind === 'one') {
|
||||
const r = t(target).find(x => x[foreign] === row[local]) || null;
|
||||
out[rel] = r ? include(target, r, opts.include) : null;
|
||||
} else if (kind === 'oneBack') {
|
||||
const r = t(target).find(x => x[foreign] === row[local]) || null;
|
||||
out[rel] = r ? include(target, r, opts.include) : null;
|
||||
} else {
|
||||
let list = t(target).filter(x => x[foreign] === row[local] && matches(x, opts.where));
|
||||
list = sort(list, opts.orderBy);
|
||||
if (opts.take) list = list.slice(0, opts.take);
|
||||
out[rel] = list.map(x => include(target, x, opts.include));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function sort(list, orderBy) {
|
||||
if (!orderBy) return list;
|
||||
const orders = Array.isArray(orderBy) ? orderBy : [orderBy];
|
||||
return [...list].sort((a, b) => {
|
||||
for (const o of orders) {
|
||||
const [k, dir] = Object.entries(o)[0];
|
||||
const c = a[k] == null ? -1 : b[k] == null ? 1 : typeof a[k] === 'string' ? a[k].localeCompare(b[k]) : cmp(a[k], b[k]);
|
||||
if (c) return dir === 'desc' ? -c : c;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
const defaults = {
|
||||
job: { status: 'queued', scheduled: false, emergency: false, createdAt: () => new Date() },
|
||||
deployment: { status: 'installing', product: 'events', createdAt: () => new Date() },
|
||||
server: { mode: 'church', joinedAt: () => new Date() },
|
||||
serverAlert: { createdAt: () => new Date(), resolvedAt: null },
|
||||
export: { bytes: 0, extended: false, deletedAt: null, createdAt: () => new Date() },
|
||||
notice: { createdAt: () => new Date(), updatedAt: () => new Date() },
|
||||
licence: { status: 'active', product: 'events' },
|
||||
};
|
||||
|
||||
function model(name) {
|
||||
const key = keyOf(name);
|
||||
const withDefaults = data => {
|
||||
const row = { ...data };
|
||||
for (const [k, v] of Object.entries(defaults[name] || {})) if (row[k] === undefined) row[k] = typeof v === 'function' ? v() : v;
|
||||
if (key === 'id' && !row.id) row.id = crypto.randomUUID();
|
||||
return row;
|
||||
};
|
||||
return {
|
||||
findUnique: async ({ where, include: inc, select }) => include(name, t(name).find(r => matches(r, where)) || null, inc || select),
|
||||
findFirst: async ({ where, include: inc, orderBy } = {}) => include(name, sort(t(name).filter(r => matches(r, where)), orderBy)[0] || null, inc),
|
||||
findMany: async ({ where, include: inc, orderBy, take, select } = {}) => {
|
||||
let list = sort(t(name).filter(r => matches(r, where)), orderBy);
|
||||
if (take) list = list.slice(0, take);
|
||||
return list.map(r => include(name, r, inc || select));
|
||||
},
|
||||
count: async ({ where } = {}) => t(name).filter(r => matches(r, where)).length,
|
||||
create: async ({ data }) => { const row = withDefaults(data); t(name).push(row); return { ...row }; },
|
||||
update: async ({ where, data }) => {
|
||||
const row = t(name).find(r => matches(r, where));
|
||||
if (!row) throw Object.assign(new Error(`fakeDb: ${name} not found`), { code: 'P2025' });
|
||||
Object.assign(row, Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined)));
|
||||
return { ...row };
|
||||
},
|
||||
updateMany: async ({ where, data }) => {
|
||||
const rows = t(name).filter(r => matches(r, where));
|
||||
for (const r of rows) Object.assign(r, data);
|
||||
return { count: rows.length };
|
||||
},
|
||||
upsert: async ({ where, update, create }) => {
|
||||
const row = t(name).find(r => matches(r, where));
|
||||
if (row) { Object.assign(row, update); return { ...row }; }
|
||||
const created = withDefaults(create);
|
||||
t(name).push(created);
|
||||
return { ...created };
|
||||
},
|
||||
delete: async ({ where }) => { const i = t(name).findIndex(r => matches(r, where)); const [r] = tables[name].splice(i, 1); return r; },
|
||||
deleteMany: async ({ where } = {}) => { const before = t(name).length; tables[name] = t(name).filter(r => !matches(r, where)); return { count: before - tables[name].length }; },
|
||||
groupBy: async () => [],
|
||||
};
|
||||
}
|
||||
|
||||
const db = new Proxy({ tables }, {
|
||||
get(target, prop) {
|
||||
if (prop === 'tables') return tables;
|
||||
if (prop === '$transaction') return async fn => (typeof fn === 'function' ? fn(db) : Promise.all(fn));
|
||||
if (prop === '$executeRaw' || prop === '$executeRawUnsafe') return async () => 0;
|
||||
if (typeof prop !== 'string' || prop.startsWith('_') || prop === 'then') return undefined;
|
||||
return (target[prop] ||= model(prop));
|
||||
},
|
||||
});
|
||||
return db;
|
||||
}
|
||||
|
||||
module.exports = { createFakeDb, matches };
|
||||
@@ -0,0 +1,314 @@
|
||||
// Servers and the agent (2.1.0, crosscode-platform docs/AGENT-1.0-PLAN.md): joining, signed agent
|
||||
// requests, jobs (signed, config sealed to the server, one at a time, missed when late), reports
|
||||
// and what follows (installs, updates, batches, uninstall + export), the port list and alerts.
|
||||
jest.mock('../src/config/db', () => require('./fakeDb').createFakeDb());
|
||||
const mockMails = [];
|
||||
jest.mock('../src/utils/mail', () => ({ sendMail: jest.fn(async m => { mockMails.push(m); }), smtpConfigured: async () => true }));
|
||||
|
||||
process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-test-encryption-key';
|
||||
process.env.FRONTEND_URL = 'https://hub.test';
|
||||
|
||||
const { agent } = require('@crosscode/contracts');
|
||||
const signing = require('@crosscode/contracts/signing');
|
||||
const db = require('../src/config/db');
|
||||
const servers = require('../src/utils/servers');
|
||||
const jobs = require('../src/utils/jobs');
|
||||
const { encrypt } = require('../src/utils/crypto');
|
||||
const { generateSecret, codeAt, STEP } = require('../src/utils/totp');
|
||||
|
||||
const hubKey = signing.generateEd25519();
|
||||
process.env.HUB_JOB_SIGNING_KEY = hubKey.privateKeyPem;
|
||||
global.fetch = jest.fn(async () => { throw new Error('no network in tests'); });
|
||||
|
||||
const NOW = new Date('2026-11-20T08:00:00.000Z');
|
||||
const H = 60 * 60 * 1000;
|
||||
const keys = { ed: signing.generateEd25519(), x: signing.generateX25519() };
|
||||
const totpSecret = generateSecret();
|
||||
const admin = { id: 'admin-1', name: 'Joshua', totpEnabled: true, totpSecret: encrypt(totpSecret) };
|
||||
const totpNow = () => codeAt(totpSecret, Math.floor(Date.now() / 1000 / STEP));
|
||||
|
||||
async function joinServer(mode = 'church', name = 'church-1') {
|
||||
const t = await servers.createJoinToken({ name, mode }, NOW);
|
||||
const reply = await servers.join({ agentApiVersion: 1, token: t.token, mode, hostname: name, agentVersion: '1.0.0', publicKeys: { ed25519: keys.ed.publicKey, x25519: keys.x.publicKey } }, NOW);
|
||||
const server = await db.server.findUnique({ where: { id: reply.serverId } });
|
||||
return { reply, server, token: t.token };
|
||||
}
|
||||
|
||||
async function seed() {
|
||||
for (const k of Object.keys(db.tables)) db.tables[k].length = 0;
|
||||
mockMails.length = 0;
|
||||
servers.resetJobKeyForTests();
|
||||
await db.setting.create({ data: { key: 'alert_email', value: 'joshua@crosscode.test' } });
|
||||
await db.customer.create({ data: { id: 'cust-1', name: 'Hope Church', billingCycle: 'none' } });
|
||||
await db.release.create({ data: { id: 'r1', product: 'events', version: '2.3.0', notes: '- New things', releasedAt: NOW } });
|
||||
await db.release.create({ data: { id: 'r2', product: 'events', version: '2.4.0', notes: '- Newer things', releasedAt: NOW } });
|
||||
}
|
||||
|
||||
const signedReport = (job, status, extra = {}) => ({
|
||||
schema: 'crosscode.agent-report/1', jobId: job.id, serverId: job.serverId, type: job.type, status,
|
||||
startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), steps: [{ name: 'step', startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), outcome: status === 'succeeded' ? 'ok' : 'failed' }],
|
||||
result: {}, log: ['==> done'], ...extra,
|
||||
});
|
||||
|
||||
beforeEach(seed);
|
||||
|
||||
describe('joining', () => {
|
||||
test('a one-time token joins a server once and returns the pinned job key', async () => {
|
||||
const { reply, token } = await joinServer();
|
||||
expect(agent.joinResponseSchema.safeParse(reply).success).toBe(true);
|
||||
expect(reply.hubJobKey).toBe(hubKey.publicKey);
|
||||
await expect(servers.join({ agentApiVersion: 1, token, mode: 'church', hostname: 'x', agentVersion: '1.0.0', publicKeys: { ed25519: keys.ed.publicKey, x25519: keys.x.publicKey } }, NOW)).rejects.toMatchObject({ code: 'BAD_TOKEN' });
|
||||
});
|
||||
|
||||
test('an expired token or the wrong mode is refused', async () => {
|
||||
const t = await servers.createJoinToken({ name: 'late', mode: 'church' }, NOW);
|
||||
const body = { agentApiVersion: 1, token: t.token, mode: 'church', hostname: 'x', agentVersion: '1.0.0', publicKeys: { ed25519: keys.ed.publicKey, x25519: keys.x.publicKey } };
|
||||
await expect(servers.join(body, new Date(NOW.getTime() + 2 * H))).rejects.toMatchObject({ code: 'BAD_TOKEN' });
|
||||
await expect(servers.join({ ...body, mode: 'central' }, NOW)).rejects.toMatchObject({ code: 'WRONG_MODE' });
|
||||
});
|
||||
|
||||
test('the install command carries the token and --central', () => {
|
||||
expect(servers.joinCommand('tok', 'central', 'https://hub.test')).toMatch(/install\.sh \| sudo bash -s -- --hub https:\/\/hub\.test --token tok --central$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('signed agent requests', () => {
|
||||
const call = async (server, headers, raw) => {
|
||||
const req = { headers, rawBody: raw };
|
||||
let status = 200;
|
||||
let body = null;
|
||||
const res = { status(s) { status = s; return this; }, json(b) { body = b; return this; } };
|
||||
let passed = false;
|
||||
await servers.requireAgent(req, res, () => { passed = true; });
|
||||
return { passed, status, body, req };
|
||||
};
|
||||
|
||||
test('the server\'s key over the exact body passes; anything else is refused', async () => {
|
||||
const { server } = await joinServer();
|
||||
const raw = JSON.stringify({ agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null });
|
||||
const h = signing.signAgentRequest({ serverId: server.id, privateKeyPem: keys.ed.privateKeyPem, rawBody: raw });
|
||||
expect((await call(server, h, raw)).passed).toBe(true);
|
||||
expect(await call(server, h, `${raw} `)).toMatchObject({ passed: false, status: 401 });
|
||||
const other = signing.signAgentRequest({ serverId: server.id, privateKeyPem: signing.generateEd25519().privateKeyPem, rawBody: raw });
|
||||
expect(await call(server, other, raw)).toMatchObject({ passed: false, status: 401 });
|
||||
expect(await call(server, { ...h, [agent.AGENT_HEADERS.server]: 'srv_unknown000' }, raw)).toMatchObject({ passed: false, status: 404 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('jobs', () => {
|
||||
test('a new install: licence, two ports, an install job the agent can verify and open', async () => {
|
||||
const { server } = await joinServer();
|
||||
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback', DB_ADMIN_URL: 'postgresql://admin:pw@10.0.0.5/postgres' });
|
||||
const { deployment } = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za', adminName: 'Jane', adminEmail: 'jane@hope.test' }, admin, NOW);
|
||||
expect(deployment).toMatchObject({ shortName: 'hope', webPort: 20000, apiPort: 20001, status: 'installing' });
|
||||
|
||||
const polled = await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW);
|
||||
expect(polled.jobs).toHaveLength(1);
|
||||
const job = polled.jobs[0];
|
||||
expect(signing.verifyJob(job, hubKey.publicKey)).toBe(true);
|
||||
expect(agent.agentJobSchema.safeParse(job).success).toBe(true);
|
||||
expect(job.args).toMatchObject({ church: 'hope', versions: { events: 'events@2.4.0' }, ports: { events: { web: 20000, api: 20001 } } });
|
||||
const config = signing.openConfig(job.config, keys.x.privateKeyPem);
|
||||
expect(config.server).toMatchObject({ TRUST_PROXY: 'loopback', DB_ADMIN_URL: 'postgresql://admin:pw@10.0.0.5/postgres' });
|
||||
expect(config.install.events).toMatchObject({ HUB_ADMIN_EMAIL: 'jane@hope.test' });
|
||||
expect(config.install.events.HUB_LICENCE_KEY).toMatch(/^CEH-/);
|
||||
expect(JSON.stringify(job)).not.toContain('pw@');
|
||||
|
||||
// One at a time: nothing else while it runs.
|
||||
expect((await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW)).jobs).toEqual([]);
|
||||
});
|
||||
|
||||
test('a new install is refused while required server settings are missing, or the agent is offline', async () => {
|
||||
const { server } = await joinServer();
|
||||
await expect(jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'CONFIG_MISSING', message: expect.stringContaining('TRUST_PROXY') });
|
||||
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
|
||||
await expect(jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, new Date(NOW.getTime() + H))).rejects.toMatchObject({ code: 'AGENT_OFFLINE' });
|
||||
});
|
||||
|
||||
test('a successful install waits for the proxy, asks the central server to check the ports, and sends the FastPanel email', async () => {
|
||||
const { server } = await joinServer();
|
||||
const central = (await joinServer('central', 'central')).server;
|
||||
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
|
||||
const { deployment } = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
|
||||
const [job] = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW)).jobs;
|
||||
await jobs.receiveReport(server, signedReport(job, 'succeeded', { result: { versions: { events: 'events@2.4.0' }, key: 'nope' } }), NOW);
|
||||
expect(await db.deployment.findUnique({ where: { id: deployment.id } })).toMatchObject({ status: 'waiting_for_proxy', version: '2.4.0' });
|
||||
expect(await db.job.findFirst({ where: { serverId: central.id, type: 'check-ports' } })).toMatchObject({ args: { ports: [20000, 20001] } });
|
||||
const mail = mockMails.find(m => m.subject.includes('Installed: hope'));
|
||||
expect(mail.text).toContain('/api → http://127.0.0.1:20001');
|
||||
expect(mail.text).toContain('everything else → http://127.0.0.1:20000');
|
||||
});
|
||||
|
||||
test('a failed install frees its ports again', async () => {
|
||||
const { server } = await joinServer();
|
||||
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
|
||||
const { deployment } = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
|
||||
const [job] = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW)).jobs;
|
||||
await jobs.receiveReport(server, signedReport(job, 'failed'), NOW);
|
||||
expect(await db.deployment.findUnique({ where: { id: deployment.id } })).toMatchObject({ status: 'failed' });
|
||||
expect(await db.port.count({ where: { port: { in: [20000, 20001] } } })).toBe(0);
|
||||
});
|
||||
|
||||
test('a job not picked up in its window is missed: nothing runs late', async () => {
|
||||
const { server } = await joinServer();
|
||||
const job = await jobs.makeJob(db, { serverId: server.id, type: 'status', args: {}, notBefore: NOW });
|
||||
await jobs.tick(new Date(NOW.getTime() + 16 * 60 * 1000));
|
||||
expect(await db.job.findUnique({ where: { id: job.id } })).toMatchObject({ status: 'missed' });
|
||||
expect((await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, new Date(NOW.getTime() + 16 * 60 * 1000))).jobs).toEqual([]);
|
||||
expect(mockMails.some(m => m.subject.includes('Missed job'))).toBe(true);
|
||||
});
|
||||
|
||||
test('a job isn\'t handed out before its time', async () => {
|
||||
const { server } = await joinServer();
|
||||
await jobs.makeJob(db, { serverId: server.id, type: 'status', args: {}, notBefore: new Date(NOW.getTime() + H) });
|
||||
expect((await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW)).jobs).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('scheduled updates (§8)', () => {
|
||||
async function liveDeployments(n) {
|
||||
const { server } = await joinServer();
|
||||
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
|
||||
const out = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const install = await db.install.create({ data: { id: `inst-${i}`, customerId: 'cust-1', product: 'events', name: `Church ${i}`, url: `https://events.c${i}.co.za`, secret: 'x', version: '2.3.0', adminContact: { name: `Admin ${i}`, email: `admin${i}@c.test` } } });
|
||||
out.push(await db.deployment.create({ data: { id: `dep-${i}`, serverId: server.id, customerId: 'cust-1', installId: install.id, product: 'events', shortName: `c${i}`, domain: `events.c${i}.co.za`, webPort: 20000 + 2 * i, apiPort: 20001 + 2 * i, status: 'live' } }));
|
||||
}
|
||||
return { server, deployments: out };
|
||||
}
|
||||
|
||||
test('at least 4 hours ahead; emergency needs 15 minutes, a reason and 2FA', async () => {
|
||||
const { deployments } = await liveDeployments(1);
|
||||
const ids = [deployments[0].id];
|
||||
await expect(jobs.scheduleUpdate({ deploymentIds: ids, version: '2.4.0', at: new Date(NOW.getTime() + 3 * H) }, admin, NOW)).rejects.toMatchObject({ code: 'TOO_SOON' });
|
||||
await expect(jobs.scheduleUpdate({ deploymentIds: ids, version: '2.4.0', at: new Date(NOW.getTime() + 20 * 60 * 1000), emergency: true, totp: totpNow() }, admin, NOW)).rejects.toMatchObject({ status: 400, message: expect.stringContaining('reason') });
|
||||
await expect(jobs.scheduleUpdate({ deploymentIds: ids, version: '2.4.0', at: new Date(NOW.getTime() + 20 * 60 * 1000), emergency: true, reason: 'Security fix', totp: '000000' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_TOTP' });
|
||||
const ok = await jobs.scheduleUpdate({ deploymentIds: ids, version: '2.4.0', at: new Date(NOW.getTime() + 20 * 60 * 1000), emergency: true, reason: 'Security fix', totp: totpNow() }, admin, NOW);
|
||||
expect(ok.jobs[0]).toMatchObject({ emergency: true, reason: 'Security fix', args: { versions: ['events@2.4.0'] } });
|
||||
});
|
||||
|
||||
test('the church gets an email with what\'s new and a banner straight away', async () => {
|
||||
const { deployments } = await liveDeployments(1);
|
||||
const at = new Date(NOW.getTime() + 5 * H);
|
||||
const { jobs: [job] } = await jobs.scheduleUpdate({ deploymentIds: [deployments[0].id], version: '2.4.0', at }, admin, NOW);
|
||||
expect(mockMails.find(m => m.to === 'admin0@c.test')?.text).toContain('Newer things');
|
||||
const notice = await db.notice.findUnique({ where: { id: job.noticeId } });
|
||||
expect(notice).toMatchObject({ allInstalls: false, installIds: ['inst-0'], showBanner: true });
|
||||
});
|
||||
|
||||
test('a batch runs one at a time and stops at the first failure; the rest are told it\'s postponed', async () => {
|
||||
const { server, deployments } = await liveDeployments(3);
|
||||
const at = new Date(NOW.getTime() + 5 * H);
|
||||
const { jobs: made, batchId } = await jobs.scheduleUpdate({ deploymentIds: deployments.map(d => d.id), version: '2.4.0', at }, admin, NOW);
|
||||
expect(batchId).toMatch(/^batch_/);
|
||||
expect(made.map(j => j.status)).toEqual(['queued', 'scheduled', 'scheduled']);
|
||||
|
||||
const poll = when => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, when);
|
||||
const first = (await poll(at)).jobs[0];
|
||||
await jobs.receiveReport(server, signedReport(first, 'succeeded'), at);
|
||||
expect((await db.job.findUnique({ where: { id: made[1].id } })).status).toBe('queued');
|
||||
|
||||
const second = (await poll(at)).jobs[0];
|
||||
expect(second.id).toBe(made[1].id);
|
||||
mockMails.length = 0;
|
||||
await jobs.receiveReport(server, signedReport(second, 'rolled-back'), at);
|
||||
expect((await db.job.findUnique({ where: { id: made[1].id } })).status).toBe('rolled_back');
|
||||
expect((await db.job.findUnique({ where: { id: made[2].id } })).status).toBe('cancelled');
|
||||
expect(mockMails.find(m => m.to === 'admin1@c.test')?.subject).toContain('didn\'t go through');
|
||||
expect(mockMails.find(m => m.to === 'admin2@c.test')?.subject).toContain('postponed');
|
||||
expect(mockMails.some(m => m.subject.includes('Batch stopped'))).toBe(true);
|
||||
});
|
||||
|
||||
test('uninstall: 2FA and the short name; the export goes first and its key is never stored', async () => {
|
||||
const { server, deployments } = await liveDeployments(1);
|
||||
const d = deployments[0];
|
||||
await expect(jobs.scheduleUninstall({ deploymentId: d.id, totp: totpNow(), confirm: 'wrong' }, admin, NOW)).rejects.toMatchObject({ code: 'CONFIRM' });
|
||||
const at = new Date(NOW.getTime() + 5 * H);
|
||||
const { exportJob, uninstallJob } = await jobs.scheduleUninstall({ deploymentId: d.id, totp: totpNow(), confirm: 'c0', at }, admin, NOW);
|
||||
expect(uninstallJob.status).toBe('scheduled');
|
||||
|
||||
const job = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, at)).jobs[0];
|
||||
expect(job.id).toBe(exportJob.id);
|
||||
await jobs.receiveExport(server, job.args.exportId, Buffer.from('encrypted bytes'));
|
||||
await jobs.receiveReport(server, signedReport(job, 'succeeded', { result: { key: 'SECRET-KEY-abc', encryptedBytes: 15 } }), at);
|
||||
const stored = await db.job.findUnique({ where: { id: job.id } });
|
||||
expect(JSON.stringify(stored)).not.toContain('SECRET-KEY-abc');
|
||||
expect(mockMails.find(m => m.to === 'admin0@c.test' && m.subject.includes('data'))?.text).toContain(`/download/${job.args.exportId}#SECRET-KEY-abc`);
|
||||
expect((await db.job.findUnique({ where: { id: uninstallJob.id } })).status).toBe('queued');
|
||||
|
||||
const un = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, at)).jobs[0];
|
||||
expect(un.args).toEqual({ church: 'c0' });
|
||||
await jobs.receiveReport(server, signedReport(un, 'succeeded'), at);
|
||||
expect(await db.deployment.findUnique({ where: { id: d.id } })).toMatchObject({ status: 'removed' });
|
||||
expect((await db.install.findUnique({ where: { id: 'inst-0' } })).releasedAt).toEqual(at);
|
||||
expect(await db.job.findFirst({ where: { type: 'purge', deploymentId: d.id } })).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ports and alerts', () => {
|
||||
test('ports are unique, and a released one is reused only after 30 days', async () => {
|
||||
const { server } = await joinServer();
|
||||
await db.port.create({ data: { port: 20000, role: 'taken' } });
|
||||
await db.port.create({ data: { port: 20001, role: 'web', releasedAt: new Date(NOW.getTime() - 10 * 24 * H) } });
|
||||
await db.port.create({ data: { port: 20002, role: 'api', releasedAt: new Date(NOW.getTime() - 40 * 24 * H) } });
|
||||
expect(await servers.allocatePorts(db, server.id, NOW)).toEqual({ web: 20002, api: 20003 });
|
||||
});
|
||||
|
||||
test('server problems: silent agent, full disk, frpc down, the central bind address', () => {
|
||||
const base = { mode: 'church', lastSeenAt: NOW, lastStats: { disks: [{ mount: '/', totalBytes: 100, usedBytes: 90 }], frpcRunning: false } };
|
||||
expect(servers.serverProblems(base, [], [], NOW).map(p => p.type)).toEqual(['disk:/', 'frpc_down']);
|
||||
expect(servers.serverProblems({ ...base, lastSeenAt: new Date(NOW.getTime() - 6 * 60 * 1000) }, [], [], NOW)[0].type).toBe('agent_silent');
|
||||
const central = { mode: 'central', lastSeenAt: NOW, lastStats: { disks: [], central: { proxyBindAddr: null, frpsRunning: true } } };
|
||||
expect(servers.serverProblems(central, [], [], NOW).map(p => p.type)).toEqual(['proxy_bind_addr']);
|
||||
const ram = Array.from({ length: 5 }, () => ({ ramUsedPercent: 95 }));
|
||||
expect(servers.serverProblems({ ...base, lastStats: { disks: [] } }, ram, [], NOW).map(p => p.type)).toEqual(['ram_high']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reusing a short name (found in the VM test)', () => {
|
||||
test('after a failed install the same short name can be used again', async () => {
|
||||
const { server } = await joinServer();
|
||||
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
|
||||
const first = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
|
||||
const [job] = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW)).jobs;
|
||||
await jobs.receiveReport(server, signedReport(job, 'failed'), NOW);
|
||||
const again = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
|
||||
expect(again.deployment.id).not.toBe(first.deployment.id);
|
||||
expect(await db.deployment.findUnique({ where: { id: first.deployment.id } })).toBeNull();
|
||||
expect(again.deployment).toMatchObject({ webPort: 20000, apiPort: 20001 });
|
||||
});
|
||||
|
||||
test('a live install keeps its name', async () => {
|
||||
const { server } = await joinServer();
|
||||
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
|
||||
await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
|
||||
await expect(jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.other.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'SHORT_NAME_TAKEN' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('settings for servers (found in the VM test)', () => {
|
||||
test('install defaults, the port range and the central IP are saved', async () => {
|
||||
const { setSettings } = require('../src/utils/settings');
|
||||
await setSettings({ install_defaults: '{"HUB_URL":"https://hub.test","SENTRY_DSN":"x"}', port_range_start: '21000', port_range_end: '21100', central_server_ip: '203.0.113.10' });
|
||||
expect(await servers.installDefaults()).toEqual({ HUB_URL: 'https://hub.test', SENTRY_DSN: 'x' });
|
||||
expect(await servers.portRange()).toEqual({ from: 21000, to: 21100 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('banners reach a site the Hub installed (found in the VM test)', () => {
|
||||
test('an update to a deployment registered through its licence gets a banner', async () => {
|
||||
const { server } = await joinServer();
|
||||
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
|
||||
await db.release.create({ data: { product: 'events', version: '2.4.0', notes: 'New', releasedAt: NOW } });
|
||||
// A Hub install: the deployment knows its licence, not yet its install.
|
||||
await db.licence.create({ data: { id: 'lic-9', customerId: 'cust-1', product: 'events', key: 'CEH-TEST' } });
|
||||
await db.install.create({ data: { id: 'inst-9', customerId: 'cust-1', licenceId: 'lic-9', product: 'events', name: 'Hope', url: 'https://events.hope.test', secret: 'x', version: '2.3.0' } });
|
||||
const d = await db.deployment.create({ data: { id: 'dep-9', serverId: server.id, customerId: 'cust-1', licenceId: 'lic-9', product: 'events', shortName: 'hope', domain: 'events.hope.test', webPort: 20000, apiPort: 20001, status: 'live', version: '2.3.0' } });
|
||||
const r = await jobs.scheduleUpdate({ deploymentIds: [d.id], version: '2.4.0', at: new Date(NOW.getTime() + 5 * H) }, admin, NOW);
|
||||
const job = await db.job.findUnique({ where: { id: r.jobs[0].id } });
|
||||
expect(job.noticeId).toBeTruthy();
|
||||
const notice = await db.notice.findUnique({ where: { id: job.noticeId } });
|
||||
expect(notice).toMatchObject({ showBanner: true, installIds: ['inst-9'] });
|
||||
expect((await db.deployment.findUnique({ where: { id: d.id } })).installId).toBe('inst-9');
|
||||
});
|
||||
});
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -393,6 +393,32 @@ address, AI per church). The migrations carry everything over, but one thing has
|
||||
its certificate (step 5), add it to `FRONTEND_URL` only if you move the dashboard to it, and keep
|
||||
`events-hub.crosscode.co.za` working: installs point at it (`HUB_URL`) until they're updated.
|
||||
|
||||
### Upgrading to 2.1 (servers and the agent)
|
||||
|
||||
2.1 adds servers: an agent on each server polls the Hub for signed jobs (installs, scheduled
|
||||
updates, adopts, uninstalls) and sends its stats (crosscode-platform `docs/AGENT-1.0-PLAN.md`). The
|
||||
migration only adds tables. The Hub never connects to a server, so nothing new is opened in frp
|
||||
or FASTPANEL: agents reach the Hub on its normal address.
|
||||
|
||||
1. **A job-signing key**, separate from the licence key: in `backend/`,
|
||||
`npm run generate-keys -- --job` → `keys/hub-job-key.pem`. Back it up with the licence key.
|
||||
In `.env`: `HUB_JOB_SIGNING_KEY_FILE=./keys/hub-job-key.pem` and `HUB_PUBLIC_URL=https://hub.crosscode.co.za`
|
||||
(the address servers use; it goes in the Add server command). Agents pin the job key when they
|
||||
join: replacing it later means every server joins again.
|
||||
2. **Deploy** as usual: `bash scripts/deploy.sh v2.1.0`.
|
||||
3. **Servers → Ports & defaults:** the port range (match `allow_ports` in frps.ini), the central
|
||||
server's IP (to check a new install's DNS), and the install defaults (`HUB_URL` is filled in).
|
||||
Mark ports used by tunnels written by hand as taken.
|
||||
4. **On the central server** first: check `frps.ini` has `proxy_bind_addr = 127.0.0.1` (and that
|
||||
every FASTPANEL site still answers after restarting frps), then Servers → Add server →
|
||||
Central, and run the command it shows as root.
|
||||
5. **Each church server:** Add server → Church, run the command, then on its page set its
|
||||
configuration: `TRUST_PROXY` (`loopback` behind frp) and the database (`DB_HOST`, `DB_PORT`,
|
||||
`DB_ADMIN_URL`, or nothing for the local PostgreSQL).
|
||||
6. **Existing installs:** Servers → Installs → Link existing (server, folder name, its two ports).
|
||||
Installs still on 2.1.x from `hope-events` then get a **Move onto the monorepo** (an `adopt` job,
|
||||
planned like an update, at least 4 hours ahead with notice to the church).
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useParams } from "next/navigation";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { fmtDate } from "@/lib/format";
|
||||
import { Loading, Message, PageTitle } from "@/components/ui";
|
||||
import { ServersNav, StatusPill, type Job } from "@/components/servers";
|
||||
|
||||
type Msg = { type: "ok" | "err"; text: string } | null;
|
||||
|
||||
const OUTCOME: Record<string, string> = { ok: "✓", failed: "✗", skipped: "–", "rolled-back": "↺" };
|
||||
|
||||
/** One job and its full report: steps, result and the last log lines (§11). */
|
||||
export default function JobPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [job, setJob] = useState<Job | null>(null);
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
const load = useCallback(() => api<{ job: Job }>(`/api/admin/jobs/${id}`).then(r => setJob(r.job)).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
|
||||
useEffect(() => {
|
||||
load();
|
||||
const t = setInterval(() => { if (!job || ["queued", "delivered", "scheduled"].includes(job.status)) load(); }, 10000);
|
||||
return () => clearInterval(t);
|
||||
}, [load, job]);
|
||||
|
||||
const post = async (path: string, ok: string) => {
|
||||
try { await api(path, { method: "POST", body: {} }); setMsg({ type: "ok", text: ok }); load(); } catch (e) { setMsg({ type: "err", text: errorText(e) }); }
|
||||
};
|
||||
|
||||
if (!job) return <div><ServersNav active="/jobs" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
|
||||
const r = job.report;
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<PageTitle title={`${job.type}${job.deployment ? `: ${job.deployment.shortName}` : ""}`} subtitle={<>on <Link className="text-indigo-700 hover:underline" href={`/servers/${job.serverId}`}>{job.server?.name}</Link> · {job.id} <StatusPill status={job.status} /></>}
|
||||
actions={<div className="flex gap-2">
|
||||
{["queued", "scheduled"].includes(job.status) && <button className="btn-secondary" onClick={() => post(`/api/admin/jobs/${job.id}/cancel`, "Cancelled.")}>Cancel</button>}
|
||||
{job.type === "purge" && job.status === "queued" && job.message !== "extended" && <button className="btn-secondary" onClick={() => post(`/api/admin/jobs/${job.id}/extend`, "Put off by 30 days.")}>Keep 30 days longer</button>}
|
||||
</div>} />
|
||||
<ServersNav active="/jobs" />
|
||||
<Message msg={msg} />
|
||||
</div>
|
||||
<div className="card grid gap-2 text-sm md:grid-cols-2">
|
||||
<div><span className="text-slate-500">Window:</span> {fmtDate(job.notBefore)} – {fmtDate(job.expiresAt)}</div>
|
||||
<div><span className="text-slate-500">Handed to the agent:</span> {fmtDate(job.deliveredAt)}</div>
|
||||
<div><span className="text-slate-500">Finished:</span> {fmtDate(job.finishedAt)}</div>
|
||||
{job.reason && <div><span className="text-slate-500">Reason:</span> {job.reason}</div>}
|
||||
{job.message && <div className="md:col-span-2"><span className="text-slate-500">Result:</span> {job.message}</div>}
|
||||
<div className="md:col-span-2"><span className="text-slate-500">Arguments:</span> <code className="text-xs">{JSON.stringify(job.args)}</code></div>
|
||||
</div>
|
||||
{r && (
|
||||
<>
|
||||
<div className="card">
|
||||
<h2 className="font-medium">Steps</h2>
|
||||
<ol className="mt-3 space-y-1 text-sm">
|
||||
{r.steps.map((s, i) => <li key={i} className={s.outcome === "failed" ? "text-red-700" : ""}><span className="inline-block w-5" aria-label={s.outcome}>{OUTCOME[s.outcome] || "•"}</span>{s.name}{s.detail && <span className="text-xs text-slate-500"> ({s.detail})</span>}</li>)}
|
||||
{!r.steps.length && <li className="text-slate-500">No steps reported.</li>}
|
||||
</ol>
|
||||
</div>
|
||||
{Object.keys(r.result || {}).length > 0 && <div className="card"><h2 className="font-medium">Result</h2><pre className="mt-3 overflow-x-auto text-xs">{JSON.stringify(r.result, null, 2)}</pre></div>}
|
||||
<div className="card"><h2 className="font-medium">Last log lines</h2><pre className="mt-3 max-h-96 overflow-auto rounded-lg bg-slate-900 p-3 text-xs text-slate-100">{(r.log || []).join("\n") || "(none)"}</pre></div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { fmtDate } from "@/lib/format";
|
||||
import { Loading, Message, PageTitle } from "@/components/ui";
|
||||
import { ServersNav, StatusPill, type Job } from "@/components/servers";
|
||||
|
||||
const FILTERS = [
|
||||
{ key: "", label: "All" },
|
||||
{ key: "upcoming", label: "Planned and running" },
|
||||
{ key: "failed", label: "Failed" },
|
||||
{ key: "rolled_back", label: "Rolled back" },
|
||||
{ key: "missed", label: "Missed" },
|
||||
{ key: "refused", label: "Refused" },
|
||||
];
|
||||
|
||||
/** Every job sent to a server's agent, newest first (§11: the full report is on each job). */
|
||||
export default function JobsPage() {
|
||||
const [filter, setFilter] = useState("");
|
||||
const [jobs, setJobs] = useState<Job[] | null>(null);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
const q = filter === "upcoming" ? "?upcoming=true" : filter ? `?status=${filter}` : "";
|
||||
setJobs(null);
|
||||
api<{ jobs: Job[] }>(`/api/admin/jobs${q}`).then(r => setJobs(r.jobs)).catch(e => setErr(errorText(e)));
|
||||
}, [filter]);
|
||||
return (
|
||||
<div>
|
||||
<PageTitle title="Jobs" subtitle="Installs, updates, adopts, exports, uninstalls and checks run by the agents." />
|
||||
<ServersNav active="/jobs" />
|
||||
{err && <Message msg={{ type: "err", text: err }} />}
|
||||
<div className="mb-4 flex flex-wrap gap-2">{FILTERS.map(f => <button key={f.key} className={filter === f.key ? "btn-primary" : "btn-secondary"} onClick={() => setFilter(f.key)}>{f.label}</button>)}</div>
|
||||
{!jobs ? <Loading /> : (
|
||||
<div className="card overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>Server</th><th>Install</th><th>When</th><th>Status</th><th>Result</th></tr></thead>
|
||||
<tbody>{jobs.map(j => (
|
||||
<tr key={j.id} className="border-t">
|
||||
<td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td>
|
||||
<td>{j.server?.name}</td><td>{j.deployment?.shortName || String(j.args?.church || "–")}</td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td>
|
||||
<td className="max-w-sm truncate text-xs text-slate-500">{j.message}</td>
|
||||
</tr>
|
||||
))}</tbody>
|
||||
</table>
|
||||
{!jobs.length && <p className="mt-2 text-sm text-slate-500">No jobs.</p>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { LayoutDashboard, Building2, BellRing, Settings, LogOut, Rocket, Megaphone, Receipt } from "lucide-react";
|
||||
import { LayoutDashboard, Building2, BellRing, Settings, LogOut, Rocket, Megaphone, Receipt, Server } from "lucide-react";
|
||||
import { api, getToken, setToken } from "@/lib/api";
|
||||
import { Logo } from "@/components/ui";
|
||||
|
||||
@@ -13,6 +13,7 @@ const NAV = [
|
||||
{ href: "/", label: "Installs", icon: LayoutDashboard },
|
||||
{ href: "/customers", label: "Customers", icon: Building2 },
|
||||
{ href: "/billing", label: "Billing", icon: Receipt },
|
||||
{ href: "/servers", label: "Servers", icon: Server },
|
||||
{ href: "/alerts", label: "Alerts", icon: BellRing },
|
||||
{ href: "/releases", label: "Releases", icon: Rocket },
|
||||
{ href: "/notices", label: "Notices", icon: Megaphone },
|
||||
@@ -32,7 +33,7 @@ export default function HubLayout({ children }: { children: React.ReactNode }) {
|
||||
|
||||
if (!me) return <div className="flex min-h-screen items-center justify-center text-sm text-slate-400">Loading…</div>;
|
||||
|
||||
const active = (href: string) => (href === "/" ? pathname === "/" || pathname.startsWith("/installs") : pathname.startsWith(href));
|
||||
const active = (href: string) => (href === "/" ? pathname === "/" || pathname.startsWith("/installs") : href === "/servers" ? pathname.startsWith("/servers") || pathname.startsWith("/jobs") : pathname.startsWith(href));
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen">
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { Plus, Trash2 } from "lucide-react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { ago, bytes, fmtDate } from "@/lib/format";
|
||||
import { Loading, Message, PageTitle } from "@/components/ui";
|
||||
import { PercentChart, ServersNav, StatusPill, pct, type Deployment, type Job, type ServerSummary } from "@/components/servers";
|
||||
|
||||
type Msg = { type: "ok" | "err"; text: string } | null;
|
||||
type Detail = {
|
||||
server: ServerSummary;
|
||||
config: Record<string, string>;
|
||||
processes: { name: string; church: string | null; product: string | null; status: string; memoryBytes: number; cpuPercent: number; restarts: number; uptimeSeconds: number }[];
|
||||
stats: { at: string; cpuPercent: number; cpuPeak: number; ramUsedPercent: number; ramPeak: number; diskUsedPercent: number }[];
|
||||
deployments: (Deployment & { customer: { id: string; name: string } })[];
|
||||
jobs: Job[];
|
||||
alerts: { id: string; type: string; level: string; message: string; createdAt: string; resolvedAt: string | null }[];
|
||||
ports: { port: number; role: string; note: string | null; releasedAt: string | null }[];
|
||||
};
|
||||
|
||||
/** The settings a church server's jobs need (§5); others can be added. */
|
||||
const SUGGESTED: { key: string; hint: string }[] = [
|
||||
{ key: "TRUST_PROXY", hint: "Behind frp: loopback" },
|
||||
{ key: "DB_HOST", hint: "The PostgreSQL server the sites use (default localhost)" },
|
||||
{ key: "DB_PORT", hint: "Default 5432" },
|
||||
{ key: "DB_ADMIN_URL", hint: "postgresql://admin:…@host/postgres: may create databases and roles. Blank: the local PostgreSQL via sudo -u postgres" },
|
||||
];
|
||||
|
||||
function ConfigEditor({ id, config, onSaved }: { id: string; config: Record<string, string>; onSaved: (m: Msg) => void }) {
|
||||
const [rows, setRows] = useState<[string, string][]>(() => {
|
||||
const keys = [...new Set([...SUGGESTED.map(s => s.key), ...Object.keys(config)])];
|
||||
return keys.map(k => [k, config[k] ?? (k === "TRUST_PROXY" ? "loopback" : "")]);
|
||||
});
|
||||
const set = (i: number, j: 0 | 1, v: string) => setRows(rows.map((r, n) => (n === i ? (j === 0 ? [v.toUpperCase(), r[1]] : [r[0], v]) : r)));
|
||||
const save = async () => {
|
||||
try {
|
||||
await api(`/api/admin/servers/${id}/config`, { method: "PUT", body: { values: Object.fromEntries(rows.filter(r => r[0].trim())) } });
|
||||
onSaved({ type: "ok", text: "Configuration saved. Jobs from now on carry it, sealed to this server's key." });
|
||||
} catch (e) { onSaved({ type: "err", text: errorText(e) }); }
|
||||
};
|
||||
return (
|
||||
<div className="card">
|
||||
<h2 className="font-medium">Configuration</h2>
|
||||
<p className="mt-1 text-sm text-slate-500">The server layer of every install's .env here. Stored encrypted; sent only inside jobs, sealed to this server. Values ending in _URL, KEY, SECRET or PASSWORD show as dots: leave them to keep them.</p>
|
||||
<div className="mt-3 space-y-2">
|
||||
{rows.map(([k, v], i) => (
|
||||
<div key={i} className="grid gap-2 md:grid-cols-[14rem_1fr_auto]">
|
||||
<input className="input font-mono" value={k} onChange={e => set(i, 0, e.target.value)} placeholder="NAME" aria-label="Name" />
|
||||
<input className="input font-mono" value={v} onChange={e => set(i, 1, e.target.value)} placeholder={SUGGESTED.find(s => s.key === k)?.hint || "value"} aria-label={`${k} value`} />
|
||||
<button type="button" className="btn-secondary" onClick={() => setRows(rows.filter((_, n) => n !== i))} aria-label={`Remove ${k}`}><Trash2 className="h-4 w-4" /></button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-3 flex gap-2">
|
||||
<button type="button" className="btn-secondary" onClick={() => setRows([...rows, ["", ""]])}><Plus className="h-4 w-4" /> Add a setting</button>
|
||||
<button type="button" className="btn-primary" onClick={save}>Save</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServerPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const router = useRouter();
|
||||
const [d, setD] = useState<Detail | null>(null);
|
||||
const [range, setRange] = useState<"24h" | "7d" | "90d">("24h");
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
const [agentVersion, setAgentVersion] = useState("");
|
||||
|
||||
const load = useCallback(() => api<Detail>(`/api/admin/servers/${id}?range=${range}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) })), [id, range]);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const job = async (type: string, args: Record<string, unknown> = {}) => {
|
||||
setMsg(null);
|
||||
try {
|
||||
const r = await api<{ job: Job }>(`/api/admin/servers/${id}/jobs`, { method: "POST", body: { type, args } });
|
||||
setMsg({ type: "ok", text: `Queued: the agent picks it up within 30 seconds.` });
|
||||
router.push(`/jobs/${r.job.id}`);
|
||||
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
|
||||
};
|
||||
const remove = async () => {
|
||||
if (!d || !window.confirm(`Remove ${d.server.name} from the Hub? Its agent stops getting jobs. (Uninstall the agent on the server too.)`)) return;
|
||||
try { await api(`/api/admin/servers/${id}`, { method: "DELETE" }); router.push("/servers"); } catch (e) { setMsg({ type: "err", text: errorText(e) }); }
|
||||
};
|
||||
|
||||
if (!d) return <div><ServersNav active="/servers" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
|
||||
const s = d.server;
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<PageTitle title={s.name} subtitle={<>{s.mode === "central" ? "Central server" : "Church server"} · {s.hostname} · agent {s.agentVersion} · last heard {ago(s.lastSeenAt)} <StatusPill status={s.online ? "online" : "offline"} /></>} />
|
||||
<ServersNav active="/servers" />
|
||||
<Message msg={msg} />
|
||||
</div>
|
||||
|
||||
{!!d.alerts.filter(a => !a.resolvedAt).length && (
|
||||
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">
|
||||
{d.alerts.filter(a => !a.resolvedAt).map(a => <div key={a.id}>⚠ {a.message} <span className="text-xs">(since {fmtDate(a.createdAt)})</span></div>)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{(["24h", "7d", "90d"] as const).map(r => <button key={r} className={range === r ? "btn-primary" : "btn-secondary"} onClick={() => setRange(r)}>{r === "24h" ? "24 hours" : r === "7d" ? "7 days" : "90 days"}</button>)}
|
||||
</div>
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<PercentChart title="CPU" points={d.stats.map(p => ({ at: p.at, value: p.cpuPercent, peak: p.cpuPeak }))} />
|
||||
<PercentChart title="RAM used" points={d.stats.map(p => ({ at: p.at, value: p.ramUsedPercent, peak: p.ramPeak }))} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<div className="card text-sm">
|
||||
<h2 className="font-medium">Resources now</h2>
|
||||
<p className="mt-2">RAM {pct(s.ram?.usedPercent)} used, {bytes(s.ram?.availableBytes)} free of {bytes(s.ram?.totalBytes)}</p>
|
||||
<p>CPU {pct(s.cpu?.percent)} · load {s.cpu?.load1?.toFixed(2)} on {s.cpu?.cores} cores</p>
|
||||
{s.disk.map(x => <p key={x.mount}>Disk {x.mount}: {pct((x.usedBytes / Math.max(1, x.totalBytes)) * 100)} used, {bytes(x.freeBytes)} free</p>)}
|
||||
</div>
|
||||
<div className="card text-sm">
|
||||
<h2 className="font-medium">Versions</h2>
|
||||
<p className="mt-2">{s.versions?.os}</p>
|
||||
<p>Node {s.versions?.node} · PostgreSQL {s.versions?.postgres || "–"} · frpc {s.versions?.frpc || "–"}</p>
|
||||
{s.mode === "church" && <p>frpc {s.frpcRunning === null ? "unknown" : s.frpcRunning ? "running" : <b className="text-red-700">not running</b>}</p>}
|
||||
{s.central && <p>frps.ini: proxy_bind_addr {s.central.proxyBindAddr || <b className="text-red-700">not set</b>}, allow_ports {s.central.allowPorts || "any"}</p>}
|
||||
</div>
|
||||
<div className="card space-y-2 text-sm">
|
||||
<h2 className="font-medium">Actions</h2>
|
||||
<button className="btn-secondary w-full" onClick={() => job("status")}>Check status now</button>
|
||||
<div className="flex gap-2"><input className="input" placeholder="agent@1.0.1" value={agentVersion} onChange={e => setAgentVersion(e.target.value)} aria-label="Agent version" /><button className="btn-secondary" disabled={!agentVersion} onClick={() => job("update-agent", { version: agentVersion })}>Update agent</button></div>
|
||||
<button className="btn-danger w-full" onClick={remove}><Trash2 className="h-4 w-4" /> Remove server</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{s.mode === "church" && <ConfigEditor key={JSON.stringify(d.config)} id={s.id} config={d.config} onSaved={m => { setMsg(m); load(); }} />}
|
||||
|
||||
{s.mode === "church" && (
|
||||
<div className="card overflow-x-auto">
|
||||
<h2 className="font-medium">Sites on this server</h2>
|
||||
<table className="mt-3 w-full text-sm">
|
||||
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Church</th><th>Domain</th><th>Version</th><th>Ports (web, api)</th><th>Status</th></tr></thead>
|
||||
<tbody>{d.deployments.map(x => (
|
||||
<tr key={x.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/servers/installs/${x.id}`}>{x.customer?.name} ({x.shortName})</Link></td><td>{x.domain}</td><td>{x.version || "–"}</td><td className="tabular-nums">{x.webPort}, {x.apiPort}</td><td><StatusPill status={x.status} /></td></tr>
|
||||
))}</tbody>
|
||||
</table>
|
||||
{!d.deployments.length && <p className="mt-2 text-sm text-slate-500">None yet. <Link className="text-indigo-700 hover:underline" href="/servers/installs">New install</Link></p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{s.mode === "church" && (
|
||||
<div className="card overflow-x-auto">
|
||||
<h2 className="font-medium">Processes (PM2)</h2>
|
||||
<table className="mt-3 w-full text-sm tabular-nums">
|
||||
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Name</th><th>Church</th><th>Status</th><th className="text-right">Memory</th><th className="text-right">CPU</th><th className="text-right">Restarts</th></tr></thead>
|
||||
<tbody>{d.processes.map(p => <tr key={p.name} className="border-t"><td className="py-1.5">{p.name}</td><td>{p.church || "–"}</td><td>{p.status}</td><td className="text-right">{bytes(p.memoryBytes)}</td><td className="text-right">{Math.round(p.cpuPercent)}%</td><td className="text-right">{p.restarts}</td></tr>)}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card overflow-x-auto">
|
||||
<h2 className="font-medium">Recent jobs</h2>
|
||||
<table className="mt-3 w-full text-sm">
|
||||
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>When</th><th>Status</th><th>Result</th></tr></thead>
|
||||
<tbody>{d.jobs.map(j => <tr key={j.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link> <span className="text-xs text-slate-500">{String(j.args?.church || "")}</span></td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td><td className="max-w-md truncate text-xs text-slate-500">{j.message}</td></tr>)}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useParams, useSearchParams } from "next/navigation";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { bytes, fmtDate } from "@/lib/format";
|
||||
import { Loading, Message, PageTitle } from "@/components/ui";
|
||||
import { ServersNav, StatusPill, toInput, fromInput, type Deployment, type Job, type ServerSummary } from "@/components/servers";
|
||||
|
||||
type Msg = { type: "ok" | "err"; text: string } | null;
|
||||
type Detail = {
|
||||
deployment: Deployment & { server: ServerSummary; jobs: Job[]; exports: { id: string; bytes: number; expiresAt: string; downloadedAt: string | null; deletedAt: string | null }[]; install: { version: string | null; url: string } | null };
|
||||
fastPanel: string;
|
||||
};
|
||||
|
||||
const H = 60 * 60 * 1000;
|
||||
|
||||
/** One install on a server: proxy, updates, adopt, uninstall (§7–9). */
|
||||
export default function DeploymentPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const warn = useSearchParams().get("warn");
|
||||
const [d, setD] = useState<Detail | null>(null);
|
||||
const [msg, setMsg] = useState<Msg>(warn ? { type: "err", text: warn } : null);
|
||||
const [problems, setProblems] = useState<string[]>([]);
|
||||
const [upd, setUpd] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, reason: "", totp: "" });
|
||||
const [adopt, setAdopt] = useState({ eventsDir: "", version: "", at: toInput(new Date(Date.now() + 5 * H)) });
|
||||
const [un, setUn] = useState({ at: toInput(new Date(Date.now() + 7 * 24 * H)), totp: "", confirm: "" });
|
||||
|
||||
const load = useCallback(() => api<Detail>(`/api/admin/deployments/${id}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const act = async (path: string, body: unknown, ok: string) => {
|
||||
setMsg(null);
|
||||
try {
|
||||
const r = await api<{ warnings?: string[] }>(path, { method: "POST", body });
|
||||
setMsg({ type: "ok", text: `${ok}${r?.warnings?.length ? ` Note: ${r.warnings.join(" ")}` : ""}` });
|
||||
load();
|
||||
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
|
||||
};
|
||||
const proxyDone = async () => {
|
||||
setMsg(null);
|
||||
try {
|
||||
const r = await api<{ live: boolean; problems: string[] }>(`/api/admin/deployments/${id}/proxy-done`, { method: "POST" });
|
||||
setProblems(r.problems);
|
||||
setMsg(r.live ? { type: "ok", text: "Live. The site admin got the welcome email." } : { type: "err", text: "The site isn't answering as expected yet:" });
|
||||
load();
|
||||
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
|
||||
};
|
||||
|
||||
if (!d) return <div><ServersNav active="/servers/installs" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
|
||||
const x = d.deployment;
|
||||
const minAt = upd.emergency ? 15 * 60 * 1000 : 4 * H;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<PageTitle title={`${x.customer?.name} (${x.shortName})`} subtitle={<>{x.domain} · on <Link className="text-indigo-700 hover:underline" href={`/servers/${x.serverId}`}>{x.server.name}</Link> · ports web {x.webPort}, api {x.apiPort} · version {x.install?.version || x.version || "–"} <StatusPill status={x.status} /></>} />
|
||||
<ServersNav active="/servers/installs" />
|
||||
<Message msg={msg} />
|
||||
{!!problems.length && <ul className="mt-2 list-disc pl-6 text-sm text-red-800">{problems.map(p => <li key={p}>{p}</li>)}</ul>}
|
||||
</div>
|
||||
|
||||
{(x.status === "waiting_for_proxy" || x.status === "installing") && (
|
||||
<div className="card">
|
||||
<h2 className="font-medium">Set up the site in FastPanel</h2>
|
||||
<pre className="mt-3 overflow-x-auto whitespace-pre-wrap rounded-lg bg-slate-50 p-3 text-xs">{d.fastPanel}</pre>
|
||||
<button className="btn-primary mt-3" disabled={x.status !== "waiting_for_proxy"} onClick={proxyDone}>Proxy done</button>
|
||||
{x.status === "installing" && <p className="mt-2 text-xs text-slate-500">Waiting for the install to finish (see its job below).</p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{x.status === "live" && (
|
||||
<form className="card grid gap-3 md:grid-cols-2" onSubmit={e => { e.preventDefault(); act("/api/admin/updates", { deploymentIds: [x.id], version: upd.version || undefined, at: fromInput(upd.at), emergency: upd.emergency, reason: upd.reason || null, totp: upd.totp || null }, "Planned. The site admin was emailed and sees a banner."); }}>
|
||||
<h2 className="font-medium md:col-span-2">Schedule an update</h2>
|
||||
<div><label className="label" htmlFor="u-v">Release</label><input id="u-v" className="input" placeholder="latest" value={upd.version} onChange={e => setUpd({ ...upd, version: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="u-at">When</label><input id="u-at" type="datetime-local" className="input" value={upd.at} min={toInput(new Date(Date.now() + minAt))} onChange={e => setUpd({ ...upd, at: e.target.value })} /><p className="mt-1 text-xs text-slate-500">At least {upd.emergency ? "15 minutes" : "4 hours"} away, so the church gets notice.</p></div>
|
||||
<label className="flex items-center gap-2 text-sm md:col-span-2"><input type="checkbox" checked={upd.emergency} onChange={e => setUpd({ ...upd, emergency: e.target.checked })} /> Emergency (security fix or broken release): 15 minutes' notice, a reason and your two-factor code</label>
|
||||
{upd.emergency && <>
|
||||
<div><label className="label" htmlFor="u-r">Reason (shown to the church)</label><input id="u-r" className="input" required value={upd.reason} onChange={e => setUpd({ ...upd, reason: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="u-t">Two-factor code</label><input id="u-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={upd.totp} onChange={e => setUpd({ ...upd, totp: e.target.value })} /></div>
|
||||
</>}
|
||||
<div className="md:col-span-2"><button className="btn-primary">Schedule</button></div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{x.status === "live" && x.install?.version?.startsWith("2.1.") && (
|
||||
<form className="card grid gap-3 md:grid-cols-3" onSubmit={e => { e.preventDefault(); act(`/api/admin/deployments/${x.id}/adopt`, { eventsDir: adopt.eventsDir, version: adopt.version || undefined, at: fromInput(adopt.at) }, "Adopt planned. The site admin was emailed."); }}>
|
||||
<h2 className="font-medium md:col-span-3">Move onto the monorepo (crosscode adopt)</h2>
|
||||
<div><label className="label" htmlFor="a-d">The old install's folder</label><input id="a-d" className="input font-mono" required placeholder="/var/www/hope-events" value={adopt.eventsDir} onChange={e => setAdopt({ ...adopt, eventsDir: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="a-v">Release</label><input id="a-v" className="input" placeholder="latest" value={adopt.version} onChange={e => setAdopt({ ...adopt, version: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="a-at">When</label><input id="a-at" type="datetime-local" className="input" value={adopt.at} onChange={e => setAdopt({ ...adopt, at: e.target.value })} /></div>
|
||||
<div className="md:col-span-3"><button className="btn-primary">Plan the move</button></div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="card overflow-x-auto">
|
||||
<h2 className="font-medium">Jobs</h2>
|
||||
<table className="mt-3 w-full text-sm">
|
||||
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>When</th><th>Status</th><th>Result</th><th /></tr></thead>
|
||||
<tbody>{x.jobs.map(j => (
|
||||
<tr key={j.id} className="border-t">
|
||||
<td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td>
|
||||
<td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td><td className="max-w-md truncate text-xs text-slate-500">{j.message}</td>
|
||||
<td>{["queued", "scheduled"].includes(j.status) && <button className="btn-secondary px-2 py-1 text-xs" onClick={() => act(`/api/admin/jobs/${j.id}/cancel`, {}, "Cancelled; the church was told.")}>Cancel</button>}</td>
|
||||
</tr>
|
||||
))}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{!!x.exports.length && (
|
||||
<div className="card text-sm">
|
||||
<h2 className="font-medium">Exports</h2>
|
||||
{x.exports.map(e => <p key={e.id} className="mt-2">{e.id}: {bytes(e.bytes)}, {e.deletedAt ? `deleted ${fmtDate(e.deletedAt)}` : `until ${fmtDate(e.expiresAt)}`}{e.downloadedAt ? `, downloaded ${fmtDate(e.downloadedAt)}` : ", not downloaded yet"}</p>)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{x.status !== "removed" && x.status !== "uninstalling" && (
|
||||
<form className="card grid gap-3 border-red-200 md:grid-cols-3" onSubmit={e => { e.preventDefault(); if (window.confirm(`Uninstall ${x.shortName} on ${un.at.replace("T", " ")}? The church gets its data first.`)) act(`/api/admin/deployments/${x.id}/uninstall`, { at: fromInput(un.at), totp: un.totp, confirm: un.confirm }, "Uninstall planned: the site admin was emailed and sees a banner. The export runs first."); }}>
|
||||
<h2 className="font-medium text-red-800 md:col-span-3">Uninstall</h2>
|
||||
<p className="text-sm text-slate-500 md:col-span-3">At the time: the church's data is exported (encrypted; the link goes to the site admin), then the site, its tunnels and database are removed. The final backup stays on the server for 30 days.</p>
|
||||
<div><label className="label" htmlFor="x-at">When</label><input id="x-at" type="datetime-local" className="input" value={un.at} onChange={e => setUn({ ...un, at: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="x-c">Type {x.shortName}</label><input id="x-c" className="input" required value={un.confirm} onChange={e => setUn({ ...un, confirm: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="x-t">Two-factor code</label><input id="x-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={un.totp} onChange={e => setUn({ ...un, totp: e.target.value })} /></div>
|
||||
<div className="md:col-span-3"><button className="btn-danger" disabled={un.confirm !== x.shortName}>Plan the uninstall</button></div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Link2, Plus } from "lucide-react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { ago } from "@/lib/format";
|
||||
import { Loading, Message, PageTitle } from "@/components/ui";
|
||||
import { ServersNav, StatusPill, pct, type Deployment, type ServerSummary } from "@/components/servers";
|
||||
|
||||
type Msg = { type: "ok" | "err"; text: string } | null;
|
||||
type Customer = { id: string; name: string; domain?: string | null };
|
||||
type InstallRow = { id: string; name: string; url: string; customer: { id: string; name: string } | null; version: string | null };
|
||||
|
||||
const emptyNew = { customerId: "", serverId: "", shortName: "", domain: "", timezone: "", adminName: "", adminEmail: "", version: "" };
|
||||
const emptyLink = { installId: "", serverId: "", shortName: "", webPort: "", apiPort: "" };
|
||||
|
||||
/** Installs on servers: New install (§7) and linking existing installs (§14). */
|
||||
export default function InstallsPage() {
|
||||
const router = useRouter();
|
||||
const [list, setList] = useState<Deployment[] | null>(null);
|
||||
const [srv, setSrv] = useState<ServerSummary[]>([]);
|
||||
const [customers, setCustomers] = useState<Customer[]>([]);
|
||||
const [installs, setInstalls] = useState<InstallRow[]>([]);
|
||||
const [mode, setMode] = useState<"none" | "new" | "link">("none");
|
||||
const [form, setForm] = useState(emptyNew);
|
||||
const [link, setLink] = useState(emptyLink);
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
api<{ deployments: Deployment[] }>("/api/admin/deployments").then(r => setList(r.deployments)).catch(e => setMsg({ type: "err", text: errorText(e) }));
|
||||
api<{ servers: ServerSummary[] }>("/api/admin/servers").then(r => setSrv(r.servers.filter(s => s.mode === "church"))).catch(() => {});
|
||||
}, []);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
useEffect(() => {
|
||||
if (mode === "new" && !customers.length) api<Customer[]>("/api/admin/customers").then(setCustomers).catch(() => {});
|
||||
if (mode === "link" && !installs.length) api<InstallRow[]>("/api/admin/installs").then(setInstalls).catch(() => {});
|
||||
}, [mode, customers.length, installs.length]);
|
||||
|
||||
const submitNew = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setMsg(null);
|
||||
try {
|
||||
const r = await api<{ deployment: Deployment; warnings: string[] }>("/api/admin/deployments", { method: "POST", body: { ...form, product: "events", version: form.version || undefined } });
|
||||
router.push(`/servers/installs/${r.deployment.id}${r.warnings.length ? `?warn=${encodeURIComponent(r.warnings.join(" "))}` : ""}`);
|
||||
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
|
||||
setBusy(false);
|
||||
};
|
||||
const submitLink = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setMsg(null);
|
||||
try {
|
||||
const r = await api<{ deployment: Deployment }>("/api/admin/deployments/link", { method: "POST", body: link });
|
||||
router.push(`/servers/installs/${r.deployment.id}`);
|
||||
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
|
||||
setBusy(false);
|
||||
};
|
||||
const f = (k: keyof typeof emptyNew) => ({ value: form[k], onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => setForm({ ...form, [k]: e.target.value }) });
|
||||
const l = (k: keyof typeof emptyLink) => ({ value: link[k], onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => setLink({ ...link, [k]: e.target.value }) });
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageTitle title="Installs on servers" subtitle="Sites the Hub installs, updates and uninstalls through each server's agent."
|
||||
actions={<div className="flex gap-2"><button className="btn-secondary" onClick={() => setMode("link")}><Link2 className="h-4 w-4" /> Link existing</button><button className="btn-primary" onClick={() => setMode("new")}><Plus className="h-4 w-4" /> New install</button></div>} />
|
||||
<ServersNav active="/servers/installs" />
|
||||
<Message msg={msg} />
|
||||
|
||||
{mode === "new" && (
|
||||
<form onSubmit={submitNew} className="card mb-6 grid gap-3 md:grid-cols-2">
|
||||
<h2 className="font-medium md:col-span-2">New Cross Events install</h2>
|
||||
<div><label className="label" htmlFor="n-cust">Customer</label><select id="n-cust" className="input" required {...f("customerId")}><option value="">Choose…</option>{customers.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}</select></div>
|
||||
<div><label className="label" htmlFor="n-short">Short name</label><input id="n-short" className="input" required pattern="[a-z][a-z0-9-]{1,30}" placeholder="hope" {...f("shortName")} /><p className="mt-1 text-xs text-slate-500">Folders, database and tunnels: a-z, 0-9 and -.</p></div>
|
||||
<div><label className="label" htmlFor="n-domain">Domain</label><input id="n-domain" className="input" required placeholder="events.hope.co.za" {...f("domain")} /></div>
|
||||
<div><label className="label" htmlFor="n-tz">Time zone</label><input id="n-tz" className="input" placeholder="Africa/Johannesburg" {...f("timezone")} /></div>
|
||||
<div><label className="label" htmlFor="n-an">Site admin name</label><input id="n-an" className="input" {...f("adminName")} /></div>
|
||||
<div><label className="label" htmlFor="n-ae">Site admin email</label><input id="n-ae" type="email" className="input" {...f("adminEmail")} /><p className="mt-1 text-xs text-slate-500">Gets the welcome email and update notices.</p></div>
|
||||
<div className="md:col-span-2">
|
||||
<span className="label">Server</span>
|
||||
<div className="grid gap-2 md:grid-cols-2">
|
||||
{srv.map(s => {
|
||||
const low = (s.ram?.availableBytes ?? 0) < 1.5 * 1024 ** 3;
|
||||
return (
|
||||
<label key={s.id} className={`flex cursor-pointer gap-2 rounded-lg border p-3 text-sm ${form.serverId === s.id ? "border-indigo-500 bg-indigo-50" : "border-slate-200"}`}>
|
||||
<input type="radio" name="server" value={s.id} checked={form.serverId === s.id} onChange={() => setForm({ ...form, serverId: s.id })} disabled={!s.online} />
|
||||
<span>
|
||||
<span className="font-medium">{s.name}</span> <StatusPill status={s.online ? "online" : "offline"} />
|
||||
<span className="block text-xs text-slate-500">RAM free {s.ram ? `${(s.ram.availableBytes / 1024 ** 3).toFixed(1)} GB` : "?"} · CPU day avg {pct(s.lastDay?.cpuAvg)} · disk {pct(s.disk.reduce((m, d) => Math.max(m, d.totalBytes ? (d.usedBytes / d.totalBytes) * 100 : 0), 0))} · {s.deployments ?? 0} site(s)</span>
|
||||
{low && <span className="block text-xs font-medium text-amber-800">Not recommended: under 1.5 GB RAM free</span>}
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="n-ver">Release</label><input id="n-ver" className="input" placeholder="latest" {...f("version")} /></div>
|
||||
<div className="flex items-end gap-2 md:col-span-2">
|
||||
<button className="btn-primary" disabled={busy || !form.serverId}>{busy ? "Starting…" : "Install"}</button>
|
||||
<button type="button" className="btn-secondary" onClick={() => setMode("none")}>Cancel</button>
|
||||
<p className="text-xs text-slate-500">The Hub makes the licence, picks two ports, and the agent installs within a minute. You get the report and the FastPanel steps by email.</p>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{mode === "link" && (
|
||||
<form onSubmit={submitLink} className="card mb-6 grid gap-3 md:grid-cols-2">
|
||||
<h2 className="font-medium md:col-span-2">Link an install that's already on a server</h2>
|
||||
<p className="text-sm text-slate-500 md:col-span-2">For sites installed by hand or moved with <code>crosscode adopt</code>. Nothing on the server changes; the Hub records the server, folder name and ports (see the server's church.env and frpc.ini).</p>
|
||||
<div><label className="label" htmlFor="l-inst">Install</label><select id="l-inst" className="input" required {...l("installId")}><option value="">Choose…</option>{installs.map(i => <option key={i.id} value={i.id}>{i.customer?.name || i.name} ({i.url})</option>)}</select></div>
|
||||
<div><label className="label" htmlFor="l-srv">Server</label><select id="l-srv" className="input" required {...l("serverId")}><option value="">Choose…</option>{srv.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}</select></div>
|
||||
<div><label className="label" htmlFor="l-short">Short name (its folder in /var/www/sites)</label><input id="l-short" className="input" required {...l("shortName")} /></div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div><label className="label" htmlFor="l-web">Web port</label><input id="l-web" className="input" required inputMode="numeric" {...l("webPort")} /></div>
|
||||
<div><label className="label" htmlFor="l-api">API port</label><input id="l-api" className="input" required inputMode="numeric" {...l("apiPort")} /></div>
|
||||
</div>
|
||||
<div className="flex gap-2 md:col-span-2"><button className="btn-primary" disabled={busy}>Link</button><button type="button" className="btn-secondary" onClick={() => setMode("none")}>Cancel</button></div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{!list ? <Loading /> : (
|
||||
<div className="card overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Church</th><th>Domain</th><th>Server</th><th>Version</th><th>Last heartbeat</th><th>Status</th></tr></thead>
|
||||
<tbody>{list.map(d => (
|
||||
<tr key={d.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/servers/installs/${d.id}`}>{d.customer?.name} ({d.shortName})</Link></td><td>{d.domain}</td><td>{d.server?.name}</td><td>{d.install?.version || d.version || "–"}</td><td>{ago(d.install?.lastHeartbeatAt)}</td><td><StatusPill status={d.status} /></td></tr>
|
||||
))}</tbody>
|
||||
</table>
|
||||
{!list.length && <p className="mt-2 text-sm text-slate-500">No installs on servers yet.</p>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Copy, Plus } from "lucide-react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { ago, bytes } from "@/lib/format";
|
||||
import { Loading, Message, PageTitle } from "@/components/ui";
|
||||
import { ServersNav, StatusPill, pct, type ServerSummary } from "@/components/servers";
|
||||
|
||||
type Msg = { type: "ok" | "err"; text: string } | null;
|
||||
|
||||
/** Hub → Servers: every server with its agent, resources and sites; Add server (§3, §10). */
|
||||
export default function ServersPage() {
|
||||
const [list, setList] = useState<ServerSummary[] | null>(null);
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [name, setName] = useState("");
|
||||
const [mode, setMode] = useState<"church" | "central">("church");
|
||||
const [joined, setJoined] = useState<{ command: string; expiresAt: string } | null>(null);
|
||||
|
||||
const load = useCallback(() => api<{ servers: ServerSummary[] }>("/api/admin/servers").then(r => setList(r.servers)).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
|
||||
useEffect(() => { load(); const t = setInterval(load, 30000); return () => clearInterval(t); }, [load]);
|
||||
|
||||
const add = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setMsg(null);
|
||||
try {
|
||||
const r = await api<{ command: string; expiresAt: string }>("/api/admin/servers/join-token", { method: "POST", body: { name, mode } });
|
||||
setJoined(r);
|
||||
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageTitle title="Servers" subtitle="Each server runs the Cross Code agent, which polls the Hub for jobs and reports its health every minute." actions={<button className="btn-primary" onClick={() => { setAdding(true); setJoined(null); setName(""); }}><Plus className="h-4 w-4" /> Add server</button>} />
|
||||
<ServersNav active="/servers" />
|
||||
<Message msg={msg} />
|
||||
|
||||
{adding && (
|
||||
<div className="card mb-6">
|
||||
{!joined ? (
|
||||
<form onSubmit={add} className="flex flex-wrap items-end gap-3">
|
||||
<div className="min-w-[14rem] flex-1"><label className="label" htmlFor="srv-name">Name</label><input id="srv-name" className="input" value={name} onChange={e => setName(e.target.value)} placeholder="church-server-2" required /></div>
|
||||
<div><label className="label" htmlFor="srv-mode">Kind</label>
|
||||
<select id="srv-mode" className="input" value={mode} onChange={e => setMode(e.target.value as "church" | "central")}>
|
||||
<option value="church">Church server (runs sites)</option>
|
||||
<option value="central">Central server (FastPanel, read-only checks)</option>
|
||||
</select>
|
||||
</div>
|
||||
<button className="btn-primary">Make the join command</button>
|
||||
<button type="button" className="btn-secondary" onClick={() => setAdding(false)}>Cancel</button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm">Run this on the new server as root. The token works once, until {new Date(joined.expiresAt).toLocaleTimeString()}:</p>
|
||||
<pre className="overflow-x-auto rounded-lg bg-slate-900 p-3 text-xs text-slate-100">{joined.command}</pre>
|
||||
<div className="flex gap-2">
|
||||
<button className="btn-secondary" onClick={() => navigator.clipboard?.writeText(joined.command)}><Copy className="h-4 w-4" /> Copy</button>
|
||||
<button className="btn-secondary" onClick={() => { setAdding(false); load(); }}>Done</button>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">The server shows here within a minute of joining. Then set its configuration (database, TRUST_PROXY) on its page.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!list ? <Loading /> : list.length === 0 ? <p className="text-sm text-slate-500">No servers yet. Add one to install churches from the Hub.</p> : (
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{list.map(s => {
|
||||
const disk = s.disk.reduce((m, d) => Math.max(m, d.totalBytes ? (d.usedBytes / d.totalBytes) * 100 : 0), 0);
|
||||
return (
|
||||
<Link key={s.id} href={`/servers/${s.id}`} className="card block hover:border-indigo-300">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="font-medium">{s.name}</div>
|
||||
<div className="text-xs text-slate-500">{s.mode === "central" ? "Central server" : "Church server"} · {s.hostname || "?"} · agent {s.agentVersion || "?"}</div>
|
||||
</div>
|
||||
<StatusPill status={s.online ? "online" : "offline"} />
|
||||
</div>
|
||||
<dl className="mt-4 grid grid-cols-3 gap-2 text-sm">
|
||||
<div><dt className="text-xs text-slate-500">RAM used</dt><dd className="tabular-nums">{pct(s.ram?.usedPercent)} <span className="text-xs text-slate-500">of {bytes(s.ram?.totalBytes)}</span></dd></div>
|
||||
<div><dt className="text-xs text-slate-500">CPU now · day avg</dt><dd className="tabular-nums">{pct(s.cpu?.percent)} · {pct(s.lastDay?.cpuAvg)}</dd></div>
|
||||
<div><dt className="text-xs text-slate-500">Fullest disk</dt><dd className="tabular-nums">{pct(disk)}</dd></div>
|
||||
</dl>
|
||||
<div className="mt-3 flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-500">
|
||||
{s.mode === "church" && <span>{s.deployments ?? 0} site(s)</span>}
|
||||
<span>Last heard {ago(s.lastSeenAt)}</span>
|
||||
{s.mode === "church" && s.frpcRunning === false && <span className="font-medium text-red-700">frpc not running</span>}
|
||||
{s.central && !s.central.proxyBindAddr && <span className="font-medium text-red-700">proxy_bind_addr not set</span>}
|
||||
</div>
|
||||
{!!s.alerts?.length && (
|
||||
<ul className="mt-3 space-y-1 text-xs">
|
||||
{s.alerts.map(a => <li key={a.type} className={a.level === "critical" ? "text-red-700" : "text-amber-800"}>⚠ {a.message}</li>)}
|
||||
</ul>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import { Plus, Trash2 } from "lucide-react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { fmtDate } from "@/lib/format";
|
||||
import { Loading, Message, PageTitle } from "@/components/ui";
|
||||
import { ServersNav } from "@/components/servers";
|
||||
|
||||
type Msg = { type: "ok" | "err"; text: string } | null;
|
||||
type Port = { port: number; role: string; note: string | null; releasedAt: string | null; deploymentId: string | null; server: { id: string; name: string } | null };
|
||||
|
||||
/** The port list (§6) and the install defaults (§5): the same for every install. */
|
||||
export default function ServerSettingsPage() {
|
||||
const [ports, setPorts] = useState<Port[] | null>(null);
|
||||
const [range, setRange] = useState({ from: "20000", to: "29999" });
|
||||
const [defaults, setDefaults] = useState<[string, string][]>([]);
|
||||
const [ip, setIp] = useState("");
|
||||
const [newPort, setNewPort] = useState({ port: "", note: "" });
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
api<{ ports: Port[]; range: { from: number; to: number } }>("/api/admin/ports").then(r => { setPorts(r.ports); setRange({ from: String(r.range.from), to: String(r.range.to) }); }).catch(e => setMsg({ type: "err", text: errorText(e) }));
|
||||
api<{ defaults: Record<string, string>; centralServerIp: string }>("/api/admin/install-defaults").then(r => { setDefaults(Object.entries(r.defaults)); setIp(r.centralServerIp); }).catch(() => {});
|
||||
}, []);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const saveDefaults = async () => {
|
||||
try {
|
||||
await api("/api/admin/install-defaults", { method: "PUT", body: { defaults: Object.fromEntries(defaults.filter(d => d[0].trim())), portRange: { from: range.from, to: range.to }, centralServerIp: ip } });
|
||||
setMsg({ type: "ok", text: "Saved." });
|
||||
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
|
||||
};
|
||||
const take = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try { await api("/api/admin/ports", { method: "POST", body: { port: newPort.port, note: newPort.note } }); setNewPort({ port: "", note: "" }); load(); } catch (err) { setMsg({ type: "err", text: errorText(err) }); }
|
||||
};
|
||||
const free = async (port: number) => {
|
||||
try { await api(`/api/admin/ports/${port}`, { method: "DELETE" }); load(); } catch (err) { setMsg({ type: "err", text: errorText(err) }); }
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<PageTitle title="Ports & defaults" />
|
||||
<ServersNav active="/servers/settings" />
|
||||
<Message msg={msg} />
|
||||
</div>
|
||||
|
||||
<div className="card space-y-3">
|
||||
<h2 className="font-medium">Install defaults</h2>
|
||||
<p className="text-sm text-slate-500">The defaults layer of every install's .env (HUB_URL, APP_TIMEZONE, job switches, SENTRY_DSN…). A server's own configuration is on its page.</p>
|
||||
{defaults.map(([k, v], i) => (
|
||||
<div key={i} className="grid gap-2 md:grid-cols-[14rem_1fr_auto]">
|
||||
<input className="input font-mono" value={k} aria-label="Name" onChange={e => setDefaults(defaults.map((d, n) => (n === i ? [e.target.value.toUpperCase(), d[1]] : d)))} />
|
||||
<input className="input font-mono" value={v} aria-label={`${k} value`} onChange={e => setDefaults(defaults.map((d, n) => (n === i ? [d[0], e.target.value] : d)))} />
|
||||
<button type="button" className="btn-secondary" aria-label={`Remove ${k}`} onClick={() => setDefaults(defaults.filter((_, n) => n !== i))}><Trash2 className="h-4 w-4" /></button>
|
||||
</div>
|
||||
))}
|
||||
<button type="button" className="btn-secondary" onClick={() => setDefaults([...defaults, ["", ""]])}><Plus className="h-4 w-4" /> Add a default</button>
|
||||
<div className="grid gap-3 border-t pt-3 md:grid-cols-3">
|
||||
<div><label className="label" htmlFor="pr-from">Port range from</label><input id="pr-from" className="input" inputMode="numeric" value={range.from} onChange={e => setRange({ ...range, from: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="pr-to">to</label><input id="pr-to" className="input" inputMode="numeric" value={range.to} onChange={e => setRange({ ...range, to: e.target.value })} /><p className="mt-1 text-xs text-slate-500">Match allow_ports in frps.ini.</p></div>
|
||||
<div><label className="label" htmlFor="c-ip">Central server IP</label><input id="c-ip" className="input" placeholder="203.0.113.10" value={ip} onChange={e => setIp(e.target.value)} /><p className="mt-1 text-xs text-slate-500">To check a new install's DNS.</p></div>
|
||||
</div>
|
||||
<button className="btn-primary" onClick={saveDefaults}>Save</button>
|
||||
</div>
|
||||
|
||||
<div className="card overflow-x-auto">
|
||||
<h2 className="font-medium">Port list</h2>
|
||||
<p className="mt-1 text-sm text-slate-500">Every port frps opens on the central server must be unique across servers. Mark ports used by anything else (today's tunnels written by hand) as taken.</p>
|
||||
<form onSubmit={take} className="mt-3 flex flex-wrap gap-2">
|
||||
<input className="input w-32" placeholder="Port" inputMode="numeric" required value={newPort.port} onChange={e => setNewPort({ ...newPort, port: e.target.value })} aria-label="Port" />
|
||||
<input className="input w-72" placeholder="What uses it" value={newPort.note} onChange={e => setNewPort({ ...newPort, note: e.target.value })} aria-label="Note" />
|
||||
<button className="btn-secondary">Mark as taken</button>
|
||||
</form>
|
||||
{!ports ? <Loading /> : (
|
||||
<table className="mt-3 w-full text-sm tabular-nums">
|
||||
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Port</th><th>Use</th><th>Server</th><th>Note</th><th /></tr></thead>
|
||||
<tbody>{ports.map(p => (
|
||||
<tr key={p.port} className="border-t"><td className="py-1.5">{p.port}</td><td>{p.releasedAt ? `free from ${fmtDate(new Date(new Date(p.releasedAt).getTime() + 30 * 24 * 3600 * 1000), false)}` : p.role}</td><td>{p.server?.name || "–"}</td><td className="text-xs text-slate-500">{p.note}</td>
|
||||
<td>{(p.role === "taken" || p.releasedAt) && <button className="btn-secondary px-2 py-1 text-xs" onClick={() => free(p.port)}>Remove</button>}</td></tr>
|
||||
))}</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { fmtDate } from "@/lib/format";
|
||||
import { Loading, Message, PageTitle } from "@/components/ui";
|
||||
import { ServersNav, StatusPill, toInput, fromInput, type Deployment, type Job } from "@/components/servers";
|
||||
|
||||
type Msg = { type: "ok" | "err"; text: string } | null;
|
||||
const H = 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Updates (§8): one release to several installs at one time with one notice. They run one at a
|
||||
* time, and the batch stops at the first failure (the rest are told it's postponed).
|
||||
*/
|
||||
export default function UpdatesPage() {
|
||||
const [deployments, setDeployments] = useState<Deployment[] | null>(null);
|
||||
const [upcoming, setUpcoming] = useState<Job[]>([]);
|
||||
const [chosen, setChosen] = useState<string[]>([]);
|
||||
const [form, setForm] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, reason: "", totp: "" });
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
api<{ deployments: Deployment[] }>("/api/admin/deployments?status=live").then(r => setDeployments(r.deployments)).catch(e => setMsg({ type: "err", text: errorText(e) }));
|
||||
api<{ jobs: Job[] }>("/api/admin/jobs?upcoming=true").then(r => setUpcoming(r.jobs)).catch(() => {});
|
||||
}, []);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
const byVersion = useMemo(() => [...new Set((deployments || []).map(d => d.install?.version || d.version || "?"))].sort(), [deployments]);
|
||||
|
||||
const submit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setMsg(null);
|
||||
try {
|
||||
const r = await api<{ jobs: Job[]; warnings: string[] }>("/api/admin/updates", { method: "POST", body: { deploymentIds: chosen, version: form.version || undefined, at: fromInput(form.at), emergency: form.emergency, reason: form.reason || null, totp: form.totp || null } });
|
||||
setMsg({ type: "ok", text: `Planned for ${r.jobs.length} install(s); each church was emailed and sees a banner.${r.warnings.length ? ` Note: ${r.warnings.join(" ")}` : ""}` });
|
||||
setChosen([]);
|
||||
load();
|
||||
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<PageTitle title="Updates" subtitle="Plan a release for one or more installs. Churches get an email and a banner now, and a reminder an hour before." />
|
||||
<ServersNav active="/servers/updates" />
|
||||
<Message msg={msg} />
|
||||
</div>
|
||||
|
||||
{!deployments ? <Loading /> : (
|
||||
<form className="card space-y-4" onSubmit={submit}>
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="text-slate-500">Select:</span>
|
||||
<button type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setChosen(deployments.map(d => d.id))}>All live ({deployments.length})</button>
|
||||
{byVersion.map(v => <button key={v} type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setChosen(deployments.filter(d => (d.install?.version || d.version || "?") === v).map(d => d.id))}>On {v}</button>)}
|
||||
<button type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setChosen([])}>None</button>
|
||||
</div>
|
||||
<div className="max-h-72 space-y-1 overflow-y-auto rounded-lg border border-slate-200 p-3">
|
||||
{deployments.map(d => (
|
||||
<label key={d.id} className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={chosen.includes(d.id)} onChange={() => setChosen(chosen.includes(d.id) ? chosen.filter(x => x !== d.id) : [...chosen, d.id])} />
|
||||
<span className="font-medium">{d.customer?.name}</span><span className="text-slate-500">{d.domain} · {d.install?.version || d.version || "?"} · {d.server?.name}</span>
|
||||
</label>
|
||||
))}
|
||||
{!deployments.length && <p className="text-sm text-slate-500">No live installs on servers.</p>}
|
||||
</div>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<div><label className="label" htmlFor="b-v">Release</label><input id="b-v" className="input" placeholder="latest" value={form.version} onChange={e => setForm({ ...form, version: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="b-at">When</label><input id="b-at" type="datetime-local" className="input" value={form.at} onChange={e => setForm({ ...form, at: e.target.value })} /><p className="mt-1 text-xs text-slate-500">At least {form.emergency ? "15 minutes" : "4 hours"} away. They run one at a time from then.</p></div>
|
||||
<label className="flex items-center gap-2 text-sm md:col-span-2"><input type="checkbox" checked={form.emergency} onChange={e => setForm({ ...form, emergency: e.target.checked })} /> Emergency: 15 minutes' notice, with a reason and your two-factor code</label>
|
||||
{form.emergency && <>
|
||||
<div><label className="label" htmlFor="b-r">Reason (shown to the churches)</label><input id="b-r" className="input" required value={form.reason} onChange={e => setForm({ ...form, reason: e.target.value })} /></div>
|
||||
<div><label className="label" htmlFor="b-t">Two-factor code</label><input id="b-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={form.totp} onChange={e => setForm({ ...form, totp: e.target.value })} /></div>
|
||||
</>}
|
||||
</div>
|
||||
<button className="btn-primary" disabled={!chosen.length}>Plan the update for {chosen.length} install(s)</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="card overflow-x-auto">
|
||||
<h2 className="font-medium">Planned and running</h2>
|
||||
<table className="mt-3 w-full text-sm">
|
||||
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>Install</th><th>When</th><th>Status</th></tr></thead>
|
||||
<tbody>{upcoming.map(j => <tr key={j.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.batchId && <span className="ml-1 text-xs text-slate-500">batch</span>}{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td><td>{j.deployment?.shortName || "–"}</td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td></tr>)}</tbody>
|
||||
</table>
|
||||
{!upcoming.length && <p className="mt-2 text-sm text-slate-500">Nothing planned.</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { Download, Lock } from "lucide-react";
|
||||
import { API_URL } from "@/lib/api";
|
||||
import { bytes, fmtDate } from "@/lib/format";
|
||||
import { Logo } from "@/components/ui";
|
||||
|
||||
/**
|
||||
* A church's export (crosscode-platform AGENT-1.0-PLAN §9). The file on the Hub is encrypted; the
|
||||
* key is the part of the link after #, which browsers never send to a server. This page fetches
|
||||
* the encrypted bytes and decrypts them here (AES-256-GCM: 12-byte IV ‖ ciphertext ‖ tag).
|
||||
*/
|
||||
const fromB64u = (s: string) => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4)), c => c.charCodeAt(0));
|
||||
|
||||
export default function DownloadPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [meta, setMeta] = useState<{ bytes: number; expiresAt: string } | null>(null);
|
||||
const [state, setState] = useState<"loading" | "ready" | "working" | "done" | "error">("loading");
|
||||
const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (!window.location.hash.slice(1)) { setState("error"); setError("This link is missing its key (the part after #). Use the whole link from the email."); return; }
|
||||
fetch(`${API_URL}/api/exports/${encodeURIComponent(id)}`).then(async r => {
|
||||
if (!r.ok) throw new Error((await r.json().catch(() => null))?.message || "This download has expired or doesn't exist.");
|
||||
setMeta(await r.json());
|
||||
setState("ready");
|
||||
}).catch(e => { setState("error"); setError(e.message); });
|
||||
}, [id]);
|
||||
|
||||
const download = async () => {
|
||||
setState("working");
|
||||
try {
|
||||
const key = fromB64u(window.location.hash.slice(1));
|
||||
if (key.length !== 32) throw new Error("This link's key isn't complete. Copy the whole link from the email.");
|
||||
const res = await fetch(`${API_URL}/api/exports/${encodeURIComponent(id)}/file`);
|
||||
if (!res.ok) throw new Error("The file couldn't be downloaded. It may have expired.");
|
||||
const data = new Uint8Array(await res.arrayBuffer());
|
||||
const cryptoKey = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);
|
||||
let zip: ArrayBuffer;
|
||||
try {
|
||||
zip = await crypto.subtle.decrypt({ name: "AES-GCM", iv: data.slice(0, 12) }, cryptoKey, data.slice(12));
|
||||
} catch {
|
||||
throw new Error("The file couldn't be opened with this link's key. Check you used the whole link.");
|
||||
}
|
||||
const url = URL.createObjectURL(new Blob([zip], { type: "application/zip" }));
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "church-data.zip";
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60000);
|
||||
setState("done");
|
||||
} catch (e) {
|
||||
setState("error");
|
||||
setError(e instanceof Error ? e.message : "Something went wrong.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex min-h-screen max-w-lg flex-col justify-center p-6">
|
||||
<Logo />
|
||||
<div className="card mt-6 space-y-4">
|
||||
<h1 className="text-xl font-semibold">Your church's data</h1>
|
||||
<p className="text-sm text-slate-600">One ZIP file with your events, people, registrations, payments, check-ins and rosters (export.json, explained in README.txt) and the uploaded files.</p>
|
||||
<p className="flex items-start gap-2 text-xs text-slate-500"><Lock className="mt-0.5 h-3.5 w-3.5 shrink-0" /> The file is encrypted. It's opened here in your browser with the key in your link; we can't read it.</p>
|
||||
{state === "loading" && <p className="text-sm text-slate-400">Checking the link…</p>}
|
||||
{meta && state !== "error" && <p className="text-sm">{bytes(meta.bytes)} · available until {fmtDate(meta.expiresAt)}</p>}
|
||||
{(state === "ready" || state === "working" || state === "done") && (
|
||||
<button className="btn-primary" onClick={download} disabled={state === "working"}><Download className="h-4 w-4" /> {state === "working" ? "Downloading and opening…" : state === "done" ? "Download again" : "Download"}</button>
|
||||
)}
|
||||
{state === "done" && <p className="text-sm text-green-700">Saved as church-data.zip.</p>}
|
||||
{state === "error" && <p className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">{error}</p>}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
"use client";
|
||||
|
||||
import React, { useMemo, useRef, useState } from "react";
|
||||
import { fmtDate } from "@/lib/format";
|
||||
|
||||
/** Shared pieces for the servers pages (2.1.0). */
|
||||
|
||||
export type ServerSummary = {
|
||||
id: string; name: string; mode: "church" | "central"; hostname: string | null; agentVersion: string | null;
|
||||
lastSeenAt: string | null; joinedAt: string; removedAt: string | null; notes: string | null; online: boolean;
|
||||
ram: { totalBytes: number; availableBytes: number; usedPercent: number } | null;
|
||||
cpu: { percent: number; load1: number; cores: number } | null;
|
||||
disk: { mount: string; totalBytes: number; usedBytes: number; freeBytes: number }[];
|
||||
versions: { os: string; node: string; postgres: string | null; frpc: string | null; agent: string } | null;
|
||||
frpcRunning: boolean | null;
|
||||
central: { proxyBindAddr: string | null; allowPorts: string | null; frpsRunning: boolean | null } | null;
|
||||
deployments?: number;
|
||||
alerts?: { type: string; level: string; message: string; createdAt: string }[];
|
||||
lastDay?: { cpuAvg: number | null; ramAvg: number | null; cpuPeak: number | null; ramPeak: number | null } | null;
|
||||
};
|
||||
|
||||
export type Deployment = {
|
||||
id: string; serverId: string; customerId: string; installId: string | null; product: string; shortName: string; domain: string;
|
||||
webPort: number; apiPort: number; status: string; version: string | null; adminName: string | null; adminEmail: string | null;
|
||||
liveAt: string | null; createdAt: string;
|
||||
server?: { id: string; name: string }; customer?: { id: string; name: string };
|
||||
install?: { id: string; version: string | null; lastHeartbeatAt: string | null; url: string } | null;
|
||||
};
|
||||
|
||||
export type Job = {
|
||||
id: string; serverId: string; type: string; args: Record<string, unknown>; status: string; notBefore: string; expiresAt: string;
|
||||
scheduled: boolean; emergency: boolean; reason: string | null; batchId: string | null; deliveredAt: string | null; finishedAt: string | null;
|
||||
message: string | null; createdAt: string; deploymentId: string | null;
|
||||
server?: { id: string; name: string }; deployment?: { id: string; shortName: string; domain: string } | null;
|
||||
report?: { status: string; steps: { name: string; startedAt: string; finishedAt: string | null; outcome: string; detail?: string }[]; result: Record<string, unknown>; log: string[]; message?: string } | null;
|
||||
};
|
||||
|
||||
const TONE: Record<string, string> = {
|
||||
green: "bg-green-50 text-green-700 ring-green-600/20",
|
||||
amber: "bg-amber-50 text-amber-800 ring-amber-600/20",
|
||||
red: "bg-red-50 text-red-700 ring-red-600/20",
|
||||
blue: "bg-indigo-50 text-indigo-700 ring-indigo-600/20",
|
||||
grey: "bg-slate-100 text-slate-600 ring-slate-500/20",
|
||||
};
|
||||
|
||||
const STATUS: Record<string, [string, string]> = {
|
||||
// deployments
|
||||
installing: ["Installing", "blue"], waiting_for_proxy: ["Waiting for proxy", "amber"], live: ["Live", "green"], failed: ["Failed", "red"],
|
||||
uninstalling: ["Uninstalling", "amber"], removed: ["Removed", "grey"],
|
||||
// jobs
|
||||
scheduled: ["Waiting its turn", "grey"], queued: ["Due", "blue"], delivered: ["Running", "blue"], succeeded: ["Succeeded", "green"],
|
||||
rolled_back: ["Rolled back", "amber"], refused: ["Refused", "red"], expired: ["Expired", "red"], missed: ["Missed", "red"], cancelled: ["Cancelled", "grey"],
|
||||
// servers
|
||||
online: ["Online", "green"], offline: ["Offline", "red"],
|
||||
};
|
||||
|
||||
/** A status as a label (never colour alone). */
|
||||
export function StatusPill({ status }: { status: string }) {
|
||||
const [label, tone] = STATUS[status] || [status, "grey"];
|
||||
return <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ring-1 ring-inset ${TONE[tone]}`}>{label}</span>;
|
||||
}
|
||||
|
||||
export const pct = (n: number | null | undefined) => (n == null ? "–" : `${Math.round(n)}%`);
|
||||
|
||||
// <input type="datetime-local"> works in the browser's time; the API takes ISO.
|
||||
export const toInput = (d: Date) => new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
|
||||
export const fromInput = (v: string) => (v ? new Date(v).toISOString() : "");
|
||||
|
||||
/**
|
||||
* A single-series line chart of a percentage (0–100) over time, with spikes over `spike`%
|
||||
* marked, a crosshair tooltip and a table view. One axis; the title names the series.
|
||||
*/
|
||||
export function PercentChart({ title, points, spike = 85 }: { title: string; points: { at: string; value: number; peak: number }[]; spike?: number }) {
|
||||
const W = 640, H = 160, L = 34, R = 8, T = 10, B = 22;
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const times = useMemo(() => points.map(p => new Date(p.at).getTime()), [points]);
|
||||
if (points.length < 2) return <div className="card"><h3 className="text-sm font-medium">{title}</h3><p className="mt-2 text-sm text-slate-500">Not enough data yet.</p></div>;
|
||||
const t0 = times[0], t1 = times[times.length - 1] || t0 + 1;
|
||||
const x = (t: number) => L + ((t - t0) / Math.max(1, t1 - t0)) * (W - L - R);
|
||||
const y = (v: number) => T + (1 - Math.min(100, Math.max(0, v)) / 100) * (H - T - B);
|
||||
const path = points.map((p, i) => `${i ? "L" : "M"}${x(times[i]).toFixed(1)},${y(p.value).toFixed(1)}`).join("");
|
||||
const spikes = points.map((p, i) => ({ p, i })).filter(({ p }) => p.peak > spike);
|
||||
const onMove = (e: React.MouseEvent<SVGSVGElement>) => {
|
||||
const r = svgRef.current?.getBoundingClientRect();
|
||||
if (!r) return;
|
||||
const t = t0 + ((((e.clientX - r.left) / r.width) * W - L) / (W - L - R)) * (t1 - t0);
|
||||
let best = 0;
|
||||
for (let i = 1; i < times.length; i++) if (Math.abs(times[i] - t) < Math.abs(times[best] - t)) best = i;
|
||||
setHover(best);
|
||||
};
|
||||
const h = hover != null ? points[hover] : null;
|
||||
return (
|
||||
<div className="card">
|
||||
<div className="flex items-baseline justify-between gap-2">
|
||||
<h3 className="text-sm font-medium">{title}</h3>
|
||||
<span className="text-xs text-slate-500">{spikes.length ? `${spikes.length} spike${spikes.length === 1 ? "" : "s"} over ${spike}%` : `No spikes over ${spike}%`}</span>
|
||||
</div>
|
||||
<div className="relative mt-2">
|
||||
<svg ref={svgRef} viewBox={`0 0 ${W} ${H}`} className="h-40 w-full" role="img" aria-label={`${title}, ${points.length} points`} onMouseMove={onMove} onMouseLeave={() => setHover(null)}>
|
||||
{[0, 50, 100].map(v => (
|
||||
<g key={v}>
|
||||
<line x1={L} x2={W - R} y1={y(v)} y2={y(v)} stroke="#e2e8f0" strokeWidth="1" />
|
||||
<text x={L - 6} y={y(v) + 4} textAnchor="end" className="fill-slate-400 text-[10px]">{v}%</text>
|
||||
</g>
|
||||
))}
|
||||
<line x1={L} x2={W - R} y1={y(spike)} y2={y(spike)} stroke="#f59e0b" strokeWidth="1" strokeDasharray="3 3" />
|
||||
<text x={L} y={H - 6} className="fill-slate-400 text-[10px]">{fmtDate(points[0].at)}</text>
|
||||
<text x={W - R} y={H - 6} textAnchor="end" className="fill-slate-400 text-[10px]">{fmtDate(points[points.length - 1].at)}</text>
|
||||
<path d={path} fill="none" stroke="#4f46e5" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
|
||||
{spikes.map(({ p, i }) => <circle key={i} cx={x(times[i])} cy={y(p.peak)} r="4" fill="#f59e0b" stroke="#fff" strokeWidth="2"><title>{`Spike ${Math.round(p.peak)}% at ${fmtDate(p.at)}`}</title></circle>)}
|
||||
{h && hover != null && (
|
||||
<g>
|
||||
<line x1={x(times[hover])} x2={x(times[hover])} y1={T} y2={H - B} stroke="#94a3b8" strokeWidth="1" />
|
||||
<circle cx={x(times[hover])} cy={y(h.value)} r="4" fill="#4f46e5" stroke="#fff" strokeWidth="2" />
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
{h && hover != null && (
|
||||
<div className="pointer-events-none absolute top-0 rounded-md border border-slate-200 bg-white px-2 py-1 text-xs shadow-sm" style={{ left: `${Math.min(80, (x(times[hover]) / W) * 100)}%` }}>
|
||||
<div className="text-slate-500">{fmtDate(h.at)}</div>
|
||||
<div className="font-medium tabular-nums">{Math.round(h.value)}% (peak {Math.round(h.peak)}%)</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<details className="mt-2 text-xs text-slate-500">
|
||||
<summary className="cursor-pointer">Show as a table</summary>
|
||||
<div className="mt-2 max-h-48 overflow-y-auto">
|
||||
<table className="w-full tabular-nums">
|
||||
<thead><tr className="text-left"><th>Time</th><th className="text-right">Average</th><th className="text-right">Peak</th></tr></thead>
|
||||
<tbody>{points.slice(-200).reverse().map(p => <tr key={p.at}><td>{fmtDate(p.at)}</td><td className="text-right">{Math.round(p.value)}%</td><td className="text-right">{Math.round(p.peak)}%</td></tr>)}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const SUBNAV = [
|
||||
{ href: "/servers", label: "Servers" },
|
||||
{ href: "/servers/installs", label: "Installs" },
|
||||
{ href: "/servers/updates", label: "Updates" },
|
||||
{ href: "/jobs", label: "Jobs" },
|
||||
{ href: "/servers/settings", label: "Ports & defaults" },
|
||||
];
|
||||
|
||||
/** The links between the servers pages. */
|
||||
export function ServersNav({ active }: { active: string }) {
|
||||
return (
|
||||
<nav className="mb-6 flex flex-wrap gap-1 border-b border-slate-200">
|
||||
{SUBNAV.map(n => (
|
||||
<a key={n.href} href={n.href} className={`-mb-px border-b-2 px-3 py-2 text-sm ${active === n.href ? "border-indigo-600 font-medium text-indigo-700" : "border-transparent text-slate-600 hover:text-slate-900"}`}>{n.label}</a>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user