diff --git a/apps/api/scripts/migrate.ts b/apps/api/scripts/migrate.ts index ec85bf8..4d830d0 100644 --- a/apps/api/scripts/migrate.ts +++ b/apps/api/scripts/migrate.ts @@ -3,7 +3,7 @@ // Also brings each site's public look up to date and adds starter public pages (landing copy, footer // pages, guides) that a site doesn't have yet. It never touches members, and never overwrites a page an // admin edited or brings back one an admin deleted. -import { addStarterPages, seedSites, upgradeSiteFields, upgradeSiteTheme, type Site } from '@whatbox/core'; +import { addPolicyNotices, addStarterPages, seedSites, upgradeSiteFields, upgradeSiteTheme, type Site } from '@whatbox/core'; import { Client } from 'pg'; import { config, dbUrl } from '../src/config'; import { closePools, pool } from '../src/db-pool'; @@ -29,6 +29,8 @@ import { applySql, ensureDb } from '../src/provision'; if (upgradeSiteTheme(doc)) console.log(`updated look for ${doc.slug}`); const wrote = await addStarterPages(doc, new PgSiteRepo(pool(siteDbName(doc.slug))), new Date()); if (wrote.length) console.log(`${doc.slug}: added pages ${wrote.join(', ')}`); + const notices = await addPolicyNotices(doc, new PgSiteRepo(pool(siteDbName(doc.slug))), new Date()); + if (notices.length) console.log(`${doc.slug}: added the message-review paragraph to ${notices.join(', ')}`); if (JSON.stringify(doc) !== before) await c.query('UPDATE sites SET doc=$2, updated_at=now() WHERE id=$1', [doc.id, doc]); } await c.end(); diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index b881280..68c2c07 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -6,7 +6,7 @@ import { import { FileInterceptor } from '@nestjs/platform-express'; import { normalizeImage } from './photos'; import { safeReturnUrl } from './payments'; -import { type ActivityKind, type ClientPlatform, type ContentPage, type ModerationDecision, type PhotoKind, type PhotoRating, type Platform, type ProfileFieldDef, RuleError, type SearchFilters, type SiteEvent, type Tier } from '@whatbox/core'; +import { type ActivityKind, type ClientPlatform, type ContentPage, type ModerationDecision, type PhotoKind, type SuspendReason, type PhotoRating, type Platform, type ProfileFieldDef, RuleError, type SearchFilters, type SiteEvent, type Tier } from '@whatbox/core'; import type { Request, Response } from 'express'; export const PLATFORM = 'PLATFORM'; @@ -147,8 +147,9 @@ export class MembersController extends SiteScoped { @Delete(':id/like') async unlike(@Req() r: Request, @Param('id') id: string) { return this.p.like(await this.ctx(r), id, false); } @Post(':id/block') async block(@Req() r: Request, @Param('id') id: string) { return this.p.block(await this.ctx(r), id, true); } @Delete(':id/block') async unblock(@Req() r: Request, @Param('id') id: string) { return this.p.block(await this.ctx(r), id, false); } - @Post(':id/report') async report(@Req() r: Request, @Param('id') id: string, @Body() b: { reason?: string }) { - return this.p.report(await this.ctx(r), id, String(b.reason ?? '')); + @Post(':id/report') async report(@Req() r: Request, @Param('id') id: string, @Body() b: { reason?: string; messageId?: string; photoId?: string }) { + const about = { ...(typeof b.messageId === 'string' ? { messageId: b.messageId } : {}), ...(typeof b.photoId === 'string' ? { photoId: b.photoId } : {}) }; + return this.p.report(await this.ctx(r), id, String(b.reason ?? ''), about); } @Post(':id/private-access') async request(@Req() r: Request, @Param('id') id: string) { return { status: await this.p.requestAccess(await this.ctx(r), id) }; } } @@ -232,8 +233,15 @@ export class AdminController { @Get('sites/:site/members/:id') async memberProfile(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string) { return this.p.adminMemberProfile(await this.admin(a), s, id); } - @Patch('sites/:site/members/:id') async memberStatus(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string, @Body() b: { status: 'active' | 'suspended' }) { - return this.p.adminSetMemberStatus(await this.admin(a), s, id, b.status); + @Patch('sites/:site/members/:id') async memberStatus(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string, @Body() b: { status: 'active' | 'suspended'; reason?: SuspendReason; notifyContacts?: boolean }) { + const reason = b.reason === 'scam' || b.reason === 'safety' || b.reason === 'other' ? b.reason : undefined; + return this.p.adminSetMemberStatus(await this.admin(a), s, id, b.status, { reason, notifyContacts: b.notifyContacts === true }); + } + @Get('sites/:site/members/:id/conversations') async memberConversations(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string) { + return this.p.adminMemberConversations(await this.admin(a), s, id); + } + @Get('sites/:site/members/:id/conversations/:other') async memberConversation(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string, @Param('other') o: string) { + return this.p.adminMemberConversation(await this.admin(a), s, id, o); } @Patch('sites/:site/members/:id/tier') async memberTier(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string, @Body() b: { tier: Tier }) { return this.p.adminSetMemberTier(await this.admin(a), s, id, b.tier); diff --git a/apps/api/src/notify.ts b/apps/api/src/notify.ts index 00e0667..24ae755 100644 --- a/apps/api/src/notify.ts +++ b/apps/api/src/notify.ts @@ -3,7 +3,7 @@ // arriving on a shared phone or inbox gives nothing away (sensitive sites especially). import { EmailClient } from '@azure/communication-email'; import { SmsClient } from '@azure/communication-sms'; -import type { Notifier, Site } from '@whatbox/core'; +import { type Notifier, safetyNoticeContent, type Site } from '@whatbox/core'; import { config } from './config'; export function codeText(site: Site, code: string) { @@ -15,6 +15,9 @@ export const consoleNotifier: Notifier = { const masked = channel === 'email' ? target.replace(/^(.).*@/, '$1•••@') : '•••' + target.slice(-2); console.log(`[notify] ${site.slug} ${channel} ${masked} code=${config.exposeDevCodes ? code : '(hidden)'}`); }, + async sendSafetyNotice({ site, email, displayName }) { + console.log(`[notify] ${site.slug} safety notice to ${email.replace(/^(.).*@/, '$1•••@')} about "${displayName}"`); + }, async sendAdminCode({ email, code }) { console.log(`[notify] admin ${email.replace(/^(.).*@/, '$1•••@')} code=${config.exposeDevCodes ? code : '(hidden)'}`); }, @@ -67,6 +70,17 @@ export class AcsNotifier implements Notifier { }); } + async sendSafetyNotice({ site, email, displayName }: { site: Site; email: string; displayName: string }) { + const from = this.siteSender(site); + if (!from) throw new Error(`No email sender configured for ${site.id}`); + const c = safetyNoticeContent(site, displayName); + await this.sendEmail(`${site.slug} safety notice ${mask(email)}`, from, { + senderAddress: from, + recipients: { to: [{ address: email }] }, + content: { subject: c.subject, plainText: c.text, html: c.html }, + }); + } + private siteSender(site: Site) { if (this.emailFrom[site.id]) return this.emailFrom[site.id]; for (const d of site.domains ?? []) { diff --git a/apps/api/src/pg-repo.ts b/apps/api/src/pg-repo.ts index 58ee8fb..a69d895 100644 --- a/apps/api/src/pg-repo.ts +++ b/apps/api/src/pg-repo.ts @@ -322,6 +322,10 @@ export class PgSiteRepo implements SiteRepo { async saveReport(r: Report) { await this.db.query('INSERT INTO reports VALUES ($1,$2,$3,$4,$5)', [r.id, r.reporterId, r.targetId, r.reason, r.at]); } + async listReportsAbout(t: string) { + const r = await this.db.query('SELECT id, reporter_id, target_id, reason, at FROM reports WHERE target_id=$1 ORDER BY at DESC LIMIT 100', [t]); + return r.rows.map((x: any) => ({ id: x.id, reporterId: x.reporter_id, targetId: x.target_id, reason: x.reason, at: new Date(x.at).toISOString() })); + } async countReports(t: string) { return Number((await this.db.query('SELECT count(*) FROM reports WHERE target_id=$1', [t])).rows[0].count); } async saveModeration(i: ModerationItem) { await this.db.query( diff --git a/apps/member/src/app/(app)/member/[id].tsx b/apps/member/src/app/(app)/member/[id].tsx index 29585c5..a34beaf 100644 --- a/apps/member/src/app/(app)/member/[id].tsx +++ b/apps/member/src/app/(app)/member/[id].tsx @@ -15,6 +15,7 @@ export default function ProfileScreen() { const [error, setError] = useState(null); const [big, setBig] = useState(); const [safety, setSafety] = useState(false); + const [reportPhoto, setReportPhoto] = useState(null); const [reason, setReason] = useState(''); const [note, setNote] = useState(null); @@ -62,6 +63,12 @@ export default function ProfileScreen() { {big?.id === p.mainPhoto?.id ? : null} + {!preview && big && !big.placeholder ? ( + { setReportPhoto(big); setReason(''); setSafety(true); }} style={{ flexDirection: 'row', alignItems: 'center', gap: 6, alignSelf: 'flex-end', minHeight: 36 }}> + + Report this photo + + ) : null} {all.length > 1 ? ( <> @@ -135,7 +142,7 @@ export default function ProfileScreen() { style={{ width: 50, height: 50, borderRadius: 25, borderWidth: 1.5, borderColor: p.favoritedByMe ? '#D9A43A' : t.line, backgroundColor: p.favoritedByMe ? '#FFF4DC' : t.surface, alignItems: 'center', justifyContent: 'center' }}> - setSafety(!safety)} style={{ width: 50, height: 50, borderRadius: 25, borderWidth: 1.5, borderColor: t.line, backgroundColor: t.surface, alignItems: 'center', justifyContent: 'center' }}> + { setReportPhoto(null); setSafety(!safety); }} style={{ width: 50, height: 50, borderRadius: 25, borderWidth: 1.5, borderColor: t.line, backgroundColor: t.surface, alignItems: 'center', justifyContent: 'center' }}> @@ -146,16 +153,22 @@ export default function ProfileScreen() { {safety ? ( - Safety - Reports are private. {p.displayName} won't know who reported them. + {reportPhoto ? 'Report this photo' : 'Safety'} + {reportPhoto ? ( + + + Our safety team will see this photo with your report. {p.displayName} won't know who reported it. + + ) : Reports are private. {p.displayName} won't know who reported them.} - {['Asked for money', 'Pushing to another app', 'Fake profile', 'Rude or abusive', 'Underage'].map((r) => ( + {(reportPhoto ? ['Not them', 'Stolen or fake photo', 'Explicit', 'Shows someone else', 'Underage'] : ['Asked for money', 'Pushing to another app', 'Fake profile', 'Rude or abusive', 'Underage']).map((r) => ( setReason(r)} /> ))} - act(() => api.report(p.id, reason), 'Thanks. The safety team will review this.').then(() => setSafety(false))} /> + act(() => api.report(p.id, reason, reportPhoto ? { photoId: reportPhoto.id } : undefined), 'Thanks. The safety team will review this.').then(() => { setSafety(false); setReportPhoto(null); })} /> + {reportPhoto ? { setSafety(false); setReportPhoto(null); }} /> : null} act(() => api.block(p.id, !p.blockedByMe), p.blockedByMe ? 'Unblocked.' : `${p.displayName} can no longer see you or message you.`)} /> diff --git a/apps/member/src/app/(app)/messages/[id].tsx b/apps/member/src/app/(app)/messages/[id].tsx index cbda087..fcca868 100644 --- a/apps/member/src/app/(app)/messages/[id].tsx +++ b/apps/member/src/app/(app)/messages/[id].tsx @@ -14,6 +14,9 @@ export default function Conversation() { const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [menu, setMenu] = useState(false); + const [reporting, setReporting] = useState(null); + const [reportReason, setReportReason] = useState(''); + const [reported, setReported] = useState>(new Set()); const scroll = useRef(null); const load = useCallback(async () => { @@ -73,7 +76,34 @@ export default function Conversation() { {m.sealed ? '🔒 ' : ''}{m.body} {m.notice ? {m.notice} : null} - {m.fromMe && m.readAt ? `Read ${clockTime(m.readAt)}` : clockTime(m.at)} + + {m.fromMe && m.readAt ? `Read ${clockTime(m.readAt)}` : clockTime(m.at)} + {!m.fromMe && !m.sealed ? ( + reported.has(m.id) ? Reported : ( + { setReporting(reporting === m.id ? null : m.id); setReportReason(''); }} hitSlop={8}> + Report + + ) + ) : null} + + {reporting === m.id ? ( + + Report this message + Our safety team will see it with your report. {other.displayName} won't know who reported it. + + {['Asked for money', 'Pushing to another app', 'Rude or abusive', 'Spam', 'Seems fake'].map((r) => ( + setReportReason(r)} /> + ))} + + + { + try { await api.report(other.id, reportReason, { messageId: m.id }); setReported(new Set([...reported, m.id])); setReporting(null); } + catch (e) { setError(e instanceof ApiError ? e.message : 'Could not send the report.'); } + }} /> + setReporting(null)} /> + + + ) : null} ))} {meetingTalk ? ( diff --git a/apps/member/src/app/admin/index.tsx b/apps/member/src/app/admin/index.tsx index 97e1c08..c76b9c8 100644 --- a/apps/member/src/app/admin/index.tsx +++ b/apps/member/src/app/admin/index.tsx @@ -3,6 +3,7 @@ import { ApiError, type AdminApi, type AdminEventRow, type AdminMemberProfile, type AdminMemberRow, type ContactMatch, findContactInfo, isoToZoned, zonedToIso, type AdminSiteSummary, type ContentPage, type ModerationDecision, type ModerationView, type PhotoView, + type AdminConversationRow, type AdminMessageRow, type SuspendReason, type ProfileFieldDef, type RiskFlag, type Site, type SiteStats, type SiteTheme, TIERS, type Tier, type TierPerms, canSortBrowse, } from '@whatbox/core'; import { router } from 'expo-router'; @@ -258,6 +259,7 @@ function Moderation({ api, siteId, niche, onChange }: { api: AdminApi; siteId: s const [items, setItems] = useState(null); const [big, setBig] = useState(null); const [recheck, setRecheck] = useState<{ busy: boolean; note?: string }>({ busy: false }); + const [suspendFor, setSuspendFor] = useState(null); const [nicheRun, setNicheRun] = useState<{ busy: boolean; note?: string }>({ busy: false }); const [openId, setOpenId] = useState(null); const load = useCallback(() => { setItems(null); api.moderation(siteId, status).then(setItems); }, [api, siteId, status]); @@ -354,11 +356,16 @@ function Moderation({ api, siteId, niche, onChange }: { api: AdminApi; siteId: s {i.signals.map((sig) => {sig})} ) : null} - {i.status === 'pending' ? ( + {i.status === 'pending' && suspendFor === i.id ? ( + setSuspendFor(null)} + onDone={async (msg) => { setSuspendFor(null); setRecheck({ busy: false, note: msg }); await decide(i.id, 'approve'); }} /> + ) : i.status === 'pending' ? ( - decide(i.id, 'approve')} /> + (i.kind === 'report' ? setSuspendFor(i.id) : decide(i.id, 'approve'))} /> + {i.kind === 'report' && i.photoId ? decide(i.id, 'remove_photo')} /> : null} decide(i.id, 'reject')} /> - {i.kind === 'member' ? setOpenId(i.memberId)} /> : null} + setOpenId(i.memberId)} /> ) : i.kind === 'member' ? setOpenId(i.memberId)} /> : null} @@ -368,7 +375,7 @@ function Moderation({ api, siteId, niche, onChange }: { api: AdminApi; siteId: s ))} setBig(null)} /> - setOpenId(null)} /> + setOpenId(null)} onChanged={load} /> ); } @@ -513,6 +520,7 @@ function Members({ api, siteId }: { api: AdminApi; siteId: string }) { const [page, setPage] = useState(1); const [data, setData] = useState<{ total: number; rows: AdminMemberRow[] } | null>(null); const [openId, setOpenId] = useState(null); + const [suspendFirst, setSuspendFirst] = useState(false); const load = useCallback(() => api.members(siteId, { search, page }).then(setData), [api, siteId, search, page]); useEffect(() => { load(); }, [load]); return ( @@ -535,8 +543,8 @@ function Members({ api, siteId }: { api: AdminApi; siteId: string }) { value={m.tier} onChange={async (tier) => { await api.setMemberTier(siteId, m.id, tier); load(); }} options={TIERS.map((x) => ({ value: x, label: x === 'free' ? 'Free' : x === 'paid' ? 'Paid' : 'VIP' }))} /> - { await api.setMemberStatus(siteId, m.id, m.status === 'active' ? 'suspended' : 'active'); load(); }} /> + { if (m.status === 'active') { setSuspendFirst(true); setOpenId(m.id); } else { await api.setMemberStatus(siteId, m.id, 'active'); load(); } }} /> ))} @@ -549,23 +557,32 @@ function Members({ api, siteId }: { api: AdminApi; siteId: string }) { ) : null} Contact details are encrypted with this site's own key and are not shown here. Click a name to see the full profile. - setOpenId(null)} /> + { setOpenId(null); setSuspendFirst(false); }} /> ); } /** The member's profile as other members see it, plus every photo with its review status. Viewing records nothing. */ -function MemberProfilePanel({ api, siteId, memberId, onClose }: { api: AdminApi; siteId: string; memberId: string | null; onClose: () => void }) { +function MemberProfilePanel({ api, siteId, memberId, onClose, startSuspend, onChanged }: { + api: AdminApi; siteId: string; memberId: string | null; onClose: () => void; startSuspend?: boolean; onChanged?: () => void; +}) { const t = useTheme(); const wide = useWide(); const [data, setData] = useState(null); const [error, setError] = useState(null); const [big, setBig] = useState(null); - useEffect(() => { - setData(null); setError(null); + const [suspending, setSuspending] = useState(false); + const [done, setDone] = useState(null); + const [showMessages, setShowMessages] = useState(false); + const reload = useCallback(() => { if (!memberId) return; api.memberProfile(siteId, memberId).then(setData, (e) => setError(e instanceof ApiError ? e.message : 'Could not load the profile.')); }, [api, siteId, memberId]); + useEffect(() => { + setData(null); setError(null); setDone(null); setShowMessages(false); setSuspending(!!startSuspend); + reload(); + }, [reload, startSuspend]); const p = data?.profile; const photoStatus = (ph: PhotoView) => `${ph.kind}${ph.rating === 'explicit' ? ' · explicit' : ''}${ph.status !== 'approved' ? ` · ${ph.status}` : ''}`; return ( @@ -598,8 +615,42 @@ function MemberProfilePanel({ api, siteId, memberId, onClose }: { api: AdminApi; Joined {relTime(data.createdAt)} · active {relTime(data.lastActiveAt)} + {done ? {done} : null} + {suspending ? ( + setSuspending(false)} + onDone={(msg) => { setSuspending(false); setDone(msg); reload(); onChanged?.(); }} /> + ) : ( + + {data.status === 'active' + ? setSuspending(true)} /> + : { await api.setMemberStatus(siteId, data.profile.id, 'active'); setDone(`${p.displayName} is active again.`); reload(); onChanged?.(); }} />} + setShowMessages(!showMessages)} /> + + )} + {showMessages ? : null} + + Reports from members ({data.reports.count}) + {data.reports.count === 0 ? Nobody has reported {p.displayName}. : data.reports.recent.map((r, idx) => ( + + {r.reason} + {r.about ? `About a ${r.about} · ` : ''}by {r.reporterName} · {relTime(r.at)} + + ))} + {data.safetyNoticeAt ? A safety notice went to their contacts {relTime(data.safetyNoticeAt)}. : null} + {p.cautions.length ? p.cautions.map((c) => {c}) : null} {data.flags.length ? : null} + {data.nicheFlags.length ? ( + + Account review flags + {data.nicheFlags.map((f) => ( + + {f.signals.join(' · ')} + + ))} + + ) : null} {data.network?.countries.length ? ( Signs in from: {data.network.countries.map((c) => `${c.name} (${c.count === 1 ? 'once' : `${c.count} times`}, last ${relTime(c.lastAt)})`).join(', ')} @@ -610,10 +661,12 @@ function MemberProfilePanel({ api, siteId, memberId, onClose }: { api: AdminApi; About me {p.about ? : Empty.} - {p.details.length ? ( + {data.answers.length ? ( - Details - {p.details.map((d) => {d.label}: {d.value})} + Profile answers + {data.answers.map((d) => ( + {d.label}: {d.value}{d.hidden ? (not shown on profile) : null} + ))} ) : null} {p.interests.length ? ( @@ -644,6 +697,102 @@ function MemberProfilePanel({ api, siteId, memberId, onClose }: { api: AdminApi; ); } +const SUSPEND_REASONS: { value: SuspendReason; label: string }[] = [ + { value: 'scam', label: 'Scam or fraud' }, + { value: 'safety', label: 'Other safety concern' }, + { value: 'other', label: 'Other rule' }, +]; + +/** Suspend with a reason and, optionally, a safety notice to everyone who exchanged messages with the member. */ +function SuspendForm({ api, siteId, memberId, name, alreadyNotified, onDone, onCancel }: { + api: AdminApi; siteId: string; memberId: string; name: string; alreadyNotified?: boolean; onDone: (msg: string) => void; onCancel: () => void; +}) { + const t = useTheme(); + const [reason, setReason] = useState('scam'); + const [notify, setNotify] = useState(!alreadyNotified); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const pick = (r: SuspendReason) => { setReason(r); if (!alreadyNotified) setNotify(r === 'scam'); }; + const go = async () => { + setBusy(true); setError(null); + try { + const r = await api.setMemberStatus(siteId, memberId, 'suspended', { reason, notifyContacts: notify && !alreadyNotified }); + onDone(notify && !alreadyNotified + ? `${name} is suspended. A safety notice went to ${r.notified} member${r.notified === 1 ? '' : 's'} they messaged${r.noEmail ? ` (${r.noEmail} had no email address on file)` : ''}.` + : `${name} is suspended.`); + } catch (e) { setError(e instanceof ApiError ? e.message : 'Could not suspend.'); setBusy(false); } + }; + return ( + + Suspend {name} + They can't sign in or be seen while suspended. You can reinstate them later. + value={reason} onChange={pick} options={SUSPEND_REASONS} /> + {alreadyNotified + ? Their contacts were already sent a safety notice, so it won't be sent again. + : } + + + + + + + ); +} + +/** Read-only view of a member's conversations for a safety review. Opening the list or a conversation is logged. */ +function MessageReview({ api, siteId, memberId, name }: { api: AdminApi; siteId: string; memberId: string; name: string }) { + const t = useTheme(); + const [rows, setRows] = useState(null); + const [open, setOpen] = useState(null); + const [msgs, setMsgs] = useState(null); + const [error, setError] = useState(null); + useEffect(() => { api.memberConversations(siteId, memberId).then(setRows, (e) => setError(e instanceof ApiError ? e.message : 'Could not load messages.')); }, [api, siteId, memberId]); + useEffect(() => { + setMsgs(null); + if (open) api.memberConversation(siteId, memberId, open.otherId).then(setMsgs, (e) => setError(e instanceof ApiError ? e.message : 'Could not load the conversation.')); + }, [api, siteId, memberId, open]); + return ( + + {open ? `${name} and ${open.otherName}` : `${name}'s messages`} + Read-only, for safety reviews. Nothing is marked as read, and each conversation you open is recorded in the audit log. + + {open ? ( + <> + setOpen(null)} accessibilityRole="button">← All conversations + {!msgs ? : msgs.map((m) => { + const mine = m.fromId === memberId; + const contact = findContactInfo(m.body); + return ( + + + {mine ? name : open.otherName} · {new Date(m.at).toLocaleString()} + + + {m.held || m.flags.length ? ( + + {m.held ? : null} + {m.flags.map((f) => )} + + ) : null} + + ); + })} + + ) : !rows ? : rows.length === 0 ? No messages. : rows.map((r) => ( + setOpen(r)} accessibilityRole="button" style={{ flexDirection: 'row', alignItems: 'center', gap: 10, paddingVertical: 6, borderTopWidth: 1, borderColor: t.line }}> + + {r.otherName} + {r.sent} sent · {r.received} received · last {relTime(r.lastAt)} + + {r.flagged ? : null} + {r.held ? : null} + + ))} + + ); +} + const EMPTY_FIELD: ProfileFieldDef = { key: '', label: '', type: 'select', options: [], filterable: true, showOnProfile: true, section: 'details', order: 99 }; function Fields({ api, site, onSite }: { api: AdminApi; site: Site; onSite: (s: Site) => void }) { diff --git a/packages/core/src/api.ts b/packages/core/src/api.ts index 9be7404..19d82da 100644 --- a/packages/core/src/api.ts +++ b/packages/core/src/api.ts @@ -4,7 +4,7 @@ import { RuleError } from './rules'; import type { AccessRow, Platform, ProfilePatch } from './services'; import type { - ActivityKind, ActivityList, AdminMemberProfile, AdminMemberRow, ClientPlatform, MemberEvent, DiscoverCard, ContentPage, ConversationSummary, ConversationView, MemberProfile, + ActivityKind, ActivityList, AdminConversationRow, AdminMemberProfile, AdminMemberRow, AdminMessageRow, SuspendReason, SuspendResult, ClientPlatform, MemberEvent, DiscoverCard, ContentPage, ConversationSummary, ConversationView, MemberProfile, MemberStatus, ModerationDecision, ModerationView, MyProfile, PhotoKind, PhotoRating, ProfileFieldDef, PublicSite, SearchFilters, SearchResult, Site, EventView, RsvpStatus, SiteEvent, GeoCountry, GeoPlace, SiteMode, SiteStats, Tier, AdminUser, AuditEntry, NewSiteInput, PlatformOverview, SiteDashboard, NetworkDashboard, } from './types'; @@ -54,7 +54,8 @@ export interface MemberApi { pass(id: string): Promise<{ ok: boolean }>; discover(): Promise; block(id: string, on: boolean): Promise<{ blocked: boolean }>; - report(id: string, reason: string): Promise<{ ok: boolean }>; + /** Report a member, or one message they sent you, or one of their photos. */ + report(id: string, reason: string, about?: { messageId?: string; photoId?: string }): Promise<{ ok: boolean }>; activity(kind: ActivityKind): Promise; // Live updates while the app is open. Returns an unsubscribe function. subscribe(onEvent: (ev: MemberEvent) => void): () => void; @@ -91,7 +92,10 @@ export interface AdminApi { runNicheChecks(siteId: string): Promise<{ checked: number; flagged: number; items: ModerationView[] }>; members(siteId: string, opts: { search?: string; page?: number }): Promise<{ total: number; page: number; rows: AdminMemberRow[] }>; memberProfile(siteId: string, memberId: string): Promise; - setMemberStatus(siteId: string, memberId: string, status: MemberStatus): Promise<{ ok: boolean }>; + setMemberStatus(siteId: string, memberId: string, status: MemberStatus, opts?: { reason?: SuspendReason; notifyContacts?: boolean }): Promise; + /** Read-only safety review of a member's messages. Every call is written to the audit log. */ + memberConversations(siteId: string, memberId: string): Promise; + memberConversation(siteId: string, memberId: string, otherId: string): Promise; setMemberTier(siteId: string, memberId: string, tier: Tier): Promise<{ ok: boolean }>; pages(siteId: string): Promise; savePage(siteId: string, page: ContentPage): Promise; @@ -158,7 +162,7 @@ export function createLocalMemberApi(platform: Platform, siteKey: string, client pass: (id) => wrap(async () => platform.pass(await ctx(), id)), discover: () => wrap(async () => platform.discover(await ctx())), block: (id, on) => wrap(async () => platform.block(await ctx(), id, on)), - report: (id, r) => wrap(async () => platform.report(await ctx(), id, r)), + report: (id, r, about) => wrap(async () => platform.report(await ctx(), id, r, about)), activity: (k) => wrap(async () => platform.activity(await ctx(), k)), favorite: (id, on) => wrap(async () => platform.favorite(await ctx(), id, on)), subscribe: (onEvent) => { @@ -205,7 +209,9 @@ export function createLocalAdminApi(platform: Platform): AdminApi { runNicheChecks: (s) => wrap(async () => platform.adminRunNicheChecks(await admin(), s)), members: (s, o) => wrap(async () => platform.adminMembers(await admin(), s, o)), memberProfile: (s, m) => wrap(async () => platform.adminMemberProfile(await admin(), s, m)), - setMemberStatus: (s, m, st) => wrap(async () => platform.adminSetMemberStatus(await admin(), s, m, st)), + setMemberStatus: (s, m, st, o) => wrap(async () => platform.adminSetMemberStatus(await admin(), s, m, st, o)), + memberConversations: (s, m) => wrap(async () => platform.adminMemberConversations(await admin(), s, m)), + memberConversation: (s, m, o) => wrap(async () => platform.adminMemberConversation(await admin(), s, m, o)), setMemberTier: (s, m, t) => wrap(async () => platform.adminSetMemberTier(await admin(), s, m, t)), audit: (siteId) => wrap(async () => platform.adminAudit(await admin(), siteId)), platform: (month) => wrap(async () => platform.platformOverview(await admin(), month)), diff --git a/packages/core/src/http-client.ts b/packages/core/src/http-client.ts index ca5278e..4bbacba 100644 --- a/packages/core/src/http-client.ts +++ b/packages/core/src/http-client.ts @@ -115,7 +115,7 @@ export function createHttpMemberApi(baseUrl: string, siteKey: string, platform: pass: (id) => req('POST', `/v1/members/${id}/pass`, {}), discover: () => req('GET', '/v1/discover'), block: (id, on) => req(on ? 'POST' : 'DELETE', `/v1/members/${id}/block`), - report: (id, reason) => req('POST', `/v1/members/${id}/report`, { reason }), + report: (id, reason, about) => req('POST', `/v1/members/${id}/report`, { reason, ...about }), activity: (kind) => req('GET', '/v1/activity/' + kind), subscribe: (onEvent) => { if (typeof XMLHttpRequest === 'undefined' || !token) return () => {}; @@ -157,7 +157,9 @@ export function createHttpAdminApi(baseUrl: string): AdminApi { runNicheChecks: (id) => req('POST', s(id) + '/niche-checks', {}), members: (id, o) => req('GET', s(id) + '/members?search=' + encodeURIComponent(o.search ?? '') + '&page=' + (o.page ?? 1)), memberProfile: (id, m) => req('GET', s(id) + '/members/' + encodeURIComponent(m)), - setMemberStatus: (id, m, status) => req('PATCH', s(id) + '/members/' + m, { status }), + setMemberStatus: (id, m, status, o) => req('PATCH', s(id) + '/members/' + m, { status, ...o }), + memberConversations: (id, m) => req('GET', s(id) + '/members/' + encodeURIComponent(m) + '/conversations'), + memberConversation: (id, m, o) => req('GET', s(id) + '/members/' + encodeURIComponent(m) + '/conversations/' + encodeURIComponent(o)), setMemberTier: (id, m, tier) => req('PATCH', s(id) + '/members/' + m + '/tier', { tier }), audit: (siteId) => req('GET', '/v1/admin/audit' + (siteId ? '?site=' + encodeURIComponent(siteId) : '')), platform: (month) => req('GET', '/v1/admin/platform' + (month ? '?month=' + encodeURIComponent(month) : '')), diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index dfc9911..02101c6 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -17,4 +17,5 @@ export * from './zoned-time'; export * from './analytics'; export * from './demo-analytics'; export * from './update-check'; +export * from './safety-notice'; export * from './network-risk'; diff --git a/packages/core/src/memory-platform.ts b/packages/core/src/memory-platform.ts index 0eccad5..6e3c6ae 100644 --- a/packages/core/src/memory-platform.ts +++ b/packages/core/src/memory-platform.ts @@ -16,6 +16,7 @@ export interface MemoryPlatform { sites: Map; snapshot(): MemoryPlatformSnapshot; sentCodes: { site: string; channel: string; target: string; code: string }[]; + sentNotices: { site: string; email: string; displayName: string }[]; } export async function createMemoryPlatform(opts: { @@ -34,6 +35,7 @@ export async function createMemoryPlatform(opts: { const keys = new DevKeyProvider(opts.masterKey ?? 'preview-master-key'); const now = opts.clock?.now() ?? new Date(); const sentCodes: MemoryPlatform['sentCodes'] = []; + const sentNotices: MemoryPlatform['sentNotices'] = []; let control: MemoryControlRepo; const sites = new Map(); @@ -58,6 +60,7 @@ export async function createMemoryPlatform(opts: { const notifier: Notifier = { async sendCode({ site, channel, target, code }) { sentCodes.push({ site: site.slug, channel, target, code }); }, + async sendSafetyNotice({ site, email, displayName }) { sentNotices.push({ site: site.slug, email, displayName }); }, }; const platform = new Platform({ @@ -72,7 +75,7 @@ export async function createMemoryPlatform(opts: { }); return { - platform, control, sites, sentCodes, + platform, control, sites, sentCodes, sentNotices, snapshot: () => ({ v: 1, control: control.snapshot(), sites: Object.fromEntries([...sites.entries()].map(([k, v]) => [k, v.snapshot()])), diff --git a/packages/core/src/memory-repo.ts b/packages/core/src/memory-repo.ts index 0aed3c7..c0364cb 100644 --- a/packages/core/src/memory-repo.ts +++ b/packages/core/src/memory-repo.ts @@ -265,6 +265,7 @@ export class MemorySiteRepo implements SiteRepo { } async saveReport(r: Report) { this.d.reports.push(clone(r)); } + async listReportsAbout(t: string) { return clone(this.d.reports.filter((r) => r.targetId === t).sort((a, b) => b.at.localeCompare(a.at)).slice(0, 100)); } async countReports(t: string) { return this.d.reports.filter((r) => r.targetId === t).length; } async saveModeration(i: ModerationItem) { this.upsert(this.d.moderation, i, (x) => x.id === i.id); } async getModeration(id: string) { return clone(this.d.moderation.find((m) => m.id === id) ?? null); } diff --git a/packages/core/src/repo.ts b/packages/core/src/repo.ts index 3682f49..39dd44c 100644 --- a/packages/core/src/repo.ts +++ b/packages/core/src/repo.ts @@ -100,6 +100,7 @@ export interface SiteRepo { // safety saveReport(r: Report): Promise; countReports(targetId: string): Promise; + listReportsAbout(targetId: string): Promise; saveModeration(item: ModerationItem): Promise; getModeration(id: string): Promise; listModeration(status: ReviewStatus | 'all'): Promise; @@ -161,6 +162,8 @@ export interface Notifier { // Sends a verification code. Dev/preview implementations just record it. sendCode(args: { site: Site; channel: 'email' | 'phone'; target: string; code: string }): Promise; sendAdminCode?(args: { email: string; code: string }): Promise; + /** Tells a member that someone they messaged was removed for breaking the safety guidelines. Sent regardless of email preferences. */ + sendSafetyNotice?(args: { site: Site; email: string; displayName: string }): Promise; } // Photo files. Each site has its own container, so a key from one site can never be read on another. diff --git a/packages/core/src/safety-notice.ts b/packages/core/src/safety-notice.ts new file mode 100644 index 0000000..ff3ca05 --- /dev/null +++ b/packages/core/src/safety-notice.ts @@ -0,0 +1,46 @@ +// The safety notice sent to a member's contacts when an admin suspends that member. +// Wording is factual and neutral ("removed for violating our safety guidelines"): it never says +// why, never accuses, and names only the display name the contact already knows. +// On sensitive sites (AfterH) the subject and opening lines say nothing about the site, so the +// inbox preview on a shared screen gives nothing away. +import type { Site } from './types'; + +export interface SafetyNoticeContent { subject: string; text: string; html: string } + +const TIPS = [ + 'Never send money, gift cards, crypto or bank details to someone you have not met in person.', + 'Be careful if they contact you on another app, by phone or by email. You do not have to reply.', + 'Do not share your home address, workplace or financial information.', + 'If they get in touch again, on the site or anywhere else, block them and tell us.', +]; + +export function safetyNoticeContent(site: Site, displayName: string): SafetyNoticeContent { + const discreet = site.settings.mode === 'sensitive'; + const subject = discreet ? 'A safety notice for your account' : `A safety notice from ${site.name}`; + const opening = discreet + ? 'For your safety, we are letting you know that a member you exchanged messages with has been removed.' + : `For your safety, we are letting you know that a member you exchanged messages with on ${site.name} has been removed.`; + const paras = [ + opening, + `The member's display name was "${displayName}". Their account was removed for violating our safety guidelines.`, + 'We recommend being very careful about any further contact with this person.', + ]; + const report = discreet + ? 'If anything about your conversations worried you, sign in and use Report on any profile or message, and our safety team will review it.' + : `If anything about your conversations worried you, use Report on any profile or message on ${site.name}, and our safety team will review it.`; + const footer = 'This is a safety notice about your account, so it is sent even if you have turned off other emails.'; + const text = [...paras, 'Safety tips:', ...TIPS.map((t) => `- ${t}`), report, footer].join('\n\n'); + const p = (s: string, extra = '') => `

