Events 3.4.0, Accounts 1.4.0, contracts 1.12.0, agent 1.3.0: jobs from the dashboard, styled Accounts emails, .env from the Hub

- Events and Accounts: Background jobs are switched on or off and rescheduled from the admin;
  the choice is kept in the database (job_overrides), wins over the .env and applies at once.
  Accounts gets an Admin -> Background jobs page and per-job env flags, as Events.
- Accounts: every email styled as Cross Events' (church colour, logo, button, footer), same
  plain text (src/lib/emails.ts).
- Contracts 1.12.0: env-read / env-set agent jobs, envReadResultSchema, isSecretEnvName.
- crosscode script: `crosscode env <church> <product>` reads the .env (secrets hidden) and, with
  --set/--unset/--restart, changes one file, rebuilds the frontend when its file changed, reloads,
  and puts the file back if the site doesn't answer (lib/envedit.cjs, tests/envedit.bats).
- Agent 1.3.0: runs env-read and env-set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 12:14:02 +02:00
co-authored by Claude Opus 5.5
parent a85347bff8
commit bbcafe61b9
43 changed files with 2276 additions and 131 deletions
+203
View File
@@ -0,0 +1,203 @@
#!/usr/bin/env node
// Reads and changes a product's .env files for `crosscode env` (the Hub's env-read and env-set
// jobs, contracts 1.12.0).
//
// node envedit.cjs read --template <file> --dir <product dir> --product <product>
// prints a crosscode env-read result (JSON) on stdout. Secrets are never printed: only
// whether they're set.
// node envedit.cjs set --template <file> --dir <product dir> --file <backend/.env>
// [--set NAME=value …] [--unset NAME …] --backup <file>
// changes the file in place (owner and mode kept), after copying it to --backup. Refuses
// secrets and the values the server generates (exit 3), and values the app can't start with
// (exit 4). Prints the names it changed, never values.
// node envedit.cjs restore --file <file> --backup <file>
// puts the copy back.
'use strict';
const fs = require('fs');
const path = require('path');
const { checkValue, keysIn, line } = require('./envtpl.cjs');
// Keep in step with SECRET_ENV_NAME in packages/contracts/src/agent.ts.
const SECRET_NAME = /(SECRET|PASS|TOKEN|PRIVATE|CREDENTIAL|_KEY$|_DSN$|DATABASE_URL|ADMIN_URL)/;
const NAME = /^[A-Z][A-Z0-9_]*$/;
const FILE = /^(backend|frontend)\/\.env(\.production)?$/;
function parseArgs(argv) {
const out = { command: argv[0], set: {}, unset: [] };
for (let i = 1; i < argv.length; i++) {
const a = argv[i];
const next = () => {
if (i + 1 >= argv.length) throw new Error(`${a} needs a value`);
return argv[++i];
};
if (a === '--template') out.template = next();
else if (a === '--dir') out.dir = next();
else if (a === '--product') out.product = next();
else if (a === '--file') out.file = next();
else if (a === '--backup') out.backup = next();
else if (a === '--set') {
const v = next();
const eq = v.indexOf('=');
if (eq < 1) throw new Error(`--set ${v.split('=')[0]}: expected NAME=value`);
out.set[v.slice(0, eq)] = v.slice(eq + 1);
} else if (a === '--unset') out.unset.push(next());
else throw new Error(`Unknown option ${a}`);
}
return out;
}
/** The template's variables by name (layer, description), and its file names. */
function templateInfo(file) {
if (!file || !fs.existsSync(file)) return { vars: new Map(), files: ['backend/.env', 'frontend/.env.production'] };
const t = JSON.parse(fs.readFileSync(file, 'utf8'));
const vars = new Map();
for (const list of Object.values(t.files || {})) for (const v of list) vars.set(v.name, v);
return { vars, files: Object.keys(t.files || {}) };
}
/** A .env file's variables in order: [{ name, value }] (the last one wins, as dotenv). */
function parse(text) {
const order = [];
const values = new Map();
for (const raw of text.split(/\r?\n/)) {
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s?(.*)$/.exec(raw);
if (!m) continue;
let v = m[2].replace(/\s+$/, '');
const dq = /^"(.*)"$/.exec(v);
const sq = /^'(.*)'$/.exec(v);
if (dq) v = dq[1].replace(/\\"/g, '"').replace(/\\\\/g, '\\');
else if (sq) v = sq[1];
else v = v.replace(/\s+#.*$/, '');
if (!values.has(m[1])) order.push(m[1]);
values.set(m[1], v);
}
return order.map(name => ({ name, value: values.get(name) }));
}
const isSecret = (name, tv) => SECRET_NAME.test(name) || tv?.layer === 'generated' && name !== 'NODE_ENV';
const editable = (name, tv) => !SECRET_NAME.test(name) && tv?.layer !== 'generated';
function read(opts) {
const { vars, files } = templateInfo(opts.template);
const out = [];
for (const rel of files.filter(f => FILE.test(f))) {
const file = path.join(opts.dir, rel);
const exists = fs.existsSync(file);
const found = exists ? parse(fs.readFileSync(file, 'utf8')) : [];
const variables = found.map(({ name, value }) => {
const tv = vars.get(name);
const secret = isSecret(name, tv);
return {
name, value: secret ? null : value.slice(0, 4000), secret, set: value !== '',
layer: tv?.layer ?? null, description: tv?.description?.slice(0, 400) ?? null, editable: editable(name, tv),
};
});
// What the template has that the file doesn't (so the Hub can offer to add it).
for (const [name, tv] of vars) {
if (found.some(f => f.name === name) || !(templateFileOf(opts.template, name) === rel)) continue;
variables.push({ name, value: null, secret: isSecret(name, tv), set: false, layer: tv.layer, description: tv.description?.slice(0, 400) ?? null, editable: editable(name, tv) });
}
out.push({ file: rel, exists, variables: variables.slice(0, 300) });
}
return { product: opts.product, files: out, readAt: new Date().toISOString() };
}
function templateFileOf(template, name) {
if (!template || !fs.existsSync(template)) return null;
const t = JSON.parse(fs.readFileSync(template, 'utf8'));
for (const [rel, list] of Object.entries(t.files || {})) if (list.some(v => v.name === name)) return rel;
return null;
}
class Refused extends Error {
constructor(message, code) { super(message); this.code = code; }
}
/** The new file text: changed lines replaced where they are, new ones appended, removed ones dropped. */
function edit(text, set, unset, stamp) {
const done = new Set();
const lines = text.split(/\r?\n/);
if (lines.length && lines[lines.length - 1] === '') lines.pop();
const out = [];
for (const raw of lines) {
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(raw);
if (m && unset.includes(m[1])) continue;
if (m && Object.prototype.hasOwnProperty.call(set, m[1])) {
if (done.has(m[1])) continue; // a duplicate: one line is enough
out.push(line(m[1], set[m[1]]));
done.add(m[1]);
continue;
}
out.push(raw);
}
const added = Object.keys(set).filter(n => !done.has(n));
if (added.length) out.push('', `# Added from the Hub ${stamp}`, ...added.map(n => line(n, set[n])));
return `${out.join('\n')}\n`;
}
function set(opts) {
if (!FILE.test(opts.file || '')) throw new Refused(`--file: expected backend/.env or frontend/.env.production`, 2);
const { vars } = templateInfo(opts.template);
const names = [...Object.keys(opts.set), ...opts.unset];
if (!names.length) throw new Refused('Nothing to change.', 2);
for (const n of names) {
if (!NAME.test(n)) throw new Refused(`${n} isn't an env variable name.`, 2);
if (!editable(n, vars.get(n))) throw new Refused(`${n} ${SECRET_NAME.test(n) ? 'is a secret' : 'is made by the server'}: it can't be changed from the Hub.`, 3);
}
const problems = Object.entries(opts.set).map(([n, v]) => {
if (/[\r\n]/.test(v)) return `${n}: values can't contain newlines`;
return checkValue(n, v);
}).filter(Boolean);
if (problems.length) throw new Refused(problems.join('; '), 4);
const file = path.join(opts.dir, opts.file);
if (!fs.existsSync(file)) throw new Refused(`${opts.file} doesn't exist.`, 2);
const before = fs.readFileSync(file, 'utf8');
const st = fs.statSync(file);
if (opts.backup) fs.copyFileSync(file, opts.backup);
const text = edit(before, opts.set, opts.unset, new Date().toISOString().slice(0, 10));
const tmp = `${file}.crosscode-${process.pid}`;
fs.writeFileSync(tmp, text, { mode: 0o600 });
try { fs.chownSync(tmp, st.uid, st.gid); } catch { /* not root: same owner anyway */ }
fs.chmodSync(tmp, st.mode & 0o777);
fs.renameSync(tmp, file);
const had = keysIn(before);
return {
changed: Object.keys(opts.set).filter(n => had.has(n)),
added: Object.keys(opts.set).filter(n => !had.has(n)),
removed: opts.unset.filter(n => had.has(n)),
};
}
function restore(opts) {
if (!opts.file || !opts.backup || !fs.existsSync(opts.backup)) throw new Refused('restore needs --file and an existing --backup', 2);
const st = fs.statSync(opts.file);
fs.copyFileSync(opts.backup, opts.file);
try { fs.chownSync(opts.file, st.uid, st.gid); } catch { /* not root */ }
fs.chmodSync(opts.file, st.mode & 0o777);
}
function main() {
let opts;
try {
opts = parseArgs(process.argv.slice(2));
if (opts.command === 'read') {
if (!opts.dir || !opts.product) throw new Refused('read needs --dir and --product', 2);
process.stdout.write(`${JSON.stringify(read(opts))}\n`);
} else if (opts.command === 'set') {
if (!opts.dir) throw new Refused('set needs --dir', 2);
const r = set(opts);
process.stdout.write(`${JSON.stringify(r)}\n`);
} else if (opts.command === 'restore') {
restore(opts);
} else throw new Refused('Expected read, set or restore', 2);
} catch (e) {
console.error(`envedit: ${e.message}`);
process.exit(e instanceof Refused ? e.code : 1);
}
}
if (require.main === module) main();
module.exports = { parse, read, set, edit, restore, SECRET_NAME };