diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c4c258..2eaab57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,25 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). +## 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 ` 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. diff --git a/apps/accounts/CHANGELOG.md b/apps/accounts/CHANGELOG.md index d45a8fc..724a3ca 100644 --- a/apps/accounts/CHANGELOG.md +++ b/apps/accounts/CHANGELOG.md @@ -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_`. 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. diff --git a/apps/accounts/backend/package.json b/apps/accounts/backend/package.json index 006ae04..ae68b53 100644 --- a/apps/accounts/backend/package.json +++ b/apps/accounts/backend/package.json @@ -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", diff --git a/apps/accounts/backend/src/accounts/service.ts b/apps/accounts/backend/src/accounts/service.ts index fcd2243..51c7a31 100644 --- a/apps/accounts/backend/src/accounts/service.ts +++ b/apps/accounts/backend/src/accounts/service.ts @@ -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'); diff --git a/apps/accounts/backend/src/admin/routes.ts b/apps/accounts/backend/src/admin/routes.ts index f69ad92..1311303 100644 --- a/apps/accounts/backend/src/admin/routes.ts +++ b/apps/accounts/backend/src/admin/routes.ts @@ -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) => { diff --git a/apps/accounts/backend/src/interaction/routes.ts b/apps/accounts/backend/src/interaction/routes.ts index a657097..2712921 100644 --- a/apps/accounts/backend/src/interaction/routes.ts +++ b/apps/accounts/backend/src/interaction/routes.ts @@ -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 }; })); diff --git a/apps/accounts/backend/src/jobs.ts b/apps/accounts/backend/src/jobs.ts index cf6bb83..ab554ff 100644 --- a/apps/accounts/backend/src/jobs.ts +++ b/apps/accounts/backend/src/jobs.ts @@ -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_) 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 }; +export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise }; 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> { - 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; + history: Map; + overrides: Record; + 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> { + 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_, 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> { + 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(); + 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) ?? [], + }; + }), + }; +} diff --git a/apps/accounts/backend/src/lib/emails.ts b/apps/accounts/backend/src/lib/emails.ts new file mode 100644 index 0000000..384e8c2 --- /dev/null +++ b/apps/accounts/backend/src/lib/emails.ts @@ -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, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); + +/** 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 { + 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 + ? `${esc(b.name)}` + : `

${esc(b.name)}

`; + const contact = [ + esc(b.name), + b.email ? `${esc(b.email)}` : '', + b.phone ? esc(b.phone) : '', + ].filter(Boolean).join(' • '); + return ` + + + + + +${esc(b.name)} + + +
${esc(preheader)}‌ ‌ ‌ 
+ + +
+ + + + +
+ ${header} +

Your ${esc(b.name)} account

+
+
+ ${body} +
+
+

${contact}

+

You're getting this because you have an account with ${esc(b.name)}, used to sign in to its sites.

+
+
+ +`; +} + +const title = (t: string, sub?: string) => + `

${esc(t)}

` + + (sub ? `

${esc(sub)}

` : ''); +const hello = (name?: string | null) => `

Hello ${esc(name || 'there')},

`; +const para = (html: string) => `

${html}

`; +const divider = () => `
`; +const small = (html: string) => `

${html}

`; + +function button(b: Brand, label: string, url: string): string { + const href = esc(safeUrl(url)); + return ` + +
+ ${esc(label)} +
+

Or copy this link: ${esc(url)}

`; +} + +/** 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 `
${html}
`; +} + +const code6 = (code: string) => + `

${esc(code)}

