diff --git a/CHANGELOG.md b/CHANGELOG.md index adfc40d..8cf39c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,26 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [2.8.0] - 2026-11-20 + +Needs `@crosscode/contracts` 1.12.0 (vendored) and, on each server, agent 1.3.0. + +### Added + +- **An install's .env on its page** (Servers → Installs → an Events or Accounts install, "Settings + (.env)"). "Read from the server" queues an `env-read` job; the values show when the agent has + answered (the panel checks every few seconds), with the addresses first (`FRONTEND_URL`, + `APP_BASE_URL`, `BACKEND_URL`, `NEXT_PUBLIC_API_URL`; `ACCOUNTS_URL`, `ACCOUNTS_API_URL`). + Secrets never reach the Hub: only whether they're set. +- **Changing values and restarting.** Edit, add or remove plain values in one file and "Save and + restart" (an `env-set` job). The backend's file restarts the backend (or not, if you untick it); + the frontend's file rebuilds and restarts the frontend. The server keeps a copy of the file and + puts it back if the site doesn't answer afterwards; the panel then says so. After a change the + file is read again by itself. Secrets, values the server generates and values the apps can't + start with (TRUST_PROXY=TRUE) are refused. One change per install at a time (`ALREADY_PLANNED`). + The audit log records the names changed, not the values. +- `env-read` and `env-set` in the Jobs page's type filter. + ## [2.7.1] - 2026-11-19 ### Fixed diff --git a/backend/package-lock.json b/backend/package-lock.json index 89b7fc5..168b770 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,16 +1,16 @@ { "name": "events-hub-backend", - "version": "2.7.1", + "version": "2.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-backend", - "version": "2.7.1", + "version": "2.8.0", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", - "@crosscode/contracts": "file:vendor/crosscode-contracts-1.10.0.tgz", + "@crosscode/contracts": "file:vendor/crosscode-contracts-1.12.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.10.0", - "resolved": "file:vendor/crosscode-contracts-1.10.0.tgz", - "integrity": "sha512-FUm5qrZcyhM7JW7H1DNHifY9IFaxCJhVsLVed++gag65RO+EFnAjlPLw2bJqPIX/9e2CD1OBtHmNKxc9NjBCWA==", + "version": "1.12.0", + "resolved": "file:vendor/crosscode-contracts-1.12.0.tgz", + "integrity": "sha512-sIf1NJtAskKghZ6D2YqiNf+F+gyZufF+XPy7QAh767+QK5zCkzeYkSPiEwW+yRJXj/R/75X2pcfuqQ0fD0WXkQ==", "license": "UNLICENSED", "dependencies": { "zod": "^4.6.7" diff --git a/backend/package.json b/backend/package.json index 7e2927b..dd22761 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-backend", - "version": "2.7.1", + "version": "2.8.0", "private": true, "description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats", "main": "src/index.js", @@ -20,7 +20,7 @@ }, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", - "@crosscode/contracts": "file:vendor/crosscode-contracts-1.10.0.tgz", + "@crosscode/contracts": "file:vendor/crosscode-contracts-1.12.0.tgz", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", "bcryptjs": "^2.4.3", diff --git a/backend/src/routes/servers.js b/backend/src/routes/servers.js index cc0dc5b..54a0ff5 100644 --- a/backend/src/routes/servers.js +++ b/backend/src/routes/servers.js @@ -195,6 +195,24 @@ router.post('/deployments/:id/demo', wrap(async (req, res) => { res.json({ isDemo: d.isDemo }); })); +// An install's .env (2.8.0): the last read (secrets only as set or not), read it again, change values. +router.get('/deployments/:id/env', wrap(async (req, res) => { + res.json(await jobs.envState(req.params.id)); +})); + +router.post('/deployments/:id/env/read', wrap(async (req, res) => { + const job = await jobs.readEnv(req.params.id, req.admin); + res.status(201).json({ job }); +})); + +router.post('/deployments/:id/env', wrap(async (req, res) => { + const body = req.body || {}; + const job = await jobs.setEnv(req.params.id, { file: body.file, set: body.set, unset: body.unset, restart: body.restart }, req.admin); + // Names only in the audit log, as on the server: values can be personal (an admin's email). + await audit(req, 'install_env_change_queued', req.params.id, { job: job.id, file: job.args.file, set: Object.keys(job.args.set), unset: job.args.unset, restart: job.args.restart }); + res.status(201).json({ job }); +})); + router.post('/deployments/:id/seed-demo', wrap(async (req, res) => { const job = await jobs.seedDemo({ deploymentId: req.params.id, profile: req.body?.profile, confirm: req.body?.confirm }, req.admin); await audit(req, 'demo_seed_queued', req.params.id, { job: job.id, profile: job.args.profile }); diff --git a/backend/src/utils/jobs.js b/backend/src/utils/jobs.js index d3e2a34..2c6067c 100644 --- a/backend/src/utils/jobs.js +++ b/backend/src/utils/jobs.js @@ -187,6 +187,13 @@ async function afterJob(job, { exportKey }, now) { await emailJoshua(`Export failed: ${deployment.shortName}`, jobReportText(job)); } break; + case 'env-set': + // 2.8.0: read the file again, so the install's page shows what's there now (also after a put-back). + if (deployment && ['succeeded', 'rolled_back'].includes(job.status)) { + await makeJob(prisma, { serverId: deployment.serverId, type: 'env-read', args: { church: deployment.shortName, product: deployment.product }, deploymentId: deployment.id, createdById: job.createdById, notBefore: now }); + } + if (deployment && !ok) await emailJoshua(`.env change ${job.status.replace('_', ' ')}: ${deployment.shortName}`, jobReportText(job)); + break; case 'uninstall': if (!deployment) break; if (ok) { @@ -985,7 +992,71 @@ async function seedDemo({ deploymentId, profile, confirm }, admin, now = new Dat return makeJob(prisma, { serverId: d.serverId, type: 'seed-demo', deploymentId: d.id, createdById: admin?.id || null, notBefore: now, args: { church: d.shortName, profile, ...(adminEmail ? { adminEmail } : {}) } }); } +// ─── An install's .env (2.8.0, contracts 1.12.0, agent 1.3.0) ───────────────── + +const ENV_PRODUCTS = ['events', 'accounts']; +const ENV_OPEN = ['queued', 'delivered']; + +/** The install, checked for reading or changing its .env: installed, a product the script knows, an agent that can. */ +async function envDeployment(deploymentId, now) { + const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { server: true } }); + if (!d) throw fail(404, 'NOT_FOUND', 'Not found.'); + if (!ENV_PRODUCTS.includes(d.product)) throw fail(400, 'NOT_SUPPORTED', `${PRODUCT_NAMES[d.product] || d.product} installs don't have .env settings here yet.`); + if (!['live', 'waiting_for_proxy'].includes(d.status)) throw fail(409, 'NOT_LIVE', `It's ${d.status.replace(/_/g, ' ')}; .env settings are for an installed site.`); + if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', 'That server was removed.'); + if (compareVersions(d.server.agentVersion || '0.0.0', agent.ENV_JOBS_MIN_AGENT) < 0) { + throw fail(409, 'AGENT_TOO_OLD', `The agent on ${d.server.name} is ${d.server.agentVersion || 'an unknown version'}; .env settings need ${agent.ENV_JOBS_MIN_AGENT} or later (update the agent first).`); + } + const running = await prisma.job.findFirst({ where: { serverId: d.serverId, status: 'delivered' }, orderBy: { deliveredAt: 'desc' } }); + if (!agentOnline(d.server, now, running)) throw fail(409, 'AGENT_OFFLINE', `The agent on ${d.server.name} isn't online.`); + return d; +} + +/** What the install's page shows: the last read of its .env (secrets only as set or not) and any env job not finished. */ +async function envState(deploymentId) { + const d = await prisma.deployment.findUnique({ where: { id: deploymentId } }); + if (!d) throw fail(404, 'NOT_FOUND', 'Not found.'); + const lastRead = await prisma.job.findFirst({ where: { deploymentId, type: 'env-read', status: 'succeeded' }, orderBy: { finishedAt: 'desc' } }); + const parsed = lastRead ? agent.envReadResultSchema.safeParse(lastRead.report?.result?.env) : null; + const pending = await prisma.job.findMany({ where: { deploymentId, type: { in: ['env-read', 'env-set'] }, status: { in: ENV_OPEN } }, orderBy: { createdAt: 'asc' } }); + const lastSet = await prisma.job.findFirst({ where: { deploymentId, type: 'env-set', status: { notIn: ENV_OPEN } }, orderBy: { createdAt: 'desc' } }); + return { + supported: ENV_PRODUCTS.includes(d.product), + minAgent: agent.ENV_JOBS_MIN_AGENT, + env: parsed?.success ? parsed.data : null, + readJobId: lastRead?.id || null, + pending: pending.map(j => ({ id: j.id, type: j.type, status: j.status, createdAt: j.createdAt })), + lastSet: lastSet ? { id: lastSet.id, status: lastSet.status, message: lastSet.message, finishedAt: lastSet.finishedAt, args: lastSet.args } : null, + }; +} + +/** Ask the agent for the install's .env values (an env-read job, at its next poll). */ +async function readEnv(deploymentId, admin, now = new Date()) { + const d = await envDeployment(deploymentId, now); + const open = await prisma.job.findFirst({ where: { deploymentId: d.id, type: 'env-read', status: { in: ENV_OPEN } } }); + if (open) return open; + return makeJob(prisma, { serverId: d.serverId, type: 'env-read', args: { church: d.shortName, product: d.product }, deploymentId: d.id, createdById: admin?.id || null, notBefore: now }); +} + +/** + * Change values in one of the install's .env files, then (with `restart`, or always for the + * frontend's file, which needs a rebuild) reload it. Never secrets (the contract refuses them, and + * so does the server); values the app can't start with are refused here first. If the site doesn't + * come back, the server puts the file back. + */ +async function setEnv(deploymentId, { file, set, unset, restart }, admin, now = new Date()) { + const d = await envDeployment(deploymentId, now); + const values = set && typeof set === 'object' && !Array.isArray(set) ? Object.fromEntries(Object.entries(set).map(([k, v]) => [k, String(v ?? '')])) : {}; + const bad = agent.invalidValues(values); + if (Object.keys(bad).length) throw fail(400, 'BAD_VALUE', Object.values(bad).join(' ')); + const args = { church: d.shortName, product: d.product, file: String(file || 'backend/.env'), set: values, unset: Array.isArray(unset) ? unset.map(String) : [], restart: restart !== false }; + const open = await prisma.job.findFirst({ where: { deploymentId: d.id, type: 'env-set', status: { in: ENV_OPEN } } }); + if (open) throw fail(409, 'ALREADY_PLANNED', 'A change to this install\'s .env is already waiting for the agent. Wait for it to finish first.'); + return makeJob(prisma, { serverId: d.serverId, type: 'env-set', args, deploymentId: d.id, createdById: admin?.id || null, notBefore: now }); +} + module.exports = { + readEnv, setEnv, envState, WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo, makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch, JOB_STATUSES, linkFromStatus, listWhere, lookForUnlinked, newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow, diff --git a/backend/tests/servers.test.js b/backend/tests/servers.test.js index 1f53408..49b1f29 100644 --- a/backend/tests/servers.test.js +++ b/backend/tests/servers.test.js @@ -743,3 +743,63 @@ describe('one update at a time per install (2.7.1)', () => { expect(await db.job.count({ where: { deploymentId: d.id, type: 'deploy' } })).toBe(1); }); }); + +describe("an install's .env from the Hub (2.8.0)", () => { + const poll = (server, v = '1.3.0') => jobs.poll(server, { agentApiVersion: 1, agentVersion: v, mode: 'church', runningJobId: null }, NOW); + async function live({ agentVersion = '1.3.0', product = 'events' } = {}) { + const { server } = await joinServer(); + await db.server.update({ where: { id: server.id }, data: { agentVersion } }); + const d = await db.deployment.create({ data: { id: 'dep-env', serverId: server.id, customerId: 'cust-1', product, shortName: 'hope', domain: `${product}.hope.test`, webPort: 20000, apiPort: 20001, status: 'live' } }); + return { server, d }; + } + const envResult = (url) => ({ env: { + product: 'events', readAt: NOW.toISOString(), + files: [{ file: 'backend/.env', exists: true, variables: [ + { name: 'FRONTEND_URL', value: url, secret: false, set: true, layer: 'install', description: null, editable: true }, + { name: 'JWT_SECRET', value: null, secret: true, set: true, layer: 'generated', description: null, editable: false }, + ] }], + } }); + + test('read: an env-read job the agent can verify, and its result shown on the page', async () => { + const { server, d } = await live(); + const job = await jobs.readEnv(d.id, admin, NOW); + expect(job).toMatchObject({ type: 'env-read', args: { church: 'hope', product: 'events' } }); + // Asking twice while it waits doesn't make a second job. + expect((await jobs.readEnv(d.id, admin, NOW)).id).toBe(job.id); + expect((await jobs.envState(d.id)).pending).toHaveLength(1); + const [signed] = (await poll(server)).jobs; + expect(agent.agentJobSchema.safeParse(signed).success).toBe(true); + expect(signed.config).toBeNull(); + await jobs.receiveReport(server, signedReport(signed, 'succeeded', { result: envResult('https://events.hope.test') }), NOW); + const state = await jobs.envState(d.id); + expect(state.pending).toEqual([]); + expect(state.env.files[0].variables.map(v => [v.name, v.value])).toEqual([['FRONTEND_URL', 'https://events.hope.test'], ['JWT_SECRET', null]]); + }); + + test('set: plain values and a restart; afterwards the .env is read again', async () => { + const { server, d } = await live(); + const job = await jobs.setEnv(d.id, { file: 'backend/.env', set: { FRONTEND_URL: 'https://new.hope.test' }, unset: [], restart: true }, admin, NOW); + expect(job.args).toEqual({ church: 'hope', product: 'events', file: 'backend/.env', set: { FRONTEND_URL: 'https://new.hope.test' }, unset: [], restart: true }); + await expect(jobs.setEnv(d.id, { set: { APP_TIMEZONE: 'UTC' } }, admin, NOW)).rejects.toMatchObject({ code: 'ALREADY_PLANNED' }); + const [signed] = (await poll(server)).jobs; + expect(agent.agentJobSchema.safeParse(signed).success).toBe(true); + await jobs.receiveReport(server, signedReport(signed, 'succeeded'), NOW); + expect(await db.job.findFirst({ where: { deploymentId: d.id, type: 'env-read', status: 'queued' } })).toBeTruthy(); + expect((await jobs.envState(d.id)).lastSet).toMatchObject({ status: 'succeeded' }); + }); + + test("refused: secrets, values the app can't start with, nothing to change, an old agent, a product without .env support", async () => { + let { d } = await live(); + await expect(jobs.setEnv(d.id, { set: { JWT_SECRET: 'x' } }, admin, NOW)).rejects.toMatchObject({ status: 400, message: expect.stringContaining('secret') }); + await expect(jobs.setEnv(d.id, { set: { TRUST_PROXY: 'TRUE' } }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_VALUE' }); + await expect(jobs.setEnv(d.id, { set: {} }, admin, NOW)).rejects.toMatchObject({ status: 400 }); + await expect(jobs.setEnv(d.id, { file: '../.env', set: { A: '1' } }, admin, NOW)).rejects.toMatchObject({ status: 400 }); + await seed(); + ({ d } = await live({ agentVersion: '1.2.0' })); + await expect(jobs.readEnv(d.id, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.3.0') }); + await seed(); + ({ d } = await live({ product: 'website' })); + await expect(jobs.readEnv(d.id, admin, NOW)).rejects.toMatchObject({ code: 'NOT_SUPPORTED' }); + expect(await db.job.findMany({})).toEqual([]); + }); +}); diff --git a/backend/vendor/crosscode-contracts-1.10.0.tgz b/backend/vendor/crosscode-contracts-1.10.0.tgz deleted file mode 100644 index b1aa962..0000000 Binary files a/backend/vendor/crosscode-contracts-1.10.0.tgz and /dev/null differ diff --git a/backend/vendor/crosscode-contracts-1.12.0.tgz b/backend/vendor/crosscode-contracts-1.12.0.tgz new file mode 100644 index 0000000..33b3663 Binary files /dev/null and b/backend/vendor/crosscode-contracts-1.12.0.tgz differ diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 7a41365..8780f6b 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-frontend", - "version": "2.7.1", + "version": "2.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-frontend", - "version": "2.7.1", + "version": "2.8.0", "dependencies": { "lucide-react": "^0.536.0", "next": "^15.5.24", diff --git a/frontend/package.json b/frontend/package.json index e60653d..668e386 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-frontend", - "version": "2.7.1", + "version": "2.8.0", "private": true, "scripts": { "dev": "next dev -p 3200", diff --git a/frontend/src/app/(hub)/jobs/page.tsx b/frontend/src/app/(hub)/jobs/page.tsx index 1c99b36..2a76b41 100644 --- a/frontend/src/app/(hub)/jobs/page.tsx +++ b/frontend/src/app/(hub)/jobs/page.tsx @@ -18,7 +18,7 @@ const FILTERS = [ { key: "cancelled", label: "Cancelled" }, ]; -const TYPES = ["", "install", "add-product", "deploy", "adopt", "adopt-undo", "export", "uninstall", "purge", "seed-demo", "restart", "status", "check-ports", "update-agent"]; +const TYPES = ["", "install", "add-product", "deploy", "adopt", "adopt-undo", "export", "uninstall", "purge", "seed-demo", "env-read", "env-set", "restart", "status", "check-ports", "update-agent"]; const PRODUCTS = [{ key: "", label: "Every product" }, { key: "events", label: "Cross Events" }, { key: "accounts", label: "Accounts" }]; /** Every job sent to a server's agent, newest first, a page at a time (§11: the full report is on each job). */ diff --git a/frontend/src/app/(hub)/servers/installs/[id]/page.tsx b/frontend/src/app/(hub)/servers/installs/[id]/page.tsx index 7653eef..ce065b4 100644 --- a/frontend/src/app/(hub)/servers/installs/[id]/page.tsx +++ b/frontend/src/app/(hub)/servers/installs/[id]/page.tsx @@ -10,6 +10,7 @@ import { PRODUCT_NAMES } from "@/lib/products"; import type { Release } from "@/lib/types"; import { Loading, Message, PageTitle, Pager } from "@/components/ui"; import { ServersNav, StatusPill, toInput, fromInput, type Deployment, type Job, type ServerSummary } from "@/components/servers"; +import { EnvPanel } from "@/components/EnvPanel"; type Msg = { type: "ok" | "err"; text: string } | null; type Detail = { @@ -164,6 +165,9 @@ export default function DeploymentPage() { )} + {/* Hub 2.8.0: the install's .env, and changing it with a restart. */} + {["events", "accounts"].includes(x.product) && ["live", "waiting_for_proxy"].includes(x.status) && } + {x.product === "events" && ["live", "waiting_for_proxy"].includes(x.status) && (

