Merge branch 'feat/install-env'

This commit is contained in:
2026-11-20 12:14:14 +02:00
13 changed files with 422 additions and 12 deletions
+20
View File
@@ -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
+6 -6
View File
@@ -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"
+2 -2
View File
@@ -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",
+18
View File
@@ -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 });
+71
View File
@@ -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,
+60
View File
@@ -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([]);
});
});
Binary file not shown.
Binary file not shown.
+2 -2
View File
@@ -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",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "2.7.1",
"version": "2.8.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
+1 -1
View File
@@ -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). */
@@ -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() {
</form>
)}
{/* 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) && <EnvPanel deploymentId={x.id} product={x.product} />}
{x.product === "events" && ["live", "waiting_for_proxy"].includes(x.status) && (
<div className="card space-y-3">
<h2 className="font-medium">Demo site</h2>
+237
View File
@@ -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<string, string>; 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<string, string[]> = {
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<string, string> = {
"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<EnvState | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const [busy, setBusy] = useState(false);
// Edits per file: changed values, names to remove, and new variables.
const [edits, setEdits] = useState<Record<string, Record<string, string>>>({});
const [removed, setRemoved] = useState<Record<string, string[]>>({});
const [added, setAdded] = useState<Record<string, { name: string; value: string }>>({});
const [restart, setRestart] = useState(true);
const [showAll, setShowAll] = useState(false);
const load = useCallback(() => api<EnvState>(`/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<void>) => {
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<string, string> = { ...(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 <div className="card"><h2 className="font-medium">Settings (.env)</h2>{msg ? <div className="mt-2"><Message msg={msg} /></div> : <p className="mt-2 text-sm text-slate-400">Loading…</p>}</div>;
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 (
<div className="card space-y-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-medium">Settings (.env)</h2>
<p className="mt-1 text-sm text-slate-500">
The values in this install&apos;s .env files on the server. Secrets (passwords, keys, the database) are never sent to the Hub: only whether they&apos;re set.
Needs agent {state.minAgent} or later.
</p>
</div>
<button className="btn-secondary" disabled={busy || !!pendingRead} onClick={read}>{pendingRead ? "Reading…" : state.env ? "Read again" : "Read from the server"}</button>
</div>
<Message msg={msg} />
{pendingSet && <p className="rounded-lg border border-indigo-200 bg-indigo-50 p-3 text-sm text-indigo-900">A change is {pendingSet.status === "delivered" ? "being made on the server now" : "waiting for the agent"} (<Link className="underline" href={`/jobs/${pendingSet.id}`}>job</Link>).</p>}
{state.lastSet && !pendingSet && state.lastSet.status !== "succeeded" && (
<p className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">
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}` : ""} <Link className="underline" href={`/jobs/${state.lastSet.id}`}>See the job</Link>.
</p>
)}
{!state.env && !pendingRead && <p className="text-sm text-slate-500">Not read yet. &ldquo;Read from the server&rdquo; asks the agent for them.</p>}
{state.env && (
<>
<p className="text-xs text-slate-500">Read {ago(state.env.readAt)} ({fmtDate(state.env.readAt)}){state.readJobId && <> · <Link className="underline" href={`/jobs/${state.readJobId}`}>job</Link></>}.</p>
{!!addresses.length && (
<div className="rounded-lg border border-slate-200 bg-slate-50 p-3">
<h3 className="text-sm font-medium">Addresses</h3>
<dl className="mt-2 grid gap-x-4 gap-y-1 text-sm sm:grid-cols-[max-content_1fr]">
{addresses.map(({ file, v }) => (
<React.Fragment key={`${file}:${v.name}`}>
<dt className="font-mono text-xs text-slate-600">{v.name}<span className="ml-1 text-slate-400">({file.split("/")[0]})</span></dt>
<dd className="break-all font-mono text-xs">{v.set ? v.value : <span className="text-amber-700">not set</span>}</dd>
</React.Fragment>
))}
</dl>
<p className="mt-2 text-xs text-slate-500">Change them in the files below. The site&apos;s address on the Hub ({product}) and in FastPanel doesn&apos;t change with them.</p>
</div>
)}
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={showAll} onChange={e => setShowAll(e.target.checked)} /> Also show variables the file doesn&apos;t have yet (from the release&apos;s template)</label>
{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 (
<form key={f.file} className="space-y-2" onSubmit={e => { e.preventDefault(); save(f.file); }}>
<div className="flex flex-wrap items-baseline justify-between gap-2">
<h3 className="font-mono text-sm font-medium">{f.file}{!f.exists && <span className="ml-2 font-sans text-xs text-amber-700">missing on the server</span>}</h3>
<span className="text-xs text-slate-500">{FILE_NOTE[f.file]}</span>
</div>
<div className="overflow-x-auto rounded-lg border">
<table className="w-full text-sm">
<thead><tr className="bg-slate-50 text-left text-xs text-slate-500"><th className="px-3 py-1.5">Name</th><th className="px-3 py-1.5">Value</th><th className="px-3 py-1.5"><span className="sr-only">Remove</span></th></tr></thead>
<tbody>
{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 (
<tr key={v.name} className={`border-t align-top ${isRemoved ? "opacity-50" : ""}`}>
<td className="px-3 py-1.5">
<div className="font-mono text-xs">{v.name}</div>
{(v.description || v.layer) && <div className="text-[11px] text-slate-400">{[v.layer, v.description].filter(Boolean).join(" · ")}</div>}
</td>
<td className="w-full px-3 py-1.5">
{v.secret ? (
<span className="text-xs text-slate-500">{v.set ? "•••••••• (secret, set)" : "secret, not set"}</span>
) : v.editable ? (
<input className={`input py-1 font-mono text-xs ${changed ? "border-indigo-400 bg-indigo-50" : ""}`} aria-label={v.name} value={value} disabled={isRemoved || !!pendingSet}
placeholder={v.set ? "" : "not set"}
onChange={e => {
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 };
});
}} />
) : (
<span className="font-mono text-xs text-slate-600">{v.value}<span className="ml-2 font-sans text-[11px] text-slate-400">made by the server</span></span>
)}
</td>
<td className="px-3 py-1.5 text-right">
{v.editable && v.set && (
<button type="button" className="text-xs text-slate-500 underline" disabled={!!pendingSet} onClick={() => setRemoved(r => {
const list = r[f.file] || [];
return { ...r, [f.file]: isRemoved ? list.filter(n => n !== v.name) : [...list, v.name] };
})}>{isRemoved ? "keep" : "remove"}</button>
)}
</td>
</tr>
);
})}
<tr className="border-t bg-slate-50/50">
<td className="px-3 py-1.5"><input className="input py-1 font-mono text-xs" aria-label={`New variable name in ${f.file}`} placeholder="NEW_NAME" value={a.name} disabled={!!pendingSet}
onChange={e => setAdded(x => ({ ...x, [f.file]: { ...a, name: e.target.value.toUpperCase() } }))} /></td>
<td className="px-3 py-1.5" colSpan={2}><input className="input py-1 font-mono text-xs" aria-label={`New variable value in ${f.file}`} placeholder="value" value={a.value} disabled={!!pendingSet}
onChange={e => setAdded(x => ({ ...x, [f.file]: { ...a, value: e.target.value } }))} /></td>
</tr>
</tbody>
</table>
</div>
<div className="flex flex-wrap items-center gap-3">
<button className="btn-primary" disabled={busy || !count || !!pendingSet}>{rebuild ? "Save, rebuild and restart" : restart ? "Save and restart" : "Save"}{count ? ` (${count})` : ""}</button>
{!rebuild && <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={restart} onChange={e => setRestart(e.target.checked)} /> Restart the backend to apply it</label>}
{!!count && <button type="button" className="text-sm text-slate-500 underline" onClick={() => { setEdits(x => ({ ...x, [f.file]: {} })); setRemoved(x => ({ ...x, [f.file]: [] })); setAdded(x => ({ ...x, [f.file]: { name: "", value: "" } })); }}>Undo my changes</button>}
</div>
</form>
);
})}
</>
)}
</div>
);
}