Compare commits

...
Author SHA1 Message Date
joshua cacbb16895 Merge branch 'fix/accounts-link' 2026-11-20 12:56:39 +02:00
joshuaandClaude Opus 5.5 08b58ae310 Events 3.5.0, contracts 1.13.0, agent 1.3.1: demo data keeps the Accounts link; sign-in health for the Hub
- Events: loading demo data emptied ProductLink but kept auth_mode, so a site in Accounts mode had
  no link and nobody could sign in (ACCOUNTS_UNAVAILABLE on events-demo). set-demo.js keeps
  ProductLink and LinkNonce; a site in Accounts mode without a link reconnects at its next
  heartbeat; sign-in failures are kept and sent in the heartbeat (stats.signIn).
- Contracts 1.13.0: stats.signIn in the Cross Events heartbeat.
- Agent 1.3.1: 1.3.0 reported itself as 1.2.0 (AGENT_VERSION not bumped).
- What's New notes for Events 3.4.0 / 3.5.0 and Accounts 1.4.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:56:37 +02:00
joshua e32a3b6144 Merge branch 'feat/env-and-jobs' 2026-11-20 12:14:04 +02:00
joshuaandClaude Opus 5.5 bbcafe61b9 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>
2026-11-20 12:14:02 +02:00
55 changed files with 2521 additions and 136 deletions
+34
View File
@@ -2,6 +2,40 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## events@3.5.0, contracts@1.13.0, agent@1.3.1 - 2026-11-20
- **Agent 1.3.1:** agent 1.3.0 still reported itself as 1.2.0 (`AGENT_VERSION` in `src/stats.ts`
wasn't bumped with `package.json`), so the Hub refused `.env` jobs on it. Use 1.3.1.
Loading demo data left a site that signs in through Accounts with no Accounts link, so nobody could
sign in (`ACCOUNTS_UNAVAILABLE`, found on events-demo). The Hub (2.9.0) now sees it.
- **Contracts 1.13.0:** `stats.signIn` in the Cross Events heartbeat (mode, the linked Accounts,
the last sign-in failure; optional).
- **Events 3.5.0:** `set-demo.js` keeps `ProductLink` and `LinkNonce`; a site in Accounts mode
without a link reconnects at its next heartbeat even after an earlier auto-connect; sign-in
failures (start, finish, Accounts unreachable) are kept and sent to the Hub; What's New notes for
3.4.0 (and Accounts 1.4.0) that were missing.
## events@3.4.0, accounts@1.4.0, contracts@1.12.0, agent@1.3.0, crosscode script - 2026-11-20
Background jobs are switched on and off (and rescheduled) from each site's admin, over the .env;
Accounts' emails look like Cross Events'; the Hub shows and changes an install's .env (Hub 2.8.0).
- **Contracts 1.12.0:** `env-read` and `env-set` agent jobs, `envReadResultSchema`,
`isSecretEnvName` / `SECRET_ENV_NAME`, `ENV_JOBS_MIN_AGENT` (1.3.0). `env-set` refuses secrets,
newlines, files other than `backend/.env` / `frontend/.env.production`, and empty changes.
- **crosscode script:** `crosscode env <church> <product>` prints the product's .env values
(secrets only as set or not); with `--set NAME=value`, `--unset NAME` and `--restart` it changes
one file (a copy is kept, the last 5), rebuilds the frontend when its file changed, reloads, and
waits for `/health`; if that fails the file is put back (and rebuilt). Secrets and generated
values are refused (`lib/envedit.cjs`). Tests: `scripts/tests/envedit.bats`.
- **Agent 1.3.0:** runs `env-read` and `env-set` as `crosscode env`.
- **Events 3.4.0:** Settings → Background jobs switches each job on or off and changes its
schedule; the choice is kept in the database, wins over the .env and applies straight away.
- **Accounts 1.4.0:** Admin → Background jobs (the same as Events'); every email is styled as
Cross Events' (church colour and logo, a button, contact details), with the same plain text.
## events@3.3.0, accounts@1.3.0, contracts@1.11.0 - 2026-11-20
Accounts looks like Cross Events and backs itself up; fixes in Events' sign-out and branding uploads.
+23
View File
@@ -1,5 +1,28 @@
# Changelog — Accounts
## [1.4.0] - 2026-11-20
Works with every Cross Events 3.x and contracts 1.11.0 or later.
### Added
- **Admin → Background jobs**, as Cross Events': each job's schedule, next run and last runs,
"Run now", and a switch and schedule per job. The choice is saved in the database
(`job_overrides`), wins over the .env and applies straight away (other processes within 30 s).
New optional .env flags per job, as Events: `EXPORTS_JOB_ENABLED`, `DELETIONS_JOB_ENABLED`,
`BACKUP_ENABLED`, `HUB_HEARTBEAT_ENABLED`, and `JOB_SCHEDULE_<NAME>`. API: `GET /api/v2/admin/jobs`,
`PUT /api/v2/admin/jobs/:name` `{ enabled, cron }`, `POST /api/v2/admin/jobs/:name/run`.
On timers (when the queue can't start) jobs now follow their cron schedule too.
### Changed
- **Every email is styled as Cross Events'** (`src/lib/emails.ts`): a header in the church's
colour with its logo or name, a button for the link (written out underneath), callouts for
warnings, and the church's contact details in the footer. Sign-in codes, password reset, "your
account at …", confirm a new email address, "your email address changed", "your data is ready"
and the test emails. The plain text is sent too and hasn't changed. Everything put in the HTML is
escaped, and only http(s) links are used.
## [1.3.0] - 2026-11-20
Needs contracts 1.11.0 (`people.removeDemo`). Works with every Cross Events 3.x.
+9
View File
@@ -3,6 +3,15 @@
What each version changes for the church, in plain language (read by the Hub like Cross Events'
WHATS-NEW.md; a section shows once its version is tagged).
## 1.4.0
- **Better-looking emails.** Sign-in codes, password links, "your account is ready" and the other
emails from your church account now look like Cross Events' emails: your church's colour and logo
at the top, a clear button, and your church's contact details at the bottom.
- Admins: **Admin → Background jobs** shows what Accounts does on a schedule (backups, privacy
requests, tidying up), when it last ran, and lets you run a job now, switch it off or change when
it runs.
## 1.3.0
- Your account and the admin pages have a new look, like Cross Events: a menu down the side, and
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-backend",
"version": "1.3.0",
"version": "1.4.0",
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
"private": true,
"type": "module",
@@ -22,6 +22,7 @@
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
"cron-parser": "^5.10.2",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"express-rate-limit": "^8.6.2",
@@ -12,6 +12,7 @@ import { loginEvent } from '../lib/audit.js';
import { queueCall } from '../links/deliveries.js';
import { currentNoticeVersion } from '../privacy/notice.js';
import { SendError } from '../lib/messages.js';
import { codeEmail } from '../lib/emails.js';
export const MAX_FAILED_SIGN_INS = 10;
export const LOCK_MINUTES = 15;
@@ -122,7 +123,7 @@ export async function sendCode(ctx: Ctx, a: Account, method: 'email' | 'whatsapp
}
}
try {
await ctx.messenger.email({ to: a.email, subject: `Your code: ${code}`, text });
await ctx.messenger.email({ to: a.email, ...(await codeEmail(ctx, { name: a.name, code, text, purpose, minutes: CODE_MINUTES })) });
} catch (e) {
console.error('[codes] could not send a code:', (e as Error).message);
throw new SendError(`We couldn't send your code: ${churchName}'s email isn't working right now. Please let the church office know, and try again later.`, 'CODE_NOT_SENT');
+33 -1
View File
@@ -22,6 +22,8 @@ import { builtInNotice, currentNotice, publish } from '../privacy/notice.js';
import { licenceStatus } from '../hub/licence.js';
import { connect as connectHub } from '../hub/client.js';
import { productName } from '../oidc/clients.js';
import { JobError, jobStatus, runNow, setOverride } from '../jobs.js';
import { testEmail } from '../lib/emails.js';
const PAGE = 50;
@@ -200,7 +202,7 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
const me = await admin(req, res);
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
try {
await ctx.messenger.email({ to: a.email, subject: 'Test email from Accounts', text: 'Email from Accounts works.' });
await ctx.messenger.email({ to: a.email, ...(await testEmail(ctx)) });
} catch (e) {
throw new ApiError(502, 'NOT_SENT', `The test email couldn't be sent: ${(e as Error).message}`);
}
@@ -299,6 +301,36 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
}
});
// ─── Background jobs (1.4.0, as Cross Events) ───────────────────────────────
const jobError = (e: unknown): never => {
if (e instanceof JobError) throw new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : e.status === 400 ? 'VALIDATION' : 'JOB_FAILED', e.message);
throw e;
};
r.get('/jobs', handle(async (req, res) => {
await admin(req, res);
return jobStatus(ctx);
}));
// Switch a job on or off, or change its schedule: wins over the .env; null goes back to it.
r.put('/jobs/:name', handle(async (req, res) => {
const me = await admin(req, res);
const name = String(req.params.name);
const change = { enabled: req.body?.enabled, cron: req.body?.cron };
const override = await setOverride(ctx, name, change).catch(jobError);
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'job_settings_changed', targetType: 'job', targetId: name, metadata: change, ip: clientIp(req) });
return { name, override };
}));
r.post('/jobs/:name/run', limit(20, 60), handle(async (req, res) => {
const me = await admin(req, res);
const name = String(req.params.name);
const out = await runNow(ctx, name).catch(jobError);
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'job_run_manual', targetType: 'job', targetId: name, metadata: { queued: out.queued }, ip: clientIp(req) });
return out;
}));
// ─── Licence, audit ────────────────────────────────────────────────────────
r.get('/licence', handle(async (req, res) => {
@@ -9,6 +9,7 @@ import { decodeState, encodeState, safeReturnPath } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { ApiError, handle, limit } from '../http.js';
import { loginEvent } from '../lib/audit.js';
import { resetPasswordEmail } from '../lib/emails.js';
import { hashToken, randomToken } from '../lib/crypto.js';
import { hashPassword, passwordProblem } from '../lib/passwords.js';
import { normaliseEmail } from '../accounts/service.js';
@@ -97,11 +98,7 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
const token = randomToken();
const uid = typeof req.body?.uid === 'string' && /^[A-Za-z0-9_-]{10,64}$/.test(req.body.uid) ? req.body.uid : null;
await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), interactionUid: uid, expiresAt: new Date(ctx.now().getTime() + RESET_MINUTES * 60e3) } });
await ctx.messenger.email({
to: a.email,
subject: 'Reset your password',
text: `Someone (we hope you) asked to reset the password for your account.\n\nChoose a new password here (the link works for ${RESET_MINUTES} minutes):\n${ctx.config.publicUrl}/reset?token=${token}\n\nIf you didn't ask, you can ignore this email: your password stays the same.`,
});
await ctx.messenger.email({ to: a.email, ...(await resetPasswordEmail(ctx, { name: a.name, url: `${ctx.config.publicUrl}/reset?token=${token}`, minutes: RESET_MINUTES })) });
}
return { sent: true };
}));
+268 -24
View File
@@ -1,7 +1,13 @@
/**
* Background jobs on pg-boss (as Cross Events): one run per schedule however many processes run,
* and timers in this process if the queue can't start. JOBS_ENABLED=false turns them all off.
*
* 1.4.0 (as Events 3.4.0): Admin → Background jobs shows each job's schedule and last runs, runs
* one now, and switches one on or off or changes its schedule. That choice is kept in the
* database (`job_overrides`), wins over the .env (a job's own flag, e.g. BACKUP_ENABLED=false, and
* JOB_SCHEDULE_<NAME>) and takes effect straight away (in other processes within 30 seconds).
*/
import { CronExpressionParser } from 'cron-parser';
import PgBoss from 'pg-boss';
import type { Ctx } from './context.js';
import { runBackupJob } from './backups/backups.js';
@@ -12,17 +18,17 @@ import { deleteExpired } from './oidc/adapter.js';
import { runDeletionJob } from './privacy/deletion.js';
import { runExportsJob } from './privacy/export.js';
type Job = { name: string; cron: string; everyMs: number; run: (ctx: Ctx) => Promise<unknown> };
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
export const JOBS: Job[] = [
{ name: 'deliveries', cron: '* * * * *', everyMs: 60e3, run: (ctx) => runDue(ctx) },
{ name: 'exports', cron: '*/5 * * * *', everyMs: 5 * 60e3, run: (ctx) => runExportsJob(ctx) },
{ name: 'deletions', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => runDeletionJob(ctx) },
{ name: 'deliveries', label: 'Linked products: send what they need to know (sign-outs, changes), retrying failures', cron: '* * * * *', env: null, run: (ctx) => runDue(ctx) },
{ name: 'exports', label: 'Privacy: make the copies of their data people asked for', cron: '*/5 * * * *', env: 'EXPORTS_JOB_ENABLED', run: (ctx) => runExportsJob(ctx) },
{ name: 'deletions', label: 'Privacy: delete the accounts whose deletion is due', cron: '*/15 * * * *', env: 'DELETIONS_JOB_ENABLED', run: (ctx) => runDeletionJob(ctx) },
// 1.3.0: a database backup every night (Settings → Backups), as Cross Events.
{ name: 'backup', cron: '0 2 * * *', everyMs: 24 * 3600e3, run: (ctx) => runBackupJob(ctx) },
{ name: 'hub-heartbeat', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => heartbeat(ctx) },
{ name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runBackupJob(ctx) },
{ name: 'hub-heartbeat', label: 'Cross Code Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: (ctx) => heartbeat(ctx) },
{
name: 'cleanup', cron: '17 * * * *', everyMs: 3600e3,
name: 'cleanup', label: 'Delete expired sign-ins, codes and links', cron: '17 * * * *', env: null,
run: async (ctx) => {
const now = ctx.now();
const [oidc, pending, tokens, nonces, requests] = await Promise.all([
@@ -37,23 +43,261 @@ export const JOBS: Job[] = [
},
];
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
if (!ctx.config.jobsEnabled) return async () => {};
const tz = ctx.config.timezone;
const SCHEMA = 'pgboss_accounts';
const OVERRIDES_KEY = 'job_overrides';
const OVERRIDES_TTL_MS = 30_000;
export type Override = { enabled?: boolean; cron?: string };
type Run = { state: string; createdOn?: Date | null; startedOn: Date | null; completedOn: Date | null; output: unknown };
/** The running queue or timers, the admin's choices (cached), and a short history for timer mode. */
type State = {
mode: 'queue' | 'timers' | 'off';
boss: PgBoss | null;
timers: Map<string, NodeJS.Timeout>;
history: Map<string, Run[]>;
overrides: Record<string, Override>;
overridesAt: number;
env: NodeJS.ProcessEnv;
};
const state: State = { mode: 'off', boss: null, timers: new Map(), history: new Map(), overrides: {}, overridesAt: 0, env: process.env };
/** Tests: a different environment for the env flags and schedules. */
export function useEnvForTest(env: NodeJS.ProcessEnv): void {
state.env = env;
}
const flag = (name: string | null) => {
if (!name) return true;
const v = state.env[name];
return v === undefined || v === '' ? true : String(v).toLowerCase() !== 'false';
};
export function isCron(cron: unknown, tz = 'Africa/Johannesburg'): cron is string {
if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false;
try {
const boss = new PgBoss({ connectionString, schema: 'pgboss_accounts', application_name: 'crosscode-accounts-jobs' });
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
await boss.start();
for (const job of JOBS) {
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
await boss.schedule(job.name, job.cron, undefined, { tz });
await boss.work(job.name, async () => job.run(ctx));
}
console.log(`[jobs] Job queue started: ${JOBS.map((j) => j.name).join(', ')}.`);
return async () => { await boss.stop({ graceful: true }); };
} catch (e) {
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
const timers = JOBS.map((job) => setInterval(() => { job.run(ctx).catch((err) => console.warn(`[jobs] ${job.name}:`, (err as Error).message)); }, job.everyMs));
return async () => { timers.forEach(clearInterval); };
CronExpressionParser.parse(cron, { tz });
return true;
} catch {
return false;
}
}
export async function loadOverrides(ctx: Ctx, force = false): Promise<Record<string, Override>> {
if (!force && state.overridesAt && Date.now() - state.overridesAt < OVERRIDES_TTL_MS) return state.overrides;
try {
// Straight from the table: Settings caches for 30 s too, and a save must show at once here.
const row = await ctx.db.appSetting.findUnique({ where: { key: OVERRIDES_KEY } });
const parsed = row?.value ? JSON.parse(row.value) : {};
state.overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
state.overridesAt = Date.now();
} catch (e) {
if (force) console.warn('[jobs] Could not read the job overrides:', (e as Error).message);
}
return state.overrides;
}
/** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */
export const envEnabled = (job: Job) => flag(job.env);
/** JOBS_ENABLED=false turns all off; then the admin's choice; then the job's env flag. */
export function isEnabled(ctx: Ctx, job: Job): boolean {
if (!ctx.config.jobsEnabled) return false;
const o = state.overrides[job.name];
if (o && typeof o.enabled === 'boolean') return o.enabled;
return envEnabled(job);
}
/** The .env's schedule (JOB_SCHEDULE_<NAME>, checked) or the job's own. */
export function envCronFor(ctx: Ctx, job: Job): string {
const v = state.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`];
if (v && isCron(v, ctx.config.timezone)) return v;
if (v) console.warn(`[jobs] Ignoring invalid schedule for ${job.name}: "${v}"`);
return job.cron;
}
export function cronFor(ctx: Ctx, job: Job): string {
const o = state.overrides[job.name];
if (o && isCron(o.cron, ctx.config.timezone)) return o.cron;
return envCronFor(ctx, job);
}
export const nextRun = (cron: string, tz: string, from = new Date()) => CronExpressionParser.parse(cron, { tz, currentDate: from }).next().toDate();
function remember(name: string, run: Run) {
state.history.set(name, [run, ...(state.history.get(name) ?? [])].slice(0, 10));
}
async function runJob(ctx: Ctx, job: Job) {
return (await job.run(ctx)) ?? null;
}
function startTimer(ctx: Ctx, job: Job) {
const tz = ctx.config.timezone;
const scheduleNext = () => {
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
const delay = Math.max(1000, nextRun(cronFor(ctx, job), tz).getTime() - Date.now());
state.timers.set(job.name, setTimeout(async () => {
await loadOverrides(ctx);
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(ctx, job);
entry.state = 'completed';
} catch (e) {
entry.state = 'failed';
entry.output = { message: (e as Error).message };
console.warn(`[jobs] ${job.name}:`, (e as Error).message);
} finally {
entry.completedOn = new Date();
remember(job.name, entry);
scheduleNext();
}
}, Math.min(delay, 2 ** 31 - 1)));
};
scheduleNext();
}
async function applyJob(ctx: Ctx, job: Job) {
if (state.mode === 'queue' && state.boss) {
if (isEnabled(ctx, job)) await state.boss.schedule(job.name, cronFor(ctx, job), undefined, { tz: ctx.config.timezone });
else await state.boss.unschedule(job.name).catch(() => {});
} else if (state.mode === 'timers') {
clearTimeout(state.timers.get(job.name));
state.timers.delete(job.name);
startTimer(ctx, job);
}
}
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
if (!ctx.config.jobsEnabled) {
state.mode = 'off';
return async () => {};
}
await loadOverrides(ctx, true);
const tz = ctx.config.timezone;
try {
const boss = new PgBoss({ connectionString, schema: SCHEMA, application_name: 'crosscode-accounts-jobs' });
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
await boss.start();
state.boss = boss;
state.mode = 'queue';
for (const job of JOBS) {
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
// Every job has a worker (an admin can switch one on later); only those on are scheduled.
await boss.work(job.name, async (batch) => {
await loadOverrides(ctx);
const manual = (Array.isArray(batch) ? batch : [batch]).some((j) => (j as { data?: { manual?: boolean } })?.data?.manual);
if (!manual && !isEnabled(ctx, job)) return { skipped: 'switched off' };
return runJob(ctx, job);
});
if (isEnabled(ctx, job)) await boss.schedule(job.name, cronFor(ctx, job), undefined, { tz });
else await boss.unschedule(job.name).catch(() => {});
}
const off = JOBS.filter((j) => !isEnabled(ctx, j)).map((j) => j.name);
console.log(`[jobs] Job queue started: ${JOBS.filter((j) => isEnabled(ctx, j)).map((j) => j.name).join(', ')}${off.length ? ` (off: ${off.join(', ')})` : ''}.`);
return async () => { await boss.stop({ graceful: true }); state.boss = null; state.mode = 'off'; };
} catch (e) {
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
state.boss = null;
state.mode = 'timers';
for (const job of JOBS) startTimer(ctx, job);
return async () => { state.timers.forEach(clearTimeout); state.timers.clear(); state.mode = 'off'; };
}
}
export class JobError extends Error {
constructor(public status: number, message: string) { super(message); }
}
/**
* Saves an admin's choice for one job and applies it. `enabled` / `cron`: a value wins over the
* .env, null goes back to it, undefined leaves it.
*/
export async function setOverride(ctx: Ctx, name: string, change: { enabled?: unknown; cron?: unknown }): Promise<{ enabled: boolean | null; cron: string | null }> {
const job = JOBS.find((j) => j.name === name);
if (!job) throw new JobError(404, 'There\'s no such job.');
const { enabled, cron } = change;
if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw new JobError(400, '"enabled" must be true, false or null.');
if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim(), ctx.config.timezone))) {
throw new JobError(400, 'That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".');
}
const all = { ...(await loadOverrides(ctx, true)) };
const entry: Override = { ...(all[name] ?? {}) };
if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled as boolean; }
if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = (cron as string).trim(); }
if (Object.keys(entry).length) all[name] = entry; else delete all[name];
const value = JSON.stringify(all);
await ctx.db.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } });
ctx.settings.forget();
state.overrides = all;
state.overridesAt = Date.now();
await applyJob(ctx, job);
return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null };
}
/** Runs a job now: queued in queue mode (it runs even when switched off), here otherwise. */
export async function runNow(ctx: Ctx, name: string): Promise<{ queued: boolean; output?: unknown }> {
const job = JOBS.find((j) => j.name === name);
if (!job) throw new JobError(404, 'There\'s no such job.');
if (state.mode === 'queue' && state.boss) {
await state.boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` });
return { queued: true };
}
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(ctx, job);
entry.state = 'completed';
return { queued: false, output: entry.output };
} catch (e) {
entry.state = 'failed';
entry.output = { message: (e as Error).message };
throw new JobError(502, `The job failed: ${(e as Error).message}`);
} finally {
entry.completedOn = new Date();
remember(job.name, entry);
}
}
/** Each job with its switch, schedule, what the .env says, the admin's choice, and its last runs. */
export async function jobStatus(ctx: Ctx) {
await loadOverrides(ctx, true);
const tz = ctx.config.timezone;
const recent = new Map<string, Run[]>();
if (state.mode === 'queue') {
try {
// As in Cross Events: timestamptz as plain UTC, so Prisma's pg adapter doesn't drop the offset.
const rows = await ctx.db.$queryRawUnsafe<(Run & { name: string })[]>(`
SELECT name, state, created_on AT TIME ZONE 'UTC' AS "createdOn", started_on AT TIME ZONE 'UTC' AS "startedOn",
completed_on AT TIME ZONE 'UTC' AS "completedOn", output
FROM (
SELECT name, state::text, created_on, started_on, completed_on, output,
row_number() OVER (PARTITION BY name ORDER BY created_on DESC) AS rn
FROM ${SCHEMA}.job WHERE name = ANY($1::text[])
) ranked WHERE rn <= 10 ORDER BY "createdOn" DESC`, JOBS.map((j) => j.name));
for (const r of rows) recent.set(r.name, [...(recent.get(r.name) ?? []), r]);
} catch (e) {
console.warn('[jobs] Could not read the run history:', (e as Error).message);
}
} else {
for (const [name, list] of state.history) recent.set(name, list);
}
return {
mode: state.mode,
timezone: tz,
jobsEnabledEnv: ctx.config.jobsEnabled,
jobs: JOBS.map((job) => {
const cron = cronFor(ctx, job);
const enabled = isEnabled(ctx, job);
const o = state.overrides[job.name] ?? {};
return {
name: job.name, label: job.label, cron, enabled, envFlag: job.env,
envEnabled: envEnabled(job), envCron: envCronFor(ctx, job), defaultCron: job.cron,
override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron, tz) ? o.cron : null },
nextRun: enabled && state.mode !== 'off' ? nextRun(cron, tz) : null,
recent: recent.get(job.name) ?? [],
};
}),
};
}
+208
View File
@@ -0,0 +1,208 @@
/**
* The emails Accounts sends (1.4.0), styled as Cross Events' (apps/events/backend/src/utils/email.js):
* a header in the church's colour with its logo or name, a white card, a button for the one thing
* to do with the link written out under it, and a footer with the church's contact details.
*
* Every email also has the plain text it always had (some mail apps show only that, and the tests
* read codes and links from it). Everything put into the HTML is escaped; colours and links are
* checked first.
*/
import type { Ctx } from '../context.js';
import { church } from '../church/profile.js';
export type Built = { subject: string; text: string; html: string };
type Brand = { name: string; colour: string; accent: string; logoUrl: string | null; email: string | null; phone: string | null; url: string };
const FONT = `-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif`;
const MONO = `'SFMono-Regular',Consolas,'Liberation Mono',Menlo,monospace`;
const HEX = /^#[0-9a-fA-F]{6}$/;
export const esc = (s: unknown) => String(s ?? '')
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
/** Only http(s) links go in an href. */
const safeUrl = (u: string) => (/^https?:\/\//i.test(u) ? u : '#');
/** A darker shade of a #rrggbb colour, for the header's gradient. */
function darker(hex: string, by = 0.25): string {
const n = parseInt(hex.slice(1), 16);
const ch = (shift: number) => Math.max(0, Math.round(((n >> shift) & 255) * (1 - by)));
return `#${[ch(16), ch(8), ch(0)].map((c) => c.toString(16).padStart(2, '0')).join('')}`;
}
async function brand(ctx: Ctx): Promise<Brand> {
const base = ctx.config.publicUrl.replace(/\/+$/, '');
try {
const c = await church(ctx);
const logo = c.branding.logoUrl;
return {
name: c.name || 'Your church',
colour: HEX.test(c.branding.colours.primary) ? c.branding.colours.primary : '#1f4e79',
accent: c.branding.colours.accent && HEX.test(c.branding.colours.accent) ? c.branding.colours.accent : '#f2a900',
logoUrl: logo ? (logo.startsWith('/') ? `${base}${logo}` : /^https:\/\//i.test(logo) ? logo : null) : null,
email: c.contact.email ?? null,
phone: c.contact.phone ?? null,
url: base,
};
} catch {
return { name: 'Your church', colour: '#1f4e79', accent: '#f2a900', logoUrl: null, email: null, phone: null, url: base };
}
}
/** The page around an email's body (Cross Events' layout). */
function layout(b: Brand, body: string, preheader: string): string {
const header = b.logoUrl
? `<img src="${esc(b.logoUrl)}" alt="${esc(b.name)}" height="56" style="display:block;margin:0 auto;max-height:56px;max-width:240px;border:0">`
: `<h1 style="color:#ffffff;font-size:26px;font-weight:800;margin:0;letter-spacing:-0.5px;font-family:${FONT};text-shadow:0 1px 3px rgba(0,0,0,0.3)">${esc(b.name)}</h1>`;
const contact = [
esc(b.name),
b.email ? `<a href="mailto:${esc(b.email)}" style="color:#94a3b8;text-decoration:underline">${esc(b.email)}</a>` : '',
b.phone ? esc(b.phone) : '',
].filter(Boolean).join(' &bull; ');
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>${esc(b.name)}</title>
</head>
<body style="margin:0;padding:0;background-color:#f1f5f9;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%">
<div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;mso-hide:all">${esc(preheader)}&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#f1f5f9">
<tr><td align="center" style="padding:40px 16px">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px">
<tr><td style="background:${b.colour};background:linear-gradient(135deg,${b.colour} 0%,${darker(b.colour)} 100%);border-radius:12px 12px 0 0;padding:36px 48px;text-align:center">
${header}
<p style="color:#ffffff;font-size:13px;font-weight:500;margin:10px 0 0 0;font-family:${FONT};letter-spacing:0.3px;opacity:0.9">Your ${esc(b.name)} account</p>
</td></tr>
<tr><td style="background:#ffffff;border-left:1px solid #e2e8f0;border-right:1px solid #e2e8f0;padding:44px 48px 36px 48px">
<div style="font-family:${FONT};color:#1e293b;font-size:15px;line-height:1.75">
${body}
</div>
</td></tr>
<tr><td style="background:#f8fafc;border:1px solid #e2e8f0;border-top:none;border-radius:0 0 12px 12px;padding:24px 48px;text-align:center">
<p style="color:#94a3b8;font-size:12px;margin:0 0 4px 0;font-family:${FONT}">${contact}</p>
<p style="color:#cbd5e1;font-size:11px;margin:6px 0 0 0;font-family:${FONT}">You're getting this because you have an account with ${esc(b.name)}, used to sign in to its sites.</p>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>`;
}
const title = (t: string, sub?: string) =>
`<p style="font-size:22px;font-weight:800;color:#0f172a;margin:0 0 8px 0;letter-spacing:-0.3px">${esc(t)}</p>` +
(sub ? `<p style="color:#64748b;font-size:14px;margin:0 0 28px 0">${esc(sub)}</p>` : '');
const hello = (name?: string | null) => `<p style="margin:0 0 8px 0;color:#374151">Hello <strong>${esc(name || 'there')}</strong>,</p>`;
const para = (html: string) => `<p style="margin:0 0 20px 0;color:#374151">${html}</p>`;
const divider = () => `<div style="border-top:1px solid #f1f5f9;margin:28px 0"></div>`;
const small = (html: string) => `<p style="margin:0;font-size:13px;color:#94a3b8">${html}</p>`;
function button(b: Brand, label: string, url: string): string {
const href = esc(safeUrl(url));
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:28px auto 8px auto">
<tr><td align="center" style="border-radius:8px;background-color:${b.colour}">
<a href="${href}" target="_blank" style="display:inline-block;padding:14px 36px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;border-radius:8px;font-family:${FONT};letter-spacing:0.2px">${esc(label)}</a>
</td></tr>
</table>
<p style="text-align:center;margin:4px 0 0 0;font-size:12px;color:#94a3b8;word-break:break-all">Or copy this link: <a href="${href}" style="color:${b.colour}">${esc(url)}</a></p>`;
}
/** Info, a warning ("if this wasn't you") or neutral: these colours never follow the church's. */
function callout(html: string, kind: 'info' | 'warning' | 'success' = 'info'): string {
const s = { info: ['#eff6ff', '#3b82f6', '#1e40af'], warning: ['#fffbeb', '#f59e0b', '#92400e'], success: ['#f0fdf4', '#22c55e', '#166534'] }[kind];
return `<div style="background:${s[0]};border-left:4px solid ${s[1]};border-radius:0 6px 6px 0;padding:14px 18px;margin:24px 0;color:${s[2]};font-size:14px;line-height:1.6">${html}</div>`;
}
const code6 = (code: string) =>
`<p style="margin:8px 0 24px 0;font-size:34px;font-weight:800;letter-spacing:8px;color:#0f172a;text-align:center;font-family:${MONO}">${esc(code)}</p>`;
const contactLine = (b: Brand) => (b.email ? ` at <a href="mailto:${esc(b.email)}" style="color:${b.colour}">${esc(b.email)}</a>` : '');
// ─── The emails ───────────────────────────────────────────────────────────────
/** A sign-in or confirm-your-email code (the text is the WhatsApp message too). */
export async function codeEmail(ctx: Ctx, o: { name?: string | null; code: string; text: string; purpose: 'sign_in' | 'verify_email' | 'setup'; minutes: number }): Promise<Built> {
const b = await brand(ctx);
const what = o.purpose === 'verify_email' ? 'confirm your email address' : 'sign in';
const body = title('Your code', o.purpose === 'verify_email' ? 'To confirm your email address' : `To sign in to ${b.name}`)
+ hello(o.name)
+ para(`Enter this code to ${esc(what)}. It works for <strong>${o.minutes} minutes</strong>.`)
+ code6(o.code)
+ divider()
+ small(`Never share this code with anyone, not even someone from the church. If you didn't ask for it, you can ignore this email: nobody can sign in without your password${o.purpose === 'sign_in' ? ' and this code' : ''}.`);
return { subject: `Your code: ${o.code}`, text: o.text, html: layout(b, body, `Your code is ${o.code}. It works for ${o.minutes} minutes.`) };
}
export async function resetPasswordEmail(ctx: Ctx, o: { name?: string | null; url: string; minutes: number }): Promise<Built> {
const b = await brand(ctx);
const body = title('Reset your password', 'Someone (we hope you) asked to reset it.')
+ hello(o.name)
+ para(`Choose a new password with the button below. The link works for <strong>${o.minutes} minutes</strong>, once.`)
+ button(b, 'Choose a new password', o.url)
+ divider()
+ small(`If you didn't ask, you can ignore this email: your password stays the same. Worried? Let the church office know${contactLine(b)}.`);
const text = `Someone (we hope you) asked to reset the password for your account.\n\nChoose a new password here (the link works for ${o.minutes} minutes):\n${o.url}\n\nIf you didn't ask, you can ignore this email: your password stays the same.`;
return { subject: 'Reset your password', text, html: layout(b, body, `Choose a new password. The link works for ${o.minutes} minutes.`) };
}
/** A product (Cross Events) made someone an account: choose a password. */
export async function newAccountEmail(ctx: Ctx, o: { name: string; url: string; days: number }): Promise<Built> {
const b = await brand(ctx);
const body = title(`Welcome to ${b.name}`, 'An account has been made for you.')
+ hello(o.name)
+ para(`${esc(b.name)} has made you an account. It signs you in to all of the church's sites, such as events and registrations. Choose your password to start using it.`)
+ button(b, 'Choose my password', o.url)
+ callout(`The link works for <strong>${o.days} days</strong>. After that, use <em>Forgot your password?</em> on the sign-in page.`, 'info')
+ small('If you weren\'t expecting this, you can ignore this email.');
const text = `Hello ${o.name},\n\n${b.name} has made you an account. Choose your password here (the link works for ${o.days} days):\n${o.url}\n\nIf you weren't expecting this, you can ignore this email.`;
return { subject: `Your account at ${b.name}`, text, html: layout(b, body, `Choose your password for your ${b.name} account.`) };
}
export async function confirmNewEmail(ctx: Ctx, o: { name?: string | null; url: string }): Promise<Built> {
const b = await brand(ctx);
const body = title('Confirm your new email address')
+ hello(o.name)
+ para('You asked to sign in with this email address from now on. Confirm it\'s yours with the button below; until then you keep signing in with your old one.')
+ button(b, 'Confirm this address', o.url)
+ divider()
+ small('The link works for 24 hours. If you didn\'t ask for this, you can ignore this email.');
const text = `Confirm this is your new email address for signing in:\n${o.url}\n\nThe link works for 24 hours.`;
return { subject: 'Confirm your new email address', text, html: layout(b, body, 'Confirm your new sign-in email address.') };
}
export async function emailChangedNotice(ctx: Ctx, o: { name?: string | null; newEmail: string }): Promise<Built> {
const b = await brand(ctx);
const body = title('Your sign-in email address changed')
+ hello(o.name)
+ para(`Your account now signs in with <strong>${esc(o.newEmail)}</strong>. Emails about your account go there from now on.`)
+ callout(`<strong>Wasn't you?</strong> Contact the church office straight away${contactLine(b)}.`, 'warning');
const text = `Your account now signs in with ${o.newEmail}. If you didn't do this, contact the church office straight away.`;
return { subject: 'Your sign-in email address changed', text, html: layout(b, body, `Your account now signs in with ${o.newEmail}.`) };
}
export async function exportReadyEmail(ctx: Ctx, o: { name?: string | null; url: string; days: number }): Promise<Built> {
const b = await brand(ctx);
const body = title('Your data is ready', 'The copy you asked for')
+ hello(o.name)
+ para('The copy of your data you asked for is ready. Download it from your account page.')
+ button(b, 'Download my data', o.url)
+ callout(`It's kept for <strong>${o.days} days</strong>, then deleted. You need to be signed in to download it.`, 'info');
const text = `The copy of your data you asked for is ready. Download it from your account page (it's kept for ${o.days} days):\n${o.url}`;
return { subject: 'Your data is ready to download', text, html: layout(b, body, 'The copy of your data you asked for is ready.') };
}
/** A test from the admin page or from a linked product (`from`: "Cross Events"). */
export async function testEmail(ctx: Ctx, o: { from?: string } = {}): Promise<Built> {
const b = await brand(ctx);
const body = title('Email works', o.from ? `A test sent from ${o.from}` : 'A test from Accounts')
+ para(`This is a test from ${esc(b.name)}'s sign-in (Accounts)${o.from ? `, sent from ${esc(o.from)}` : ''}.`)
+ callout('Email is set up: sign-in codes, password links and security notices can be sent.', 'success');
const text = o.from
? `This is a test from ${b.name}'s sign-in (Accounts), sent from ${o.from}. Email works: sign-in codes and password links can be sent.`
: 'Email from Accounts works.';
return { subject: o.from ? `Test email from ${b.name}'s sign-in` : 'Test email from Accounts', text, html: layout(b, body, 'A test email: email works.') };
}
+4 -3
View File
@@ -5,7 +5,8 @@
import nodemailer from 'nodemailer';
import type { Ctx } from '../context.js';
export type Email = { to: string; subject: string; text: string };
/** `html` (1.4.0, src/lib/emails.ts): the styled version; `text` is always sent too. */
export type Email = { to: string; subject: string; text: string; html?: string };
export type WhatsApp = { to: string; text: string };
/** SMTP settings to try before saving them (1.2.0), as kept in `smtp_*`. */
@@ -87,7 +88,7 @@ export class LiveMessenger implements Messenger {
return;
}
const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name;
await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text });
await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text, ...(msg.html ? { html: msg.html } : {}) });
}
async emailReady(): Promise<boolean> {
@@ -112,7 +113,7 @@ export class LiveMessenger implements Messenger {
async emailWith(settings: SmtpTry, msg: Email): Promise<void> {
const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name;
await transportFor(settings).sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${settings.from}>` : settings.from, to: msg.to, subject: msg.subject, text: msg.text });
await transportFor(settings).sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${settings.from}>` : settings.from, to: msg.to, subject: msg.subject, text: msg.text, ...(msg.html ? { html: msg.html } : {}) });
}
async whatsappWith(settings: WawpTry, msg: WhatsApp): Promise<void> {
+3 -7
View File
@@ -23,6 +23,7 @@ import type { Ctx } from '../context.js';
import type { ProductLink } from '../generated/prisma/client.js';
import { limit } from '../http.js';
import { audit, clientIp, loginEvent } from '../lib/audit.js';
import { newAccountEmail, testEmail } from '../lib/emails.js';
import { hashToken, randomToken } from '../lib/crypto.js';
import { appVersion } from '../lib/version.js';
import { BUILT_IN_VERSION } from '../privacy/notice.js';
@@ -224,16 +225,11 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
// Only the product's own address: never somewhere else.
const returnUrl = new URL(r.returnUrl).origin === new URL(link.url).origin ? r.returnUrl : link.url;
await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), returnUrl, expiresAt: new Date(ctx.now().getTime() + SET_PASSWORD_DAYS * 86400e3) } });
const churchName = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church';
// 1.2.0: the account stands even when the email can't go (they can use "Forgot your password?"
// once email works); the product is told.
let emailSent = true;
try {
await ctx.messenger.email({
to: email,
subject: `Your account at ${churchName}`,
text: `Hello ${r.name},\n\n${churchName} has made you an account. Choose your password here (the link works for ${SET_PASSWORD_DAYS} days):\n${ctx.config.publicUrl}/reset?token=${token}\n\nIf you weren't expecting this, you can ignore this email.`,
});
await ctx.messenger.email({ to: email, ...(await newAccountEmail(ctx, { name: r.name, url: `${ctx.config.publicUrl}/reset?token=${token}`, days: SET_PASSWORD_DAYS })) });
} catch (e) {
emailSent = false;
console.warn('[people.ensure] the "choose your password" email could not be sent:', (e as Error).message);
@@ -325,7 +321,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
const pass = s.pass === null ? ((await ctx.settings.get('smtp_pass')) ?? '') : opened(secret, s.pass, 'SMTP password');
const tryWith = { host: s.host, port: s.port, secure: s.secure, user: s.user, pass: pass ?? '', from: s.from };
try {
await ctx.messenger.emailWith(tryWith, { to: r.email.to, subject: `Test email from ${church}'s sign-in`, text: `This is a test from ${church}'s sign-in (Accounts), sent from ${link.product === 'events' ? 'Cross Events' : link.product}. Email works: sign-in codes and password links can be sent.` });
await ctx.messenger.emailWith(tryWith, { to: r.email.to, ...(await testEmail(ctx, { from: link.product === 'events' ? 'Cross Events' : link.product })) });
email = { ok: true, error: null, saved: false };
if (save) {
await ctx.settings.setMany({ smtp_host: s.host, smtp_port: String(s.port), smtp_secure: String(s.secure), smtp_user: s.user, smtp_from: s.from, ...(s.pass === null ? {} : { smtp_pass: pass }) });
+3 -2
View File
@@ -8,6 +8,7 @@ import type Provider from 'oidc-provider';
import type { Ctx } from '../context.js';
import { ApiError, handle, limit } from '../http.js';
import { loginEvent } from '../lib/audit.js';
import { confirmNewEmail, emailChangedNotice } from '../lib/emails.js';
import { hashPassword, passwordProblem, verifyPassword } from '../lib/passwords.js';
import { emailProblem, normaliseEmail, normalisePhone, profileChanged, setNewsConsent } from '../accounts/service.js';
import { confirmTwoFactorSetup, recoveryCodesLeft, replaceRecoveryCodes, startTwoFactorSetup, turnOff } from '../accounts/twoFactor.js';
@@ -93,7 +94,7 @@ export function meRouter(ctx: Ctx, provider: Provider) {
if (await ctx.db.account.findUnique({ where: { email } })) throw new ApiError(409, 'EXISTS', 'Another account uses that email address.', { email: 'Another account uses that email address.' });
const token = randomToken();
await ctx.db.emailToken.create({ data: { accountId: s.account.id, purpose: `change_email:${email}`, tokenHash: hashToken(token), expiresAt: new Date(ctx.now().getTime() + 24 * 3600e3) } });
await ctx.messenger.email({ to: email, subject: 'Confirm your new email address', text: `Confirm this is your new email address for signing in:\n${ctx.config.publicUrl}/account/confirm-email?token=${token}\n\nThe link works for 24 hours.` });
await ctx.messenger.email({ to: email, ...(await confirmNewEmail(ctx, { name: s.account.name, url: `${ctx.config.publicUrl}/account/confirm-email?token=${token}` })) });
return { sent: true };
}));
@@ -105,7 +106,7 @@ export function meRouter(ctx: Ctx, provider: Provider) {
if (await ctx.db.account.findUnique({ where: { email } })) throw new ApiError(409, 'EXISTS', 'Another account uses that email address now.');
await ctx.db.account.update({ where: { id: s.account.id }, data: { email, emailVerified: true } });
await ctx.db.emailToken.update({ where: { id: row.id }, data: { usedAt: ctx.now() } });
await ctx.messenger.email({ to: s.account.email, subject: 'Your sign-in email address changed', text: `Your account now signs in with ${email}. If you didn't do this, contact the church office straight away.` });
await ctx.messenger.email({ to: s.account.email, ...(await emailChangedNotice(ctx, { name: s.account.name, newEmail: email })) });
await loginEvent(ctx, s.account.id, 'email_changed', req);
await profileChanged(ctx, s.account.id);
return view(s);
+2 -1
View File
@@ -9,6 +9,7 @@ import path from 'node:path';
import { IDENTITY_SCHEMA, userExportReplySchema } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { onReply, queueCall } from '../links/deliveries.js';
import { exportReadyEmail } from '../lib/emails.js';
const WAIT_MS = 24 * 3600e3;
const KEEP_MS = 7 * 24 * 3600e3;
@@ -71,7 +72,7 @@ export async function finishIfComplete(ctx: Ctx, exportId: string, force = false
}, null, 2), { mode: 0o600 });
await ctx.db.dataExport.update({ where: { id: exp.id }, data: { status: 'ready', file, readyAt: ctx.now(), expiresAt: new Date(ctx.now().getTime() + KEEP_MS) } });
const a = await ctx.db.account.findUnique({ where: { id: exp.accountId } });
if (a) await ctx.messenger.email({ to: a.email, subject: 'Your data is ready to download', text: `The copy of your data you asked for is ready. Download it from your account page (it's kept for 7 days):\n${ctx.config.publicUrl}/account/privacy` });
if (a) await ctx.messenger.email({ to: a.email, ...(await exportReadyEmail(ctx, { name: a.name, url: `${ctx.config.publicUrl}/account/privacy`, days: Math.round(KEEP_MS / 86400e3) })) });
return true;
}
@@ -0,0 +1,103 @@
// 1.4.0: Admin → Background jobs (switch a job on or off, change its schedule, over the .env) and
// the styled emails (as Cross Events').
import assert from 'node:assert/strict';
import { after, before, describe, test } from 'node:test';
import { Browser, startHarness, type Harness } from './support/harness.js';
import { codeAt } from '../src/lib/totp.js';
import { JOBS, cronFor, isEnabled, useEnvForTest } from '../src/jobs.js';
import { esc, newAccountEmail, resetPasswordEmail } from '../src/lib/emails.js';
import type { MemoryMessenger } from '../src/lib/messages.js';
let h: Harness;
before(async () => { h = await startHarness(); });
after(async () => { useEnvForTest(process.env); await h.close(); });
let adminBrowser: Browser | null = null;
async function adminPage() {
if (adminBrowser) return adminBrowser;
await h.makeAccount({ email: 'jobs.admin@hope.test', password: 'Correct-horse-8', role: 'admin' });
const browser = new Browser();
const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/admin`, (u) => u.pathname === '/signin');
const uid = url.searchParams.get('uid')!;
await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'jobs.admin@hope.test', password: 'Correct-horse-8' });
const setup = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor/setup`, { method: 'totp' });
const done = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor/setup/confirm`, { method: 'totp', code: codeAt(String(setup.body.secret), Math.floor(Date.now() / 30000)) });
await browser.follow(done.body.redirectTo as string, (u) => u.pathname === '/admin' || u.pathname === '/account');
adminBrowser = browser;
return browser;
}
const backup = JOBS.find((j) => j.name === 'backup')!;
describe('background jobs', () => {
test('the .env flag and schedule apply until an admin chooses; their choice wins; null goes back', async () => {
useEnvForTest({ BACKUP_ENABLED: 'false', JOB_SCHEDULE_BACKUP: '30 1 * * *' });
h.ctx.config.jobsEnabled = true; // the harness turns them off; nothing is started here either way
const browser = await adminPage();
let list = await h.api(browser, 'GET', '/api/v2/admin/jobs');
assert.equal(list.status, 200);
let job = (list.body.jobs as { name: string; enabled: boolean; envEnabled: boolean; cron: string; override: { enabled: boolean | null; cron: string | null } }[]).find((j) => j.name === 'backup')!;
assert.equal(job.enabled, false);
assert.equal(job.envEnabled, false);
assert.equal(job.cron, '30 1 * * *');
assert.deepEqual(job.override, { enabled: null, cron: null });
const on = await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { enabled: true, cron: '0 3 * * *' });
assert.equal(on.status, 200);
assert.deepEqual(on.body.override, { enabled: true, cron: '0 3 * * *' });
assert.equal(isEnabled(h.ctx, backup), true);
assert.equal(cronFor(h.ctx, backup), '0 3 * * *');
list = await h.api(browser, 'GET', '/api/v2/admin/jobs');
job = (list.body.jobs as typeof job[]).find((j) => j.name === 'backup')!;
assert.equal(job.enabled, true);
assert.equal(job.envEnabled, false);
const back = await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { enabled: null, cron: null });
assert.deepEqual(back.body.override, { enabled: null, cron: null });
assert.equal(isEnabled(h.ctx, backup), false);
assert.equal(cronFor(h.ctx, backup), '30 1 * * *');
const audit = await h.ctx.db.auditLog.findMany({ where: { action: 'job_settings_changed' } });
assert.equal(audit.length, 2);
});
test('a bad schedule, a bad switch and an unknown job are refused', async () => {
const browser = await adminPage();
assert.equal((await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { cron: 'every night' })).status, 400);
assert.equal((await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { enabled: 'yes' })).status, 400);
assert.equal((await h.api(browser, 'PUT', '/api/v2/admin/jobs/nope', { enabled: true })).status, 404);
});
test('only admins see them', async () => {
const anon = new Browser();
assert.equal((await h.api(anon, 'GET', '/api/v2/admin/jobs')).status, 401);
});
});
describe('styled emails', () => {
test('in the church colour, with its name escaped, and the same plain text as before', async () => {
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope <Church> & Co', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#336699', accent: null } }, contact: { email: 'office@hope.test', phone: null, whatsapp: null, address: null } }));
const r = await resetPasswordEmail(h.ctx, { name: '<b>Jane</b>', url: 'https://accounts.hope.test/reset?token=abc', minutes: 60 });
assert.equal(r.subject, 'Reset your password');
assert.match(r.text, /https:\/\/accounts\.hope\.test\/reset\?token=abc/);
assert.match(r.html, /background-color:#336699/);
assert.match(r.html, /Hope &lt;Church&gt; &amp; Co/);
assert.ok(!r.html.includes('<b>Jane</b>'));
assert.match(r.html, /href="https:\/\/accounts\.hope\.test\/reset\?token=abc"/);
assert.match(r.html, /office@hope\.test/);
const n = await newAccountEmail(h.ctx, { name: 'Sam', url: 'javascript:alert(1)', days: 7 });
assert.equal(n.subject, 'Your account at Hope <Church> & Co');
assert.ok(!n.html.includes('href="javascript:'));
assert.equal(esc('"x"'), '&quot;x&quot;');
});
test('the test email from admin goes as HTML too', async () => {
const browser = await adminPage();
const m = h.ctx.messenger as MemoryMessenger;
const before = m.emails.length;
assert.equal((await h.api(browser, 'POST', '/api/v2/admin/settings/test-email', {})).status, 200);
const sent = m.emails.slice(before).at(-1)!;
assert.equal(sent.subject, 'Test email from Accounts');
assert.match(sent.html ?? '', /<!DOCTYPE html>/);
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-frontend",
"version": "1.3.0",
"version": "1.4.0",
"private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"scripts": {
+161 -1
View File
@@ -2,7 +2,7 @@
import Link from "next/link";
import React, { useCallback, useState } from "react";
import { DatabaseBackup, Download } from "lucide-react";
import { DatabaseBackup, Download, Play, RefreshCw, Timer } from "lucide-react";
import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
import { AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell";
import { NoticeText } from "@/components/NoticeText";
@@ -61,6 +61,7 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
{section === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />}
{section === "notice" && <NoticeTab flash={flash} />}
{section === "backups" && <Backups flash={flash} />}
{section === "jobs" && <Jobs flash={flash} />}
{section === "licence" && <Licence flash={flash} />}
{section === "audit" && <Audit />}
</div>
@@ -463,3 +464,162 @@ function Backups({ flash }: { flash: Flash }) {
</div>
);
}
// ─── Background jobs (1.4.0, as Cross Events) ────────────────────────────────
type JobRun = { state: string; createdOn?: string | null; startedOn: string | null; completedOn: string | null; output: unknown };
type JobInfo = {
name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[];
envEnabled: boolean; envCron: string; defaultCron: string; override: { enabled: boolean | null; cron: string | null };
};
type JobList = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: JobInfo[] };
const RUN_STATE: Record<string, string> = {
completed: "bg-green-50 text-green-800", failed: "bg-red-50 text-red-700", active: "bg-blue-50 text-blue-700",
created: "bg-gray-100 text-gray-600", retry: "bg-amber-50 text-amber-800", cancelled: "bg-gray-100 text-gray-500",
};
const SCHEDULES = [
{ label: "Every minute", cron: "* * * * *" }, { label: "Every 5 minutes", cron: "*/5 * * * *" }, { label: "Every 15 minutes", cron: "*/15 * * * *" },
{ label: "Every hour", cron: "0 * * * *" }, { label: "Daily at 02:00", cron: "0 2 * * *" }, { label: "Daily at 07:00", cron: "0 7 * * *" },
];
function describeCron(cron: string): string {
if (cron === "* * * * *") return "Every minute";
const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron);
if (m) return `Every ${m[1]} minutes`;
const h = /^(\d+) \* \* \* \*$/.exec(cron);
if (h) return `Every hour at :${h[1]!.padStart(2, "0")}`;
const d = /^(\d+) (\d+) \* \* \*$/.exec(cron);
if (d) return `Daily at ${d[2]!.padStart(2, "0")}:${d[1]!.padStart(2, "0")}`;
return cron;
}
function runText(r: JobRun): string {
if (r.output === null || r.output === undefined) return "";
if (r.state === "failed" && typeof r.output === "object" && r.output && "message" in r.output) return String((r.output as { message: unknown }).message);
try { return JSON.stringify(r.output); } catch { return ""; }
}
/** An on/off switch (role="switch", so screen readers hear on and off). */
function Toggle({ on, label, disabled, onChange }: { on: boolean; label: string; disabled?: boolean; onChange: (on: boolean) => void }) {
return (
<button type="button" role="switch" aria-checked={on} aria-label={label} disabled={disabled} onClick={() => onChange(!on)}
className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 disabled:cursor-not-allowed disabled:opacity-50 ${on ? "bg-brand" : "bg-gray-300"}`}>
<span className={`inline-block h-5 w-5 rounded-full bg-white shadow transition-transform ${on ? "translate-x-5" : "translate-x-0.5"}`} />
</button>
);
}
function Jobs({ flash }: { flash: Flash }) {
const [data, setData] = useState<JobList | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [open, setOpen] = useState<string | null>(null);
const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
// Not tied to `flash` (a new function each render): the list loads once, then on Refresh.
const load = useCallback(async () => {
const r = await call<JobList>("GET", "/admin/jobs");
if (r.ok) { setData(r.data); setLoadError(null); } else setLoadError(r.error.message);
}, []);
useExternalEffect(() => { void load(); }, [load]);
const save = async (job: JobInfo, change: { enabled?: boolean | null; cron?: string | null }, done: string) => {
setBusy(job.name);
const r = await call("PUT", `/admin/jobs/${encodeURIComponent(job.name)}`, change);
setBusy(null);
if (r.ok) { flash("success", done); setEditing(null); void load(); } else flash("error", r.error.message);
};
const runNow = async (job: JobInfo) => {
setBusy(job.name);
const r = await call<{ queued: boolean }>("POST", `/admin/jobs/${encodeURIComponent(job.name)}/run`);
setBusy(null);
if (r.ok) {
flash("success", r.data.queued ? `"${job.label}" queued: it starts within a few seconds.` : `"${job.label}" ran.`);
setTimeout(() => void load(), r.data.queued ? 4000 : 0);
} else flash("error", r.error.message);
};
if (!data) return loadError ? <Notice tone="error">{loadError}</Notice> : <p className="text-gray-600">Loading…</p>;
const off = data.mode === "off";
return (
<Card>
<div className="mb-3 flex items-start justify-between gap-3">
<Heading icon={<Timer className="h-4 w-4" />} sub={`Times are ${data.timezone}. Each job runs once per schedule, however many server processes there are.`}>Jobs</Heading>
<Button variant="secondary" onClick={() => void load()}><RefreshCw className="mr-1.5 inline h-3.5 w-3.5" aria-hidden />Refresh</Button>
</div>
{off && <Notice tone="warning">All background jobs are switched off in the server&apos;s .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change that from the Hub.</Notice>}
{data.mode === "timers" && <Notice tone="warning">The job queue couldn&apos;t start, so jobs run on simple timers in this process (history only since the last restart).</Notice>}
<ul className="divide-y rounded-lg border">
{data.jobs.map((job) => {
const last = job.recent[0];
const mine = busy === job.name;
const isEditing = editing?.name === job.name;
return (
<li key={job.name} className="p-3">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<Toggle on={job.enabled} disabled={mine || off} label={`${job.label}: ${job.enabled ? "on" : "off"}`}
onChange={(on) => void save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)} />
<div className="mr-auto min-w-0">
<div className={`text-sm font-medium ${job.enabled ? "text-gray-900" : "text-gray-500"}`}>{job.label}</div>
<div className="text-xs text-gray-500">
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : "Off"}
{job.override.enabled !== null
? <> · {job.enabled ? "switched on" : "switched off"} here · <button type="button" disabled={mine} className="underline hover:text-gray-700" onClick={() => void save(job, { enabled: null }, `"${job.label}" follows the .env again.`)}>use the .env ({job.envEnabled ? "on" : "off"})</button></>
: !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""}
</div>
</div>
{last && (
<button type="button" onClick={() => setOpen(open === job.name ? null : job.name)} title="Recent runs" className={`rounded px-2 py-0.5 text-xs ${RUN_STATE[last.state] ?? "bg-gray-100 text-gray-600"}`}>
{last.state} · {when(last.completedOn || last.startedOn || last.createdOn)}
</button>
)}
<Button variant="secondary" disabled={mine || isEditing} onClick={() => setEditing({ name: job.name, cron: job.cron })}>Schedule</Button>
<Button variant="secondary" disabled={!!busy || off} onClick={() => void runNow(job)}><Play className="mr-1 inline h-3.5 w-3.5" aria-hidden />Run now</Button>
</div>
{isEditing && editing && (
<form className="mt-3 space-y-2 rounded-lg border bg-gray-50 p-3" onSubmit={(e) => { e.preventDefault(); void save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}>
<div className="flex flex-wrap gap-1.5">
{SCHEDULES.map((p) => (
<button key={p.cron} type="button" onClick={() => setEditing({ name: job.name, cron: p.cron })}
className={`rounded border px-2 py-1 text-xs ${editing.cron === p.cron ? "border-brand bg-white font-medium" : "bg-white hover:bg-gray-100"}`}>{p.label}</button>
))}
</div>
<div className="flex flex-wrap items-end gap-3">
<Field label="Cron (minute hour day month weekday)" name="cron" value={editing.cron} maxLength={100} className="mb-0 w-64 font-mono"
onChange={(e) => setEditing({ name: job.name, cron: e.target.value })} hint={describeCron(editing.cron.trim())} />
<div className="ml-auto flex gap-2 pb-6">
<Button type="button" variant="secondary" onClick={() => setEditing(null)}>Cancel</Button>
<Button type="submit" busy={mine} disabled={!editing.cron.trim()}>Save schedule</Button>
</div>
</div>
<p className="text-xs text-gray-500">
The server&apos;s own schedule is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (from the .env; normally ${describeCron(job.defaultCron)})` : ""}.{" "}
{job.override.cron !== null && <button type="button" disabled={mine} className="underline hover:text-gray-700" onClick={() => void save(job, { cron: null }, `"${job.label}" is back on its own schedule.`)}>Use that again</button>}
</p>
</form>
)}
{open === job.name && job.recent.length > 0 && (
<div className="mt-2 overflow-x-auto">
<table className="w-full text-xs">
<thead className="text-gray-500"><tr><th className="py-1 text-left font-medium">Started</th><th className="text-left font-medium">Finished</th><th className="text-left font-medium">State</th><th className="text-left font-medium">Result</th></tr></thead>
<tbody>
{job.recent.map((r, i) => (
<tr key={i} className="border-t">
<td className="whitespace-nowrap py-1 pr-2">{when(r.startedOn)}</td>
<td className="whitespace-nowrap pr-2">{when(r.completedOn)}</td>
<td className="pr-2"><span className={`rounded px-1.5 py-0.5 ${RUN_STATE[r.state] ?? ""}`}>{r.state}</span></td>
<td className="break-all font-mono text-[11px] text-gray-600">{runText(r)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</li>
);
})}
</ul>
<p className="mt-3 text-xs text-gray-500">Without a choice here, the server&apos;s .env applies: a job&apos;s own flag (e.g. BACKUP_ENABLED=false) and JOB_SCHEDULE_&lt;NAME&gt;. The nightly backup also follows Backups → &quot;Back up every night&quot;.</p>
</Card>
);
}
@@ -4,7 +4,7 @@ import Link from "next/link";
import React, { useState } from "react";
import {
Activity, Building2, DatabaseBackup, FileText, KeyRound, LayoutDashboard, Link2, Lock, LogIn, LogOut, Mail, Menu, ScrollText,
ShieldCheck, User, Users, UserX, X, type LucideIcon,
ShieldCheck, Timer, User, Users, UserX, X, type LucideIcon,
} from "lucide-react";
import { ChurchMark } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
@@ -31,6 +31,7 @@ export const ADMIN_NAV: NavItem[] = [
{ href: "/admin/messages", label: "Email and WhatsApp", icon: Mail },
{ href: "/admin/notice", label: "Privacy notice", icon: FileText },
{ href: "/admin/backups", label: "Backups", icon: DatabaseBackup },
{ href: "/admin/jobs", label: "Background jobs", icon: Timer },
{ href: "/admin/licence", label: "Licence", icon: KeyRound },
{ href: "/admin/audit", label: "Audit log", icon: ScrollText },
];
@@ -8,6 +8,7 @@ export const ADMIN_SECTIONS = {
messages: { path: "/admin/messages", title: "Email and WhatsApp", sub: "How Accounts sends sign-in codes, password links and security notices." },
notice: { path: "/admin/notice", title: "Privacy notice", sub: "What people read before they sign in for the first time, and after it changes." },
backups: { path: "/admin/backups", title: "Backups", sub: "Copies of the Accounts database, kept on this server." },
jobs: { path: "/admin/jobs", title: "Background jobs", sub: "What the server does on a schedule. Switch a job on or off or change when it runs: your choice wins over the server's .env and applies straight away." },
licence: { path: "/admin/licence", title: "Licence", sub: "Accounts' connection to Cross Code." },
audit: { path: "/admin/audit", title: "Audit log", sub: "What admins and the church's sites changed here." },
} as const;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/agent",
"version": "1.2.0",
"version": "1.3.1",
"private": true,
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
"license": "UNLICENSED",
+10
View File
@@ -48,6 +48,16 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
return ["adopt", job.args.church, "--undo"];
case "restart":
return ["restart", job.args.church, ...(job.args.product ? [job.args.product] : [])];
case "env-read":
return ["env", job.args.church, job.args.product];
case "env-set": {
// Each value is its own argument (no shell), so spaces and quotes in values are safe.
const out = ["env", job.args.church, job.args.product, "--file", job.args.file];
for (const [name, value] of Object.entries(job.args.set)) out.push("--set", `${name}=${value}`);
for (const name of job.args.unset) out.push("--unset", name);
if (job.args.restart) out.push("--restart");
return out;
}
case "seed-demo":
return ["demo", job.args.church, "--profile", job.args.profile, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
case "export":
+1 -1
View File
@@ -12,7 +12,7 @@ import { paths } from "./paths";
* the tools that are there; anything missing is null rather than an error.
*/
export const AGENT_VERSION = "1.2.0";
export const AGENT_VERSION = "1.3.1";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
+9
View File
@@ -45,6 +45,15 @@ describe("crosscode arguments for each job", () => {
.toEqual(["demo", "hope", "--profile", "events", "--admin-email", "jane@hope.test"]);
});
it("env-read and env-set (1.3.0): crosscode env, each value its own argument", () => {
expect(crosscodeArgs(parsed({ type: "env-read", args: { church: "hope", product: "accounts" } }))).toEqual(["env", "hope", "accounts"]);
expect(crosscodeArgs(parsed({
type: "env-set",
args: { church: "hope", product: "events", file: "backend/.env", set: { FRONTEND_URL: "https://events.hope.co.za", ORG_NAME: "Hope; rm -rf /" }, unset: ["OLD"], restart: true },
}))).toEqual(["env", "hope", "events", "--file", "backend/.env", "--set", "FRONTEND_URL=https://events.hope.co.za", "--set", "ORG_NAME=Hope; rm -rf /", "--unset", "OLD", "--restart"]);
expect(() => parsed({ type: "env-set", args: { church: "hope", product: "events", file: "backend/.env", set: { JWT_SECRET: "x" }, unset: [], restart: false } })).toThrow();
});
it("export writes to the file the agent gives", () => {
const j = parsed({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh" } });
expect(crosscodeArgs(j, { exportFile: "/var/lib/crosscode-agent/exports/exp_abcdefgh.zip" })).toEqual(["export", "hope", "--out", "/var/lib/crosscode-agent/exports/exp_abcdefgh.zip"]);
+36
View File
@@ -5,6 +5,42 @@ All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project follows [Semantic Versioning](https://semver.org/).
## [3.5.0] - 2026-11-20
### Fixed
- **After "Load demo data" nobody could sign in** ("Sign-in isn't available right now",
`ACCOUNTS_UNAVAILABLE`). `scripts/set-demo.js` emptied `ProductLink` (it keeps only a few tables)
but kept `AppSetting`, so the site stayed in Accounts mode with no Accounts link, and
`accounts_auto_connected` stopped it reconnecting. Demo data now keeps `ProductLink` and
`LinkNonce`, and a site in Accounts mode without a link connects to the Accounts the Hub lists at
its next heartbeat whatever happened before (a site on its own sign-in still keeps an admin's
Disconnect).
### Added
- Heartbeat `stats.signIn` (contracts 1.13.0): the sign-in mode, the linked Accounts (install id and
address) and the last failure to start or finish a sign-in (`accounts_last_signin_error`, cleared
by the next sign-in that works). The Hub 2.9.0 alerts on it.
## [3.4.0] - 2026-11-20
### Added
- **Background jobs are switched on and off from Settings → Background jobs.** Each job has a
switch and a Schedule button (presets or a cron expression). The choice is saved in the database
(`AppSetting` `job_overrides`), wins over the .env (the job's own flag such as
`WAITLIST_JOB_ENABLED`, and `JOB_SCHEDULE_<NAME>`), and applies straight away: the queue is
rescheduled in this process, and other processes see it within 30 seconds (a run of a job switched
off elsewhere is skipped). "use the .env" goes back to what the server says.
`JOBS_ENABLED=false` still turns every job off (the end-to-end tests use it).
API: `PUT /api/v2/admin/jobs/:name` `{ enabled, cron }` (null goes back to the .env); `GET
/admin/jobs` also gives `envEnabled`, `envCron`, `defaultCron` and `override`.
### Changed
- "Run now" also works for a job that's switched off.
## [3.3.0] - 2026-11-20
Works with Accounts 1.3.0 (needed for the demo-data part; with an older Accounts the old demo people
+15
View File
@@ -12,6 +12,21 @@ Write for church admins, not developers: no environment variables, endpoints or
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
-->
## 3.5.0
- **Fix:** after loading demo data, nobody could sign in: the site forgot its link to the church's
sign-in (Accounts). Demo data keeps it now, and a site that lost it connects again by itself
within about 15 minutes of updating.
- When signing in fails, Cross Code is told why, so it can help sooner.
## 3.4.0
- **Switch background jobs on and off yourself.** Settings → Background jobs has a switch for each
job (reminders, backups, the daily summary and so on) and lets you change when it runs, with ready
choices such as "every 15 minutes" or "daily at 07:00". It works straight away, no restart needed,
and one click puts a job back to how the server normally runs it.
- **Run now** works for a job that's switched off too, for when you want it once.
## 3.3.0
- **Fix:** a new logo or favicon sometimes didn't show after saving. It's saved and shown properly
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "3.3.0",
"version": "3.5.0",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
+3
View File
@@ -76,6 +76,9 @@ const LIST_ONLY = process.argv.includes('--list');
const KEEP_TABLES = new Set([
'_prisma_migrations', 'AppSetting', 'User',
'SecurityEvent', 'PasswordReset', 'TwoFactorChallenge', 'TrustedDevice',
// 3.5.0: the links to the church's other products (Accounts above all: in Accounts mode, without
// its link nobody can sign in). Their feeds are data and go.
'ProductLink', 'LinkNonce',
]);
const SCHEDULED_EMAILS_PATH = path.resolve(__dirname, '../data/scheduled-emails.json');
@@ -7,12 +7,16 @@
import { connectTo } from '../links/connect';
import { linkedProducts } from '../links/store';
import { accountsLink } from './client';
import { getSetting, setSetting } from './mode';
import { getSetting, setSetting, viaAccounts } from './mode';
export const AUTO_KEY = 'accounts_auto_connected';
export async function connectAccountsIfListed(now = new Date()): Promise<'connected' | 'skipped'> {
if (await getSetting(AUTO_KEY)) return 'skipped';
// 3.5.0: a site that signs in through Accounts but has lost its link (before 3.5.0, loading demo
// data deleted it) can't sign anyone in, so it reconnects whatever was done before. A site on its
// own sign-in keeps an admin's Disconnect.
const stranded = (await viaAccounts()) && !(await accountsLink());
if ((await getSetting(AUTO_KEY)) && !stranded) return 'skipped';
if (await accountsLink()) {
await setSetting(AUTO_KEY, now.toISOString());
return 'skipped';
+9 -2
View File
@@ -20,6 +20,7 @@ import { siteUrl } from '../feed/context';
import { accounts, AccountsUnavailable } from './client';
import { viaAccounts } from './mode';
import { handleAccountsCall } from './calls';
import { clearSignInError, recordSignInError } from './status';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
@@ -144,7 +145,10 @@ async function startSignIn(req: Request, res: Response) {
return res.redirect(303, url);
} catch (e) {
console.warn('[accounts] sign-in could not start:', (e as Error).message);
return problem(res, e instanceof AccountsUnavailable ? 'ACCOUNTS_UNAVAILABLE' : 'START_FAILED', returnTo);
const failed = e instanceof AccountsUnavailable ? 'ACCOUNTS_UNAVAILABLE' : 'START_FAILED';
// 3.5.0: the reason goes to the Hub with the next heartbeat (the page only says "try again").
await recordSignInError(failed, (e as Error).message);
return problem(res, failed, returnTo);
}
}
@@ -158,7 +162,8 @@ async function callback(req: Request, res: Response) {
let auth;
try {
auth = await accounts();
} catch {
} catch (e) {
await recordSignInError('ACCOUNTS_UNAVAILABLE', (e as Error).message);
return problem(res, 'ACCOUNTS_UNAVAILABLE');
}
let signed;
@@ -168,8 +173,10 @@ async function callback(req: Request, res: Response) {
} catch (e) {
const code = (e as { code?: string }).code;
console.warn('[accounts] sign-in could not finish:', (e as Error).message);
if (code !== 'NO_PENDING') await recordSignInError('FINISH_FAILED', (e as Error).message);
return problem(res, code === 'NO_PENDING' ? 'EXPIRED' : 'FINISH_FAILED');
}
await clearSignInError();
const { claims, returnTo, idToken } = signed;
const found = await userForClaims(claims);
@@ -0,0 +1,32 @@
/**
* How people sign in here, for the Hub (3.5.0, heartbeat `stats.signIn`, contracts 1.13.0): the
* mode, the Accounts this site is linked to, and the last sign-in that failed to start or finish.
* A site in `accounts` mode without a link can't sign anyone in; the Hub raises an alert for it.
*/
import { accountsLink } from './client';
import { authMode, getSetting, setSetting } from './mode';
export const LAST_ERROR_KEY = 'accounts_last_signin_error';
type LastError = { at: string; code: string; message: string };
/** Keeps the last failure (a code and a sentence; never tokens or cookies). */
export async function recordSignInError(code: string, message: string, now = new Date()): Promise<void> {
const value: LastError = { at: now.toISOString(), code: code.slice(0, 60), message: message.replace(/\s+/g, ' ').slice(0, 500) };
await setSetting(LAST_ERROR_KEY, JSON.stringify(value)).catch(() => {});
}
/** A sign-in that worked clears it. */
export async function clearSignInError(): Promise<void> {
if (await getSetting(LAST_ERROR_KEY).catch(() => null)) await setSetting(LAST_ERROR_KEY, null).catch(() => {});
}
export async function signInStatus(): Promise<{ mode: 'local' | 'accounts'; accounts: { installId: string; url: string } | null; lastError: LastError | null }> {
const [mode, link, raw] = await Promise.all([authMode(), accountsLink(), getSetting(LAST_ERROR_KEY).catch(() => null)]);
let lastError: LastError | null = null;
try {
const parsed = raw ? JSON.parse(raw) : null;
if (parsed && typeof parsed.at === 'string' && typeof parsed.code === 'string' && typeof parsed.message === 'string') lastError = parsed;
} catch { /* an unreadable value is no error */ }
return { mode, accounts: link ? { installId: link.installId, url: link.url } : null, lastError };
}
@@ -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 };
+3
View File
@@ -145,10 +145,13 @@ async function stats(now = new Date()) {
const live = await liveNow(now).catch(() => undefined);
const campusesOn = await campusesEnabled().catch(() => false);
const campusCount = campusesOn ? await prisma.campus.count({ where: { archivedAt: null } }) : 0;
// 3.5.0: how people sign in (the Hub flags a site in Accounts mode without a link, or failing).
const signIn = await require('../accounts/status').signInStatus().catch(() => undefined);
return {
users,
events: { active: activeEvents, upcoming: upcomingEvents, total: totalEvents },
...(live ? { live } : {}),
...(signIn ? { signIn } : {}),
registrations: { last30d: regs30, total: regsTotal },
tickets: { last30d: tickets30, total: ticketsTotal },
checkIns: { last30d: checkIns30 },
+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 });
@@ -7,7 +7,9 @@ let mockLink: object | null = null;
jest.mock('../src/links/connect', () => ({ connectTo: async (...args: unknown[]) => { mockConnects.push(args); mockLink = { installId: args[0] }; } }));
jest.mock('../src/links/store', () => ({ linkedProducts: async () => mockListed }));
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => mockLink }));
let mockMode = 'local';
jest.mock('../src/accounts/mode', () => ({
viaAccounts: async () => mockMode === 'accounts',
getSetting: async (k: string) => mockSettings.get(k) ?? null,
setSetting: async (k: string, v: string | null) => { if (v === null) mockSettings.delete(k); else mockSettings.set(k, v); },
}));
@@ -21,6 +23,7 @@ beforeEach(() => {
mockConnects.length = 0;
mockListed = [];
mockLink = null;
mockMode = 'local';
});
test('connects to the Accounts the Hub lists, as the system, once', async () => {
@@ -46,3 +49,13 @@ test('already connected by an admin: just remembers it', async () => {
expect(mockConnects).toEqual([]);
expect(mockSettings.has(AUTO_KEY)).toBe(true);
});
test('3.5.0: a site in Accounts mode that lost its link (a demo load before 3.5.0) connects again', async () => {
mockSettings.set(AUTO_KEY, '2026-11-19T10:00:00.000Z');
mockListed = [{ installId: ACCOUNTS, product: 'accounts' }];
// On its own sign-in, an earlier Disconnect stays.
expect(await connectAccountsIfListed()).toBe('skipped');
mockMode = 'accounts';
expect(await connectAccountsIfListed()).toBe('connected');
expect(mockConnects).toEqual([[ACCOUNTS, { id: null, role: 'system' }, null, expect.any(Date)]]);
});
@@ -0,0 +1,32 @@
// 3.5.0: how people sign in, for the Hub (heartbeat stats.signIn, contracts 1.13.0).
import { hub } from '@crosscode/contracts';
const mockSettings = new Map<string, string>();
let mockMode = 'accounts';
let mockLink: object | null = null;
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => mockLink }));
jest.mock('../src/accounts/mode', () => ({
authMode: async () => mockMode,
getSetting: async (k: string) => mockSettings.get(k) ?? null,
setSetting: async (k: string, v: string | null) => { if (v === null) mockSettings.delete(k); else mockSettings.set(k, v); },
}));
import { clearSignInError, recordSignInError, signInStatus } from '../src/accounts/status';
beforeEach(() => { mockSettings.clear(); mockMode = 'accounts'; mockLink = null; });
test('Accounts mode without a link, and why the last sign-in failed', async () => {
await recordSignInError('ACCOUNTS_UNAVAILABLE', 'Accounts isn\'t connected.\nConnect it under Settings → Linked products.', new Date('2026-11-20T10:00:00.000Z'));
const s = await signInStatus();
expect(s).toEqual({ mode: 'accounts', accounts: null, lastError: { at: '2026-11-20T10:00:00.000Z', code: 'ACCOUNTS_UNAVAILABLE', message: 'Accounts isn\'t connected. Connect it under Settings → Linked products.' } });
// It fits the heartbeat's contract.
expect(hub.eventsStatsSchema.shape.signIn.safeParse(s).success).toBe(true);
await clearSignInError();
expect((await signInStatus()).lastError).toBeNull();
});
test('linked: the Accounts install and its address', async () => {
mockLink = { installId: 'acc-1', url: 'https://accounts.hope.test', secret: 'x', updatedAt: new Date() };
expect((await signInStatus()).accounts).toEqual({ installId: 'acc-1', url: 'https://accounts.hope.test' });
});
+35
View File
@@ -36,6 +36,41 @@ describe('job registry', () => {
warn.mockRestore();
});
test('3.4.0: an admin choice wins over the env flag and schedule; JOBS_ENABLED=false still wins over everything', () => {
const { setOverridesForTest, envEnabled } = require('../src/jobs');
try {
delete process.env.JOBS_ENABLED;
process.env.WAITLIST_JOB_ENABLED = 'false';
process.env.JOB_SCHEDULE_WAITLIST = '*/5 * * * *';
setOverridesForTest({ waitlist: { enabled: true, cron: '*/20 * * * *' }, backup: { enabled: false } });
expect(envEnabled(job('waitlist'))).toBe(false);
expect(isEnabled(job('waitlist'))).toBe(true);
expect(cronFor(job('waitlist'))).toBe('*/20 * * * *');
expect(isEnabled(job('backup'))).toBe(false);
expect(isEnabled(job('temp-cleanup'))).toBe(true); // no env flag, no choice
process.env.JOBS_ENABLED = 'false';
expect(isEnabled(job('waitlist'))).toBe(false);
// A broken saved schedule falls back to the env's.
delete process.env.JOBS_ENABLED;
setOverridesForTest({ waitlist: { cron: 'nonsense' } });
expect(cronFor(job('waitlist'))).toBe('*/5 * * * *');
expect(isEnabled(job('waitlist'))).toBe(false); // the env flag again
} finally {
setOverridesForTest({});
}
});
test('3.4.0: setOverride checks its input before saving', async () => {
const { setOverride, isCron } = require('../src/jobs');
expect(isCron('*/10 * * * *')).toBe(true);
expect(isCron('0 7 * * *')).toBe(true);
expect(isCron('every day')).toBe(false);
expect(isCron('* * * * * *')).toBe(false); // seconds aren't offered
await expect(setOverride('nope', { enabled: true })).rejects.toMatchObject({ statusCode: 404 });
await expect(setOverride('waitlist', { enabled: 'yes' })).rejects.toMatchObject({ statusCode: 400 });
await expect(setOverride('waitlist', { cron: 'every day' })).rejects.toMatchObject({ statusCode: 400 });
});
test('daily jobs fire at local (Johannesburg) time', () => {
// 07:00 SAST = 05:00 UTC
const next = nextRun('0 7 * * *', new Date('2026-11-04T06:00:00Z'));
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "3.3.0",
"version": "3.5.0",
"private": true,
"scripts": {
"dev": "next dev",
@@ -1,16 +1,21 @@
"use client";
import React, { useCallback, useState } from "react";
import { Timer, Play, RefreshCw } from "lucide-react";
import { Timer, Play, RefreshCw, Pencil, RotateCcw } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { useDismissingState } from "@/hooks/useDismissingState";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
import { Switch } from "@/components/ui/switch";
type JobRun = { state: string; createdOn?: string; startedOn: string | null; completedOn: string | null; output: unknown };
type JobInfo = { name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[] };
type JobsResponse = { mode: "queue" | "timers" | "off"; timezone: string; jobs: JobInfo[] };
type Override = { enabled: boolean | null; cron: string | null };
type JobInfo = {
name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[];
envEnabled: boolean; envCron: string; defaultCron: string; override: Override;
};
type JobsResponse = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: JobInfo[] };
const STATE: Record<string, string> = {
completed: "bg-green-50 text-green-800",
@@ -21,12 +26,23 @@ const STATE: Record<string, string> = {
cancelled: "bg-gray-100 text-gray-500",
};
const PRESETS: { label: string; cron: string }[] = [
{ label: "Every minute", cron: "* * * * *" },
{ label: "Every 5 minutes", cron: "*/5 * * * *" },
{ label: "Every 15 minutes", cron: "*/15 * * * *" },
{ label: "Every hour", cron: "0 * * * *" },
{ label: "Daily at 02:00", cron: "0 2 * * *" },
{ label: "Daily at 07:00", cron: "0 7 * * *" },
];
const when = (d: string | null) => (d ? new Date(d).toLocaleString("en-GB", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) : "—");
function describeCron(cron: string): string {
if (cron === "* * * * *") return "Every minute";
const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron);
if (m) return `Every ${m[1]} minutes`;
const h = /^(\d+) \* \* \* \*$/.exec(cron);
if (h) return `Every hour at :${h[1].padStart(2, "0")}`;
const d = /^(\d+) (\d+) \* \* \*$/.exec(cron);
if (d) return `Daily at ${d[2].padStart(2, "0")}:${d[1].padStart(2, "0")}`;
return cron;
@@ -38,13 +54,16 @@ function outputText(run: JobRun): string {
try { return JSON.stringify(run.output); } catch { return ""; }
}
// Settings → Background jobs: what runs when, the last runs of each job, and "Run now".
// Settings → Background jobs: what runs when, the last runs of each job, "Run now", and (3.4.0)
// switching a job on or off and changing its schedule here, over what the server's .env says.
export function JobsTab({ active }: { active: boolean }) {
const { token } = useAuth();
const [data, setData] = useState<JobsResponse | null>(null);
const [loading, setLoading] = useState(true);
const [running, setRunning] = useState<string | null>(null);
const [saving, setSaving] = useState<string | null>(null);
const [open, setOpen] = useState<string | null>(null);
const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null);
const [message, setMessage] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
const load = useCallback(async () => {
@@ -75,6 +94,24 @@ export function JobsTab({ active }: { active: boolean }) {
}
};
/** Saves a choice for one job: a value wins over the .env, null goes back to it. */
const save = async (job: JobInfo, change: { enabled?: boolean | null; cron?: string | null }, done: string) => {
if (!token) return;
setSaving(job.name);
try {
await apiV2Data("put", "/admin/jobs/{name}", { params: { name: job.name }, authToken: token, body: change });
setMessage({ type: "ok", text: done });
setEditing(null);
await load();
} catch (e) {
setMessage({ type: "err", text: errorMessage(e) || "Couldn't save that" });
} finally {
setSaving(null);
}
};
const off = data?.mode === "off";
return (
<div className="space-y-4">
<div className="flex items-start justify-between gap-3">
@@ -82,6 +119,7 @@ export function JobsTab({ active }: { active: boolean }) {
<h2 className="text-lg font-semibold flex items-center gap-2"><Timer className="w-5 h-5 text-brand-600" /> Background jobs</h2>
<p className="text-sm text-gray-500 mt-0.5">
Tasks the server runs on a schedule ({data?.timezone || "local"} time). Each runs once per schedule, even with more than one server process, and failed runs are retried.
Switch a job on or off, or change when it runs: what you choose here wins over the server&apos;s .env and takes effect straight away.
</p>
</div>
<button type="button" onClick={load} disabled={loading} className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded border bg-white hover:bg-gray-50 disabled:opacity-50 shrink-0">
@@ -89,24 +127,37 @@ export function JobsTab({ active }: { active: boolean }) {
</button>
</div>
{message && <div className={`p-3 border rounded text-sm ${message.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`}>{message.text}</div>}
{message && <div role="status" className={`p-3 border rounded text-sm ${message.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`}>{message.text}</div>}
{data?.mode === "timers" && (
<div className="p-3 border rounded bg-amber-50 text-amber-900 text-sm">The job queue couldn&apos;t start, so jobs are running on simple timers in this server process (no retries, history only since the last restart). Check the server log for &quot;[jobs]&quot;.</div>
)}
{data?.mode === "off" && (
<div className="p-3 border rounded bg-gray-50 text-gray-700 text-sm">All background jobs are switched off (JOBS_ENABLED=false).</div>
{off && (
<div className="p-3 border rounded bg-gray-50 text-gray-700 text-sm">All background jobs are switched off in the server&apos;s .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change it from the Hub.</div>
)}
<ul className="divide-y border rounded-lg">
{(data?.jobs || []).map(job => {
const last = job.recent[0];
const busy = saving === job.name;
const enabledHere = job.override.enabled !== null;
const cronHere = job.override.cron !== null;
const isEditing = editing?.name === job.name;
return (
<li key={job.name} className="p-3">
<div className="flex flex-wrap items-center gap-2">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<Switch
checked={job.enabled}
disabled={busy || off}
onCheckedChange={(on) => save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)}
aria-label={`${job.label}: ${job.enabled ? "on" : "off"}`}
/>
<div className="min-w-0 mr-auto">
<div className="font-medium text-sm text-gray-900">{job.label}</div>
<div className={`font-medium text-sm ${job.enabled ? "text-gray-900" : "text-gray-500"}`}>{job.label}</div>
<div className="text-xs text-gray-500">
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : `Off${job.envFlag ? ` (${job.envFlag}=false)` : ""}`}
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : "Off"}
{enabledHere
? <> · {job.enabled ? "switched on" : "switched off"} here <button type="button" disabled={busy} className="underline hover:text-gray-700" onClick={() => save(job, { enabled: null }, `"${job.label}" follows the .env again (${job.envEnabled ? "on" : "off"}).`)}>use the .env ({job.envEnabled ? "on" : "off"})</button></>
: !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""}
</div>
</div>
{last && (
@@ -114,11 +165,43 @@ export function JobsTab({ active }: { active: boolean }) {
{last.state} · {when(last.completedOn || last.startedOn || last.createdOn || null)}
</button>
)}
<button type="button" disabled={running !== null || data?.mode === "off"} onClick={() => runNow(job)}
<button type="button" disabled={busy || isEditing} onClick={() => setEditing({ name: job.name, cron: job.cron })}
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border bg-white hover:bg-gray-50 disabled:opacity-50">
<Pencil className="w-3.5 h-3.5" /> Schedule
</button>
<button type="button" disabled={running !== null || off} onClick={() => runNow(job)}
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border border-brand-200 bg-brand-50 text-brand-700 hover:bg-brand-100 disabled:opacity-50">
<Play className="w-3.5 h-3.5" /> {running === job.name ? "Starting…" : "Run now"}
</button>
</div>
{isEditing && editing && (
<form className="mt-3 rounded border bg-gray-50 p-3 space-y-2" onSubmit={e => { e.preventDefault(); save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}>
<div className="flex flex-wrap gap-1.5">
{PRESETS.map(p => (
<button key={p.cron} type="button" onClick={() => setEditing({ name: job.name, cron: p.cron })}
className={`text-xs px-2 py-1 rounded border ${editing.cron === p.cron ? "bg-brand-50 border-brand-300 text-brand-800" : "bg-white hover:bg-gray-100"}`}>{p.label}</button>
))}
</div>
<div className="flex flex-wrap items-end gap-2">
<label className="text-xs text-gray-600">
Cron (minute hour day month weekday)
<input value={editing.cron} onChange={e => setEditing({ name: job.name, cron: e.target.value })} maxLength={100}
className="mt-1 block w-56 rounded border px-2 py-1 font-mono text-sm" aria-label="Cron schedule" />
</label>
<span className="text-xs text-gray-500 pb-1.5">{describeCron(editing.cron.trim())}</span>
<div className="ml-auto flex gap-2">
<button type="button" onClick={() => setEditing(null)} className="text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-100">Cancel</button>
<button type="submit" disabled={busy || !editing.cron.trim()} className="text-xs px-2.5 py-1.5 rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50">{busy ? "Saving…" : "Save schedule"}</button>
</div>
</div>
<p className="text-xs text-gray-500">
The server&apos;s own schedule for this job is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (set in the .env; normally ${describeCron(job.defaultCron)})` : ""}.
{cronHere && <> <button type="button" disabled={busy} className="inline-flex items-center gap-1 underline hover:text-gray-700" onClick={() => save(job, { cron: null }, `"${job.label}" is back on its own schedule.`)}><RotateCcw className="w-3 h-3" /> Use that again</button></>}
</p>
</form>
)}
{open === job.name && job.recent.length > 0 && (
<table className="mt-2 w-full text-xs">
<thead className="text-gray-500"><tr><th className="text-left font-medium py-1">Started</th><th className="text-left font-medium">Finished</th><th className="text-left font-medium">State</th><th className="text-left font-medium">Result</th></tr></thead>
@@ -139,7 +222,7 @@ export function JobsTab({ active }: { active: boolean }) {
})}
{!loading && data && data.jobs.length === 0 && <li className="p-3 text-sm text-gray-500">No jobs.</li>}
</ul>
<p className="text-xs text-gray-400">Change a schedule with the env var JOB_SCHEDULE_&lt;NAME&gt; (cron, e.g. JOB_SCHEDULE_WAITLIST=&quot;*/5 * * * *&quot;), or switch one off with its own flag.</p>
<p className="text-xs text-gray-400">Without a choice here, the server&apos;s .env applies: each job&apos;s own flag (e.g. WAITLIST_JOB_ENABLED=false) and JOB_SCHEDULE_&lt;NAME&gt;.</p>
</div>
);
}
@@ -61198,11 +61198,15 @@
"properties": {
"mode": {
"type": "string",
"description": "on, off or timers"
"description": "queue, timers or off"
},
"timezone": {
"type": "string"
},
"jobsEnabledEnv": {
"type": "boolean",
"description": "JOBS_ENABLED in the .env"
},
"jobs": {
"type": "array",
"items": {
@@ -61229,6 +61233,38 @@
"null"
]
},
"envEnabled": {
"type": "boolean",
"description": "What the .env says"
},
"envCron": {
"type": "string"
},
"defaultCron": {
"type": "string"
},
"override": {
"type": "object",
"properties": {
"enabled": {
"type": [
"boolean",
"null"
]
},
"cron": {
"type": [
"string",
"null"
]
}
},
"required": [
"enabled"
],
"additionalProperties": {},
"description": "What an admin chose over the .env (null: the .env applies)"
},
"nextRun": {
"anyOf": [
{
@@ -61254,6 +61290,10 @@
"name",
"label",
"enabled",
"envEnabled",
"envCron",
"defaultCron",
"override",
"recent"
],
"additionalProperties": {}
@@ -61263,6 +61303,7 @@
"required": [
"mode",
"timezone",
"jobsEnabledEnv",
"jobs"
],
"additionalProperties": {}
@@ -61299,6 +61340,157 @@
}
}
},
"/admin/jobs/{name}": {
"put": {
"tags": [
"Admin"
],
"summary": "Switch a background job on or off, or change its schedule",
"description": "**Who:** Admins only.",
"operationId": "putAdminJobsName",
"security": [
{
"bearerAuth": []
}
],
"parameters": [
{
"name": "name",
"in": "path",
"required": true,
"description": "The name",
"schema": {
"type": "string",
"minLength": 1,
"maxLength": 100
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"enabled": {
"description": "true or false wins over the .env; null goes back to it",
"type": [
"boolean",
"null"
]
},
"cron": {
"description": "A cron schedule (five fields) that wins over the .env; null or empty goes back to it",
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
}
}
}
}
}
},
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"override": {
"type": "object",
"properties": {
"enabled": {
"type": [
"boolean",
"null"
]
},
"cron": {
"type": [
"string",
"null"
]
}
},
"required": [
"enabled"
],
"additionalProperties": {}
}
},
"required": [
"name",
"override"
],
"additionalProperties": {}
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
},
"400": {
"description": "Validation failed (VALIDATION_FAILED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"401": {
"description": "Not signed in (UNAUTHENTICATED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Not allowed for this role (FORBIDDEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"404": {
"description": "Not found (NOT_FOUND)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/admin/jobs/{name}/run": {
"post": {
"tags": [
+114 -1
View File
@@ -6290,6 +6290,26 @@ export interface paths {
patch?: never;
trace?: never;
};
"/admin/jobs/{name}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
/**
* Switch a background job on or off, or change its schedule
* @description **Who:** Admins only.
*/
put: operations["putAdminJobsName"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/admin/jobs/{name}/run": {
parameters: {
query?: never;
@@ -35118,15 +35138,28 @@ export interface operations {
content: {
"application/json": {
data: {
/** @description on, off or timers */
/** @description queue, timers or off */
mode: string;
timezone: string;
/** @description JOBS_ENABLED in the .env */
jobsEnabledEnv: boolean;
jobs: ({
name: string;
label: string;
cron?: string | null;
enabled: boolean;
envFlag?: string | null;
/** @description What the .env says */
envEnabled: boolean;
envCron: string;
defaultCron: string;
/** @description What an admin chose over the .env (null: the .env applies) */
override: {
enabled: boolean | null;
cron?: string | null;
} & {
[key: string]: unknown;
};
nextRun?: string | null;
/** @description Recent runs */
recent: {
@@ -35161,6 +35194,86 @@ export interface operations {
};
};
};
putAdminJobsName: {
parameters: {
query?: never;
header?: never;
path: {
/** @description The name */
name: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** @description true or false wins over the .env; null goes back to it */
enabled?: boolean | null;
/** @description A cron schedule (five fields) that wins over the .env; null or empty goes back to it */
cron?: string | null;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
name: string;
override: {
enabled: boolean | null;
cron?: string | null;
} & {
[key: string]: unknown;
};
} & {
[key: string]: unknown;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
postAdminJobsNameRun: {
parameters: {
query?: never;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events",
"version": "3.3.0",
"version": "3.5.0",
"main": "index.js",
"scripts": {
"dev:backend": "cd backend && npm run dev",
+19 -6
View File
@@ -10,13 +10,13 @@ separately below; the two often differ.
| What | Repo | Latest | Tag | Released |
|------|------|--------|-----|----------|
| Cross Events | `crosscode-platform` (`apps/events`) | **3.3.0** | `events@3.3.0` | 2026-11-20 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.3.0** | `accounts@1.3.0` | 2026-11-20 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.2.0** | `agent@1.2.0` | 2026-11-19 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.11.0** | `contracts@1.11.0` | 2026-11-20 |
| Cross Code Hub | `events-hub` | **2.7.1** | `v2.7.1` | 2026-11-19 |
| Cross Events | `crosscode-platform` (`apps/events`) | **3.5.0** | `events@3.5.0` | 2026-11-20 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.4.0** | `accounts@1.4.0` | 2026-11-20 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.3.1** | `agent@1.3.1` | 2026-11-20 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.13.0** | `contracts@1.13.0` | 2026-11-20 |
| Cross Code Hub | `events-hub` | **2.9.0** | `v2.9.0` | 2026-11-20 |
| crosscode.co.za | `crosscode-site` | **1.6.0** | `v1.6.0` | 2026-11-19 |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-19 (last change) |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-20 (last change: `crosscode env`) |
The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main`
on each run, so merging to `main` and pushing releases it. Its changes are listed in
@@ -37,6 +37,19 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for
- **Events 3.5.0 + contracts 1.13.0 + agent 1.3.1 + Hub 2.9.0:** loading demo data no longer deletes
the Accounts link (on events-demo nobody could sign in); a site in Accounts mode without a link
reconnects at its next heartbeat; the heartbeat says how the site signs in and the last failure,
and the Hub alerts when it isn't linked, is linked wrongly or sign-ins fail. **Agent 1.3.0
reported itself as 1.2.0**, so the Hub refused its .env jobs: install 1.3.1. No migrations.
- **Events 3.4.0 + Accounts 1.4.0 + contracts 1.12.0 + agent 1.3.0 + Hub 2.8.0:** background jobs
switched on and off (and rescheduled) from each site's admin, over the .env (saved in the
database, no migration); Accounts' emails styled as Cross Events'; the Hub shows an install's
.env (secrets only as set or not) and changes plain values with a restart or frontend rebuild
(`env-read` / `env-set` jobs, `crosscode env`; the file is put back if the site doesn't start).
The Hub's .env panel needs agent 1.3.0 on the server. No migrations.
- **Events 3.3.0 + Accounts 1.3.0 + contracts 1.11.0:** Accounts' pages in Cross Events' layout
(sidebar, a page per section), quick links to the church's sites, nightly backups (Admin →
Backups; needs `pg_dump` on the server), a fuller built-in privacy notice, a fixed favicon.
+7 -6
View File
@@ -46,7 +46,7 @@
},
"apps/accounts/backend": {
"name": "@crosscode/accounts-backend",
"version": "1.3.0",
"version": "1.4.0",
"hasInstallScript": true,
"dependencies": {
"@crosscode/contracts": "*",
@@ -54,6 +54,7 @@
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
"cron-parser": "^5.10.2",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"express-rate-limit": "^8.6.2",
@@ -82,7 +83,7 @@
},
"apps/accounts/frontend": {
"name": "@crosscode/accounts-frontend",
"version": "1.3.0",
"version": "1.4.0",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/ui": "*",
@@ -108,7 +109,7 @@
},
"apps/agent": {
"name": "@crosscode/agent",
"version": "1.2.0",
"version": "1.3.1",
"license": "UNLICENSED",
"dependencies": {
"@crosscode/contracts": "*",
@@ -127,7 +128,7 @@
},
"apps/events/backend": {
"name": "@crosscode/events-backend",
"version": "3.3.0",
"version": "3.5.0",
"hasInstallScript": true,
"dependencies": {
"@cj-tech-master/excelts": "^10.2.0",
@@ -177,7 +178,7 @@
},
"apps/events/frontend": {
"name": "@crosscode/events-frontend",
"version": "3.3.0",
"version": "3.5.0",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
@@ -21275,7 +21276,7 @@
},
"packages/contracts": {
"name": "@crosscode/contracts",
"version": "1.11.0",
"version": "1.13.0",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/contracts",
"version": "1.11.0",
"version": "1.13.0",
"description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads",
"license": "UNLICENSED",
"type": "commonjs",
+244
View File
@@ -854,6 +854,250 @@
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.agent-job/1"
},
"id": {
"type": "string",
"pattern": "^job_[A-Za-z0-9_-]{8,64}$"
},
"serverId": {
"type": "string",
"pattern": "^srv_[A-Za-z0-9_-]{8,64}$"
},
"config": {
"anyOf": [
{
"type": "object",
"properties": {
"alg": {
"type": "string",
"const": "x25519-hkdf-sha256-aes-256-gcm"
},
"epk": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{43}$"
},
"iv": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{16}$"
},
"ciphertext": {
"type": "string",
"maxLength": 200000,
"pattern": "^[A-Za-z0-9_-]+$"
}
},
"required": [
"alg",
"epk",
"iv",
"ciphertext"
],
"additionalProperties": false
},
{
"type": "null"
}
]
},
"notBefore": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"expiresAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"signature": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{86}$"
},
"type": {
"type": "string",
"const": "env-read"
},
"args": {
"type": "object",
"properties": {
"church": {
"type": "string",
"pattern": "^[a-z][a-z0-9-]{1,30}$"
},
"product": {
"type": "string",
"enum": [
"events",
"website",
"app",
"accounts"
]
}
},
"required": [
"church",
"product"
],
"additionalProperties": false
}
},
"required": [
"schema",
"id",
"serverId",
"notBefore",
"expiresAt",
"signature",
"type",
"args"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.agent-job/1"
},
"id": {
"type": "string",
"pattern": "^job_[A-Za-z0-9_-]{8,64}$"
},
"serverId": {
"type": "string",
"pattern": "^srv_[A-Za-z0-9_-]{8,64}$"
},
"config": {
"anyOf": [
{
"type": "object",
"properties": {
"alg": {
"type": "string",
"const": "x25519-hkdf-sha256-aes-256-gcm"
},
"epk": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{43}$"
},
"iv": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{16}$"
},
"ciphertext": {
"type": "string",
"maxLength": 200000,
"pattern": "^[A-Za-z0-9_-]+$"
}
},
"required": [
"alg",
"epk",
"iv",
"ciphertext"
],
"additionalProperties": false
},
{
"type": "null"
}
]
},
"notBefore": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"expiresAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"signature": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{86}$"
},
"type": {
"type": "string",
"const": "env-set"
},
"args": {
"type": "object",
"properties": {
"church": {
"type": "string",
"pattern": "^[a-z][a-z0-9-]{1,30}$"
},
"product": {
"type": "string",
"enum": [
"events",
"website",
"app",
"accounts"
]
},
"file": {
"type": "string",
"maxLength": 100,
"pattern": "^(backend|frontend)\\/\\.env(\\.production)?$"
},
"set": {
"type": "object",
"propertyNames": {
"type": "string",
"maxLength": 100,
"pattern": "^[A-Z][A-Z0-9_]*$"
},
"additionalProperties": {
"type": "string",
"maxLength": 4000,
"pattern": "^[^\\r\\n]*$"
}
},
"unset": {
"maxItems": 50,
"type": "array",
"items": {
"type": "string",
"maxLength": 100,
"pattern": "^[A-Z][A-Z0-9_]*$"
}
},
"restart": {
"type": "boolean"
}
},
"required": [
"church",
"product",
"file",
"set",
"unset",
"restart"
],
"additionalProperties": false
}
},
"required": [
"schema",
"id",
"serverId",
"notBefore",
"expiresAt",
"signature",
"type",
"args"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
@@ -25,6 +25,8 @@
"adopt-undo",
"restart",
"seed-demo",
"env-read",
"env-set",
"export",
"uninstall",
"purge",
@@ -324,6 +324,77 @@
"eventsNow",
"checkInsLastHour"
]
},
"signIn": {
"type": "object",
"properties": {
"mode": {
"type": "string",
"enum": [
"local",
"accounts"
]
},
"accounts": {
"anyOf": [
{
"type": "object",
"properties": {
"installId": {
"type": "string",
"maxLength": 100
},
"url": {
"type": "string",
"maxLength": 500
}
},
"required": [
"installId",
"url"
]
},
{
"type": "null"
}
]
},
"lastError": {
"anyOf": [
{
"type": "object",
"properties": {
"at": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"code": {
"type": "string",
"maxLength": 60
},
"message": {
"type": "string",
"maxLength": 500
}
},
"required": [
"at",
"code",
"message"
]
},
{
"type": "null"
}
]
}
},
"required": [
"mode",
"accounts",
"lastError"
]
}
},
"required": [
+76 -2
View File
@@ -62,6 +62,25 @@ export type DemoProfile = z.infer<typeof demoProfileSchema>;
/** The first agent that runs `seed-demo` jobs (an older one refuses the unknown type). */
export const SEED_DEMO_MIN_AGENT = "1.2.0";
/** The first agent that runs `env-read` and `env-set` jobs (an older one refuses the unknown types). */
export const ENV_JOBS_MIN_AGENT = "1.3.0";
/** A .env variable's name. */
export const envNameSchema = z.string().max(100).regex(/^[A-Z][A-Z0-9_]*$/, "Expected an env variable name (A-Z, 0-9, _)");
/** A product's .env file, relative to `apps/<product>`: `backend/.env`, `frontend/.env.production`. */
export const envFileSchema = z.string().max(100).regex(/^(backend|frontend)\/\.env(\.production)?$/, "Expected backend/.env or frontend/.env.production");
/**
* Names whose values are secrets: never shown on the Hub (only whether they're set) and never
* changed from it. Keep in step with SECRET_NAME in scripts/lib/envedit.cjs.
*/
export const SECRET_ENV_NAME = /(SECRET|PASS|TOKEN|PRIVATE|CREDENTIAL|_KEY$|_DSN$|DATABASE_URL|ADMIN_URL)/;
export const isSecretEnvName = (name: string): boolean => SECRET_ENV_NAME.test(name);
/** At most this many changes in one `env-set` job. */
export const ENV_SET_MAX = 50;
/** Each job type and the arguments it takes. Unknown keys are refused, not stripped. */
export const jobArgsSchemas = {
/** `crosscode install <church> --products … --frp --json` */
@@ -95,6 +114,35 @@ export const jobArgsSchemas = {
* marked as demo sites. `adminEmail`: the account kept (default: the release's own choice).
*/
"seed-demo": z.strictObject({ church: shortNameSchema, profile: demoProfileSchema, adminEmail: z.email().max(254).optional() }),
/**
* `crosscode env <church> <product> --json`: the product's .env values, secrets hidden (only
* whether they're set). The report's `result` is an {@link envReadResultSchema}.
*/
"env-read": z.strictObject({ church: shortNameSchema, product: productSchema }),
/**
* `crosscode env <church> <product> --file <file> --set NAME=value … --unset NAME … [--restart]
* --json`: changes values in one .env file (a copy is kept first), rebuilds the frontend when its
* file changed (Next.js builds the values in), then reloads; on a failure the file is put back.
* Never secrets, never what the server generates (DATABASE_URL, JWT_SECRET …): the script
* refuses those too.
*/
"env-set": z.strictObject({
church: shortNameSchema,
product: productSchema,
file: envFileSchema,
set: z.record(envNameSchema, z.string().max(4000).regex(/^[^\r\n]*$/, "Values can't contain newlines")),
unset: z.array(envNameSchema).max(ENV_SET_MAX),
restart: z.boolean(),
}).check((ctx) => {
const a = ctx.value;
const names = [...Object.keys(a.set), ...a.unset];
const issue = (message: string) => ctx.issues.push({ code: "custom", message, input: a });
if (names.length === 0) issue("Nothing to change");
if (names.length > ENV_SET_MAX) issue(`At most ${ENV_SET_MAX} changes at a time`);
const secret = names.find(isSecretEnvName);
if (secret) issue(`${secret} is a secret: it can't be changed from the Hub`);
if (a.unset.some((n) => Object.prototype.hasOwnProperty.call(a.set, n))) issue("A name can't be both set and removed");
}),
/** `crosscode export <church> --out <zip> --json`; the agent encrypts the ZIP and uploads it under `exportId`. */
export: z.strictObject({ church: shortNameSchema, exportId: z.string().regex(/^exp_[A-Za-z0-9_-]{8,64}$/) }),
/** `crosscode uninstall <church> --json` */
@@ -119,7 +167,7 @@ export const CENTRAL_JOB_TYPES: readonly JobType[] = ["check-ports", "status", "
/** Time limits per job type, in minutes (§3). A job past it is stopped and reported as failed. */
export const JOB_TIME_LIMIT_MINUTES: Record<JobType, number> = {
install: 30, "add-product": 30, deploy: 20, adopt: 30, "adopt-undo": 15, restart: 5, "seed-demo": 15, export: 20,
install: 30, "add-product": 30, deploy: 20, adopt: 30, "adopt-undo": 15, restart: 5, "seed-demo": 15, "env-read": 2, "env-set": 20, export: 20,
uninstall: 20, purge: 10, "update-agent": 15, "check-ports": 2, status: 3,
};
@@ -164,7 +212,7 @@ function jobOf<T extends JobType>(type: T) {
export const agentJobSchema = z.discriminatedUnion("type", [
jobOf("install"), jobOf("add-product"), jobOf("deploy"), jobOf("adopt"), jobOf("adopt-undo"), jobOf("restart"), jobOf("seed-demo"),
jobOf("export"), jobOf("uninstall"), jobOf("purge"), jobOf("update-agent"), jobOf("check-ports"), jobOf("status"),
jobOf("env-read"), jobOf("env-set"), jobOf("export"), jobOf("uninstall"), jobOf("purge"), jobOf("update-agent"), jobOf("check-ports"), jobOf("status"),
]);
export type AgentJob = z.infer<typeof agentJobSchema>;
export type UnsignedAgentJob = Omit<AgentJob, "signature">;
@@ -321,6 +369,32 @@ export const envTemplateSchema = z.object({
});
export type EnvTemplate = z.infer<typeof envTemplateSchema>;
// ---------------------------------------------------------------------------------------------
// Reading an install's .env (the env-read job, contracts 1.12.0)
// ---------------------------------------------------------------------------------------------
/** One variable in an `env-read` result. `value` is null for a secret (`set` says whether it has one). */
export const envReadVariableSchema = z.object({
name: envNameSchema,
value: z.string().max(4000).nullable(),
secret: z.boolean(),
set: z.boolean(),
/** From the release's env template (null when the template doesn't list it). */
layer: envLayerSchema.nullable(),
description: z.string().max(400).nullable(),
/** Whether the Hub may change it: not secret, not generated on the server. */
editable: z.boolean(),
});
export type EnvReadVariable = z.infer<typeof envReadVariableSchema>;
/** The `result` of an `env-read` report: each of the product's .env files, variables in file order. */
export const envReadResultSchema = z.object({
product: productSchema,
files: z.array(z.object({ file: envFileSchema, exists: z.boolean(), variables: z.array(envReadVariableSchema).max(300) })).max(10),
readAt: dateTimeSchema,
});
export type EnvReadResult = z.infer<typeof envReadResultSchema>;
/** The variables a layer must provide for a template, that it doesn't (the Hub's check before a job). */
export function missingRequired(template: EnvTemplate, layer: "server" | "defaults", values: Record<string, string | undefined>): string[] {
const missing: string[] = [];
+12
View File
@@ -196,6 +196,18 @@ export const eventsStatsSchema = z.object({
* 30 minutes), and tickets checked in during the last hour. Optional: older installs don't send it.
*/
live: z.object({ eventsNow: count, checkInsLastHour: count }).optional(),
/**
* 1.13.0: how people sign in, so the Hub can flag a site that can't. `mode`: Cross Events' own
* sign-in or the church's Accounts; `accounts`: the Accounts install it's linked to (null: not
* linked, which with mode `accounts` means nobody can sign in); `lastError`: the last time
* starting or finishing a sign-in failed (cleared by the next one that works). Optional: older
* installs don't send it.
*/
signIn: z.object({
mode: z.enum(["local", "accounts"]),
accounts: z.object({ installId: z.string().max(100), url: z.string().max(500) }).nullable(),
lastError: z.object({ at: dateTimeSchema, code: z.string().max(60), message: z.string().max(500) }).nullable(),
}).optional(),
});
/** Church Website. `storage` is what the extra-storage add-on is billed on (ROADMAP-v3 §10). */
+41
View File
@@ -167,6 +167,47 @@ describe("seed-demo jobs", () => {
});
});
describe("env-read and env-set jobs (1.12.0)", () => {
const set = (a: Record<string, unknown>) => agent.jobArgsSchemas["env-set"].safeParse({ church: "hope", product: "events", file: "backend/.env", set: {}, unset: [], restart: true, ...a });
it("read one product", () => {
expect(agent.jobArgsSchemas["env-read"].safeParse({ church: "hope", product: "accounts" }).success).toBe(true);
expect(agent.jobArgsSchemas["env-read"].safeParse({ church: "hope", product: "nope" }).success).toBe(false);
expect(agent.JOB_TYPES).toEqual(expect.arrayContaining(["env-read", "env-set"]));
expect(agent.CENTRAL_JOB_TYPES).not.toContain("env-set");
});
it("set plain values in a product's .env file", () => {
expect(set({ set: { FRONTEND_URL: "https://events.hope.test" } }).success).toBe(true);
expect(set({ file: "frontend/.env.production", set: { NEXT_PUBLIC_API_URL: "https://events.hope.test" }, unset: ["OLD_THING"] }).success).toBe(true);
});
it("refuse secrets, nothing to do, newlines, other files and bad names", () => {
expect(set({}).success).toBe(false);
for (const name of ["JWT_SECRET", "DATABASE_URL", "SMTP_PASS", "HUB_LICENCE_KEY", "SENTRY_DSN", "DB_ADMIN_URL"]) {
expect(set({ set: { [name]: "x" } }).success).toBe(false);
expect(set({ unset: [name] }).success).toBe(false);
}
expect(set({ set: { A_URL: "x\nEVIL=1" } }).success).toBe(false);
expect(set({ file: "../.env", set: { A: "1" } }).success).toBe(false);
expect(set({ set: { "lower": "1" } }).success).toBe(false);
expect(set({ set: { A: "1" }, unset: ["A"] }).success).toBe(false);
expect(set({ set: { A: "1" }, extra: true }).success).toBe(false);
});
it("tell secrets by name", () => {
expect(agent.isSecretEnvName("ACCOUNTS_SECRET")).toBe(true);
expect(agent.isSecretEnvName("FRONTEND_URL")).toBe(false);
expect(agent.isSecretEnvName("JOBS_ENABLED")).toBe(false);
});
it("read results", () => {
const ok = agent.envReadResultSchema.safeParse({
product: "events", readAt: "2026-11-20T10:00:00.000Z",
files: [{ file: "backend/.env", exists: true, variables: [
{ name: "FRONTEND_URL", value: "https://events.hope.test", secret: false, set: true, layer: "install", description: null, editable: true },
{ name: "JWT_SECRET", value: null, secret: true, set: true, layer: "generated", description: "never change it", editable: false },
] }],
});
expect(ok.success).toBe(true);
});
});
describe("env templates", () => {
it("lists the required server and defaults values that are missing", () => {
const template = agent.envTemplateSchema.parse({
+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"
}