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
+3 -1
View File
@@ -97,6 +97,7 @@ crosscode: Cross Code installs on this server ($(git -C "${CROSSCODE_FROM:-.}" r
crosscode adopt <church> --undo go back to the old folder (within 14 days)
crosscode restart <church> [events] reload the PM2 processes
crosscode demo <church> --profile <profile> replace Events' data with a demo set
crosscode env <church> <product> [--set NAME=value] show or change a product's .env values
crosscode export <church> --out <file.zip> the church's data and uploads
crosscode uninstall <church> --confirm <church> remove it (a final backup is kept 30 days)
crosscode purge <church> --confirm <church> delete what uninstall kept
@@ -114,6 +115,7 @@ case "$command" in
adopt) cmd_adopt "$@" ;;
restart) cmd_restart "$@" ;;
demo) cmd_demo "$@" ;;
env) cmd_env "$@" ;;
export) cmd_export "$@" ;;
uninstall) cmd_uninstall "$@" ;;
purge) cmd_purge "$@" ;;
@@ -125,7 +127,7 @@ case "$command" in
install) install_usage ;;
add) add_usage ;;
adopt) adopt_usage ;;
restart|demo|export|uninstall|purge) manage_usage ;;
restart|demo|env|export|uninstall|purge) manage_usage ;;
*) usage ;;
esac ;;
*) usage; die "Unknown command \"$command\"." ;;
+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 };
+96
View File
@@ -10,6 +10,11 @@ crosscode demo <church> --profile <profile> [--admin-email <email>]
replace Cross Events' data with a demo set
(small, events, ministry, multicampus); a backup
is taken first, one admin account is kept
crosscode env <church> <product> the product's .env values (secrets hidden)
crosscode env <church> <product> [--file backend/.env] --set NAME=value … [--unset NAME …] [--restart]
change values (a copy is kept; never secrets or
generated values). The frontend's file rebuilds it.
If it doesn't start again, the file is put back.
crosscode export <church> --out <file.zip> the church's data (crosscode.church-export/1) and uploads
crosscode uninstall <church> --confirm <church>
final backup and uploads kept in
@@ -102,6 +107,97 @@ cmd_demo() {
die "Events didn't answer after the reload (sudo -u $user pm2 logs)."
}
# crosscode env <church> <product>: the product's .env values, secrets hidden (the Hub's env-read).
# With --set / --unset (the Hub's env-set): changes one file (--file, default backend/.env), keeping
# a copy first; when the frontend's file changed, the frontend is rebuilt (Next.js builds its values
# in); then, with --restart or after a rebuild, the product is reloaded and must answer /health.
# Anything failing after the change puts the file back (and rebuilds again if it had rebuilt).
ENV_BACKUPS_KEPT=5
cmd_env() {
local church="" product="" file="backend/.env" restart=0 dir user app tpl path backup stamp out rc=0 rebuilt=0
local -a changes=()
while [ $# -gt 0 ]; do
case "$1" in
--file) [ $# -ge 2 ] || die "--file needs a value."; file="$2"; shift 2 ;;
--set|--unset) [ $# -ge 2 ] || die "$1 needs a value."; changes+=("$1" "$2"); shift 2 ;;
--restart) restart=1; shift ;;
-h|--help) manage_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode help env)." ;;
*) if [ -z "$church" ]; then church="$1"; elif [ -z "$product" ]; then product="$1"; else die "Name one church and one product."; fi; shift ;;
esac
done
[ -n "$church" ] && [ -n "$product" ] || die "Name the church and the product (crosscode env hope events)."
[[ "$file" =~ ^(backend|frontend)/\.env(\.production)?$ ]] || die "--file: backend/.env or frontend/.env.production."
require_root
load_church "$church"
church_has_product "$product" || die "$church has no $product."
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/$product.sh"
dir="$(pvar "$product" DIR)"
user="$(pvar "$product" USER)"
app="$("${product}_app" "$dir")"
tpl="$(env_template "$app" "$product")"
if [ "${#changes[@]}" -eq 0 ]; then
step "$product: reading its .env files"
out="$(node "$CROSSCODE_HOME/lib/envedit.cjs" read --template "$tpl" --dir "$app" --product "$product")" || die "Couldn't read $product's .env files."
report_result_json env "$out"
# shellcheck disable=SC2016 # JavaScript template strings, not shell
[ "$CROSSCODE_JSON" = 1 ] || printf '%s\n' "$out" | node -e '
const r = JSON.parse(require("fs").readFileSync(0, "utf8"));
for (const f of r.files) {
console.log(`${f.file}${f.exists ? "" : " (missing)"}`);
for (const v of f.variables) console.log(` ${v.name}=${v.secret ? (v.set ? "(secret, set)" : "(secret, not set)") : (v.set ? v.value : "(not set)")}`);
}' >&2
return 0
fi
path="$app/$file"
[ -f "$path" ] || die "$church has no $product $file."
stamp="$(date -u +%Y%m%d%H%M%S)"
backup="$path.before-$stamp"
step "$product: changing $file (a copy is kept as $(basename "$backup"))"
out="$(node "$CROSSCODE_HOME/lib/envedit.cjs" set --template "$tpl" --dir "$app" --file "$file" --backup "$backup" "${changes[@]}")" || {
rm -f "$backup"
die "$product $file wasn't changed (see the message above)."
}
report_result_json changes "$out"
info "$out"
# Only the last few copies.
# shellcheck disable=SC2012 # names are ours: <file>.before-<digits>
ls -1t "$path".before-* 2>/dev/null | tail -n +$((ENV_BACKUPS_KEPT + 1)) | while read -r old; do rm -f -- "$old"; done
if [[ "$file" == frontend/* ]]; then
step "$product: rebuilding the frontend (it builds $file in)"
if run_as "$user" "$app/frontend" npm run build; then rebuilt=1; else rc=1; fi
fi
if [ "$rc" = 0 ] && { [ "$restart" = 1 ] || [ "$rebuilt" = 1 ]; }; then
step "$product: reloading PM2"
"${product}_reload" "$dir" "$user" || rc=1
if [ "$rc" = 0 ]; then
step "$product: waiting for it to answer"
wait_for_version "$("${product}_health_url")" "$("${product}_expected_version" "$dir")" 90 || rc=1
fi
fi
[ "$rc" = 0 ] && return 0
report_step_outcome failed
step "$product: putting $file back"
node "$CROSSCODE_HOME/lib/envedit.cjs" restore --file "$path" --backup "$backup" || die "Couldn't put $file back: the copy is $backup."
if [[ "$file" == frontend/* ]]; then
step "$product: rebuilding the frontend as it was"
run_as "$user" "$app/frontend" npm run build || die "The frontend didn't build again with the old $file: run npm run build in $app/frontend."
fi
if [ "$restart" = 1 ] || [[ "$file" == frontend/* ]]; then
step "$product: reloading PM2"
"${product}_reload" "$dir" "$user" || warn "PM2 reload failed: check pm2 status as $user."
wait_for_version "$("${product}_health_url")" "$("${product}_expected_version" "$dir")" 90 || true
fi
report_status rolled-back
die "$product didn't start with the new values, so $file was put back as it was."
}
cmd_export() {
local church="" out="" p tmp dir user bytes
while [ $# -gt 0 ]; do
+2 -2
View File
@@ -4,8 +4,8 @@
# The agent reads the object, adds the log lines and sends it to the Hub.
#
# What goes in: each step() as a step (the next step, or the end, closes it), report_result
# key/values, report_status (rolled-back), and the last die() message. Only names and outcomes:
# never values from .env files.
# key/values, report_status (rolled-back), and the last die() message. Only names and outcomes,
# never values from .env files (except `crosscode env`, the Hub's env-read: non-secret values only).
REPORT_FILE=""
REPORT_COMMAND=""
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env bats
# Reading and changing .env values for the Hub (lib/envedit.cjs, `crosscode env`, contracts 1.12.0):
# secrets are never printed, edits keep the rest of the file, secrets and generated values are refused.
setup() {
TMP="$BATS_TEST_TMPDIR"
JS="$BATS_TEST_DIRNAME/../lib/envedit.cjs"
APP="$TMP/app"
mkdir -p "$APP/backend" "$APP/frontend"
cat > "$TMP/template.json" <<'EOF'
{ "schema": "crosscode.env-template/1", "product": "events", "files": {
"backend/.env": [
{ "name": "NODE_ENV", "layer": "generated", "required": true },
{ "name": "DATABASE_URL", "layer": "generated", "required": true },
{ "name": "JWT_SECRET", "layer": "generated", "required": true },
{ "name": "FRONTEND_URL", "layer": "install", "from": "https://{domain}", "required": true, "description": "The site's address" },
{ "name": "TRUST_PROXY", "layer": "server", "required": true },
{ "name": "SENTRY_DSN", "layer": "defaults" }
],
"frontend/.env.production": [
{ "name": "NEXT_PUBLIC_API_URL", "layer": "install", "from": "https://{domain}", "required": true }
] } }
EOF
cat > "$APP/backend/.env" <<'EOF'
# Written by crosscode
NODE_ENV=production
DATABASE_URL=postgresql://hope:s3cr3t@localhost:5432/hope
JWT_SECRET=abcdef123456
FRONTEND_URL=https://events.hope.co.za
TRUST_PROXY=loopback
SMTP_PASS="pa ss"
ORG_NAME="Hope Church"
EOF
chmod 640 "$APP/backend/.env"
printf 'NEXT_PUBLIC_API_URL=https://events.hope.co.za\n' > "$APP/frontend/.env.production"
}
edit() { node "$JS" "$@" --template "$TMP/template.json" --dir "$APP"; }
@test "read: values in file order, secrets only as set or not, template values the file lacks" {
run edit read --product events
[ "$status" -eq 0 ]
[[ "$output" != *"s3cr3t"* && "$output" != *"abcdef"* && "$output" != *"pa ss"* ]]
node -e '
const r = JSON.parse(process.argv[1]);
const be = r.files.find(f => f.file === "backend/.env");
const v = Object.fromEntries(be.variables.map(x => [x.name, x]));
const ok = r.product === "events" && be.exists
&& v.FRONTEND_URL.value === "https://events.hope.co.za" && v.FRONTEND_URL.editable && v.FRONTEND_URL.description === "The site'"'"'s address"
&& v.ORG_NAME.value === "Hope Church" && v.ORG_NAME.layer === null && v.ORG_NAME.editable
&& v.DATABASE_URL.value === null && v.DATABASE_URL.secret && v.DATABASE_URL.set && !v.DATABASE_URL.editable
&& v.SMTP_PASS.value === null && v.SMTP_PASS.secret
&& v.NODE_ENV.value === "production" && !v.NODE_ENV.editable
&& v.SENTRY_DSN.set === false && v.SENTRY_DSN.secret
&& r.files.find(f => f.file === "frontend/.env.production").variables[0].value === "https://events.hope.co.za";
process.exit(ok ? 0 : 1);' "$output"
}
@test "set: changes lines where they are, appends new ones, removes, keeps the mode and a copy" {
run edit set --file backend/.env --backup "$TMP/copy" --set FRONTEND_URL=https://new.hope.co.za --set ORG_NAME="Hope & Co" --set NEW_FLAG=false --unset TRUST_PROXY
[ "$status" -eq 0 ]
[[ "$output" == *'"changed":["FRONTEND_URL","ORG_NAME"]'* && "$output" == *'"added":["NEW_FLAG"]'* && "$output" == *'"removed":["TRUST_PROXY"]'* ]]
[ "$(sed -n 5p "$APP/backend/.env")" = "FRONTEND_URL=https://new.hope.co.za" ]
grep -qx 'ORG_NAME="Hope & Co"' "$APP/backend/.env"
grep -qx 'NEW_FLAG=false' "$APP/backend/.env"
! grep -q '^TRUST_PROXY=' "$APP/backend/.env"
grep -qx 'JWT_SECRET=abcdef123456' "$APP/backend/.env"
[ "$(uname -s)" != Linux ] || [ "$(stat -c %a "$APP/backend/.env")" = 640 ]
grep -qx 'FRONTEND_URL=https://events.hope.co.za' "$TMP/copy"
}
@test "set: refuses secrets, generated values and bad values, changing nothing" {
cp "$APP/backend/.env" "$TMP/before"
run edit set --file backend/.env --set JWT_SECRET=x
[ "$status" -eq 3 ]
run edit set --file backend/.env --set NODE_ENV=development
[ "$status" -eq 3 ]
run edit set --file backend/.env --unset SMTP_PASS
[ "$status" -eq 3 ]
run edit set --file backend/.env --set TRUST_PROXY=TRUE
[ "$status" -eq 4 ]
run edit set --file ../.env --set A=1
[ "$status" -eq 2 ]
cmp "$TMP/before" "$APP/backend/.env"
}
@test "restore: puts the copy back" {
edit set --file backend/.env --backup "$TMP/copy" --set FRONTEND_URL=https://new.hope.co.za
node "$JS" restore --file "$APP/backend/.env" --backup "$TMP/copy"
grep -qx 'FRONTEND_URL=https://events.hope.co.za' "$APP/backend/.env"
}