Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
293a9b73e5 | ||
|
|
621821f5c0 | ||
|
|
88b3e1fb36 | ||
|
|
70c471666b | ||
|
|
cc18b7b514 | ||
|
|
4b28fc485b | ||
|
|
793831ca44 | ||
|
|
4b033a1d1d |
@@ -2,6 +2,41 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## events@3.2.0, contracts@1.10.0 - 2026-11-19
|
||||
|
||||
Emergency updates can run as soon as possible (Hub 2.7.0); the Hub asks again when an event is on.
|
||||
|
||||
- **Contracts 1.10.0:** `stats.live` in the Cross Events heartbeat (`eventsNow`, `checkInsLastHour`;
|
||||
optional).
|
||||
- **Events 3.2.0:** sends it (sessions or one-day events on now, check-ins in the last hour).
|
||||
|
||||
## events@3.1.0, accounts@1.2.0, contracts@1.9.0 - 2026-11-19
|
||||
|
||||
A church moved Cross Events' sign-in to Accounts without email set up in Accounts: Accounts couldn't
|
||||
send codes or password links, sign-in failed with a 500, and nobody could get in.
|
||||
|
||||
- **Contracts 1.9.0:** `messaging.status`, `messaging.test`, `messaging.set` in
|
||||
`crosscode.identity-request/1` (SMTP and WAWP settings, secrets sealed); `people.ensure` answers
|
||||
`emailSent`.
|
||||
- **Accounts 1.2.0:** a code or link that can't be sent shows a message instead of a 500 (WhatsApp
|
||||
codes fall back to email); forgot password says email isn't set up; the `messaging.*` requests
|
||||
(test, and save only what worked); a test WhatsApp in its admin; WAWP from the `.env` too.
|
||||
- **The sign-in pages look like the church's site:** `@crosscode/ui` Shell / Card / Heading redone
|
||||
(colour wash, logo and name, cards edged in the church's colour, icons); Events sends its logo and
|
||||
colours (`church.branding`, and with a move).
|
||||
- **Events 3.1.0:** Settings → Sign-in shows what Accounts can send and sets it up by copying this
|
||||
site's SMTP / WAWP (its secrets stay on the server), with a test before saving; the move needs
|
||||
Accounts' email (disabled, and refused by the server, without it).
|
||||
|
||||
## crosscode script - 2026-11-19 (no tag: servers run `main`)
|
||||
|
||||
- **A church with Accounts couldn't be updated.** `crosscode install` / `add` writes Accounts' PM2
|
||||
config to `apps/accounts/ecosystem.config.cjs`, which no `.gitignore` covered, so the next
|
||||
`deploy` stopped at "files … were changed or added by hand: ?? apps/accounts/ecosystem.config.cjs".
|
||||
The PM2 configs crosscode makes (`apps/events/ecosystem.config.js`, `apps/accounts/ecosystem.config.cjs`)
|
||||
no longer count as changes by hand, also in checkouts of releases that don't ignore them, and
|
||||
`apps/accounts/.gitignore` ignores it from the next Accounts release on. bats test.
|
||||
|
||||
## events@3.0.0, accounts@1.1.0, contracts@1.8.0, crosscode script - 2026-11-19
|
||||
|
||||
Cross Events signs in through the church's Accounts (ROADMAP-v3 phase 4, docs/EVENTS-3.0-PLAN.md).
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# this install's PM2 config (made from ecosystem.config.example.cjs by the crosscode script)
|
||||
/ecosystem.config.cjs
|
||||
@@ -1,5 +1,41 @@
|
||||
# Changelog — Accounts
|
||||
|
||||
## [1.2.0] - 2026-11-19
|
||||
|
||||
Found after a church moved Cross Events' sign-in here without email set up in Accounts: every
|
||||
sign-in that needed an emailed code failed with a 500, and nobody could get in.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A code that can't be sent no longer fails the sign-in (500).** The page says the church's email
|
||||
isn't working and to tell the office (`CODE_NOT_SENT`, 503). A WhatsApp sign-in code that can't go
|
||||
is sent by email instead (as Cross Events); setting WhatsApp up still needs WhatsApp to work.
|
||||
- **Forgot password** says plainly that email isn't set up (`EMAIL_NOT_READY`, the same for every
|
||||
address) instead of failing.
|
||||
- Setting up two-step sign-in only offers email when email works (an app always does).
|
||||
- `people.ensure` makes the account even when its "choose your password" email can't go, and tells
|
||||
the product (`emailSent: false`).
|
||||
|
||||
### Changed
|
||||
|
||||
- **The sign-in pages look like the church's other sites:** a wash of the church's colour, its logo
|
||||
and name across the top (its first letter on its colour while there's no logo), the form in a card
|
||||
edged in that colour with an icon per step, and a footer (`@crosscode/ui` Shell, Card, Heading,
|
||||
ChurchMark; the account and admin pages get the same frame).
|
||||
- **The church's logo and colours come from Cross Events:** a move fills the logo, colours and name
|
||||
Accounts doesn't have yet (`import.begin` now carries the logo and accent colour), and
|
||||
`church.branding` (contracts 1.9.0) replaces them when an admin asks.
|
||||
|
||||
### Added
|
||||
|
||||
- **`messaging.*` requests** (contracts 1.9.0) for a linked product's sign-in settings: `status`
|
||||
(what can be sent, no secrets), `test` (sends a test email / WhatsApp with the settings given,
|
||||
saves nothing) and `set` (tests, then saves each part only if its test worked). The SMTP password
|
||||
and WAWP token come sealed with the link's secret, are stored encrypted, and `null` keeps the saved one.
|
||||
- Admin → Email and WhatsApp: **Send a test WhatsApp** (to the admin's own phone), next to the test email.
|
||||
- WAWP from the server's `.env` (`WAWP_ACCESS_TOKEN`, `WAWP_INSTANCE_ID`) when the database has
|
||||
none, as Cross Events and as SMTP already did.
|
||||
|
||||
## [1.1.0] - 2026-11-19
|
||||
|
||||
For Cross Events 3.0 (docs/EVENTS-3.0-PLAN.md §8), with contracts 1.8.0.
|
||||
|
||||
@@ -3,6 +3,15 @@
|
||||
What each version changes for the church, in plain language (read by the Hub like Cross Events'
|
||||
WHATS-NEW.md; a section shows once its version is tagged).
|
||||
|
||||
## 1.2.0
|
||||
|
||||
- **Fix:** when the church's email isn't working, signing in tells people so (and to let the office
|
||||
know) instead of showing an error page. Codes by WhatsApp are sent by email if WhatsApp is down.
|
||||
- Email and WhatsApp for sign-in can be set up from Cross Events (Settings → Sign-in), copying its
|
||||
own settings, with a test before they're saved.
|
||||
- Admins can send a test WhatsApp message from Email and WhatsApp.
|
||||
- **A nicer sign-in page** with your church's logo and colours, taken from Cross Events.
|
||||
|
||||
## 1.1.0
|
||||
|
||||
- **Ready for Cross Events 3.0:** Cross Events can move its people into your church's accounts,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -11,6 +11,7 @@ import { hashToken, randomCode, safeEqual } from '../lib/crypto.js';
|
||||
import { loginEvent } from '../lib/audit.js';
|
||||
import { queueCall } from '../links/deliveries.js';
|
||||
import { currentNoticeVersion } from '../privacy/notice.js';
|
||||
import { SendError } from '../lib/messages.js';
|
||||
|
||||
export const MAX_FAILED_SIGN_INS = 10;
|
||||
export const LOCK_MINUTES = 15;
|
||||
@@ -100,18 +101,33 @@ export function maskedTarget(a: Account, method: 'email' | 'whatsapp'): string {
|
||||
return `${user!.slice(0, 1)}***@${domain}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a code. 1.2.0: a WhatsApp code that can't go is sent by email instead (as Cross Events), and
|
||||
* when nothing can send it the person is told so (`SendError`, shown on the page) instead of the
|
||||
* sign-in failing.
|
||||
*/
|
||||
export async function sendCode(ctx: Ctx, a: Account, method: 'email' | 'whatsapp', purpose: 'sign_in' | 'verify_email' | 'setup'): Promise<{ codeHash: string; sentTo: string }> {
|
||||
const code = randomCode();
|
||||
const churchName = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church';
|
||||
const what = purpose === 'verify_email' ? 'confirm your email address' : 'sign in';
|
||||
const text = `Your code to ${what} at ${churchName} is ${code}. It works for ${CODE_MINUTES} minutes. If you didn't ask for it, you can ignore this message.`;
|
||||
if (method === 'whatsapp') {
|
||||
if (!a.phone) throw new Error('There\'s no phone number on this account.');
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text });
|
||||
} else {
|
||||
await ctx.messenger.email({ to: a.email, subject: `Your code: ${code}`, text });
|
||||
if (method === 'whatsapp' && a.phone) {
|
||||
try {
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text });
|
||||
return { codeHash: hashToken(code), sentTo: maskedTarget(a, 'whatsapp') };
|
||||
} catch (e) {
|
||||
// Setting WhatsApp up has to prove WhatsApp works, so no email instead then.
|
||||
if (purpose !== 'sign_in') throw new SendError('We couldn\'t send a code by WhatsApp. Choose another way to get your codes.', 'CODE_NOT_SENT');
|
||||
console.warn('[codes] WhatsApp failed, trying email:', (e as Error).message);
|
||||
}
|
||||
}
|
||||
return { codeHash: hashToken(code), sentTo: maskedTarget(a, method) };
|
||||
try {
|
||||
await ctx.messenger.email({ to: a.email, subject: `Your code: ${code}`, text });
|
||||
} 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');
|
||||
}
|
||||
return { codeHash: hashToken(code), sentTo: maskedTarget(a, 'email') };
|
||||
}
|
||||
|
||||
export const codeMatches = (code: unknown, hash: string | null | undefined) =>
|
||||
|
||||
@@ -196,7 +196,24 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
|
||||
r.post('/settings/test-email', limit(5), handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
|
||||
await ctx.messenger.email({ to: a.email, subject: 'Test email from Accounts', text: 'Email from Accounts works.' });
|
||||
try {
|
||||
await ctx.messenger.email({ to: a.email, subject: 'Test email from Accounts', text: 'Email from Accounts works.' });
|
||||
} catch (e) {
|
||||
throw new ApiError(502, 'NOT_SENT', `The test email couldn't be sent: ${(e as Error).message}`);
|
||||
}
|
||||
return { sent: true };
|
||||
}));
|
||||
|
||||
// 1.2.0: as the test email, for WhatsApp (WAWP), to the admin's own phone.
|
||||
r.post('/settings/test-whatsapp', limit(5), handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
|
||||
if (!a.phone) throw new ApiError(400, 'NO_PHONE', 'Add your mobile number on your account page first.');
|
||||
try {
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text: 'WhatsApp from Accounts works.' });
|
||||
} catch (e) {
|
||||
throw new ApiError(502, 'NOT_SENT', `The test message couldn't be sent: ${(e as Error).message}`);
|
||||
}
|
||||
return { sent: true };
|
||||
}));
|
||||
|
||||
|
||||
@@ -99,19 +99,23 @@ export async function describe(ctx: Ctx, details: Details, pending: PendingSignI
|
||||
};
|
||||
if (stage === 'password' || stage === 'done') return base;
|
||||
const a = await account(ctx, pending);
|
||||
let sentNow: string | null = null;
|
||||
if ((stage === 'verify_email' || (stage === 'two_factor' && a.twoFactorMethod !== 'totp')) && !pending.codeSentAt) {
|
||||
const method = stage === 'verify_email' ? 'email' : (a.twoFactorMethod as 'email' | 'whatsapp');
|
||||
const sent = await sendCode(ctx, a, method, stage === 'verify_email' ? 'verify_email' : 'sign_in');
|
||||
await save(ctx, pending, { codeHash: sent.codeHash, codeSentAt: ctx.now(), attempts: 0 });
|
||||
sentNow = sent.sentTo;
|
||||
}
|
||||
const extra: Record<string, unknown> = { name: a.name, email: a.email };
|
||||
if (stage === 'verify_email') extra.sentTo = maskedTarget(a, 'email');
|
||||
if (stage === 'two_factor') {
|
||||
extra.method = a.twoFactorMethod;
|
||||
if (a.twoFactorMethod !== 'totp') extra.sentTo = maskedTarget(a, a.twoFactorMethod as 'email' | 'whatsapp');
|
||||
// Where it actually went (a WhatsApp code that couldn't go was sent by email).
|
||||
if (a.twoFactorMethod !== 'totp') extra.sentTo = sentNow ?? maskedTarget(a, a.twoFactorMethod as 'email' | 'whatsapp');
|
||||
}
|
||||
if (stage === 'setup_two_factor') {
|
||||
extra.methods = ['totp', 'email', ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
|
||||
// Only the ways that can deliver a code now (1.2.0): an app always works.
|
||||
extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
|
||||
extra.why = a.role === 'admin' ? 'admin' : 'product';
|
||||
}
|
||||
if (stage === 'notice') {
|
||||
|
||||
@@ -88,6 +88,8 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
|
||||
// ─── Forgot / reset password ───────────────────────────────────────────────
|
||||
|
||||
r.post('/password/forgot', limit(5), handle(async (req) => {
|
||||
// 1.2.0: without email nobody gets a link; say so (the same answer whoever asks).
|
||||
if (!(await ctx.messenger.emailReady())) throw new ApiError(503, 'EMAIL_NOT_READY', 'Password reset links can\'t be sent right now: the church\'s email isn\'t set up. Please let the church office know.');
|
||||
const email = normaliseEmail(req.body?.email);
|
||||
const a = email ? await ctx.db.account.findUnique({ where: { email } }) : null;
|
||||
// The same answer either way, so nobody can find out who has an account (Events 1.51.17).
|
||||
|
||||
@@ -20,6 +20,8 @@ export type Config = {
|
||||
hubAdminEmail: string | null;
|
||||
timezone: string;
|
||||
smtp: { host: string; port: number; user: string; pass: string; from: string; secure: boolean } | null;
|
||||
/** 1.2.0: WAWP from the .env when the database has none (as Cross Events). */
|
||||
wawp: { accessToken: string; instanceId: string } | null;
|
||||
/** Local testing only: linked products on http or private addresses. */
|
||||
allowPrivateLinks: boolean;
|
||||
jobsEnabled: boolean;
|
||||
@@ -67,6 +69,7 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
|
||||
smtp: env.SMTP_HOST
|
||||
? { host: env.SMTP_HOST, port: Number(env.SMTP_PORT || 587), user: env.SMTP_USER || '', pass: env.SMTP_PASS || '', from: env.SMTP_FROM || env.SMTP_USER || '', secure: bool(env.SMTP_SECURE, Number(env.SMTP_PORT) === 465) }
|
||||
: null,
|
||||
wawp: env.WAWP_ACCESS_TOKEN && env.WAWP_INSTANCE_ID ? { accessToken: env.WAWP_ACCESS_TOKEN, instanceId: env.WAWP_INSTANCE_ID } : null,
|
||||
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
|
||||
jobsEnabled: bool(env.JOBS_ENABLED, true),
|
||||
};
|
||||
|
||||
@@ -8,11 +8,49 @@ import type { Ctx } from '../context.js';
|
||||
export type Email = { to: string; subject: string; text: string };
|
||||
export type WhatsApp = { to: string; text: string };
|
||||
|
||||
/** SMTP settings to try before saving them (1.2.0), as kept in `smtp_*`. */
|
||||
export type SmtpTry = { host: string; port: number; secure: boolean; user: string; pass: string; from: string };
|
||||
/** WAWP settings to try before saving them (1.2.0). */
|
||||
export type WawpTry = { accessToken: string; instanceId: string };
|
||||
|
||||
export interface Messenger {
|
||||
email(msg: Email): Promise<void>;
|
||||
whatsapp(msg: WhatsApp): Promise<void>;
|
||||
/** Whether email is set up (sign-in codes, password links and new accounts need it). */
|
||||
emailReady(): Promise<boolean>;
|
||||
/** Whether WhatsApp is set up, so it's offered as a 2FA method. */
|
||||
whatsappReady(): Promise<boolean>;
|
||||
/** Sends one email with settings that aren't saved (a test before saving them). Throws why it failed. */
|
||||
emailWith(settings: SmtpTry, msg: Email): Promise<void>;
|
||||
/** Sends one WhatsApp message with settings that aren't saved. Throws why it failed. */
|
||||
whatsappWith(settings: WawpTry, msg: WhatsApp): Promise<void>;
|
||||
}
|
||||
|
||||
/** Thrown when a message can't be sent: the sign-in pages show it instead of failing. */
|
||||
export class SendError extends Error {
|
||||
status = 503;
|
||||
constructor(message: string, public code = 'NOT_SENT') {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
function transportFor(s: SmtpTry) {
|
||||
return nodemailer.createTransport({
|
||||
host: s.host, port: s.port, secure: s.secure, auth: s.user ? { user: s.user, pass: s.pass } : undefined,
|
||||
connectionTimeout: 15000, greetingTimeout: 15000, socketTimeout: 20000,
|
||||
});
|
||||
}
|
||||
|
||||
async function wawpSend(s: WawpTry, msg: WhatsApp) {
|
||||
const number = waNumber(msg.to);
|
||||
if (!number) throw new Error('That isn\'t a WhatsApp number.');
|
||||
const res = await fetch('https://api.wawp.net/v2/send/text', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ access_token: s.accessToken, instance_id: s.instanceId, chatId: `${number}@c.us`, message: msg.text }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`WhatsApp couldn't send the message (${res.status}).`);
|
||||
}
|
||||
|
||||
/** 0821234567 / +27 82 123 4567 → 27821234567 (South African mobiles; others as given, digits only). */
|
||||
@@ -52,23 +90,33 @@ export class LiveMessenger implements Messenger {
|
||||
await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text });
|
||||
}
|
||||
|
||||
async emailReady(): Promise<boolean> {
|
||||
return !!(await this.smtp());
|
||||
}
|
||||
|
||||
private async wawp(): Promise<WawpTry | null> {
|
||||
const accessToken = (await this.ctx.settings.get('wawp_access_token')) || this.ctx.config.wawp?.accessToken;
|
||||
const instanceId = (await this.ctx.settings.get('wawp_instance_id')) || this.ctx.config.wawp?.instanceId;
|
||||
return accessToken && instanceId ? { accessToken, instanceId } : null;
|
||||
}
|
||||
|
||||
async whatsappReady(): Promise<boolean> {
|
||||
return !!((await this.ctx.settings.get('wawp_access_token')) && (await this.ctx.settings.get('wawp_instance_id')));
|
||||
return !!(await this.wawp());
|
||||
}
|
||||
|
||||
async whatsapp(msg: WhatsApp): Promise<void> {
|
||||
const token = await this.ctx.settings.get('wawp_access_token');
|
||||
const instance = await this.ctx.settings.get('wawp_instance_id');
|
||||
const number = waNumber(msg.to);
|
||||
if (!token || !instance) throw new Error('WhatsApp isn\'t set up.');
|
||||
if (!number) throw new Error('That isn\'t a WhatsApp number.');
|
||||
const res = await fetch('https://api.wawp.net/v2/send/text', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ access_token: token, instance_id: instance, chatId: `${number}@c.us`, message: msg.text }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`WhatsApp couldn't send the message (${res.status}).`);
|
||||
const s = await this.wawp();
|
||||
if (!s) throw new Error('WhatsApp isn\'t set up.');
|
||||
await wawpSend(s, msg);
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
async whatsappWith(settings: WawpTry, msg: WhatsApp): Promise<void> {
|
||||
await wawpSend(settings, msg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,9 +124,30 @@ export class MemoryMessenger implements Messenger {
|
||||
emails: Email[] = [];
|
||||
whatsapps: WhatsApp[] = [];
|
||||
whatsappOn = false;
|
||||
async email(msg: Email) { this.emails.push(msg); }
|
||||
async whatsapp(msg: WhatsApp) { this.whatsapps.push(msg); }
|
||||
/** Tests: false makes email fail as an unset SMTP does in production. */
|
||||
emailOn = true;
|
||||
/** Tests: settings tried with emailWith / whatsappWith, and a host that fails. */
|
||||
tried: { kind: 'email' | 'whatsapp'; settings: SmtpTry | WawpTry; to: string }[] = [];
|
||||
failHost: string | null = null;
|
||||
async email(msg: Email) {
|
||||
if (!this.emailOn) throw new Error('Email isn\'t set up (Admin → Email and WhatsApp).');
|
||||
this.emails.push(msg);
|
||||
}
|
||||
async whatsapp(msg: WhatsApp) {
|
||||
if (!this.whatsappOn) throw new Error('WhatsApp isn\'t set up.');
|
||||
this.whatsapps.push(msg);
|
||||
}
|
||||
async emailReady() { return this.emailOn; }
|
||||
async whatsappReady() { return this.whatsappOn; }
|
||||
async emailWith(settings: SmtpTry, msg: Email) {
|
||||
this.tried.push({ kind: 'email', settings, to: msg.to });
|
||||
if (settings.host === this.failHost) throw new Error(`connect ECONNREFUSED ${settings.host}:${settings.port}`);
|
||||
this.emails.push(msg);
|
||||
}
|
||||
async whatsappWith(settings: WawpTry, msg: WhatsApp) {
|
||||
this.tried.push({ kind: 'whatsapp', settings, to: msg.to });
|
||||
this.whatsapps.push(msg);
|
||||
}
|
||||
/** The last 6-digit code sent to `to` (tests). */
|
||||
lastCode(to: string): string | null {
|
||||
const all = [...this.emails.filter((e) => e.to === to).map((e) => e.text), ...this.whatsapps.filter((w) => w.to === to).map((w) => w.text)];
|
||||
|
||||
@@ -16,7 +16,7 @@ import express, { type Request, type Response } from 'express';
|
||||
import type Provider from 'oidc-provider';
|
||||
import {
|
||||
ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
|
||||
type IdentityRequest, type ImportPerson, type ImportResult,
|
||||
type ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult,
|
||||
} from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
@@ -166,13 +166,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
await ctx.db.privacyNotice.create({ data: { version: n.version, title: n.title, body: n.body, publishedAt: new Date(n.publishedAt), publishedById: null } });
|
||||
}
|
||||
}
|
||||
const stored = await ctx.settings.json<Record<string, unknown> & { branding?: { colours?: { primary?: string; accent?: string } } }>('church_profile', {});
|
||||
const next = { ...stored };
|
||||
if (!stored.name && r.church.name) next.name = r.church.name;
|
||||
if (!stored.branding?.colours?.primary && r.church.primaryColour) {
|
||||
next.branding = { logoUrl: null, iconUrl: null, ...(stored.branding ?? {}), colours: { accent: '#f2a900', ...(stored.branding?.colours ?? {}), primary: r.church.primaryColour } } as never;
|
||||
}
|
||||
if (JSON.stringify(next) !== JSON.stringify(stored)) await ctx.settings.set('church_profile', JSON.stringify(next));
|
||||
await applyLook(ctx, r.church, false);
|
||||
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: ctx.now() } });
|
||||
await logRequest(ctx, link, r, 'import_started', null, req, { notices: noticesTaken ? r.notices.length : 0 });
|
||||
}
|
||||
@@ -227,14 +221,22 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
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';
|
||||
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.`,
|
||||
});
|
||||
// 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.`,
|
||||
});
|
||||
} catch (e) {
|
||||
emailSent = false;
|
||||
console.warn('[people.ensure] the "choose your password" email could not be sent:', (e as Error).message);
|
||||
}
|
||||
await loginEvent(ctx, a.id, 'account_created', req, { clientId: link.installId, detail: { by: 'product', product: link.product } });
|
||||
await logRequest(ctx, link, r, 'person_created_by_product', a.id, req);
|
||||
return reply({ sub: a.id, created: true });
|
||||
await logRequest(ctx, link, r, 'person_created_by_product', a.id, req, { emailSent });
|
||||
return reply({ sub: a.id, created: true, emailSent });
|
||||
}
|
||||
case 'people.update': {
|
||||
const a = await knownAccount(ctx, link, r.sub);
|
||||
@@ -282,6 +284,53 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
await logRequest(ctx, link, r, r.active ? 'account_reactivated_by_product' : 'account_deactivated_by_product', a.id, req);
|
||||
return reply({ ok: true as const });
|
||||
}
|
||||
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 });
|
||||
return reply({ ok: true as const });
|
||||
}
|
||||
case 'messaging.status':
|
||||
return reply(await messagingStatus(ctx));
|
||||
case 'messaging.test':
|
||||
case 'messaging.set': {
|
||||
const save = r.type === 'messaging.set';
|
||||
const church = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church';
|
||||
let email: { ok: boolean; error: string | null; saved: boolean } | null = null;
|
||||
let whatsapp: { ok: boolean; error: string | null; saved: boolean } | null = null;
|
||||
if (r.email) {
|
||||
const s = r.email.settings;
|
||||
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.` });
|
||||
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 }) });
|
||||
email.saved = true;
|
||||
}
|
||||
} catch (e) {
|
||||
email = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false };
|
||||
}
|
||||
}
|
||||
if (r.whatsapp) {
|
||||
const s = r.whatsapp.settings;
|
||||
const token = s.accessToken === null ? ((await ctx.settings.get('wawp_access_token')) ?? '') : opened(secret, s.accessToken, 'WAWP access token');
|
||||
try {
|
||||
if (!token) throw new Error('Give the WAWP access token.');
|
||||
await ctx.messenger.whatsappWith({ accessToken: token, instanceId: s.instanceId }, { to: r.whatsapp.to, text: `This is a test from ${church}'s sign-in. WhatsApp works: sign-in codes can be sent.` });
|
||||
whatsapp = { ok: true, error: null, saved: false };
|
||||
if (save) {
|
||||
await ctx.settings.setMany({ wawp_instance_id: s.instanceId, ...(s.accessToken === null ? {} : { wawp_access_token: token }) });
|
||||
whatsapp.saved = true;
|
||||
}
|
||||
} catch (e) {
|
||||
whatsapp = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false };
|
||||
}
|
||||
}
|
||||
await logRequest(ctx, link, r, save ? 'messaging_set_by_product' : 'messaging_tested_by_product', null, req, { email: email && { ok: email.ok, saved: email.saved }, whatsapp: whatsapp && { ok: whatsapp.ok, saved: whatsapp.saved } });
|
||||
const status = await messagingStatus(ctx);
|
||||
return reply({ email, whatsapp, status: { email: status.email, whatsapp: status.whatsapp } });
|
||||
}
|
||||
case 'people.newsOff': {
|
||||
const a = await knownAccount(ctx, link, r.sub);
|
||||
const off = r.channel === 'all' ? { email: false, whatsapp: false } : { [r.channel]: false };
|
||||
@@ -328,6 +377,38 @@ export function requestsRouter(ctx: Ctx, provider: Provider) {
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* The church's look on Accounts' pages from a product's (1.9.0): its name, logo and colours.
|
||||
* `overwrite: false` (a move) fills only what's empty; `true` (an admin's button) replaces them.
|
||||
* Returns the fields changed.
|
||||
*/
|
||||
async function applyLook(ctx: Ctx, look: ChurchLook, overwrite: boolean): Promise<string[]> {
|
||||
type Stored = Record<string, unknown> & { name?: string; branding?: { logoUrl?: string | null; iconUrl?: string | null; colours?: { primary?: string; accent?: string | null } } };
|
||||
const stored = await ctx.settings.json<Stored>('church_profile', {});
|
||||
const branding = { logoUrl: null as string | null, iconUrl: null as string | null, ...(stored.branding ?? {}), colours: { primary: '#1f4e79', accent: '#f2a900', ...(stored.branding?.colours ?? {}) } };
|
||||
const changed: string[] = [];
|
||||
const take = (has: unknown, value: unknown) => value !== null && value !== undefined && value !== '' && (overwrite || !has);
|
||||
const next: Stored = { ...stored };
|
||||
if (take(stored.name, look.name)) { next.name = look.name!; changed.push('name'); }
|
||||
if (take(stored.branding?.logoUrl, look.logoUrl)) { branding.logoUrl = look.logoUrl!; changed.push('logo'); }
|
||||
if (take(stored.branding?.colours?.primary, look.primaryColour)) { branding.colours.primary = look.primaryColour!; changed.push('primary colour'); }
|
||||
if (take(stored.branding?.colours?.accent && stored.branding?.colours?.accent !== '#f2a900', look.accentColour)) { branding.colours.accent = look.accentColour!; changed.push('accent colour'); }
|
||||
if (!changed.length) return changed;
|
||||
next.branding = branding;
|
||||
next.updatedAt = ctx.now().toISOString();
|
||||
await ctx.settings.set('church_profile', JSON.stringify(next));
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** What can be sent now (no secrets), for a product's sign-in settings page. */
|
||||
async function messagingStatus(ctx: Ctx) {
|
||||
const emailReady = await ctx.messenger.emailReady();
|
||||
return {
|
||||
email: { ready: emailReady, host: emailReady ? ((await ctx.settings.get('smtp_host')) || ctx.config.smtp?.host || null) : null, from: emailReady ? ((await ctx.settings.get('smtp_from')) || ctx.config.smtp?.from || null) : null },
|
||||
whatsapp: { ready: await ctx.messenger.whatsappReady(), instanceId: (await ctx.settings.get('wawp_instance_id')) || ctx.config.wawp?.instanceId || null },
|
||||
};
|
||||
}
|
||||
|
||||
/** Old remembered requests (the `cleanup` job). */
|
||||
export async function forgetOldRequests(ctx: Ctx) {
|
||||
return ctx.db.productRequest.deleteMany({ where: { createdAt: { lt: new Date(ctx.now().getTime() - KEEP_REQUESTS_DAYS * 86400e3) } } });
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
// Accounts 1.2.0: sign-in never fails with a 500 when a code can't be sent, WhatsApp codes fall back
|
||||
// to email, and a linked product can check, test and set Accounts' email and WhatsApp
|
||||
// (crosscode.identity-request/1 messaging.*, contracts 1.9.0).
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import { after, before, beforeEach, describe, test } from 'node:test';
|
||||
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, sealLinkValue, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { Browser, startHarness, type Harness } from './support/harness.js';
|
||||
import type { MemoryMessenger } from '../src/lib/messages.js';
|
||||
|
||||
const EVENTS_ID = '6d1f0b2c-8a3e-4c5d-9e7f-1a2b3c4d5e6f';
|
||||
let h: Harness;
|
||||
let secret: string;
|
||||
let messenger: MemoryMessenger;
|
||||
|
||||
before(async () => {
|
||||
h = await startHarness();
|
||||
messenger = h.messenger as MemoryMessenger;
|
||||
secret = newLinkSecret();
|
||||
await h.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: 'https://events.hope.test', publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(secret), connectedAt: new Date() } });
|
||||
});
|
||||
after(async () => { await h.close(); });
|
||||
beforeEach(() => { messenger.emailOn = true; messenger.whatsappOn = false; messenger.failHost = null; });
|
||||
|
||||
async function ask(body: Record<string, unknown>) {
|
||||
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: null, ...body });
|
||||
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret, rawBody: raw }) } });
|
||||
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
|
||||
}
|
||||
|
||||
const smtp = (over: Record<string, unknown> = {}) => ({ host: 'smtp.hope.test', port: 587, secure: false, user: 'events@hope.test', pass: sealLinkValue(secret, 'mail-pass'), from: 'events@hope.test', ...over });
|
||||
|
||||
describe('a code that can\'t be sent', () => {
|
||||
test('without email, the page says so (503 with a message), never a 500', async () => {
|
||||
messenger.emailOn = false;
|
||||
await h.makeAccount({ email: 'unverified@hope.test', password: 'Correct-horse-1', emailVerified: false });
|
||||
const r = await h.signIn(new Browser(), 'unverified@hope.test', 'Correct-horse-1');
|
||||
// The password step answers with the error of the next step: the email code couldn't go.
|
||||
assert.ok('pending' in r);
|
||||
assert.equal(r.pending.error && (r.pending.error as { code: string }).code, 'CODE_NOT_SENT', JSON.stringify(r.pending));
|
||||
});
|
||||
|
||||
test('a WhatsApp code that can\'t go is sent by email', async () => {
|
||||
await h.makeAccount({ email: 'wa@hope.test', password: 'Correct-horse-1', phone: '+27821230000', twoFactorMethod: 'whatsapp' });
|
||||
const r = await h.signIn(new Browser(), 'wa@hope.test', 'Correct-horse-1');
|
||||
assert.ok('pending' in r);
|
||||
assert.equal(r.pending.stage, 'two_factor', JSON.stringify(r.pending));
|
||||
assert.match(String(r.pending.sentTo), /@hope\.test$/);
|
||||
assert.ok(messenger.lastCode('wa@hope.test'));
|
||||
});
|
||||
|
||||
test('forgot password says email isn\'t set up, for any address', async () => {
|
||||
messenger.emailOn = false;
|
||||
const res = await h.api(new Browser(), 'POST', '/api/v2/password/forgot', { email: 'nobody@hope.test' });
|
||||
assert.equal(res.status, 503);
|
||||
assert.equal((res.body.error as { code: string }).code, 'EMAIL_NOT_READY');
|
||||
});
|
||||
});
|
||||
|
||||
describe('messaging.* from a product', () => {
|
||||
test('status says what can be sent, without secrets', async () => {
|
||||
messenger.emailOn = false;
|
||||
const r = await ask({ type: 'messaging.status' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.deepEqual(r.body.email, { ready: false, host: null, from: null });
|
||||
assert.equal(JSON.stringify(r.body).includes('pass'), false);
|
||||
});
|
||||
|
||||
test('test sends with the settings given and saves nothing; a failure says why', async () => {
|
||||
const ok = await ask({ type: 'messaging.test', email: { settings: smtp(), to: 'office@hope.test' } });
|
||||
assert.deepEqual(ok.body.email, { ok: true, error: null, saved: false });
|
||||
assert.deepEqual(messenger.tried.at(-1), { kind: 'email', settings: { host: 'smtp.hope.test', port: 587, secure: false, user: 'events@hope.test', pass: 'mail-pass', from: 'events@hope.test' }, to: 'office@hope.test' });
|
||||
assert.equal(await h.ctx.settings.get('smtp_host'), null);
|
||||
messenger.failHost = 'bad.hope.test';
|
||||
const bad = await ask({ type: 'messaging.test', email: { settings: smtp({ host: 'bad.hope.test' }), to: 'office@hope.test' } });
|
||||
assert.equal((bad.body.email as { ok: boolean }).ok, false);
|
||||
assert.match(String((bad.body.email as { error: string }).error), /ECONNREFUSED/);
|
||||
});
|
||||
|
||||
test('set saves only what worked, with the password encrypted; null keeps the saved password', async () => {
|
||||
messenger.failHost = 'bad.hope.test';
|
||||
const failed = await ask({ type: 'messaging.set', email: { settings: smtp({ host: 'bad.hope.test' }), to: 'office@hope.test' } });
|
||||
assert.equal((failed.body.email as { saved: boolean }).saved, false);
|
||||
assert.equal(await h.ctx.settings.get('smtp_host'), null);
|
||||
|
||||
const saved = await ask({ type: 'messaging.set', email: { settings: smtp(), to: 'office@hope.test' }, whatsapp: { settings: { accessToken: sealLinkValue(secret, 'wawp-token'), instanceId: 'INST1' }, to: '+27821234567' } });
|
||||
assert.deepEqual([saved.body.email, saved.body.whatsapp].map((x) => (x as { saved: boolean }).saved), [true, true]);
|
||||
assert.equal(await h.ctx.settings.get('smtp_pass'), 'mail-pass');
|
||||
const row = await h.db.appSetting.findUnique({ where: { key: 'smtp_pass' } });
|
||||
assert.notEqual(row!.value, 'mail-pass', 'encrypted at rest');
|
||||
assert.equal(await h.ctx.settings.get('wawp_instance_id'), 'INST1');
|
||||
|
||||
const kept = await ask({ type: 'messaging.set', email: { settings: smtp({ pass: null, from: 'office@hope.test' }), to: 'office@hope.test' } });
|
||||
assert.equal((kept.body.email as { saved: boolean }).saved, true);
|
||||
assert.equal(await h.ctx.settings.get('smtp_pass'), 'mail-pass');
|
||||
assert.equal(await h.ctx.settings.get('smtp_from'), 'office@hope.test');
|
||||
});
|
||||
|
||||
test('people.ensure still makes the account when its email can\'t go, and says so', async () => {
|
||||
messenger.emailOn = false;
|
||||
const r = await ask({ type: 'people.ensure', name: 'No Mail', email: 'nomail@hope.test', phone: null, returnUrl: 'https://events.hope.test/' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.equal(r.body.created, true);
|
||||
assert.equal(r.body.emailSent, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the church\'s look from a product (1.9.0)', () => {
|
||||
test('a move fills only what\'s empty; the button replaces it', async () => {
|
||||
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope' }));
|
||||
const look = { name: 'Other Name', primaryColour: '#123456', accentColour: '#abcdef', logoUrl: 'https://events.hope.test/uploads/logo.png' };
|
||||
assert.equal((await ask({ type: 'church.branding', church: look, overwrite: false })).status, 200);
|
||||
const filled = await h.ctx.settings.json<{ name: string; branding: { logoUrl: string; colours: { primary: string; accent: string } } }>('church_profile', {} as never);
|
||||
assert.equal(filled.name, 'Hope Family Church', 'kept');
|
||||
assert.equal(filled.branding.logoUrl, 'https://events.hope.test/uploads/logo.png');
|
||||
assert.equal(filled.branding.colours.primary, '#123456');
|
||||
await ask({ type: 'church.branding', church: { ...look, primaryColour: '#654321', logoUrl: 'https://events.hope.test/new.png' }, overwrite: true });
|
||||
const replaced = await h.ctx.settings.json<{ name: string; branding: { logoUrl: string; colours: { primary: string } } }>('church_profile', {} as never);
|
||||
assert.deepEqual([replaced.name, replaced.branding.logoUrl, replaced.branding.colours.primary], ['Other Name', 'https://events.hope.test/new.png', '#654321']);
|
||||
// The sign-in pages get it.
|
||||
const b = await h.api(new Browser(), 'GET', '/api/v2/branding');
|
||||
assert.equal(b.body.logoUrl, 'https://events.hope.test/new.png');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"private": true,
|
||||
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
|
||||
"scripts": {
|
||||
|
||||
@@ -283,6 +283,7 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
|
||||
<div className="flex gap-2">
|
||||
<Button type="submit">Save</Button>
|
||||
{keys.includes("smtp_host") && <Button type="button" variant="secondary" onClick={async () => { const r = await call("POST", "/admin/settings/test-email"); flash(r.ok ? "success" : "error", r.ok ? "A test email is on its way to you." : r.error.message); }}>Send a test email</Button>}
|
||||
{keys.includes("wawp_instance_id") && <Button type="button" variant="secondary" onClick={async () => { const r = await call("POST", "/admin/settings/test-whatsapp"); flash(r.ok ? "success" : "error", r.ok ? "A test WhatsApp message is on its way to your phone." : r.error.message); }}>Send a test WhatsApp</Button>}
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { KeyRound } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
@@ -13,7 +14,7 @@ export function Forgot({ uid }: { uid: string | null }) {
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading sub="We'll email you a link to choose a new one.">Forgot your password?</Heading>
|
||||
<Heading icon={<KeyRound className="h-5 w-5" />} sub="We'll email you a link to choose a new one.">Forgot your password?</Heading>
|
||||
{sent ? (
|
||||
<Notice tone="success">If there's an account with that email address, a link is on its way. It works for an hour. You can close this page: the link brings you back.</Notice>
|
||||
) : (
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { KeyRound } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
@@ -12,7 +13,7 @@ export function Reset({ token }: { token: string | null }) {
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading sub="At least 8 characters.">Choose a new password</Heading>
|
||||
<Heading icon={<KeyRound className="h-5 w-5" />} sub="At least 8 characters.">Choose a new password</Heading>
|
||||
{error && <Notice tone="error">{error}</Notice>}
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { LogOut } from "lucide-react";
|
||||
import { Card, Heading, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { selfSignIn } from "@/lib/api";
|
||||
@@ -9,7 +10,7 @@ export default function SignedOutPage() {
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading sub={`You've been signed out of all of ${branding.name}'s sites.`}>You're signed out</Heading>
|
||||
<Heading icon={<LogOut className="h-5 w-5" />} sub={`You've been signed out of all of ${branding.name}'s sites.`}>You're signed out</Heading>
|
||||
<a href={selfSignIn("/account")} className="text-brand underline">Sign in again</a>
|
||||
</Card>
|
||||
</Shell>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { AlertTriangle, FileText, KeyRound, LogIn, Mail, Megaphone, ShieldCheck, UserPlus } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import QRCode from "qrcode";
|
||||
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
@@ -88,7 +89,7 @@ export function SignIn({ uid }: { uid: string }) {
|
||||
if (!state) {
|
||||
return frame(error ? (
|
||||
<>
|
||||
<Heading>We couldn't continue</Heading>
|
||||
<Heading icon={<AlertTriangle className="h-5 w-5" />}>We couldn't continue</Heading>
|
||||
<Notice tone="error">{error.message}</Notice>
|
||||
</>
|
||||
) : <p className="text-gray-600">Loading…</p>);
|
||||
@@ -121,7 +122,7 @@ function PasswordStep({ state, busy, err, onSubmit, onSignUp }: { state: State;
|
||||
const branding = useBranding();
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ email: f.get("email"), password: f.get("password"), remember: f.get("remember") === "on" }); }}>
|
||||
<Heading sub={`to continue to ${state.product}`}>Sign in to {branding.name}</Heading>
|
||||
<Heading icon={<LogIn className="h-5 w-5" />} sub={`to continue to ${state.product}`}>Sign in to {branding.name}</Heading>
|
||||
{err}
|
||||
<Field label="Email address" name="email" type="email" autoComplete="username" required defaultValue={state.loginHint ?? ""} />
|
||||
<Field label="Password" name="password" type="password" autoComplete="current-password" required />
|
||||
@@ -144,7 +145,7 @@ function SignUpStep({ busy, err, fieldError, onSubmit, onBack }: { busy: boolean
|
||||
const f = new FormData(e.currentTarget);
|
||||
onSubmit({ name: f.get("name"), email: f.get("email"), phone: f.get("phone") || undefined, password: f.get("password"), acceptNotice: f.get("acceptNotice") === "on", newsEmail: f.get("newsEmail") === "on", newsWhatsApp: f.get("newsWhatsApp") === "on", remember: true });
|
||||
}}>
|
||||
<Heading sub={`One account for all of ${branding.name}'s sites and apps.`}>Create your account</Heading>
|
||||
<Heading icon={<UserPlus className="h-5 w-5" />} sub={`One account for all of ${branding.name}'s sites and apps.`}>Create your account</Heading>
|
||||
{err}
|
||||
<Field label="Your name" name="name" autoComplete="name" required error={fieldError("name")} />
|
||||
<Field label="Email address" name="email" type="email" autoComplete="email" required error={fieldError("email")} />
|
||||
@@ -162,7 +163,7 @@ function SignUpStep({ busy, err, fieldError, onSubmit, onBack }: { busy: boolean
|
||||
function CodeStep({ title, sub, busy, err, onSubmit, onResend }: { title: string; sub: React.ReactNode; busy: boolean; err: React.ReactNode; onSubmit: (code: string) => void; onResend?: () => void }) {
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); onSubmit(String(new FormData(e.currentTarget).get("code") ?? "")); }}>
|
||||
<Heading sub={sub}>{title}</Heading>
|
||||
<Heading icon={<Mail className="h-5 w-5" />} sub={sub}>{title}</Heading>
|
||||
{err}
|
||||
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" pattern="[0-9 ]{6,7}" required autoFocus />
|
||||
<Button type="submit" busy={busy} className="w-full">Continue</Button>
|
||||
@@ -212,7 +213,7 @@ function SetupStep({ uid, state, busy, err, setError, onConfirm }: { uid: string
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<Heading sub={why}>Set up two-step sign-in</Heading>
|
||||
<Heading icon={<ShieldCheck className="h-5 w-5" />} sub={why}>Set up two-step sign-in</Heading>
|
||||
{err}
|
||||
<div className="space-y-2">
|
||||
{(state.methods ?? []).map((m) => (
|
||||
@@ -243,7 +244,7 @@ function RecoveryCodes({ codes, onDone }: { codes: string[]; onDone: () => void
|
||||
const text = codes.join("\n");
|
||||
return (
|
||||
<>
|
||||
<Heading sub="If you lose your phone, one of these lets you sign in. Each works once. Keep them somewhere safe: we can't show them again.">Save your recovery codes</Heading>
|
||||
<Heading icon={<KeyRound className="h-5 w-5" />} sub="If you lose your phone, one of these lets you sign in. Each works once. Keep them somewhere safe: we can't show them again.">Save your recovery codes</Heading>
|
||||
<pre className="mb-4 rounded-lg bg-gray-50 p-4 text-center font-mono text-sm leading-7">{text}</pre>
|
||||
<div className="mb-4 flex gap-2">
|
||||
<Button type="button" variant="secondary" onClick={() => navigator.clipboard?.writeText(text)}>Copy</Button>
|
||||
@@ -257,7 +258,7 @@ function RecoveryCodes({ codes, onDone }: { codes: string[]; onDone: () => void
|
||||
function NoticeStep({ state, busy, err, onAccept }: { state: State; busy: boolean; err: React.ReactNode; onAccept: () => void }) {
|
||||
return (
|
||||
<>
|
||||
<Heading sub={state.updated ? "Our privacy notice has changed. Please read it before you carry on." : "Please read our privacy notice before you carry on."}>{state.notice!.title}</Heading>
|
||||
<Heading icon={<FileText className="h-5 w-5" />} sub={state.updated ? "Our privacy notice has changed. Please read it before you carry on." : "Please read our privacy notice before you carry on."}>{state.notice!.title}</Heading>
|
||||
{err}
|
||||
<div className="mb-4 max-h-80 overflow-y-auto whitespace-pre-line rounded-lg border bg-gray-50 p-4 text-sm text-gray-700">{state.notice!.body}</div>
|
||||
<Button type="button" busy={busy} className="w-full" onClick={onAccept}>I've read it</Button>
|
||||
@@ -269,7 +270,7 @@ function NewsStep({ busy, err, onSubmit }: { busy: boolean; err: React.ReactNode
|
||||
const branding = useBranding();
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ email: f.get("email") === "on", whatsapp: f.get("whatsapp") === "on" }); }}>
|
||||
<Heading sub="You can change this at any time on your account page.">Would you like news from {branding.name}?</Heading>
|
||||
<Heading icon={<Megaphone className="h-5 w-5" />} sub="You can change this at any time on your account page.">Would you like news from {branding.name}?</Heading>
|
||||
{err}
|
||||
<Checkbox name="email" label="Yes, by email" />
|
||||
<Checkbox name="whatsapp" label="Yes, on WhatsApp" hint="If your mobile number is on your account." />
|
||||
|
||||
@@ -5,6 +5,43 @@ 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.2.0] - 2026-11-19
|
||||
|
||||
### Added
|
||||
|
||||
- **The heartbeat says what's on now** (`stats.live`, contracts 1.10.0, `hub/report.js liveNow`):
|
||||
events with a session on now, or a one-day event (no sessions, at most 36 hours) on now, each give
|
||||
or take 30 minutes, and tickets checked in during the last hour. Hub 2.7.0 asks for a second "yes"
|
||||
before an emergency update takes a site with an event on down.
|
||||
|
||||
## [3.1.0] - 2026-11-19
|
||||
|
||||
Found after a church moved sign-in without email set up in Accounts: Accounts couldn't send codes or
|
||||
password links, sign-in failed with a 500, and nobody could get in. Requires Accounts 1.2.0
|
||||
(`— requires accounts 1.2.0`) and contracts 1.9.0.
|
||||
|
||||
### Added
|
||||
|
||||
- **Settings → Sign-in → Email and WhatsApp for the church's sign-in** (`src/accounts/messaging.ts`,
|
||||
`components/admin/AccountsMessaging.tsx`): what Accounts can send, and this site's SMTP and WAWP
|
||||
settings to copy into it. The password and access token never reach the page: left blank, this
|
||||
site's own are used, sealed with the link's secret on the way. **Send a test** has Accounts send a
|
||||
test email / WhatsApp with those settings (nothing saved); **Save in Accounts** tests again and
|
||||
saves each part only if its test worked. Shown whenever Accounts is connected, so a church that
|
||||
already moved can mend it. `GET /api/v2/settings/sign-in/messaging`, `POST …/messaging/test`,
|
||||
`POST …/messaging`.
|
||||
|
||||
- **"Use this site's logo and colours"** on Settings → Sign-in (`POST /api/v2/settings/sign-in/look`):
|
||||
the church's sign-in pages get this site's name, logo (made a full address) and colours
|
||||
(`church.branding`); a move sends them too, filling only what Accounts doesn't have
|
||||
(`src/accounts/look.ts`).
|
||||
|
||||
### Changed
|
||||
|
||||
- **The move needs Accounts' email.** Check reports what Accounts can send (and how many people get
|
||||
WhatsApp codes, which go by email while Accounts' WhatsApp isn't set up); Move is disabled, and
|
||||
refused by the server (`EMAIL_NOT_READY`), until Accounts' email works.
|
||||
|
||||
## [3.0.0] - 2026-11-19
|
||||
|
||||
Sign-in through the church's Accounts (ROADMAP-v3 phase 4, docs/EVENTS-3.0-PLAN.md). Requires
|
||||
|
||||
@@ -22,12 +22,17 @@ Events password until an admin moves sign-in (step 4). The plan behind it is
|
||||
|
||||
Site settings → **Sign-in**:
|
||||
|
||||
1. **Check the move.** Nothing changes. It lists how many people move, who already has a church
|
||||
1. **Set up the church account's email** (Email and WhatsApp for the church's sign-in, on the same
|
||||
page, from 3.1.0). Accounts sends sign-in codes and password links itself, so without email there
|
||||
nobody could sign in after the move; Move stays disabled until it works. The page copies this
|
||||
site's email settings (leave the password blank to use this site's), **Send a test email**, check
|
||||
it arrived, then **Save in Accounts**. WhatsApp the same way, if you use it.
|
||||
2. **Check the move.** Nothing changes. It lists how many people move, who already has a church
|
||||
account (they're linked to it and keep that account's password), anyone who can't move and why,
|
||||
and the guests and deleted people who stay in Cross Events only.
|
||||
2. Tick which Cross Events admins should also be **Accounts admins** (they can manage everyone's
|
||||
3. Tick which Cross Events admins should also be **Accounts admins** (they can manage everyone's
|
||||
sign-in). By default every admin is ticked.
|
||||
3. **Move sign-in to Accounts** at a quiet time (not the evening before a big event's registration
|
||||
4. **Move sign-in to Accounts** at a quiet time (not the evening before a big event's registration
|
||||
closes). It takes about a minute. People already signed in stay signed in.
|
||||
|
||||
What people notice afterwards:
|
||||
|
||||
@@ -12,6 +12,21 @@ Write for church admins, not developers: no environment variables, endpoints or
|
||||
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||
-->
|
||||
|
||||
## 3.2.0
|
||||
|
||||
- Cross Code now sees when an event is on at your church before an urgent update, so it isn't taken
|
||||
offline in the middle of your check-in without a good reason.
|
||||
|
||||
## 3.1.0 — requires accounts 1.2.0
|
||||
|
||||
- **Fix:** moving sign-in to your church's Accounts now needs Accounts' email to work first, so
|
||||
people can always get their sign-in codes and password links. Settings → Sign-in shows whether it
|
||||
does, and sets it up for you: it copies this site's email settings (your password stays where it
|
||||
is), sends a test, and only saves them in Accounts once the test arrived. The same for WhatsApp.
|
||||
- If your church already moved without it, the same page sets it up now.
|
||||
- The church's sign-in page now has your logo and colours: they're taken from this site when you
|
||||
move, and **Use this site's logo and colours** (Settings → Sign-in) updates them any time.
|
||||
|
||||
## 3.0.0 — requires accounts 1.1.0
|
||||
|
||||
- **One sign-in for all your church's sites and apps.** People can now sign in to Cross Events with
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.0.0",
|
||||
"version": "3.2.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* This site's look (3.1.0) for the church's Accounts sign-in pages: its name, logo and colours, so
|
||||
* signing in looks like the church's own site. Sent with a move (filling what Accounts doesn't have
|
||||
* yet) and by Settings → Sign-in → "Use this site's logo and colours" (replacing it).
|
||||
*/
|
||||
import type { ChurchLook } from '@crosscode/contracts';
|
||||
import { siteUrl } from '../feed/context';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const { getSetting } = require('../utils/settingsCache') as { getSetting(k: string, f?: string): Promise<string> };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const hex = (v: string) => (/^#[0-9a-fA-F]{6}$/.test(v) ? v : null);
|
||||
|
||||
export async function churchLook(): Promise<ChurchLook> {
|
||||
const name = (await getSetting('org_name', '')) || (await getSetting('site_name', '')) || null;
|
||||
const primary = hex(await getSetting('primary_color', '')) || hex(await getSetting('brand_color', ''));
|
||||
const accent = hex(await getSetting('accent_color', '')) || hex(await getSetting('secondary_color', ''));
|
||||
// The logo as an address anyone can load: an uploaded one is a path on this site.
|
||||
const raw = String(await getSetting('logo_url', '')).trim();
|
||||
let logoUrl: string | null = null;
|
||||
if (raw) {
|
||||
try {
|
||||
const u = new URL(raw, `${(await siteUrl()).replace(/\/+$/, '')}/`);
|
||||
if (/^https?:$/.test(u.protocol)) logoUrl = u.toString();
|
||||
} catch {
|
||||
logoUrl = null;
|
||||
}
|
||||
}
|
||||
return { name: name ? name.slice(0, 200) : null, primaryColour: primary, accentColour: accent, logoUrl };
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Email and WhatsApp for the church's Accounts (3.1.0). Accounts sends its own sign-in codes and
|
||||
* password links, with its own settings, which a move doesn't bring along: a church that moved
|
||||
* sign-in without them couldn't sign in at all. Settings → Sign-in therefore shows what Accounts can
|
||||
* send, offers this site's own SMTP and WAWP settings to copy (the password and token stay on the
|
||||
* server: blank means "use this site's"), tests them through Accounts, and saves them there only
|
||||
* once the test worked (`crosscode.identity-request/1` messaging.*, contracts 1.9.0). The move
|
||||
* itself needs Accounts' email to work (move.ts).
|
||||
*/
|
||||
import type { MessagingStatusReply, MessagingTestReply } from '@crosscode/contracts';
|
||||
import { accounts } from './client';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const { getSetting } = require('../utils/settingsCache') as { getSetting(k: string, f?: string): Promise<string> };
|
||||
const whatsapp = require('../utils/whatsapp') as { getConfig(): Promise<{ token: string; instanceId: string }> };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
type Smtp = { host: string; port: number; secure: boolean; user: string; pass: string; from: string };
|
||||
|
||||
/** This site's SMTP settings, as utils/email.js reads them (the database, then the .env). */
|
||||
async function eventsSmtp(): Promise<Smtp | null> {
|
||||
const env = process.env;
|
||||
const host = await getSetting('smtp_host', env.SMTP_HOST || env.EMAIL_HOST || '');
|
||||
if (!host) return null;
|
||||
const port = parseInt(await getSetting('smtp_port', env.SMTP_PORT || env.EMAIL_PORT || '587'), 10) || 587;
|
||||
return {
|
||||
host,
|
||||
port,
|
||||
secure: String(await getSetting('smtp_secure', env.SMTP_SECURE || env.EMAIL_SECURE || 'false')).toLowerCase() === 'true',
|
||||
user: await getSetting('smtp_user', env.SMTP_USER || env.EMAIL_USER || ''),
|
||||
pass: await getSetting('smtp_pass', env.SMTP_PASS || env.EMAIL_PASS || ''),
|
||||
from: await getSetting('smtp_from', env.MAIL_FROM || env.EMAIL_FROM || ''),
|
||||
};
|
||||
}
|
||||
|
||||
/** What this site has, to offer for copying: never the password or token themselves. */
|
||||
export async function eventsMessaging() {
|
||||
const smtp = await eventsSmtp();
|
||||
const wa = await whatsapp.getConfig().catch(() => ({ token: '', instanceId: '' }));
|
||||
return {
|
||||
email: smtp ? { host: smtp.host, port: smtp.port, secure: smtp.secure, user: smtp.user, from: smtp.from || smtp.user, hasPass: !!smtp.pass } : null,
|
||||
whatsapp: wa.instanceId ? { instanceId: wa.instanceId, hasToken: !!wa.token } : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** What Accounts can send now. */
|
||||
export async function accountsMessaging(): Promise<Omit<MessagingStatusReply, 'schema'>> {
|
||||
const r = await (await accounts()).request<MessagingStatusReply>({ type: 'messaging.status', actor: null });
|
||||
return { email: r.email, whatsapp: r.whatsapp };
|
||||
}
|
||||
|
||||
export type MessagingInput = {
|
||||
email?: { host: string; port: number; secure: boolean; user: string; from: string; pass?: string | null; to: string };
|
||||
whatsapp?: { instanceId: string; accessToken?: string | null; to: string };
|
||||
};
|
||||
|
||||
/**
|
||||
* Tests (and with `save`, saves) settings in Accounts. A blank password or token means this site's
|
||||
* own; Accounts gets it sealed with the link's secret. Returns Accounts' answer per part.
|
||||
*/
|
||||
export async function sendToAccounts(input: MessagingInput, opts: { save: boolean; actor: string | null }): Promise<Omit<MessagingTestReply, 'schema'>> {
|
||||
const auth = await accounts();
|
||||
let email;
|
||||
if (input.email) {
|
||||
const own = await eventsSmtp();
|
||||
const pass = input.email.pass ? input.email.pass : (own?.pass ?? '');
|
||||
email = {
|
||||
settings: { host: input.email.host.trim(), port: input.email.port, secure: input.email.secure, user: input.email.user.trim(), from: input.email.from.trim(), pass: pass ? auth.seal(pass) : null },
|
||||
to: input.email.to.trim(),
|
||||
};
|
||||
}
|
||||
let wa;
|
||||
if (input.whatsapp) {
|
||||
const own = await whatsapp.getConfig().catch(() => ({ token: '', instanceId: '' }));
|
||||
const token = input.whatsapp.accessToken ? input.whatsapp.accessToken : own.token;
|
||||
wa = { settings: { instanceId: input.whatsapp.instanceId.trim(), accessToken: token ? auth.seal(token) : null }, to: input.whatsapp.to.trim() };
|
||||
}
|
||||
const r = await auth.request<MessagingTestReply>({
|
||||
type: opts.save ? 'messaging.set' : 'messaging.test',
|
||||
actor: opts.actor,
|
||||
...(email ? { email } : {}),
|
||||
...(wa ? { whatsapp: wa } : {}),
|
||||
}, { timeoutMs: 60000 });
|
||||
return { email: r.email, whatsapp: r.whatsapp, status: r.status };
|
||||
}
|
||||
@@ -17,13 +17,14 @@ import crypto from 'node:crypto';
|
||||
import { IMPORT_BATCH_MAX, phoneSchema, type ImportPerson, type ImportResult } from '@crosscode/contracts';
|
||||
import { siteUrl } from '../feed/context';
|
||||
import { accounts, accountsLink, AccountsUnavailable } from './client';
|
||||
import { accountsMessaging } from './messaging';
|
||||
import { churchLook } from './look';
|
||||
import { authMode, CLEARED_KEY, getSetting, MODE_KEY, MOVED_AT_KEY, REPORT_KEY, setSetting, UNDO_DAYS } from './mode';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
|
||||
const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
|
||||
const { getSettingSync } = require('../utils/settingsCache') as { getSettingSync(k: string, f?: string): string };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
export class MoveError extends Error {
|
||||
@@ -143,11 +144,6 @@ export async function status(): Promise<MoveSummary> {
|
||||
};
|
||||
}
|
||||
|
||||
function church() {
|
||||
const name = getSettingSync('org_name', '') || getSettingSync('site_name', '') || null;
|
||||
const colour = getSettingSync('primary_color', '') || getSettingSync('brand_color', '');
|
||||
return { name: name ? name.slice(0, 200) : null, primaryColour: /^#[0-9a-fA-F]{6}$/.test(colour) ? colour : null };
|
||||
}
|
||||
|
||||
export type CheckResult = {
|
||||
accountsVersion: string;
|
||||
@@ -159,6 +155,8 @@ export type CheckResult = {
|
||||
admins: { id: string; name: string; email: string }[];
|
||||
noticeConflict: { accountsVersions: number[]; eventsVersions: number[] } | null;
|
||||
withTwoFactor: number;
|
||||
/** 3.1.0: what Accounts can send. The move needs email (codes and password links); WhatsApp codes go by email when WhatsApp can't. */
|
||||
messaging: { email: boolean; whatsapp: boolean; whatsappTwoFactor: number };
|
||||
};
|
||||
|
||||
async function connected() {
|
||||
@@ -174,7 +172,7 @@ async function connected() {
|
||||
/** The dry run: nothing is written, here or in Accounts. */
|
||||
export async function check(): Promise<CheckResult> {
|
||||
const auth = await connected();
|
||||
const begin = await auth.request<{ noticesTaken: boolean; accountsNoticeVersions: number[]; accountsVersion: string }>({ type: 'import.begin', actor: null, check: true, notices: [], church: church() });
|
||||
const begin = await auth.request<{ noticesTaken: boolean; accountsNoticeVersions: number[]; accountsVersion: string }>({ type: 'import.begin', actor: null, check: true, notices: [], church: await churchLook() });
|
||||
if (!versionAtLeast(begin.accountsVersion, MIN_ACCOUNTS)) {
|
||||
throw new MoveError(`The church's Accounts is version ${begin.accountsVersion}; moving sign-in needs 1.1.0 or later. Update Accounts first.`, 'ACCOUNTS_TOO_OLD');
|
||||
}
|
||||
@@ -199,9 +197,15 @@ export async function check(): Promise<CheckResult> {
|
||||
admins: people.filter((p) => p.role === 'admin').map((p) => ({ id: p.id, name: p.name, email: p.email })),
|
||||
noticeConflict: !begin.noticesTaken && eventsNotices.length ? { accountsVersions: begin.accountsNoticeVersions, eventsVersions: eventsNotices.map((n) => n.version - 1) } : null,
|
||||
withTwoFactor: people.filter((p) => p.twoFactorEnabled).length,
|
||||
messaging: await messagingNow(people),
|
||||
};
|
||||
}
|
||||
|
||||
async function messagingNow(people: Row[]) {
|
||||
const status = await accountsMessaging();
|
||||
return { email: status.email.ready, whatsapp: status.whatsapp.ready, whatsappTwoFactor: people.filter((p) => p.twoFactorEnabled && p.twoFactorMethod === 'whatsapp').length };
|
||||
}
|
||||
|
||||
export type MoveReport = {
|
||||
movedAt: string;
|
||||
by: string;
|
||||
@@ -262,6 +266,12 @@ export async function moveNewPeople(actor: string | null = null): Promise<{ move
|
||||
/** The move. Throws MoveError when it doesn't finish; nothing changes for anyone then. */
|
||||
export async function move(opts: { actor: { id: string; role: string; name?: string }; adminIds: string[]; keepAccountsNotices?: boolean; ip?: string | null }): Promise<MoveReport> {
|
||||
const auth = await connected();
|
||||
// 3.1.0: without email in Accounts nobody can get a code or a password link there, so nobody
|
||||
// could sign in after the move. Set it up first (Settings → Sign-in → Email and WhatsApp).
|
||||
const messaging = await accountsMessaging();
|
||||
if (!messaging.email.ready) {
|
||||
throw new MoveError("The church's Accounts can't send email yet, so people couldn't get their sign-in codes or password links there. Set up its email first (copy this site's, test it, save it), then move.", 'EMAIL_NOT_READY');
|
||||
}
|
||||
const running = await getSetting(RUNNING_KEY);
|
||||
if (running && Date.now() - new Date(running).getTime() < 30 * 60e3) throw new MoveError('A move is already running.', 'RUNNING');
|
||||
await setSetting(RUNNING_KEY, new Date().toISOString());
|
||||
@@ -271,7 +281,7 @@ export async function move(opts: { actor: { id: string; role: string; name?: str
|
||||
try {
|
||||
const eventsNotices = await notices();
|
||||
const begin = await auth.request<{ noticesTaken: boolean; accountsVersion: string }>({
|
||||
type: 'import.begin', actor: opts.actor.id, check: false, notices: opts.keepAccountsNotices ? [] : eventsNotices, church: church(),
|
||||
type: 'import.begin', actor: opts.actor.id, check: false, notices: opts.keepAccountsNotices ? [] : eventsNotices, church: await churchLook(),
|
||||
});
|
||||
begun = true;
|
||||
if (!versionAtLeast(begin.accountsVersion, MIN_ACCOUNTS)) throw new MoveError(`The church's Accounts is version ${begin.accountsVersion}; moving sign-in needs 1.1.0 or later.`, 'ACCOUNTS_TOO_OLD');
|
||||
|
||||
@@ -58,6 +58,25 @@ async function pendingMigrations() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 3.2.0: what's happening at the church now (heartbeat `stats.live`), so the Hub warns before an
|
||||
* emergency update takes the site down: events with a session on now, or a one-day event (no
|
||||
* sessions, at most 36 hours long) on now, each give or take 30 minutes; and tickets checked in
|
||||
* during the last hour. A multi-week course without a session today doesn't count.
|
||||
*/
|
||||
async function liveNow(now = new Date()) {
|
||||
const soon = new Date(now.getTime() + 30 * 60e3);
|
||||
const recent = new Date(now.getTime() - 30 * 60e3);
|
||||
const [sessions, plain, checkInsLastHour] = await Promise.all([
|
||||
prisma.eventSession.findMany({ where: { cancelledAt: null, startsAt: { lte: soon }, endsAt: { gte: recent }, event: { isActive: true } }, select: { eventId: true } }),
|
||||
prisma.event.findMany({ where: { isActive: true, startDate: { lte: soon }, endDate: { gte: recent }, sessions: { none: {} } }, select: { id: true, startDate: true, endDate: true } }),
|
||||
prisma.ticketUsage.count({ where: { scannedAt: { gte: new Date(now.getTime() - 60 * 60e3) } } }),
|
||||
]);
|
||||
const ids = new Set(sessions.map(x => x.eventId));
|
||||
for (const e of plain) if (new Date(e.endDate) - new Date(e.startDate) <= 36 * 60 * 60e3) ids.add(e.id);
|
||||
return { eventsNow: ids.size, checkInsLastHour };
|
||||
}
|
||||
|
||||
async function disk() {
|
||||
try {
|
||||
const s = await fs.promises.statfs(path.join(__dirname, '..', '..'));
|
||||
@@ -123,11 +142,13 @@ async function stats(now = new Date()) {
|
||||
prisma.payment.aggregate({ where: { createdAt: { gte: yearAgo }, ...EVENT_INCOME }, _sum: { amount: true } }),
|
||||
require('../payments').availableProviders().then(list => list.map(p => p.id)).catch(() => []),
|
||||
]);
|
||||
const live = await liveNow(now).catch(() => undefined);
|
||||
const campusesOn = await campusesEnabled().catch(() => false);
|
||||
const campusCount = campusesOn ? await prisma.campus.count({ where: { archivedAt: null } }) : 0;
|
||||
return {
|
||||
users,
|
||||
events: { active: activeEvents, upcoming: upcomingEvents, total: totalEvents },
|
||||
...(live ? { live } : {}),
|
||||
registrations: { last30d: regs30, total: regsTotal },
|
||||
tickets: { last30d: tickets30, total: ticketsTotal },
|
||||
checkIns: { last30d: checkIns30 },
|
||||
@@ -165,4 +186,4 @@ async function installInfo() {
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { APP_VERSION, incomeBand, health, stats, installInfo };
|
||||
module.exports = { APP_VERSION, incomeBand, health, stats, installInfo, liveNow };
|
||||
|
||||
@@ -5,6 +5,8 @@ import { single } from '../paging';
|
||||
import { authMode } from '../../accounts/mode';
|
||||
import { check, move, MoveError, status, undo } from '../../accounts/move';
|
||||
import { accounts, accountsLink, AccountsUnavailable } from '../../accounts/client';
|
||||
import { accountsMessaging, eventsMessaging, sendToAccounts } from '../../accounts/messaging';
|
||||
import { churchLook } from '../../accounts/look';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../../config/db');
|
||||
@@ -94,6 +96,7 @@ export const signInCheck = defineRoute({
|
||||
admins: z.array(person.extend({ id: z.string() })),
|
||||
noticeConflict: z.object({ accountsVersions: z.array(z.number()), eventsVersions: z.array(z.number()) }).nullable(),
|
||||
withTwoFactor: z.number().int(),
|
||||
messaging: z.object({ email: z.boolean(), whatsapp: z.boolean(), whatsappTwoFactor: z.number().int() }).describe('3.1.0: what Accounts can send; the move needs email'),
|
||||
})),
|
||||
async handler() {
|
||||
return { data: await check().catch(asApiError) };
|
||||
@@ -132,6 +135,120 @@ export const signInUndo = defineRoute({
|
||||
},
|
||||
});
|
||||
|
||||
// ─── Email and WhatsApp for Accounts (3.1.0) ────────────────────────────────
|
||||
|
||||
const messagingOverview = z.object({
|
||||
events: z.object({
|
||||
email: z.object({ host: z.string(), port: z.number().int(), secure: z.boolean(), user: z.string(), from: z.string(), hasPass: z.boolean() }).nullable(),
|
||||
whatsapp: z.object({ instanceId: z.string(), hasToken: z.boolean() }).nullable(),
|
||||
}).describe("This site's own settings, to copy (never the password or token)"),
|
||||
accounts: z.object({
|
||||
email: z.object({ ready: z.boolean(), host: z.string().nullable(), from: z.string().nullable() }),
|
||||
whatsapp: z.object({ ready: z.boolean(), instanceId: z.string().nullable() }),
|
||||
}).nullable().describe("What the church's Accounts can send (null: it can't be reached)"),
|
||||
accountsError: z.string().nullable(),
|
||||
});
|
||||
|
||||
export const signInMessaging = defineRoute({
|
||||
method: 'get',
|
||||
path: '/settings/sign-in/messaging',
|
||||
tag: 'Accounts',
|
||||
summary: "Email and WhatsApp: this site's, and what Accounts can send",
|
||||
access: 'admin',
|
||||
response: single(messagingOverview),
|
||||
async handler() {
|
||||
const events = await eventsMessaging();
|
||||
try {
|
||||
return { data: { events, accounts: await accountsMessaging(), accountsError: null } };
|
||||
} catch (e) {
|
||||
return { data: { events, accounts: null, accountsError: (e as Error).message } };
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
/** 082 123 4567 → +27821234567 (as Accounts keeps phone numbers). */
|
||||
const toE164 = (raw: string) => {
|
||||
const d = raw.replace(/\D/g, '');
|
||||
if (raw.trim().startsWith('+')) return `+${d}`;
|
||||
return d.startsWith('0') && d.length === 10 ? `+27${d.slice(1)}` : `+${d}`;
|
||||
};
|
||||
|
||||
const messagingBody = z.object({
|
||||
email: z.object({
|
||||
host: z.string().trim().min(1).max(253),
|
||||
port: z.number().int().min(1).max(65535),
|
||||
secure: z.boolean(),
|
||||
user: z.string().max(254),
|
||||
from: z.string().trim().min(3).max(320),
|
||||
pass: z.string().max(500).nullable().optional().describe("Blank: this site's own password"),
|
||||
to: z.email().describe('Where the test email goes'),
|
||||
}).optional(),
|
||||
whatsapp: z.object({
|
||||
instanceId: z.string().trim().min(1).max(200),
|
||||
accessToken: z.string().max(500).nullable().optional().describe("Blank: this site's own token"),
|
||||
to: z.string().trim().min(8).max(30).describe('The phone the test message goes to'),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
const messagingResult = z.object({ ok: z.boolean(), error: z.string().nullable(), saved: z.boolean() }).nullable();
|
||||
const messagingAnswer = single(z.object({ email: messagingResult, whatsapp: messagingResult, status: z.object({ email: z.object({ ready: z.boolean(), host: z.string().nullable(), from: z.string().nullable() }), whatsapp: z.object({ ready: z.boolean(), instanceId: z.string().nullable() }) }) }));
|
||||
|
||||
async function messagingFor(body: z.infer<typeof messagingBody>, user: { id: string; role: string }, req: unknown, save: boolean) {
|
||||
if (!body.email && !body.whatsapp) throw new ApiError('VALIDATION_FAILED', 'Give email or WhatsApp settings.');
|
||||
const actor = (await prisma.user.findUnique({ where: { id: user.id }, select: { accountId: true } }))?.accountId ?? null;
|
||||
const input = { ...(body.email ? { email: body.email } : {}), ...(body.whatsapp ? { whatsapp: { ...body.whatsapp, to: toE164(body.whatsapp.to) } } : {}) };
|
||||
const out = await sendToAccounts(input, { save, actor }).catch(asApiError);
|
||||
if (save) {
|
||||
await logAdminAction({ actorId: user.id, actorRole: user.role, action: 'account_changed_in_accounts', targetType: 'setting', targetId: 'accounts_messaging', metadata: { email: out.email && { ok: out.email.ok, saved: out.email.saved, host: body.email?.host }, whatsapp: out.whatsapp && { ok: out.whatsapp.ok, saved: out.whatsapp.saved } }, ip: getClientIp(req) });
|
||||
}
|
||||
return { data: out };
|
||||
}
|
||||
|
||||
export const signInMessagingTest = defineRoute({
|
||||
method: 'post',
|
||||
path: '/settings/sign-in/messaging/test',
|
||||
tag: 'Accounts',
|
||||
summary: 'Test email / WhatsApp settings through Accounts (nothing saved)',
|
||||
description: "Accounts sends a test email to `email.to` and a WhatsApp message to `whatsapp.to` with the settings given. A blank password or token uses this site's own.",
|
||||
access: 'admin',
|
||||
body: messagingBody,
|
||||
response: messagingAnswer,
|
||||
async handler({ body, user, req }) {
|
||||
return messagingFor(body, user!, req, false);
|
||||
},
|
||||
});
|
||||
|
||||
export const signInMessagingSave = defineRoute({
|
||||
method: 'post',
|
||||
path: '/settings/sign-in/messaging',
|
||||
tag: 'Accounts',
|
||||
summary: 'Save email / WhatsApp settings in Accounts (after a test)',
|
||||
description: 'Accounts tests each part as /test does, and saves it only if its test worked.',
|
||||
access: 'admin',
|
||||
body: messagingBody,
|
||||
response: messagingAnswer,
|
||||
async handler({ body, user, req }) {
|
||||
return messagingFor(body, user!, req, true);
|
||||
},
|
||||
});
|
||||
|
||||
export const signInLook = defineRoute({
|
||||
method: 'post',
|
||||
path: '/settings/sign-in/look',
|
||||
tag: 'Accounts',
|
||||
summary: "Use this site's logo and colours on the church's sign-in pages",
|
||||
description: "Sends this site's name, logo and colours to the church's Accounts, replacing what its sign-in pages had.",
|
||||
access: 'admin',
|
||||
response: single(z.object({ name: z.string().nullable(), logoUrl: z.string().nullable(), primaryColour: z.string().nullable(), accentColour: z.string().nullable() })),
|
||||
async handler({ user, req }) {
|
||||
const look = await churchLook();
|
||||
const actor = (await prisma.user.findUnique({ where: { id: user!.id }, select: { accountId: true } }))?.accountId ?? null;
|
||||
await (await accounts().catch(asApiError)).request({ type: 'church.branding', actor, church: look, overwrite: true }).catch(asApiError);
|
||||
await logAdminAction({ actorId: user!.id, actorRole: user!.role, action: 'account_changed_in_accounts', targetType: 'setting', targetId: 'accounts_look', metadata: look, ip: getClientIp(req) });
|
||||
return { data: { name: look.name, logoUrl: look.logoUrl ?? null, primaryColour: look.primaryColour, accentColour: look.accentColour ?? null } };
|
||||
},
|
||||
});
|
||||
|
||||
// ─── An admin, for someone's account (sign-in through Accounts) ─────────────
|
||||
|
||||
const idParams = z.object({ id: z.uuid() });
|
||||
|
||||
@@ -58,6 +58,7 @@ const { signInGuard } = require('../../src/accounts/guard.ts');
|
||||
const { protect } = require('../../src/middleware/authMiddleware.js');
|
||||
const move = require('../../src/accounts/move.ts');
|
||||
const mode = require('../../src/accounts/mode.ts');
|
||||
const messaging = require('../../src/accounts/messaging.ts');
|
||||
const { setAuthClientLoader } = require('../../src/accounts/client.ts');
|
||||
|
||||
const EVENTS_ID = '6d1f0b2c-8a3e-4c5d-9e7f-1a2b3c4d5e6f';
|
||||
@@ -104,6 +105,10 @@ before(async () => {
|
||||
await h.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: eventsUrl, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(secret), connectedAt: new Date() } });
|
||||
await edb.productLink.create({ data: { installId: ACCOUNTS_ID, product: 'accounts', url: h.publicUrl, publicKey: 'x', secret: encrypt(secret), connectedAt: new Date(), updatedAt: new Date() } });
|
||||
await edb.appSetting.create({ data: { key: 'hub_install_id', value: EVENTS_ID } });
|
||||
// This site's own email settings (3.1.0: copied to Accounts before the move).
|
||||
for (const [key, value] of Object.entries({ smtp_host: 'smtp.hope.test', smtp_port: '587', smtp_secure: 'false', smtp_user: 'events@hope.test', smtp_pass: 'events-mail-pass', smtp_from: 'events@hope.test' })) {
|
||||
await edb.appSetting.create({ data: { key, value } });
|
||||
}
|
||||
|
||||
// Events' people before the move.
|
||||
await eventsUser({ id: ids.thandi, name: 'Thandi Mokoena', email: 'thandi@hope.test', password: await bcrypt.hash('Old-events-pass1', 4), newsEmail: true });
|
||||
@@ -143,6 +148,34 @@ async function signInThroughEvents(browser: Browser, email: string, password: st
|
||||
|
||||
const me = (token: string) => fetch(`${eventsUrl}/api/v2/me`, { headers: { authorization: `Bearer ${token}` } });
|
||||
|
||||
describe('Accounts\' email before the move (3.1.0)', () => {
|
||||
test('without email in Accounts, the check says so and the move is refused', async () => {
|
||||
(h.messenger as unknown as { emailOn: boolean }).emailOn = false;
|
||||
const r = await move.check();
|
||||
assert.equal(r.messaging.email, false);
|
||||
await assert.rejects(move.move({ actor: { id: ids.sam, role: 'admin' }, adminIds: [] }), (e: { code?: string }) => e.code === 'EMAIL_NOT_READY');
|
||||
mode.forgetMode();
|
||||
assert.equal(await mode.authMode(), 'local');
|
||||
});
|
||||
|
||||
test('this site\'s SMTP is copied (its own password, never sent to the page), tested, then saved in Accounts', async () => {
|
||||
const own = await messaging.eventsMessaging();
|
||||
assert.deepEqual(own.email, { host: 'smtp.hope.test', port: 587, secure: false, user: 'events@hope.test', from: 'events@hope.test', hasPass: true });
|
||||
const email = { host: own.email.host, port: own.email.port, secure: own.email.secure, user: own.email.user, from: own.email.from, pass: null, to: 'sam@hope.test' };
|
||||
const tested = await messaging.sendToAccounts({ email }, { save: false, actor: null });
|
||||
assert.deepEqual(tested.email, { ok: true, error: null, saved: false });
|
||||
const tried = (h.messenger as unknown as { tried: { settings: { pass: string } }[] }).tried.at(-1)!;
|
||||
assert.equal(tried.settings.pass, 'events-mail-pass', 'this site\'s own password, sealed on the way');
|
||||
assert.equal(await h.ctx.settings.get('smtp_host'), null, 'a test saves nothing');
|
||||
const saved = await messaging.sendToAccounts({ email }, { save: true, actor: null });
|
||||
assert.equal(saved.email.saved, true);
|
||||
assert.equal(await h.ctx.settings.get('smtp_pass'), 'events-mail-pass');
|
||||
// (The in-memory messenger stands for a working SMTP from here.)
|
||||
(h.messenger as unknown as { emailOn: boolean }).emailOn = true;
|
||||
assert.equal((await messaging.accountsMessaging()).email.ready, true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('moving Events\' sign-in to Accounts', () => {
|
||||
test('the check counts people and writes nothing', async () => {
|
||||
const r = await move.check();
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// 3.2.0: the heartbeat's `stats.live` (what's on now), which the Hub reads before an emergency
|
||||
// update takes the site down. A session on now, or a one-day event without sessions, counts; a
|
||||
// multi-week course with no session today doesn't.
|
||||
const NOW = new Date('2026-11-22T09:00:00.000Z');
|
||||
const H = 3600e3;
|
||||
const mockSessions = [];
|
||||
const mockEvents = [];
|
||||
let mockCheckIns = 0;
|
||||
|
||||
jest.mock('../src/config/db', () => ({
|
||||
eventSession: {
|
||||
findMany: async ({ where }) => mockSessions.filter(s => s.cancelledAt === null && s.startsAt <= where.startsAt.lte && s.endsAt >= where.endsAt.gte).map(s => ({ eventId: s.eventId })),
|
||||
},
|
||||
event: {
|
||||
findMany: async ({ where }) => mockEvents.filter(e => !e.hasSessions && e.startDate <= where.startDate.lte && e.endDate >= where.endDate.gte),
|
||||
},
|
||||
ticketUsage: { count: async () => mockCheckIns },
|
||||
}));
|
||||
|
||||
const { liveNow } = require('../src/hub/report');
|
||||
|
||||
beforeEach(() => { mockSessions.length = 0; mockEvents.length = 0; mockCheckIns = 0; });
|
||||
|
||||
test('a session on now and a one-day event on now count; a long course and a later session don\'t', async () => {
|
||||
mockSessions.push({ eventId: 'course', startsAt: new Date(NOW.getTime() - H), endsAt: new Date(NOW.getTime() + H), cancelledAt: null });
|
||||
mockSessions.push({ eventId: 'later', startsAt: new Date(NOW.getTime() + 5 * H), endsAt: new Date(NOW.getTime() + 6 * H), cancelledAt: null });
|
||||
mockSessions.push({ eventId: 'cancelled', startsAt: new Date(NOW.getTime() - H), endsAt: new Date(NOW.getTime() + H), cancelledAt: new Date() });
|
||||
mockEvents.push({ id: 'breakfast', startDate: new Date(NOW.getTime() - H), endDate: new Date(NOW.getTime() + 2 * H) });
|
||||
mockEvents.push({ id: 'term', startDate: new Date(NOW.getTime() - 20 * 24 * H), endDate: new Date(NOW.getTime() + 40 * 24 * H) });
|
||||
mockCheckIns = 12;
|
||||
expect(await liveNow(NOW)).toEqual({ eventsNow: 2, checkInsLastHour: 12 });
|
||||
});
|
||||
|
||||
test('starting within half an hour counts as on', async () => {
|
||||
mockEvents.push({ id: 'soon', startDate: new Date(NOW.getTime() + 20 * 60e3), endDate: new Date(NOW.getTime() + 3 * H) });
|
||||
expect((await liveNow(NOW)).eventsNow).toBe(1);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.0.0",
|
||||
"version": "3.2.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Mail, MessageCircle } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiV2, type V2Result } from "@/lib/apiV2";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Overview = V2Result<"/settings/sign-in/messaging", "get">["data"];
|
||||
type Answer = V2Result<"/settings/sign-in/messaging", "post">["data"];
|
||||
type Result = { ok: boolean; error: string | null; saved: boolean } | null;
|
||||
|
||||
/**
|
||||
* Email and WhatsApp for the church's Accounts (3.1.0): Accounts sends its own sign-in codes and
|
||||
* password links, with its own settings, so they're set up before sign-in moves there. This site's
|
||||
* own settings are offered to copy (its password and WAWP token stay on the server: leave the field
|
||||
* blank to use them), tested through Accounts, and saved there only once the test worked.
|
||||
*/
|
||||
export function AccountsMessaging({ onReady }: { onReady: (ready: { email: boolean; whatsapp: boolean }) => void }) {
|
||||
const { token, user } = useAuth();
|
||||
const [data, setData] = useState<Overview | null>(null);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [email, setEmail] = useState({ host: "", port: "587", secure: false, user: "", from: "", pass: "", to: "" });
|
||||
const [wa, setWa] = useState({ instanceId: "", accessToken: "", to: "" });
|
||||
const [emailResult, setEmailResult] = useState<Result>(null);
|
||||
const [waResult, setWaResult] = useState<Result>(null);
|
||||
const [testedEmail, setTestedEmail] = useState<string | null>(null);
|
||||
const [testedWa, setTestedWa] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
|
||||
const load = () => {
|
||||
if (!token) return;
|
||||
apiV2("get", "/settings/sign-in/messaging", { authToken: token })
|
||||
.then(({ data: d }) => {
|
||||
setData(d);
|
||||
if (d.accounts) onReady({ email: d.accounts.email.ready, whatsapp: d.accounts.whatsapp.ready });
|
||||
const e = d.events.email;
|
||||
if (e) setEmail((x) => (x.host ? x : { ...x, host: e.host, port: String(e.port), secure: e.secure, user: e.user, from: e.from }));
|
||||
if (d.events.whatsapp) setWa((x) => (x.instanceId ? x : { ...x, instanceId: d.events.whatsapp!.instanceId }));
|
||||
})
|
||||
.catch((e) => setErr(errorMessage(e) || "Could not load the email settings."));
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- once per sign-in
|
||||
useEffect(load, [token]);
|
||||
useEffect(() => {
|
||||
setEmail((x) => (x.to ? x : { ...x, to: user?.email || "" }));
|
||||
setWa((x) => (x.to ? x : { ...x, to: user?.phoneNumber || "" }));
|
||||
}, [user]);
|
||||
|
||||
if (!token) return null;
|
||||
if (!data) return err ? <p className="text-sm text-red-700">{err}</p> : <p className="text-sm text-gray-500">Loading email settings…</p>;
|
||||
|
||||
const emailKey = JSON.stringify({ ...email, to: undefined });
|
||||
const waKey = JSON.stringify({ ...wa, to: undefined });
|
||||
const emailBody = () => ({ email: { host: email.host, port: parseInt(email.port, 10) || 587, secure: email.secure, user: email.user, from: email.from, pass: email.pass || null, to: email.to } });
|
||||
const waBody = () => ({ whatsapp: { instanceId: wa.instanceId, accessToken: wa.accessToken || null, to: wa.to } });
|
||||
|
||||
const run = async (key: string, save: boolean, body: object, after: (a: Answer) => void) => {
|
||||
setBusy(key);
|
||||
setErr(null);
|
||||
try {
|
||||
const { data: a } = save
|
||||
? await apiV2("post", "/settings/sign-in/messaging", { authToken: token, body: body as never })
|
||||
: await apiV2("post", "/settings/sign-in/messaging/test", { authToken: token, body: body as never });
|
||||
after(a);
|
||||
setData((d) => (d ? { ...d, accounts: { email: a.status.email, whatsapp: a.status.whatsapp }, accountsError: null } : d));
|
||||
onReady({ email: a.status.email.ready, whatsapp: a.status.whatsapp.ready });
|
||||
} catch (e) {
|
||||
setErr(errorMessage(e) || "That didn't work.");
|
||||
}
|
||||
setBusy(null);
|
||||
};
|
||||
|
||||
const acc = data.accounts;
|
||||
const input = "w-full rounded-lg border px-3 py-2 text-sm";
|
||||
const line = (r: Result, what: string) => r && (
|
||||
<p className={`text-sm ${r.ok ? "text-green-800" : "text-red-800"}`} role="status">
|
||||
{r.ok ? (r.saved ? `Saved in Accounts: ${what} works there now.` : `The test ${what} went. Check it arrived, then save.`) : `The test didn't work: ${r.error}`}
|
||||
</p>
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="border rounded-xl p-4 space-y-4">
|
||||
<div>
|
||||
<h3 className="font-medium">Email and WhatsApp for the church's sign-in</h3>
|
||||
<p className="text-sm text-gray-600">Accounts sends sign-in codes and password links itself, with its own settings. Without email there, nobody can sign in after the move.</p>
|
||||
</div>
|
||||
{data.accountsError ? (
|
||||
<p className="text-sm text-red-700">Accounts can't be reached: {data.accountsError}</p>
|
||||
) : acc && (
|
||||
<ul className="text-sm space-y-1">
|
||||
<li className="flex items-center gap-2"><Mail className="h-4 w-4" aria-hidden /> Email: {acc.email.ready ? <span className="text-green-800">works{acc.email.from ? ` (from ${acc.email.from})` : ""}</span> : <span className="font-medium text-red-800">not set up</span>}</li>
|
||||
<li className="flex items-center gap-2"><MessageCircle className="h-4 w-4" aria-hidden /> WhatsApp: {acc.whatsapp.ready ? <span className="text-green-800">works</span> : <span className="text-amber-800">not set up (WhatsApp codes then go by email)</span>}</li>
|
||||
</ul>
|
||||
)}
|
||||
{err && <p className="text-sm text-red-800">{err}</p>}
|
||||
|
||||
<details open={!!acc && !acc.email.ready} className="rounded-lg border p-3">
|
||||
<summary className="cursor-pointer text-sm font-medium">{acc?.email.ready ? "Change Accounts' email" : "Set up Accounts' email"}{data.events.email ? " (copied from this site)" : ""}</summary>
|
||||
<div className="mt-3 grid gap-3 md:grid-cols-2">
|
||||
<label className="text-sm">SMTP server<input className={input} value={email.host} onChange={(e) => setEmail({ ...email, host: e.target.value })} /></label>
|
||||
<label className="text-sm">Port<input className={input} inputMode="numeric" value={email.port} onChange={(e) => setEmail({ ...email, port: e.target.value })} /></label>
|
||||
<label className="text-sm">User name<input className={input} value={email.user} onChange={(e) => setEmail({ ...email, user: e.target.value })} autoComplete="off" /></label>
|
||||
<label className="text-sm">Password<input className={input} type="password" value={email.pass} onChange={(e) => setEmail({ ...email, pass: e.target.value })} autoComplete="new-password" placeholder={data.events.email?.hasPass ? "Leave blank to use this site's password" : ""} /></label>
|
||||
<label className="text-sm">Send from<input className={input} value={email.from} onChange={(e) => setEmail({ ...email, from: e.target.value })} /></label>
|
||||
<label className="flex items-center gap-2 text-sm md:mt-6"><input type="checkbox" checked={email.secure} onChange={(e) => setEmail({ ...email, secure: e.target.checked })} /> TLS from the start (port 465)</label>
|
||||
<label className="text-sm md:col-span-2">Send the test email to<input className={input} type="email" value={email.to} onChange={(e) => setEmail({ ...email, to: e.target.value })} /></label>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" className="px-3 py-2 rounded-lg border text-sm" disabled={!!busy || !email.host || !email.to}
|
||||
onClick={() => run("email-test", false, emailBody(), (a) => { setEmailResult(a.email); if (a.email?.ok) setTestedEmail(emailKey); })}>
|
||||
{busy === "email-test" ? "Sending…" : "Send a test email"}
|
||||
</button>
|
||||
<button type="button" className="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm disabled:opacity-50" disabled={!!busy || testedEmail !== emailKey}
|
||||
title={testedEmail !== emailKey ? "Send a test with these settings first" : undefined}
|
||||
onClick={() => run("email-save", true, emailBody(), (a) => setEmailResult(a.email))}>
|
||||
{busy === "email-save" ? "Saving…" : "Save in Accounts"}
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-2">{line(emailResult, "email")}</div>
|
||||
</details>
|
||||
|
||||
<details className="rounded-lg border p-3">
|
||||
<summary className="cursor-pointer text-sm font-medium">{acc?.whatsapp.ready ? "Change Accounts' WhatsApp (WAWP)" : "Set up Accounts' WhatsApp (WAWP), optional"}{data.events.whatsapp ? " (copied from this site)" : ""}</summary>
|
||||
<div className="mt-3 grid gap-3 md:grid-cols-2">
|
||||
<label className="text-sm">WAWP instance id<input className={input} value={wa.instanceId} onChange={(e) => setWa({ ...wa, instanceId: e.target.value })} /></label>
|
||||
<label className="text-sm">WAWP access token<input className={input} type="password" value={wa.accessToken} onChange={(e) => setWa({ ...wa, accessToken: e.target.value })} autoComplete="new-password" placeholder={data.events.whatsapp?.hasToken ? "Leave blank to use this site's token" : ""} /></label>
|
||||
<label className="text-sm md:col-span-2">Send the test message to<input className={input} type="tel" value={wa.to} onChange={(e) => setWa({ ...wa, to: e.target.value })} placeholder="082 123 4567" /></label>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" className="px-3 py-2 rounded-lg border text-sm" disabled={!!busy || !wa.instanceId || !wa.to}
|
||||
onClick={() => run("wa-test", false, waBody(), (a) => { setWaResult(a.whatsapp); if (a.whatsapp?.ok) setTestedWa(waKey); })}>
|
||||
{busy === "wa-test" ? "Sending…" : "Send a test WhatsApp"}
|
||||
</button>
|
||||
<button type="button" className="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm disabled:opacity-50" disabled={!!busy || testedWa !== waKey}
|
||||
title={testedWa !== waKey ? "Send a test with these settings first" : undefined}
|
||||
onClick={() => run("wa-save", true, waBody(), (a) => setWaResult(a.whatsapp))}>
|
||||
{busy === "wa-save" ? "Saving…" : "Save in Accounts"}
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-2">{line(waResult, "WhatsApp")}</div>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { LogIn } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiV2, type V2Result } from "@/lib/apiV2";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { AccountsMessaging } from "@/components/admin/AccountsMessaging";
|
||||
|
||||
type Status = V2Result<"/settings/sign-in", "get">["data"];
|
||||
type Check = V2Result<"/settings/sign-in/check", "post">["data"];
|
||||
@@ -26,6 +27,8 @@ export function SignInTab({ active }: { active: boolean }) {
|
||||
const [keepAccountsNotices, setKeepAccountsNotices] = useState(false);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
// 3.1.0: what Accounts can send (the move needs its email).
|
||||
const [sending, setSending] = useState<{ email: boolean; whatsapp: boolean } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || !token) return;
|
||||
@@ -98,6 +101,28 @@ export function SignInTab({ active }: { active: boolean }) {
|
||||
|
||||
{msg && <p className={`text-sm rounded-lg px-3 py-2 ${msg.ok ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`} role="status">{msg.text}</p>}
|
||||
|
||||
{status.accountsConnected && <AccountsMessaging onReady={setSending} />}
|
||||
|
||||
{status.accountsConnected && (
|
||||
<section className="border rounded-xl p-4 flex flex-wrap items-center gap-3">
|
||||
<div className="flex-1 min-w-[16rem]">
|
||||
<h3 className="font-medium">How the sign-in page looks</h3>
|
||||
<p className="text-sm text-gray-600">The church's sign-in page uses its name, logo and colours. Moving sign-in copies this site's when it has none; this replaces them with this site's now.</p>
|
||||
</div>
|
||||
<button type="button" className="px-3 py-2 rounded-lg border text-sm" disabled={!!busy} onClick={async () => {
|
||||
setBusy("look");
|
||||
setMsg(null);
|
||||
try {
|
||||
await apiV2("post", "/settings/sign-in/look", auth);
|
||||
setMsg({ ok: true, text: "The sign-in page now uses this site's logo and colours." });
|
||||
} catch (e) {
|
||||
setMsg({ ok: false, text: errorMessage(e) || "That didn't work." });
|
||||
}
|
||||
setBusy(null);
|
||||
}}>{busy === "look" ? "Sending…" : "Use this site's logo and colours"}</button>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{status.mode === "accounts" ? (
|
||||
<section className="border rounded-xl p-4 space-y-3">
|
||||
<p className="text-sm"><span className="font-medium">Through Accounts</span>{status.accountsUrl ? <> at <a className="underline" href={status.accountsUrl} target="_blank" rel="noreferrer">{status.accountsUrl.replace(/^https?:\/\//, "")}</a></> : null}{status.movedAt ? `, since ${when(status.movedAt)}` : ""}.</p>
|
||||
@@ -158,7 +183,13 @@ export function SignInTab({ active }: { active: boolean }) {
|
||||
<label className="flex items-center gap-2 text-sm py-0.5 text-gray-400"><input type="radio" name="notice" disabled checked={!keepAccountsNotices} readOnly /> Use Cross Events' notice (remove Accounts' notice in Accounts first)</label>
|
||||
</fieldset>
|
||||
)}
|
||||
<button type="button" onClick={runMove} disabled={!!busy || (!!checked.noticeConflict && !keepAccountsNotices)} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium disabled:opacity-50">
|
||||
{!(sending?.email ?? checked.messaging.email) && (
|
||||
<p className="text-sm font-medium text-red-800">Set up Accounts' email above first (copy this site's, test it, save it): without it nobody could get a sign-in code or password link after the move.</p>
|
||||
)}
|
||||
{!!checked.messaging.whatsappTwoFactor && !(sending?.whatsapp ?? checked.messaging.whatsapp) && (
|
||||
<p className="text-sm text-amber-800">{checked.messaging.whatsappTwoFactor} people get their codes by WhatsApp, which Accounts can't send yet: their codes will go by email until you set it up.</p>
|
||||
)}
|
||||
<button type="button" onClick={runMove} disabled={!!busy || (!!checked.noticeConflict && !keepAccountsNotices) || !(sending?.email ?? checked.messaging.email)} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium disabled:opacity-50">
|
||||
{busy === "move" ? "Moving… (don't close this page)" : "Move sign-in to Accounts"}
|
||||
</button>
|
||||
<p className="text-xs text-gray-500">Pick a quiet time. It takes about a minute; people already signed in stay signed in. You can undo it for 14 days.</p>
|
||||
|
||||
@@ -72554,6 +72554,29 @@
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"messaging": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"whatsappTwoFactor": {
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email",
|
||||
"whatsapp",
|
||||
"whatsappTwoFactor"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"description": "3.1.0: what Accounts can send; the move needs email"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -72565,7 +72588,8 @@
|
||||
"skipped",
|
||||
"admins",
|
||||
"noticeConflict",
|
||||
"withTwoFactor"
|
||||
"withTwoFactor",
|
||||
"messaging"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -72870,6 +72894,877 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/settings/sign-in/messaging": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Accounts"
|
||||
],
|
||||
"summary": "Email and WhatsApp: this site's, and what Accounts can send",
|
||||
"description": "**Who:** Admins only.",
|
||||
"operationId": "getSettingsSign-inMessaging",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"parameters": [],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"events": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"host": {
|
||||
"type": "string"
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"secure": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"user": {
|
||||
"type": "string"
|
||||
},
|
||||
"from": {
|
||||
"type": "string"
|
||||
},
|
||||
"hasPass": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"host",
|
||||
"port",
|
||||
"secure",
|
||||
"user",
|
||||
"from",
|
||||
"hasPass"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"instanceId": {
|
||||
"type": "string"
|
||||
},
|
||||
"hasToken": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"instanceId",
|
||||
"hasToken"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email",
|
||||
"whatsapp"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"description": "This site's own settings, to copy (never the password or token)"
|
||||
},
|
||||
"accounts": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ready": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"host": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"from": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ready",
|
||||
"host",
|
||||
"from"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ready": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"instanceId": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ready",
|
||||
"instanceId"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email",
|
||||
"whatsapp"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "What the church's Accounts can send (null: it can't be reached)"
|
||||
},
|
||||
"accountsError": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"events",
|
||||
"accounts",
|
||||
"accountsError"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"tags": [
|
||||
"Accounts"
|
||||
],
|
||||
"summary": "Save email / WhatsApp settings in Accounts (after a test)",
|
||||
"description": "Accounts tests each part as /test does, and saves it only if its test worked.\n\n**Who:** Admins only.",
|
||||
"operationId": "postSettingsSign-inMessaging",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"host": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 65535
|
||||
},
|
||||
"secure": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"user": {
|
||||
"type": "string",
|
||||
"maxLength": 254
|
||||
},
|
||||
"from": {
|
||||
"type": "string",
|
||||
"minLength": 3,
|
||||
"maxLength": 320
|
||||
},
|
||||
"pass": {
|
||||
"description": "Blank: this site's own password",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 500
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"to": {
|
||||
"type": "string",
|
||||
"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,}$",
|
||||
"description": "Where the test email goes"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"host",
|
||||
"port",
|
||||
"secure",
|
||||
"user",
|
||||
"from",
|
||||
"to"
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"instanceId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"accessToken": {
|
||||
"description": "Blank: this site's own token",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 500
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"to": {
|
||||
"type": "string",
|
||||
"minLength": 8,
|
||||
"maxLength": 30,
|
||||
"description": "The phone the test message goes to"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"instanceId",
|
||||
"to"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ok": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"error": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"saved": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ok",
|
||||
"error",
|
||||
"saved"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ok": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"error": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"saved": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ok",
|
||||
"error",
|
||||
"saved"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"status": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ready": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"host": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"from": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ready",
|
||||
"host",
|
||||
"from"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ready": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"instanceId": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ready",
|
||||
"instanceId"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email",
|
||||
"whatsapp"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email",
|
||||
"whatsapp",
|
||||
"status"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/settings/sign-in/messaging/test": {
|
||||
"post": {
|
||||
"tags": [
|
||||
"Accounts"
|
||||
],
|
||||
"summary": "Test email / WhatsApp settings through Accounts (nothing saved)",
|
||||
"description": "Accounts sends a test email to `email.to` and a WhatsApp message to `whatsapp.to` with the settings given. A blank password or token uses this site's own.\n\n**Who:** Admins only.",
|
||||
"operationId": "postSettingsSign-inMessagingTest",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"host": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 65535
|
||||
},
|
||||
"secure": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"user": {
|
||||
"type": "string",
|
||||
"maxLength": 254
|
||||
},
|
||||
"from": {
|
||||
"type": "string",
|
||||
"minLength": 3,
|
||||
"maxLength": 320
|
||||
},
|
||||
"pass": {
|
||||
"description": "Blank: this site's own password",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 500
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"to": {
|
||||
"type": "string",
|
||||
"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,}$",
|
||||
"description": "Where the test email goes"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"host",
|
||||
"port",
|
||||
"secure",
|
||||
"user",
|
||||
"from",
|
||||
"to"
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"instanceId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"accessToken": {
|
||||
"description": "Blank: this site's own token",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 500
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"to": {
|
||||
"type": "string",
|
||||
"minLength": 8,
|
||||
"maxLength": 30,
|
||||
"description": "The phone the test message goes to"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"instanceId",
|
||||
"to"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ok": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"error": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"saved": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ok",
|
||||
"error",
|
||||
"saved"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ok": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"error": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"saved": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ok",
|
||||
"error",
|
||||
"saved"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"status": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ready": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"host": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"from": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ready",
|
||||
"host",
|
||||
"from"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ready": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"instanceId": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ready",
|
||||
"instanceId"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email",
|
||||
"whatsapp"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email",
|
||||
"whatsapp",
|
||||
"status"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/settings/sign-in/look": {
|
||||
"post": {
|
||||
"tags": [
|
||||
"Accounts"
|
||||
],
|
||||
"summary": "Use this site's logo and colours on the church's sign-in pages",
|
||||
"description": "Sends this site's name, logo and colours to the church's Accounts, replacing what its sign-in pages had.\n\n**Who:** Admins only.",
|
||||
"operationId": "postSettingsSign-inLook",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"parameters": [],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"logoUrl": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"primaryColour": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"accentColour": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"logoUrl",
|
||||
"primaryColour",
|
||||
"accentColour"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/users/{id}/account/reset-two-factor": {
|
||||
"post": {
|
||||
"tags": [
|
||||
|
||||
+384
@@ -7606,6 +7606,76 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/settings/sign-in/messaging": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* Email and WhatsApp: this site's, and what Accounts can send
|
||||
* @description **Who:** Admins only.
|
||||
*/
|
||||
get: operations["getSettingsSign-inMessaging"];
|
||||
put?: never;
|
||||
/**
|
||||
* Save email / WhatsApp settings in Accounts (after a test)
|
||||
* @description Accounts tests each part as /test does, and saves it only if its test worked.
|
||||
*
|
||||
* **Who:** Admins only.
|
||||
*/
|
||||
post: operations["postSettingsSign-inMessaging"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/settings/sign-in/messaging/test": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Test email / WhatsApp settings through Accounts (nothing saved)
|
||||
* @description Accounts sends a test email to `email.to` and a WhatsApp message to `whatsapp.to` with the settings given. A blank password or token uses this site's own.
|
||||
*
|
||||
* **Who:** Admins only.
|
||||
*/
|
||||
post: operations["postSettingsSign-inMessagingTest"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/settings/sign-in/look": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Use this site's logo and colours on the church's sign-in pages
|
||||
* @description Sends this site's name, logo and colours to the church's Accounts, replacing what its sign-in pages had.
|
||||
*
|
||||
* **Who:** Admins only.
|
||||
*/
|
||||
post: operations["postSettingsSign-inLook"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/users/{id}/account/reset-two-factor": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -39892,6 +39962,12 @@ export interface operations {
|
||||
eventsVersions: number[];
|
||||
} | null;
|
||||
withTwoFactor: number;
|
||||
/** @description 3.1.0: what Accounts can send; the move needs email */
|
||||
messaging: {
|
||||
email: boolean;
|
||||
whatsapp: boolean;
|
||||
whatsappTwoFactor: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
@@ -40044,6 +40120,314 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
"getSettingsSign-inMessaging": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
/** @description This site's own settings, to copy (never the password or token) */
|
||||
events: {
|
||||
email: {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user: string;
|
||||
from: string;
|
||||
hasPass: boolean;
|
||||
} | null;
|
||||
whatsapp: {
|
||||
instanceId: string;
|
||||
hasToken: boolean;
|
||||
} | null;
|
||||
};
|
||||
/** @description What the church's Accounts can send (null: it can't be reached) */
|
||||
accounts: {
|
||||
email: {
|
||||
ready: boolean;
|
||||
host: string | null;
|
||||
from: string | null;
|
||||
};
|
||||
whatsapp: {
|
||||
ready: boolean;
|
||||
instanceId: string | null;
|
||||
};
|
||||
} | null;
|
||||
accountsError: string | null;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @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"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
"postSettingsSign-inMessaging": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
email?: {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user: string;
|
||||
from: string;
|
||||
/** @description Blank: this site's own password */
|
||||
pass?: string | null;
|
||||
/**
|
||||
* Format: email
|
||||
* @description Where the test email goes
|
||||
*/
|
||||
to: string;
|
||||
};
|
||||
whatsapp?: {
|
||||
instanceId: string;
|
||||
/** @description Blank: this site's own token */
|
||||
accessToken?: string | null;
|
||||
/** @description The phone the test message goes to */
|
||||
to: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
email: {
|
||||
ok: boolean;
|
||||
error: string | null;
|
||||
saved: boolean;
|
||||
} | null;
|
||||
whatsapp: {
|
||||
ok: boolean;
|
||||
error: string | null;
|
||||
saved: boolean;
|
||||
} | null;
|
||||
status: {
|
||||
email: {
|
||||
ready: boolean;
|
||||
host: string | null;
|
||||
from: string | null;
|
||||
};
|
||||
whatsapp: {
|
||||
ready: boolean;
|
||||
instanceId: string | null;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @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"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
"postSettingsSign-inMessagingTest": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
email?: {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user: string;
|
||||
from: string;
|
||||
/** @description Blank: this site's own password */
|
||||
pass?: string | null;
|
||||
/**
|
||||
* Format: email
|
||||
* @description Where the test email goes
|
||||
*/
|
||||
to: string;
|
||||
};
|
||||
whatsapp?: {
|
||||
instanceId: string;
|
||||
/** @description Blank: this site's own token */
|
||||
accessToken?: string | null;
|
||||
/** @description The phone the test message goes to */
|
||||
to: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
email: {
|
||||
ok: boolean;
|
||||
error: string | null;
|
||||
saved: boolean;
|
||||
} | null;
|
||||
whatsapp: {
|
||||
ok: boolean;
|
||||
error: string | null;
|
||||
saved: boolean;
|
||||
} | null;
|
||||
status: {
|
||||
email: {
|
||||
ready: boolean;
|
||||
host: string | null;
|
||||
from: string | null;
|
||||
};
|
||||
whatsapp: {
|
||||
ready: boolean;
|
||||
instanceId: string | null;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @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"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
"postSettingsSign-inLook": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
name: string | null;
|
||||
logoUrl: string | null;
|
||||
primaryColour: string | null;
|
||||
accentColour: string | null;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @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"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
"postUsersIdAccountReset-two-factor": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events",
|
||||
"version": "3.0.0",
|
||||
"version": "3.2.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev:backend": "cd backend && npm run dev",
|
||||
|
||||
@@ -464,6 +464,13 @@ only for a connected product:
|
||||
logout, `user.updated`, Undo) against the whole Accounts app on real ports, each with an in-memory
|
||||
database (14 tests, including demo people and moving again after Undo). `user.export` and `user.deleted` are Jest tests (`tests/accountsCalls.test.ts`).
|
||||
|
||||
13. **3.1.0 (after the first church moved):** Accounts has its own email and WhatsApp settings,
|
||||
which a move doesn't bring, and it failed with a 500 when a code couldn't be sent, so nobody
|
||||
could sign in. Now the move needs Accounts' email; Settings → Sign-in copies Events' SMTP / WAWP
|
||||
into Accounts (secrets sealed, never on the page), with a test first (`messaging.*`, contracts
|
||||
1.9.0); Accounts 1.2.0 shows a message instead of a 500 and sends WhatsApp codes by email when
|
||||
WhatsApp is down.
|
||||
|
||||
## Decisions
|
||||
|
||||
Confirmed by Joshua on 2026-11-19, all as proposed.
|
||||
|
||||
+2
-1
@@ -843,7 +843,7 @@ ranking.
|
||||
| 27 | Deploying from the Hub | A **server agent** on every server runs installs, updates and uninstalls on **signed jobs of fixed types** from the Hub, always through the `crosscode` script (which still works by hand). Changes decisions 10 and 23; rule 2 (§1) reworded |
|
||||
| 28 | The agent's exposure | **It has no URL or listening port.** It only polls the Hub over outgoing HTTPS |
|
||||
| 29 | Confirming risky jobs | Uninstall and emergency updates need **2FA again** in the Hub; uninstall also needs the short name typed |
|
||||
| 30 | Notice before updates | **Scheduled: at least 4 hours**; **emergency: at least 15 minutes**, with a reason. The site admin gets an email and a banner straight away. Joshua picks the time. A job the agent misses doesn't run late |
|
||||
| 30 | Notice before updates | **Scheduled: at least 4 hours**; **emergency: at least 15 minutes**, with a reason. The site admin gets an email and a banner straight away. Joshua picks the time. A job the agent misses doesn't run late. **Changed 2026-11-19** (decision 39): an emergency can also run as soon as possible |
|
||||
| 31 | Uninstall | The church gets a **JSON export in our own format** (`crosscode.church-export/1`, no internal tables or ids), encrypted so the Hub can't read it, downloadable for **30 days**. The final backup is kept 30 days, then deleted (Joshua emailed 3 days before) |
|
||||
| 32 | frp | Every church server is behind frp to **one central FastPanel server**. The Hub keeps the **port list** (unique across servers, same number local and remote), tunnels are named `<church>-<product>-web/-api` |
|
||||
| 33 | frpc.ini | **Only appended to**, in marked blocks, checked with `frpc verify`, with a backup first; uninstall removes only its own block. `admin_addr = 127.0.0.1` / `admin_port = 7400` added once to `[common]` so frpc reloads without dropping other sites |
|
||||
@@ -857,6 +857,7 @@ ranking.
|
||||
| # | Question | Decision |
|
||||
|---|----------|----------|
|
||||
| 38 | Order after Accounts | **Cross Events 3.0.0 (sign-in through Accounts) is phase 4, the Church Website phase 5** (swapped). Events is what churches use today, so Accounts is proven on real users and their migrated passwords and 2FA first; the Website then starts with a church whose people already have accounts |
|
||||
| 39 | Emergency updates now | An emergency update (reason and 2FA, as before) can run **as soon as possible**, at the agent's next poll (within a minute), as well as at a time at least 15 minutes away. The church is told it's happening now. When the church's Events heartbeat shows an event on now (a session or a one-day event, or check-ins in the last hour), the Hub names it and needs a second "yes". Hub 2.7.0, Events 3.2.0 |
|
||||
|
||||
## Still open
|
||||
|
||||
|
||||
+20
-4
@@ -10,11 +10,11 @@ separately below; the two often differ.
|
||||
|
||||
| What | Repo | Latest | Tag | Released |
|
||||
|------|------|--------|-----|----------|
|
||||
| Cross Events | `crosscode-platform` (`apps/events`) | **3.0.0** | `events@3.0.0` | 2026-11-19 |
|
||||
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.1.0** | `accounts@1.1.0` | 2026-11-19 |
|
||||
| Cross Events | `crosscode-platform` (`apps/events`) | **3.2.0** | `events@3.2.0` | 2026-11-19 |
|
||||
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.2.0** | `accounts@1.2.0` | 2026-11-19 |
|
||||
| Server agent | `crosscode-platform` (`apps/agent`) | **1.2.0** | `agent@1.2.0` | 2026-11-19 |
|
||||
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.8.0** | `contracts@1.8.0` | 2026-11-19 |
|
||||
| Cross Code Hub | `events-hub` | **2.5.0** | `v2.5.0` | 2026-11-19 |
|
||||
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.10.0** | `contracts@1.10.0` | 2026-11-19 |
|
||||
| Cross Code Hub | `events-hub` | **2.7.0** | `v2.7.0` | 2026-11-19 |
|
||||
| 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) |
|
||||
|
||||
@@ -37,6 +37,22 @@ need their own tags until something outside this repo depends on them.
|
||||
|
||||
## What each latest release was for
|
||||
|
||||
- **Hub 2.7.0:** emergency updates "as soon as possible" (the agent's next poll), and a second "yes"
|
||||
when the church has an event on now (from Events 3.2.0's heartbeat). 2.6.1: the Failed jobs filter
|
||||
and alert search answered 500. No migration; deploy it.
|
||||
- **Events 3.2.0 + contracts 1.10.0:** the heartbeat says what's on now (`stats.live`).
|
||||
|
||||
- **Events 3.1.0 + Accounts 1.2.0 + contracts 1.9.0:** the move to Accounts needs Accounts' email
|
||||
(Settings → Sign-in sets it up by copying Events' SMTP / WAWP, tests, then saves); Accounts shows a
|
||||
message instead of a 500 when a code can't be sent. **Use these instead of 3.0.0 / 1.1.0.**
|
||||
|
||||
- **Hub 2.6.0:** paged lists (jobs, audit log and alerts on the server), job filters for every
|
||||
status, updates for one product at a time with that product's releases, an Events update that
|
||||
keeps (or updates, or first installs) the church's Accounts explicitly, and installs found on a
|
||||
server tied to their registration. No migration. **Deploy it** (after 2.5.0, or straight to it).
|
||||
- **`crosscode` script (2026-11-19, later):** Accounts' own `ecosystem.config.cjs` no longer stops
|
||||
a deploy as "changed by hand".
|
||||
|
||||
- **Events 3.0.0** (phase 4, [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)): sign-in through the
|
||||
church's Accounts. Needs Accounts 1.1.0 (`requires accounts 1.1.0`). Nothing changes for a
|
||||
church until an admin moves sign-in (Settings → Sign-in); see `apps/events/MIGRATING-TO-3.md`.
|
||||
|
||||
Generated
+5
-5
@@ -46,7 +46,7 @@
|
||||
},
|
||||
"apps/accounts/backend": {
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
@@ -82,7 +82,7 @@
|
||||
},
|
||||
"apps/accounts/frontend": {
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/ui": "*",
|
||||
@@ -127,7 +127,7 @@
|
||||
},
|
||||
"apps/events/backend": {
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.0.0",
|
||||
"version": "3.2.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
@@ -177,7 +177,7 @@
|
||||
},
|
||||
"apps/events/frontend": {
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.0.0",
|
||||
"version": "3.2.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
@@ -21275,7 +21275,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.8.0",
|
||||
"version": "1.10.0",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"zod": "^4.6.7"
|
||||
|
||||
@@ -10,7 +10,7 @@ Events and the Hub, uses it, so the key fields are the same in every product's J
|
||||
| Event feed | `crosscode.event-feed/1` | `GET /api/feed/v1/events?updatedSince=` and the `event.changed` webhook | `src/event.ts` |
|
||||
| Church | `crosscode.church/1` | The church profile: name, branding, campuses, service times, contact details, product links | `src/church.ts` |
|
||||
| Identity | `crosscode.identity/1` | Accounts' sign-in claims and back-channel calls (`user.updated`, `user.deleted`, `user.export`) and their replies | `src/identity.ts` |
|
||||
| Identity requests | `crosscode.identity-request/1` | From 1.8.0: what a product asks of its Accounts at `POST /api/accounts/v1/requests`: moving its users in (`import.begin` / `batch` / `finish` / `abort`, secrets sealed with `sealLinkValue`) and `people.*` (ensure, update, reset 2FA, unlock, set active, news off) | `src/identity-request.ts` |
|
||||
| Identity requests | `crosscode.identity-request/1` | From 1.8.0: what a product asks of its Accounts at `POST /api/accounts/v1/requests`: moving its users in (`import.begin` / `batch` / `finish` / `abort`, secrets sealed with `sealLinkValue`) and `people.*` (ensure, update, reset 2FA, unlock, set active, news off); from 1.9.0 `messaging.*` (status, test, set Accounts' email and WhatsApp) | `src/identity-request.ts` |
|
||||
| Sign-in return | — | The return-path check and OIDC `state` every product uses (ROADMAP-v3 §3) | `src/return-to.ts` |
|
||||
| Product link | `crosscode.link/1` | **Connect** under Settings → Linked products: the signed handshake that sets up a link's secret (`link.connect`, `link.connected`, `link.disconnect`) | `src/link.ts` |
|
||||
| Hub protocol v2 | `protocolVersion: 2` | Register, heartbeat (stats per product), linked products, update requests, AI, licence token | `src/hub.ts` (exported as `hub`) |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.8.0",
|
||||
"version": "1.10.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",
|
||||
|
||||
@@ -5,22 +5,51 @@
|
||||
"health": {
|
||||
"uptimeSeconds": 86400,
|
||||
"db": true,
|
||||
"jobs": { "mode": "queue", "failedLast24h": 0 },
|
||||
"jobs": {
|
||||
"mode": "queue",
|
||||
"failedLast24h": 0
|
||||
},
|
||||
"lastBackupAt": "2026-11-03T00:00:12.000Z",
|
||||
"disk": { "freeBytes": 21474836480, "totalBytes": 53687091200 },
|
||||
"disk": {
|
||||
"freeBytes": 21474836480,
|
||||
"totalBytes": 53687091200
|
||||
},
|
||||
"errorsLast24h": 0,
|
||||
"pendingMigrations": 0
|
||||
},
|
||||
"stats": {
|
||||
"users": 412,
|
||||
"events": { "active": 3, "upcoming": 5, "total": 61 },
|
||||
"registrations": { "last30d": 88, "total": 2310 },
|
||||
"tickets": { "last30d": 140, "total": 3901 },
|
||||
"checkIns": { "last30d": 96 },
|
||||
"events": {
|
||||
"active": 3,
|
||||
"upcoming": 5,
|
||||
"total": 61
|
||||
},
|
||||
"registrations": {
|
||||
"last30d": 88,
|
||||
"total": 2310
|
||||
},
|
||||
"tickets": {
|
||||
"last30d": 140,
|
||||
"total": 3901
|
||||
},
|
||||
"checkIns": {
|
||||
"last30d": 96
|
||||
},
|
||||
"messages": null,
|
||||
"paymentProviders": ["yoco", "payfast"],
|
||||
"paymentProviders": [
|
||||
"yoco",
|
||||
"payfast"
|
||||
],
|
||||
"campuses": true,
|
||||
"campusCount": 2,
|
||||
"income": { "last30d": "R5 001–R20 000", "allTime": "R150 001–R250 000", "eventIncome12m": "R100 001–R150 000" }
|
||||
"income": {
|
||||
"last30d": "R5 001–R20 000",
|
||||
"allTime": "R150 001–R250 000",
|
||||
"eventIncome12m": "R100 001–R150 000"
|
||||
},
|
||||
"live": {
|
||||
"eventsNow": 1,
|
||||
"checkInsLastHour": 42
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"schema": "crosscode.identity-request/1",
|
||||
"requestId": "5a0b1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d",
|
||||
"actor": "8d2e4f6a-1b3c-4d5e-8f7a-9b0c1d2e3f4a",
|
||||
"type": "messaging.set",
|
||||
"email": {
|
||||
"settings": {
|
||||
"host": "smtp.hopefamily.co.za",
|
||||
"port": 587,
|
||||
"secure": false,
|
||||
"user": "events@hopefamily.co.za",
|
||||
"pass": "sealed1.BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||
"from": "events@hopefamily.co.za"
|
||||
},
|
||||
"to": "office@hopefamily.co.za"
|
||||
},
|
||||
"whatsapp": {
|
||||
"settings": {
|
||||
"accessToken": "sealed1.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC",
|
||||
"instanceId": "ABC123"
|
||||
},
|
||||
"to": "+27821234567"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"schema": "crosscode.identity-request/1",
|
||||
"email": {
|
||||
"ok": true,
|
||||
"error": null,
|
||||
"saved": true
|
||||
},
|
||||
"whatsapp": {
|
||||
"ok": false,
|
||||
"error": "WhatsApp couldn't send the message (401).",
|
||||
"saved": false
|
||||
},
|
||||
"status": {
|
||||
"email": {
|
||||
"ready": true,
|
||||
"host": "smtp.hopefamily.co.za",
|
||||
"from": "events@hopefamily.co.za"
|
||||
},
|
||||
"whatsapp": {
|
||||
"ready": false,
|
||||
"instanceId": null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -305,6 +305,25 @@
|
||||
"allTime",
|
||||
"eventIncome12m"
|
||||
]
|
||||
},
|
||||
"live": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"eventsNow": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"checkInsLastHour": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"eventsNow",
|
||||
"checkInsLastHour"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -93,6 +93,29 @@
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"accentColour": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^#[0-9a-fA-F]{6}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"logoUrl": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -786,6 +809,412 @@
|
||||
"sub",
|
||||
"channel"
|
||||
]
|
||||
},
|
||||
{
|
||||
"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": "messaging.status"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"requestId",
|
||||
"actor",
|
||||
"type"
|
||||
]
|
||||
},
|
||||
{
|
||||
"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": "messaging.test"
|
||||
},
|
||||
"email": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"settings": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"host": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 65535
|
||||
},
|
||||
"secure": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"user": {
|
||||
"type": "string",
|
||||
"maxLength": 254
|
||||
},
|
||||
"pass": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 4096,
|
||||
"pattern": "^sealed1\\.[A-Za-z0-9_-]{40,}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"from": {
|
||||
"type": "string",
|
||||
"minLength": 3,
|
||||
"maxLength": 320
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"host",
|
||||
"port",
|
||||
"secure",
|
||||
"user",
|
||||
"pass",
|
||||
"from"
|
||||
]
|
||||
},
|
||||
"to": {
|
||||
"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,}$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"settings",
|
||||
"to"
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"settings": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"accessToken": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 4096,
|
||||
"pattern": "^sealed1\\.[A-Za-z0-9_-]{40,}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"instanceId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"accessToken",
|
||||
"instanceId"
|
||||
]
|
||||
},
|
||||
"to": {
|
||||
"type": "string",
|
||||
"pattern": "^\\+[1-9]\\d{6,14}$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"settings",
|
||||
"to"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"requestId",
|
||||
"actor",
|
||||
"type"
|
||||
]
|
||||
},
|
||||
{
|
||||
"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": "messaging.set"
|
||||
},
|
||||
"email": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"settings": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"host": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 65535
|
||||
},
|
||||
"secure": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"user": {
|
||||
"type": "string",
|
||||
"maxLength": 254
|
||||
},
|
||||
"pass": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 4096,
|
||||
"pattern": "^sealed1\\.[A-Za-z0-9_-]{40,}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"from": {
|
||||
"type": "string",
|
||||
"minLength": 3,
|
||||
"maxLength": 320
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"host",
|
||||
"port",
|
||||
"secure",
|
||||
"user",
|
||||
"pass",
|
||||
"from"
|
||||
]
|
||||
},
|
||||
"to": {
|
||||
"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,}$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"settings",
|
||||
"to"
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"settings": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"accessToken": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 4096,
|
||||
"pattern": "^sealed1\\.[A-Za-z0-9_-]{40,}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"instanceId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"accessToken",
|
||||
"instanceId"
|
||||
]
|
||||
},
|
||||
"to": {
|
||||
"type": "string",
|
||||
"pattern": "^\\+[1-9]\\d{6,14}$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"settings",
|
||||
"to"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"requestId",
|
||||
"actor",
|
||||
"type"
|
||||
]
|
||||
},
|
||||
{
|
||||
"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": "church.branding"
|
||||
},
|
||||
"church": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"primaryColour": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^#[0-9a-fA-F]{6}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"accentColour": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^#[0-9a-fA-F]{6}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"logoUrl": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"primaryColour"
|
||||
]
|
||||
},
|
||||
"overwrite": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"requestId",
|
||||
"actor",
|
||||
"type",
|
||||
"church",
|
||||
"overwrite"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/messaging-status-reply.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.identity-request/1"
|
||||
},
|
||||
"email": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ready": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"host": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"from": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ready",
|
||||
"host",
|
||||
"from"
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ready": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"instanceId": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ready",
|
||||
"instanceId"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"email",
|
||||
"whatsapp"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/messaging-test-reply.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.identity-request/1"
|
||||
},
|
||||
"email": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ok": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"error": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 500
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"saved": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ok",
|
||||
"error",
|
||||
"saved"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ok": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"error": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 500
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"saved": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ok",
|
||||
"error",
|
||||
"saved"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"status": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ready": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"host": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"from": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ready",
|
||||
"host",
|
||||
"from"
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ready": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"instanceId": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ready",
|
||||
"instanceId"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email",
|
||||
"whatsapp"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"email",
|
||||
"whatsapp",
|
||||
"status"
|
||||
]
|
||||
}
|
||||
@@ -14,6 +14,9 @@
|
||||
},
|
||||
"created": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"emailSent": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -64,6 +64,8 @@ function contracts(c) {
|
||||
"import-batch-reply": c.importBatchReplySchema,
|
||||
"import-finish-reply": c.importFinishReplySchema,
|
||||
"people-ensure-reply": c.peopleEnsureReplySchema,
|
||||
"messaging-status-reply": c.messagingStatusReplySchema,
|
||||
"messaging-test-reply": c.messagingTestReplySchema,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -190,6 +190,12 @@ export const eventsStatsSchema = z.object({
|
||||
/** What the Events licence tier is billed on. */
|
||||
eventIncome12m: incomeBandSchema,
|
||||
}),
|
||||
/**
|
||||
* 1.10.0: what's happening now, so the Hub can warn before taking the site down (an emergency
|
||||
* update "as soon as possible"): events with a session or a one-day event on now (give or take
|
||||
* 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(),
|
||||
});
|
||||
|
||||
/** Church Website. `storage` is what the extra-storage add-on is billed on (ROADMAP-v3 §10). */
|
||||
|
||||
@@ -13,6 +13,9 @@ import { schemaName } from "./schema-name";
|
||||
* - **`import.*`**: moving a product's existing users into Accounts (Cross Events 3.0), with their
|
||||
* password hashes and authenticator secrets. Secret fields are sealed with the link's secret
|
||||
* (`sealLinkValue` in `@crosscode/contracts/signing`) on top of the request signature.
|
||||
* - **`messaging.*`** (1.9.0): whether Accounts can send email and WhatsApp (its sign-in codes and
|
||||
* links need them), and setting them up from a product: a test first, saved only if it worked.
|
||||
* The SMTP password and WAWP access token are sealed with the link's secret.
|
||||
* - **`people.*`**: what a product's admin can do to someone's account from the product (add a
|
||||
* person, change their name or email, reset 2FA, unlock, deactivate, news off from an
|
||||
* unsubscribe link). Accounts only acts on people the product knows (signed in through it or
|
||||
@@ -40,6 +43,18 @@ const base = z.object({
|
||||
|
||||
// ─── import.* ────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The church's look as a product has it, for Accounts' sign-in pages: its name, logo (an https
|
||||
* address) and colours. 1.9.0 adds the logo and accent colour (optional, so 1.8.0 senders still fit).
|
||||
*/
|
||||
export const churchLookSchema = z.object({
|
||||
name: z.string().trim().min(1).max(200).nullable(),
|
||||
primaryColour: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable(),
|
||||
accentColour: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional(),
|
||||
logoUrl: z.url({ protocol: /^https?$/ }).max(2048).nullable().optional(),
|
||||
});
|
||||
export type ChurchLook = z.infer<typeof churchLookSchema>;
|
||||
|
||||
/** A privacy notice version, numbers kept (EVENTS-3.0-PLAN decision 5). */
|
||||
export const importNoticeSchema = z.object({
|
||||
version: z.int().positive(),
|
||||
@@ -87,7 +102,7 @@ export const importBeginSchema = base.extend({
|
||||
/** The product's privacy notice versions. Taken only when Accounts has published none of its own. */
|
||||
notices: z.array(importNoticeSchema).max(100),
|
||||
/** Fills the church profile's empty fields, so the sign-in page looks like the church at once. */
|
||||
church: z.object({ name: z.string().trim().min(1).max(200).nullable(), primaryColour: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable() }),
|
||||
church: churchLookSchema,
|
||||
});
|
||||
|
||||
export const importBatchSchema = base.extend({
|
||||
@@ -140,9 +155,52 @@ export const peopleSetActiveSchema = base.extend({ type: z.literal("people.setAc
|
||||
/** Only ever turns news off (an unsubscribe link); turning it on is the person's own choice in Accounts. */
|
||||
export const peopleNewsOffSchema = base.extend({ type: z.literal("people.newsOff"), ...onePerson, channel: z.enum(["email", "whatsapp", "all"]) });
|
||||
|
||||
// ─── messaging.* (contracts 1.9.0) ───────────────────────────────────────────
|
||||
|
||||
/** SMTP settings as Cross Events and Accounts both keep them (`smtp_*`). `pass` sealed; null: keep the saved one. */
|
||||
export const smtpSettingsSchema = z.object({
|
||||
host: z.string().trim().min(1).max(253),
|
||||
port: z.int().min(1).max(65535),
|
||||
secure: z.boolean(),
|
||||
user: z.string().max(254),
|
||||
pass: sealedValueSchema.nullable(),
|
||||
from: z.string().trim().min(3).max(320),
|
||||
});
|
||||
export type SmtpSettings = z.infer<typeof smtpSettingsSchema>;
|
||||
|
||||
/** WAWP (wawp.net) settings, as both keep them. `accessToken` sealed; null: keep the saved one. */
|
||||
export const wawpSettingsSchema = z.object({
|
||||
accessToken: sealedValueSchema.nullable(),
|
||||
instanceId: z.string().trim().min(1).max(200),
|
||||
});
|
||||
export type WawpSettings = z.infer<typeof wawpSettingsSchema>;
|
||||
|
||||
/** Whether Accounts can send email and WhatsApp now (never its secrets). */
|
||||
export const messagingStatusSchema = base.extend({ type: z.literal("messaging.status") });
|
||||
|
||||
/**
|
||||
* Sends a test with the settings given (not saved): an email to `email.to`, a WhatsApp message to
|
||||
* `whatsapp.to`. Each part is tried on its own; the answer says how each went.
|
||||
*/
|
||||
export const messagingTestSchema = base.extend({
|
||||
type: z.literal("messaging.test"),
|
||||
email: z.object({ settings: smtpSettingsSchema, to: emailSchema }).optional(),
|
||||
whatsapp: z.object({ settings: wawpSettingsSchema, to: phoneSchema }).optional(),
|
||||
});
|
||||
|
||||
/** Tests the settings given as messaging.test does, and saves each part only if its test worked. */
|
||||
export const messagingSetSchema = messagingTestSchema.extend({ type: z.literal("messaging.set") });
|
||||
|
||||
/**
|
||||
* 1.9.0: use the product's look (name, logo, colours) on Accounts' pages. `overwrite: false` only
|
||||
* fills what Accounts doesn't have yet; `true` replaces it (an admin pressing the button).
|
||||
*/
|
||||
export const churchBrandingSchema = base.extend({ type: z.literal("church.branding"), church: churchLookSchema, overwrite: z.boolean() });
|
||||
|
||||
export const identityRequestSchema = z.discriminatedUnion("type", [
|
||||
importBeginSchema, importBatchSchema, importFinishSchema, importAbortSchema,
|
||||
peopleEnsureSchema, peopleUpdateSchema, peopleResetTwoFactorSchema, peopleUnlockSchema, peopleSetActiveSchema, peopleNewsOffSchema,
|
||||
messagingStatusSchema, messagingTestSchema, messagingSetSchema, churchBrandingSchema,
|
||||
]);
|
||||
export type IdentityRequest = z.infer<typeof identityRequestSchema>;
|
||||
export type IdentityRequestType = IdentityRequest["type"];
|
||||
@@ -188,10 +246,32 @@ export const peopleEnsureReplySchema = z.object({
|
||||
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
|
||||
sub: idSchema,
|
||||
created: z.boolean(),
|
||||
/** 1.9.0: whether the "choose your password" email went (false: Accounts' email isn't working). */
|
||||
emailSent: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const okReplySchema = z.object({ schema: z.literal(IDENTITY_REQUEST_SCHEMA), ok: z.literal(true) });
|
||||
|
||||
/** messaging.status: what's set up (no secrets; `from` and `host` to recognise it). */
|
||||
export const messagingStatusReplySchema = z.object({
|
||||
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
|
||||
email: z.object({ ready: z.boolean(), host: z.string().nullable(), from: z.string().nullable() }),
|
||||
whatsapp: z.object({ ready: z.boolean(), instanceId: z.string().nullable() }),
|
||||
});
|
||||
export type MessagingStatusReply = z.infer<typeof messagingStatusReplySchema>;
|
||||
|
||||
/** One part's test: sent, or why not. `saved` only on messaging.set. */
|
||||
export const messagingResultSchema = z.object({ ok: z.boolean(), error: z.string().max(500).nullable(), saved: z.boolean() });
|
||||
|
||||
/** messaging.test / messaging.set: each part that was given, and the status after. */
|
||||
export const messagingTestReplySchema = z.object({
|
||||
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
|
||||
email: messagingResultSchema.nullable(),
|
||||
whatsapp: messagingResultSchema.nullable(),
|
||||
status: messagingStatusReplySchema.omit({ schema: true }),
|
||||
});
|
||||
export type MessagingTestReply = z.infer<typeof messagingTestReplySchema>;
|
||||
|
||||
/** Errors: `{ message, code }` as the other link calls. */
|
||||
export const IDENTITY_REQUEST_ERROR_CODES = [
|
||||
"NOT_LINKED", "BAD_SIGNATURE", "STALE_REQUEST", "INVALID_REQUEST", "NOT_MOVING", "WRONG_PRODUCT", "UNKNOWN_PERSON", "EMAIL_TAKEN", "NOT_ALLOWED",
|
||||
|
||||
@@ -33,6 +33,13 @@ describe("crosscode.identity-request/1", () => {
|
||||
expect(identityRequestSchema.safeParse(many).success).toBe(false);
|
||||
});
|
||||
|
||||
test("messaging.set needs the password sealed, or null to keep the saved one", () => {
|
||||
const set = sample<{ email: { settings: Record<string, unknown> } }>("messaging-set.json");
|
||||
expect(identityRequestSchema.safeParse(set).success).toBe(true);
|
||||
expect(identityRequestSchema.safeParse({ ...set, email: { ...set.email, settings: { ...set.email.settings, pass: null } } }).success).toBe(true);
|
||||
expect(identityRequestSchema.safeParse({ ...set, email: { ...set.email, settings: { ...set.email.settings, pass: "plain-password" } } }).success).toBe(false);
|
||||
});
|
||||
|
||||
test("unknown request types are refused", () => {
|
||||
expect(identityRequestSchema.safeParse({ ...sample("people-ensure.json"), type: "people.delete" }).success).toBe(false);
|
||||
});
|
||||
|
||||
@@ -46,6 +46,8 @@ const SAMPLE_SCHEMA: Record<string, string> = {
|
||||
"import-finish.json": "identity-request",
|
||||
"people-ensure.json": "identity-request",
|
||||
"people-ensure-reply.json": "people-ensure-reply",
|
||||
"messaging-set.json": "identity-request",
|
||||
"messaging-test-reply.json": "messaging-test-reply",
|
||||
};
|
||||
|
||||
describe("JSON Schema (schemas/)", () => {
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
identityRequestSchema,
|
||||
importBatchReplySchema,
|
||||
peopleEnsureReplySchema,
|
||||
messagingTestReplySchema,
|
||||
userDeletedReplySchema,
|
||||
userExportReplySchema,
|
||||
} from "../src";
|
||||
@@ -53,6 +54,8 @@ const SCHEMAS: Record<string, z.ZodType> = {
|
||||
"import-finish.json": identityRequestSchema,
|
||||
"people-ensure.json": identityRequestSchema,
|
||||
"people-ensure-reply.json": peopleEnsureReplySchema,
|
||||
"messaging-set.json": identityRequestSchema,
|
||||
"messaging-test-reply.json": messagingTestReplySchema,
|
||||
};
|
||||
|
||||
describe("samples", () => {
|
||||
|
||||
+30
-11
@@ -9,30 +9,49 @@ const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).jo
|
||||
export type Branding = { name: string; shortName?: string | null; logoUrl?: string | null };
|
||||
|
||||
/** The page frame: the church's logo and name, then the content in a centred column. */
|
||||
/** The church's logo, or its first letter on its colour while it has none. */
|
||||
export function ChurchMark({ branding, size = "md" }: { branding: Branding; size?: "md" | "lg" }) {
|
||||
const box = size === "lg" ? "h-14 w-14 text-2xl" : "h-10 w-10 text-lg";
|
||||
if (branding.logoUrl) return <img src={branding.logoUrl} alt="" className={cx(size === "lg" ? "h-14" : "h-10", "w-auto max-w-[12rem] rounded-xl object-contain")} />;
|
||||
return <span className={cx(box, "flex shrink-0 items-center justify-center rounded-xl bg-brand font-semibold text-white")} aria-hidden>{(branding.shortName || branding.name || "?").trim().charAt(0).toUpperCase()}</span>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The page frame (as the church's other sites): a soft wash of the church's colour, its logo and
|
||||
* name across the top, the content in a centred column, and a quiet footer. `wide` for the account
|
||||
* and admin pages; otherwise a sign-in column.
|
||||
*/
|
||||
export function Shell({ branding, children, wide = false, aside }: { branding: Branding; children: React.ReactNode; wide?: boolean; aside?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<header className="bg-white border-b">
|
||||
<div className={cx("mx-auto flex items-center gap-3 px-4 py-3", wide ? "max-w-5xl" : "max-w-md")}>
|
||||
{branding.logoUrl ? <img src={branding.logoUrl} alt="" className="h-9 w-auto rounded" /> : <span className="h-9 w-9 rounded-lg bg-brand" aria-hidden />}
|
||||
<span className="font-semibold text-gray-900">{branding.name}</span>
|
||||
<div className="min-h-screen flex flex-col bg-gradient-to-br from-brand/10 via-white to-brand/5">
|
||||
<header className="border-b border-brand/10 bg-white/90 backdrop-blur">
|
||||
<div className="mx-auto flex max-w-5xl items-center gap-3 px-4 py-3">
|
||||
<ChurchMark branding={branding} />
|
||||
<span className="text-lg font-semibold text-brand-dark">{branding.name}</span>
|
||||
{aside && <div className="ml-auto">{aside}</div>}
|
||||
</div>
|
||||
</header>
|
||||
<main className={cx("mx-auto w-full flex-1 px-4 py-8", wide ? "max-w-5xl" : "max-w-md")}>{children}</main>
|
||||
<main className={cx("mx-auto w-full flex-1 px-4", wide ? "max-w-5xl py-8" : "max-w-md py-10 sm:py-16")}>{children}</main>
|
||||
<footer className="px-4 py-6 text-center text-xs text-gray-500">
|
||||
{branding.name} · your church account, for all its sites and apps
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Card({ children, className }: { children: React.ReactNode; className?: string }) {
|
||||
return <div className={cx("rounded-2xl border bg-white p-6 shadow-sm", className)}>{children}</div>;
|
||||
return <div className={cx("rounded-2xl border border-gray-200 border-t-4 border-t-brand bg-white p-6 shadow-sm sm:p-8", className)}>{children}</div>;
|
||||
}
|
||||
|
||||
export function Heading({ children, sub }: { children: React.ReactNode; sub?: React.ReactNode }) {
|
||||
/** A page's title, with an optional icon in a tile of the church's colour (as on the church's other sites). */
|
||||
export function Heading({ children, sub, icon }: { children: React.ReactNode; sub?: React.ReactNode; icon?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="mb-5">
|
||||
<h1 className="text-xl font-semibold text-gray-900">{children}</h1>
|
||||
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>}
|
||||
<div className="mb-6 flex items-start gap-3">
|
||||
{icon && <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-brand/10 text-brand" aria-hidden>{icon}</span>}
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-gray-900">{children}</h1>
|
||||
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -353,5 +353,12 @@ wait_for_version() {
|
||||
node_major() { node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0; }
|
||||
|
||||
# Files changed or added by hand in a checkout (ignored files such as .env, uploads, backups and
|
||||
# the install's ecosystem.config.js never count).
|
||||
local_changes() { git_in "$1" status --porcelain --untracked-files=all; }
|
||||
# the install's ecosystem.config.js never count). The PM2 configs this script makes for each
|
||||
# install never count either, also in checkouts of releases that don't ignore them yet (Accounts
|
||||
# 1.0–1.1 has no .gitignore for its ecosystem.config.cjs).
|
||||
CROSSCODE_OWN_FILES=(apps/events/ecosystem.config.js apps/accounts/ecosystem.config.cjs)
|
||||
local_changes() {
|
||||
git_in "$1" status --porcelain --untracked-files=all | awk -v own="${CROSSCODE_OWN_FILES[*]}" '
|
||||
BEGIN { n = split(own, f, " "); for (i = 1; i <= n; i++) skip[f[i]] = 1 }
|
||||
!(substr($0, 1, 2) == "??" && substr($0, 4) in skip)'
|
||||
}
|
||||
|
||||
@@ -146,6 +146,19 @@ cc() { bash "$CROSSCODE_HOME/crosscode" "$@"; }
|
||||
[ ! -s "$LOG" ]
|
||||
}
|
||||
|
||||
@test "the PM2 configs crosscode makes don't count as changes by hand" {
|
||||
echo "module.exports = {}" > "$CROSSCODE_SITES/hope/events/apps/events/ecosystem.config.js"
|
||||
mkdir -p "$CROSSCODE_SITES/hope/events/apps/accounts"
|
||||
echo "module.exports = {}" > "$CROSSCODE_SITES/hope/events/apps/accounts/ecosystem.config.cjs"
|
||||
run cc deploy hope events --version events@2.2.1 --check
|
||||
[ "$status" -eq 0 ]
|
||||
# Anything else added there still does.
|
||||
echo "notes" > "$CROSSCODE_SITES/hope/events/apps/accounts/notes.txt"
|
||||
run cc deploy hope events --version events@2.2.1 --check
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"apps/accounts/notes.txt"* ]]
|
||||
}
|
||||
|
||||
@test "--allow-local-changes deploys with a file added by hand" {
|
||||
echo "notes" > "$CROSSCODE_SITES/hope/events/apps/events/notes.txt"
|
||||
run cc deploy hope events --version events@2.2.1
|
||||
|
||||
Reference in New Issue
Block a user