Accounts 1.6.0: a "New sign-in" email (and WhatsApp) after every sign-in
As Cross Events' own sign-in sends: when, the site, rough location and device, with what to do if it wasn't them. WhatsApp too for a verified number. Admins can turn it off (signin_notices). Fire-and-forget: never holds up or fails a sign-in. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* "New sign-in" notices (1.6.0), as Cross Events sends for its own sign-in: after each completed
|
||||
* sign-in, an email to the person, and a WhatsApp message too when they have a verified number and
|
||||
* WhatsApp is set up. Admins can turn them off (Sign-in settings, `signin_notices`). Never holds up
|
||||
* or fails the sign-in.
|
||||
*
|
||||
* The rough location comes from the IP (ip-api.com, as Cross Events), in production only, and never
|
||||
* for private addresses.
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
import { newSignInEmail } from '../lib/emails.js';
|
||||
import { productName } from '../oidc/clients.js';
|
||||
|
||||
const PRIVATE_IP = /^(::1$|127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|fc|fd|fe80|::ffff:(127|10|192\.168)\.)/i;
|
||||
|
||||
/** "Chrome on Windows" from a user agent; the raw string when it can't tell. */
|
||||
export function describeDevice(ua: string | null | undefined): string {
|
||||
const s = String(ua || '');
|
||||
if (!s) return 'Unknown device';
|
||||
const browser = /Edg\//.test(s) ? 'Edge' : /OPR\/|Opera/.test(s) ? 'Opera' : /Firefox\//.test(s) ? 'Firefox'
|
||||
: /SamsungBrowser\//.test(s) ? 'Samsung Internet' : /Chrome\//.test(s) ? 'Chrome' : /Safari\//.test(s) ? 'Safari' : null;
|
||||
const os = /iPhone|iPad|iPod/.test(s) ? 'iPhone or iPad' : /Android/.test(s) ? 'Android' : /Windows/.test(s) ? 'Windows'
|
||||
: /Mac OS X|Macintosh/.test(s) ? 'a Mac' : /CrOS/.test(s) ? 'a Chromebook' : /Linux/.test(s) ? 'Linux' : null;
|
||||
if (browser && os) return `${browser} on ${os}`;
|
||||
return browser || os || s.slice(0, 120);
|
||||
}
|
||||
|
||||
async function roughLocation(ctx: Ctx, ip: string | null): Promise<string> {
|
||||
if (!ip || PRIVATE_IP.test(ip) || !ctx.config.production) return 'Unknown';
|
||||
try {
|
||||
const res = await fetch(`http://ip-api.com/json/${encodeURIComponent(ip.replace(/^::ffff:/, ''))}?fields=status,city,regionName,country`, { signal: AbortSignal.timeout(3000) });
|
||||
const geo = (await res.json()) as { status?: string; city?: string; regionName?: string; country?: string };
|
||||
const parts = geo.status === 'success' ? [geo.city, geo.regionName, geo.country].filter(Boolean) : [];
|
||||
return parts.length ? parts.join(', ') : 'Unknown';
|
||||
} catch {
|
||||
return 'Unknown';
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendSignInNotice(ctx: Ctx, o: { accountId: string; ip: string | null; userAgent: string | null; clientId: string | null }): Promise<'sent' | 'off' | 'failed'> {
|
||||
try {
|
||||
if (!(await ctx.settings.bool('signin_notices', true))) return 'off';
|
||||
const a = await ctx.db.account.findUnique({ where: { id: o.accountId } });
|
||||
if (!a || a.status !== 'active') return 'off';
|
||||
const link = o.clientId ? await ctx.db.productLink.findUnique({ where: { installId: o.clientId } }) : null;
|
||||
const site = link ? productName(link.product) : o.clientId === 'accounts-self' ? 'Your account page' : null;
|
||||
const when = ctx.now().toLocaleString('en-ZA', { timeZone: ctx.config.timezone, dateStyle: 'medium', timeStyle: 'short' });
|
||||
const msg = await newSignInEmail(ctx, { name: a.name, when, location: await roughLocation(ctx, o.ip), device: describeDevice(o.userAgent), site });
|
||||
await ctx.messenger.email({ to: a.email, subject: msg.subject, text: msg.text, html: msg.html });
|
||||
if (a.phone && a.phoneVerified && (await ctx.messenger.whatsappReady())) {
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text: msg.whatsapp }).catch((e: Error) => console.warn('[sign-in notice] WhatsApp:', e.message));
|
||||
}
|
||||
return 'sent';
|
||||
} catch (e) {
|
||||
console.warn('[sign-in notice] not sent:', (e as Error).message);
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@ import type Provider from 'oidc-provider';
|
||||
import { decodeState, encodeState, safeReturnPath } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError, handle, limit } from '../http.js';
|
||||
import { loginEvent } from '../lib/audit.js';
|
||||
import { clientIp, loginEvent } from '../lib/audit.js';
|
||||
import { sendSignInNotice } from '../accounts/signInNotice.js';
|
||||
import { resetPasswordEmail } from '../lib/emails.js';
|
||||
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||
import { hashPassword, passwordProblem } from '../lib/passwords.js';
|
||||
@@ -44,6 +45,8 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
|
||||
const clientId = String(details.params.client_id ?? '') || null;
|
||||
await loginEvent(ctx, pending.accountId, 'sign_in', req, { clientId, detail: { amr: pending.amr } });
|
||||
await signedInThrough(ctx, clientId, pending.accountId);
|
||||
// 1.6.0: "New sign-in" email (and WhatsApp), as Cross Events; never waited for.
|
||||
if (pending.accountId) void sendSignInNotice(ctx, { accountId: pending.accountId, ip: clientIp(req), userAgent: req.get('user-agent') ?? null, clientId });
|
||||
await ctx.db.pendingSignIn.deleteMany({ where: { uid: pending.uid } });
|
||||
return { stage: 'done', redirectTo, ...extra };
|
||||
}
|
||||
|
||||
@@ -206,3 +206,20 @@ export async function testEmail(ctx: Ctx, o: { from?: string } = {}): Promise<Bu
|
||||
: 'Email from Accounts works.';
|
||||
return { subject: o.from ? `Test email from ${b.name}'s sign-in` : 'Test email from Accounts', text, html: layout(b, body, 'A test email: email works.') };
|
||||
}
|
||||
|
||||
/** A sign-in happened (1.6.0, as Cross Events' "New login detected"). `whatsapp`: the same in a few lines. */
|
||||
export async function newSignInEmail(ctx: Ctx, o: { name?: string | null; when: string; location: string; device: string; site: string | null }): Promise<Built & { whatsapp: string }> {
|
||||
const b = await brand(ctx);
|
||||
const row = (k: string, v: string) => `<tr><td style="padding:10px 14px;border-top:1px solid #f1f5f9;color:#64748b;font-size:13px;font-weight:600;width:34%">${esc(k)}</td><td style="padding:10px 14px;border-top:1px solid #f1f5f9;color:#1e293b;font-size:14px;word-break:break-word">${esc(v)}</td></tr>`;
|
||||
const body = title('New sign-in', `Someone signed in to your ${b.name} account`)
|
||||
+ hello(o.name)
|
||||
+ `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;margin:0 0 8px 0">`
|
||||
+ row('When', o.when) + (o.site ? row('Signed in to', o.site) : '') + row('Where (roughly)', o.location) + row('Device', o.device)
|
||||
+ '</table>'
|
||||
+ callout(`<strong>Not you?</strong> Change your password straight away from your account page, and let the church office know${contactLine(b)}.`, 'warning')
|
||||
+ small('If this was you, there\'s nothing to do.');
|
||||
const lines = [`When: ${o.when}`, ...(o.site ? [`Signed in to: ${o.site}`] : []), `Where (roughly): ${o.location}`, `Device: ${o.device}`];
|
||||
const text = `Hello ${o.name || 'there'},\n\nSomeone signed in to your ${b.name} account.\n\n${lines.join('\n')}\n\nIf this wasn't you, change your password straight away and let the church office know${b.email ? ` (${b.email})` : ''}.\nIf it was you, there's nothing to do.`;
|
||||
const whatsapp = `🔐 *New sign-in*\n\nHello ${o.name || 'there'}, someone signed in to your *${b.name}* account.\n\n${lines.join('\n')}\n\nNot you? Change your password straight away and let the church office know.`;
|
||||
return { subject: `New sign-in to your ${b.name} account`, text, html: layout(b, body, `New sign-in: ${o.when}, ${o.device}.`), whatsapp };
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_i
|
||||
|
||||
/** The settings an admin may read and change through the generic settings API. */
|
||||
export const ADMIN_SETTINGS = new Set([
|
||||
'signup_enabled', 'two_factor_required_for_admins', 'session_days',
|
||||
'signup_enabled', 'two_factor_required_for_admins', 'session_days', 'signin_notices',
|
||||
'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure',
|
||||
'wawp_access_token', 'wawp_instance_id',
|
||||
]);
|
||||
|
||||
Reference in New Issue
Block a user