- Events and Accounts: Background jobs are switched on or off and rescheduled from the admin; the choice is kept in the database (job_overrides), wins over the .env and applies at once. Accounts gets an Admin -> Background jobs page and per-job env flags, as Events. - Accounts: every email styled as Cross Events' (church colour, logo, button, footer), same plain text (src/lib/emails.ts). - Contracts 1.12.0: env-read / env-set agent jobs, envReadResultSchema, isSecretEnvName. - crosscode script: `crosscode env <church> <product>` reads the .env (secrets hidden) and, with --set/--unset/--restart, changes one file, rebuilds the frontend when its file changed, reloads, and puts the file back if the site doesn't answer (lib/envedit.cjs, tests/envedit.bats). - Agent 1.3.0: runs env-read and env-set. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
138 lines
7.1 KiB
TypeScript
138 lines
7.1 KiB
TypeScript
/**
|
|
* People's accounts: what the products are told about someone (`crosscode.identity/1`), consent,
|
|
* lockout, and the codes sent for 2FA and verifying an address.
|
|
*/
|
|
import crypto from 'node:crypto';
|
|
import { IDENTITY_SCHEMA, type IdentityClaims, type Profile } from '@crosscode/contracts';
|
|
import type { Request } from 'express';
|
|
import type { Ctx } from '../context.js';
|
|
import type { Account } from '../generated/prisma/client.js';
|
|
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';
|
|
import { codeEmail } from '../lib/emails.js';
|
|
|
|
export const MAX_FAILED_SIGN_INS = 10;
|
|
export const LOCK_MINUTES = 15;
|
|
export const CODE_MINUTES = 10;
|
|
|
|
export const normaliseEmail = (e: unknown) => String(e ?? '').trim().toLowerCase();
|
|
|
|
export function emailProblem(email: string): string | null {
|
|
return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) && email.length <= 254 ? null : 'Enter a valid email address.';
|
|
}
|
|
|
|
/** +27821234567 from 0821234567 and the like; null when it can't be read. */
|
|
export function normalisePhone(raw: unknown): string | null {
|
|
const s = String(raw ?? '').trim();
|
|
if (!s) return null;
|
|
let d = s.replace(/\D/g, '');
|
|
if (s.startsWith('+')) return d.length >= 8 && d.length <= 15 ? `+${d}` : null;
|
|
if (d.startsWith('0') && d.length === 10) d = `27${d.slice(1)}`;
|
|
return d.length >= 8 && d.length <= 15 ? `+${d}` : null;
|
|
}
|
|
|
|
export function profileOf(a: Account): Profile {
|
|
return {
|
|
name: a.name,
|
|
given_name: a.givenName,
|
|
family_name: a.familyName,
|
|
email: a.email,
|
|
email_verified: a.emailVerified,
|
|
phone_number: a.phone,
|
|
phone_number_verified: a.phoneVerified,
|
|
news_consent: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
|
|
};
|
|
}
|
|
|
|
/** The `crosscode.identity/1` claims (without `amr`, which comes from the sign-in itself). */
|
|
export async function identityClaims(ctx: Ctx, a: Account): Promise<Omit<IdentityClaims, 'amr'>> {
|
|
return {
|
|
schema: IDENTITY_SCHEMA,
|
|
sub: a.id,
|
|
...profileOf(a),
|
|
two_factor: a.twoFactorMethod,
|
|
privacy_notice_version: Math.max(1, a.noticeVersionAccepted || (await currentNoticeVersion(ctx))),
|
|
};
|
|
}
|
|
|
|
/** Tell every linked product the profile or consent changed (`user.updated`). */
|
|
export async function profileChanged(ctx: Ctx, accountId: string) {
|
|
const a = await ctx.db.account.findUnique({ where: { id: accountId } });
|
|
if (!a || a.status !== 'active') return;
|
|
await queueCall(ctx, 'user.updated', (callId) => ({ schema: IDENTITY_SCHEMA, type: 'user.updated', callId, occurredAt: ctx.now().toISOString(), sub: a.id, profile: profileOf(a) }));
|
|
}
|
|
|
|
/** Records news consent (POPIA proof of each change) and returns whether anything changed. */
|
|
export async function setNewsConsent(ctx: Ctx, a: Account, next: { email?: boolean; whatsapp?: boolean }, source: string): Promise<boolean> {
|
|
const changes: { channel: string; granted: boolean }[] = [];
|
|
if (next.email !== undefined && next.email !== a.newsEmail) changes.push({ channel: 'email', granted: next.email });
|
|
if (next.whatsapp !== undefined && next.whatsapp !== a.newsWhatsApp) changes.push({ channel: 'whatsapp', granted: next.whatsapp });
|
|
await ctx.db.account.update({
|
|
where: { id: a.id },
|
|
data: { ...(next.email !== undefined ? { newsEmail: next.email } : {}), ...(next.whatsapp !== undefined ? { newsWhatsApp: next.whatsapp } : {}), newsAskedAt: a.newsAskedAt ?? ctx.now() },
|
|
});
|
|
for (const c of changes) await ctx.db.consentChange.create({ data: { accountId: a.id, ...c, source, createdAt: ctx.now() } });
|
|
return changes.length > 0;
|
|
}
|
|
|
|
// ─── Lockout ──────────────────────────────────────────────────────────────────
|
|
|
|
export const isLocked = (ctx: Ctx, a: Account) => !!a.lockedUntil && a.lockedUntil > ctx.now();
|
|
|
|
export async function signInFailed(ctx: Ctx, a: Account, req?: Request) {
|
|
const failed = a.failedSignIns + 1;
|
|
const lock = failed >= MAX_FAILED_SIGN_INS;
|
|
await ctx.db.account.update({ where: { id: a.id }, data: { failedSignIns: lock ? 0 : failed, ...(lock ? { lockedUntil: new Date(ctx.now().getTime() + LOCK_MINUTES * 60e3) } : {}) } });
|
|
await loginEvent(ctx, a.id, lock ? 'locked' : 'sign_in_failed', req);
|
|
}
|
|
|
|
export async function signInSucceeded(ctx: Ctx, a: Account) {
|
|
await ctx.db.account.update({ where: { id: a.id }, data: { failedSignIns: 0, lockedUntil: null, lastSignInAt: ctx.now() } });
|
|
}
|
|
|
|
// ─── Codes by email or WhatsApp ───────────────────────────────────────────────
|
|
|
|
/** Where a code goes, partly hidden for the screen: "j***@hope.co.za", "+27 ** *** 4567". */
|
|
export function maskedTarget(a: Account, method: 'email' | 'whatsapp'): string {
|
|
if (method === 'whatsapp') return a.phone ? `${a.phone.slice(0, 3)} ** *** ${a.phone.slice(-4)}` : 'your phone';
|
|
const [user, domain] = a.email.split('@');
|
|
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' && 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);
|
|
}
|
|
}
|
|
try {
|
|
await ctx.messenger.email({ to: a.email, ...(await codeEmail(ctx, { name: a.name, code, text, purpose, minutes: CODE_MINUTES })) });
|
|
} catch (e) {
|
|
console.error('[codes] could not send a code:', (e as Error).message);
|
|
throw new SendError(`We couldn't send your code: ${churchName}'s email isn't working right now. Please let the church office know, and try again later.`, 'CODE_NOT_SENT');
|
|
}
|
|
return { codeHash: hashToken(code), sentTo: maskedTarget(a, 'email') };
|
|
}
|
|
|
|
export const codeMatches = (code: unknown, hash: string | null | undefined) =>
|
|
!!hash && safeEqual(hashToken(String(code ?? '').replace(/\D/g, '')), hash);
|
|
|
|
export const newId = () => crypto.randomUUID();
|