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
@@ -31,4 +31,22 @@ const runJobNow = async (req, res) => {
}
};
module.exports = { listJobs, runJobNow };
// @desc Switch a background job on or off, or change its schedule (3.4.0). Wins over the .env;
// null for either goes back to the .env.
// @route PUT /api/admin/jobs/:name
// @access Private/Admin
const updateJob = async (req, res) => {
try {
const body = req.body || {};
const choice = await jobs.setOverride(req.params.name, { enabled: body.enabled, cron: body.cron });
logAdminAction({
actorId: req.user.id, actorRole: req.user.role, action: 'job_settings_changed',
targetType: 'Job', targetId: req.params.name, metadata: { enabled: body.enabled, cron: body.cron }, ip: getClientIp(req),
});
res.json({ name: req.params.name, override: choice });
} catch (error) {
res.status(error.statusCode || 500).json({ message: safeErrorMessage(error) });
}
};
module.exports = { listJobs, runJobNow, updateJob };
+161 -45
View File
@@ -10,7 +10,10 @@
*
* Each job can be switched off with its env flag (e.g. WAITLIST_JOB_ENABLED=false), and
* its schedule changed with JOB_SCHEDULE_<NAME> (cron, e.g. JOB_SCHEDULE_WAITLIST="*\/5 * * * *").
* JOBS_ENABLED=false turns all of them off (used by the end-to-end tests).
* 3.4.0: an admin can do both on the Background jobs page; their choice is kept in the database
* (AppSetting job_overrides), wins over the .env and takes effect straight away (other processes
* within 30 seconds).
* JOBS_ENABLED=false still turns all of them off (used by the end-to-end tests).
* If the queue can't start (e.g. the database user can't create the pgboss schema), the
* same jobs run on in-process timers instead, as before.
*/
@@ -117,13 +120,69 @@ const flag = (name, def = true) => {
return v === undefined || v === '' ? def : String(v).toLowerCase() !== 'false';
};
/** Whether a job is switched on (JOBS_ENABLED and its own flag). */
function isEnabled(job) {
return flag('JOBS_ENABLED') && (!job.env || flag(job.env));
// ─── The admin's choices (3.4.0) ──────────────────────────────────────────────
const OVERRIDES_KEY = 'job_overrides';
const OVERRIDES_TTL_MS = 30 * 1000;
/** { [job name]: { enabled?: boolean, cron?: string } } from the database, cached here. */
let overrides = {};
let overridesAt = 0;
/** Reads the admin's choices again when the copy here is older than 30 s (or with `force`). */
async function loadOverrides(force = false) {
if (!force && overridesAt && Date.now() - overridesAt < OVERRIDES_TTL_MS) return overrides;
try {
const prisma = require('../config/db');
const row = await prisma.appSetting.findUnique({ where: { key: OVERRIDES_KEY } });
const parsed = row?.value ? JSON.parse(row.value) : {};
overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
overridesAt = Date.now();
} catch (e) {
// Keep the last copy (or none): the .env still applies.
if (force) console.warn('[jobs] Could not read the job overrides:', e?.message || e);
}
return overrides;
}
/** A job's cron schedule, with any JOB_SCHEDULE_<NAME> override (checked). */
/** Sets the cached choices (tests, and after saving). */
function setOverridesForTest(value) {
overrides = value || {};
overridesAt = Date.now();
}
/** A cron expression with five fields that cron-parser understands. */
function isCron(cron) {
if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false;
try {
CronExpressionParser.parse(cron, { tz: TIMEZONE });
return true;
} catch {
return false;
}
}
/** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */
function envEnabled(job) {
return !job.env || flag(job.env);
}
/** Whether a job is switched on: JOBS_ENABLED=false turns all off; then the admin's choice; then its env flag. */
function isEnabled(job) {
if (!flag('JOBS_ENABLED')) return false;
const o = overrides[job.name];
if (o && typeof o.enabled === 'boolean') return o.enabled;
return envEnabled(job);
}
/** A job's cron schedule: the admin's choice, else JOB_SCHEDULE_<NAME>, else its default. */
function cronFor(job) {
const o = overrides[job.name];
if (o && isCron(o.cron)) return o.cron;
return envCronFor(job);
}
/** A job's cron schedule from the .env (JOB_SCHEDULE_<NAME>, checked), else its default. */
function envCronFor(job) {
const override = process.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`];
if (override) {
try {
@@ -208,31 +267,75 @@ const timers = new Map();
// Timer mode keeps its own short history so the admin page still has something to show.
const timerHistory = new Map();
/** One job on an in-process timer while it's on. The schedule and the switch are read each time. */
function startTimer(job) {
const scheduleNext = () => {
if (!isEnabled(job)) { timers.delete(job.name); return; }
const delay = Math.max(1000, nextRun(cronFor(job)).getTime() - Date.now());
timers.set(job.name, setTimeout(async () => {
await loadOverrides();
if (!isEnabled(job)) { timers.delete(job.name); return; }
const entry = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(job);
entry.state = 'completed';
} catch (e) {
entry.state = 'failed';
entry.output = { message: e?.message || String(e) };
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
} finally {
entry.completedOn = new Date();
timerHistory.set(job.name, [entry, ...(timerHistory.get(job.name) || [])].slice(0, 10));
scheduleNext();
}
}, Math.min(delay, 2 ** 31 - 1)));
};
scheduleNext();
}
function startTimers(jobs) {
mode = 'timers';
for (const job of jobs) {
const cron = cronFor(job);
const scheduleNext = () => {
const delay = Math.max(1000, nextRun(cron).getTime() - Date.now());
timers.set(job.name, setTimeout(async () => {
const entry = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(job);
entry.state = 'completed';
} catch (e) {
entry.state = 'failed';
entry.output = { message: e?.message || String(e) };
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
} finally {
entry.completedOn = new Date();
timerHistory.set(job.name, [entry, ...(timerHistory.get(job.name) || [])].slice(0, 10));
scheduleNext();
}
}, Math.min(delay, 2 ** 31 - 1)));
};
scheduleNext();
for (const job of jobs) startTimer(job);
console.log(`[jobs] Running ${jobs.filter(isEnabled).length} job(s) on in-process timers.`);
}
/** Puts one job's schedule in line with its switch and schedule now (queue or timers). */
async function applyJob(job) {
if (mode === 'queue' && boss) {
if (isEnabled(job)) await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE });
else await boss.unschedule(job.name).catch(() => {});
} else if (mode === 'timers') {
clearTimeout(timers.get(job.name));
timers.delete(job.name);
startTimer(job);
}
console.log(`[jobs] Running ${jobs.length} job(s) on in-process timers.`);
}
const badRequest = (message) => Object.assign(new Error(message), { statusCode: 400 });
/**
* Saves an admin's choice for one job and applies it straight away. `enabled` / `cron`: a value
* wins over the .env; null goes back to the .env; undefined leaves it as it is.
* @returns the job's choices now ({ enabled, cron }, null where the .env applies)
*/
async function setOverride(name, { enabled, cron } = {}) {
const job = JOBS.find(j => j.name === name);
if (!job) throw Object.assign(new Error('Unknown job'), { statusCode: 404 });
if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw badRequest('"enabled" must be true, false or null.');
if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim()))) {
throw badRequest('That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".');
}
const prisma = require('../config/db');
const all = { ...(await loadOverrides(true)) };
const entry = { ...(all[name] || {}) };
if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled; }
if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = cron.trim(); }
if (Object.keys(entry).length) all[name] = entry; else delete all[name];
const value = JSON.stringify(all);
await prisma.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } });
setOverridesForTest(all);
await applyJob(job);
return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null };
}
/**
@@ -240,12 +343,13 @@ function startTimers(jobs) {
* @returns {Promise<'queue'|'timers'|'off'>}
*/
async function startJobs() {
const enabled = JOBS.filter(isEnabled);
if (!flag('JOBS_ENABLED')) {
console.log('[jobs] All background jobs disabled by env JOBS_ENABLED=false');
mode = 'off';
return mode;
}
await loadOverrides(true);
const enabled = JOBS.filter(isEnabled);
try {
const PgBoss = require('pg-boss');
boss = new PgBoss({ connectionString: process.env.DATABASE_URL, schema: SCHEMA, application_name: 'hope-events-jobs' });
@@ -257,19 +361,21 @@ async function startJobs() {
// stately: at most one waiting and one running, so a slow run never piles up.
await boss.createQueue(job.name, { policy: 'stately', retryLimit: 2, retryDelay: 60, expireInSeconds: 60 * 60 });
}
if (isEnabled(job)) {
await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE });
await boss.work(job.name, async () => {
try {
return await runJob(job);
} catch (e) {
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
throw e; // recorded as failed, and retried
}
});
} else {
await boss.unschedule(job.name).catch(() => {});
}
// 3.4.0: every job has a worker (an admin can switch one on later); only those on are scheduled.
await boss.work(job.name, async (batch) => {
const list = Array.isArray(batch) ? batch : [batch];
await loadOverrides();
// Switched off (perhaps in another process) after this run was scheduled: skip it. "Run now" still runs.
if (!isEnabled(job) && !list.some(j => j?.data?.manual)) return { skipped: 'switched off' };
try {
return await runJob(job);
} catch (e) {
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
throw e; // recorded as failed, and retried
}
});
if (isEnabled(job)) await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE });
else await boss.unschedule(job.name).catch(() => {});
}
// One-off tasks: any number can wait and run (unlike the stately scheduled jobs).
for (const name of Object.keys(TASKS)) {
@@ -295,7 +401,7 @@ async function startJobs() {
console.warn('[jobs] Job queue unavailable, falling back to timers:', e?.message || e);
if (boss) { try { await boss.stop({ graceful: false }); } catch { /* ignore */ } }
boss = null;
startTimers(enabled);
startTimers(JOBS);
}
return mode;
}
@@ -318,8 +424,9 @@ async function runNow(name) {
err.statusCode = 404;
throw err;
}
if (mode === 'queue' && isEnabled(job)) {
const id = await boss.send(job.name, null, { singletonKey: `${job.name}-manual` });
if (mode === 'queue' && boss) {
// Marked manual so it runs even when the job is switched off.
const id = await boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` });
return { queued: true, id };
}
const output = await runJob(job);
@@ -330,6 +437,7 @@ async function runNow(name) {
/** Each job with its schedule, next run and recent runs, for the admin page. */
async function jobStatus(prisma) {
await loadOverrides(true);
const recent = new Map();
if (mode === 'queue') {
// pg-boss columns are timestamptz, and Prisma's pg adapter drops their offset in raw queries
@@ -356,11 +464,16 @@ async function jobStatus(prisma) {
return {
mode,
timezone: TIMEZONE,
jobsEnabledEnv: flag('JOBS_ENABLED'),
jobs: JOBS.map(job => {
const cron = cronFor(job);
const enabled = isEnabled(job);
const o = overrides[job.name] || {};
return {
name: job.name, label: job.label, cron, enabled, envFlag: job.env,
// 3.4.0: what the .env says, and the admin's choice over it (null: the .env applies).
envEnabled: envEnabled(job), envCron: envCronFor(job), defaultCron: job.cron,
override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron) ? o.cron : null },
nextRun: enabled && mode !== 'off' ? nextRun(cron) : null,
recent: recent.get(job.name) || [],
};
@@ -368,4 +481,7 @@ async function jobStatus(prisma) {
};
}
module.exports = { JOBS, TASKS, TIMEZONE, isEnabled, cronFor, nextRun, isNoop, startJobs, stopJobs, runNow, jobStatus, enqueueTask };
module.exports = {
JOBS, TASKS, TIMEZONE, isEnabled, envEnabled, cronFor, isCron, nextRun, isNoop, startJobs, stopJobs, runNow, jobStatus, enqueueTask,
setOverride, loadOverrides, setOverridesForTest,
};
@@ -100,7 +100,8 @@ v1Route({ method: 'put', path: '/privacy/breaches/:id', tag: 'Privacy', summary:
// ─── Admin ───────────────────────────────────────────────────────────────────
v1Route({ method: 'get', path: '/admin/audit-log', tag: 'Admin', summary: 'The audit log', access: 'admin', query: filters('page', 'limit', 'actorId', 'action', 'role', 'from', 'to', 'search'), documented: { response: D.obj({ rows: z.array(D.auditEntry), total: D.num, page: D.num, limit: D.num }) }, v1: audit.listAuditLog });
v1Route({ method: 'get', path: '/admin/jobs', tag: 'Admin', summary: 'Background jobs', access: 'admin', documented: { response: D.obj({ mode: D.str.describe('on, off or timers'), timezone: D.str, jobs: z.array(D.obj({ name: D.str, label: D.str, cron: D.optStr, enabled: D.bool, envFlag: D.optStr, nextRun: D.optDate, recent: z.array(D.anyObj).describe('Recent runs') })) }) }, v1: jobs.listJobs });
v1Route({ method: 'get', path: '/admin/jobs', tag: 'Admin', summary: 'Background jobs', access: 'admin', documented: { response: D.obj({ mode: D.str.describe('queue, timers or off'), timezone: D.str, jobsEnabledEnv: D.bool.describe('JOBS_ENABLED in the .env'), jobs: z.array(D.obj({ name: D.str, label: D.str, cron: D.optStr, enabled: D.bool, envFlag: D.optStr, envEnabled: D.bool.describe('What the .env says'), envCron: D.str, defaultCron: D.str, override: D.obj({ enabled: z.boolean().nullable(), cron: D.optStr }).describe('What an admin chose over the .env (null: the .env applies)'), nextRun: D.optDate, recent: z.array(D.anyObj).describe('Recent runs') })) }) }, v1: jobs.listJobs });
v1Route({ method: 'put', path: '/admin/jobs/:name', tag: 'Admin', summary: 'Switch a background job on or off, or change its schedule', access: 'admin', params: z.object({ name: z.string().min(1).max(100) }), body: z.object({ enabled: z.boolean().nullable().optional().describe('true or false wins over the .env; null goes back to it'), cron: z.string().max(100).nullable().optional().describe('A cron schedule (five fields) that wins over the .env; null or empty goes back to it') }), documented: { response: D.obj({ name: D.str, override: D.obj({ enabled: z.boolean().nullable(), cron: D.optStr }) }) }, v1: jobs.updateJob });
v1Route({ method: 'post', path: '/admin/jobs/:name/run', tag: 'Admin', summary: 'Run a background job now', access: 'admin', params: z.object({ name: z.string().min(1).max(100) }), body: loose, documented: { response: D.obj({ queued: D.bool, id: D.optStr, output: z.unknown().optional().describe('When it ran straight away') }) }, v1: jobs.runJobNow });
v1Route({ method: 'get', path: '/admin/impersonation-sessions', tag: 'Admin', summary: 'Times admins viewed the site as someone else', access: 'admin', query: filters('limit'), documented: { response: z.array(D.obj({ id: D.str, reason: D.optStr, startedAt: D.optDate, endedAt: D.optDate, expiresAt: D.optDate, admin: D.obj({ name: D.str, email: D.optStr }).nullish(), target: D.obj({ name: D.str, email: D.optStr }).nullish(), requests: z.array(D.obj({ method: D.str, path: D.str, blocked: D.bool, createdAt: D.date })).describe('What they did (up to 500)') })) }, v1: imp.listSessions });
v1Route({ method: 'post', path: '/admin/impersonate/:userId', tag: 'Admin', summary: 'View the site as someone (read-only)', description: 'Answers a token for a read-only session, logged.', access: 'admin', params: z.object({ userId: z.string().min(1).max(64) }), body: loose, documented: { body: D.obj({ reason: D.str.describe('Why — kept in the log') }), response: D.obj({ token: D.str.describe('A read-only sign-in token'), session: D.obj({ id: D.str, expiresAt: D.date, target: D.obj({ id: D.str, name: D.str, email: D.str, role: D.str }) }) }) }, v1: imp.startImpersonation });