Events 3.4.0, Accounts 1.4.0, contracts 1.12.0, agent 1.3.0: jobs from the dashboard, styled Accounts emails, .env from the Hub
- Events and Accounts: Background jobs are switched on or off and rescheduled from the admin; the choice is kept in the database (job_overrides), wins over the .env and applies at once. Accounts gets an Admin -> Background jobs page and per-job env flags, as Events. - Accounts: every email styled as Cross Events' (church colour, logo, button, footer), same plain text (src/lib/emails.ts). - Contracts 1.12.0: env-read / env-set agent jobs, envReadResultSchema, isSecretEnvName. - crosscode script: `crosscode env <church> <product>` reads the .env (secrets hidden) and, with --set/--unset/--restart, changes one file, rebuilds the frontend when its file changed, reloads, and puts the file back if the site doesn't answer (lib/envedit.cjs, tests/envedit.bats). - Agent 1.3.0: runs env-read and env-set. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,28 @@
|
||||
# Changelog — Accounts
|
||||
|
||||
## [1.4.0] - 2026-11-20
|
||||
|
||||
Works with every Cross Events 3.x and contracts 1.11.0 or later.
|
||||
|
||||
### Added
|
||||
|
||||
- **Admin → Background jobs**, as Cross Events': each job's schedule, next run and last runs,
|
||||
"Run now", and a switch and schedule per job. The choice is saved in the database
|
||||
(`job_overrides`), wins over the .env and applies straight away (other processes within 30 s).
|
||||
New optional .env flags per job, as Events: `EXPORTS_JOB_ENABLED`, `DELETIONS_JOB_ENABLED`,
|
||||
`BACKUP_ENABLED`, `HUB_HEARTBEAT_ENABLED`, and `JOB_SCHEDULE_<NAME>`. API: `GET /api/v2/admin/jobs`,
|
||||
`PUT /api/v2/admin/jobs/:name` `{ enabled, cron }`, `POST /api/v2/admin/jobs/:name/run`.
|
||||
On timers (when the queue can't start) jobs now follow their cron schedule too.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Every email is styled as Cross Events'** (`src/lib/emails.ts`): a header in the church's
|
||||
colour with its logo or name, a button for the link (written out underneath), callouts for
|
||||
warnings, and the church's contact details in the footer. Sign-in codes, password reset, "your
|
||||
account at …", confirm a new email address, "your email address changed", "your data is ready"
|
||||
and the test emails. The plain text is sent too and hasn't changed. Everything put in the HTML is
|
||||
escaped, and only http(s) links are used.
|
||||
|
||||
## [1.3.0] - 2026-11-20
|
||||
|
||||
Needs contracts 1.11.0 (`people.removeDemo`). Works with every Cross Events 3.x.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -22,6 +22,7 @@
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"cron-parser": "^5.10.2",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^5.3.0",
|
||||
"express-rate-limit": "^8.6.2",
|
||||
|
||||
@@ -12,6 +12,7 @@ import { loginEvent } from '../lib/audit.js';
|
||||
import { queueCall } from '../links/deliveries.js';
|
||||
import { currentNoticeVersion } from '../privacy/notice.js';
|
||||
import { SendError } from '../lib/messages.js';
|
||||
import { codeEmail } from '../lib/emails.js';
|
||||
|
||||
export const MAX_FAILED_SIGN_INS = 10;
|
||||
export const LOCK_MINUTES = 15;
|
||||
@@ -122,7 +123,7 @@ export async function sendCode(ctx: Ctx, a: Account, method: 'email' | 'whatsapp
|
||||
}
|
||||
}
|
||||
try {
|
||||
await ctx.messenger.email({ to: a.email, subject: `Your code: ${code}`, text });
|
||||
await ctx.messenger.email({ to: a.email, ...(await codeEmail(ctx, { name: a.name, code, text, purpose, minutes: CODE_MINUTES })) });
|
||||
} catch (e) {
|
||||
console.error('[codes] could not send a code:', (e as Error).message);
|
||||
throw new SendError(`We couldn't send your code: ${churchName}'s email isn't working right now. Please let the church office know, and try again later.`, 'CODE_NOT_SENT');
|
||||
|
||||
@@ -22,6 +22,8 @@ import { builtInNotice, currentNotice, publish } from '../privacy/notice.js';
|
||||
import { licenceStatus } from '../hub/licence.js';
|
||||
import { connect as connectHub } from '../hub/client.js';
|
||||
import { productName } from '../oidc/clients.js';
|
||||
import { JobError, jobStatus, runNow, setOverride } from '../jobs.js';
|
||||
import { testEmail } from '../lib/emails.js';
|
||||
|
||||
const PAGE = 50;
|
||||
|
||||
@@ -200,7 +202,7 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
|
||||
const me = await admin(req, res);
|
||||
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
|
||||
try {
|
||||
await ctx.messenger.email({ to: a.email, subject: 'Test email from Accounts', text: 'Email from Accounts works.' });
|
||||
await ctx.messenger.email({ to: a.email, ...(await testEmail(ctx)) });
|
||||
} catch (e) {
|
||||
throw new ApiError(502, 'NOT_SENT', `The test email couldn't be sent: ${(e as Error).message}`);
|
||||
}
|
||||
@@ -299,6 +301,36 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Background jobs (1.4.0, as Cross Events) ───────────────────────────────
|
||||
|
||||
const jobError = (e: unknown): never => {
|
||||
if (e instanceof JobError) throw new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : e.status === 400 ? 'VALIDATION' : 'JOB_FAILED', e.message);
|
||||
throw e;
|
||||
};
|
||||
|
||||
r.get('/jobs', handle(async (req, res) => {
|
||||
await admin(req, res);
|
||||
return jobStatus(ctx);
|
||||
}));
|
||||
|
||||
// Switch a job on or off, or change its schedule: wins over the .env; null goes back to it.
|
||||
r.put('/jobs/:name', handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
const name = String(req.params.name);
|
||||
const change = { enabled: req.body?.enabled, cron: req.body?.cron };
|
||||
const override = await setOverride(ctx, name, change).catch(jobError);
|
||||
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'job_settings_changed', targetType: 'job', targetId: name, metadata: change, ip: clientIp(req) });
|
||||
return { name, override };
|
||||
}));
|
||||
|
||||
r.post('/jobs/:name/run', limit(20, 60), handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
const name = String(req.params.name);
|
||||
const out = await runNow(ctx, name).catch(jobError);
|
||||
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'job_run_manual', targetType: 'job', targetId: name, metadata: { queued: out.queued }, ip: clientIp(req) });
|
||||
return out;
|
||||
}));
|
||||
|
||||
// ─── Licence, audit ────────────────────────────────────────────────────────
|
||||
|
||||
r.get('/licence', handle(async (req, res) => {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { decodeState, encodeState, safeReturnPath } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError, handle, limit } from '../http.js';
|
||||
import { loginEvent } from '../lib/audit.js';
|
||||
import { resetPasswordEmail } from '../lib/emails.js';
|
||||
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||
import { hashPassword, passwordProblem } from '../lib/passwords.js';
|
||||
import { normaliseEmail } from '../accounts/service.js';
|
||||
@@ -97,11 +98,7 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
|
||||
const token = randomToken();
|
||||
const uid = typeof req.body?.uid === 'string' && /^[A-Za-z0-9_-]{10,64}$/.test(req.body.uid) ? req.body.uid : null;
|
||||
await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), interactionUid: uid, expiresAt: new Date(ctx.now().getTime() + RESET_MINUTES * 60e3) } });
|
||||
await ctx.messenger.email({
|
||||
to: a.email,
|
||||
subject: 'Reset your password',
|
||||
text: `Someone (we hope you) asked to reset the password for your account.\n\nChoose a new password here (the link works for ${RESET_MINUTES} minutes):\n${ctx.config.publicUrl}/reset?token=${token}\n\nIf you didn't ask, you can ignore this email: your password stays the same.`,
|
||||
});
|
||||
await ctx.messenger.email({ to: a.email, ...(await resetPasswordEmail(ctx, { name: a.name, url: `${ctx.config.publicUrl}/reset?token=${token}`, minutes: RESET_MINUTES })) });
|
||||
}
|
||||
return { sent: true };
|
||||
}));
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
/**
|
||||
* Background jobs on pg-boss (as Cross Events): one run per schedule however many processes run,
|
||||
* and timers in this process if the queue can't start. JOBS_ENABLED=false turns them all off.
|
||||
*
|
||||
* 1.4.0 (as Events 3.4.0): Admin → Background jobs shows each job's schedule and last runs, runs
|
||||
* one now, and switches one on or off or changes its schedule. That choice is kept in the
|
||||
* database (`job_overrides`), wins over the .env (a job's own flag, e.g. BACKUP_ENABLED=false, and
|
||||
* JOB_SCHEDULE_<NAME>) and takes effect straight away (in other processes within 30 seconds).
|
||||
*/
|
||||
import { CronExpressionParser } from 'cron-parser';
|
||||
import PgBoss from 'pg-boss';
|
||||
import type { Ctx } from './context.js';
|
||||
import { runBackupJob } from './backups/backups.js';
|
||||
@@ -12,17 +18,17 @@ import { deleteExpired } from './oidc/adapter.js';
|
||||
import { runDeletionJob } from './privacy/deletion.js';
|
||||
import { runExportsJob } from './privacy/export.js';
|
||||
|
||||
type Job = { name: string; cron: string; everyMs: number; run: (ctx: Ctx) => Promise<unknown> };
|
||||
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
|
||||
|
||||
export const JOBS: Job[] = [
|
||||
{ name: 'deliveries', cron: '* * * * *', everyMs: 60e3, run: (ctx) => runDue(ctx) },
|
||||
{ name: 'exports', cron: '*/5 * * * *', everyMs: 5 * 60e3, run: (ctx) => runExportsJob(ctx) },
|
||||
{ name: 'deletions', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => runDeletionJob(ctx) },
|
||||
{ name: 'deliveries', label: 'Linked products: send what they need to know (sign-outs, changes), retrying failures', cron: '* * * * *', env: null, run: (ctx) => runDue(ctx) },
|
||||
{ name: 'exports', label: 'Privacy: make the copies of their data people asked for', cron: '*/5 * * * *', env: 'EXPORTS_JOB_ENABLED', run: (ctx) => runExportsJob(ctx) },
|
||||
{ name: 'deletions', label: 'Privacy: delete the accounts whose deletion is due', cron: '*/15 * * * *', env: 'DELETIONS_JOB_ENABLED', run: (ctx) => runDeletionJob(ctx) },
|
||||
// 1.3.0: a database backup every night (Settings → Backups), as Cross Events.
|
||||
{ name: 'backup', cron: '0 2 * * *', everyMs: 24 * 3600e3, run: (ctx) => runBackupJob(ctx) },
|
||||
{ name: 'hub-heartbeat', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => heartbeat(ctx) },
|
||||
{ name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runBackupJob(ctx) },
|
||||
{ name: 'hub-heartbeat', label: 'Cross Code Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: (ctx) => heartbeat(ctx) },
|
||||
{
|
||||
name: 'cleanup', cron: '17 * * * *', everyMs: 3600e3,
|
||||
name: 'cleanup', label: 'Delete expired sign-ins, codes and links', cron: '17 * * * *', env: null,
|
||||
run: async (ctx) => {
|
||||
const now = ctx.now();
|
||||
const [oidc, pending, tokens, nonces, requests] = await Promise.all([
|
||||
@@ -37,23 +43,261 @@ export const JOBS: Job[] = [
|
||||
},
|
||||
];
|
||||
|
||||
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
|
||||
if (!ctx.config.jobsEnabled) return async () => {};
|
||||
const tz = ctx.config.timezone;
|
||||
const SCHEMA = 'pgboss_accounts';
|
||||
const OVERRIDES_KEY = 'job_overrides';
|
||||
const OVERRIDES_TTL_MS = 30_000;
|
||||
|
||||
export type Override = { enabled?: boolean; cron?: string };
|
||||
type Run = { state: string; createdOn?: Date | null; startedOn: Date | null; completedOn: Date | null; output: unknown };
|
||||
|
||||
/** The running queue or timers, the admin's choices (cached), and a short history for timer mode. */
|
||||
type State = {
|
||||
mode: 'queue' | 'timers' | 'off';
|
||||
boss: PgBoss | null;
|
||||
timers: Map<string, NodeJS.Timeout>;
|
||||
history: Map<string, Run[]>;
|
||||
overrides: Record<string, Override>;
|
||||
overridesAt: number;
|
||||
env: NodeJS.ProcessEnv;
|
||||
};
|
||||
|
||||
const state: State = { mode: 'off', boss: null, timers: new Map(), history: new Map(), overrides: {}, overridesAt: 0, env: process.env };
|
||||
|
||||
/** Tests: a different environment for the env flags and schedules. */
|
||||
export function useEnvForTest(env: NodeJS.ProcessEnv): void {
|
||||
state.env = env;
|
||||
}
|
||||
|
||||
const flag = (name: string | null) => {
|
||||
if (!name) return true;
|
||||
const v = state.env[name];
|
||||
return v === undefined || v === '' ? true : String(v).toLowerCase() !== 'false';
|
||||
};
|
||||
|
||||
export function isCron(cron: unknown, tz = 'Africa/Johannesburg'): cron is string {
|
||||
if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false;
|
||||
try {
|
||||
const boss = new PgBoss({ connectionString, schema: 'pgboss_accounts', application_name: 'crosscode-accounts-jobs' });
|
||||
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
|
||||
await boss.start();
|
||||
for (const job of JOBS) {
|
||||
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
|
||||
await boss.schedule(job.name, job.cron, undefined, { tz });
|
||||
await boss.work(job.name, async () => job.run(ctx));
|
||||
}
|
||||
console.log(`[jobs] Job queue started: ${JOBS.map((j) => j.name).join(', ')}.`);
|
||||
return async () => { await boss.stop({ graceful: true }); };
|
||||
} catch (e) {
|
||||
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
|
||||
const timers = JOBS.map((job) => setInterval(() => { job.run(ctx).catch((err) => console.warn(`[jobs] ${job.name}:`, (err as Error).message)); }, job.everyMs));
|
||||
return async () => { timers.forEach(clearInterval); };
|
||||
CronExpressionParser.parse(cron, { tz });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadOverrides(ctx: Ctx, force = false): Promise<Record<string, Override>> {
|
||||
if (!force && state.overridesAt && Date.now() - state.overridesAt < OVERRIDES_TTL_MS) return state.overrides;
|
||||
try {
|
||||
// Straight from the table: Settings caches for 30 s too, and a save must show at once here.
|
||||
const row = await ctx.db.appSetting.findUnique({ where: { key: OVERRIDES_KEY } });
|
||||
const parsed = row?.value ? JSON.parse(row.value) : {};
|
||||
state.overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
||||
state.overridesAt = Date.now();
|
||||
} catch (e) {
|
||||
if (force) console.warn('[jobs] Could not read the job overrides:', (e as Error).message);
|
||||
}
|
||||
return state.overrides;
|
||||
}
|
||||
|
||||
/** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */
|
||||
export const envEnabled = (job: Job) => flag(job.env);
|
||||
|
||||
/** JOBS_ENABLED=false turns all off; then the admin's choice; then the job's env flag. */
|
||||
export function isEnabled(ctx: Ctx, job: Job): boolean {
|
||||
if (!ctx.config.jobsEnabled) return false;
|
||||
const o = state.overrides[job.name];
|
||||
if (o && typeof o.enabled === 'boolean') return o.enabled;
|
||||
return envEnabled(job);
|
||||
}
|
||||
|
||||
/** The .env's schedule (JOB_SCHEDULE_<NAME>, checked) or the job's own. */
|
||||
export function envCronFor(ctx: Ctx, job: Job): string {
|
||||
const v = state.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`];
|
||||
if (v && isCron(v, ctx.config.timezone)) return v;
|
||||
if (v) console.warn(`[jobs] Ignoring invalid schedule for ${job.name}: "${v}"`);
|
||||
return job.cron;
|
||||
}
|
||||
|
||||
export function cronFor(ctx: Ctx, job: Job): string {
|
||||
const o = state.overrides[job.name];
|
||||
if (o && isCron(o.cron, ctx.config.timezone)) return o.cron;
|
||||
return envCronFor(ctx, job);
|
||||
}
|
||||
|
||||
export const nextRun = (cron: string, tz: string, from = new Date()) => CronExpressionParser.parse(cron, { tz, currentDate: from }).next().toDate();
|
||||
|
||||
function remember(name: string, run: Run) {
|
||||
state.history.set(name, [run, ...(state.history.get(name) ?? [])].slice(0, 10));
|
||||
}
|
||||
|
||||
async function runJob(ctx: Ctx, job: Job) {
|
||||
return (await job.run(ctx)) ?? null;
|
||||
}
|
||||
|
||||
function startTimer(ctx: Ctx, job: Job) {
|
||||
const tz = ctx.config.timezone;
|
||||
const scheduleNext = () => {
|
||||
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
|
||||
const delay = Math.max(1000, nextRun(cronFor(ctx, job), tz).getTime() - Date.now());
|
||||
state.timers.set(job.name, setTimeout(async () => {
|
||||
await loadOverrides(ctx);
|
||||
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
|
||||
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
|
||||
try {
|
||||
entry.output = await runJob(ctx, job);
|
||||
entry.state = 'completed';
|
||||
} catch (e) {
|
||||
entry.state = 'failed';
|
||||
entry.output = { message: (e as Error).message };
|
||||
console.warn(`[jobs] ${job.name}:`, (e as Error).message);
|
||||
} finally {
|
||||
entry.completedOn = new Date();
|
||||
remember(job.name, entry);
|
||||
scheduleNext();
|
||||
}
|
||||
}, Math.min(delay, 2 ** 31 - 1)));
|
||||
};
|
||||
scheduleNext();
|
||||
}
|
||||
|
||||
async function applyJob(ctx: Ctx, job: Job) {
|
||||
if (state.mode === 'queue' && state.boss) {
|
||||
if (isEnabled(ctx, job)) await state.boss.schedule(job.name, cronFor(ctx, job), undefined, { tz: ctx.config.timezone });
|
||||
else await state.boss.unschedule(job.name).catch(() => {});
|
||||
} else if (state.mode === 'timers') {
|
||||
clearTimeout(state.timers.get(job.name));
|
||||
state.timers.delete(job.name);
|
||||
startTimer(ctx, job);
|
||||
}
|
||||
}
|
||||
|
||||
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
|
||||
if (!ctx.config.jobsEnabled) {
|
||||
state.mode = 'off';
|
||||
return async () => {};
|
||||
}
|
||||
await loadOverrides(ctx, true);
|
||||
const tz = ctx.config.timezone;
|
||||
try {
|
||||
const boss = new PgBoss({ connectionString, schema: SCHEMA, application_name: 'crosscode-accounts-jobs' });
|
||||
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
|
||||
await boss.start();
|
||||
state.boss = boss;
|
||||
state.mode = 'queue';
|
||||
for (const job of JOBS) {
|
||||
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
|
||||
// Every job has a worker (an admin can switch one on later); only those on are scheduled.
|
||||
await boss.work(job.name, async (batch) => {
|
||||
await loadOverrides(ctx);
|
||||
const manual = (Array.isArray(batch) ? batch : [batch]).some((j) => (j as { data?: { manual?: boolean } })?.data?.manual);
|
||||
if (!manual && !isEnabled(ctx, job)) return { skipped: 'switched off' };
|
||||
return runJob(ctx, job);
|
||||
});
|
||||
if (isEnabled(ctx, job)) await boss.schedule(job.name, cronFor(ctx, job), undefined, { tz });
|
||||
else await boss.unschedule(job.name).catch(() => {});
|
||||
}
|
||||
const off = JOBS.filter((j) => !isEnabled(ctx, j)).map((j) => j.name);
|
||||
console.log(`[jobs] Job queue started: ${JOBS.filter((j) => isEnabled(ctx, j)).map((j) => j.name).join(', ')}${off.length ? ` (off: ${off.join(', ')})` : ''}.`);
|
||||
return async () => { await boss.stop({ graceful: true }); state.boss = null; state.mode = 'off'; };
|
||||
} catch (e) {
|
||||
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
|
||||
state.boss = null;
|
||||
state.mode = 'timers';
|
||||
for (const job of JOBS) startTimer(ctx, job);
|
||||
return async () => { state.timers.forEach(clearTimeout); state.timers.clear(); state.mode = 'off'; };
|
||||
}
|
||||
}
|
||||
|
||||
export class JobError extends Error {
|
||||
constructor(public status: number, message: string) { super(message); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves an admin's choice for one job and applies it. `enabled` / `cron`: a value wins over the
|
||||
* .env, null goes back to it, undefined leaves it.
|
||||
*/
|
||||
export async function setOverride(ctx: Ctx, name: string, change: { enabled?: unknown; cron?: unknown }): Promise<{ enabled: boolean | null; cron: string | null }> {
|
||||
const job = JOBS.find((j) => j.name === name);
|
||||
if (!job) throw new JobError(404, 'There\'s no such job.');
|
||||
const { enabled, cron } = change;
|
||||
if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw new JobError(400, '"enabled" must be true, false or null.');
|
||||
if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim(), ctx.config.timezone))) {
|
||||
throw new JobError(400, 'That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".');
|
||||
}
|
||||
const all = { ...(await loadOverrides(ctx, true)) };
|
||||
const entry: Override = { ...(all[name] ?? {}) };
|
||||
if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled as boolean; }
|
||||
if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = (cron as string).trim(); }
|
||||
if (Object.keys(entry).length) all[name] = entry; else delete all[name];
|
||||
const value = JSON.stringify(all);
|
||||
await ctx.db.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } });
|
||||
ctx.settings.forget();
|
||||
state.overrides = all;
|
||||
state.overridesAt = Date.now();
|
||||
await applyJob(ctx, job);
|
||||
return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null };
|
||||
}
|
||||
|
||||
/** Runs a job now: queued in queue mode (it runs even when switched off), here otherwise. */
|
||||
export async function runNow(ctx: Ctx, name: string): Promise<{ queued: boolean; output?: unknown }> {
|
||||
const job = JOBS.find((j) => j.name === name);
|
||||
if (!job) throw new JobError(404, 'There\'s no such job.');
|
||||
if (state.mode === 'queue' && state.boss) {
|
||||
await state.boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` });
|
||||
return { queued: true };
|
||||
}
|
||||
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
|
||||
try {
|
||||
entry.output = await runJob(ctx, job);
|
||||
entry.state = 'completed';
|
||||
return { queued: false, output: entry.output };
|
||||
} catch (e) {
|
||||
entry.state = 'failed';
|
||||
entry.output = { message: (e as Error).message };
|
||||
throw new JobError(502, `The job failed: ${(e as Error).message}`);
|
||||
} finally {
|
||||
entry.completedOn = new Date();
|
||||
remember(job.name, entry);
|
||||
}
|
||||
}
|
||||
|
||||
/** Each job with its switch, schedule, what the .env says, the admin's choice, and its last runs. */
|
||||
export async function jobStatus(ctx: Ctx) {
|
||||
await loadOverrides(ctx, true);
|
||||
const tz = ctx.config.timezone;
|
||||
const recent = new Map<string, Run[]>();
|
||||
if (state.mode === 'queue') {
|
||||
try {
|
||||
// As in Cross Events: timestamptz as plain UTC, so Prisma's pg adapter doesn't drop the offset.
|
||||
const rows = await ctx.db.$queryRawUnsafe<(Run & { name: string })[]>(`
|
||||
SELECT name, state, created_on AT TIME ZONE 'UTC' AS "createdOn", started_on AT TIME ZONE 'UTC' AS "startedOn",
|
||||
completed_on AT TIME ZONE 'UTC' AS "completedOn", output
|
||||
FROM (
|
||||
SELECT name, state::text, created_on, started_on, completed_on, output,
|
||||
row_number() OVER (PARTITION BY name ORDER BY created_on DESC) AS rn
|
||||
FROM ${SCHEMA}.job WHERE name = ANY($1::text[])
|
||||
) ranked WHERE rn <= 10 ORDER BY "createdOn" DESC`, JOBS.map((j) => j.name));
|
||||
for (const r of rows) recent.set(r.name, [...(recent.get(r.name) ?? []), r]);
|
||||
} catch (e) {
|
||||
console.warn('[jobs] Could not read the run history:', (e as Error).message);
|
||||
}
|
||||
} else {
|
||||
for (const [name, list] of state.history) recent.set(name, list);
|
||||
}
|
||||
return {
|
||||
mode: state.mode,
|
||||
timezone: tz,
|
||||
jobsEnabledEnv: ctx.config.jobsEnabled,
|
||||
jobs: JOBS.map((job) => {
|
||||
const cron = cronFor(ctx, job);
|
||||
const enabled = isEnabled(ctx, job);
|
||||
const o = state.overrides[job.name] ?? {};
|
||||
return {
|
||||
name: job.name, label: job.label, cron, enabled, envFlag: job.env,
|
||||
envEnabled: envEnabled(job), envCron: envCronFor(ctx, job), defaultCron: job.cron,
|
||||
override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron, tz) ? o.cron : null },
|
||||
nextRun: enabled && state.mode !== 'off' ? nextRun(cron, tz) : null,
|
||||
recent: recent.get(job.name) ?? [],
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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, '"').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<Brand> {
|
||||
const base = ctx.config.publicUrl.replace(/\/+$/, '');
|
||||
try {
|
||||
const c = await church(ctx);
|
||||
const logo = c.branding.logoUrl;
|
||||
return {
|
||||
name: c.name || 'Your church',
|
||||
colour: HEX.test(c.branding.colours.primary) ? c.branding.colours.primary : '#1f4e79',
|
||||
accent: c.branding.colours.accent && HEX.test(c.branding.colours.accent) ? c.branding.colours.accent : '#f2a900',
|
||||
logoUrl: logo ? (logo.startsWith('/') ? `${base}${logo}` : /^https:\/\//i.test(logo) ? logo : null) : null,
|
||||
email: c.contact.email ?? null,
|
||||
phone: c.contact.phone ?? null,
|
||||
url: base,
|
||||
};
|
||||
} catch {
|
||||
return { name: 'Your church', colour: '#1f4e79', accent: '#f2a900', logoUrl: null, email: null, phone: null, url: base };
|
||||
}
|
||||
}
|
||||
|
||||
/** The page around an email's body (Cross Events' layout). */
|
||||
function layout(b: Brand, body: string, preheader: string): string {
|
||||
const header = b.logoUrl
|
||||
? `<img src="${esc(b.logoUrl)}" alt="${esc(b.name)}" height="56" style="display:block;margin:0 auto;max-height:56px;max-width:240px;border:0">`
|
||||
: `<h1 style="color:#ffffff;font-size:26px;font-weight:800;margin:0;letter-spacing:-0.5px;font-family:${FONT};text-shadow:0 1px 3px rgba(0,0,0,0.3)">${esc(b.name)}</h1>`;
|
||||
const contact = [
|
||||
esc(b.name),
|
||||
b.email ? `<a href="mailto:${esc(b.email)}" style="color:#94a3b8;text-decoration:underline">${esc(b.email)}</a>` : '',
|
||||
b.phone ? esc(b.phone) : '',
|
||||
].filter(Boolean).join(' • ');
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
|
||||
<title>${esc(b.name)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:0;background-color:#f1f5f9;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%">
|
||||
<div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;mso-hide:all">${esc(preheader)}‌ ‌ ‌ </div>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#f1f5f9">
|
||||
<tr><td align="center" style="padding:40px 16px">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px">
|
||||
<tr><td style="background:${b.colour};background:linear-gradient(135deg,${b.colour} 0%,${darker(b.colour)} 100%);border-radius:12px 12px 0 0;padding:36px 48px;text-align:center">
|
||||
${header}
|
||||
<p style="color:#ffffff;font-size:13px;font-weight:500;margin:10px 0 0 0;font-family:${FONT};letter-spacing:0.3px;opacity:0.9">Your ${esc(b.name)} account</p>
|
||||
</td></tr>
|
||||
<tr><td style="background:#ffffff;border-left:1px solid #e2e8f0;border-right:1px solid #e2e8f0;padding:44px 48px 36px 48px">
|
||||
<div style="font-family:${FONT};color:#1e293b;font-size:15px;line-height:1.75">
|
||||
${body}
|
||||
</div>
|
||||
</td></tr>
|
||||
<tr><td style="background:#f8fafc;border:1px solid #e2e8f0;border-top:none;border-radius:0 0 12px 12px;padding:24px 48px;text-align:center">
|
||||
<p style="color:#94a3b8;font-size:12px;margin:0 0 4px 0;font-family:${FONT}">${contact}</p>
|
||||
<p style="color:#cbd5e1;font-size:11px;margin:6px 0 0 0;font-family:${FONT}">You're getting this because you have an account with ${esc(b.name)}, used to sign in to its sites.</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
const title = (t: string, sub?: string) =>
|
||||
`<p style="font-size:22px;font-weight:800;color:#0f172a;margin:0 0 8px 0;letter-spacing:-0.3px">${esc(t)}</p>` +
|
||||
(sub ? `<p style="color:#64748b;font-size:14px;margin:0 0 28px 0">${esc(sub)}</p>` : '');
|
||||
const hello = (name?: string | null) => `<p style="margin:0 0 8px 0;color:#374151">Hello <strong>${esc(name || 'there')}</strong>,</p>`;
|
||||
const para = (html: string) => `<p style="margin:0 0 20px 0;color:#374151">${html}</p>`;
|
||||
const divider = () => `<div style="border-top:1px solid #f1f5f9;margin:28px 0"></div>`;
|
||||
const small = (html: string) => `<p style="margin:0;font-size:13px;color:#94a3b8">${html}</p>`;
|
||||
|
||||
function button(b: Brand, label: string, url: string): string {
|
||||
const href = esc(safeUrl(url));
|
||||
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:28px auto 8px auto">
|
||||
<tr><td align="center" style="border-radius:8px;background-color:${b.colour}">
|
||||
<a href="${href}" target="_blank" style="display:inline-block;padding:14px 36px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;border-radius:8px;font-family:${FONT};letter-spacing:0.2px">${esc(label)}</a>
|
||||
</td></tr>
|
||||
</table>
|
||||
<p style="text-align:center;margin:4px 0 0 0;font-size:12px;color:#94a3b8;word-break:break-all">Or copy this link: <a href="${href}" style="color:${b.colour}">${esc(url)}</a></p>`;
|
||||
}
|
||||
|
||||
/** Info, a warning ("if this wasn't you") or neutral: these colours never follow the church's. */
|
||||
function callout(html: string, kind: 'info' | 'warning' | 'success' = 'info'): string {
|
||||
const s = { info: ['#eff6ff', '#3b82f6', '#1e40af'], warning: ['#fffbeb', '#f59e0b', '#92400e'], success: ['#f0fdf4', '#22c55e', '#166534'] }[kind];
|
||||
return `<div style="background:${s[0]};border-left:4px solid ${s[1]};border-radius:0 6px 6px 0;padding:14px 18px;margin:24px 0;color:${s[2]};font-size:14px;line-height:1.6">${html}</div>`;
|
||||
}
|
||||
|
||||
const code6 = (code: string) =>
|
||||
`<p style="margin:8px 0 24px 0;font-size:34px;font-weight:800;letter-spacing:8px;color:#0f172a;text-align:center;font-family:${MONO}">${esc(code)}</p>`;
|
||||
|
||||
const contactLine = (b: Brand) => (b.email ? ` at <a href="mailto:${esc(b.email)}" style="color:${b.colour}">${esc(b.email)}</a>` : '');
|
||||
|
||||
// ─── The emails ───────────────────────────────────────────────────────────────
|
||||
|
||||
/** A sign-in or confirm-your-email code (the text is the WhatsApp message too). */
|
||||
export async function codeEmail(ctx: Ctx, o: { name?: string | null; code: string; text: string; purpose: 'sign_in' | 'verify_email' | 'setup'; minutes: number }): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const what = o.purpose === 'verify_email' ? 'confirm your email address' : 'sign in';
|
||||
const body = title('Your code', o.purpose === 'verify_email' ? 'To confirm your email address' : `To sign in to ${b.name}`)
|
||||
+ hello(o.name)
|
||||
+ para(`Enter this code to ${esc(what)}. It works for <strong>${o.minutes} minutes</strong>.`)
|
||||
+ code6(o.code)
|
||||
+ divider()
|
||||
+ small(`Never share this code with anyone, not even someone from the church. If you didn't ask for it, you can ignore this email: nobody can sign in without your password${o.purpose === 'sign_in' ? ' and this code' : ''}.`);
|
||||
return { subject: `Your code: ${o.code}`, text: o.text, html: layout(b, body, `Your code is ${o.code}. It works for ${o.minutes} minutes.`) };
|
||||
}
|
||||
|
||||
export async function resetPasswordEmail(ctx: Ctx, o: { name?: string | null; url: string; minutes: number }): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const body = title('Reset your password', 'Someone (we hope you) asked to reset it.')
|
||||
+ hello(o.name)
|
||||
+ para(`Choose a new password with the button below. The link works for <strong>${o.minutes} minutes</strong>, once.`)
|
||||
+ button(b, 'Choose a new password', o.url)
|
||||
+ divider()
|
||||
+ small(`If you didn't ask, you can ignore this email: your password stays the same. Worried? Let the church office know${contactLine(b)}.`);
|
||||
const text = `Someone (we hope you) asked to reset the password for your account.\n\nChoose a new password here (the link works for ${o.minutes} minutes):\n${o.url}\n\nIf you didn't ask, you can ignore this email: your password stays the same.`;
|
||||
return { subject: 'Reset your password', text, html: layout(b, body, `Choose a new password. The link works for ${o.minutes} minutes.`) };
|
||||
}
|
||||
|
||||
/** A product (Cross Events) made someone an account: choose a password. */
|
||||
export async function newAccountEmail(ctx: Ctx, o: { name: string; url: string; days: number }): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const body = title(`Welcome to ${b.name}`, 'An account has been made for you.')
|
||||
+ hello(o.name)
|
||||
+ para(`${esc(b.name)} has made you an account. It signs you in to all of the church's sites, such as events and registrations. Choose your password to start using it.`)
|
||||
+ button(b, 'Choose my password', o.url)
|
||||
+ callout(`The link works for <strong>${o.days} days</strong>. After that, use <em>Forgot your password?</em> on the sign-in page.`, 'info')
|
||||
+ small('If you weren\'t expecting this, you can ignore this email.');
|
||||
const text = `Hello ${o.name},\n\n${b.name} has made you an account. Choose your password here (the link works for ${o.days} days):\n${o.url}\n\nIf you weren't expecting this, you can ignore this email.`;
|
||||
return { subject: `Your account at ${b.name}`, text, html: layout(b, body, `Choose your password for your ${b.name} account.`) };
|
||||
}
|
||||
|
||||
export async function confirmNewEmail(ctx: Ctx, o: { name?: string | null; url: string }): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const body = title('Confirm your new email address')
|
||||
+ hello(o.name)
|
||||
+ para('You asked to sign in with this email address from now on. Confirm it\'s yours with the button below; until then you keep signing in with your old one.')
|
||||
+ button(b, 'Confirm this address', o.url)
|
||||
+ divider()
|
||||
+ small('The link works for 24 hours. If you didn\'t ask for this, you can ignore this email.');
|
||||
const text = `Confirm this is your new email address for signing in:\n${o.url}\n\nThe link works for 24 hours.`;
|
||||
return { subject: 'Confirm your new email address', text, html: layout(b, body, 'Confirm your new sign-in email address.') };
|
||||
}
|
||||
|
||||
export async function emailChangedNotice(ctx: Ctx, o: { name?: string | null; newEmail: string }): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const body = title('Your sign-in email address changed')
|
||||
+ hello(o.name)
|
||||
+ para(`Your account now signs in with <strong>${esc(o.newEmail)}</strong>. Emails about your account go there from now on.`)
|
||||
+ callout(`<strong>Wasn't you?</strong> Contact the church office straight away${contactLine(b)}.`, 'warning');
|
||||
const text = `Your account now signs in with ${o.newEmail}. If you didn't do this, contact the church office straight away.`;
|
||||
return { subject: 'Your sign-in email address changed', text, html: layout(b, body, `Your account now signs in with ${o.newEmail}.`) };
|
||||
}
|
||||
|
||||
export async function exportReadyEmail(ctx: Ctx, o: { name?: string | null; url: string; days: number }): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const body = title('Your data is ready', 'The copy you asked for')
|
||||
+ hello(o.name)
|
||||
+ para('The copy of your data you asked for is ready. Download it from your account page.')
|
||||
+ button(b, 'Download my data', o.url)
|
||||
+ callout(`It's kept for <strong>${o.days} days</strong>, then deleted. You need to be signed in to download it.`, 'info');
|
||||
const text = `The copy of your data you asked for is ready. Download it from your account page (it's kept for ${o.days} days):\n${o.url}`;
|
||||
return { subject: 'Your data is ready to download', text, html: layout(b, body, 'The copy of your data you asked for is ready.') };
|
||||
}
|
||||
|
||||
/** A test from the admin page or from a linked product (`from`: "Cross Events"). */
|
||||
export async function testEmail(ctx: Ctx, o: { from?: string } = {}): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const body = title('Email works', o.from ? `A test sent from ${o.from}` : 'A test from Accounts')
|
||||
+ para(`This is a test from ${esc(b.name)}'s sign-in (Accounts)${o.from ? `, sent from ${esc(o.from)}` : ''}.`)
|
||||
+ callout('Email is set up: sign-in codes, password links and security notices can be sent.', 'success');
|
||||
const text = o.from
|
||||
? `This is a test from ${b.name}'s sign-in (Accounts), sent from ${o.from}. Email works: sign-in codes and password links can be sent.`
|
||||
: 'Email from Accounts works.';
|
||||
return { subject: o.from ? `Test email from ${b.name}'s sign-in` : 'Test email from Accounts', text, html: layout(b, body, 'A test email: email works.') };
|
||||
}
|
||||
@@ -5,7 +5,8 @@
|
||||
import nodemailer from 'nodemailer';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export type Email = { to: string; subject: string; text: string };
|
||||
/** `html` (1.4.0, src/lib/emails.ts): the styled version; `text` is always sent too. */
|
||||
export type Email = { to: string; subject: string; text: string; html?: string };
|
||||
export type WhatsApp = { to: string; text: string };
|
||||
|
||||
/** SMTP settings to try before saving them (1.2.0), as kept in `smtp_*`. */
|
||||
@@ -87,7 +88,7 @@ export class LiveMessenger implements Messenger {
|
||||
return;
|
||||
}
|
||||
const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name;
|
||||
await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text });
|
||||
await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text, ...(msg.html ? { html: msg.html } : {}) });
|
||||
}
|
||||
|
||||
async emailReady(): Promise<boolean> {
|
||||
@@ -112,7 +113,7 @@ export class LiveMessenger implements Messenger {
|
||||
|
||||
async emailWith(settings: SmtpTry, msg: Email): Promise<void> {
|
||||
const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name;
|
||||
await transportFor(settings).sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${settings.from}>` : settings.from, to: msg.to, subject: msg.subject, text: msg.text });
|
||||
await transportFor(settings).sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${settings.from}>` : settings.from, to: msg.to, subject: msg.subject, text: msg.text, ...(msg.html ? { html: msg.html } : {}) });
|
||||
}
|
||||
|
||||
async whatsappWith(settings: WawpTry, msg: WhatsApp): Promise<void> {
|
||||
|
||||
@@ -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 }) });
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -9,6 +9,7 @@ import path from 'node:path';
|
||||
import { IDENTITY_SCHEMA, userExportReplySchema } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { onReply, queueCall } from '../links/deliveries.js';
|
||||
import { exportReadyEmail } from '../lib/emails.js';
|
||||
|
||||
const WAIT_MS = 24 * 3600e3;
|
||||
const KEEP_MS = 7 * 24 * 3600e3;
|
||||
@@ -71,7 +72,7 @@ export async function finishIfComplete(ctx: Ctx, exportId: string, force = false
|
||||
}, null, 2), { mode: 0o600 });
|
||||
await ctx.db.dataExport.update({ where: { id: exp.id }, data: { status: 'ready', file, readyAt: ctx.now(), expiresAt: new Date(ctx.now().getTime() + KEEP_MS) } });
|
||||
const a = await ctx.db.account.findUnique({ where: { id: exp.accountId } });
|
||||
if (a) await ctx.messenger.email({ to: a.email, subject: 'Your data is ready to download', text: `The copy of your data you asked for is ready. Download it from your account page (it's kept for 7 days):\n${ctx.config.publicUrl}/account/privacy` });
|
||||
if (a) await ctx.messenger.email({ to: a.email, ...(await exportReadyEmail(ctx, { name: a.name, url: `${ctx.config.publicUrl}/account/privacy`, days: Math.round(KEEP_MS / 86400e3) })) });
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// 1.4.0: Admin → Background jobs (switch a job on or off, change its schedule, over the .env) and
|
||||
// the styled emails (as Cross Events').
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import { Browser, startHarness, type Harness } from './support/harness.js';
|
||||
import { codeAt } from '../src/lib/totp.js';
|
||||
import { JOBS, cronFor, isEnabled, useEnvForTest } from '../src/jobs.js';
|
||||
import { esc, newAccountEmail, resetPasswordEmail } from '../src/lib/emails.js';
|
||||
import type { MemoryMessenger } from '../src/lib/messages.js';
|
||||
|
||||
let h: Harness;
|
||||
before(async () => { h = await startHarness(); });
|
||||
after(async () => { useEnvForTest(process.env); await h.close(); });
|
||||
|
||||
let adminBrowser: Browser | null = null;
|
||||
async function adminPage() {
|
||||
if (adminBrowser) return adminBrowser;
|
||||
await h.makeAccount({ email: 'jobs.admin@hope.test', password: 'Correct-horse-8', role: 'admin' });
|
||||
const browser = new Browser();
|
||||
const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/admin`, (u) => u.pathname === '/signin');
|
||||
const uid = url.searchParams.get('uid')!;
|
||||
await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'jobs.admin@hope.test', password: 'Correct-horse-8' });
|
||||
const setup = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor/setup`, { method: 'totp' });
|
||||
const done = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor/setup/confirm`, { method: 'totp', code: codeAt(String(setup.body.secret), Math.floor(Date.now() / 30000)) });
|
||||
await browser.follow(done.body.redirectTo as string, (u) => u.pathname === '/admin' || u.pathname === '/account');
|
||||
adminBrowser = browser;
|
||||
return browser;
|
||||
}
|
||||
|
||||
const backup = JOBS.find((j) => j.name === 'backup')!;
|
||||
|
||||
describe('background jobs', () => {
|
||||
test('the .env flag and schedule apply until an admin chooses; their choice wins; null goes back', async () => {
|
||||
useEnvForTest({ BACKUP_ENABLED: 'false', JOB_SCHEDULE_BACKUP: '30 1 * * *' });
|
||||
h.ctx.config.jobsEnabled = true; // the harness turns them off; nothing is started here either way
|
||||
const browser = await adminPage();
|
||||
let list = await h.api(browser, 'GET', '/api/v2/admin/jobs');
|
||||
assert.equal(list.status, 200);
|
||||
let job = (list.body.jobs as { name: string; enabled: boolean; envEnabled: boolean; cron: string; override: { enabled: boolean | null; cron: string | null } }[]).find((j) => j.name === 'backup')!;
|
||||
assert.equal(job.enabled, false);
|
||||
assert.equal(job.envEnabled, false);
|
||||
assert.equal(job.cron, '30 1 * * *');
|
||||
assert.deepEqual(job.override, { enabled: null, cron: null });
|
||||
|
||||
const on = await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { enabled: true, cron: '0 3 * * *' });
|
||||
assert.equal(on.status, 200);
|
||||
assert.deepEqual(on.body.override, { enabled: true, cron: '0 3 * * *' });
|
||||
assert.equal(isEnabled(h.ctx, backup), true);
|
||||
assert.equal(cronFor(h.ctx, backup), '0 3 * * *');
|
||||
list = await h.api(browser, 'GET', '/api/v2/admin/jobs');
|
||||
job = (list.body.jobs as typeof job[]).find((j) => j.name === 'backup')!;
|
||||
assert.equal(job.enabled, true);
|
||||
assert.equal(job.envEnabled, false);
|
||||
|
||||
const back = await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { enabled: null, cron: null });
|
||||
assert.deepEqual(back.body.override, { enabled: null, cron: null });
|
||||
assert.equal(isEnabled(h.ctx, backup), false);
|
||||
assert.equal(cronFor(h.ctx, backup), '30 1 * * *');
|
||||
|
||||
const audit = await h.ctx.db.auditLog.findMany({ where: { action: 'job_settings_changed' } });
|
||||
assert.equal(audit.length, 2);
|
||||
});
|
||||
|
||||
test('a bad schedule, a bad switch and an unknown job are refused', async () => {
|
||||
const browser = await adminPage();
|
||||
assert.equal((await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { cron: 'every night' })).status, 400);
|
||||
assert.equal((await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { enabled: 'yes' })).status, 400);
|
||||
assert.equal((await h.api(browser, 'PUT', '/api/v2/admin/jobs/nope', { enabled: true })).status, 404);
|
||||
});
|
||||
|
||||
test('only admins see them', async () => {
|
||||
const anon = new Browser();
|
||||
assert.equal((await h.api(anon, 'GET', '/api/v2/admin/jobs')).status, 401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('styled emails', () => {
|
||||
test('in the church colour, with its name escaped, and the same plain text as before', async () => {
|
||||
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope <Church> & Co', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#336699', accent: null } }, contact: { email: 'office@hope.test', phone: null, whatsapp: null, address: null } }));
|
||||
const r = await resetPasswordEmail(h.ctx, { name: '<b>Jane</b>', url: 'https://accounts.hope.test/reset?token=abc', minutes: 60 });
|
||||
assert.equal(r.subject, 'Reset your password');
|
||||
assert.match(r.text, /https:\/\/accounts\.hope\.test\/reset\?token=abc/);
|
||||
assert.match(r.html, /background-color:#336699/);
|
||||
assert.match(r.html, /Hope <Church> & Co/);
|
||||
assert.ok(!r.html.includes('<b>Jane</b>'));
|
||||
assert.match(r.html, /href="https:\/\/accounts\.hope\.test\/reset\?token=abc"/);
|
||||
assert.match(r.html, /office@hope\.test/);
|
||||
const n = await newAccountEmail(h.ctx, { name: 'Sam', url: 'javascript:alert(1)', days: 7 });
|
||||
assert.equal(n.subject, 'Your account at Hope <Church> & Co');
|
||||
assert.ok(!n.html.includes('href="javascript:'));
|
||||
assert.equal(esc('"x"'), '"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 ?? '', /<!DOCTYPE html>/);
|
||||
});
|
||||
});
|
||||
@@ -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": {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import React, { useCallback, useState } from "react";
|
||||
import { DatabaseBackup, Download } from "lucide-react";
|
||||
import { DatabaseBackup, Download, Play, RefreshCw, Timer } from "lucide-react";
|
||||
import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
|
||||
import { AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell";
|
||||
import { NoticeText } from "@/components/NoticeText";
|
||||
@@ -61,6 +61,7 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
|
||||
{section === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />}
|
||||
{section === "notice" && <NoticeTab flash={flash} />}
|
||||
{section === "backups" && <Backups flash={flash} />}
|
||||
{section === "jobs" && <Jobs flash={flash} />}
|
||||
{section === "licence" && <Licence flash={flash} />}
|
||||
{section === "audit" && <Audit />}
|
||||
</div>
|
||||
@@ -463,3 +464,162 @@ function Backups({ flash }: { flash: Flash }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Background jobs (1.4.0, as Cross Events) ────────────────────────────────
|
||||
|
||||
type JobRun = { state: string; createdOn?: string | null; startedOn: string | null; completedOn: string | null; output: unknown };
|
||||
type JobInfo = {
|
||||
name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[];
|
||||
envEnabled: boolean; envCron: string; defaultCron: string; override: { enabled: boolean | null; cron: string | null };
|
||||
};
|
||||
type JobList = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: JobInfo[] };
|
||||
|
||||
const RUN_STATE: Record<string, string> = {
|
||||
completed: "bg-green-50 text-green-800", failed: "bg-red-50 text-red-700", active: "bg-blue-50 text-blue-700",
|
||||
created: "bg-gray-100 text-gray-600", retry: "bg-amber-50 text-amber-800", cancelled: "bg-gray-100 text-gray-500",
|
||||
};
|
||||
const SCHEDULES = [
|
||||
{ label: "Every minute", cron: "* * * * *" }, { label: "Every 5 minutes", cron: "*/5 * * * *" }, { label: "Every 15 minutes", cron: "*/15 * * * *" },
|
||||
{ label: "Every hour", cron: "0 * * * *" }, { label: "Daily at 02:00", cron: "0 2 * * *" }, { label: "Daily at 07:00", cron: "0 7 * * *" },
|
||||
];
|
||||
|
||||
function describeCron(cron: string): string {
|
||||
if (cron === "* * * * *") return "Every minute";
|
||||
const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron);
|
||||
if (m) return `Every ${m[1]} minutes`;
|
||||
const h = /^(\d+) \* \* \* \*$/.exec(cron);
|
||||
if (h) return `Every hour at :${h[1]!.padStart(2, "0")}`;
|
||||
const d = /^(\d+) (\d+) \* \* \*$/.exec(cron);
|
||||
if (d) return `Daily at ${d[2]!.padStart(2, "0")}:${d[1]!.padStart(2, "0")}`;
|
||||
return cron;
|
||||
}
|
||||
|
||||
function runText(r: JobRun): string {
|
||||
if (r.output === null || r.output === undefined) return "";
|
||||
if (r.state === "failed" && typeof r.output === "object" && r.output && "message" in r.output) return String((r.output as { message: unknown }).message);
|
||||
try { return JSON.stringify(r.output); } catch { return ""; }
|
||||
}
|
||||
|
||||
/** An on/off switch (role="switch", so screen readers hear on and off). */
|
||||
function Toggle({ on, label, disabled, onChange }: { on: boolean; label: string; disabled?: boolean; onChange: (on: boolean) => void }) {
|
||||
return (
|
||||
<button type="button" role="switch" aria-checked={on} aria-label={label} disabled={disabled} onClick={() => onChange(!on)}
|
||||
className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 disabled:cursor-not-allowed disabled:opacity-50 ${on ? "bg-brand" : "bg-gray-300"}`}>
|
||||
<span className={`inline-block h-5 w-5 rounded-full bg-white shadow transition-transform ${on ? "translate-x-5" : "translate-x-0.5"}`} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function Jobs({ flash }: { flash: Flash }) {
|
||||
const [data, setData] = useState<JobList | null>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [open, setOpen] = useState<string | null>(null);
|
||||
const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
// Not tied to `flash` (a new function each render): the list loads once, then on Refresh.
|
||||
const load = useCallback(async () => {
|
||||
const r = await call<JobList>("GET", "/admin/jobs");
|
||||
if (r.ok) { setData(r.data); setLoadError(null); } else setLoadError(r.error.message);
|
||||
}, []);
|
||||
useExternalEffect(() => { void load(); }, [load]);
|
||||
|
||||
const save = async (job: JobInfo, change: { enabled?: boolean | null; cron?: string | null }, done: string) => {
|
||||
setBusy(job.name);
|
||||
const r = await call("PUT", `/admin/jobs/${encodeURIComponent(job.name)}`, change);
|
||||
setBusy(null);
|
||||
if (r.ok) { flash("success", done); setEditing(null); void load(); } else flash("error", r.error.message);
|
||||
};
|
||||
const runNow = async (job: JobInfo) => {
|
||||
setBusy(job.name);
|
||||
const r = await call<{ queued: boolean }>("POST", `/admin/jobs/${encodeURIComponent(job.name)}/run`);
|
||||
setBusy(null);
|
||||
if (r.ok) {
|
||||
flash("success", r.data.queued ? `"${job.label}" queued: it starts within a few seconds.` : `"${job.label}" ran.`);
|
||||
setTimeout(() => void load(), r.data.queued ? 4000 : 0);
|
||||
} else flash("error", r.error.message);
|
||||
};
|
||||
|
||||
if (!data) return loadError ? <Notice tone="error">{loadError}</Notice> : <p className="text-gray-600">Loading…</p>;
|
||||
const off = data.mode === "off";
|
||||
return (
|
||||
<Card>
|
||||
<div className="mb-3 flex items-start justify-between gap-3">
|
||||
<Heading icon={<Timer className="h-4 w-4" />} sub={`Times are ${data.timezone}. Each job runs once per schedule, however many server processes there are.`}>Jobs</Heading>
|
||||
<Button variant="secondary" onClick={() => void load()}><RefreshCw className="mr-1.5 inline h-3.5 w-3.5" aria-hidden />Refresh</Button>
|
||||
</div>
|
||||
{off && <Notice tone="warning">All background jobs are switched off in the server's .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change that from the Hub.</Notice>}
|
||||
{data.mode === "timers" && <Notice tone="warning">The job queue couldn't start, so jobs run on simple timers in this process (history only since the last restart).</Notice>}
|
||||
<ul className="divide-y rounded-lg border">
|
||||
{data.jobs.map((job) => {
|
||||
const last = job.recent[0];
|
||||
const mine = busy === job.name;
|
||||
const isEditing = editing?.name === job.name;
|
||||
return (
|
||||
<li key={job.name} className="p-3">
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
|
||||
<Toggle on={job.enabled} disabled={mine || off} label={`${job.label}: ${job.enabled ? "on" : "off"}`}
|
||||
onChange={(on) => void save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)} />
|
||||
<div className="mr-auto min-w-0">
|
||||
<div className={`text-sm font-medium ${job.enabled ? "text-gray-900" : "text-gray-500"}`}>{job.label}</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : "Off"}
|
||||
{job.override.enabled !== null
|
||||
? <> · {job.enabled ? "switched on" : "switched off"} here · <button type="button" disabled={mine} className="underline hover:text-gray-700" onClick={() => void save(job, { enabled: null }, `"${job.label}" follows the .env again.`)}>use the .env ({job.envEnabled ? "on" : "off"})</button></>
|
||||
: !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""}
|
||||
</div>
|
||||
</div>
|
||||
{last && (
|
||||
<button type="button" onClick={() => setOpen(open === job.name ? null : job.name)} title="Recent runs" className={`rounded px-2 py-0.5 text-xs ${RUN_STATE[last.state] ?? "bg-gray-100 text-gray-600"}`}>
|
||||
{last.state} · {when(last.completedOn || last.startedOn || last.createdOn)}
|
||||
</button>
|
||||
)}
|
||||
<Button variant="secondary" disabled={mine || isEditing} onClick={() => setEditing({ name: job.name, cron: job.cron })}>Schedule</Button>
|
||||
<Button variant="secondary" disabled={!!busy || off} onClick={() => void runNow(job)}><Play className="mr-1 inline h-3.5 w-3.5" aria-hidden />Run now</Button>
|
||||
</div>
|
||||
{isEditing && editing && (
|
||||
<form className="mt-3 space-y-2 rounded-lg border bg-gray-50 p-3" onSubmit={(e) => { e.preventDefault(); void save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{SCHEDULES.map((p) => (
|
||||
<button key={p.cron} type="button" onClick={() => setEditing({ name: job.name, cron: p.cron })}
|
||||
className={`rounded border px-2 py-1 text-xs ${editing.cron === p.cron ? "border-brand bg-white font-medium" : "bg-white hover:bg-gray-100"}`}>{p.label}</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<Field label="Cron (minute hour day month weekday)" name="cron" value={editing.cron} maxLength={100} className="mb-0 w-64 font-mono"
|
||||
onChange={(e) => setEditing({ name: job.name, cron: e.target.value })} hint={describeCron(editing.cron.trim())} />
|
||||
<div className="ml-auto flex gap-2 pb-6">
|
||||
<Button type="button" variant="secondary" onClick={() => setEditing(null)}>Cancel</Button>
|
||||
<Button type="submit" busy={mine} disabled={!editing.cron.trim()}>Save schedule</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">
|
||||
The server's own schedule is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (from the .env; normally ${describeCron(job.defaultCron)})` : ""}.{" "}
|
||||
{job.override.cron !== null && <button type="button" disabled={mine} className="underline hover:text-gray-700" onClick={() => void save(job, { cron: null }, `"${job.label}" is back on its own schedule.`)}>Use that again</button>}
|
||||
</p>
|
||||
</form>
|
||||
)}
|
||||
{open === job.name && job.recent.length > 0 && (
|
||||
<div className="mt-2 overflow-x-auto">
|
||||
<table className="w-full text-xs">
|
||||
<thead className="text-gray-500"><tr><th className="py-1 text-left font-medium">Started</th><th className="text-left font-medium">Finished</th><th className="text-left font-medium">State</th><th className="text-left font-medium">Result</th></tr></thead>
|
||||
<tbody>
|
||||
{job.recent.map((r, i) => (
|
||||
<tr key={i} className="border-t">
|
||||
<td className="whitespace-nowrap py-1 pr-2">{when(r.startedOn)}</td>
|
||||
<td className="whitespace-nowrap pr-2">{when(r.completedOn)}</td>
|
||||
<td className="pr-2"><span className={`rounded px-1.5 py-0.5 ${RUN_STATE[r.state] ?? ""}`}>{r.state}</span></td>
|
||||
<td className="break-all font-mono text-[11px] text-gray-600">{runText(r)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<p className="mt-3 text-xs text-gray-500">Without a choice here, the server'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".</p>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import Link from "next/link";
|
||||
import React, { useState } from "react";
|
||||
import {
|
||||
Activity, Building2, DatabaseBackup, FileText, KeyRound, LayoutDashboard, Link2, Lock, LogIn, LogOut, Mail, Menu, ScrollText,
|
||||
ShieldCheck, User, Users, UserX, X, type LucideIcon,
|
||||
ShieldCheck, Timer, User, Users, UserX, X, type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { ChurchMark } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
@@ -31,6 +31,7 @@ export const ADMIN_NAV: NavItem[] = [
|
||||
{ href: "/admin/messages", label: "Email and WhatsApp", icon: Mail },
|
||||
{ href: "/admin/notice", label: "Privacy notice", icon: FileText },
|
||||
{ href: "/admin/backups", label: "Backups", icon: DatabaseBackup },
|
||||
{ href: "/admin/jobs", label: "Background jobs", icon: Timer },
|
||||
{ href: "/admin/licence", label: "Licence", icon: KeyRound },
|
||||
{ href: "/admin/audit", label: "Audit log", icon: ScrollText },
|
||||
];
|
||||
|
||||
@@ -8,6 +8,7 @@ export const ADMIN_SECTIONS = {
|
||||
messages: { path: "/admin/messages", title: "Email and WhatsApp", sub: "How Accounts sends sign-in codes, password links and security notices." },
|
||||
notice: { path: "/admin/notice", title: "Privacy notice", sub: "What people read before they sign in for the first time, and after it changes." },
|
||||
backups: { path: "/admin/backups", title: "Backups", sub: "Copies of the Accounts database, kept on this server." },
|
||||
jobs: { path: "/admin/jobs", title: "Background jobs", sub: "What the server does on a schedule. Switch a job on or off or change when it runs: your choice wins over the server's .env and applies straight away." },
|
||||
licence: { path: "/admin/licence", title: "Licence", sub: "Accounts' connection to Cross Code." },
|
||||
audit: { path: "/admin/audit", title: "Audit log", sub: "What admins and the church's sites changed here." },
|
||||
} as const;
|
||||
|
||||
@@ -1,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",
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -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"]);
|
||||
|
||||
@@ -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_<NAME>`), and applies straight away: the queue is
|
||||
rescheduled in this process, and other processes see it within 30 seconds (a run of a job switched
|
||||
off elsewhere is skipped). "use the .env" goes back to what the server says.
|
||||
`JOBS_ENABLED=false` still turns every job off (the end-to-end tests use it).
|
||||
API: `PUT /api/v2/admin/jobs/:name` `{ enabled, cron }` (null goes back to the .env); `GET
|
||||
/admin/jobs` also gives `envEnabled`, `envCron`, `defaultCron` and `override`.
|
||||
|
||||
### Changed
|
||||
|
||||
- "Run now" also works for a job that's switched off.
|
||||
|
||||
## [3.3.0] - 2026-11-20
|
||||
|
||||
Works with Accounts 1.3.0 (needed for the demo-data part; with an older Accounts the old demo people
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -10,7 +10,10 @@
|
||||
*
|
||||
* Each job can be switched off with its env flag (e.g. WAITLIST_JOB_ENABLED=false), and
|
||||
* its schedule changed with JOB_SCHEDULE_<NAME> (cron, e.g. JOB_SCHEDULE_WAITLIST="*\/5 * * * *").
|
||||
* JOBS_ENABLED=false turns all of them off (used by the end-to-end tests).
|
||||
* 3.4.0: an admin can do both on the Background jobs page; their choice is kept in the database
|
||||
* (AppSetting job_overrides), wins over the .env and takes effect straight away (other processes
|
||||
* within 30 seconds).
|
||||
* JOBS_ENABLED=false still turns all of them off (used by the end-to-end tests).
|
||||
* If the queue can't start (e.g. the database user can't create the pgboss schema), the
|
||||
* same jobs run on in-process timers instead, as before.
|
||||
*/
|
||||
@@ -117,13 +120,69 @@ const flag = (name, def = true) => {
|
||||
return v === undefined || v === '' ? def : String(v).toLowerCase() !== 'false';
|
||||
};
|
||||
|
||||
/** Whether a job is switched on (JOBS_ENABLED and its own flag). */
|
||||
function isEnabled(job) {
|
||||
return flag('JOBS_ENABLED') && (!job.env || flag(job.env));
|
||||
// ─── The admin's choices (3.4.0) ──────────────────────────────────────────────
|
||||
|
||||
const OVERRIDES_KEY = 'job_overrides';
|
||||
const OVERRIDES_TTL_MS = 30 * 1000;
|
||||
/** { [job name]: { enabled?: boolean, cron?: string } } from the database, cached here. */
|
||||
let overrides = {};
|
||||
let overridesAt = 0;
|
||||
|
||||
/** Reads the admin's choices again when the copy here is older than 30 s (or with `force`). */
|
||||
async function loadOverrides(force = false) {
|
||||
if (!force && overridesAt && Date.now() - overridesAt < OVERRIDES_TTL_MS) return overrides;
|
||||
try {
|
||||
const prisma = require('../config/db');
|
||||
const row = await prisma.appSetting.findUnique({ where: { key: OVERRIDES_KEY } });
|
||||
const parsed = row?.value ? JSON.parse(row.value) : {};
|
||||
overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
||||
overridesAt = Date.now();
|
||||
} catch (e) {
|
||||
// Keep the last copy (or none): the .env still applies.
|
||||
if (force) console.warn('[jobs] Could not read the job overrides:', e?.message || e);
|
||||
}
|
||||
return overrides;
|
||||
}
|
||||
|
||||
/** A job's cron schedule, with any JOB_SCHEDULE_<NAME> override (checked). */
|
||||
/** Sets the cached choices (tests, and after saving). */
|
||||
function setOverridesForTest(value) {
|
||||
overrides = value || {};
|
||||
overridesAt = Date.now();
|
||||
}
|
||||
|
||||
/** A cron expression with five fields that cron-parser understands. */
|
||||
function isCron(cron) {
|
||||
if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false;
|
||||
try {
|
||||
CronExpressionParser.parse(cron, { tz: TIMEZONE });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */
|
||||
function envEnabled(job) {
|
||||
return !job.env || flag(job.env);
|
||||
}
|
||||
|
||||
/** Whether a job is switched on: JOBS_ENABLED=false turns all off; then the admin's choice; then its env flag. */
|
||||
function isEnabled(job) {
|
||||
if (!flag('JOBS_ENABLED')) return false;
|
||||
const o = overrides[job.name];
|
||||
if (o && typeof o.enabled === 'boolean') return o.enabled;
|
||||
return envEnabled(job);
|
||||
}
|
||||
|
||||
/** A job's cron schedule: the admin's choice, else JOB_SCHEDULE_<NAME>, else its default. */
|
||||
function cronFor(job) {
|
||||
const o = overrides[job.name];
|
||||
if (o && isCron(o.cron)) return o.cron;
|
||||
return envCronFor(job);
|
||||
}
|
||||
|
||||
/** A job's cron schedule from the .env (JOB_SCHEDULE_<NAME>, checked), else its default. */
|
||||
function envCronFor(job) {
|
||||
const override = process.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`];
|
||||
if (override) {
|
||||
try {
|
||||
@@ -208,31 +267,75 @@ const timers = new Map();
|
||||
// Timer mode keeps its own short history so the admin page still has something to show.
|
||||
const timerHistory = new Map();
|
||||
|
||||
/** One job on an in-process timer while it's on. The schedule and the switch are read each time. */
|
||||
function startTimer(job) {
|
||||
const scheduleNext = () => {
|
||||
if (!isEnabled(job)) { timers.delete(job.name); return; }
|
||||
const delay = Math.max(1000, nextRun(cronFor(job)).getTime() - Date.now());
|
||||
timers.set(job.name, setTimeout(async () => {
|
||||
await loadOverrides();
|
||||
if (!isEnabled(job)) { timers.delete(job.name); return; }
|
||||
const entry = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
|
||||
try {
|
||||
entry.output = await runJob(job);
|
||||
entry.state = 'completed';
|
||||
} catch (e) {
|
||||
entry.state = 'failed';
|
||||
entry.output = { message: e?.message || String(e) };
|
||||
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
|
||||
} finally {
|
||||
entry.completedOn = new Date();
|
||||
timerHistory.set(job.name, [entry, ...(timerHistory.get(job.name) || [])].slice(0, 10));
|
||||
scheduleNext();
|
||||
}
|
||||
}, Math.min(delay, 2 ** 31 - 1)));
|
||||
};
|
||||
scheduleNext();
|
||||
}
|
||||
|
||||
function startTimers(jobs) {
|
||||
mode = 'timers';
|
||||
for (const job of jobs) {
|
||||
const cron = cronFor(job);
|
||||
const scheduleNext = () => {
|
||||
const delay = Math.max(1000, nextRun(cron).getTime() - Date.now());
|
||||
timers.set(job.name, setTimeout(async () => {
|
||||
const entry = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
|
||||
try {
|
||||
entry.output = await runJob(job);
|
||||
entry.state = 'completed';
|
||||
} catch (e) {
|
||||
entry.state = 'failed';
|
||||
entry.output = { message: e?.message || String(e) };
|
||||
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
|
||||
} finally {
|
||||
entry.completedOn = new Date();
|
||||
timerHistory.set(job.name, [entry, ...(timerHistory.get(job.name) || [])].slice(0, 10));
|
||||
scheduleNext();
|
||||
}
|
||||
}, Math.min(delay, 2 ** 31 - 1)));
|
||||
};
|
||||
scheduleNext();
|
||||
for (const job of jobs) startTimer(job);
|
||||
console.log(`[jobs] Running ${jobs.filter(isEnabled).length} job(s) on in-process timers.`);
|
||||
}
|
||||
|
||||
/** Puts one job's schedule in line with its switch and schedule now (queue or timers). */
|
||||
async function applyJob(job) {
|
||||
if (mode === 'queue' && boss) {
|
||||
if (isEnabled(job)) await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE });
|
||||
else await boss.unschedule(job.name).catch(() => {});
|
||||
} else if (mode === 'timers') {
|
||||
clearTimeout(timers.get(job.name));
|
||||
timers.delete(job.name);
|
||||
startTimer(job);
|
||||
}
|
||||
console.log(`[jobs] Running ${jobs.length} job(s) on in-process timers.`);
|
||||
}
|
||||
|
||||
const badRequest = (message) => Object.assign(new Error(message), { statusCode: 400 });
|
||||
|
||||
/**
|
||||
* Saves an admin's choice for one job and applies it straight away. `enabled` / `cron`: a value
|
||||
* wins over the .env; null goes back to the .env; undefined leaves it as it is.
|
||||
* @returns the job's choices now ({ enabled, cron }, null where the .env applies)
|
||||
*/
|
||||
async function setOverride(name, { enabled, cron } = {}) {
|
||||
const job = JOBS.find(j => j.name === name);
|
||||
if (!job) throw Object.assign(new Error('Unknown job'), { statusCode: 404 });
|
||||
if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw badRequest('"enabled" must be true, false or null.');
|
||||
if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim()))) {
|
||||
throw badRequest('That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".');
|
||||
}
|
||||
const prisma = require('../config/db');
|
||||
const all = { ...(await loadOverrides(true)) };
|
||||
const entry = { ...(all[name] || {}) };
|
||||
if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled; }
|
||||
if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = cron.trim(); }
|
||||
if (Object.keys(entry).length) all[name] = entry; else delete all[name];
|
||||
const value = JSON.stringify(all);
|
||||
await prisma.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } });
|
||||
setOverridesForTest(all);
|
||||
await applyJob(job);
|
||||
return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -240,12 +343,13 @@ function startTimers(jobs) {
|
||||
* @returns {Promise<'queue'|'timers'|'off'>}
|
||||
*/
|
||||
async function startJobs() {
|
||||
const enabled = JOBS.filter(isEnabled);
|
||||
if (!flag('JOBS_ENABLED')) {
|
||||
console.log('[jobs] All background jobs disabled by env JOBS_ENABLED=false');
|
||||
mode = 'off';
|
||||
return mode;
|
||||
}
|
||||
await loadOverrides(true);
|
||||
const enabled = JOBS.filter(isEnabled);
|
||||
try {
|
||||
const PgBoss = require('pg-boss');
|
||||
boss = new PgBoss({ connectionString: process.env.DATABASE_URL, schema: SCHEMA, application_name: 'hope-events-jobs' });
|
||||
@@ -257,19 +361,21 @@ async function startJobs() {
|
||||
// stately: at most one waiting and one running, so a slow run never piles up.
|
||||
await boss.createQueue(job.name, { policy: 'stately', retryLimit: 2, retryDelay: 60, expireInSeconds: 60 * 60 });
|
||||
}
|
||||
if (isEnabled(job)) {
|
||||
await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE });
|
||||
await boss.work(job.name, async () => {
|
||||
try {
|
||||
return await runJob(job);
|
||||
} catch (e) {
|
||||
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
|
||||
throw e; // recorded as failed, and retried
|
||||
}
|
||||
});
|
||||
} else {
|
||||
await boss.unschedule(job.name).catch(() => {});
|
||||
}
|
||||
// 3.4.0: every job has a worker (an admin can switch one on later); only those on are scheduled.
|
||||
await boss.work(job.name, async (batch) => {
|
||||
const list = Array.isArray(batch) ? batch : [batch];
|
||||
await loadOverrides();
|
||||
// Switched off (perhaps in another process) after this run was scheduled: skip it. "Run now" still runs.
|
||||
if (!isEnabled(job) && !list.some(j => j?.data?.manual)) return { skipped: 'switched off' };
|
||||
try {
|
||||
return await runJob(job);
|
||||
} catch (e) {
|
||||
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
|
||||
throw e; // recorded as failed, and retried
|
||||
}
|
||||
});
|
||||
if (isEnabled(job)) await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE });
|
||||
else await boss.unschedule(job.name).catch(() => {});
|
||||
}
|
||||
// One-off tasks: any number can wait and run (unlike the stately scheduled jobs).
|
||||
for (const name of Object.keys(TASKS)) {
|
||||
@@ -295,7 +401,7 @@ async function startJobs() {
|
||||
console.warn('[jobs] Job queue unavailable, falling back to timers:', e?.message || e);
|
||||
if (boss) { try { await boss.stop({ graceful: false }); } catch { /* ignore */ } }
|
||||
boss = null;
|
||||
startTimers(enabled);
|
||||
startTimers(JOBS);
|
||||
}
|
||||
return mode;
|
||||
}
|
||||
@@ -318,8 +424,9 @@ async function runNow(name) {
|
||||
err.statusCode = 404;
|
||||
throw err;
|
||||
}
|
||||
if (mode === 'queue' && isEnabled(job)) {
|
||||
const id = await boss.send(job.name, null, { singletonKey: `${job.name}-manual` });
|
||||
if (mode === 'queue' && boss) {
|
||||
// Marked manual so it runs even when the job is switched off.
|
||||
const id = await boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` });
|
||||
return { queued: true, id };
|
||||
}
|
||||
const output = await runJob(job);
|
||||
@@ -330,6 +437,7 @@ async function runNow(name) {
|
||||
|
||||
/** Each job with its schedule, next run and recent runs, for the admin page. */
|
||||
async function jobStatus(prisma) {
|
||||
await loadOverrides(true);
|
||||
const recent = new Map();
|
||||
if (mode === 'queue') {
|
||||
// pg-boss columns are timestamptz, and Prisma's pg adapter drops their offset in raw queries
|
||||
@@ -356,11 +464,16 @@ async function jobStatus(prisma) {
|
||||
return {
|
||||
mode,
|
||||
timezone: TIMEZONE,
|
||||
jobsEnabledEnv: flag('JOBS_ENABLED'),
|
||||
jobs: JOBS.map(job => {
|
||||
const cron = cronFor(job);
|
||||
const enabled = isEnabled(job);
|
||||
const o = overrides[job.name] || {};
|
||||
return {
|
||||
name: job.name, label: job.label, cron, enabled, envFlag: job.env,
|
||||
// 3.4.0: what the .env says, and the admin's choice over it (null: the .env applies).
|
||||
envEnabled: envEnabled(job), envCron: envCronFor(job), defaultCron: job.cron,
|
||||
override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron) ? o.cron : null },
|
||||
nextRun: enabled && mode !== 'off' ? nextRun(cron) : null,
|
||||
recent: recent.get(job.name) || [],
|
||||
};
|
||||
@@ -368,4 +481,7 @@ async function jobStatus(prisma) {
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { JOBS, TASKS, TIMEZONE, isEnabled, cronFor, nextRun, isNoop, startJobs, stopJobs, runNow, jobStatus, enqueueTask };
|
||||
module.exports = {
|
||||
JOBS, TASKS, TIMEZONE, isEnabled, envEnabled, cronFor, isCron, nextRun, isNoop, startJobs, stopJobs, runNow, jobStatus, enqueueTask,
|
||||
setOverride, loadOverrides, setOverridesForTest,
|
||||
};
|
||||
|
||||
@@ -100,7 +100,8 @@ v1Route({ method: 'put', path: '/privacy/breaches/:id', tag: 'Privacy', summary:
|
||||
// ─── Admin ───────────────────────────────────────────────────────────────────
|
||||
|
||||
v1Route({ method: 'get', path: '/admin/audit-log', tag: 'Admin', summary: 'The audit log', access: 'admin', query: filters('page', 'limit', 'actorId', 'action', 'role', 'from', 'to', 'search'), documented: { response: D.obj({ rows: z.array(D.auditEntry), total: D.num, page: D.num, limit: D.num }) }, v1: audit.listAuditLog });
|
||||
v1Route({ method: 'get', path: '/admin/jobs', tag: 'Admin', summary: 'Background jobs', access: 'admin', documented: { response: D.obj({ mode: D.str.describe('on, off or timers'), timezone: D.str, jobs: z.array(D.obj({ name: D.str, label: D.str, cron: D.optStr, enabled: D.bool, envFlag: D.optStr, nextRun: D.optDate, recent: z.array(D.anyObj).describe('Recent runs') })) }) }, v1: jobs.listJobs });
|
||||
v1Route({ method: 'get', path: '/admin/jobs', tag: 'Admin', summary: 'Background jobs', access: 'admin', documented: { response: D.obj({ mode: D.str.describe('queue, timers or off'), timezone: D.str, jobsEnabledEnv: D.bool.describe('JOBS_ENABLED in the .env'), jobs: z.array(D.obj({ name: D.str, label: D.str, cron: D.optStr, enabled: D.bool, envFlag: D.optStr, envEnabled: D.bool.describe('What the .env says'), envCron: D.str, defaultCron: D.str, override: D.obj({ enabled: z.boolean().nullable(), cron: D.optStr }).describe('What an admin chose over the .env (null: the .env applies)'), nextRun: D.optDate, recent: z.array(D.anyObj).describe('Recent runs') })) }) }, v1: jobs.listJobs });
|
||||
v1Route({ method: 'put', path: '/admin/jobs/:name', tag: 'Admin', summary: 'Switch a background job on or off, or change its schedule', access: 'admin', params: z.object({ name: z.string().min(1).max(100) }), body: z.object({ enabled: z.boolean().nullable().optional().describe('true or false wins over the .env; null goes back to it'), cron: z.string().max(100).nullable().optional().describe('A cron schedule (five fields) that wins over the .env; null or empty goes back to it') }), documented: { response: D.obj({ name: D.str, override: D.obj({ enabled: z.boolean().nullable(), cron: D.optStr }) }) }, v1: jobs.updateJob });
|
||||
v1Route({ method: 'post', path: '/admin/jobs/:name/run', tag: 'Admin', summary: 'Run a background job now', access: 'admin', params: z.object({ name: z.string().min(1).max(100) }), body: loose, documented: { response: D.obj({ queued: D.bool, id: D.optStr, output: z.unknown().optional().describe('When it ran straight away') }) }, v1: jobs.runJobNow });
|
||||
v1Route({ method: 'get', path: '/admin/impersonation-sessions', tag: 'Admin', summary: 'Times admins viewed the site as someone else', access: 'admin', query: filters('limit'), documented: { response: z.array(D.obj({ id: D.str, reason: D.optStr, startedAt: D.optDate, endedAt: D.optDate, expiresAt: D.optDate, admin: D.obj({ name: D.str, email: D.optStr }).nullish(), target: D.obj({ name: D.str, email: D.optStr }).nullish(), requests: z.array(D.obj({ method: D.str, path: D.str, blocked: D.bool, createdAt: D.date })).describe('What they did (up to 500)') })) }, v1: imp.listSessions });
|
||||
v1Route({ method: 'post', path: '/admin/impersonate/:userId', tag: 'Admin', summary: 'View the site as someone (read-only)', description: 'Answers a token for a read-only session, logged.', access: 'admin', params: z.object({ userId: z.string().min(1).max(64) }), body: loose, documented: { body: D.obj({ reason: D.str.describe('Why — kept in the log') }), response: D.obj({ token: D.str.describe('A read-only sign-in token'), session: D.obj({ id: D.str, expiresAt: D.date, target: D.obj({ id: D.str, name: D.str, email: D.str, role: D.str }) }) }) }, v1: imp.startImpersonation });
|
||||
|
||||
@@ -36,6 +36,41 @@ describe('job registry', () => {
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
test('3.4.0: an admin choice wins over the env flag and schedule; JOBS_ENABLED=false still wins over everything', () => {
|
||||
const { setOverridesForTest, envEnabled } = require('../src/jobs');
|
||||
try {
|
||||
delete process.env.JOBS_ENABLED;
|
||||
process.env.WAITLIST_JOB_ENABLED = 'false';
|
||||
process.env.JOB_SCHEDULE_WAITLIST = '*/5 * * * *';
|
||||
setOverridesForTest({ waitlist: { enabled: true, cron: '*/20 * * * *' }, backup: { enabled: false } });
|
||||
expect(envEnabled(job('waitlist'))).toBe(false);
|
||||
expect(isEnabled(job('waitlist'))).toBe(true);
|
||||
expect(cronFor(job('waitlist'))).toBe('*/20 * * * *');
|
||||
expect(isEnabled(job('backup'))).toBe(false);
|
||||
expect(isEnabled(job('temp-cleanup'))).toBe(true); // no env flag, no choice
|
||||
process.env.JOBS_ENABLED = 'false';
|
||||
expect(isEnabled(job('waitlist'))).toBe(false);
|
||||
// A broken saved schedule falls back to the env's.
|
||||
delete process.env.JOBS_ENABLED;
|
||||
setOverridesForTest({ waitlist: { cron: 'nonsense' } });
|
||||
expect(cronFor(job('waitlist'))).toBe('*/5 * * * *');
|
||||
expect(isEnabled(job('waitlist'))).toBe(false); // the env flag again
|
||||
} finally {
|
||||
setOverridesForTest({});
|
||||
}
|
||||
});
|
||||
|
||||
test('3.4.0: setOverride checks its input before saving', async () => {
|
||||
const { setOverride, isCron } = require('../src/jobs');
|
||||
expect(isCron('*/10 * * * *')).toBe(true);
|
||||
expect(isCron('0 7 * * *')).toBe(true);
|
||||
expect(isCron('every day')).toBe(false);
|
||||
expect(isCron('* * * * * *')).toBe(false); // seconds aren't offered
|
||||
await expect(setOverride('nope', { enabled: true })).rejects.toMatchObject({ statusCode: 404 });
|
||||
await expect(setOverride('waitlist', { enabled: 'yes' })).rejects.toMatchObject({ statusCode: 400 });
|
||||
await expect(setOverride('waitlist', { cron: 'every day' })).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
test('daily jobs fire at local (Johannesburg) time', () => {
|
||||
// 07:00 SAST = 05:00 UTC
|
||||
const next = nextRun('0 7 * * *', new Date('2026-11-04T06:00:00Z'));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.3.0",
|
||||
"version": "3.4.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useState } from "react";
|
||||
import { Timer, Play, RefreshCw } from "lucide-react";
|
||||
import { Timer, Play, RefreshCw, Pencil, RotateCcw } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { apiV2Data } from "@/lib/apiV2";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
|
||||
type JobRun = { state: string; createdOn?: string; startedOn: string | null; completedOn: string | null; output: unknown };
|
||||
type JobInfo = { name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[] };
|
||||
type JobsResponse = { mode: "queue" | "timers" | "off"; timezone: string; jobs: JobInfo[] };
|
||||
type Override = { enabled: boolean | null; cron: string | null };
|
||||
type JobInfo = {
|
||||
name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[];
|
||||
envEnabled: boolean; envCron: string; defaultCron: string; override: Override;
|
||||
};
|
||||
type JobsResponse = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: JobInfo[] };
|
||||
|
||||
const STATE: Record<string, string> = {
|
||||
completed: "bg-green-50 text-green-800",
|
||||
@@ -21,12 +26,23 @@ const STATE: Record<string, string> = {
|
||||
cancelled: "bg-gray-100 text-gray-500",
|
||||
};
|
||||
|
||||
const PRESETS: { label: string; cron: string }[] = [
|
||||
{ label: "Every minute", cron: "* * * * *" },
|
||||
{ label: "Every 5 minutes", cron: "*/5 * * * *" },
|
||||
{ label: "Every 15 minutes", cron: "*/15 * * * *" },
|
||||
{ label: "Every hour", cron: "0 * * * *" },
|
||||
{ label: "Daily at 02:00", cron: "0 2 * * *" },
|
||||
{ label: "Daily at 07:00", cron: "0 7 * * *" },
|
||||
];
|
||||
|
||||
const when = (d: string | null) => (d ? new Date(d).toLocaleString("en-GB", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) : "—");
|
||||
|
||||
function describeCron(cron: string): string {
|
||||
if (cron === "* * * * *") return "Every minute";
|
||||
const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron);
|
||||
if (m) return `Every ${m[1]} minutes`;
|
||||
const h = /^(\d+) \* \* \* \*$/.exec(cron);
|
||||
if (h) return `Every hour at :${h[1].padStart(2, "0")}`;
|
||||
const d = /^(\d+) (\d+) \* \* \*$/.exec(cron);
|
||||
if (d) return `Daily at ${d[2].padStart(2, "0")}:${d[1].padStart(2, "0")}`;
|
||||
return cron;
|
||||
@@ -38,13 +54,16 @@ function outputText(run: JobRun): string {
|
||||
try { return JSON.stringify(run.output); } catch { return ""; }
|
||||
}
|
||||
|
||||
// Settings → Background jobs: what runs when, the last runs of each job, and "Run now".
|
||||
// Settings → Background jobs: what runs when, the last runs of each job, "Run now", and (3.4.0)
|
||||
// switching a job on or off and changing its schedule here, over what the server's .env says.
|
||||
export function JobsTab({ active }: { active: boolean }) {
|
||||
const { token } = useAuth();
|
||||
const [data, setData] = useState<JobsResponse | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [running, setRunning] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState<string | null>(null);
|
||||
const [open, setOpen] = useState<string | null>(null);
|
||||
const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null);
|
||||
const [message, setMessage] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
@@ -75,6 +94,24 @@ export function JobsTab({ active }: { active: boolean }) {
|
||||
}
|
||||
};
|
||||
|
||||
/** Saves a choice for one job: a value wins over the .env, null goes back to it. */
|
||||
const save = async (job: JobInfo, change: { enabled?: boolean | null; cron?: string | null }, done: string) => {
|
||||
if (!token) return;
|
||||
setSaving(job.name);
|
||||
try {
|
||||
await apiV2Data("put", "/admin/jobs/{name}", { params: { name: job.name }, authToken: token, body: change });
|
||||
setMessage({ type: "ok", text: done });
|
||||
setEditing(null);
|
||||
await load();
|
||||
} catch (e) {
|
||||
setMessage({ type: "err", text: errorMessage(e) || "Couldn't save that" });
|
||||
} finally {
|
||||
setSaving(null);
|
||||
}
|
||||
};
|
||||
|
||||
const off = data?.mode === "off";
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
@@ -82,6 +119,7 @@ export function JobsTab({ active }: { active: boolean }) {
|
||||
<h2 className="text-lg font-semibold flex items-center gap-2"><Timer className="w-5 h-5 text-brand-600" /> Background jobs</h2>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Tasks the server runs on a schedule ({data?.timezone || "local"} time). Each runs once per schedule, even with more than one server process, and failed runs are retried.
|
||||
Switch a job on or off, or change when it runs: what you choose here wins over the server's .env and takes effect straight away.
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" onClick={load} disabled={loading} className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded border bg-white hover:bg-gray-50 disabled:opacity-50 shrink-0">
|
||||
@@ -89,24 +127,37 @@ export function JobsTab({ active }: { active: boolean }) {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{message && <div className={`p-3 border rounded text-sm ${message.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`}>{message.text}</div>}
|
||||
{message && <div role="status" className={`p-3 border rounded text-sm ${message.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`}>{message.text}</div>}
|
||||
{data?.mode === "timers" && (
|
||||
<div className="p-3 border rounded bg-amber-50 text-amber-900 text-sm">The job queue couldn'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]".</div>
|
||||
)}
|
||||
{data?.mode === "off" && (
|
||||
<div className="p-3 border rounded bg-gray-50 text-gray-700 text-sm">All background jobs are switched off (JOBS_ENABLED=false).</div>
|
||||
{off && (
|
||||
<div className="p-3 border rounded bg-gray-50 text-gray-700 text-sm">All background jobs are switched off in the server's .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change it from the Hub.</div>
|
||||
)}
|
||||
|
||||
<ul className="divide-y border rounded-lg">
|
||||
{(data?.jobs || []).map(job => {
|
||||
const last = job.recent[0];
|
||||
const busy = saving === job.name;
|
||||
const enabledHere = job.override.enabled !== null;
|
||||
const cronHere = job.override.cron !== null;
|
||||
const isEditing = editing?.name === job.name;
|
||||
return (
|
||||
<li key={job.name} className="p-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
|
||||
<Switch
|
||||
checked={job.enabled}
|
||||
disabled={busy || off}
|
||||
onCheckedChange={(on) => save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)}
|
||||
aria-label={`${job.label}: ${job.enabled ? "on" : "off"}`}
|
||||
/>
|
||||
<div className="min-w-0 mr-auto">
|
||||
<div className="font-medium text-sm text-gray-900">{job.label}</div>
|
||||
<div className={`font-medium text-sm ${job.enabled ? "text-gray-900" : "text-gray-500"}`}>{job.label}</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : `Off${job.envFlag ? ` (${job.envFlag}=false)` : ""}`}
|
||||
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : "Off"}
|
||||
{enabledHere
|
||||
? <> · {job.enabled ? "switched on" : "switched off"} here <button type="button" disabled={busy} className="underline hover:text-gray-700" onClick={() => save(job, { enabled: null }, `"${job.label}" follows the .env again (${job.envEnabled ? "on" : "off"}).`)}>use the .env ({job.envEnabled ? "on" : "off"})</button></>
|
||||
: !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""}
|
||||
</div>
|
||||
</div>
|
||||
{last && (
|
||||
@@ -114,11 +165,43 @@ export function JobsTab({ active }: { active: boolean }) {
|
||||
{last.state} · {when(last.completedOn || last.startedOn || last.createdOn || null)}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" disabled={running !== null || data?.mode === "off"} onClick={() => runNow(job)}
|
||||
<button type="button" disabled={busy || isEditing} onClick={() => setEditing({ name: job.name, cron: job.cron })}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border bg-white hover:bg-gray-50 disabled:opacity-50">
|
||||
<Pencil className="w-3.5 h-3.5" /> Schedule
|
||||
</button>
|
||||
<button type="button" disabled={running !== null || off} onClick={() => runNow(job)}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border border-brand-200 bg-brand-50 text-brand-700 hover:bg-brand-100 disabled:opacity-50">
|
||||
<Play className="w-3.5 h-3.5" /> {running === job.name ? "Starting…" : "Run now"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{isEditing && editing && (
|
||||
<form className="mt-3 rounded border bg-gray-50 p-3 space-y-2" onSubmit={e => { e.preventDefault(); save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{PRESETS.map(p => (
|
||||
<button key={p.cron} type="button" onClick={() => setEditing({ name: job.name, cron: p.cron })}
|
||||
className={`text-xs px-2 py-1 rounded border ${editing.cron === p.cron ? "bg-brand-50 border-brand-300 text-brand-800" : "bg-white hover:bg-gray-100"}`}>{p.label}</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-end gap-2">
|
||||
<label className="text-xs text-gray-600">
|
||||
Cron (minute hour day month weekday)
|
||||
<input value={editing.cron} onChange={e => setEditing({ name: job.name, cron: e.target.value })} maxLength={100}
|
||||
className="mt-1 block w-56 rounded border px-2 py-1 font-mono text-sm" aria-label="Cron schedule" />
|
||||
</label>
|
||||
<span className="text-xs text-gray-500 pb-1.5">{describeCron(editing.cron.trim())}</span>
|
||||
<div className="ml-auto flex gap-2">
|
||||
<button type="button" onClick={() => setEditing(null)} className="text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-100">Cancel</button>
|
||||
<button type="submit" disabled={busy || !editing.cron.trim()} className="text-xs px-2.5 py-1.5 rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50">{busy ? "Saving…" : "Save schedule"}</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">
|
||||
The server's own schedule for this job is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (set in the .env; normally ${describeCron(job.defaultCron)})` : ""}.
|
||||
{cronHere && <> <button type="button" disabled={busy} className="inline-flex items-center gap-1 underline hover:text-gray-700" onClick={() => save(job, { cron: null }, `"${job.label}" is back on its own schedule.`)}><RotateCcw className="w-3 h-3" /> Use that again</button></>}
|
||||
</p>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{open === job.name && job.recent.length > 0 && (
|
||||
<table className="mt-2 w-full text-xs">
|
||||
<thead className="text-gray-500"><tr><th className="text-left font-medium py-1">Started</th><th className="text-left font-medium">Finished</th><th className="text-left font-medium">State</th><th className="text-left font-medium">Result</th></tr></thead>
|
||||
@@ -139,7 +222,7 @@ export function JobsTab({ active }: { active: boolean }) {
|
||||
})}
|
||||
{!loading && data && data.jobs.length === 0 && <li className="p-3 text-sm text-gray-500">No jobs.</li>}
|
||||
</ul>
|
||||
<p className="text-xs text-gray-400">Change a schedule with the env var JOB_SCHEDULE_<NAME> (cron, e.g. JOB_SCHEDULE_WAITLIST="*/5 * * * *"), or switch one off with its own flag.</p>
|
||||
<p className="text-xs text-gray-400">Without a choice here, the server's .env applies: each job's own flag (e.g. WAITLIST_JOB_ENABLED=false) and JOB_SCHEDULE_<NAME>.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -61198,11 +61198,15 @@
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"description": "on, off or timers"
|
||||
"description": "queue, timers or off"
|
||||
},
|
||||
"timezone": {
|
||||
"type": "string"
|
||||
},
|
||||
"jobsEnabledEnv": {
|
||||
"type": "boolean",
|
||||
"description": "JOBS_ENABLED in the .env"
|
||||
},
|
||||
"jobs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -61229,6 +61233,38 @@
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"envEnabled": {
|
||||
"type": "boolean",
|
||||
"description": "What the .env says"
|
||||
},
|
||||
"envCron": {
|
||||
"type": "string"
|
||||
},
|
||||
"defaultCron": {
|
||||
"type": "string"
|
||||
},
|
||||
"override": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"cron": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"enabled"
|
||||
],
|
||||
"additionalProperties": {},
|
||||
"description": "What an admin chose over the .env (null: the .env applies)"
|
||||
},
|
||||
"nextRun": {
|
||||
"anyOf": [
|
||||
{
|
||||
@@ -61254,6 +61290,10 @@
|
||||
"name",
|
||||
"label",
|
||||
"enabled",
|
||||
"envEnabled",
|
||||
"envCron",
|
||||
"defaultCron",
|
||||
"override",
|
||||
"recent"
|
||||
],
|
||||
"additionalProperties": {}
|
||||
@@ -61263,6 +61303,7 @@
|
||||
"required": [
|
||||
"mode",
|
||||
"timezone",
|
||||
"jobsEnabledEnv",
|
||||
"jobs"
|
||||
],
|
||||
"additionalProperties": {}
|
||||
@@ -61299,6 +61340,157 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/admin/jobs/{name}": {
|
||||
"put": {
|
||||
"tags": [
|
||||
"Admin"
|
||||
],
|
||||
"summary": "Switch a background job on or off, or change its schedule",
|
||||
"description": "**Who:** Admins only.",
|
||||
"operationId": "putAdminJobsName",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "name",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "The name",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 100
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"description": "true or false wins over the .env; null goes back to it",
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"cron": {
|
||||
"description": "A cron schedule (five fields) that wins over the .env; null or empty goes back to it",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"override": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"cron": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"enabled"
|
||||
],
|
||||
"additionalProperties": {}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"override"
|
||||
],
|
||||
"additionalProperties": {}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Validation failed (VALIDATION_FAILED)",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Not signed in (UNAUTHENTICATED)",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Not allowed for this role (FORBIDDEN)",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Not found (NOT_FOUND)",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/admin/jobs/{name}/run": {
|
||||
"post": {
|
||||
"tags": [
|
||||
|
||||
+114
-1
@@ -6290,6 +6290,26 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/admin/jobs/{name}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
/**
|
||||
* Switch a background job on or off, or change its schedule
|
||||
* @description **Who:** Admins only.
|
||||
*/
|
||||
put: operations["putAdminJobsName"];
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/admin/jobs/{name}/run": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -35118,15 +35138,28 @@ export interface operations {
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
/** @description on, off or timers */
|
||||
/** @description queue, timers or off */
|
||||
mode: string;
|
||||
timezone: string;
|
||||
/** @description JOBS_ENABLED in the .env */
|
||||
jobsEnabledEnv: boolean;
|
||||
jobs: ({
|
||||
name: string;
|
||||
label: string;
|
||||
cron?: string | null;
|
||||
enabled: boolean;
|
||||
envFlag?: string | null;
|
||||
/** @description What the .env says */
|
||||
envEnabled: boolean;
|
||||
envCron: string;
|
||||
defaultCron: string;
|
||||
/** @description What an admin chose over the .env (null: the .env applies) */
|
||||
override: {
|
||||
enabled: boolean | null;
|
||||
cron?: string | null;
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
nextRun?: string | null;
|
||||
/** @description Recent runs */
|
||||
recent: {
|
||||
@@ -35161,6 +35194,86 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
putAdminJobsName: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The name */
|
||||
name: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
/** @description true or false wins over the .env; null goes back to it */
|
||||
enabled?: boolean | null;
|
||||
/** @description A cron schedule (five fields) that wins over the .env; null or empty goes back to it */
|
||||
cron?: string | null;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
name: string;
|
||||
override: {
|
||||
enabled: boolean | null;
|
||||
cron?: string | null;
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @description Validation failed (VALIDATION_FAILED) */
|
||||
400: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description Not signed in (UNAUTHENTICATED) */
|
||||
401: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description Not allowed for this role (FORBIDDEN) */
|
||||
403: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description Not found (NOT_FOUND) */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
postAdminJobsNameRun: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
||||
@@ -1,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",
|
||||
|
||||
Reference in New Issue
Block a user