`; + +const contactLine = (b: Brand) => (b.email ? ` at ${esc(b.email)}` : ''); + +// ─── 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 { + 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 ${o.minutes} minutes.`) + + 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 { + 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 ${o.minutes} minutes, 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 { + 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 ${o.days} days. After that, use Forgot your password? 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 { + 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 { + const b = await brand(ctx); + const body = title('Your sign-in email address changed') + + hello(o.name) + + para(`Your account now signs in with ${esc(o.newEmail)}. Emails about your account go there from now on.`) + + callout(`Wasn't you? 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 { + 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 ${o.days} days, 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 { + 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.') }; +} diff --git a/apps/accounts/backend/src/lib/messages.ts b/apps/accounts/backend/src/lib/messages.ts index 6fc1d8e..a39d233 100644 --- a/apps/accounts/backend/src/lib/messages.ts +++ b/apps/accounts/backend/src/lib/messages.ts @@ -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 { @@ -112,7 +113,7 @@ export class LiveMessenger implements Messenger { async emailWith(settings: SmtpTry, msg: Email): Promise { 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 { diff --git a/apps/accounts/backend/src/links/requests.ts b/apps/accounts/backend/src/links/requests.ts index 261e19c..4109f31 100644 --- a/apps/accounts/backend/src/links/requests.ts +++ b/apps/accounts/backend/src/links/requests.ts @@ -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 }) }); diff --git a/apps/accounts/backend/src/me/routes.ts b/apps/accounts/backend/src/me/routes.ts index 3164021..637bf9c 100644 --- a/apps/accounts/backend/src/me/routes.ts +++ b/apps/accounts/backend/src/me/routes.ts @@ -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); diff --git a/apps/accounts/backend/src/privacy/export.ts b/apps/accounts/backend/src/privacy/export.ts index 79bc34e..d485e53 100644 --- a/apps/accounts/backend/src/privacy/export.ts +++ b/apps/accounts/backend/src/privacy/export.ts @@ -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; } diff --git a/apps/accounts/backend/tests/jobsAndEmails.test.ts b/apps/accounts/backend/tests/jobsAndEmails.test.ts new file mode 100644 index 0000000..b50595c --- /dev/null +++ b/apps/accounts/backend/tests/jobsAndEmails.test.ts @@ -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 & 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: 'Jane', 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 <Church> & Co/); + assert.ok(!r.html.includes('Jane')); + 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 & Co'); + assert.ok(!n.html.includes('href="javascript:')); + assert.equal(esc('"x"'), '"x"'); + }); + + 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 ?? '', //); + }); +}); diff --git a/apps/accounts/frontend/package.json b/apps/accounts/frontend/package.json index c90c7c3..c5c55f9 100644 --- a/apps/accounts/frontend/package.json +++ b/apps/accounts/frontend/package.json @@ -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": { diff --git a/apps/accounts/frontend/src/app/admin/Admin.tsx b/apps/accounts/frontend/src/app/admin/Admin.tsx index 187d266..97cbeb7 100644 --- a/apps/accounts/frontend/src/app/admin/Admin.tsx +++ b/apps/accounts/frontend/src/app/admin/Admin.tsx @@ -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" && } {section === "notice" && } {section === "backups" && } + {section === "jobs" && } {section === "licence" && } {section === "audit" && } @@ -463,3 +464,162 @@ function Backups({ flash }: { flash: Flash }) { ); } + +// ─── 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 = { + 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 ( + + ); +} + +function Jobs({ flash }: { flash: Flash }) { + const [data, setData] = useState(null); + const [busy, setBusy] = useState(null); + const [open, setOpen] = useState(null); + const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null); + const [loadError, setLoadError] = useState(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("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 ? {loadError} :

Loading…

; + const off = data.mode === "off"; + return ( + +
+ } sub={`Times are ${data.timezone}. Each job runs once per schedule, however many server processes there are.`}>Jobs + +
+ {off && All background jobs are switched off in the server's .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change that from the Hub.} + {data.mode === "timers" && The job queue couldn't start, so jobs run on simple timers in this process (history only since the last restart).} +
    + {data.jobs.map((job) => { + const last = job.recent[0]; + const mine = busy === job.name; + const isEditing = editing?.name === job.name; + return ( +
  • +
    + void save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)} /> +
    +
    {job.label}
    +
    + {job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : "Off"} + {job.override.enabled !== null + ? <> · {job.enabled ? "switched on" : "switched off"} here · + : !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""} +
    +
    + {last && ( + + )} + + +
    + {isEditing && editing && ( +
    { e.preventDefault(); void save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}> +
    + {SCHEDULES.map((p) => ( + + ))} +
    +
    + setEditing({ name: job.name, cron: e.target.value })} hint={describeCron(editing.cron.trim())} /> +
    + + +
    +
    +

    + The server's own schedule is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (from the .env; normally ${describeCron(job.defaultCron)})` : ""}.{" "} + {job.override.cron !== null && } +

    +
    + )} + {open === job.name && job.recent.length > 0 && ( +
    + + + + {job.recent.map((r, i) => ( + + + + + + + ))} + +
    StartedFinishedStateResult
    {when(r.startedOn)}{when(r.completedOn)}{r.state}{runText(r)}
    +
    + )} +
  • + ); + })} +
