Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9239d429a | ||
|
|
405b5f1b92 | ||
|
|
c8c5db46bc | ||
|
|
031fb11e02 | ||
|
|
16d3ffe6ba | ||
|
|
eac6564e11 | ||
|
|
8f78fcc75c | ||
|
|
cacbb16895 | ||
|
|
08b58ae310 | ||
|
|
e32a3b6144 | ||
|
|
bbcafe61b9 |
@@ -2,6 +2,57 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## accounts@1.6.0 - 2026-11-20
|
||||
|
||||
- **Accounts 1.6.0:** a "New sign-in" email (and WhatsApp for a verified number) after every
|
||||
sign-in, as Cross Events' own sign-in did; Sign-in settings → `signin_notices` turns it off.
|
||||
|
||||
## events@3.6.0, accounts@1.5.0, contracts@1.14.0 - 2026-11-20
|
||||
|
||||
A nightly check that each site's copies of people match their church accounts, for changes that
|
||||
never arrived.
|
||||
|
||||
- **Contracts 1.14.0:** `people.check` in `crosscode.identity-request/1` (`PEOPLE_CHECK_MAX` 500)
|
||||
and `peopleCheckReplySchema` (each sub `active` / `deactivated` / `deleted` / `unknown`, with the
|
||||
profile for the first two). Samples and JSON Schema `people-check-reply`.
|
||||
- **Accounts 1.5.0:** answers it, only with profiles of people the product knows.
|
||||
- **Events 3.6.0:** the `accounts-people-check` job (04:30): fixes out-of-date copies, handles
|
||||
deleted accounts as `user.deleted`, and stops if most people are unknown (wrong Accounts?).
|
||||
|
||||
## events@3.5.0, contracts@1.13.0, agent@1.3.1 - 2026-11-20
|
||||
|
||||
- **Agent 1.3.1:** agent 1.3.0 still reported itself as 1.2.0 (`AGENT_VERSION` in `src/stats.ts`
|
||||
wasn't bumped with `package.json`), so the Hub refused `.env` jobs on it. Use 1.3.1.
|
||||
|
||||
Loading demo data left a site that signs in through Accounts with no Accounts link, so nobody could
|
||||
sign in (`ACCOUNTS_UNAVAILABLE`, found on events-demo). The Hub (2.9.0) now sees it.
|
||||
|
||||
- **Contracts 1.13.0:** `stats.signIn` in the Cross Events heartbeat (mode, the linked Accounts,
|
||||
the last sign-in failure; optional).
|
||||
- **Events 3.5.0:** `set-demo.js` keeps `ProductLink` and `LinkNonce`; a site in Accounts mode
|
||||
without a link reconnects at its next heartbeat even after an earlier auto-connect; sign-in
|
||||
failures (start, finish, Accounts unreachable) are kept and sent to the Hub; What's New notes for
|
||||
3.4.0 (and Accounts 1.4.0) that were missing.
|
||||
|
||||
## events@3.4.0, accounts@1.4.0, contracts@1.12.0, agent@1.3.0, crosscode script - 2026-11-20
|
||||
|
||||
Background jobs are switched on and off (and rescheduled) from each site's admin, over the .env;
|
||||
Accounts' emails look like Cross Events'; the Hub shows and changes an install's .env (Hub 2.8.0).
|
||||
|
||||
- **Contracts 1.12.0:** `env-read` and `env-set` agent jobs, `envReadResultSchema`,
|
||||
`isSecretEnvName` / `SECRET_ENV_NAME`, `ENV_JOBS_MIN_AGENT` (1.3.0). `env-set` refuses secrets,
|
||||
newlines, files other than `backend/.env` / `frontend/.env.production`, and empty changes.
|
||||
- **crosscode script:** `crosscode env <church> <product>` prints the product's .env values
|
||||
(secrets only as set or not); with `--set NAME=value`, `--unset NAME` and `--restart` it changes
|
||||
one file (a copy is kept, the last 5), rebuilds the frontend when its file changed, reloads, and
|
||||
waits for `/health`; if that fails the file is put back (and rebuilt). Secrets and generated
|
||||
values are refused (`lib/envedit.cjs`). Tests: `scripts/tests/envedit.bats`.
|
||||
- **Agent 1.3.0:** runs `env-read` and `env-set` as `crosscode env`.
|
||||
- **Events 3.4.0:** Settings → Background jobs switches each job on or off and changes its
|
||||
schedule; the choice is kept in the database, wins over the .env and applies straight away.
|
||||
- **Accounts 1.4.0:** Admin → Background jobs (the same as Events'); every email is styled as
|
||||
Cross Events' (church colour and logo, a button, contact details), with the same plain text.
|
||||
|
||||
## events@3.3.0, accounts@1.3.0, contracts@1.11.0 - 2026-11-20
|
||||
|
||||
Accounts looks like Cross Events and backs itself up; fixes in Events' sign-out and branding uploads.
|
||||
|
||||
@@ -1,5 +1,52 @@
|
||||
# Changelog — Accounts
|
||||
|
||||
## [1.6.0] - 2026-11-20
|
||||
|
||||
### Added
|
||||
|
||||
- **"New sign-in" notices**, as Cross Events' own sign-in sends (`src/accounts/signInNotice.ts`):
|
||||
after each completed sign-in (the interaction reaching done, so not the silent ones a second
|
||||
product gets from an existing session), an email with when, the site, rough location and device
|
||||
(`newSignInEmail` in `src/lib/emails.ts`), and a WhatsApp message when the person has a verified
|
||||
number and WhatsApp is set up. Location from ip-api.com in production only, never for private
|
||||
addresses. Fire-and-forget: never holds up or fails a sign-in. Admins can turn it off:
|
||||
`signin_notices` (Sign-in settings, on by default). In Accounts mode Cross Events no longer sends
|
||||
its own, so before this nobody was told.
|
||||
|
||||
## [1.5.0] - 2026-11-20
|
||||
|
||||
Needs contracts 1.14.0.
|
||||
|
||||
### Added
|
||||
|
||||
- `people.check` (contracts 1.14.0): for up to 500 subs, the current profile of each person the
|
||||
product knows (`active` / `deactivated`), `deleted` for a deleted account, `unknown` for anyone
|
||||
else (no profile). Audited once per request (`people_checked_by_product`, counts only); the reply
|
||||
isn't stored for retries, since it holds profiles. Cross Events 3.6.0 asks nightly.
|
||||
|
||||
## [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.
|
||||
|
||||
@@ -3,6 +3,28 @@
|
||||
What each version changes for the church, in plain language (read by the Hub like Cross Events'
|
||||
WHATS-NEW.md; a section shows once its version is tagged).
|
||||
|
||||
## 1.6.0
|
||||
|
||||
- **You're told about each sign-in.** After someone signs in, they get an email saying when, roughly
|
||||
where, on what device and to which site, with what to do if it wasn't them, as Cross Events
|
||||
does for its own sign-in. People with a confirmed WhatsApp number get it on WhatsApp too.
|
||||
Admins can turn this off under Sign-in settings.
|
||||
|
||||
## 1.5.0
|
||||
|
||||
- Your church's sites can now check every night that the details they keep for each person match
|
||||
their church account (Cross Events 3.6.0 does), so a change that didn't reach a site is fixed the
|
||||
next morning.
|
||||
|
||||
## 1.4.0
|
||||
|
||||
- **Better-looking emails.** Sign-in codes, password links, "your account is ready" and the other
|
||||
emails from your church account now look like Cross Events' emails: your church's colour and logo
|
||||
at the top, a clear button, and your church's contact details at the bottom.
|
||||
- Admins: **Admin → Background jobs** shows what Accounts does on a schedule (backups, privacy
|
||||
requests, tidying up), when it last ran, and lets you run a job now, switch it off or change when
|
||||
it runs.
|
||||
|
||||
## 1.3.0
|
||||
|
||||
- Your account and the admin pages have a new look, like Cross Events: a menu down the side, and
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.3.0",
|
||||
"version": "1.6.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');
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* "New sign-in" notices (1.6.0), as Cross Events sends for its own sign-in: after each completed
|
||||
* sign-in, an email to the person, and a WhatsApp message too when they have a verified number and
|
||||
* WhatsApp is set up. Admins can turn them off (Sign-in settings, `signin_notices`). Never holds up
|
||||
* or fails the sign-in.
|
||||
*
|
||||
* The rough location comes from the IP (ip-api.com, as Cross Events), in production only, and never
|
||||
* for private addresses.
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
import { newSignInEmail } from '../lib/emails.js';
|
||||
import { productName } from '../oidc/clients.js';
|
||||
|
||||
const PRIVATE_IP = /^(::1$|127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|fc|fd|fe80|::ffff:(127|10|192\.168)\.)/i;
|
||||
|
||||
/** "Chrome on Windows" from a user agent; the raw string when it can't tell. */
|
||||
export function describeDevice(ua: string | null | undefined): string {
|
||||
const s = String(ua || '');
|
||||
if (!s) return 'Unknown device';
|
||||
const browser = /Edg\//.test(s) ? 'Edge' : /OPR\/|Opera/.test(s) ? 'Opera' : /Firefox\//.test(s) ? 'Firefox'
|
||||
: /SamsungBrowser\//.test(s) ? 'Samsung Internet' : /Chrome\//.test(s) ? 'Chrome' : /Safari\//.test(s) ? 'Safari' : null;
|
||||
const os = /iPhone|iPad|iPod/.test(s) ? 'iPhone or iPad' : /Android/.test(s) ? 'Android' : /Windows/.test(s) ? 'Windows'
|
||||
: /Mac OS X|Macintosh/.test(s) ? 'a Mac' : /CrOS/.test(s) ? 'a Chromebook' : /Linux/.test(s) ? 'Linux' : null;
|
||||
if (browser && os) return `${browser} on ${os}`;
|
||||
return browser || os || s.slice(0, 120);
|
||||
}
|
||||
|
||||
async function roughLocation(ctx: Ctx, ip: string | null): Promise<string> {
|
||||
if (!ip || PRIVATE_IP.test(ip) || !ctx.config.production) return 'Unknown';
|
||||
try {
|
||||
const res = await fetch(`http://ip-api.com/json/${encodeURIComponent(ip.replace(/^::ffff:/, ''))}?fields=status,city,regionName,country`, { signal: AbortSignal.timeout(3000) });
|
||||
const geo = (await res.json()) as { status?: string; city?: string; regionName?: string; country?: string };
|
||||
const parts = geo.status === 'success' ? [geo.city, geo.regionName, geo.country].filter(Boolean) : [];
|
||||
return parts.length ? parts.join(', ') : 'Unknown';
|
||||
} catch {
|
||||
return 'Unknown';
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendSignInNotice(ctx: Ctx, o: { accountId: string; ip: string | null; userAgent: string | null; clientId: string | null }): Promise<'sent' | 'off' | 'failed'> {
|
||||
try {
|
||||
if (!(await ctx.settings.bool('signin_notices', true))) return 'off';
|
||||
const a = await ctx.db.account.findUnique({ where: { id: o.accountId } });
|
||||
if (!a || a.status !== 'active') return 'off';
|
||||
const link = o.clientId ? await ctx.db.productLink.findUnique({ where: { installId: o.clientId } }) : null;
|
||||
const site = link ? productName(link.product) : o.clientId === 'accounts-self' ? 'Your account page' : null;
|
||||
const when = ctx.now().toLocaleString('en-ZA', { timeZone: ctx.config.timezone, dateStyle: 'medium', timeStyle: 'short' });
|
||||
const msg = await newSignInEmail(ctx, { name: a.name, when, location: await roughLocation(ctx, o.ip), device: describeDevice(o.userAgent), site });
|
||||
await ctx.messenger.email({ to: a.email, subject: msg.subject, text: msg.text, html: msg.html });
|
||||
if (a.phone && a.phoneVerified && (await ctx.messenger.whatsappReady())) {
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text: msg.whatsapp }).catch((e: Error) => console.warn('[sign-in notice] WhatsApp:', e.message));
|
||||
}
|
||||
return 'sent';
|
||||
} catch (e) {
|
||||
console.warn('[sign-in notice] not sent:', (e as Error).message);
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
@@ -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) => {
|
||||
|
||||
@@ -8,7 +8,9 @@ import type Provider from 'oidc-provider';
|
||||
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 { clientIp, loginEvent } from '../lib/audit.js';
|
||||
import { sendSignInNotice } from '../accounts/signInNotice.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';
|
||||
@@ -43,6 +45,8 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
|
||||
const clientId = String(details.params.client_id ?? '') || null;
|
||||
await loginEvent(ctx, pending.accountId, 'sign_in', req, { clientId, detail: { amr: pending.amr } });
|
||||
await signedInThrough(ctx, clientId, pending.accountId);
|
||||
// 1.6.0: "New sign-in" email (and WhatsApp), as Cross Events; never waited for.
|
||||
if (pending.accountId) void sendSignInNotice(ctx, { accountId: pending.accountId, ip: clientIp(req), userAgent: req.get('user-agent') ?? null, clientId });
|
||||
await ctx.db.pendingSignIn.deleteMany({ where: { uid: pending.uid } });
|
||||
return { stage: 'done', redirectTo, ...extra };
|
||||
}
|
||||
@@ -97,11 +101,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,225 @@
|
||||
/**
|
||||
* 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.') };
|
||||
}
|
||||
|
||||
/** A sign-in happened (1.6.0, as Cross Events' "New login detected"). `whatsapp`: the same in a few lines. */
|
||||
export async function newSignInEmail(ctx: Ctx, o: { name?: string | null; when: string; location: string; device: string; site: string | null }): Promise<Built & { whatsapp: string }> {
|
||||
const b = await brand(ctx);
|
||||
const row = (k: string, v: string) => `<tr><td style="padding:10px 14px;border-top:1px solid #f1f5f9;color:#64748b;font-size:13px;font-weight:600;width:34%">${esc(k)}</td><td style="padding:10px 14px;border-top:1px solid #f1f5f9;color:#1e293b;font-size:14px;word-break:break-word">${esc(v)}</td></tr>`;
|
||||
const body = title('New sign-in', `Someone signed in to your ${b.name} account`)
|
||||
+ hello(o.name)
|
||||
+ `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;margin:0 0 8px 0">`
|
||||
+ row('When', o.when) + (o.site ? row('Signed in to', o.site) : '') + row('Where (roughly)', o.location) + row('Device', o.device)
|
||||
+ '</table>'
|
||||
+ callout(`<strong>Not you?</strong> Change your password straight away from your account page, and let the church office know${contactLine(b)}.`, 'warning')
|
||||
+ small('If this was you, there\'s nothing to do.');
|
||||
const lines = [`When: ${o.when}`, ...(o.site ? [`Signed in to: ${o.site}`] : []), `Where (roughly): ${o.location}`, `Device: ${o.device}`];
|
||||
const text = `Hello ${o.name || 'there'},\n\nSomeone signed in to your ${b.name} account.\n\n${lines.join('\n')}\n\nIf this wasn't you, change your password straight away and let the church office know${b.email ? ` (${b.email})` : ''}.\nIf it was you, there's nothing to do.`;
|
||||
const whatsapp = `🔐 *New sign-in*\n\nHello ${o.name || 'there'}, someone signed in to your *${b.name}* account.\n\n${lines.join('\n')}\n\nNot you? Change your password straight away and let the church office know.`;
|
||||
return { subject: `New sign-in to your ${b.name} account`, text, html: layout(b, body, `New sign-in: ${o.when}, ${o.device}.`), whatsapp };
|
||||
}
|
||||
@@ -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> {
|
||||
|
||||
@@ -9,7 +9,7 @@ export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_i
|
||||
|
||||
/** The settings an admin may read and change through the generic settings API. */
|
||||
export const ADMIN_SETTINGS = new Set([
|
||||
'signup_enabled', 'two_factor_required_for_admins', 'session_days',
|
||||
'signup_enabled', 'two_factor_required_for_admins', 'session_days', 'signin_notices',
|
||||
'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure',
|
||||
'wawp_access_token', 'wawp_instance_id',
|
||||
]);
|
||||
|
||||
@@ -23,10 +23,11 @@ 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';
|
||||
import { emailProblem, normaliseEmail, profileChanged, setNewsConsent } from '../accounts/service.js';
|
||||
import { emailProblem, normaliseEmail, profileChanged, profileOf, setNewsConsent } from '../accounts/service.js';
|
||||
import { turnOff } from '../accounts/twoFactor.js';
|
||||
import { signOutEverywhere } from '../oidc/sessions.js';
|
||||
import { anonymise } from '../privacy/deletion.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);
|
||||
@@ -307,6 +303,22 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
await logRequest(ctx, link, r, 'demo_people_removed_by_product', null, req, { removed, kept: kept.length });
|
||||
return reply({ removed, kept });
|
||||
}
|
||||
case 'people.check': {
|
||||
// 1.5.0: the product's regular check that its copies are current. Profiles only for people
|
||||
// this product knows; a deleted account is said to be deleted (its sub was that person's).
|
||||
const subs = [...new Set(r.subs)];
|
||||
const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: subs } }, select: { accountId: true } })).map((p) => p.accountId));
|
||||
const accounts = new Map((await ctx.db.account.findMany({ where: { id: { in: subs } } })).map((a) => [a.id, a]));
|
||||
const people = subs.map((sub) => {
|
||||
const a = accounts.get(sub);
|
||||
if (a?.status === 'deleted') return { sub, status: 'deleted' as const, profile: null };
|
||||
if (!a || !known.has(sub)) return { sub, status: 'unknown' as const, profile: null };
|
||||
return { sub, status: a.status === 'deactivated' ? 'deactivated' as const : 'active' as const, profile: profileOf(a) };
|
||||
});
|
||||
const count = (s: string) => people.filter((p) => p.status === s).length;
|
||||
await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') });
|
||||
return reply({ people });
|
||||
}
|
||||
case 'church.branding': {
|
||||
const changed = await applyLook(ctx, r.church, r.overwrite);
|
||||
await logRequest(ctx, link, r, 'church_look_from_product', null, req, { changed, overwrite: r.overwrite });
|
||||
@@ -325,7 +337,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 }) });
|
||||
@@ -386,7 +398,8 @@ export function requestsRouter(ctx: Ctx, provider: Provider) {
|
||||
}
|
||||
const out = await handle(ctx, provider, link, secret, request, req);
|
||||
// Checks write nothing, so they needn't be remembered.
|
||||
const isCheck = 'check' in request && request.check;
|
||||
// people.check (1.5.0) only reads, and its reply holds profiles: never kept.
|
||||
const isCheck = ('check' in request && request.check) || request.type === 'people.check';
|
||||
if (!isCheck) {
|
||||
await ctx.db.productRequest.create({ data: { requestId: request.requestId, linkId: link.installId, type: request.type, reply: out as never, createdAt: ctx.now() } }).catch(() => {});
|
||||
}
|
||||
|
||||
@@ -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>/);
|
||||
});
|
||||
});
|
||||
@@ -199,6 +199,29 @@ describe('people.* from a product', () => {
|
||||
assert.equal(again.body.created, true);
|
||||
});
|
||||
|
||||
test('1.5.0 people.check: profiles of the product\'s people, deleted accounts, and unknown for the rest; never stored', async () => {
|
||||
const ensure = (name: string, email: string) => ask({ type: 'people.ensure', name, email, phone: null, returnUrl: 'https://events.hope.test/' }).then((r) => r.body.sub as string);
|
||||
const known = await ensure('Check Known', 'check.known@hope.test');
|
||||
const gone = await ensure('Check Gone', 'check.gone@hope.test');
|
||||
await h.db.account.update({ where: { id: gone }, data: { status: 'deleted' } });
|
||||
const off = await ensure('Check Off', 'check.off@hope.test');
|
||||
await h.db.account.update({ where: { id: off }, data: { status: 'deactivated' } });
|
||||
const stranger = (await h.makeAccount({ email: 'check.stranger@hope.test' })).id as string;
|
||||
const nobody = crypto.randomUUID();
|
||||
const requestId = crypto.randomUUID();
|
||||
const res = await ask({ type: 'people.check', subs: [known, gone, off, stranger, nobody] }, { requestId });
|
||||
assert.equal(res.status, 200, JSON.stringify(res.body));
|
||||
const bySub = Object.fromEntries((res.body.people as { sub: string; status: string; profile: { name: string } | null }[]).map((p) => [p.sub, p]));
|
||||
assert.equal(bySub[known]!.status, 'active');
|
||||
assert.equal(bySub[known]!.profile!.name, 'Check Known');
|
||||
assert.equal(bySub[gone]!.status, 'deleted');
|
||||
assert.equal(bySub[gone]!.profile, null);
|
||||
assert.equal(bySub[off]!.status, 'deactivated');
|
||||
assert.deepEqual([bySub[stranger]!.status, bySub[stranger]!.profile], ['unknown', null], 'not known through this product: no profile');
|
||||
assert.equal(bySub[nobody]!.status, 'unknown');
|
||||
assert.equal(await h.db.productRequest.findUnique({ where: { requestId } }), null, 'the reply holds profiles: not kept');
|
||||
});
|
||||
|
||||
test('a retry with the same request id gets the same answer; a bad signature is refused', async () => {
|
||||
const requestId = crypto.randomUUID();
|
||||
const body = { type: 'people.ensure', name: 'Retry', email: 'retry@hope.test', phone: null, returnUrl: 'https://events.hope.test/' };
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// 1.6.0: a "New sign-in" email (and WhatsApp) after each sign-in, as Cross Events sends.
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import { startHarness, type Harness } from './support/harness.js';
|
||||
import { describeDevice, sendSignInNotice } from '../src/accounts/signInNotice.js';
|
||||
import type { MemoryMessenger } from '../src/lib/messages.js';
|
||||
|
||||
let h: Harness;
|
||||
before(async () => { h = await startHarness(); });
|
||||
after(async () => { await h.close(); });
|
||||
|
||||
const CHROME_WIN = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36';
|
||||
|
||||
describe('sign-in notices', () => {
|
||||
test('an email with when, where, the device and the site; WhatsApp too for a verified number', async () => {
|
||||
const m = h.ctx.messenger as MemoryMessenger;
|
||||
const a = await h.makeAccount({ email: 'notice.person@hope.test' });
|
||||
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: '127.0.0.1', userAgent: CHROME_WIN, clientId: 'accounts-self' }), 'sent');
|
||||
const mail = m.emails.filter((e) => e.to === 'notice.person@hope.test').at(-1)!;
|
||||
assert.match(mail.subject, /^New sign-in to your .+ account$/);
|
||||
assert.match(mail.text, /Device: Chrome on Windows/);
|
||||
assert.match(mail.text, /Signed in to: Your account page/);
|
||||
assert.match(mail.html ?? '', /Not you\?/);
|
||||
|
||||
await h.db.account.update({ where: { id: a.id as string }, data: { phone: '+27821234567', phoneVerified: true } });
|
||||
m.whatsappOn = true;
|
||||
const before = m.whatsapps.length;
|
||||
await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null });
|
||||
assert.equal(m.whatsapps.length, before + 1);
|
||||
assert.match(m.whatsapps.at(-1)!.text, /New sign-in/);
|
||||
m.whatsappOn = false;
|
||||
});
|
||||
|
||||
test('admins can switch them off; a failing email never throws', async () => {
|
||||
const m = h.ctx.messenger as MemoryMessenger;
|
||||
const a = await h.makeAccount({ email: 'notice.off@hope.test' });
|
||||
await h.ctx.settings.set('signin_notices', 'false');
|
||||
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null }), 'off');
|
||||
await h.ctx.settings.set('signin_notices', null);
|
||||
m.emailOn = false;
|
||||
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null }), 'failed');
|
||||
m.emailOn = true;
|
||||
});
|
||||
|
||||
test('device names', () => {
|
||||
assert.equal(describeDevice(CHROME_WIN), 'Chrome on Windows');
|
||||
assert.equal(describeDevice('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Version/17.0 Mobile/15E148 Safari/604.1'), 'Safari on iPhone or iPad');
|
||||
assert.equal(describeDevice(null), 'Unknown device');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.3.0",
|
||||
"version": "1.6.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";
|
||||
@@ -57,10 +57,11 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
|
||||
{section === "deletions" && <Deletions flash={flash} />}
|
||||
{section === "church" && <Church flash={flash} />}
|
||||
{section === "linked" && <Linked flash={flash} />}
|
||||
{section === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "session_days"]} />}
|
||||
{section === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "signin_notices", "session_days"]} />}
|
||||
{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>
|
||||
@@ -251,6 +252,7 @@ function Linked({ flash }: { flash: Flash }) {
|
||||
const SETTING_LABELS: Record<string, [string, "bool" | "text" | "secret" | "number"]> = {
|
||||
signup_enabled: ["Members can create their own account", "bool"],
|
||||
two_factor_required_for_admins: ["Admins must use two-step sign-in", "bool"],
|
||||
signin_notices: ["Tell people by email (and WhatsApp) each time they sign in", "bool"],
|
||||
session_days: ['Days "Keep me signed in" lasts', "number"],
|
||||
smtp_host: ["SMTP server", "text"], smtp_port: ["SMTP port", "number"], smtp_user: ["SMTP user name", "text"], smtp_pass: ["SMTP password", "secret"],
|
||||
smtp_from: ["Send from (email address)", "text"], smtp_secure: ["Use TLS from the start (port 465)", "bool"],
|
||||
@@ -265,7 +267,7 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
if (!values) return <p className="text-gray-600">Loading…</p>;
|
||||
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true };
|
||||
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true, signin_notices: true };
|
||||
return (
|
||||
<Card>
|
||||
<form onSubmit={async (e) => {
|
||||
@@ -463,3 +465,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.1",
|
||||
"private": true,
|
||||
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
|
||||
"license": "UNLICENSED",
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -12,7 +12,7 @@ import { paths } from "./paths";
|
||||
* the tools that are there; anything missing is null rather than an error.
|
||||
*/
|
||||
|
||||
export const AGENT_VERSION = "1.2.0";
|
||||
export const AGENT_VERSION = "1.3.1";
|
||||
|
||||
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
|
||||
@@ -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,57 @@ 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.6.0] - 2026-11-20
|
||||
|
||||
Works with any Accounts; the people check needs Accounts 1.5.0 (with an older one it's skipped).
|
||||
|
||||
### Added
|
||||
|
||||
- **The nightly people check** (`accounts-people-check`, 04:30, `ACCOUNTS_PEOPLE_CHECK_ENABLED`,
|
||||
`src/accounts/peopleCheck.ts`). In Accounts mode it sends every linked person's `sub` to
|
||||
Accounts, 500 at a time (`people.check`, contracts 1.14.0), and: updates the local copy where the
|
||||
name, email, phone or news choices differ (as `user.updated`); handles deleted accounts as
|
||||
`user.deleted` (anonymised, or deferred while there's a registration for an event that hasn't
|
||||
ended); counts deactivated and unknown people. When more than half a page (10+) is unknown, the
|
||||
site is probably linked to the wrong Accounts: the check stops, changes nothing for them, fails
|
||||
(Background jobs, the Hub's "jobs failing") and records why (the Hub's "sign-in failed" alert).
|
||||
|
||||
## [3.5.0] - 2026-11-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- **After "Load demo data" nobody could sign in** ("Sign-in isn't available right now",
|
||||
`ACCOUNTS_UNAVAILABLE`). `scripts/set-demo.js` emptied `ProductLink` (it keeps only a few tables)
|
||||
but kept `AppSetting`, so the site stayed in Accounts mode with no Accounts link, and
|
||||
`accounts_auto_connected` stopped it reconnecting. Demo data now keeps `ProductLink` and
|
||||
`LinkNonce`, and a site in Accounts mode without a link connects to the Accounts the Hub lists at
|
||||
its next heartbeat whatever happened before (a site on its own sign-in still keeps an admin's
|
||||
Disconnect).
|
||||
|
||||
### Added
|
||||
|
||||
- Heartbeat `stats.signIn` (contracts 1.13.0): the sign-in mode, the linked Accounts (install id and
|
||||
address) and the last failure to start or finish a sign-in (`accounts_last_signin_error`, cleared
|
||||
by the next sign-in that works). The Hub 2.9.0 alerts on it.
|
||||
|
||||
## [3.4.0] - 2026-11-20
|
||||
|
||||
### Added
|
||||
|
||||
- **Background jobs are switched on and off from Settings → Background jobs.** Each job has a
|
||||
switch and a Schedule button (presets or a cron expression). The choice is saved in the database
|
||||
(`AppSetting` `job_overrides`), wins over the .env (the job's own flag such as
|
||||
`WAITLIST_JOB_ENABLED`, and `JOB_SCHEDULE_<NAME>`), and applies straight away: the queue is
|
||||
rescheduled in this process, and other processes see it within 30 seconds (a run of a job switched
|
||||
off elsewhere is skipped). "use the .env" goes back to what the server says.
|
||||
`JOBS_ENABLED=false` still turns every job off (the end-to-end tests use it).
|
||||
API: `PUT /api/v2/admin/jobs/:name` `{ enabled, cron }` (null goes back to the .env); `GET
|
||||
/admin/jobs` also gives `envEnabled`, `envCron`, `defaultCron` and `override`.
|
||||
|
||||
### Changed
|
||||
|
||||
- "Run now" also works for a job that's switched off.
|
||||
|
||||
## [3.3.0] - 2026-11-20
|
||||
|
||||
Works with Accounts 1.3.0 (needed for the demo-data part; with an older Accounts the old demo people
|
||||
|
||||
@@ -12,6 +12,28 @@ Write for church admins, not developers: no environment variables, endpoints or
|
||||
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||
-->
|
||||
|
||||
## 3.6.0
|
||||
|
||||
- **People's details are checked every night.** Cross Events compares everyone's name, email,
|
||||
phone and news choices with their church account and fixes any that are out of date, and handles
|
||||
accounts that were deleted, in case a change never reached this site. You can see it, run it or
|
||||
switch it off under Settings → Background jobs. It needs Accounts 1.5.0.
|
||||
|
||||
## 3.5.0
|
||||
|
||||
- **Fix:** after loading demo data, nobody could sign in: the site forgot its link to the church's
|
||||
sign-in (Accounts). Demo data keeps it now, and a site that lost it connects again by itself
|
||||
within about 15 minutes of updating.
|
||||
- When signing in fails, Cross Code is told why, so it can help sooner.
|
||||
|
||||
## 3.4.0
|
||||
|
||||
- **Switch background jobs on and off yourself.** Settings → Background jobs has a switch for each
|
||||
job (reminders, backups, the daily summary and so on) and lets you change when it runs, with ready
|
||||
choices such as "every 15 minutes" or "daily at 07:00". It works straight away, no restart needed,
|
||||
and one click puts a job back to how the server normally runs it.
|
||||
- **Run now** works for a job that's switched off too, for when you want it once.
|
||||
|
||||
## 3.3.0
|
||||
|
||||
- **Fix:** a new logo or favicon sometimes didn't show after saving. It's saved and shown properly
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.3.0",
|
||||
"version": "3.6.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -76,6 +76,9 @@ const LIST_ONLY = process.argv.includes('--list');
|
||||
const KEEP_TABLES = new Set([
|
||||
'_prisma_migrations', 'AppSetting', 'User',
|
||||
'SecurityEvent', 'PasswordReset', 'TwoFactorChallenge', 'TrustedDevice',
|
||||
// 3.5.0: the links to the church's other products (Accounts above all: in Accounts mode, without
|
||||
// its link nobody can sign in). Their feeds are data and go.
|
||||
'ProductLink', 'LinkNonce',
|
||||
]);
|
||||
|
||||
const SCHEDULED_EMAILS_PATH = path.resolve(__dirname, '../data/scheduled-emails.json');
|
||||
|
||||
@@ -7,12 +7,16 @@
|
||||
import { connectTo } from '../links/connect';
|
||||
import { linkedProducts } from '../links/store';
|
||||
import { accountsLink } from './client';
|
||||
import { getSetting, setSetting } from './mode';
|
||||
import { getSetting, setSetting, viaAccounts } from './mode';
|
||||
|
||||
export const AUTO_KEY = 'accounts_auto_connected';
|
||||
|
||||
export async function connectAccountsIfListed(now = new Date()): Promise<'connected' | 'skipped'> {
|
||||
if (await getSetting(AUTO_KEY)) return 'skipped';
|
||||
// 3.5.0: a site that signs in through Accounts but has lost its link (before 3.5.0, loading demo
|
||||
// data deleted it) can't sign anyone in, so it reconnects whatever was done before. A site on its
|
||||
// own sign-in keeps an admin's Disconnect.
|
||||
const stranded = (await viaAccounts()) && !(await accountsLink());
|
||||
if ((await getSetting(AUTO_KEY)) && !stranded) return 'skipped';
|
||||
if (await accountsLink()) {
|
||||
await setSetting(AUTO_KEY, now.toISOString());
|
||||
return 'skipped';
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* The nightly people check (3.6.0, contracts 1.14.0 `people.check`, Accounts 1.5.0): Accounts tells
|
||||
* Events about every change (`user.updated`, `user.deleted`), retried for about a week; this catches
|
||||
* whatever never arrived (a link that was down, as after a demo load before 3.5.0). For everyone here
|
||||
* with an account it asks Accounts, a page at a time, and:
|
||||
*
|
||||
* - updates the local copy when the profile differs (as `user.updated` does);
|
||||
* - handles a deleted account as `user.deleted` does (anonymised, or deferred while the person has a
|
||||
* registration for an event that hasn't ended);
|
||||
* - only counts people Accounts doesn't know through this site (`unknown`). When most of a page is
|
||||
* unknown, Events is probably linked to the wrong Accounts: the check stops and fails, so it
|
||||
* shows on Background jobs and the Hub, and nothing is changed for those people.
|
||||
*/
|
||||
import { PEOPLE_CHECK_MAX, peopleCheckReplySchema, type PeopleCheckReply, type Profile } from '@crosscode/contracts';
|
||||
import { accounts, accountsLink } from './client';
|
||||
import { handleAccountsCall } from './calls';
|
||||
import { viaAccounts } from './mode';
|
||||
import { recordSignInError } from './status';
|
||||
import { updateLocalCopy } from './signin';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
type Local = { id: string; accountId: string; name: string; email: string; phoneNumber: string | null; newsEmail: boolean; newsWhatsApp: boolean };
|
||||
export type PeopleCheckResult = { checked: number; updated: number; deleted: number; deferred: number; deactivated: number; unknown: number } | { skipped: string };
|
||||
|
||||
/** Asks Accounts about these subs (tests replace it). */
|
||||
export type Ask = (subs: string[]) => Promise<PeopleCheckReply>;
|
||||
|
||||
const defaultAsk: Ask = async (subs) => {
|
||||
const auth = await accounts();
|
||||
const raw = await auth.request({ type: 'people.check', actor: null, subs }, { timeoutMs: 120000 });
|
||||
return peopleCheckReplySchema.parse(raw);
|
||||
};
|
||||
|
||||
/** Whether the local copy already says what the profile says (only what Events keeps). */
|
||||
export function sameAsLocal(u: Local, p: Profile): boolean {
|
||||
return u.name === p.name
|
||||
&& u.email.toLowerCase() === p.email.toLowerCase()
|
||||
&& (u.phoneNumber ?? null) === (p.phone_number ?? null)
|
||||
&& u.newsEmail === p.news_consent.email
|
||||
&& u.newsWhatsApp === p.news_consent.whatsapp;
|
||||
}
|
||||
|
||||
/** More than this share of a page unknown (with at least MIN_FOR_ALARM people) stops the check. */
|
||||
const UNKNOWN_ALARM = 0.5;
|
||||
const MIN_FOR_ALARM = 10;
|
||||
|
||||
export async function runPeopleCheck(opts: { ask?: Ask; pageSize?: number } = {}): Promise<PeopleCheckResult> {
|
||||
if (!(await viaAccounts())) return { skipped: 'This site uses its own sign-in.' };
|
||||
if (!(await accountsLink())) return { skipped: 'Accounts isn\'t linked.' };
|
||||
const ask = opts.ask ?? defaultAsk;
|
||||
const size = Math.min(opts.pageSize ?? PEOPLE_CHECK_MAX, PEOPLE_CHECK_MAX);
|
||||
const out = { checked: 0, updated: 0, deleted: 0, deferred: 0, deactivated: 0, unknown: 0 };
|
||||
let cursor: string | undefined;
|
||||
for (;;) {
|
||||
const page: Local[] = await prisma.user.findMany({
|
||||
where: { accountId: { not: null } },
|
||||
select: { id: true, accountId: true, name: true, email: true, phoneNumber: true, newsEmail: true, newsWhatsApp: true },
|
||||
orderBy: { id: 'asc' },
|
||||
take: size,
|
||||
...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
|
||||
});
|
||||
if (!page.length) break;
|
||||
cursor = page[page.length - 1]!.id;
|
||||
const bySub = new Map(page.map((u) => [u.accountId, u]));
|
||||
let reply: PeopleCheckReply;
|
||||
try {
|
||||
reply = await ask(page.map((u) => u.accountId));
|
||||
} catch (e) {
|
||||
// Accounts before 1.5.0 doesn't know people.check: nothing to do until it's updated.
|
||||
const err = e as { code?: string; message?: string };
|
||||
if (err.code === 'INVALID_REQUEST' && /\btype\b/.test(err.message ?? '')) return { skipped: 'The church\'s Accounts is older than 1.5.0, which this check needs.' };
|
||||
throw e;
|
||||
}
|
||||
const unknown = reply.people.filter((p) => p.status === 'unknown').length;
|
||||
if (page.length >= MIN_FOR_ALARM && unknown / page.length > UNKNOWN_ALARM) {
|
||||
const message = `Accounts doesn't know ${unknown} of ${page.length} people here: is this site linked to the church's own Accounts? Nothing was changed for them.`;
|
||||
await recordSignInError('PEOPLE_UNKNOWN', message);
|
||||
throw new Error(message);
|
||||
}
|
||||
for (const p of reply.people) {
|
||||
const u = bySub.get(p.sub);
|
||||
if (!u) continue; // not one we asked about
|
||||
out.checked++;
|
||||
if (p.status === 'unknown') { out.unknown++; continue; }
|
||||
if (p.status === 'deleted') {
|
||||
const r = await handleAccountsCall({ type: 'user.deleted', sub: p.sub } as never) as { status?: string };
|
||||
if (r.status === 'deferred') out.deferred++; else out.deleted++;
|
||||
continue;
|
||||
}
|
||||
if (p.status === 'deactivated') out.deactivated++;
|
||||
if (p.profile && !sameAsLocal(u, p.profile)) {
|
||||
await updateLocalCopy(u.id, p.profile);
|
||||
out.updated++;
|
||||
}
|
||||
}
|
||||
if (page.length < size) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { siteUrl } from '../feed/context';
|
||||
import { accounts, AccountsUnavailable } from './client';
|
||||
import { viaAccounts } from './mode';
|
||||
import { handleAccountsCall } from './calls';
|
||||
import { clearSignInError, recordSignInError } from './status';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
@@ -144,7 +145,10 @@ async function startSignIn(req: Request, res: Response) {
|
||||
return res.redirect(303, url);
|
||||
} catch (e) {
|
||||
console.warn('[accounts] sign-in could not start:', (e as Error).message);
|
||||
return problem(res, e instanceof AccountsUnavailable ? 'ACCOUNTS_UNAVAILABLE' : 'START_FAILED', returnTo);
|
||||
const failed = e instanceof AccountsUnavailable ? 'ACCOUNTS_UNAVAILABLE' : 'START_FAILED';
|
||||
// 3.5.0: the reason goes to the Hub with the next heartbeat (the page only says "try again").
|
||||
await recordSignInError(failed, (e as Error).message);
|
||||
return problem(res, failed, returnTo);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,7 +162,8 @@ async function callback(req: Request, res: Response) {
|
||||
let auth;
|
||||
try {
|
||||
auth = await accounts();
|
||||
} catch {
|
||||
} catch (e) {
|
||||
await recordSignInError('ACCOUNTS_UNAVAILABLE', (e as Error).message);
|
||||
return problem(res, 'ACCOUNTS_UNAVAILABLE');
|
||||
}
|
||||
let signed;
|
||||
@@ -168,8 +173,10 @@ async function callback(req: Request, res: Response) {
|
||||
} catch (e) {
|
||||
const code = (e as { code?: string }).code;
|
||||
console.warn('[accounts] sign-in could not finish:', (e as Error).message);
|
||||
if (code !== 'NO_PENDING') await recordSignInError('FINISH_FAILED', (e as Error).message);
|
||||
return problem(res, code === 'NO_PENDING' ? 'EXPIRED' : 'FINISH_FAILED');
|
||||
}
|
||||
await clearSignInError();
|
||||
const { claims, returnTo, idToken } = signed;
|
||||
|
||||
const found = await userForClaims(claims);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* How people sign in here, for the Hub (3.5.0, heartbeat `stats.signIn`, contracts 1.13.0): the
|
||||
* mode, the Accounts this site is linked to, and the last sign-in that failed to start or finish.
|
||||
* A site in `accounts` mode without a link can't sign anyone in; the Hub raises an alert for it.
|
||||
*/
|
||||
import { accountsLink } from './client';
|
||||
import { authMode, getSetting, setSetting } from './mode';
|
||||
|
||||
export const LAST_ERROR_KEY = 'accounts_last_signin_error';
|
||||
|
||||
type LastError = { at: string; code: string; message: string };
|
||||
|
||||
/** Keeps the last failure (a code and a sentence; never tokens or cookies). */
|
||||
export async function recordSignInError(code: string, message: string, now = new Date()): Promise<void> {
|
||||
const value: LastError = { at: now.toISOString(), code: code.slice(0, 60), message: message.replace(/\s+/g, ' ').slice(0, 500) };
|
||||
await setSetting(LAST_ERROR_KEY, JSON.stringify(value)).catch(() => {});
|
||||
}
|
||||
|
||||
/** A sign-in that worked clears it. */
|
||||
export async function clearSignInError(): Promise<void> {
|
||||
if (await getSetting(LAST_ERROR_KEY).catch(() => null)) await setSetting(LAST_ERROR_KEY, null).catch(() => {});
|
||||
}
|
||||
|
||||
export async function signInStatus(): Promise<{ mode: 'local' | 'accounts'; accounts: { installId: string; url: string } | null; lastError: LastError | null }> {
|
||||
const [mode, link, raw] = await Promise.all([authMode(), accountsLink(), getSetting(LAST_ERROR_KEY).catch(() => null)]);
|
||||
let lastError: LastError | null = null;
|
||||
try {
|
||||
const parsed = raw ? JSON.parse(raw) : null;
|
||||
if (parsed && typeof parsed.at === 'string' && typeof parsed.code === 'string' && typeof parsed.message === 'string') lastError = parsed;
|
||||
} catch { /* an unreadable value is no error */ }
|
||||
return { mode, accounts: link ? { installId: link.installId, url: link.url } : null, lastError };
|
||||
}
|
||||
@@ -31,4 +31,22 @@ const runJobNow = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { listJobs, runJobNow };
|
||||
// @desc Switch a background job on or off, or change its schedule (3.4.0). Wins over the .env;
|
||||
// null for either goes back to the .env.
|
||||
// @route PUT /api/admin/jobs/:name
|
||||
// @access Private/Admin
|
||||
const updateJob = async (req, res) => {
|
||||
try {
|
||||
const body = req.body || {};
|
||||
const choice = await jobs.setOverride(req.params.name, { enabled: body.enabled, cron: body.cron });
|
||||
logAdminAction({
|
||||
actorId: req.user.id, actorRole: req.user.role, action: 'job_settings_changed',
|
||||
targetType: 'Job', targetId: req.params.name, metadata: { enabled: body.enabled, cron: body.cron }, ip: getClientIp(req),
|
||||
});
|
||||
res.json({ name: req.params.name, override: choice });
|
||||
} catch (error) {
|
||||
res.status(error.statusCode || 500).json({ message: safeErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { listJobs, runJobNow, updateJob };
|
||||
|
||||
@@ -145,10 +145,13 @@ async function stats(now = new Date()) {
|
||||
const live = await liveNow(now).catch(() => undefined);
|
||||
const campusesOn = await campusesEnabled().catch(() => false);
|
||||
const campusCount = campusesOn ? await prisma.campus.count({ where: { archivedAt: null } }) : 0;
|
||||
// 3.5.0: how people sign in (the Hub flags a site in Accounts mode without a link, or failing).
|
||||
const signIn = await require('../accounts/status').signInStatus().catch(() => undefined);
|
||||
return {
|
||||
users,
|
||||
events: { active: activeEvents, upcoming: upcomingEvents, total: totalEvents },
|
||||
...(live ? { live } : {}),
|
||||
...(signIn ? { signIn } : {}),
|
||||
registrations: { last30d: regs30, total: regsTotal },
|
||||
tickets: { last30d: tickets30, total: ticketsTotal },
|
||||
checkIns: { last30d: checkIns30 },
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
@@ -95,6 +98,11 @@ const JOBS = [
|
||||
name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED',
|
||||
run: async () => ({ file: (await require('../utils/backupUtils').runBackup()).filename }),
|
||||
},
|
||||
{
|
||||
// 3.6.0: catch any change from Accounts that never arrived (accounts/peopleCheck.ts).
|
||||
name: 'accounts-people-check', label: 'Accounts: check everyone\'s details here match their church account', cron: '30 4 * * *', env: 'ACCOUNTS_PEOPLE_CHECK_ENABLED',
|
||||
run: () => require('../accounts/peopleCheck').runPeopleCheck(),
|
||||
},
|
||||
{
|
||||
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §5): 14 days after sign-in moved to Accounts, Events' old
|
||||
// passwords and 2FA secrets go; sign-in records (for signing out of Accounts) after 40 days.
|
||||
@@ -117,13 +125,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 +272,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 +348,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 +366,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 +406,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 +429,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 +442,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 +469,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 +486,7 @@ async function jobStatus(prisma) {
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { JOBS, TASKS, TIMEZONE, isEnabled, cronFor, nextRun, isNoop, startJobs, stopJobs, runNow, jobStatus, enqueueTask };
|
||||
module.exports = {
|
||||
JOBS, TASKS, TIMEZONE, isEnabled, envEnabled, cronFor, isCron, nextRun, isNoop, startJobs, stopJobs, runNow, jobStatus, enqueueTask,
|
||||
setOverride, loadOverrides, setOverridesForTest,
|
||||
};
|
||||
|
||||
@@ -100,7 +100,8 @@ v1Route({ method: 'put', path: '/privacy/breaches/:id', tag: 'Privacy', summary:
|
||||
// ─── Admin ───────────────────────────────────────────────────────────────────
|
||||
|
||||
v1Route({ method: 'get', path: '/admin/audit-log', tag: 'Admin', summary: 'The audit log', access: 'admin', query: filters('page', 'limit', 'actorId', 'action', 'role', 'from', 'to', 'search'), documented: { response: D.obj({ rows: z.array(D.auditEntry), total: D.num, page: D.num, limit: D.num }) }, v1: audit.listAuditLog });
|
||||
v1Route({ method: 'get', path: '/admin/jobs', tag: 'Admin', summary: 'Background jobs', access: 'admin', documented: { response: D.obj({ mode: D.str.describe('on, off or timers'), timezone: D.str, jobs: z.array(D.obj({ name: D.str, label: D.str, cron: D.optStr, enabled: D.bool, envFlag: D.optStr, nextRun: D.optDate, recent: z.array(D.anyObj).describe('Recent runs') })) }) }, v1: jobs.listJobs });
|
||||
v1Route({ method: 'get', path: '/admin/jobs', tag: 'Admin', summary: 'Background jobs', access: 'admin', documented: { response: D.obj({ mode: D.str.describe('queue, timers or off'), timezone: D.str, jobsEnabledEnv: D.bool.describe('JOBS_ENABLED in the .env'), jobs: z.array(D.obj({ name: D.str, label: D.str, cron: D.optStr, enabled: D.bool, envFlag: D.optStr, envEnabled: D.bool.describe('What the .env says'), envCron: D.str, defaultCron: D.str, override: D.obj({ enabled: z.boolean().nullable(), cron: D.optStr }).describe('What an admin chose over the .env (null: the .env applies)'), nextRun: D.optDate, recent: z.array(D.anyObj).describe('Recent runs') })) }) }, v1: jobs.listJobs });
|
||||
v1Route({ method: 'put', path: '/admin/jobs/:name', tag: 'Admin', summary: 'Switch a background job on or off, or change its schedule', access: 'admin', params: z.object({ name: z.string().min(1).max(100) }), body: z.object({ enabled: z.boolean().nullable().optional().describe('true or false wins over the .env; null goes back to it'), cron: z.string().max(100).nullable().optional().describe('A cron schedule (five fields) that wins over the .env; null or empty goes back to it') }), documented: { response: D.obj({ name: D.str, override: D.obj({ enabled: z.boolean().nullable(), cron: D.optStr }) }) }, v1: jobs.updateJob });
|
||||
v1Route({ method: 'post', path: '/admin/jobs/:name/run', tag: 'Admin', summary: 'Run a background job now', access: 'admin', params: z.object({ name: z.string().min(1).max(100) }), body: loose, documented: { response: D.obj({ queued: D.bool, id: D.optStr, output: z.unknown().optional().describe('When it ran straight away') }) }, v1: jobs.runJobNow });
|
||||
v1Route({ method: 'get', path: '/admin/impersonation-sessions', tag: 'Admin', summary: 'Times admins viewed the site as someone else', access: 'admin', query: filters('limit'), documented: { response: z.array(D.obj({ id: D.str, reason: D.optStr, startedAt: D.optDate, endedAt: D.optDate, expiresAt: D.optDate, admin: D.obj({ name: D.str, email: D.optStr }).nullish(), target: D.obj({ name: D.str, email: D.optStr }).nullish(), requests: z.array(D.obj({ method: D.str, path: D.str, blocked: D.bool, createdAt: D.date })).describe('What they did (up to 500)') })) }, v1: imp.listSessions });
|
||||
v1Route({ method: 'post', path: '/admin/impersonate/:userId', tag: 'Admin', summary: 'View the site as someone (read-only)', description: 'Answers a token for a read-only session, logged.', access: 'admin', params: z.object({ userId: z.string().min(1).max(64) }), body: loose, documented: { body: D.obj({ reason: D.str.describe('Why — kept in the log') }), response: D.obj({ token: D.str.describe('A read-only sign-in token'), session: D.obj({ id: D.str, expiresAt: D.date, target: D.obj({ id: D.str, name: D.str, email: D.str, role: D.str }) }) }) }, v1: imp.startImpersonation });
|
||||
|
||||
@@ -7,7 +7,9 @@ let mockLink: object | null = null;
|
||||
jest.mock('../src/links/connect', () => ({ connectTo: async (...args: unknown[]) => { mockConnects.push(args); mockLink = { installId: args[0] }; } }));
|
||||
jest.mock('../src/links/store', () => ({ linkedProducts: async () => mockListed }));
|
||||
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => mockLink }));
|
||||
let mockMode = 'local';
|
||||
jest.mock('../src/accounts/mode', () => ({
|
||||
viaAccounts: async () => mockMode === 'accounts',
|
||||
getSetting: async (k: string) => mockSettings.get(k) ?? null,
|
||||
setSetting: async (k: string, v: string | null) => { if (v === null) mockSettings.delete(k); else mockSettings.set(k, v); },
|
||||
}));
|
||||
@@ -21,6 +23,7 @@ beforeEach(() => {
|
||||
mockConnects.length = 0;
|
||||
mockListed = [];
|
||||
mockLink = null;
|
||||
mockMode = 'local';
|
||||
});
|
||||
|
||||
test('connects to the Accounts the Hub lists, as the system, once', async () => {
|
||||
@@ -46,3 +49,13 @@ test('already connected by an admin: just remembers it', async () => {
|
||||
expect(mockConnects).toEqual([]);
|
||||
expect(mockSettings.has(AUTO_KEY)).toBe(true);
|
||||
});
|
||||
|
||||
test('3.5.0: a site in Accounts mode that lost its link (a demo load before 3.5.0) connects again', async () => {
|
||||
mockSettings.set(AUTO_KEY, '2026-11-19T10:00:00.000Z');
|
||||
mockListed = [{ installId: ACCOUNTS, product: 'accounts' }];
|
||||
// On its own sign-in, an earlier Disconnect stays.
|
||||
expect(await connectAccountsIfListed()).toBe('skipped');
|
||||
mockMode = 'accounts';
|
||||
expect(await connectAccountsIfListed()).toBe('connected');
|
||||
expect(mockConnects).toEqual([[ACCOUNTS, { id: null, role: 'system' }, null, expect.any(Date)]]);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// 3.6.0: the nightly people check against Accounts (contracts 1.14.0 people.check).
|
||||
type U = { id: string; accountId: string; name: string; email: string; phoneNumber: string | null; newsEmail: boolean; newsWhatsApp: boolean };
|
||||
let mockUsers: U[] = [];
|
||||
const mockUpdated: string[] = [];
|
||||
const mockCalls: { type: string; sub: string }[] = [];
|
||||
const mockErrors: string[] = [];
|
||||
let mockMode = true;
|
||||
let mockLinked = true;
|
||||
let mockDeferred = new Set<string>();
|
||||
|
||||
jest.mock('../src/config/db', () => ({
|
||||
user: {
|
||||
findMany: async ({ take, cursor }: { take: number; cursor?: { id: string } }) => {
|
||||
const sorted = [...mockUsers].sort((a, b) => a.id.localeCompare(b.id));
|
||||
const start = cursor ? sorted.findIndex((u) => u.id === cursor.id) + 1 : 0;
|
||||
return sorted.slice(start, start + take);
|
||||
},
|
||||
},
|
||||
}));
|
||||
jest.mock('../src/accounts/mode', () => ({ viaAccounts: async () => mockMode }));
|
||||
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => (mockLinked ? { installId: 'acc-1' } : null), accounts: async () => { throw new Error('not in tests'); } }));
|
||||
jest.mock('../src/accounts/signin', () => ({ updateLocalCopy: async (id: string) => { mockUpdated.push(id); } }));
|
||||
jest.mock('../src/accounts/calls', () => ({
|
||||
handleAccountsCall: async (c: { type: string; sub: string }) => { mockCalls.push(c); return { status: mockDeferred.has(c.sub) ? 'deferred' : 'deleted' }; },
|
||||
}));
|
||||
jest.mock('../src/accounts/status', () => ({ recordSignInError: async (_c: string, m: string) => { mockErrors.push(m); } }));
|
||||
|
||||
import type { PeopleCheckReply, Profile } from '@crosscode/contracts';
|
||||
import { runPeopleCheck, sameAsLocal } from '../src/accounts/peopleCheck';
|
||||
|
||||
const sub = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
|
||||
const user = (n: number, over: Partial<U> = {}): U => ({ id: `u${String(n).padStart(3, '0')}`, accountId: sub(n), name: `Person ${n}`, email: `p${n}@hope.test`, phoneNumber: null, newsEmail: false, newsWhatsApp: false, ...over });
|
||||
const profile = (u: U, over: Partial<Profile> = {}): Profile => ({ name: u.name, given_name: null, family_name: null, email: u.email, email_verified: true, phone_number: u.phoneNumber, phone_number_verified: false, news_consent: { email: u.newsEmail, whatsapp: u.newsWhatsApp }, ...over });
|
||||
|
||||
beforeEach(() => {
|
||||
mockUsers = []; mockUpdated.length = 0; mockCalls.length = 0; mockErrors.length = 0;
|
||||
mockMode = true; mockLinked = true; mockDeferred = new Set();
|
||||
});
|
||||
|
||||
test('updates only copies that differ, handles deleted accounts as user.deleted does, counts the rest', async () => {
|
||||
mockUsers = [user(1), user(2), user(3), user(4), user(5)];
|
||||
mockDeferred = new Set([sub(4)]);
|
||||
const ask = async (subs: string[]): Promise<PeopleCheckReply> => ({
|
||||
schema: 'crosscode.identity-request/1',
|
||||
people: subs.map((s) => {
|
||||
const u = mockUsers.find((x) => x.accountId === s)!;
|
||||
if (s === sub(1)) return { sub: s, status: 'active' as const, profile: profile(u) };
|
||||
if (s === sub(2)) return { sub: s, status: 'active' as const, profile: profile(u, { name: 'New Name', news_consent: { email: true, whatsapp: false } }) };
|
||||
if (s === sub(3) || s === sub(4)) return { sub: s, status: 'deleted' as const, profile: null };
|
||||
return { sub: s, status: 'unknown' as const, profile: null };
|
||||
}),
|
||||
});
|
||||
expect(await runPeopleCheck({ ask, pageSize: 2 })).toEqual({ checked: 5, updated: 1, deleted: 1, deferred: 1, deactivated: 0, unknown: 1 });
|
||||
expect(mockUpdated).toEqual(['u002']);
|
||||
expect(mockCalls.map((c) => [c.type, c.sub])).toEqual([['user.deleted', sub(3)], ['user.deleted', sub(4)]]);
|
||||
});
|
||||
|
||||
test('stops, changing nothing, when Accounts knows hardly anyone (linked to the wrong Accounts?)', async () => {
|
||||
mockUsers = Array.from({ length: 12 }, (_, i) => user(i + 1));
|
||||
const ask = async (subs: string[]): Promise<PeopleCheckReply> => ({ schema: 'crosscode.identity-request/1', people: subs.map((s) => ({ sub: s, status: 'unknown' as const, profile: null })) });
|
||||
await expect(runPeopleCheck({ ask })).rejects.toThrow(/doesn't know 12 of 12/);
|
||||
expect(mockCalls).toEqual([]);
|
||||
expect(mockErrors).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('skipped on its own sign-in, or without a link', async () => {
|
||||
mockMode = false;
|
||||
expect(await runPeopleCheck({ ask: async () => { throw new Error('asked'); } })).toEqual({ skipped: expect.any(String) });
|
||||
mockMode = true; mockLinked = false;
|
||||
expect(await runPeopleCheck({ ask: async () => { throw new Error('asked'); } })).toEqual({ skipped: expect.any(String) });
|
||||
});
|
||||
|
||||
test('sameAsLocal ignores email case and what Events doesn\'t keep', () => {
|
||||
const u = user(1, { email: 'Jane@Hope.test' });
|
||||
expect(sameAsLocal(u, profile(u, { email: 'jane@hope.test', email_verified: false, given_name: 'Jane' }))).toBe(true);
|
||||
expect(sameAsLocal(u, profile(u, { phone_number: '+27821234567' }))).toBe(false);
|
||||
});
|
||||
|
||||
test('an Accounts before 1.5.0 (people.check unknown there) skips the check instead of failing every night', async () => {
|
||||
mockUsers = [user(1)];
|
||||
const ask = async () => { throw Object.assign(new Error('Not a crosscode.identity-request/1 request: type Invalid input'), { code: 'INVALID_REQUEST' }); };
|
||||
expect(await runPeopleCheck({ ask })).toEqual({ skipped: expect.stringContaining('1.5.0') });
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
// 3.5.0: how people sign in, for the Hub (heartbeat stats.signIn, contracts 1.13.0).
|
||||
import { hub } from '@crosscode/contracts';
|
||||
|
||||
const mockSettings = new Map<string, string>();
|
||||
let mockMode = 'accounts';
|
||||
let mockLink: object | null = null;
|
||||
|
||||
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => mockLink }));
|
||||
jest.mock('../src/accounts/mode', () => ({
|
||||
authMode: async () => mockMode,
|
||||
getSetting: async (k: string) => mockSettings.get(k) ?? null,
|
||||
setSetting: async (k: string, v: string | null) => { if (v === null) mockSettings.delete(k); else mockSettings.set(k, v); },
|
||||
}));
|
||||
|
||||
import { clearSignInError, recordSignInError, signInStatus } from '../src/accounts/status';
|
||||
|
||||
beforeEach(() => { mockSettings.clear(); mockMode = 'accounts'; mockLink = null; });
|
||||
|
||||
test('Accounts mode without a link, and why the last sign-in failed', async () => {
|
||||
await recordSignInError('ACCOUNTS_UNAVAILABLE', 'Accounts isn\'t connected.\nConnect it under Settings → Linked products.', new Date('2026-11-20T10:00:00.000Z'));
|
||||
const s = await signInStatus();
|
||||
expect(s).toEqual({ mode: 'accounts', accounts: null, lastError: { at: '2026-11-20T10:00:00.000Z', code: 'ACCOUNTS_UNAVAILABLE', message: 'Accounts isn\'t connected. Connect it under Settings → Linked products.' } });
|
||||
// It fits the heartbeat's contract.
|
||||
expect(hub.eventsStatsSchema.shape.signIn.safeParse(s).success).toBe(true);
|
||||
await clearSignInError();
|
||||
expect((await signInStatus()).lastError).toBeNull();
|
||||
});
|
||||
|
||||
test('linked: the Accounts install and its address', async () => {
|
||||
mockLink = { installId: 'acc-1', url: 'https://accounts.hope.test', secret: 'x', updatedAt: new Date() };
|
||||
expect((await signInStatus()).accounts).toEqual({ installId: 'acc-1', url: 'https://accounts.hope.test' });
|
||||
});
|
||||
@@ -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.6.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.6.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev:backend": "cd backend && npm run dev",
|
||||
|
||||
+47
-11
@@ -1,6 +1,6 @@
|
||||
# Handover — Cross Code, all products
|
||||
|
||||
Last updated: 2026-11-19. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
|
||||
Last updated: 2026-11-20. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
|
||||
decisions table near the end). This file says where each phase stands and what comes next.
|
||||
Product-specific notes (where the code lives, known gaps) stay with each product: Cross Events'
|
||||
are in [`apps/events/docs/HANDOVER.md`](../apps/events/docs/HANDOVER.md), and the Hub's are in
|
||||
@@ -33,20 +33,43 @@ every release).
|
||||
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` (+ contracts 1.4.0, Hub 2.2.0) | **Released** 2026-11-18 (`events@2.4.0`, `contracts@1.4.0`, Hub `v2.2.0`, crosscode-site `v1.4.0`; [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md)). **Before any church gets it:** the Events e2e run on Postgres and the VM test (EVENTS-2.4-PLAN §8) |
|
||||
| 3 | Accounts 1.0.0 (+ contracts 1.5.0, agent 1.1.0, Hub 2.3.0) | **Released** 2026-11-18 (`accounts@1.0.0`, `contracts@1.5.0`, `agent@1.1.0`, Hub `v2.3.0`, crosscode-site `v1.5.0`; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)). 37 backend and 8 Playwright tests pass without Postgres. **Before installing it for a church:** the VM test and a run on real Postgres; a Hub release source for `accounts@` tags |
|
||||
| 4 | Cross Events 3.0.0: sign-in through Accounts, users migrated with their password hashes and 2FA | **Released** 2026-11-19 (`events@3.0.0`, `accounts@1.1.0`, `contracts@1.8.0`, Hub `v2.5.0`, crosscode-site `v1.6.0`; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Tested on Postgres 18: both migrations, `test:accounts` on real databases (14/14), the Events e2e suite (111, incl. `sign-in-accounts.spec.ts`). **Not VM tested yet.** Roll out: Hub 2.5.0 deployed first, then per church Accounts 1.1.0 → Events 3.0 → Move (MIGRATING-TO-3.md); crosscode-site 1.6.0 once the first church has moved |
|
||||
| 4+ | Running it: jobs from the dashboard, styled Accounts emails, .env from the Hub, sign-in health, the nightly people check | **Released** 2026-11-20 (see below). Unit, bats and full `npm run check` passing; **not VM tested, not deployed** |
|
||||
| 5–7 | Website 1.0.0 → App 1.0.0 → App 1.x | Not started |
|
||||
|
||||
## Released 2026-11-20
|
||||
|
||||
All tagged and pushed; nothing deployed yet. Details in [CHANGELOG.md](../CHANGELOG.md), the apps' CHANGELOGs
|
||||
and What's New, and [VERSIONS.md](./VERSIONS.md).
|
||||
|
||||
| Release | What |
|
||||
|---------|------|
|
||||
| `events@3.4.0`, `accounts@1.4.0`, `contracts@1.12.0`, `agent@1.3.0`, Hub `v2.8.0` | Background jobs switched on/off and rescheduled from each site's admin (saved in `job_overrides`, wins over the .env, applies at once; Accounts gets an Admin → Background jobs page). Accounts' emails styled as Events' (`src/lib/emails.ts`). The Hub reads and changes an install's .env (`env-read` / `env-set` jobs → `crosscode env`; secrets never leave the server; the file is put back if the site doesn't start; the frontend's file triggers a rebuild) |
|
||||
| `events@3.5.0`, `contracts@1.13.0`, `agent@1.3.1`, Hub `v2.9.0` | **Fix:** "Load demo data" deleted the Accounts link (`set-demo.js` truncated `ProductLink`), so events-demo couldn't sign anyone in (`ACCOUNTS_UNAVAILABLE`). Demo data keeps the link; a site in Accounts mode without a link reconnects at its next heartbeat. Heartbeat `stats.signIn`; Hub alerts: not linked (critical), wrong Accounts, sign-in failing, an Accounts nothing links to. **Agent 1.3.0 reported itself as 1.2.0**: use 1.3.1 |
|
||||
| `events@3.6.0`, `accounts@1.5.0`, `contracts@1.14.0` | The nightly people check (`accounts-people-check`, 04:30): `people.check` 500 subs at a time; fixes out-of-date copies, handles deleted accounts as `user.deleted`, stops (changing nothing) when most people are unknown. Skipped with an Accounts before 1.5.0 |
|
||||
|
||||
**To fix events-demo before it's updated:** its Settings → Linked products → Connect the church's
|
||||
Accounts (or update it to Events 3.5.0+, which reconnects within ~15 minutes).
|
||||
|
||||
## Next up
|
||||
|
||||
1. **Roll out**, in the order in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md) (with the latest patch
|
||||
releases: Hub 2.1.1, agent 1.0.1, Events 2.3.1): Hub 2.1 (make and back up
|
||||
the job-signing key first) → the central server's agent (check `proxy_bind_addr = 127.0.0.1`)
|
||||
→ each church server's agent → **adopt** the demo site, then each church (Link existing → Move
|
||||
onto the monorepo) → a throwaway New install to prove FASTPANEL, DNS and Let's Encrypt.
|
||||
2. **Deploy crosscode-site `v1.3.0`** (secure sign-in in the features and the brochure).
|
||||
3. **Archive `hope-events`** once every install reports 2.2.0 or later (EVENTS-2.2-PLAN §7).
|
||||
4. **Cross Events 2.4.0** (phase 2) is built on branches: run `npm run test:e2e` in `apps/events`
|
||||
(with the e2e Postgres) and the VM test in EVENTS-2.4-PLAN §8, then merge and release in its
|
||||
order (contracts 1.4.0 → Hub 2.2.0, deployed → Events 2.4.0 → crosscode-site 1.4.0).
|
||||
Nothing from phase 1 onwards is rolled out yet (VERSIONS.md, "Deployed / rolled out"), so roll out
|
||||
straight to the latest releases rather than each one in turn.
|
||||
|
||||
1. **VM test the latest releases** before any church gets them (the 2026-11-17 VM test covered
|
||||
Events 2.2 and agent 1.0; Events 2.4+, Accounts and Events 3.x haven't been on it): Events 3.x
|
||||
with Accounts and the move (MIGRATING-TO-3.md), the event feed and Linked products
|
||||
(EVENTS-2.4-PLAN §8), and today's: the Hub's .env panel (read; a backend URL with restart; a
|
||||
frontend value with rebuild; a value that stops the site, so it's put back), the job switches,
|
||||
a demo load (the Accounts link stays) and the people check. Also the Events e2e suite on Postgres.
|
||||
2. **Roll out**, in the order in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md), with the latest releases:
|
||||
**Hub 2.9.0** (make and back up the job-signing key first; 2.4.0 onwards have migrations) → the
|
||||
central server's agent (check `proxy_bind_addr = 127.0.0.1`) → each church server's agent
|
||||
(**1.3.1**, never 1.3.0) → **adopt** the demo site, then each church (Link existing → Move onto the
|
||||
monorepo) → per church **Accounts 1.5.0 before Events 3.6.0**, then the move to Accounts
|
||||
(MIGRATING-TO-3.md) → a throwaway New install to prove FASTPANEL, DNS and Let's Encrypt.
|
||||
3. **Deploy crosscode-site.** `v1.3.0`–`v1.5.0` are tagged but not recorded as deployed;
|
||||
`v1.6.0` (one sign-in through Accounts) once the first church has moved.
|
||||
4. **Archive `hope-events`** once every install reports 2.2.0 or later (EVENTS-2.2-PLAN §7).
|
||||
|
||||
## The VM test (2026-11-17)
|
||||
|
||||
@@ -95,6 +118,19 @@ rollout.
|
||||
- **AI for a church:** set the licence's monthly AI cap above R0 on the Hub; with no cap the
|
||||
buttons don't show (rules in Events' handover, "AI rules"). Churches see tokens; only the Hub
|
||||
shows rand (markup 15% by default).
|
||||
- **The agent's version is in two places:** `apps/agent/package.json` *and* `AGENT_VERSION` in
|
||||
`apps/agent/src/stats.ts` (what it reports to the Hub). Bump both; the agent's test checks they match,
|
||||
so run `npm run check` *after* the bump (1.3.0 shipped reporting 1.2.0).
|
||||
- **Background jobs:** each job's switch and schedule can be set in the site's admin (Events and
|
||||
Accounts, AppSetting `job_overrides`); that wins over the .env flag and `JOB_SCHEDULE_<NAME>`.
|
||||
`JOBS_ENABLED=false` still turns everything off. A new job gets a `label` and, if it may be turned
|
||||
off from the .env, an `env` flag.
|
||||
- **An install's .env from the Hub** (install page → Settings (.env), agent 1.3.0+): plain values
|
||||
only. Names matching `SECRET_ENV_NAME` (contracts) / `SECRET_NAME` (`scripts/lib/envedit.cjs`;
|
||||
keep them in step) and generated values can't be read or changed from the Hub. Changing an
|
||||
address there doesn't change the Hub's domain for the install or FastPanel.
|
||||
- **Demo data keeps the links** to the church's other products (`KEEP_TABLES` in
|
||||
`apps/events/backend/scripts/set-demo.js`). Anything that must survive a demo load goes there.
|
||||
- **Releasing:** branch → merge → tag (`<product>@<version>` here, `v<version>` in events-hub and
|
||||
crosscode-site) → push, with a CHANGELOG entry, and `npm run check` first. Pushes to c-git often
|
||||
fail authentication the first time; retry once. A push can also hang waiting on a login prompt
|
||||
|
||||
+27
-6
@@ -10,13 +10,13 @@ separately below; the two often differ.
|
||||
|
||||
| What | Repo | Latest | Tag | Released |
|
||||
|------|------|--------|-----|----------|
|
||||
| Cross Events | `crosscode-platform` (`apps/events`) | **3.3.0** | `events@3.3.0` | 2026-11-20 |
|
||||
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.3.0** | `accounts@1.3.0` | 2026-11-20 |
|
||||
| Server agent | `crosscode-platform` (`apps/agent`) | **1.2.0** | `agent@1.2.0` | 2026-11-19 |
|
||||
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.11.0** | `contracts@1.11.0` | 2026-11-20 |
|
||||
| Cross Code Hub | `events-hub` | **2.7.1** | `v2.7.1` | 2026-11-19 |
|
||||
| Cross Events | `crosscode-platform` (`apps/events`) | **3.6.0** | `events@3.6.0` | 2026-11-20 |
|
||||
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.6.0** | `accounts@1.6.0` | 2026-11-20 |
|
||||
| Server agent | `crosscode-platform` (`apps/agent`) | **1.3.1** | `agent@1.3.1` | 2026-11-20 |
|
||||
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.14.0** | `contracts@1.14.0` | 2026-11-20 |
|
||||
| Cross Code Hub | `events-hub` | **2.9.0** | `v2.9.0` | 2026-11-20 |
|
||||
| crosscode.co.za | `crosscode-site` | **1.6.0** | `v1.6.0` | 2026-11-19 |
|
||||
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-19 (last change) |
|
||||
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-20 (last change: `crosscode env`) |
|
||||
|
||||
The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main`
|
||||
on each run, so merging to `main` and pushing releases it. Its changes are listed in
|
||||
@@ -37,6 +37,27 @@ need their own tags until something outside this repo depends on them.
|
||||
|
||||
## What each latest release was for
|
||||
|
||||
- **Accounts 1.6.0:** a "New sign-in" email (and WhatsApp) after every sign-in, as Cross Events'
|
||||
own sign-in sends; admins can turn it off. No migration.
|
||||
|
||||
- **Events 3.6.0 + Accounts 1.5.0 + contracts 1.14.0:** a nightly people check (Events asks Accounts
|
||||
about everyone with an account, 500 at a time, `people.check`): out-of-date copies are fixed,
|
||||
deleted accounts handled as `user.deleted`, and it stops if most people are unknown. Update
|
||||
Accounts first (Events skips the check with an older one). No migrations; the Hub is unchanged.
|
||||
|
||||
- **Events 3.5.0 + contracts 1.13.0 + agent 1.3.1 + Hub 2.9.0:** loading demo data no longer deletes
|
||||
the Accounts link (on events-demo nobody could sign in); a site in Accounts mode without a link
|
||||
reconnects at its next heartbeat; the heartbeat says how the site signs in and the last failure,
|
||||
and the Hub alerts when it isn't linked, is linked wrongly or sign-ins fail. **Agent 1.3.0
|
||||
reported itself as 1.2.0**, so the Hub refused its .env jobs: install 1.3.1. No migrations.
|
||||
|
||||
- **Events 3.4.0 + Accounts 1.4.0 + contracts 1.12.0 + agent 1.3.0 + Hub 2.8.0:** background jobs
|
||||
switched on and off (and rescheduled) from each site's admin, over the .env (saved in the
|
||||
database, no migration); Accounts' emails styled as Cross Events'; the Hub shows an install's
|
||||
.env (secrets only as set or not) and changes plain values with a restart or frontend rebuild
|
||||
(`env-read` / `env-set` jobs, `crosscode env`; the file is put back if the site doesn't start).
|
||||
The Hub's .env panel needs agent 1.3.0 on the server. No migrations.
|
||||
|
||||
- **Events 3.3.0 + Accounts 1.3.0 + contracts 1.11.0:** Accounts' pages in Cross Events' layout
|
||||
(sidebar, a page per section), quick links to the church's sites, nightly backups (Admin →
|
||||
Backups; needs `pg_dump` on the server), a fuller built-in privacy notice, a fixed favicon.
|
||||
|
||||
Generated
+7
-6
@@ -46,7 +46,7 @@
|
||||
},
|
||||
"apps/accounts/backend": {
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.3.0",
|
||||
"version": "1.6.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
@@ -54,6 +54,7 @@
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"cron-parser": "^5.10.2",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^5.3.0",
|
||||
"express-rate-limit": "^8.6.2",
|
||||
@@ -82,7 +83,7 @@
|
||||
},
|
||||
"apps/accounts/frontend": {
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.3.0",
|
||||
"version": "1.6.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/ui": "*",
|
||||
@@ -108,7 +109,7 @@
|
||||
},
|
||||
"apps/agent": {
|
||||
"name": "@crosscode/agent",
|
||||
"version": "1.2.0",
|
||||
"version": "1.3.1",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
@@ -127,7 +128,7 @@
|
||||
},
|
||||
"apps/events/backend": {
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.3.0",
|
||||
"version": "3.6.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
@@ -177,7 +178,7 @@
|
||||
},
|
||||
"apps/events/frontend": {
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.3.0",
|
||||
"version": "3.6.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
@@ -21275,7 +21276,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.11.0",
|
||||
"version": "1.14.0",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"zod": "^4.6.7"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.11.0",
|
||||
"version": "1.14.0",
|
||||
"description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads",
|
||||
"license": "UNLICENSED",
|
||||
"type": "commonjs",
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"schema": "crosscode.identity-request/1",
|
||||
"people": [
|
||||
{
|
||||
"sub": "6b2c3d4e-5f6a-4b7c-9d8e-0f1a2b3c4d5e",
|
||||
"status": "active",
|
||||
"profile": {
|
||||
"name": "Thandi Mokoena",
|
||||
"given_name": "Thandi",
|
||||
"family_name": "Mokoena",
|
||||
"email": "thandi@example.com",
|
||||
"email_verified": true,
|
||||
"phone_number": "+27821234567",
|
||||
"phone_number_verified": false,
|
||||
"news_consent": {
|
||||
"email": true,
|
||||
"whatsapp": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"sub": "7c3d4e5f-6a7b-4c8d-8e9f-1a2b3c4d5e6f",
|
||||
"status": "deleted",
|
||||
"profile": null
|
||||
},
|
||||
{
|
||||
"sub": "8d4e5f6a-7b8c-4d9e-9f0a-2b3c4d5e6f7a",
|
||||
"status": "unknown",
|
||||
"profile": null
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"schema": "crosscode.identity-request/1",
|
||||
"actor": null,
|
||||
"requestId": "9e4f5a6b-7c8d-4e9f-8a0b-2c3d4e5f6a7b",
|
||||
"type": "people.check",
|
||||
"subs": [
|
||||
"6b2c3d4e-5f6a-4b7c-9d8e-0f1a2b3c4d5e",
|
||||
"7c3d4e5f-6a7b-4c8d-8e9f-1a2b3c4d5e6f",
|
||||
"8d4e5f6a-7b8c-4d9e-9f0a-2b3c4d5e6f7a"
|
||||
]
|
||||
}
|
||||
@@ -854,6 +854,250 @@
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.agent-job/1"
|
||||
},
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^job_[A-Za-z0-9_-]{8,64}$"
|
||||
},
|
||||
"serverId": {
|
||||
"type": "string",
|
||||
"pattern": "^srv_[A-Za-z0-9_-]{8,64}$"
|
||||
},
|
||||
"config": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"alg": {
|
||||
"type": "string",
|
||||
"const": "x25519-hkdf-sha256-aes-256-gcm"
|
||||
},
|
||||
"epk": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{43}$"
|
||||
},
|
||||
"iv": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{16}$"
|
||||
},
|
||||
"ciphertext": {
|
||||
"type": "string",
|
||||
"maxLength": 200000,
|
||||
"pattern": "^[A-Za-z0-9_-]+$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"alg",
|
||||
"epk",
|
||||
"iv",
|
||||
"ciphertext"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"notBefore": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"expiresAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"signature": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{86}$"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "env-read"
|
||||
},
|
||||
"args": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"church": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9-]{1,30}$"
|
||||
},
|
||||
"product": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"events",
|
||||
"website",
|
||||
"app",
|
||||
"accounts"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"church",
|
||||
"product"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"id",
|
||||
"serverId",
|
||||
"notBefore",
|
||||
"expiresAt",
|
||||
"signature",
|
||||
"type",
|
||||
"args"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.agent-job/1"
|
||||
},
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^job_[A-Za-z0-9_-]{8,64}$"
|
||||
},
|
||||
"serverId": {
|
||||
"type": "string",
|
||||
"pattern": "^srv_[A-Za-z0-9_-]{8,64}$"
|
||||
},
|
||||
"config": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"alg": {
|
||||
"type": "string",
|
||||
"const": "x25519-hkdf-sha256-aes-256-gcm"
|
||||
},
|
||||
"epk": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{43}$"
|
||||
},
|
||||
"iv": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{16}$"
|
||||
},
|
||||
"ciphertext": {
|
||||
"type": "string",
|
||||
"maxLength": 200000,
|
||||
"pattern": "^[A-Za-z0-9_-]+$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"alg",
|
||||
"epk",
|
||||
"iv",
|
||||
"ciphertext"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"notBefore": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"expiresAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"signature": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{86}$"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "env-set"
|
||||
},
|
||||
"args": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"church": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9-]{1,30}$"
|
||||
},
|
||||
"product": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"events",
|
||||
"website",
|
||||
"app",
|
||||
"accounts"
|
||||
]
|
||||
},
|
||||
"file": {
|
||||
"type": "string",
|
||||
"maxLength": 100,
|
||||
"pattern": "^(backend|frontend)\\/\\.env(\\.production)?$"
|
||||
},
|
||||
"set": {
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"type": "string",
|
||||
"maxLength": 100,
|
||||
"pattern": "^[A-Z][A-Z0-9_]*$"
|
||||
},
|
||||
"additionalProperties": {
|
||||
"type": "string",
|
||||
"maxLength": 4000,
|
||||
"pattern": "^[^\\r\\n]*$"
|
||||
}
|
||||
},
|
||||
"unset": {
|
||||
"maxItems": 50,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"maxLength": 100,
|
||||
"pattern": "^[A-Z][A-Z0-9_]*$"
|
||||
}
|
||||
},
|
||||
"restart": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"church",
|
||||
"product",
|
||||
"file",
|
||||
"set",
|
||||
"unset",
|
||||
"restart"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"id",
|
||||
"serverId",
|
||||
"notBefore",
|
||||
"expiresAt",
|
||||
"signature",
|
||||
"type",
|
||||
"args"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
"adopt-undo",
|
||||
"restart",
|
||||
"seed-demo",
|
||||
"env-read",
|
||||
"env-set",
|
||||
"export",
|
||||
"uninstall",
|
||||
"purge",
|
||||
|
||||
@@ -324,6 +324,77 @@
|
||||
"eventsNow",
|
||||
"checkInsLastHour"
|
||||
]
|
||||
},
|
||||
"signIn": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"local",
|
||||
"accounts"
|
||||
]
|
||||
},
|
||||
"accounts": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"installId": {
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
"url": {
|
||||
"type": "string",
|
||||
"maxLength": 500
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"installId",
|
||||
"url"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"lastError": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"code": {
|
||||
"type": "string",
|
||||
"maxLength": 60
|
||||
},
|
||||
"message": {
|
||||
"type": "string",
|
||||
"maxLength": 500
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"at",
|
||||
"code",
|
||||
"message"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"mode",
|
||||
"accounts",
|
||||
"lastError"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -856,6 +856,53 @@
|
||||
"subs"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.identity-request/1"
|
||||
},
|
||||
"requestId": {
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
|
||||
},
|
||||
"actor": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "people.check"
|
||||
},
|
||||
"subs": {
|
||||
"minItems": 1,
|
||||
"maxItems": 500,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"requestId",
|
||||
"actor",
|
||||
"type",
|
||||
"subs"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/people-check-reply.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.identity-request/1"
|
||||
},
|
||||
"people": {
|
||||
"maxItems": 500,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"sub": {
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"active",
|
||||
"deactivated",
|
||||
"deleted",
|
||||
"unknown"
|
||||
]
|
||||
},
|
||||
"profile": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"given_name": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"family_name": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"email": {
|
||||
"type": "string",
|
||||
"maxLength": 254,
|
||||
"format": "email",
|
||||
"pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"
|
||||
},
|
||||
"email_verified": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"phone_number": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^\\+[1-9]\\d{6,14}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"phone_number_verified": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"news_consent": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email",
|
||||
"whatsapp"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"given_name",
|
||||
"family_name",
|
||||
"email",
|
||||
"email_verified",
|
||||
"phone_number",
|
||||
"phone_number_verified",
|
||||
"news_consent"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"sub",
|
||||
"status",
|
||||
"profile"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"people"
|
||||
]
|
||||
}
|
||||
@@ -67,6 +67,7 @@ function contracts(c) {
|
||||
"messaging-status-reply": c.messagingStatusReplySchema,
|
||||
"messaging-test-reply": c.messagingTestReplySchema,
|
||||
"people-remove-demo-reply": c.peopleRemoveDemoReplySchema,
|
||||
"people-check-reply": c.peopleCheckReplySchema,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -62,6 +62,25 @@ export type DemoProfile = z.infer<typeof demoProfileSchema>;
|
||||
/** The first agent that runs `seed-demo` jobs (an older one refuses the unknown type). */
|
||||
export const SEED_DEMO_MIN_AGENT = "1.2.0";
|
||||
|
||||
/** The first agent that runs `env-read` and `env-set` jobs (an older one refuses the unknown types). */
|
||||
export const ENV_JOBS_MIN_AGENT = "1.3.0";
|
||||
|
||||
/** A .env variable's name. */
|
||||
export const envNameSchema = z.string().max(100).regex(/^[A-Z][A-Z0-9_]*$/, "Expected an env variable name (A-Z, 0-9, _)");
|
||||
|
||||
/** A product's .env file, relative to `apps/<product>`: `backend/.env`, `frontend/.env.production`. */
|
||||
export const envFileSchema = z.string().max(100).regex(/^(backend|frontend)\/\.env(\.production)?$/, "Expected backend/.env or frontend/.env.production");
|
||||
|
||||
/**
|
||||
* Names whose values are secrets: never shown on the Hub (only whether they're set) and never
|
||||
* changed from it. Keep in step with SECRET_NAME in scripts/lib/envedit.cjs.
|
||||
*/
|
||||
export const SECRET_ENV_NAME = /(SECRET|PASS|TOKEN|PRIVATE|CREDENTIAL|_KEY$|_DSN$|DATABASE_URL|ADMIN_URL)/;
|
||||
export const isSecretEnvName = (name: string): boolean => SECRET_ENV_NAME.test(name);
|
||||
|
||||
/** At most this many changes in one `env-set` job. */
|
||||
export const ENV_SET_MAX = 50;
|
||||
|
||||
/** Each job type and the arguments it takes. Unknown keys are refused, not stripped. */
|
||||
export const jobArgsSchemas = {
|
||||
/** `crosscode install <church> --products … --frp --json` */
|
||||
@@ -95,6 +114,35 @@ export const jobArgsSchemas = {
|
||||
* marked as demo sites. `adminEmail`: the account kept (default: the release's own choice).
|
||||
*/
|
||||
"seed-demo": z.strictObject({ church: shortNameSchema, profile: demoProfileSchema, adminEmail: z.email().max(254).optional() }),
|
||||
/**
|
||||
* `crosscode env <church> <product> --json`: the product's .env values, secrets hidden (only
|
||||
* whether they're set). The report's `result` is an {@link envReadResultSchema}.
|
||||
*/
|
||||
"env-read": z.strictObject({ church: shortNameSchema, product: productSchema }),
|
||||
/**
|
||||
* `crosscode env <church> <product> --file <file> --set NAME=value … --unset NAME … [--restart]
|
||||
* --json`: changes values in one .env file (a copy is kept first), rebuilds the frontend when its
|
||||
* file changed (Next.js builds the values in), then reloads; on a failure the file is put back.
|
||||
* Never secrets, never what the server generates (DATABASE_URL, JWT_SECRET …): the script
|
||||
* refuses those too.
|
||||
*/
|
||||
"env-set": z.strictObject({
|
||||
church: shortNameSchema,
|
||||
product: productSchema,
|
||||
file: envFileSchema,
|
||||
set: z.record(envNameSchema, z.string().max(4000).regex(/^[^\r\n]*$/, "Values can't contain newlines")),
|
||||
unset: z.array(envNameSchema).max(ENV_SET_MAX),
|
||||
restart: z.boolean(),
|
||||
}).check((ctx) => {
|
||||
const a = ctx.value;
|
||||
const names = [...Object.keys(a.set), ...a.unset];
|
||||
const issue = (message: string) => ctx.issues.push({ code: "custom", message, input: a });
|
||||
if (names.length === 0) issue("Nothing to change");
|
||||
if (names.length > ENV_SET_MAX) issue(`At most ${ENV_SET_MAX} changes at a time`);
|
||||
const secret = names.find(isSecretEnvName);
|
||||
if (secret) issue(`${secret} is a secret: it can't be changed from the Hub`);
|
||||
if (a.unset.some((n) => Object.prototype.hasOwnProperty.call(a.set, n))) issue("A name can't be both set and removed");
|
||||
}),
|
||||
/** `crosscode export <church> --out <zip> --json`; the agent encrypts the ZIP and uploads it under `exportId`. */
|
||||
export: z.strictObject({ church: shortNameSchema, exportId: z.string().regex(/^exp_[A-Za-z0-9_-]{8,64}$/) }),
|
||||
/** `crosscode uninstall <church> --json` */
|
||||
@@ -119,7 +167,7 @@ export const CENTRAL_JOB_TYPES: readonly JobType[] = ["check-ports", "status", "
|
||||
|
||||
/** Time limits per job type, in minutes (§3). A job past it is stopped and reported as failed. */
|
||||
export const JOB_TIME_LIMIT_MINUTES: Record<JobType, number> = {
|
||||
install: 30, "add-product": 30, deploy: 20, adopt: 30, "adopt-undo": 15, restart: 5, "seed-demo": 15, export: 20,
|
||||
install: 30, "add-product": 30, deploy: 20, adopt: 30, "adopt-undo": 15, restart: 5, "seed-demo": 15, "env-read": 2, "env-set": 20, export: 20,
|
||||
uninstall: 20, purge: 10, "update-agent": 15, "check-ports": 2, status: 3,
|
||||
};
|
||||
|
||||
@@ -164,7 +212,7 @@ function jobOf<T extends JobType>(type: T) {
|
||||
|
||||
export const agentJobSchema = z.discriminatedUnion("type", [
|
||||
jobOf("install"), jobOf("add-product"), jobOf("deploy"), jobOf("adopt"), jobOf("adopt-undo"), jobOf("restart"), jobOf("seed-demo"),
|
||||
jobOf("export"), jobOf("uninstall"), jobOf("purge"), jobOf("update-agent"), jobOf("check-ports"), jobOf("status"),
|
||||
jobOf("env-read"), jobOf("env-set"), jobOf("export"), jobOf("uninstall"), jobOf("purge"), jobOf("update-agent"), jobOf("check-ports"), jobOf("status"),
|
||||
]);
|
||||
export type AgentJob = z.infer<typeof agentJobSchema>;
|
||||
export type UnsignedAgentJob = Omit<AgentJob, "signature">;
|
||||
@@ -321,6 +369,32 @@ export const envTemplateSchema = z.object({
|
||||
});
|
||||
export type EnvTemplate = z.infer<typeof envTemplateSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Reading an install's .env (the env-read job, contracts 1.12.0)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** One variable in an `env-read` result. `value` is null for a secret (`set` says whether it has one). */
|
||||
export const envReadVariableSchema = z.object({
|
||||
name: envNameSchema,
|
||||
value: z.string().max(4000).nullable(),
|
||||
secret: z.boolean(),
|
||||
set: z.boolean(),
|
||||
/** From the release's env template (null when the template doesn't list it). */
|
||||
layer: envLayerSchema.nullable(),
|
||||
description: z.string().max(400).nullable(),
|
||||
/** Whether the Hub may change it: not secret, not generated on the server. */
|
||||
editable: z.boolean(),
|
||||
});
|
||||
export type EnvReadVariable = z.infer<typeof envReadVariableSchema>;
|
||||
|
||||
/** The `result` of an `env-read` report: each of the product's .env files, variables in file order. */
|
||||
export const envReadResultSchema = z.object({
|
||||
product: productSchema,
|
||||
files: z.array(z.object({ file: envFileSchema, exists: z.boolean(), variables: z.array(envReadVariableSchema).max(300) })).max(10),
|
||||
readAt: dateTimeSchema,
|
||||
});
|
||||
export type EnvReadResult = z.infer<typeof envReadResultSchema>;
|
||||
|
||||
/** The variables a layer must provide for a template, that it doesn't (the Hub's check before a job). */
|
||||
export function missingRequired(template: EnvTemplate, layer: "server" | "defaults", values: Record<string, string | undefined>): string[] {
|
||||
const missing: string[] = [];
|
||||
|
||||
@@ -196,6 +196,18 @@ export const eventsStatsSchema = z.object({
|
||||
* 30 minutes), and tickets checked in during the last hour. Optional: older installs don't send it.
|
||||
*/
|
||||
live: z.object({ eventsNow: count, checkInsLastHour: count }).optional(),
|
||||
/**
|
||||
* 1.13.0: how people sign in, so the Hub can flag a site that can't. `mode`: Cross Events' own
|
||||
* sign-in or the church's Accounts; `accounts`: the Accounts install it's linked to (null: not
|
||||
* linked, which with mode `accounts` means nobody can sign in); `lastError`: the last time
|
||||
* starting or finishing a sign-in failed (cleared by the next one that works). Optional: older
|
||||
* installs don't send it.
|
||||
*/
|
||||
signIn: z.object({
|
||||
mode: z.enum(["local", "accounts"]),
|
||||
accounts: z.object({ installId: z.string().max(100), url: z.string().max(500) }).nullable(),
|
||||
lastError: z.object({ at: dateTimeSchema, code: z.string().max(60), message: z.string().max(500) }).nullable(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
/** Church Website. `storage` is what the extra-storage add-on is billed on (ROADMAP-v3 §10). */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { dateTimeSchema, emailSchema, idSchema, phoneSchema } from "./common";
|
||||
import { twoFactorMethodSchema } from "./identity";
|
||||
import { profileSchema, twoFactorMethodSchema } from "./identity";
|
||||
import { schemaName } from "./schema-name";
|
||||
|
||||
/**
|
||||
@@ -171,6 +171,33 @@ export const peopleRemoveDemoSchema = base.extend({
|
||||
subs: z.array(idSchema).max(REMOVE_DEMO_MAX),
|
||||
});
|
||||
|
||||
/** Subs per `people.check`. */
|
||||
export const PEOPLE_CHECK_MAX = 500;
|
||||
|
||||
/**
|
||||
* 1.14.0: the product's regular check that its copies of people are current (Cross Events does it
|
||||
* nightly), in case a `user.updated` or `user.deleted` never arrived. Accounts answers for each sub
|
||||
* with the current profile, or says the account was deleted, or that it doesn't know the person
|
||||
* through this product (`unknown`; never a reason to delete anything).
|
||||
*/
|
||||
export const peopleCheckSchema = base.extend({
|
||||
type: z.literal("people.check"),
|
||||
subs: z.array(idSchema).min(1).max(PEOPLE_CHECK_MAX),
|
||||
});
|
||||
|
||||
export const PEOPLE_CHECK_STATUSES = ["active", "deactivated", "deleted", "unknown"] as const;
|
||||
|
||||
export const peopleCheckReplySchema = z.object({
|
||||
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
|
||||
people: z.array(z.object({
|
||||
sub: idSchema,
|
||||
status: z.enum(PEOPLE_CHECK_STATUSES),
|
||||
/** The profile as `user.updated` sends it; null for `deleted` and `unknown`. */
|
||||
profile: profileSchema.nullable(),
|
||||
})).max(PEOPLE_CHECK_MAX),
|
||||
});
|
||||
export type PeopleCheckReply = z.infer<typeof peopleCheckReplySchema>;
|
||||
|
||||
// ─── messaging.* (contracts 1.9.0) ───────────────────────────────────────────
|
||||
|
||||
/** SMTP settings as Cross Events and Accounts both keep them (`smtp_*`). `pass` sealed; null: keep the saved one. */
|
||||
@@ -216,7 +243,7 @@ export const churchBrandingSchema = base.extend({ type: z.literal("church.brandi
|
||||
export const identityRequestSchema = z.discriminatedUnion("type", [
|
||||
importBeginSchema, importBatchSchema, importFinishSchema, importAbortSchema,
|
||||
peopleEnsureSchema, peopleUpdateSchema, peopleResetTwoFactorSchema, peopleUnlockSchema, peopleSetActiveSchema, peopleNewsOffSchema,
|
||||
peopleRemoveDemoSchema, messagingStatusSchema, messagingTestSchema, messagingSetSchema, churchBrandingSchema,
|
||||
peopleRemoveDemoSchema, peopleCheckSchema, messagingStatusSchema, messagingTestSchema, messagingSetSchema, churchBrandingSchema,
|
||||
]);
|
||||
export type IdentityRequest = z.infer<typeof identityRequestSchema>;
|
||||
export type IdentityRequestType = IdentityRequest["type"];
|
||||
|
||||
@@ -167,6 +167,47 @@ describe("seed-demo jobs", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("env-read and env-set jobs (1.12.0)", () => {
|
||||
const set = (a: Record<string, unknown>) => agent.jobArgsSchemas["env-set"].safeParse({ church: "hope", product: "events", file: "backend/.env", set: {}, unset: [], restart: true, ...a });
|
||||
it("read one product", () => {
|
||||
expect(agent.jobArgsSchemas["env-read"].safeParse({ church: "hope", product: "accounts" }).success).toBe(true);
|
||||
expect(agent.jobArgsSchemas["env-read"].safeParse({ church: "hope", product: "nope" }).success).toBe(false);
|
||||
expect(agent.JOB_TYPES).toEqual(expect.arrayContaining(["env-read", "env-set"]));
|
||||
expect(agent.CENTRAL_JOB_TYPES).not.toContain("env-set");
|
||||
});
|
||||
it("set plain values in a product's .env file", () => {
|
||||
expect(set({ set: { FRONTEND_URL: "https://events.hope.test" } }).success).toBe(true);
|
||||
expect(set({ file: "frontend/.env.production", set: { NEXT_PUBLIC_API_URL: "https://events.hope.test" }, unset: ["OLD_THING"] }).success).toBe(true);
|
||||
});
|
||||
it("refuse secrets, nothing to do, newlines, other files and bad names", () => {
|
||||
expect(set({}).success).toBe(false);
|
||||
for (const name of ["JWT_SECRET", "DATABASE_URL", "SMTP_PASS", "HUB_LICENCE_KEY", "SENTRY_DSN", "DB_ADMIN_URL"]) {
|
||||
expect(set({ set: { [name]: "x" } }).success).toBe(false);
|
||||
expect(set({ unset: [name] }).success).toBe(false);
|
||||
}
|
||||
expect(set({ set: { A_URL: "x\nEVIL=1" } }).success).toBe(false);
|
||||
expect(set({ file: "../.env", set: { A: "1" } }).success).toBe(false);
|
||||
expect(set({ set: { "lower": "1" } }).success).toBe(false);
|
||||
expect(set({ set: { A: "1" }, unset: ["A"] }).success).toBe(false);
|
||||
expect(set({ set: { A: "1" }, extra: true }).success).toBe(false);
|
||||
});
|
||||
it("tell secrets by name", () => {
|
||||
expect(agent.isSecretEnvName("ACCOUNTS_SECRET")).toBe(true);
|
||||
expect(agent.isSecretEnvName("FRONTEND_URL")).toBe(false);
|
||||
expect(agent.isSecretEnvName("JOBS_ENABLED")).toBe(false);
|
||||
});
|
||||
it("read results", () => {
|
||||
const ok = agent.envReadResultSchema.safeParse({
|
||||
product: "events", readAt: "2026-11-20T10:00:00.000Z",
|
||||
files: [{ file: "backend/.env", exists: true, variables: [
|
||||
{ name: "FRONTEND_URL", value: "https://events.hope.test", secret: false, set: true, layer: "install", description: null, editable: true },
|
||||
{ name: "JWT_SECRET", value: null, secret: true, set: true, layer: "generated", description: "never change it", editable: false },
|
||||
] }],
|
||||
});
|
||||
expect(ok.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("env templates", () => {
|
||||
it("lists the required server and defaults values that are missing", () => {
|
||||
const template = agent.envTemplateSchema.parse({
|
||||
|
||||
@@ -50,6 +50,8 @@ const SAMPLE_SCHEMA: Record<string, string> = {
|
||||
"messaging-test-reply.json": "messaging-test-reply",
|
||||
"people-remove-demo.json": "identity-request",
|
||||
"people-remove-demo-reply.json": "people-remove-demo-reply",
|
||||
"people-check.json": "identity-request",
|
||||
"people-check-reply.json": "people-check-reply",
|
||||
};
|
||||
|
||||
describe("JSON Schema (schemas/)", () => {
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
importBatchReplySchema,
|
||||
peopleEnsureReplySchema,
|
||||
messagingTestReplySchema,
|
||||
peopleRemoveDemoReplySchema,
|
||||
peopleRemoveDemoReplySchema, peopleCheckReplySchema,
|
||||
userDeletedReplySchema,
|
||||
userExportReplySchema,
|
||||
} from "../src";
|
||||
@@ -59,6 +59,8 @@ const SCHEMAS: Record<string, z.ZodType> = {
|
||||
"messaging-test-reply.json": messagingTestReplySchema,
|
||||
"people-remove-demo.json": identityRequestSchema,
|
||||
"people-remove-demo-reply.json": peopleRemoveDemoReplySchema,
|
||||
"people-check.json": identityRequestSchema,
|
||||
"people-check-reply.json": peopleCheckReplySchema,
|
||||
};
|
||||
|
||||
describe("samples", () => {
|
||||
|
||||
+3
-1
@@ -97,6 +97,7 @@ crosscode: Cross Code installs on this server ($(git -C "${CROSSCODE_FROM:-.}" r
|
||||
crosscode adopt <church> --undo go back to the old folder (within 14 days)
|
||||
crosscode restart <church> [events] reload the PM2 processes
|
||||
crosscode demo <church> --profile <profile> replace Events' data with a demo set
|
||||
crosscode env <church> <product> [--set NAME=value] show or change a product's .env values
|
||||
crosscode export <church> --out <file.zip> the church's data and uploads
|
||||
crosscode uninstall <church> --confirm <church> remove it (a final backup is kept 30 days)
|
||||
crosscode purge <church> --confirm <church> delete what uninstall kept
|
||||
@@ -114,6 +115,7 @@ case "$command" in
|
||||
adopt) cmd_adopt "$@" ;;
|
||||
restart) cmd_restart "$@" ;;
|
||||
demo) cmd_demo "$@" ;;
|
||||
env) cmd_env "$@" ;;
|
||||
export) cmd_export "$@" ;;
|
||||
uninstall) cmd_uninstall "$@" ;;
|
||||
purge) cmd_purge "$@" ;;
|
||||
@@ -125,7 +127,7 @@ case "$command" in
|
||||
install) install_usage ;;
|
||||
add) add_usage ;;
|
||||
adopt) adopt_usage ;;
|
||||
restart|demo|export|uninstall|purge) manage_usage ;;
|
||||
restart|demo|env|export|uninstall|purge) manage_usage ;;
|
||||
*) usage ;;
|
||||
esac ;;
|
||||
*) usage; die "Unknown command \"$command\"." ;;
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env node
|
||||
// Reads and changes a product's .env files for `crosscode env` (the Hub's env-read and env-set
|
||||
// jobs, contracts 1.12.0).
|
||||
//
|
||||
// node envedit.cjs read --template <file> --dir <product dir> --product <product>
|
||||
// prints a crosscode env-read result (JSON) on stdout. Secrets are never printed: only
|
||||
// whether they're set.
|
||||
// node envedit.cjs set --template <file> --dir <product dir> --file <backend/.env>
|
||||
// [--set NAME=value …] [--unset NAME …] --backup <file>
|
||||
// changes the file in place (owner and mode kept), after copying it to --backup. Refuses
|
||||
// secrets and the values the server generates (exit 3), and values the app can't start with
|
||||
// (exit 4). Prints the names it changed, never values.
|
||||
// node envedit.cjs restore --file <file> --backup <file>
|
||||
// puts the copy back.
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { checkValue, keysIn, line } = require('./envtpl.cjs');
|
||||
|
||||
// Keep in step with SECRET_ENV_NAME in packages/contracts/src/agent.ts.
|
||||
const SECRET_NAME = /(SECRET|PASS|TOKEN|PRIVATE|CREDENTIAL|_KEY$|_DSN$|DATABASE_URL|ADMIN_URL)/;
|
||||
const NAME = /^[A-Z][A-Z0-9_]*$/;
|
||||
const FILE = /^(backend|frontend)\/\.env(\.production)?$/;
|
||||
|
||||
function parseArgs(argv) {
|
||||
const out = { command: argv[0], set: {}, unset: [] };
|
||||
for (let i = 1; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
const next = () => {
|
||||
if (i + 1 >= argv.length) throw new Error(`${a} needs a value`);
|
||||
return argv[++i];
|
||||
};
|
||||
if (a === '--template') out.template = next();
|
||||
else if (a === '--dir') out.dir = next();
|
||||
else if (a === '--product') out.product = next();
|
||||
else if (a === '--file') out.file = next();
|
||||
else if (a === '--backup') out.backup = next();
|
||||
else if (a === '--set') {
|
||||
const v = next();
|
||||
const eq = v.indexOf('=');
|
||||
if (eq < 1) throw new Error(`--set ${v.split('=')[0]}: expected NAME=value`);
|
||||
out.set[v.slice(0, eq)] = v.slice(eq + 1);
|
||||
} else if (a === '--unset') out.unset.push(next());
|
||||
else throw new Error(`Unknown option ${a}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The template's variables by name (layer, description), and its file names. */
|
||||
function templateInfo(file) {
|
||||
if (!file || !fs.existsSync(file)) return { vars: new Map(), files: ['backend/.env', 'frontend/.env.production'] };
|
||||
const t = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
const vars = new Map();
|
||||
for (const list of Object.values(t.files || {})) for (const v of list) vars.set(v.name, v);
|
||||
return { vars, files: Object.keys(t.files || {}) };
|
||||
}
|
||||
|
||||
/** A .env file's variables in order: [{ name, value }] (the last one wins, as dotenv). */
|
||||
function parse(text) {
|
||||
const order = [];
|
||||
const values = new Map();
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s?(.*)$/.exec(raw);
|
||||
if (!m) continue;
|
||||
let v = m[2].replace(/\s+$/, '');
|
||||
const dq = /^"(.*)"$/.exec(v);
|
||||
const sq = /^'(.*)'$/.exec(v);
|
||||
if (dq) v = dq[1].replace(/\\"/g, '"').replace(/\\\\/g, '\\');
|
||||
else if (sq) v = sq[1];
|
||||
else v = v.replace(/\s+#.*$/, '');
|
||||
if (!values.has(m[1])) order.push(m[1]);
|
||||
values.set(m[1], v);
|
||||
}
|
||||
return order.map(name => ({ name, value: values.get(name) }));
|
||||
}
|
||||
|
||||
const isSecret = (name, tv) => SECRET_NAME.test(name) || tv?.layer === 'generated' && name !== 'NODE_ENV';
|
||||
const editable = (name, tv) => !SECRET_NAME.test(name) && tv?.layer !== 'generated';
|
||||
|
||||
function read(opts) {
|
||||
const { vars, files } = templateInfo(opts.template);
|
||||
const out = [];
|
||||
for (const rel of files.filter(f => FILE.test(f))) {
|
||||
const file = path.join(opts.dir, rel);
|
||||
const exists = fs.existsSync(file);
|
||||
const found = exists ? parse(fs.readFileSync(file, 'utf8')) : [];
|
||||
const variables = found.map(({ name, value }) => {
|
||||
const tv = vars.get(name);
|
||||
const secret = isSecret(name, tv);
|
||||
return {
|
||||
name, value: secret ? null : value.slice(0, 4000), secret, set: value !== '',
|
||||
layer: tv?.layer ?? null, description: tv?.description?.slice(0, 400) ?? null, editable: editable(name, tv),
|
||||
};
|
||||
});
|
||||
// What the template has that the file doesn't (so the Hub can offer to add it).
|
||||
for (const [name, tv] of vars) {
|
||||
if (found.some(f => f.name === name) || !(templateFileOf(opts.template, name) === rel)) continue;
|
||||
variables.push({ name, value: null, secret: isSecret(name, tv), set: false, layer: tv.layer, description: tv.description?.slice(0, 400) ?? null, editable: editable(name, tv) });
|
||||
}
|
||||
out.push({ file: rel, exists, variables: variables.slice(0, 300) });
|
||||
}
|
||||
return { product: opts.product, files: out, readAt: new Date().toISOString() };
|
||||
}
|
||||
|
||||
function templateFileOf(template, name) {
|
||||
if (!template || !fs.existsSync(template)) return null;
|
||||
const t = JSON.parse(fs.readFileSync(template, 'utf8'));
|
||||
for (const [rel, list] of Object.entries(t.files || {})) if (list.some(v => v.name === name)) return rel;
|
||||
return null;
|
||||
}
|
||||
|
||||
class Refused extends Error {
|
||||
constructor(message, code) { super(message); this.code = code; }
|
||||
}
|
||||
|
||||
/** The new file text: changed lines replaced where they are, new ones appended, removed ones dropped. */
|
||||
function edit(text, set, unset, stamp) {
|
||||
const done = new Set();
|
||||
const lines = text.split(/\r?\n/);
|
||||
if (lines.length && lines[lines.length - 1] === '') lines.pop();
|
||||
const out = [];
|
||||
for (const raw of lines) {
|
||||
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(raw);
|
||||
if (m && unset.includes(m[1])) continue;
|
||||
if (m && Object.prototype.hasOwnProperty.call(set, m[1])) {
|
||||
if (done.has(m[1])) continue; // a duplicate: one line is enough
|
||||
out.push(line(m[1], set[m[1]]));
|
||||
done.add(m[1]);
|
||||
continue;
|
||||
}
|
||||
out.push(raw);
|
||||
}
|
||||
const added = Object.keys(set).filter(n => !done.has(n));
|
||||
if (added.length) out.push('', `# Added from the Hub ${stamp}`, ...added.map(n => line(n, set[n])));
|
||||
return `${out.join('\n')}\n`;
|
||||
}
|
||||
|
||||
function set(opts) {
|
||||
if (!FILE.test(opts.file || '')) throw new Refused(`--file: expected backend/.env or frontend/.env.production`, 2);
|
||||
const { vars } = templateInfo(opts.template);
|
||||
const names = [...Object.keys(opts.set), ...opts.unset];
|
||||
if (!names.length) throw new Refused('Nothing to change.', 2);
|
||||
for (const n of names) {
|
||||
if (!NAME.test(n)) throw new Refused(`${n} isn't an env variable name.`, 2);
|
||||
if (!editable(n, vars.get(n))) throw new Refused(`${n} ${SECRET_NAME.test(n) ? 'is a secret' : 'is made by the server'}: it can't be changed from the Hub.`, 3);
|
||||
}
|
||||
const problems = Object.entries(opts.set).map(([n, v]) => {
|
||||
if (/[\r\n]/.test(v)) return `${n}: values can't contain newlines`;
|
||||
return checkValue(n, v);
|
||||
}).filter(Boolean);
|
||||
if (problems.length) throw new Refused(problems.join('; '), 4);
|
||||
|
||||
const file = path.join(opts.dir, opts.file);
|
||||
if (!fs.existsSync(file)) throw new Refused(`${opts.file} doesn't exist.`, 2);
|
||||
const before = fs.readFileSync(file, 'utf8');
|
||||
const st = fs.statSync(file);
|
||||
if (opts.backup) fs.copyFileSync(file, opts.backup);
|
||||
const text = edit(before, opts.set, opts.unset, new Date().toISOString().slice(0, 10));
|
||||
const tmp = `${file}.crosscode-${process.pid}`;
|
||||
fs.writeFileSync(tmp, text, { mode: 0o600 });
|
||||
try { fs.chownSync(tmp, st.uid, st.gid); } catch { /* not root: same owner anyway */ }
|
||||
fs.chmodSync(tmp, st.mode & 0o777);
|
||||
fs.renameSync(tmp, file);
|
||||
const had = keysIn(before);
|
||||
return {
|
||||
changed: Object.keys(opts.set).filter(n => had.has(n)),
|
||||
added: Object.keys(opts.set).filter(n => !had.has(n)),
|
||||
removed: opts.unset.filter(n => had.has(n)),
|
||||
};
|
||||
}
|
||||
|
||||
function restore(opts) {
|
||||
if (!opts.file || !opts.backup || !fs.existsSync(opts.backup)) throw new Refused('restore needs --file and an existing --backup', 2);
|
||||
const st = fs.statSync(opts.file);
|
||||
fs.copyFileSync(opts.backup, opts.file);
|
||||
try { fs.chownSync(opts.file, st.uid, st.gid); } catch { /* not root */ }
|
||||
fs.chmodSync(opts.file, st.mode & 0o777);
|
||||
}
|
||||
|
||||
function main() {
|
||||
let opts;
|
||||
try {
|
||||
opts = parseArgs(process.argv.slice(2));
|
||||
if (opts.command === 'read') {
|
||||
if (!opts.dir || !opts.product) throw new Refused('read needs --dir and --product', 2);
|
||||
process.stdout.write(`${JSON.stringify(read(opts))}\n`);
|
||||
} else if (opts.command === 'set') {
|
||||
if (!opts.dir) throw new Refused('set needs --dir', 2);
|
||||
const r = set(opts);
|
||||
process.stdout.write(`${JSON.stringify(r)}\n`);
|
||||
} else if (opts.command === 'restore') {
|
||||
restore(opts);
|
||||
} else throw new Refused('Expected read, set or restore', 2);
|
||||
} catch (e) {
|
||||
console.error(`envedit: ${e.message}`);
|
||||
process.exit(e instanceof Refused ? e.code : 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) main();
|
||||
|
||||
module.exports = { parse, read, set, edit, restore, SECRET_NAME };
|
||||
@@ -10,6 +10,11 @@ crosscode demo <church> --profile <profile> [--admin-email <email>]
|
||||
replace Cross Events' data with a demo set
|
||||
(small, events, ministry, multicampus); a backup
|
||||
is taken first, one admin account is kept
|
||||
crosscode env <church> <product> the product's .env values (secrets hidden)
|
||||
crosscode env <church> <product> [--file backend/.env] --set NAME=value … [--unset NAME …] [--restart]
|
||||
change values (a copy is kept; never secrets or
|
||||
generated values). The frontend's file rebuilds it.
|
||||
If it doesn't start again, the file is put back.
|
||||
crosscode export <church> --out <file.zip> the church's data (crosscode.church-export/1) and uploads
|
||||
crosscode uninstall <church> --confirm <church>
|
||||
final backup and uploads kept in
|
||||
@@ -102,6 +107,97 @@ cmd_demo() {
|
||||
die "Events didn't answer after the reload (sudo -u $user pm2 logs)."
|
||||
}
|
||||
|
||||
# crosscode env <church> <product>: the product's .env values, secrets hidden (the Hub's env-read).
|
||||
# With --set / --unset (the Hub's env-set): changes one file (--file, default backend/.env), keeping
|
||||
# a copy first; when the frontend's file changed, the frontend is rebuilt (Next.js builds its values
|
||||
# in); then, with --restart or after a rebuild, the product is reloaded and must answer /health.
|
||||
# Anything failing after the change puts the file back (and rebuilds again if it had rebuilt).
|
||||
ENV_BACKUPS_KEPT=5
|
||||
|
||||
cmd_env() {
|
||||
local church="" product="" file="backend/.env" restart=0 dir user app tpl path backup stamp out rc=0 rebuilt=0
|
||||
local -a changes=()
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--file) [ $# -ge 2 ] || die "--file needs a value."; file="$2"; shift 2 ;;
|
||||
--set|--unset) [ $# -ge 2 ] || die "$1 needs a value."; changes+=("$1" "$2"); shift 2 ;;
|
||||
--restart) restart=1; shift ;;
|
||||
-h|--help) manage_usage; return 0 ;;
|
||||
-*) die "Unknown option $1 (crosscode help env)." ;;
|
||||
*) if [ -z "$church" ]; then church="$1"; elif [ -z "$product" ]; then product="$1"; else die "Name one church and one product."; fi; shift ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$church" ] && [ -n "$product" ] || die "Name the church and the product (crosscode env hope events)."
|
||||
[[ "$file" =~ ^(backend|frontend)/\.env(\.production)?$ ]] || die "--file: backend/.env or frontend/.env.production."
|
||||
require_root
|
||||
load_church "$church"
|
||||
church_has_product "$product" || die "$church has no $product."
|
||||
# shellcheck source=/dev/null
|
||||
source "$CROSSCODE_HOME/products/$product.sh"
|
||||
dir="$(pvar "$product" DIR)"
|
||||
user="$(pvar "$product" USER)"
|
||||
app="$("${product}_app" "$dir")"
|
||||
tpl="$(env_template "$app" "$product")"
|
||||
|
||||
if [ "${#changes[@]}" -eq 0 ]; then
|
||||
step "$product: reading its .env files"
|
||||
out="$(node "$CROSSCODE_HOME/lib/envedit.cjs" read --template "$tpl" --dir "$app" --product "$product")" || die "Couldn't read $product's .env files."
|
||||
report_result_json env "$out"
|
||||
# shellcheck disable=SC2016 # JavaScript template strings, not shell
|
||||
[ "$CROSSCODE_JSON" = 1 ] || printf '%s\n' "$out" | node -e '
|
||||
const r = JSON.parse(require("fs").readFileSync(0, "utf8"));
|
||||
for (const f of r.files) {
|
||||
console.log(`${f.file}${f.exists ? "" : " (missing)"}`);
|
||||
for (const v of f.variables) console.log(` ${v.name}=${v.secret ? (v.set ? "(secret, set)" : "(secret, not set)") : (v.set ? v.value : "(not set)")}`);
|
||||
}' >&2
|
||||
return 0
|
||||
fi
|
||||
|
||||
path="$app/$file"
|
||||
[ -f "$path" ] || die "$church has no $product $file."
|
||||
stamp="$(date -u +%Y%m%d%H%M%S)"
|
||||
backup="$path.before-$stamp"
|
||||
step "$product: changing $file (a copy is kept as $(basename "$backup"))"
|
||||
out="$(node "$CROSSCODE_HOME/lib/envedit.cjs" set --template "$tpl" --dir "$app" --file "$file" --backup "$backup" "${changes[@]}")" || {
|
||||
rm -f "$backup"
|
||||
die "$product $file wasn't changed (see the message above)."
|
||||
}
|
||||
report_result_json changes "$out"
|
||||
info "$out"
|
||||
# Only the last few copies.
|
||||
# shellcheck disable=SC2012 # names are ours: <file>.before-<digits>
|
||||
ls -1t "$path".before-* 2>/dev/null | tail -n +$((ENV_BACKUPS_KEPT + 1)) | while read -r old; do rm -f -- "$old"; done
|
||||
|
||||
if [[ "$file" == frontend/* ]]; then
|
||||
step "$product: rebuilding the frontend (it builds $file in)"
|
||||
if run_as "$user" "$app/frontend" npm run build; then rebuilt=1; else rc=1; fi
|
||||
fi
|
||||
if [ "$rc" = 0 ] && { [ "$restart" = 1 ] || [ "$rebuilt" = 1 ]; }; then
|
||||
step "$product: reloading PM2"
|
||||
"${product}_reload" "$dir" "$user" || rc=1
|
||||
if [ "$rc" = 0 ]; then
|
||||
step "$product: waiting for it to answer"
|
||||
wait_for_version "$("${product}_health_url")" "$("${product}_expected_version" "$dir")" 90 || rc=1
|
||||
fi
|
||||
fi
|
||||
[ "$rc" = 0 ] && return 0
|
||||
|
||||
report_step_outcome failed
|
||||
step "$product: putting $file back"
|
||||
node "$CROSSCODE_HOME/lib/envedit.cjs" restore --file "$path" --backup "$backup" || die "Couldn't put $file back: the copy is $backup."
|
||||
if [[ "$file" == frontend/* ]]; then
|
||||
step "$product: rebuilding the frontend as it was"
|
||||
run_as "$user" "$app/frontend" npm run build || die "The frontend didn't build again with the old $file: run npm run build in $app/frontend."
|
||||
fi
|
||||
if [ "$restart" = 1 ] || [[ "$file" == frontend/* ]]; then
|
||||
step "$product: reloading PM2"
|
||||
"${product}_reload" "$dir" "$user" || warn "PM2 reload failed: check pm2 status as $user."
|
||||
wait_for_version "$("${product}_health_url")" "$("${product}_expected_version" "$dir")" 90 || true
|
||||
fi
|
||||
report_status rolled-back
|
||||
die "$product didn't start with the new values, so $file was put back as it was."
|
||||
}
|
||||
|
||||
cmd_export() {
|
||||
local church="" out="" p tmp dir user bytes
|
||||
while [ $# -gt 0 ]; do
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
# The agent reads the object, adds the log lines and sends it to the Hub.
|
||||
#
|
||||
# What goes in: each step() as a step (the next step, or the end, closes it), report_result
|
||||
# key/values, report_status (rolled-back), and the last die() message. Only names and outcomes:
|
||||
# never values from .env files.
|
||||
# key/values, report_status (rolled-back), and the last die() message. Only names and outcomes,
|
||||
# never values from .env files (except `crosscode env`, the Hub's env-read: non-secret values only).
|
||||
|
||||
REPORT_FILE=""
|
||||
REPORT_COMMAND=""
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env bats
|
||||
# Reading and changing .env values for the Hub (lib/envedit.cjs, `crosscode env`, contracts 1.12.0):
|
||||
# secrets are never printed, edits keep the rest of the file, secrets and generated values are refused.
|
||||
|
||||
setup() {
|
||||
TMP="$BATS_TEST_TMPDIR"
|
||||
JS="$BATS_TEST_DIRNAME/../lib/envedit.cjs"
|
||||
APP="$TMP/app"
|
||||
mkdir -p "$APP/backend" "$APP/frontend"
|
||||
cat > "$TMP/template.json" <<'EOF'
|
||||
{ "schema": "crosscode.env-template/1", "product": "events", "files": {
|
||||
"backend/.env": [
|
||||
{ "name": "NODE_ENV", "layer": "generated", "required": true },
|
||||
{ "name": "DATABASE_URL", "layer": "generated", "required": true },
|
||||
{ "name": "JWT_SECRET", "layer": "generated", "required": true },
|
||||
{ "name": "FRONTEND_URL", "layer": "install", "from": "https://{domain}", "required": true, "description": "The site's address" },
|
||||
{ "name": "TRUST_PROXY", "layer": "server", "required": true },
|
||||
{ "name": "SENTRY_DSN", "layer": "defaults" }
|
||||
],
|
||||
"frontend/.env.production": [
|
||||
{ "name": "NEXT_PUBLIC_API_URL", "layer": "install", "from": "https://{domain}", "required": true }
|
||||
] } }
|
||||
EOF
|
||||
cat > "$APP/backend/.env" <<'EOF'
|
||||
# Written by crosscode
|
||||
NODE_ENV=production
|
||||
DATABASE_URL=postgresql://hope:s3cr3t@localhost:5432/hope
|
||||
JWT_SECRET=abcdef123456
|
||||
FRONTEND_URL=https://events.hope.co.za
|
||||
TRUST_PROXY=loopback
|
||||
SMTP_PASS="pa ss"
|
||||
ORG_NAME="Hope Church"
|
||||
EOF
|
||||
chmod 640 "$APP/backend/.env"
|
||||
printf 'NEXT_PUBLIC_API_URL=https://events.hope.co.za\n' > "$APP/frontend/.env.production"
|
||||
}
|
||||
|
||||
edit() { node "$JS" "$@" --template "$TMP/template.json" --dir "$APP"; }
|
||||
|
||||
@test "read: values in file order, secrets only as set or not, template values the file lacks" {
|
||||
run edit read --product events
|
||||
[ "$status" -eq 0 ]
|
||||
[[ "$output" != *"s3cr3t"* && "$output" != *"abcdef"* && "$output" != *"pa ss"* ]]
|
||||
node -e '
|
||||
const r = JSON.parse(process.argv[1]);
|
||||
const be = r.files.find(f => f.file === "backend/.env");
|
||||
const v = Object.fromEntries(be.variables.map(x => [x.name, x]));
|
||||
const ok = r.product === "events" && be.exists
|
||||
&& v.FRONTEND_URL.value === "https://events.hope.co.za" && v.FRONTEND_URL.editable && v.FRONTEND_URL.description === "The site'"'"'s address"
|
||||
&& v.ORG_NAME.value === "Hope Church" && v.ORG_NAME.layer === null && v.ORG_NAME.editable
|
||||
&& v.DATABASE_URL.value === null && v.DATABASE_URL.secret && v.DATABASE_URL.set && !v.DATABASE_URL.editable
|
||||
&& v.SMTP_PASS.value === null && v.SMTP_PASS.secret
|
||||
&& v.NODE_ENV.value === "production" && !v.NODE_ENV.editable
|
||||
&& v.SENTRY_DSN.set === false && v.SENTRY_DSN.secret
|
||||
&& r.files.find(f => f.file === "frontend/.env.production").variables[0].value === "https://events.hope.co.za";
|
||||
process.exit(ok ? 0 : 1);' "$output"
|
||||
}
|
||||
|
||||
@test "set: changes lines where they are, appends new ones, removes, keeps the mode and a copy" {
|
||||
run edit set --file backend/.env --backup "$TMP/copy" --set FRONTEND_URL=https://new.hope.co.za --set ORG_NAME="Hope & Co" --set NEW_FLAG=false --unset TRUST_PROXY
|
||||
[ "$status" -eq 0 ]
|
||||
[[ "$output" == *'"changed":["FRONTEND_URL","ORG_NAME"]'* && "$output" == *'"added":["NEW_FLAG"]'* && "$output" == *'"removed":["TRUST_PROXY"]'* ]]
|
||||
[ "$(sed -n 5p "$APP/backend/.env")" = "FRONTEND_URL=https://new.hope.co.za" ]
|
||||
grep -qx 'ORG_NAME="Hope & Co"' "$APP/backend/.env"
|
||||
grep -qx 'NEW_FLAG=false' "$APP/backend/.env"
|
||||
! grep -q '^TRUST_PROXY=' "$APP/backend/.env"
|
||||
grep -qx 'JWT_SECRET=abcdef123456' "$APP/backend/.env"
|
||||
[ "$(uname -s)" != Linux ] || [ "$(stat -c %a "$APP/backend/.env")" = 640 ]
|
||||
grep -qx 'FRONTEND_URL=https://events.hope.co.za' "$TMP/copy"
|
||||
}
|
||||
|
||||
@test "set: refuses secrets, generated values and bad values, changing nothing" {
|
||||
cp "$APP/backend/.env" "$TMP/before"
|
||||
run edit set --file backend/.env --set JWT_SECRET=x
|
||||
[ "$status" -eq 3 ]
|
||||
run edit set --file backend/.env --set NODE_ENV=development
|
||||
[ "$status" -eq 3 ]
|
||||
run edit set --file backend/.env --unset SMTP_PASS
|
||||
[ "$status" -eq 3 ]
|
||||
run edit set --file backend/.env --set TRUST_PROXY=TRUE
|
||||
[ "$status" -eq 4 ]
|
||||
run edit set --file ../.env --set A=1
|
||||
[ "$status" -eq 2 ]
|
||||
cmp "$TMP/before" "$APP/backend/.env"
|
||||
}
|
||||
|
||||
@test "restore: puts the copy back" {
|
||||
edit set --file backend/.env --backup "$TMP/copy" --set FRONTEND_URL=https://new.hope.co.za
|
||||
node "$JS" restore --file "$APP/backend/.env" --backup "$TMP/copy"
|
||||
grep -qx 'FRONTEND_URL=https://events.hope.co.za' "$APP/backend/.env"
|
||||
}
|
||||
Reference in New Issue
Block a user