Hub 2.8.0: an install's .env on its page, changed with a restart

- Settings (.env) panel on an Events or Accounts install: reads the .env through an env-read job
  (addresses first; secrets only as set or not), and changes plain values with an env-set job
  (restart, or rebuild for the frontend's file; the server puts the file back if the site doesn't
  start). After a change the file is read again. One change per install at a time.
- Contracts 1.12.0 vendored (env jobs need agent 1.3.0).
- env-read / env-set in the Jobs type filter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 12:14:13 +02:00
co-authored by Claude Opus 5.5
parent 3fbe8708e8
commit 98db54aad2
13 changed files with 422 additions and 12 deletions
+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.