${esc(s)}

`; + const html = [ + ...paras.map((s) => p(s)), + p('Safety tips:', ';font-weight:700'), + `
    ${TIPS.map((t) => `
  • ${esc(t)}
  • `).join('')}
`, + p(report), + `

${esc(footer)}

`, + ].join('\n'); + return { subject, text, html }; +} + +function esc(s: string) { + return s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!); +} diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts index 9fa6480..b73195a 100644 --- a/packages/core/src/services.ts +++ b/packages/core/src/services.ts @@ -16,7 +16,7 @@ import { ONLINE_WINDOW_MS, PHOTO_LIMITS, effectivePerms, tierFor, photoVisibleTo, RuleError, scoreCandidate, screenMessage, } from './rules'; import type { - AccessStatus, ActivityKind, ActivityList, ActivityPerson, AdminMemberProfile, AdminMemberRow, DiscoverCard, Units, Tier, TierPerms, MembershipSettings, Message, MemberEvent, Subscription, + AccessStatus, ActivityKind, ActivityList, ActivityPerson, AdminConversationRow, AdminMemberProfile, AdminMemberRow, AdminMessageRow, SuspendReason, SuspendResult, DiscoverCard, Units, Tier, TierPerms, MembershipSettings, Message, MemberEvent, Subscription, NewSiteInput, SiteMode, PlatformOverview, PlatformSiteRow, SiteLicensing, SiteStatus, UsageKind, AdminUser, ClientPlatform, ContentPage, ConversationSummary, ConversationView, Gender, GeoPlace, GeoProvider, LocationInput, Member, MemberCard, MemberProfile, MemberStatus, ModerationDecision, ModerationItem, ModerationView, MyProfile, Photo, PhotoKind, PhotoRating, PhotoView, ProfileFieldDef, PublicSite, SearchFilters, SearchResult, Site, @@ -1047,16 +1047,30 @@ export class Platform { return { blocked: on }; } - async report(ctx: MemberCtx, id: string, reason: string) { + /** Report a member, or one message they sent me, or one of their photos. Lands in the moderation queue. */ + async report(ctx: MemberCtx, id: string, reason: string, about?: { messageId?: string; photoId?: string }) { const target = await ctx.repo.getMember(id); - if (!target) throw new RuleError('not_found', 'Member not found.', 404); - const r = { id: randomId('rp_'), reporterId: ctx.me.id, targetId: id, reason: reason.slice(0, 500), at: this.iso() }; + if (!target || target.id === ctx.me.id) throw new RuleError('not_found', 'Member not found.', 404); + let what = ''; + if (about?.messageId) { + const msg = await ctx.repo.getMessage(about.messageId); + // only the person a message was sent to can report it + if (!msg || msg.fromId !== id || msg.toId !== ctx.me.id) throw new RuleError('not_found', 'Message not found.', 404); + what = 'reported a message'; + } else if (about?.photoId) { + const ph = await ctx.repo.getPhoto(about.photoId); + if (!ph || ph.memberId !== id) throw new RuleError('not_found', 'Photo not found.', 404); + what = `reported a ${ph.kind} photo`; + } + const r = { id: randomId('rp_'), reporterId: ctx.me.id, targetId: id, reason: ((what ? `[${what}] ` : '') + reason.trim()).slice(0, 500), at: this.iso() }; await ctx.repo.saveReport(r); const count = await ctx.repo.countReports(id); await ctx.repo.saveModeration({ id: randomId('mod_'), kind: 'report', refId: r.id, memberId: id, - summary: reason.slice(0, 280) || 'No reason given', - reasons: [`reported by ${ctx.me.displayName}`, `${count} report${count === 1 ? '' : 's'} total`], + summary: reason.trim().slice(0, 280) || 'No reason given', + reasons: [`reported by ${ctx.me.displayName}`, ...(what ? [what] : []), `${count} report${count === 1 ? '' : 's'} total`], + ...(about?.messageId ? { messageId: about.messageId } : {}), + ...(about?.photoId ? { photoId: about.photoId } : {}), status: 'pending', createdAt: this.iso(), }); this.changed(); @@ -1468,6 +1482,11 @@ export class Platform { if (p) v.photo = { id: p.id, kind: p.kind, rating: p.rating, status: p.status, url: this.fileUrl(site, p), tone: p.tone }; } if (i.kind === 'message') v.messageBody = (await repo.getMessage(i.refId))?.body; + if (i.kind === 'report' && i.messageId) v.messageBody = (await repo.getMessage(i.messageId))?.body; + if (i.kind === 'report' && i.photoId) { + const p = await repo.getPhoto(i.photoId); + if (p) v.photo = { id: p.id, kind: p.kind, rating: p.rating, status: p.status, url: this.fileUrl(site, p), tone: p.tone }; + } if (i.kind === 'profile') { const about = members.get(i.memberId)?.about ?? ''; v.profileText = about; @@ -1485,6 +1504,17 @@ export class Platform { const item = await repo.getModeration(itemId); if (!item) throw new RuleError('not_found', 'Item not found.', 404); if (decision === 'redact' || decision === 'edit') return this.adminFixProfileText(admin, site, repo, item, decision, text); + if (decision === 'remove_photo') { + const photoId = item.kind === 'photo' ? item.refId : item.photoId; + const p = photoId ? await repo.getPhoto(photoId) : null; + if (!p) throw new RuleError('not_found', 'Photo not found.', 404); + await repo.savePhoto({ ...p, status: 'rejected' }); + if (p.status !== 'rejected') { try { this.deps.events?.emit(site, p.memberId, { type: 'photo', photoId: p.id, status: 'rejected' }); } catch { /* best effort */ } } + await repo.saveModeration({ ...item, status: 'approved', decidedAt: this.iso(), decidedBy: admin.email }); + await this.audit(admin, 'moderation.remove_photo', site.id, item.memberId, item.kind); + this.changed(); + return this.adminModeration(admin, siteId, 'pending'); + } if (decision !== 'approve' && decision !== 'reject') throw new RuleError('bad_decision', 'Unknown decision.'); const status = decision === 'approve' ? 'approved' : 'rejected'; if (item.kind === 'photo') { @@ -1598,10 +1628,57 @@ export class Platform { const ctx: MemberCtx = { site, repo, me: m, platform: 'web' }; const profile = await this.buildProfile(ctx, m, true); const photos = (await repo.listPhotos(m.id)).map((p) => this.photoView(ctx, p, { owner: true })); + const reports = await repo.listReportsAbout(m.id); + const reporters = new Map((await repo.getMembers([...new Set(reports.map((r) => r.reporterId))])).map((x) => [x.id, x.displayName])); + const recent = reports.slice(0, 20).map((r) => { + const about = r.reason.startsWith('[reported a message]') ? 'message' as const : r.reason.startsWith('[reported a') ? 'photo' as const : undefined; + return { reason: r.reason.replace(/^\[reported an? [^\]]*\]\s*/, '') || 'No reason given', at: r.at, reporterName: reporters.get(r.reporterId) || 'A former member', ...(about ? { about } : {}) }; + }); const network = m.network ? { countries: m.network.countries.map((c) => ({ ...c, name: countryName(c.code) })), hosting: m.network.hosting, torAt: m.network.torAt, } : undefined; - return { profile, photos, status: m.status, profileComplete: m.profileComplete, createdAt: m.createdAt, lastActiveAt: m.lastActiveAt, imported: !!m.imported, flags: riskFlags(m), network, country: m.country }; + return { + profile, photos, status: m.status, profileComplete: m.profileComplete, createdAt: m.createdAt, lastActiveAt: m.lastActiveAt, imported: !!m.imported, + flags: riskFlags(m), network, country: m.country, + nicheFlags: memberFlags(site, m), + answers: [...site.fields].sort((x, y) => x.order - y.order) + .filter((def) => m.fields[def.key] !== undefined && m.fields[def.key] !== '') + .map((def) => ({ key: def.key, label: def.label, value: this.fieldText(ctx, def, m.fields[def.key]), hidden: def.showOnProfile === false })), + reports: { count: await repo.countReports(m.id), recent }, + ...(m.safetyNoticeAt ? { safetyNoticeAt: m.safetyNoticeAt } : {}), + }; + } + + /** A member's conversations, for a safety review. Read-only: nothing is marked read. Every look is in the audit log. */ + async adminMemberConversations(admin: AdminUser, siteId: string, memberId: string): Promise { + const site = await this.adminSite(admin, siteId); + const repo = await this.repo(site); + const m = await repo.getMember(memberId); + if (!m) throw new RuleError('not_found', 'Member not found.', 404); + const msgs = await repo.listMessagesInvolving(m.id); + const rows = new Map(); + for (const x of msgs) { + const otherId = x.fromId === m.id ? x.toId : x.fromId; + const r = rows.get(otherId) ?? { otherId, otherName: '', sent: 0, received: 0, held: 0, flagged: 0, lastAt: x.at }; + if (x.fromId === m.id) r.sent++; else r.received++; + if (x.held) r.held++; + if (x.flags.length) r.flagged++; + if (x.at > r.lastAt) r.lastAt = x.at; + rows.set(otherId, r); + } + const names = new Map((await repo.getMembers([...rows.keys()])).map((x) => [x.id, x.displayName])); + await this.audit(admin, 'member.messages.list', site.id, m.id, `${rows.size} conversations`); + return [...rows.values()].map((r) => ({ ...r, otherName: names.get(r.otherId) || 'A former member' })).sort((a, b) => b.lastAt.localeCompare(a.lastAt)); + } + + async adminMemberConversation(admin: AdminUser, siteId: string, memberId: string, otherId: string): Promise { + const site = await this.adminSite(admin, siteId); + const repo = await this.repo(site); + const m = await repo.getMember(memberId); + if (!m) throw new RuleError('not_found', 'Member not found.', 404); + const msgs = await repo.listMessagesBetween(m.id, otherId); + await this.audit(admin, 'member.messages.view', site.id, m.id, `with ${otherId}, ${msgs.length} messages`); + return msgs.map((x) => ({ id: x.id, fromId: x.fromId, body: x.body, at: x.at, flags: x.flags, held: x.held, ...(x.readAt ? { readAt: x.readAt } : {}) })); } async adminMembers(admin: AdminUser, siteId: string, opts: { search?: string; page?: number }) { @@ -1621,15 +1698,35 @@ export class Platform { return { total, page, rows: out }; } - async adminSetMemberStatus(admin: AdminUser, siteId: string, memberId: string, status: MemberStatus) { + /** + * Suspend or reinstate. When suspending, the admin can send a safety notice to everyone who exchanged + * delivered messages with the member. It is sent once per member and names only their display name. + */ + async adminSetMemberStatus(admin: AdminUser, siteId: string, memberId: string, status: MemberStatus, opts: { reason?: SuspendReason; notifyContacts?: boolean } = {}): Promise { const site = await this.adminSite(admin, siteId); const repo = await this.repo(site); const m = await repo.getMember(memberId); if (!m) throw new RuleError('not_found', 'Member not found.', 404); - await repo.saveMember({ ...m, status }); - await this.audit(admin, 'member.status', site.id, memberId, status); + let notified = 0; + let noEmail = 0; + let saved: Member = { ...m, status }; + if (status === 'suspended' && opts.notifyContacts && !m.safetyNoticeAt) { + const msgs = (await repo.listMessagesInvolving(m.id)).filter((x) => !x.held); + const ids = [...new Set(msgs.map((x) => (x.fromId === m.id ? x.toId : x.fromId)))]; + const crypto = this.crypto(site); + for (const c of await repo.getMembers(ids)) { + if (c.status !== 'active' || !c.emailEnc || !this.deps.notifier.sendSafetyNotice) { noEmail++; continue; } + try { + await this.deps.notifier.sendSafetyNotice({ site, email: await crypto.decrypt(c.emailEnc), displayName: m.displayName }); + notified++; + } catch (e) { noEmail++; console.error('[safety-notice] send failed', (e as Error).message); } + } + saved = { ...saved, safetyNoticeAt: this.iso() }; + } + await repo.saveMember(saved); + await this.audit(admin, 'member.status', site.id, memberId, [status, opts.reason, opts.notifyContacts ? `notice sent to ${notified}, ${noEmail} without email` : ''].filter(Boolean).join(', ')); this.changed(); - return { ok: true }; + return { ok: true, notified, noEmail }; } // ---------------- Audit log ---------------- diff --git a/packages/core/src/starter-content.ts b/packages/core/src/starter-content.ts index a38d814..af9dbb2 100644 --- a/packages/core/src/starter-content.ts +++ b/packages/core/src/starter-content.ts @@ -67,6 +67,19 @@ const safetyTips = (n: string, extra: string[] = []): Draft => ({ ].join('\n\n'), }); +/** Policy paragraphs added to new and existing Privacy/Terms pages. The key is recorded in site.policyNotices. */ +export const POLICY_NOTICES: { key: string; slug: 'privacy' | 'terms'; marker: string; text: string }[] = [ + { + key: 'message-review-2026-11', slug: 'privacy', marker: 'Safety reviews.', + text: 'Safety reviews. To keep members safe, our moderators may read messages, view photos and review accounts when something is reported or looks suspicious, including messages that were not themselves reported. Only staff for this site can do this, and every review is logged.', + }, + { + key: 'message-review-2026-11', slug: 'terms', marker: 'Moderators may review', + text: 'Moderators may review messages, photos and profiles to keep the community safe, including when an account is reported or looks suspicious. If we remove an account for violating our safety guidelines, we may let members who exchanged messages with it know, by display name, so they can take care.', + }, +]; +const notice = (slug: 'privacy' | 'terms') => POLICY_NOTICES.filter((x) => x.slug === slug).map((x) => x.text); + const privacy = (n: string, descriptor: string, extra: string): Draft => ({ slug: 'privacy', kind: 'page', title: 'Privacy policy', placement: 'footer', summary: 'How we handle your information, in plain language.', @@ -78,6 +91,7 @@ const privacy = (n: string, descriptor: string, extra: string): Draft => ({ 'How we protect it. Each WhatBox site keeps its members in its own database with its own encryption key, so your information is never mixed with another site\'s. Your email address and phone number are encrypted and are never shown to other members.', extra, 'How we use it. To run your account, show your profile to signed-in members, deliver messages, keep the community safe from scams and abuse, and, if you upgrade, process your payment. Payment details go straight to the payment provider. We never see or store your card number.', + ...notice('privacy'), `What we never do. We do not sell your information. Upgrades appear on your statement as "${descriptor}".`, 'Your choices. You can edit or hide your profile, remove photos, revoke private photo access, and delete your account at any time from your settings.', 'Questions. Contact us through the help link in the app.', @@ -95,6 +109,7 @@ const terms = (n: string): Draft => ({ 'Be respectful. No harassment, hate, threats, or treating anyone as a fetish. No asking members for money. No advertising or recruiting for other services.', 'Only post photos you have the right to share, of yourself. Private photos are shared only with members you approve.', 'We may pause messages for review, remove content, or close accounts that break these rules or put members at risk.', + ...notice('terms'), 'Joining is free. If you buy an upgrade, it renews until you cancel, and you can cancel any time from your settings.', 'The service is provided as is. We work hard to keep scammers out, but please follow our safety tips and use good judgment when meeting anyone.', ].join('\n\n'), @@ -432,6 +447,32 @@ export function starterPages(site: Site, now: Date): ContentPage[] { return drafts.map((d) => page(d, at)); } +/** + * Adds each policy paragraph once to an existing Privacy/Terms page (e.g. pages created before the paragraph + * existed, or edited by an admin). Additive only: it never changes other text, and once a key is recorded in + * site.policyNotices it is never added again, so an admin who removes or rewords it keeps their version. + */ +export async function addPolicyNotices( + site: Site, repo: { listPages(): Promise; savePage(p: ContentPage): Promise }, now: Date, +): Promise { + const done = new Set(site.policyNotices ?? []); + const pages = new Map((await repo.listPages()).map((p) => [p.slug, p])); + const wrote: string[] = []; + const keys = new Set(POLICY_NOTICES.map((x) => x.key)); + for (const key of keys) { + if (done.has(key)) continue; + for (const n of POLICY_NOTICES.filter((x) => x.key === key)) { + const p = pages.get(n.slug); + if (!p || p.body.includes(n.marker)) continue; + await repo.savePage({ ...p, body: `${p.body.trimEnd()}\n\n${n.text}`, updatedAt: now.toISOString() }); + wrote.push(n.slug); + } + done.add(key); + } + site.policyNotices = [...done].sort(); + return wrote; +} + /** * Adds the starter pages a site doesn't have yet. Safe to run on every deploy: * - a page an admin edited is never touched (an unedited old placeholder page is replaced) diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 15450ff..cf58a35 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -151,6 +151,7 @@ export interface Site { status?: SiteStatus; // missing means active licensing?: SiteLicensing; starterPages?: string[]; // starter page slugs already added once (so an admin's deletion sticks) + policyNotices?: string[]; // policy paragraphs already added to existing Privacy/Terms pages once (see addPolicyNotices) } export type SiteStatus = 'active' | 'suspended'; @@ -246,6 +247,8 @@ export interface Member { risk?: { openItemId?: string; clearedKey?: string }; createdAt: string; lastActiveAt: string; + /** When contacts were last sent a safety notice about this member (sent once). */ + safetyNoticeAt?: string; } export type PhotoKind = 'main' | 'public' | 'private'; @@ -312,6 +315,9 @@ export interface ModerationItem { memberId: string; // member the item is about summary: string; reasons: string[]; + /** report items: the message or photo the member reported, when they reported one. */ + messageId?: string; + photoId?: string; status: ReviewStatus; createdAt: string; decidedAt?: string; @@ -685,6 +691,14 @@ export interface AdminMemberProfile { createdAt: string; lastActiveAt: string; imported: boolean; + /** Niche review flags (answers that don't add up, fetish or "third" wording). Empty on non-niche sites. */ + nicheFlags: { code: string; reason: string; signals: string[] }[]; + /** Every profile answer, including ones not shown on the profile (hidden: true), e.g. type of dwarfism or disability categories. */ + answers: { key: string; label: string; value: string; hidden: boolean }[]; + /** Reports other members made about this person, newest first. */ + reports: { count: number; recent: { reason: string; at: string; reporterName: string; about?: 'message' | 'photo' }[] }; + /** Set once their contacts were sent a safety notice. */ + safetyNoticeAt?: string; flags: RiskFlag[]; /** Where they sign in from, by country and network type (derived; the IP is never kept). */ network?: { countries: { code: string; name: string; count: number; lastAt: string }[]; hosting?: { org: string; lastAt: string }; torAt?: string }; @@ -705,7 +719,20 @@ export interface ModerationView extends ModerationItem { } /** approve/reject as before; redact removes only the contact details; edit saves the admin's corrected text. */ -export type ModerationDecision = 'approve' | 'reject' | 'redact' | 'edit'; +export type ModerationDecision = 'approve' | 'reject' | 'redact' | 'edit' | 'remove_photo'; + +/** Why an admin suspended someone. Scam and safety suggest telling their contacts. */ +export type SuspendReason = 'scam' | 'safety' | 'other'; + +export interface SuspendResult { ok: boolean; notified: number; noEmail: number } + +/** One conversation of a member, for the admin message review (read-only). */ +export interface AdminConversationRow { + otherId: string; otherName: string; sent: number; received: number; held: number; flagged: number; lastAt: string; +} +export interface AdminMessageRow { + id: string; fromId: string; body: string; at: string; flags: MessageFlag[]; held: boolean; readAt?: string; +} // ---------- Places (worldwide) ---------- export interface GeoPlace { id: string; name: string; region: string; country: string; lat: number; lng: number; postal?: string } diff --git a/packages/core/test/platform.test.ts b/packages/core/test/platform.test.ts index a458e21..5259ccd 100644 --- a/packages/core/test/platform.test.ts +++ b/packages/core/test/platform.test.ts @@ -693,6 +693,95 @@ test('admin can open a member profile with every photo', async () => { const v = await admin.memberProfile('site_afterh', me.member.id); assert.equal(v.profile.id, me.member.id); assert.ok(v.photos.some((p) => p.kind === 'private' && !p.placeholder), 'admin sees private photos unlocked'); + assert.ok(v.answers.some((x) => x.key === 'hsv_status'), 'admin sees every answer'); + assert.deepEqual(v.nicheFlags, [], 'AfterH is not a niche-check site'); +}); + +test('members report a message or a photo; admin sees it in the queue and the profile', async () => { + const { mp, api } = await signIn(); + const convs = await api.conversations(); + const priya = convs.find((c) => c.other.displayName === 'Priya')!.other; + const theirs = (await api.conversation(priya.id)).messages.find((m) => !m.fromMe)!; + await api.report(priya.id, 'Asked for money', { messageId: theirs.id }); + const mine = (await api.conversation(priya.id)).messages.find((m) => m.fromMe); + if (mine) await assert.rejects(api.report(priya.id, 'x', { messageId: mine.id }), /not found/i); + const prof = await api.profile(priya.id); + await api.report(priya.id, 'Stolen or fake photo', { photoId: prof.mainPhoto!.id }); + + const admin = await ownerAdmin(mp); + const queue = await admin.moderation('site_afterh', 'pending'); + const msgItem = queue.find((q) => q.kind === 'report' && q.messageId === theirs.id)!; + assert.equal(msgItem.messageBody, (await api.conversation(priya.id)).messages.find((m) => m.id === theirs.id)!.body); + assert.ok(msgItem.reasons.includes('reported a message')); + const photoItem = queue.find((q) => q.kind === 'report' && q.photoId === prof.mainPhoto!.id)!; + assert.equal(photoItem.photo?.id, prof.mainPhoto!.id); + await admin.decide('site_afterh', photoItem.id, 'remove_photo'); + const view = await admin.memberProfile('site_afterh', priya.id); + assert.equal(view.photos.find((p) => p.id === prof.mainPhoto!.id)!.status, 'rejected'); + assert.equal(view.reports.count, 2); + assert.ok(view.reports.recent.some((r) => r.about === 'message' && r.reason === 'Asked for money')); +}); + +test('admin reviews a member\'s messages read-only, and every look is audited', async () => { + const { mp, api } = await signIn(); + const me = await api.me(); + const priya = (await api.conversations()).find((c) => c.other.displayName === 'Priya')!.other; + const admin = await ownerAdmin(mp); + const rows = await admin.memberConversations('site_afterh', priya.id); + const withAlex = rows.find((r) => r.otherId === me.member.id)!; + assert.ok(withAlex.sent + withAlex.received > 0); + const msgs = await admin.memberConversation('site_afterh', priya.id, me.member.id); + assert.equal(msgs.length, withAlex.sent + withAlex.received); + const unread = msgs.filter((m) => m.fromId === priya.id && !m.readAt).length; + assert.equal((await admin.memberConversation('site_afterh', priya.id, me.member.id)).filter((m) => m.fromId === priya.id && !m.readAt).length, unread, 'nothing marked read'); + const log = await admin.audit('site_afterh'); + assert.ok(log.some((e) => e.action === 'member.messages.list' && e.target === priya.id)); + assert.ok(log.some((e) => e.action === 'member.messages.view' && e.target === priya.id && e.detail?.includes(me.member.id))); + // another site's owner can't read them + const outsider = await adminSignIn(mp, 'nobody@example.com').catch(() => null); + if (outsider) await assert.rejects(outsider.memberConversations('site_afterh', priya.id)); +}); + +test('suspending with a notice emails each contact once, with neutral wording', async () => { + const { mp, api } = await signIn(); + const me = await api.me(); + const priya = (await api.conversations()).find((c) => c.other.displayName === 'Priya')!.other; + const admin = await ownerAdmin(mp); + const r = await admin.setMemberStatus('site_afterh', priya.id, 'suspended', { reason: 'scam', notifyContacts: true }); + assert.ok(r.notified >= 1); + const toAlex = mp.sentNotices.filter((n) => n.displayName === 'Priya'); + assert.ok(toAlex.some((n) => n.email === DEMO_MEMBER_EMAIL)); + await admin.setMemberStatus('site_afterh', priya.id, 'active'); + const again = await admin.setMemberStatus('site_afterh', priya.id, 'suspended', { reason: 'scam', notifyContacts: true }); + assert.equal(again.notified, 0, 'sent once per member'); + assert.ok((await admin.memberProfile('site_afterh', priya.id)).safetyNoticeAt); + + const { safetyNoticeContent, seedSites } = await import('../src/index'); + const [afterh] = seedSites(new Date()); + const c = safetyNoticeContent(afterh, 'Priya'); + assert.equal(afterh.settings.mode, 'sensitive'); + assert.ok(!c.subject.includes(afterh.name), 'discreet subject on sensitive sites'); + assert.ok(!c.text.split('\n\n')[0].includes(afterh.name), 'discreet opening line'); + assert.match(c.text, /violating our safety guidelines/); + assert.match(c.text, /Never send money/); + assert.doesNotMatch(c.text, /scam|fraud|criminal/i); + void me; +}); + +test('policy paragraph is added once to existing Privacy and Terms pages', async () => { + const { addPolicyNotices, seedSites } = await import('../src/index'); + const site = seedSites(new Date())[0]; + const pages = new Map([ + ['privacy', { slug: 'privacy', body: 'Old privacy text', updatedAt: '' }], + ['terms', { slug: 'terms', body: 'Old terms text', updatedAt: '' }], + ]); + const repo = { listPages: async () => [...pages.values()], savePage: async (p: any) => { pages.set(p.slug, p); } }; + assert.deepEqual((await addPolicyNotices(site, repo, new Date())).sort(), ['privacy', 'terms']); + assert.match(pages.get('privacy').body, /^Old privacy text\n\nSafety reviews\./); + assert.match(pages.get('terms').body, /Moderators may review/); + pages.set('privacy', { ...pages.get('privacy'), body: 'Admin rewrote it' }); + assert.deepEqual(await addPolicyNotices(site, repo, new Date()), [], 'never re-added'); + assert.equal(pages.get('privacy').body, 'Admin rewrote it'); }); test('profiles never send join or last-active dates to members; admins still get them', async () => {