+

Without a choice here, the server's .env applies: a job's own flag (e.g. BACKUP_ENABLED=false) and JOB_SCHEDULE_<NAME>. The nightly backup also follows Backups → "Back up every night".

+
+ ); +} diff --git a/apps/accounts/frontend/src/components/AppShell.tsx b/apps/accounts/frontend/src/components/AppShell.tsx index ac99484..407cb4a 100644 --- a/apps/accounts/frontend/src/components/AppShell.tsx +++ b/apps/accounts/frontend/src/components/AppShell.tsx @@ -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 }, ]; diff --git a/apps/accounts/frontend/src/lib/sections.ts b/apps/accounts/frontend/src/lib/sections.ts index 0d44af5..d1f976e 100644 --- a/apps/accounts/frontend/src/lib/sections.ts +++ b/apps/accounts/frontend/src/lib/sections.ts @@ -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; diff --git a/apps/agent/package.json b/apps/agent/package.json index 5d33b6a..bf801e3 100644 --- a/apps/agent/package.json +++ b/apps/agent/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/agent", - "version": "1.2.0", + "version": "1.3.0", "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", diff --git a/apps/agent/src/command.ts b/apps/agent/src/command.ts index 1bf9ab0..0b3c40d 100644 --- a/apps/agent/src/command.ts +++ b/apps/agent/src/command.ts @@ -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": diff --git a/apps/agent/tests/command.test.ts b/apps/agent/tests/command.test.ts index bf7904b..2c7e2da 100644 --- a/apps/agent/tests/command.test.ts +++ b/apps/agent/tests/command.test.ts @@ -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"]); diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md index d49c861..5b1a769 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -5,6 +5,24 @@ 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.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_`), 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 diff --git a/apps/events/backend/package.json b/apps/events/backend/package.json index cd9c2ab..29397cc 100644 --- a/apps/events/backend/package.json +++ b/apps/events/backend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/events-backend", - "version": "3.3.0", + "version": "3.4.0", "description": "Event Management System Backend", "main": "src/index.js", "scripts": { diff --git a/apps/events/backend/src/controllers/jobsController.js b/apps/events/backend/src/controllers/jobsController.js index 886b694..1cd69d9 100644 --- a/apps/events/backend/src/controllers/jobsController.js +++ b/apps/events/backend/src/controllers/jobsController.js @@ -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 }; diff --git a/apps/events/backend/src/jobs/index.js b/apps/events/backend/src/jobs/index.js index da08cdb..ed46078 100644 --- a/apps/events/backend/src/jobs/index.js +++ b/apps/events/backend/src/jobs/index.js @@ -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_ (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_ 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_, 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_, 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, +}; diff --git a/apps/events/backend/src/v2/resources/adminPrivacy.ts b/apps/events/backend/src/v2/resources/adminPrivacy.ts index bb52820..be3986b 100644 --- a/apps/events/backend/src/v2/resources/adminPrivacy.ts +++ b/apps/events/backend/src/v2/resources/adminPrivacy.ts @@ -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 }); diff --git a/apps/events/backend/tests/jobs.test.js b/apps/events/backend/tests/jobs.test.js index f3f7d54..2aac249 100644 --- a/apps/events/backend/tests/jobs.test.js +++ b/apps/events/backend/tests/jobs.test.js @@ -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')); diff --git a/apps/events/frontend/package.json b/apps/events/frontend/package.json index 784d363..a7cffc5 100644 --- a/apps/events/frontend/package.json +++ b/apps/events/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/events-frontend", - "version": "3.3.0", + "version": "3.4.0", "private": true, "scripts": { "dev": "next dev", diff --git a/apps/events/frontend/src/components/admin/JobsTab.tsx b/apps/events/frontend/src/components/admin/JobsTab.tsx index b0cc349..b6a8464 100644 --- a/apps/events/frontend/src/components/admin/JobsTab.tsx +++ b/apps/events/frontend/src/components/admin/JobsTab.tsx @@ -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 = { completed: "bg-green-50 text-green-800", @@ -21,12 +26,23 @@ const STATE: Record = { 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(null); const [loading, setLoading] = useState(true); const [running, setRunning] = useState(null); + const [saving, setSaving] = useState(null); const [open, setOpen] = useState(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 (
@@ -82,6 +119,7 @@ export function JobsTab({ active }: { active: boolean }) {

Background jobs

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's .env and takes effect straight away.

- {message &&
{message.text}
} + {message &&
{message.text}
} {data?.mode === "timers" && (
The job queue couldn'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 "[jobs]".
)} - {data?.mode === "off" && ( -
All background jobs are switched off (JOBS_ENABLED=false).
+ {off && ( +
All background jobs are switched off in the server's .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change it from the Hub.
)}
    {(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 (
  • -
    +
    + save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)} + aria-label={`${job.label}: ${job.enabled ? "on" : "off"}`} + />
    -
    {job.label}
    +
    {job.label}
    - {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 + : !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""}
    {last && ( @@ -114,11 +165,43 @@ export function JobsTab({ active }: { active: boolean }) { {last.state} · {when(last.completedOn || last.startedOn || last.createdOn || null)} )} - +
    + + {isEditing && editing && ( +
    { e.preventDefault(); save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}> +
    + {PRESETS.map(p => ( + + ))} +
    +
    + + {describeCron(editing.cron.trim())} +
    + + +
    +
    +

    + The server's own schedule for this job is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (set in the .env; normally ${describeCron(job.defaultCron)})` : ""}. + {cronHere && <> } +

    +
    + )} + {open === job.name && job.recent.length > 0 && ( @@ -139,7 +222,7 @@ export function JobsTab({ active }: { active: boolean }) { })} {!loading && data && data.jobs.length === 0 &&
  • No jobs.
  • } -

    Change a schedule with the env var JOB_SCHEDULE_<NAME> (cron, e.g. JOB_SCHEDULE_WAITLIST="*/5 * * * *"), or switch one off with its own flag.

    +

    Without a choice here, the server's .env applies: each job's own flag (e.g. WAITLIST_JOB_ENABLED=false) and JOB_SCHEDULE_<NAME>.

    ); } diff --git a/apps/events/frontend/src/lib/api-v2/openapi.json b/apps/events/frontend/src/lib/api-v2/openapi.json index 24b3bd8..33e2260 100644 --- a/apps/events/frontend/src/lib/api-v2/openapi.json +++ b/apps/events/frontend/src/lib/api-v2/openapi.json @@ -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": [ diff --git a/apps/events/frontend/src/lib/api-v2/schema.d.ts b/apps/events/frontend/src/lib/api-v2/schema.d.ts index 7f1ebb2..9687732 100644 --- a/apps/events/frontend/src/lib/api-v2/schema.d.ts +++ b/apps/events/frontend/src/lib/api-v2/schema.d.ts @@ -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; diff --git a/apps/events/package.json b/apps/events/package.json index 8c7a766..19df283 100644 --- a/apps/events/package.json +++ b/apps/events/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/events", - "version": "3.3.0", + "version": "3.4.0", "main": "index.js", "scripts": { "dev:backend": "cd backend && npm run dev", diff --git a/docs/VERSIONS.md b/docs/VERSIONS.md index cff47fa..7eab1b5 100644 --- a/docs/VERSIONS.md +++ b/docs/VERSIONS.md @@ -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.4.0** | `events@3.4.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.0** | `agent@1.3.0` | 2026-11-20 | +| Contracts | `crosscode-platform` (`packages/contracts`) | **1.12.0** | `contracts@1.12.0` | 2026-11-20 | +| Cross Code Hub | `events-hub` | **2.8.0** | `v2.8.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,13 @@ need their own tags until something outside this repo depends on them. ## What each latest release was for +- **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. diff --git a/package-lock.json b/package-lock.json index 299c3cb..c8444c6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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.0", "license": "UNLICENSED", "dependencies": { "@crosscode/contracts": "*", @@ -127,7 +128,7 @@ }, "apps/events/backend": { "name": "@crosscode/events-backend", - "version": "3.3.0", + "version": "3.4.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.4.0", "dependencies": { "@crosscode/contracts": "*", "@crosscode/seo": "*", @@ -21275,7 +21276,7 @@ }, "packages/contracts": { "name": "@crosscode/contracts", - "version": "1.11.0", + "version": "1.12.0", "license": "UNLICENSED", "dependencies": { "zod": "^4.6.7" diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 8204030..40a376d 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/contracts", - "version": "1.11.0", + "version": "1.12.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", diff --git a/packages/contracts/schemas/agent-job.json b/packages/contracts/schemas/agent-job.json index ead9d38..b37f768 100644 --- a/packages/contracts/schemas/agent-job.json +++ b/packages/contracts/schemas/agent-job.json @@ -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": { diff --git a/packages/contracts/schemas/agent-report.json b/packages/contracts/schemas/agent-report.json index 656e5d8..0f8e8ba 100644 --- a/packages/contracts/schemas/agent-report.json +++ b/packages/contracts/schemas/agent-report.json @@ -25,6 +25,8 @@ "adopt-undo", "restart", "seed-demo", + "env-read", + "env-set", "export", "uninstall", "purge", diff --git a/packages/contracts/src/agent.ts b/packages/contracts/src/agent.ts index 033781b..5da3966 100644 --- a/packages/contracts/src/agent.ts +++ b/packages/contracts/src/agent.ts @@ -62,6 +62,25 @@ export type DemoProfile = z.infer; /** 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/`: `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 --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 --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 --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 --out --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 --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 = { - 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(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; export type UnsignedAgentJob = Omit; @@ -321,6 +369,32 @@ export const envTemplateSchema = z.object({ }); export type EnvTemplate = z.infer; +// --------------------------------------------------------------------------------------------- +// 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; + +/** 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; + /** 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[] { const missing: string[] = []; diff --git a/packages/contracts/tests/agent.test.ts b/packages/contracts/tests/agent.test.ts index c64fa41..5ba6e60 100644 --- a/packages/contracts/tests/agent.test.ts +++ b/packages/contracts/tests/agent.test.ts @@ -167,6 +167,47 @@ describe("seed-demo jobs", () => { }); }); +describe("env-read and env-set jobs (1.12.0)", () => { + const set = (a: Record) => 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({ diff --git a/scripts/crosscode b/scripts/crosscode index 858ee85..8ffab29 100755 --- a/scripts/crosscode +++ b/scripts/crosscode @@ -97,6 +97,7 @@ crosscode: Cross Code installs on this server ($(git -C "${CROSSCODE_FROM:-.}" r crosscode adopt --undo go back to the old folder (within 14 days) crosscode restart [events] reload the PM2 processes crosscode demo --profile replace Events' data with a demo set + crosscode env [--set NAME=value] show or change a product's .env values crosscode export --out the church's data and uploads crosscode uninstall --confirm remove it (a final backup is kept 30 days) crosscode purge --confirm 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\"." ;; diff --git a/scripts/lib/envedit.cjs b/scripts/lib/envedit.cjs new file mode 100644 index 0000000..44690e9 --- /dev/null +++ b/scripts/lib/envedit.cjs @@ -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 --dir --product +// prints a crosscode env-read result (JSON) on stdout. Secrets are never printed: only +// whether they're set. +// node envedit.cjs set --template --dir --file +// [--set NAME=value …] [--unset NAME …] --backup +// 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 --backup +// 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 }; diff --git a/scripts/lib/manage.sh b/scripts/lib/manage.sh index 1e5906c..6bac731 100644 --- a/scripts/lib/manage.sh +++ b/scripts/lib/manage.sh @@ -10,6 +10,11 @@ crosscode demo --profile [--admin-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 the product's .env values (secrets hidden) +crosscode env [--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 --out the church's data (crosscode.church-export/1) and uploads crosscode uninstall --confirm 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 : 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: .before- + 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 diff --git a/scripts/lib/report.sh b/scripts/lib/report.sh index 7dc47d5..ae74f71 100644 --- a/scripts/lib/report.sh +++ b/scripts/lib/report.sh @@ -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="" diff --git a/scripts/tests/envedit.bats b/scripts/tests/envedit.bats new file mode 100644 index 0000000..365070c --- /dev/null +++ b/scripts/tests/envedit.bats @@ -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" +}
    StartedFinishedStateResult