diff --git a/backend/.env.example b/backend/.env.example index 46d1359..65c04d5 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -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 diff --git a/backend/package-lock.json b/backend/package-lock.json index 3aff61b..f62f01e 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -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" diff --git a/backend/package.json b/backend/package.json index effe6bf..18bb7b2 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/prisma/migrations/20261118090000_servers_agent/migration.sql b/backend/prisma/migrations/20261118090000_servers_agent/migration.sql new file mode 100644 index 0000000..bc2d300 --- /dev/null +++ b/backend/prisma/migrations/20261118090000_servers_agent/migration.sql @@ -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; + diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 208909f..6e28675 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -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 (.crosscode.co.za) R10 · // included (a domain registered in the church's name and renewed by Cross Code) R25. - addressType AddressType @default(own_domain) + addressType AddressType @default(own_domain) // The domain: hopefamily.co.za, or hopefamily.crosscode.co.za for a Cross Code address. - domain String? + domain String? // A price per month instead of the option's (e.g. a .com charged at cost), in cents. - addressCustomCents Int? + addressCustomCents Int? // Domain included: when it's next due for renewal, and the renewal date Joshua was last // reminded about (30 days before), so he's reminded once per renewal. - domainRenewsOn DateTime? @db.Date - domainRemindedFor DateTime? @db.Date + domainRenewsOn DateTime? @db.Date + domainRemindedFor DateTime? @db.Date // Hub 2.0 (moved from Licence): the monthly AI spend cap in cents (rand), counted in charged // rand over all the church's installs. 0 = AI off. And the markup on the real cost, in %; null = // the Hub default (Settings → AI). - aiMonthlyCapCents Int @default(0) - aiMarkupPercent Int? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - licences Licence[] - installs Install[] - invoices Invoice[] - payments Payment[] - licenceChanges LicenceChange[] - billingEmails BillingEmail[] + aiMonthlyCapCents Int @default(0) + aiMarkupPercent Int? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + licences Licence[] + installs Install[] + invoices Invoice[] + payments Payment[] + licenceChanges LicenceChange[] + billingEmails BillingEmail[] + deployments Deployment[] } enum LicenceStatus { @@ -169,6 +170,7 @@ model Install { heartbeats Heartbeat[] events InstallEvent[] aiUsage AiUsage[] + deployment Deployment? @@index([lastHeartbeatAt]) } @@ -451,3 +453,215 @@ model DocumentCounter { key String @id value Int @default(0) } + +// ─── Servers and the agent (2.1.0, crosscode-platform docs/AGENT-1.0-PLAN.md) ────────────────── + +enum ServerMode { + church + central +} + +// A server running the crosscode agent. It joined with a one-time token and its two public keys: +// Ed25519 (checks its requests) and X25519 (config is sealed to it). The agent polls; the Hub +// never connects to a server. +model Server { + id String @id + name String + mode ServerMode @default(church) + hostname String? + ed25519Key String + x25519Key String + // Server configuration (§5): database host, port and admin, TRUST_PROXY, … AES-GCM encrypted + // JSON (utils/crypto.js); sealed to the server's key in each job that needs it. + config String? + agentVersion String? + lastSeenAt DateTime? + // The latest stats (crosscode.agent-stats/1), for the Servers page. + lastStats Json? + joinedAt DateTime @default(now()) + removedAt DateTime? + notes String? + stats ServerStat[] + jobs Job[] + deployments Deployment[] + ports Port[] + alerts ServerAlert[] +} + +// One-time join tokens (Servers → Add server), valid an hour. Only the hash is kept. +model ServerJoinToken { + id String @id @default(uuid()) + tokenHash String @unique + name String + mode ServerMode @default(church) + expiresAt DateTime + usedAt DateTime? + serverId String? + createdById String? + createdAt DateTime @default(now()) +} + +enum StatGranularity { + minute + hour +} + +// Server stats: one row a minute for 7 days, then one an hour (average and peak) for 90 days. +model ServerStat { + id String @id @default(uuid()) + serverId String + server Server @relation(fields: [serverId], references: [id], onDelete: Cascade) + at DateTime + granularity StatGranularity @default(minute) + cpuPercent Float + cpuPeak Float + ramUsedPercent Float + ramPeak Float + ramUsedBytes BigInt + ramTotalBytes BigInt + diskUsedPercent Float + load1 Float + + @@index([serverId, granularity, at]) +} + +// Open problems on a server (agent silent, disk, RAM, a process restarting, frpc, the central +// checks). Emailed once when they start and once when they clear. +model ServerAlert { + id String @id @default(uuid()) + serverId String + server Server @relation(fields: [serverId], references: [id], onDelete: Cascade) + type String + level EventLevel @default(warning) + message String + createdAt DateTime @default(now()) + resolvedAt DateTime? + + @@index([serverId, resolvedAt]) +} + +enum DeploymentStatus { + installing + waiting_for_proxy + live + failed + uninstalling + removed +} + +// A product installed on a server through the agent (or an existing install linked to it): the +// church's short name, domain and tunnel ports. Linked to its Install once the site registers. +model Deployment { + id String @id @default(uuid()) + serverId String + server Server @relation(fields: [serverId], references: [id], onDelete: Restrict) + customerId String + customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict) + licenceId String? + installId String? @unique + install Install? @relation(fields: [installId], references: [id], onDelete: SetNull) + product Product @default(events) + // Folders, PM2, database and tunnel names on the server: hope → /var/www/sites/hope/events. + shortName String + domain String + webPort Int + apiPort Int + timezone String? + // The church's site admin, for the welcome and update emails. + adminName String? + adminEmail String? + status DeploymentStatus @default(installing) + // The release it runs (from reports and heartbeats). + version String? + liveAt DateTime? + removedAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + jobs Job[] + exports Export[] + + @@unique([shortName, product]) + @@index([serverId]) +} + +enum JobStatus { + // Waiting for its time (a scheduled update, or a batch's later installs). + scheduled + // Due: handed to the agent on its next poll. + queued + delivered + succeeded + failed + rolled_back + refused + expired + // Its time passed before the agent picked it up: nothing ran. + missed + cancelled +} + +// A signed job for a server's agent (crosscode.agent-job/1) and its report. +model Job { + id String @id + serverId String + server Server @relation(fields: [serverId], references: [id], onDelete: Restrict) + deploymentId String? + deployment Deployment? @relation(fields: [deploymentId], references: [id], onDelete: SetNull) + type String + args Json + status JobStatus @default(queued) + notBefore DateTime + expiresAt DateTime + // An update with notice to the church (§8); emergency = at least 15 minutes, with a reason. + scheduled Boolean @default(false) + emergency Boolean @default(false) + reason String? + // A batch runs its jobs one at a time and stops at the first failure. + batchId String? + batchOrder Int? + // The notice (banner) for a scheduled job, removed when it's done or cancelled. + noticeId String? + remindedAt DateTime? + createdById String? + deliveredAt DateTime? + finishedAt DateTime? + // crosscode.agent-report/1 (without the export key). + report Json? + message String? + createdAt DateTime @default(now()) + + @@index([serverId, status, notBefore]) + @@index([batchId]) + @@index([status, expiresAt]) +} + +// The port list (§6): every port frps opens on the central server, unique across servers. +model Port { + port Int @id + serverId String? + server Server? @relation(fields: [serverId], references: [id], onDelete: SetNull) + deploymentId String? + // web, api, or taken (found in use / reserved by hand). + role String + note String? + // Free again 30 days after an uninstall. + releasedAt DateTime? + createdAt DateTime @default(now()) + + @@index([serverId]) +} + +// A church's data when it leaves (§9): encrypted on the server with a key only in the emailed +// link, so the Hub stores it but can't read it. Deleted after 30 days (extendable once). +model Export { + id String @id + deploymentId String? + deployment Deployment? @relation(fields: [deploymentId], references: [id], onDelete: SetNull) + data Bytes? + bytes Int @default(0) + expiresAt DateTime + extended Boolean @default(false) + downloadedAt DateTime? + deletedAt DateTime? + createdAt DateTime @default(now()) +} diff --git a/backend/scripts/generate-keys.js b/backend/scripts/generate-keys.js index 3f54294..875ddc4 100644 --- a/backend/scripts/generate-keys.js +++ b/backend/scripts/generate-keys.js @@ -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' })); +} diff --git a/backend/src/app.js b/backend/src/app.js index 96e1a46..8b768df 100644 --- a/backend/src/app.js +++ b/backend/src/app.js @@ -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' })); diff --git a/backend/src/index.js b/backend/src/index.js index 9eb8bde..f26bb58 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -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); diff --git a/backend/src/routes/agentApi.js b/backend/src/routes/agentApi.js new file mode 100644 index 0000000..3d500e7 --- /dev/null +++ b/backend/src/routes/agentApi.js @@ -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; diff --git a/backend/src/routes/exports.js b/backend/src/routes/exports.js new file mode 100644 index 0000000..f0b2034 --- /dev/null +++ b/backend/src/routes/exports.js @@ -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; diff --git a/backend/src/routes/servers.js b/backend/src/routes/servers.js new file mode 100644 index 0000000..825e0be --- /dev/null +++ b/backend/src/routes/servers.js @@ -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, cpu: x.cpuPercent, cpuPeak: x.cpuPeak, ram: x.ramUsedPercent, ramPeak: x.ramPeak, disk: 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; diff --git a/backend/src/utils/envTemplates.js b/backend/src/utils/envTemplates.js new file mode 100644 index 0000000..d5239e6 --- /dev/null +++ b/backend/src/utils/envTemplates.js @@ -0,0 +1,43 @@ +/** + * The env template of the release being installed (crosscode.env-template/1, + * apps//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 }; diff --git a/backend/src/utils/envTemplates/events.json b/backend/src/utils/envTemplates/events.json new file mode 100644 index 0000000..b0f8581 --- /dev/null +++ b/backend/src/utils/envTemplates/events.json @@ -0,0 +1,28 @@ +{ + "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_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 } + ] + } +} diff --git a/backend/src/utils/jobs.js b/backend/src/utils/jobs.js new file mode 100644 index 0000000..4b4bae9 --- /dev/null +++ b/backend/src/utils/jobs.js @@ -0,0 +1,601 @@ +/** + * 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 || ''} (${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/deployments/${d.id}`, + ].join('\n'); +} + +// ─── Notices (banners) ──────────────────────────────────────────────────────── + +async function addNotice(deployment, { title, message, endsAt, level = 'maintenance' }, now) { + if (!deployment.installId) return null; + const n = await prisma.notice.create({ data: { title, message, level, allInstalls: false, installIds: [deployment.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: { not: 'removed' } } })) throw fail(409, 'SHORT_NAME_TAKEN', `The short name ${shortName} is already used.`); + 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, +}; diff --git a/backend/src/utils/releaseSync.js b/backend/src/utils/releaseSync.js index daa5640..cf6260d 100644 --- a/backend/src/utils/releaseSync.js +++ b/backend/src/utils/releaseSync.js @@ -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 }; diff --git a/backend/src/utils/servers.js b/backend/src/utils/servers.js new file mode 100644 index 0000000..c247b01 --- /dev/null +++ b/backend/src/utils/servers.js @@ -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, +}; diff --git a/backend/tests/fakeDb.js b/backend/tests/fakeDb.js new file mode 100644 index 0000000..9861946 --- /dev/null +++ b/backend/tests/fakeDb.js @@ -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 }; diff --git a/backend/tests/servers.test.js b/backend/tests/servers.test.js new file mode 100644 index 0000000..4dfc9fa --- /dev/null +++ b/backend/tests/servers.test.js @@ -0,0 +1,266 @@ +// 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']); + }); +}); diff --git a/backend/vendor/crosscode-contracts-1.1.0.tgz b/backend/vendor/crosscode-contracts-1.1.0.tgz deleted file mode 100644 index 1aade2a..0000000 Binary files a/backend/vendor/crosscode-contracts-1.1.0.tgz and /dev/null differ diff --git a/backend/vendor/crosscode-contracts-1.3.0.tgz b/backend/vendor/crosscode-contracts-1.3.0.tgz new file mode 100644 index 0000000..4de106d Binary files /dev/null and b/backend/vendor/crosscode-contracts-1.3.0.tgz differ