Demo site

diff --git a/frontend/src/components/EnvPanel.tsx b/frontend/src/components/EnvPanel.tsx new file mode 100644 index 0000000..b66975d --- /dev/null +++ b/frontend/src/components/EnvPanel.tsx @@ -0,0 +1,237 @@ +"use client"; + +import React, { useCallback, useEffect, useMemo, useState } from "react"; +import Link from "next/link"; +import { api, errorText } from "@/lib/api"; +import { ago, fmtDate } from "@/lib/format"; +import { Message } from "@/components/ui"; + +/** + * An install's .env (Hub 2.8.0, agent 1.3.0): what's in it (secrets only as set or not), changing + * plain values, then a restart (or a rebuild for the frontend's file). The server keeps a copy of + * the file and puts it back when the site doesn't start again with the new values. + */ + +type Variable = { name: string; value: string | null; secret: boolean; set: boolean; layer: string | null; description: string | null; editable: boolean }; +type EnvFile = { file: string; exists: boolean; variables: Variable[] }; +type EnvState = { + supported: boolean; + minAgent: string; + env: { product: string; files: EnvFile[]; readAt: string } | null; + readJobId: string | null; + pending: { id: string; type: "env-read" | "env-set"; status: string; createdAt: string }[]; + lastSet: { id: string; status: string; message: string | null; finishedAt: string | null; args: { file: string; set: Record; unset: string[] } } | null; +}; +type Msg = { type: "ok" | "err"; text: string } | null; + +/** The addresses, shown first: what people most often need to check or fix. */ +const ADDRESSES: Record = { + events: ["FRONTEND_URL", "APP_BASE_URL", "BACKEND_URL", "NEXT_PUBLIC_API_URL"], + accounts: ["ACCOUNTS_URL", "ACCOUNTS_API_URL"], +}; +const NAME = /^[A-Z][A-Z0-9_]*$/; +const SECRET = /(SECRET|PASS|TOKEN|PRIVATE|CREDENTIAL|_KEY$|_DSN$|DATABASE_URL|ADMIN_URL)/; + +const FILE_NOTE: Record = { + "backend/.env": "The backend reads it when it starts: saving restarts it (unless you untick it).", + "frontend/.env.production": "Next.js builds these values in: saving rebuilds the frontend (a few minutes), then restarts it.", +}; + +export function EnvPanel({ deploymentId, product }: { deploymentId: string; product: string }) { + const [state, setState] = useState(null); + const [msg, setMsg] = useState(null); + const [busy, setBusy] = useState(false); + // Edits per file: changed values, names to remove, and new variables. + const [edits, setEdits] = useState>>({}); + const [removed, setRemoved] = useState>({}); + const [added, setAdded] = useState>({}); + const [restart, setRestart] = useState(true); + const [showAll, setShowAll] = useState(false); + + const load = useCallback(() => api(`/api/admin/deployments/${deploymentId}/env`).then(setState).catch(e => setMsg({ type: "err", text: errorText(e) })), [deploymentId]); + useEffect(() => { load(); }, [load]); + // While the agent has a job of ours, look again every few seconds. + const waiting = !!state?.pending.length; + useEffect(() => { + if (!waiting) return; + const t = setInterval(load, 4000); + return () => clearInterval(t); + }, [waiting, load]); + + const run = async (fn: () => Promise) => { + if (busy) return; + setBusy(true); + setMsg(null); + try { await fn(); } catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); } + }; + + const read = () => run(async () => { + await api(`/api/admin/deployments/${deploymentId}/env/read`, { method: "POST" }); + setMsg({ type: "ok", text: "Asked the agent: the values show here within a minute." }); + await load(); + }); + + const changesFor = (file: string) => { + const set: Record = { ...(edits[file] || {}) }; + const a = added[file]; + if (a?.name.trim()) set[a.name.trim()] = a.value; + return { set, unset: removed[file] || [] }; + }; + + const save = (file: string) => run(async () => { + const { set, unset } = changesFor(file); + const names = [...Object.keys(set), ...unset]; + if (!names.length) return; + const bad = names.find(n => !NAME.test(n)); + if (bad) throw new Error(`${bad} isn't a variable name (A-Z, 0-9 and _, starting with a letter).`); + const secret = names.find(n => SECRET.test(n)); + if (secret) throw new Error(`${secret} looks like a secret: change it on the server, not from the Hub.`); + const rebuild = file.startsWith("frontend/"); + const lines = [...Object.entries(set).map(([k, v]) => ` ${k}=${v}`), ...unset.map(n => ` remove ${n}`)].join("\n"); + const then = rebuild ? "The frontend is then rebuilt and restarted (the site is slow or unavailable for a few minutes)." : restart ? "The backend is then restarted (a few seconds)." : "Nothing is restarted: the new values apply at the next restart."; + if (!window.confirm(`Change ${file} on the server?\n\n${lines}\n\n${then} If it doesn't start again, the file is put back as it was.`)) return; + await api(`/api/admin/deployments/${deploymentId}/env`, { method: "POST", body: { file, set, unset, restart: rebuild || restart } }); + setEdits(e => ({ ...e, [file]: {} })); + setRemoved(r => ({ ...r, [file]: [] })); + setAdded(a => ({ ...a, [file]: { name: "", value: "" } })); + setMsg({ type: "ok", text: "Queued: the agent changes the file at its next poll. This panel updates when it's done." }); + await load(); + }); + + const addresses = useMemo(() => { + const names = ADDRESSES[product] || []; + const out: { file: string; v: Variable }[] = []; + for (const f of state?.env?.files || []) for (const v of f.variables) if (names.includes(v.name)) out.push({ file: f.file, v }); + return out; + }, [state, product]); + + if (!state) return

Settings (.env)

{msg ?
:

Loading…

}
; + if (!state.supported) return null; + + const pendingRead = state.pending.find(p => p.type === "env-read"); + const pendingSet = state.pending.find(p => p.type === "env-set"); + + return ( +
+
+
+

Settings (.env)

+

+ The values in this install's .env files on the server. Secrets (passwords, keys, the database) are never sent to the Hub: only whether they're set. + Needs agent {state.minAgent} or later. +

+
+ +
+ + + {pendingSet &&

A change is {pendingSet.status === "delivered" ? "being made on the server now" : "waiting for the agent"} (job).

} + {state.lastSet && !pendingSet && state.lastSet.status !== "succeeded" && ( +

+ The last change ({fmtDate(state.lastSet.finishedAt)}) {state.lastSet.status === "rolled_back" ? "was put back: the site didn't start with it" : `didn't go through (${state.lastSet.status.replace(/_/g, " ")})`}. + {state.lastSet.message ? ` ${state.lastSet.message}` : ""} See the job. +

+ )} + + {!state.env && !pendingRead &&

Not read yet. “Read from the server” asks the agent for them.

} + + {state.env && ( + <> +

Read {ago(state.env.readAt)} ({fmtDate(state.env.readAt)}){state.readJobId && <> · job}.

+ + {!!addresses.length && ( +
+

Addresses

+
+ {addresses.map(({ file, v }) => ( + +
{v.name}({file.split("/")[0]})
+
{v.set ? v.value : not set}
+
+ ))} +
+

Change them in the files below. The site's address on the Hub ({product}) and in FastPanel doesn't change with them.

+
+ )} + + + + {state.env.files.map(f => { + const fileEdits = edits[f.file] || {}; + const fileRemoved = removed[f.file] || []; + const a = added[f.file] || { name: "", value: "" }; + const { set, unset } = changesFor(f.file); + const count = Object.keys(set).length + unset.length; + const rebuild = f.file.startsWith("frontend/"); + const rows = f.variables.filter(v => showAll || v.set || v.name in fileEdits); + return ( +
{ e.preventDefault(); save(f.file); }}> +
+

{f.file}{!f.exists && missing on the server}

+ {FILE_NOTE[f.file]} +
+
+ + + + {rows.map(v => { + const isRemoved = fileRemoved.includes(v.name); + const value = v.name in fileEdits ? fileEdits[v.name] : (v.value ?? ""); + const changed = v.name in fileEdits && fileEdits[v.name] !== (v.value ?? ""); + return ( + + + + + + ); + })} + + + + + +
NameValueRemove
+
{v.name}
+ {(v.description || v.layer) &&
{[v.layer, v.description].filter(Boolean).join(" · ")}
} +
+ {v.secret ? ( + {v.set ? "•••••••• (secret, set)" : "secret, not set"} + ) : v.editable ? ( + { + const next = e.target.value; + setEdits(x => { + const fe = { ...(x[f.file] || {}) }; + if (next === (v.value ?? "")) delete fe[v.name]; else fe[v.name] = next; + return { ...x, [f.file]: fe }; + }); + }} /> + ) : ( + {v.value}made by the server + )} + + {v.editable && v.set && ( + + )} +
setAdded(x => ({ ...x, [f.file]: { ...a, name: e.target.value.toUpperCase() } }))} /> setAdded(x => ({ ...x, [f.file]: { ...a, value: e.target.value } }))} />
+
+
+ + {!rebuild && } + {!!count && } +
+
+ ); + })} + + )} +
+ ); +}