From 318bfc48d5abd7990f85920a863c443cd3c2d271 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:07:22 +0000 Subject: [PATCH 1/2] Moderation queue: full About me with flagged parts highlighted, edit or redact in place, fewer false contact flags, photo lightbox, member profile view - Contact check no longer reads ordinary English ("a giver at heart. more later"), year ranges, measurements or "mixed signal" as contact info; spelled emails need a mail provider or a spelled "dot", bare domains are lower-case only, handles need a separator or a handle-like name, phone numbers must look like phone numbers. - Profile items show the member's whole About me, with each match highlighted and named. - New decisions: redact (remove only the contact details) and edit (save corrected text). - Re-check button marks waiting import flags fine when today's check finds nothing. - Click a photo in the queue to see it larger. - Members tab: click a member for their full profile plus every photo with its status. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015x8UvSnJ9qFe7pZLH6BupP --- apps/api/src/app.ts | 12 +- apps/member/src/app/admin/index.tsx | 277 ++++++++++++++++++++++++++-- packages/core/src/api.ts | 13 +- packages/core/src/http-client.ts | 4 +- packages/core/src/rules.ts | 66 ++++++- packages/core/src/seed.ts | 10 + packages/core/src/services.ts | 73 +++++++- packages/core/src/types.ts | 18 ++ packages/core/test/platform.test.ts | 64 +++++++ 9 files changed, 496 insertions(+), 41 deletions(-) diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 6a80b52..c9e6f94 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 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 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'; @@ -212,12 +212,18 @@ export class AdminController { @Get('sites/:site/moderation') async mod(@Headers('authorization') a: string, @Param('site') s: string, @Query('status') st = 'pending') { return this.p.adminModeration(await this.admin(a), s, st as any); } - @Post('sites/:site/moderation/:id') async decide(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string, @Body() b: { decision: 'approve' | 'reject' }) { - return this.p.adminDecide(await this.admin(a), s, id, b.decision); + @Post('sites/:site/moderation/:id') async decide(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string, @Body() b: { decision: ModerationDecision; text?: string }) { + return this.p.adminDecide(await this.admin(a), s, id, b.decision, b.text); + } + @Post('sites/:site/moderation-recheck') async recheck(@Headers('authorization') a: string, @Param('site') s: string) { + return this.p.adminRecheckModeration(await this.admin(a), s); } @Get('sites/:site/members') async members(@Headers('authorization') a: string, @Param('site') s: string, @Query('search') q?: string, @Query('page') page?: string) { return this.p.adminMembers(await this.admin(a), s, { search: q || undefined, page: Number(page) || 1 }); } + @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); } diff --git a/apps/member/src/app/admin/index.tsx b/apps/member/src/app/admin/index.tsx index 6877a7b..681241c 100644 --- a/apps/member/src/app/admin/index.tsx +++ b/apps/member/src/app/admin/index.tsx @@ -1,12 +1,13 @@ // Owner Admin: one login, a site switcher, and per-site moderation, members, fields, pages and settings. // Platform admins (WhatBox) see every site and can change a site's mode; owners see only their sites. import { - ApiError, type AdminApi, type AdminEventRow, type AdminMemberRow, isoToZoned, zonedToIso, type AdminSiteSummary, type ContentPage, type ModerationView, + 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 ProfileFieldDef, type Site, type SiteStats, type SiteTheme, TIERS, type Tier, type TierPerms, } from '@whatbox/core'; import { router } from 'expo-router'; import { useCallback, useEffect, useState, type ReactNode } from 'react'; -import { Platform, Pressable, ScrollView, Text, TextInput, View } from 'react-native'; +import { Image, Modal, Platform, Pressable, ScrollView, Text, TextInput, View } from 'react-native'; import Svg, { Circle } from 'react-native-svg'; import { adminApi, IS_PREVIEW } from '../../lib/backend'; import { storage } from '../../lib/storage'; @@ -256,18 +257,32 @@ function Overview({ stats, site, go }: { stats: SiteStats | null; site: Site; go ); } +const CONTACT_FLAG = 'contact info in profile'; +const KIND_LABEL: Record = { email: 'email', url: 'link', phone: 'phone number', handle: 'app handle' }; + function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; onChange: () => void }) { const t = useTheme(); const [status, setStatus] = useState<'pending' | 'all'>('pending'); const [items, setItems] = useState(null); + const [big, setBig] = useState(null); + const [recheck, setRecheck] = useState<{ busy: boolean; note?: string }>({ busy: false }); const load = useCallback(() => { setItems(null); api.moderation(siteId, status).then(setItems); }, [api, siteId, status]); useEffect(() => { load(); }, [load]); - const decide = async (id: string, d: 'approve' | 'reject') => { await api.decide(siteId, id, d); load(); onChange(); }; + const decide = async (id: string, d: ModerationDecision, text?: string) => { await api.decide(siteId, id, d, text); load(); onChange(); }; const labels: Record = { photo: ['Photo', 'Approve', 'Reject photo'], message: ['Held message', 'Release to recipient', 'Keep blocked'], report: ['Member report', 'Suspend member', 'Dismiss'], - profile: ['Profile text', 'Looks fine', 'Clear "About me"'], + profile: ['Profile text', 'Looks fine', 'Clear all of "About me"'], + }; + const stale = (items ?? []).filter((i) => i.status === 'pending' && i.kind === 'profile' && i.reasons.length === 1 && i.reasons[0] === CONTACT_FLAG && !i.contactMatches?.length).length; + const runRecheck = async () => { + setRecheck({ busy: true }); + try { + const r = await api.recheckModeration(siteId); + setItems(r.items); onChange(); + setRecheck({ busy: false, note: r.cleared ? r.cleared === 1 ? '1 item marked fine: the updated check finds no contact info in it.' : `${r.cleared} items marked fine: the updated check finds no contact info in them.` : 'Nothing to clear: every waiting item still has contact info.' }); + } catch (e) { setRecheck({ busy: false, note: e instanceof ApiError ? e.message : 'Re-check failed.' }); } }; return ( @@ -275,9 +290,21 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; setStatus('pending')} /> setStatus('all')} /> + {stale ? ( + = 200 ? '+' : ''} "contact info" flags no longer hold up`}> + The import used an older, looser check that read phrases like "at heart. more" as an email address. The updated check finds no contact info in these profiles. Re-checking marks only those items fine and changes no profile text. + + + ) : null} + {recheck.note ? {recheck.note} : null} {!items ? : items.length === 0 ? Nothing waiting. New uploads, held messages and reports land here. : items.map((i) => ( - {i.photo ? : ( + {i.photo ? ( + setBig(i.photo!)} accessibilityRole="button" accessibilityLabel="View photo larger"> + + Click to enlarge + + ) : ( @@ -289,28 +316,156 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; {i.status !== 'pending' ? : null} {i.messageBody ? "{i.messageBody}" : null} - {i.summary} - - {i.reasons.map((r) => )} - - {i.status === 'pending' ? ( - - decide(i.id, 'approve')} /> - decide(i.id, 'reject')} /> - - ) : Decided by {i.decidedBy} {i.decidedAt ? relTime(i.decidedAt) : ''}} + {i.kind === 'profile' && i.profileText !== undefined + ? decide(i.id, d, text)} rejectLabel={labels.profile[2]} approveLabel={labels.profile[1]} /> + : ( + <> + {i.summary} + + {i.reasons.map((r) => )} + + {i.status === 'pending' ? ( + + decide(i.id, 'approve')} /> + decide(i.id, 'reject')} /> + + ) : null} + + )} + {i.status !== 'pending' ? Decided by {i.decidedBy} {i.decidedAt ? relTime(i.decidedAt) : ''} : null} ))} + setBig(null)} /> + + ); +} + +/** Splits text into plain and flagged runs so the flagged parts can be highlighted. */ +function contactRuns(text: string, matches: ContactMatch[]) { + const runs: { text: string; kind?: ContactMatch['kind'] }[] = []; + let pos = 0; + for (const m of matches) { + if (m.start > pos) runs.push({ text: text.slice(pos, m.start) }); + runs.push({ text: text.slice(m.start, m.end), kind: m.kind }); + pos = m.end; + } + if (pos < text.length) runs.push({ text: text.slice(pos) }); + return runs; +} + +function Highlighted({ text, matches }: { text: string; matches: ContactMatch[] }) { + return ( + + {contactRuns(text, matches).map((r, idx) => r.kind + ? {r.text} + : {r.text})} + + ); +} + +const COLLAPSE_AT = 600; + +function ProfileTextReview({ item, onDecide, approveLabel, rejectLabel }: { + item: ModerationView; onDecide: (d: ModerationDecision, text?: string) => Promise; approveLabel: string; rejectLabel: string; +}) { + const t = useTheme(); + const text = item.profileText ?? ''; + const matches = item.contactMatches ?? []; + const [open, setOpen] = useState(text.length <= COLLAPSE_AT); + const [draft, setDraft] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const pending = item.status === 'pending'; + const contactFlag = item.reasons.includes(CONTACT_FLAG); + const run = async (d: ModerationDecision, body?: string) => { + setBusy(true); setError(null); + try { await onDecide(d, body); } catch (e) { setError(e instanceof ApiError ? e.message : 'Could not save.'); setBusy(false); } + }; + // Collapsed: the opening, then a short window around each later flagged part, so nothing flagged is ever hidden. + const excerpt = () => { + const spanning = matches.find((m) => m.start < 280 && m.end > 280); + const headEnd = spanning ? spanning.end : 280; + const parts: ReactNode[] = [ m.end <= headEnd)} />]; + matches.filter((m) => m.start >= headEnd).forEach((m, idx) => { + const from = Math.max(headEnd, m.start - 80); + const to = Math.min(text.length, m.end + 80); + parts.push( + + Later in the text + + , + ); + }); + return parts; + }; + if (draft !== null) { + const live = findContactInfo(draft); + return ( + + KIND_LABEL[m.kind]).join(', ')}.` : 'No contact info found in this version.'} /> + {live.length ? : null} + + + run('edit', draft)} /> + { setDraft(null); setError(null); }} /> + + + ); + } + return ( + + + {text ? (open ? : excerpt()) : "About me" is empty now.} + {text.length > COLLAPSE_AT ? ( + setOpen(!open)} accessibilityRole="button"> + {open ? 'Show less' : `Show full text (${text.length.toLocaleString()} characters)`} + + ) : null} + + + {item.reasons.map((r) => )} + + {matches.length ? ( + Found {matches.map((m) => `${KIND_LABEL[m.kind]} "${text.slice(m.start, m.end)}"`).join(', ')}. Highlighted above. + ) : contactFlag ? ( + The updated check finds no contact info in this text. It was flagged by the older, looser check, so "{approveLabel}" is likely right. + ) : null} + + {pending ? ( + + run('approve')} /> + {matches.length ? run('redact')} /> : null} + { setDraft(text); setError(null); }} /> + run('reject')} /> + + ) : null} ); } +function PhotoLightbox({ photo, onClose }: { photo: PhotoView | null; onClose: () => void }) { + return ( + + + {photo?.url + ? + : photo ? : null} + + + + + + ); +} + function Members({ api, siteId }: { api: AdminApi; siteId: string }) { const t = useTheme(); const [search, setSearch] = useState(''); const [page, setPage] = useState(1); const [data, setData] = useState<{ total: number; rows: AdminMemberRow[] } | null>(null); + const [openId, setOpenId] = useState(null); const load = useCallback(() => api.members(siteId, { search, page }).then(setData), [api, siteId, search, page]); useEffect(() => { load(); }, [load]); return ( @@ -320,15 +475,15 @@ function Members({ api, siteId }: { api: AdminApi; siteId: string }) { {data.rows.map((m, idx) => ( - + setOpenId(m.id)} accessibilityRole="button" accessibilityLabel={`View ${m.displayName}'s profile`}> - {m.displayName}{m.age ? `, ${m.age}` : ''} + {m.displayName}{m.age ? `, ${m.age}` : ''} {m.tier !== 'free' ? : null} {m.status === 'suspended' ? : null} {m.reports ? 1 ? 's' : ''}`} tone="alert" /> : null} {m.city || 'No city yet'} · {m.photoCount} photos · joined {relTime(m.createdAt)} · active {relTime(m.lastActiveAt)} - + 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' }))} /> = data.total} onPress={() => setPage(page + 1)} /> ) : null} - Contact details are encrypted with this site's own key and are not shown here. + 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)} /> ); } +/** 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 }) { + 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); + if (!memberId) return; + api.memberProfile(siteId, memberId).then(setData, (e) => setError(e instanceof ApiError ? e.message : 'Could not load the profile.')); + }, [api, siteId, memberId]); + const p = data?.profile; + const photoStatus = (ph: PhotoView) => `${ph.kind}${ph.rating === 'explicit' ? ' · explicit' : ''}${ph.status !== 'approved' ? ` · ${ph.status}` : ''}`; + return ( + + + + + {p ? `${p.displayName}${p.age ? `, ${p.age}` : ''}` : 'Profile'} + + + + + + {error ? {error} : !data || !p ? : ( + <> + + p.mainPhoto && setBig(p.mainPhoto)} accessibilityRole="button" accessibilityLabel="View main photo larger"> + + + + {[p.city, p.region].filter(Boolean).join(', ') || 'No location yet'} + + {data.status === 'suspended' ? : null} + {!data.profileComplete ? : null} + {p.verified ? : null} + {data.imported ? : null} + {p.tier !== 'free' ? : null} + + {p.gender}{p.seeking ? ` · looking for ${p.seeking.join(', ')}` : ''}{p.ageMin ? ` · ages ${p.ageMin} to ${p.ageMax}` : ''} + Joined {relTime(data.createdAt)} · active {relTime(p.lastActiveAt)} + + + {p.cautions.length ? p.cautions.map((c) => {c}) : null} + + About me + {p.about ? : Empty.} + + {p.details.length ? ( + + Details + {p.details.map((d) => {d.label}: {d.value})} + + ) : null} + {p.interests.length ? ( + + Interests + {p.interests.map((x) => )} + + ) : null} + + All photos ({data.photos.length}) + Includes private, pending and rejected photos, which members don't see. Click one to enlarge. + + {data.photos.map((ph) => ( + setBig(ph)} accessibilityRole="button" accessibilityLabel={`View ${photoStatus(ph)} photo larger`} style={{ gap: 4 }}> + + {photoStatus(ph)} + + ))} + + + + )} + + + + setBig(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 f19db4e..09992cf 100644 --- a/packages/core/src/api.ts +++ b/packages/core/src/api.ts @@ -4,8 +4,8 @@ import { RuleError } from './rules'; import type { AccessRow, Platform, ProfilePatch } from './services'; import type { - ActivityKind, ActivityList, AdminMemberRow, ClientPlatform, MemberEvent, DiscoverCard, ContentPage, ConversationSummary, ConversationView, MemberProfile, - MemberStatus, ModerationView, MyProfile, PhotoKind, PhotoRating, ProfileFieldDef, PublicSite, SearchFilters, + ActivityKind, ActivityList, AdminMemberProfile, AdminMemberRow, 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, } from './types'; @@ -81,8 +81,11 @@ export interface AdminApi { deleteField(siteId: string, key: string): Promise; stats(siteId: string): Promise; moderation(siteId: string, status: 'pending' | 'approved' | 'rejected' | 'all'): Promise; - decide(siteId: string, itemId: string, decision: 'approve' | 'reject'): Promise; + decide(siteId: string, itemId: string, decision: ModerationDecision, text?: string): Promise; + /** Marks waiting "contact info in profile" items fine when today's check no longer finds contact details. */ + recheckModeration(siteId: string): Promise<{ cleared: 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 }>; setMemberTier(siteId: string, memberId: string, tier: Tier): Promise<{ ok: boolean }>; pages(siteId: string): Promise; @@ -190,8 +193,10 @@ export function createLocalAdminApi(platform: Platform): AdminApi { deleteField: (s, k) => wrap(async () => platform.adminDeleteField(await admin(), s, k)), stats: (s) => wrap(async () => platform.adminStats(await admin(), s)), moderation: (s, st) => wrap(async () => platform.adminModeration(await admin(), s, st)), - decide: (s, i, d) => wrap(async () => platform.adminDecide(await admin(), s, i, d)), + decide: (s, i, d, text) => wrap(async () => platform.adminDecide(await admin(), s, i, d, text)), + recheckModeration: (s) => wrap(async () => platform.adminRecheckModeration(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)), setMemberTier: (s, m, t) => wrap(async () => platform.adminSetMemberTier(await admin(), s, m, t)), audit: (siteId) => wrap(async () => platform.adminAudit(await admin(), siteId)), diff --git a/packages/core/src/http-client.ts b/packages/core/src/http-client.ts index 1b5ecc4..d66b6b7 100644 --- a/packages/core/src/http-client.ts +++ b/packages/core/src/http-client.ts @@ -150,8 +150,10 @@ export function createHttpAdminApi(baseUrl: string): AdminApi { deleteField: (id, key) => req('DELETE', s(id) + '/fields/' + key), stats: (id) => req('GET', s(id) + '/stats'), moderation: (id, status) => req('GET', s(id) + '/moderation?status=' + status), - decide: (id, item, decision) => req('POST', s(id) + '/moderation/' + item, { decision }), + decide: (id, item, decision, text) => req('POST', s(id) + '/moderation/' + item, { decision, text }), + recheckModeration: (id) => req('POST', s(id) + '/moderation-recheck', {}), 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 }), setMemberTier: (id, m, tier) => req('PATCH', s(id) + '/members/' + m + '/tier', { tier }), audit: (siteId) => req('GET', '/v1/admin/audit' + (siteId ? '?site=' + encodeURIComponent(siteId) : '')), diff --git a/packages/core/src/rules.ts b/packages/core/src/rules.ts index e9def7c..723e46e 100644 --- a/packages/core/src/rules.ts +++ b/packages/core/src/rules.ts @@ -45,28 +45,62 @@ export function checkPhotoAllowed( // ---------- Message screening ---------- -const EMAIL_RE = /[A-Z0-9._%+-]+\s*(?:@|\(at\)|\[at\]|\sat\s)\s*[A-Z0-9.-]+\s*(?:\.|\(dot\)|\[dot\]|\sdot\s)\s*[A-Z]{2,}/gi; -const URL_RE = /\b(?:https?:\/\/|www\.)\S+|\b[a-z0-9-]+\.(?:com|net|org|io|me|co|app|ly)\b(?:\/\S*)?/gi; -// 10+ digits, allowing spaces, dots, dashes, parentheses between them -const PHONE_RE = /(?:\+?\d[\s().-]*){10,}/g; -const HANDLE_RE = /\b(?:whats\s?app|telegram|signal|snap(?:chat)?|insta(?:gram)?|kik|wechat|hangouts|google\s?chat|ig)\b\s*[:@-]?\s*@?[\w.]{0,30}/gi; +// Tuned on imported profiles (Nov 2026): ordinary English like "a giver at heart. more later", +// year ranges like "1990-2000 2005", body measurements and "mixed signal" used to be flagged. +// Each pattern now needs something that only contact details have. +const MAIL_PROVIDERS = 'gmail|googlemail|yahoo|ymail|hotmail|outlook|live|msn|aol|icloud|me\\.com|proton(?:mail)?|gmx|comcast|att|verizon|zoho|yandex|mail'; +// a real address: name@domain.tld (a space either side of @ is allowed) +const EMAIL_RE = /[A-Z0-9._%+-]+ ?@ ?[A-Z0-9-]+(?:\.[A-Z0-9-]+)*\.[A-Z]{2,}\b/gi; +// a disguised address: "jo (at) yahoo (dot) com", "jo at gmail", "jo [at] example [dot] net" +const EMAIL_SPELLED_RE = new RegExp( + String.raw`[A-Z0-9._%+-]+\s*(?:\(at\)|\[at\]|\{at\}|\bat\b)\s*(?:(?:${MAIL_PROVIDERS})\b(?:\s*(?:\.|\(dot\)|\[dot\]|\{dot\}|\bdot\b)\s*[A-Z]{2,4}\b)?|[A-Z0-9-]+\s*(?:\(dot\)|\[dot\]|\{dot\}|\bdot\b)\s*[A-Z]{2,4}\b)`, + 'gi', +); +// links: anything with http(s):// or www., or a bare lower-case name.com/.net/.org/.info/.biz/.io +// (case-sensitive so "laugh.Me too" or "deal.Co-workers", a missing space after a period, is not a link) +const URL_RE = /\b(?:https?:\/\/|www\.)\S+/gi; +const BARE_DOMAIN_RE = /\b[a-z0-9][a-z0-9-]*\.(?:com|net|org|info|biz|io)\b(?:\/\S*)?/g; +// 10 to 15 digits, allowing spaces, dots, dashes, parentheses between them; checked by looksLikePhone +const PHONE_RE = /\+?\(?\d[\d\s().-]{8,}\d/g; +const HANDLE_KEYWORDS = String.raw`whats\s?app|telegram|signal|snap(?:chat)?|insta(?:gram)?|kik|wechat|skype|discord|ig`; +// a handle needs a separator ("snap: jo", "kik - jo", "whatsapp @jo") or a name that looks like a handle (a digit, _ or .) +const HANDLE_RE = new RegExp( + String.raw`\b(?:${HANDLE_KEYWORDS})\b(?:\s*(?:id|name|handle|user\s?name|is|me|at))*\s*(?:[:=@-]\s*@?[A-Z0-9_.]{2,30}|@?(?=[A-Z0-9_.]*[0-9_.][A-Z0-9_.]*\b)[A-Z0-9_.]{3,30}[A-Z0-9_])`, + 'gi', +); const SPELLED_DIGITS_RE = /\b(?:(?:zero|one|two|three|four|five|six|seven|eight|nine)[\s,.-]*){7,}/gi; -export interface ContactMatch { start: number; end: number; kind: 'email' | 'url' | 'phone' | 'handle' } +function looksLikePhone(s: string): boolean { + const groups = s.match(/\d+/g) ?? []; + const digits = groups.join('').length; + if (digits < 10 || digits > 15) return false; + if (groups.length === 1) return true; + // "1990-2000 2005": years, not a number + if (groups.every((g) => /^(?:19|20)\d\d$/.test(g) || g.length <= 2)) return false; + // "36-24-36 5 10 170" or "30 35 40 45 50": too many small groups to be a phone number + if (groups.length > 5) return false; + if (groups.filter((g) => g.length >= 3).length < 2) return false; + return groups.every((g, i) => g.length >= 2 || i === 0); +} + +export type ContactKind = 'email' | 'url' | 'phone' | 'handle'; +export interface ContactMatch { start: number; end: number; kind: ContactKind } export function findContactInfo(text: string): ContactMatch[] { const out: ContactMatch[] = []; - const scan = (re: RegExp, kind: ContactMatch['kind']) => { + const scan = (re: RegExp, kind: ContactKind, ok: (s: string) => boolean = () => true) => { re.lastIndex = 0; let m: RegExpExecArray | null; while ((m = re.exec(text))) { - const s = m[0].trimEnd(); - if (s.length) out.push({ start: m.index, end: m.index + s.length, kind }); + const s = m[0].replace(/[\s.,;:!?)-]+$/, ''); + if (s.length && ok(s)) out.push({ start: m.index, end: m.index + s.length, kind }); } }; scan(EMAIL_RE, 'email'); + scan(EMAIL_SPELLED_RE, 'email'); scan(URL_RE, 'url'); - scan(PHONE_RE, 'phone'); + scan(BARE_DOMAIN_RE, 'url'); + scan(PHONE_RE, 'phone', looksLikePhone); scan(SPELLED_DIGITS_RE, 'phone'); scan(HANDLE_RE, 'handle'); // merge overlaps @@ -80,6 +114,18 @@ export function findContactInfo(text: string): ContactMatch[] { return merged; } +/** Replaces only the contact details, keeping the rest of the text. */ +export function redactContactInfo(text: string, placeholder = '[contact info removed]'): string { + const matches = findContactInfo(text); + let out = ''; + let pos = 0; + for (const m of matches) { + out += text.slice(pos, m.start) + placeholder; + pos = m.end; + } + return out + text.slice(pos); +} + export function maskContactInfo(text: string): string { const matches = findContactInfo(text); if (!matches.length) return text; diff --git a/packages/core/src/seed.ts b/packages/core/src/seed.ts index cc1d82e..62fc800 100644 --- a/packages/core/src/seed.ts +++ b/packages/core/src/seed.ts @@ -304,6 +304,16 @@ export function seedSite(site: Site, now: Date, opts: { demoMemberHash?: { email const tess = byName('Tess'); photos.push({ id: 'ph_seed_pending', memberId: tess.id, kind: 'public', rating: 'safe', status: 'pending', tone: ['#E9DEC5', '#B8A27A'], sort: 9, createdAt: t(12) }); moderation.push({ id: 'mod_seed_photo', kind: 'photo', refId: 'ph_seed_pending', memberId: tess.id, summary: 'New public photo, marked safe', reasons: ['new upload'], status: 'pending', createdAt: t(12) }); + // Profile text flagged for contact info: one real (late in a long About me), one the old, looser check got wrong + const dana = byName('Dana'); + dana.about = 'I am a pretty simple person who loves live music, slow Sunday mornings and long walks with my dog. ' + + 'I try never to miss a concert and I can usually be talked into something fun or a little spontaneous. ' + + 'Friends say I am a good listener and a terrible cook, and both are true. I am looking for someone kind, curious and honest, ' + + 'who likes to laugh at themselves. If you want to skip the small talk, text me at 303-555-0144 and say hi.'; + moderation.push({ id: 'mod_seed_profile', kind: 'profile', refId: dana.id, memberId: dana.id, summary: dana.about.slice(0, 280), reasons: ['contact info in profile'], status: 'pending', createdAt: t(40) }); + const sam = byName('Sam'); + sam.about = "A giver at heart. more later\n\nWho I'd like to meet: Tallish, more latter"; + moderation.push({ id: 'mod_seed_profile_old', kind: 'profile', refId: sam.id, memberId: sam.id, summary: sam.about, reasons: ['contact info in profile'], status: 'pending', createdAt: t(45) }); } // Priya is VIP in the demo: with the paywall on, her messages stay readable for free members. diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts index 13db1b6..267bf5e 100644 --- a/packages/core/src/services.ts +++ b/packages/core/src/services.ts @@ -7,13 +7,13 @@ import type { ControlRepo, Clock, EventSink, IdTokenVerifier, Notifier, PaymentG import { systemClock } from './repo'; import { DEFAULT_LICENSING, DEFAULT_NOTIFY, DEFAULT_STRICT, isGender, type HiddenPrefs, type NotifyPrefs, type StrictPrefs } from './types'; import { - ageFromBirthYear, checkPhotoAllowed, CODE_MAX_ATTEMPTS, CODE_TTL_MS, formatHeight, maskContactInfo, milesBetween, + ageFromBirthYear, checkPhotoAllowed, CODE_MAX_ATTEMPTS, CODE_TTL_MS, findContactInfo, formatHeight, maskContactInfo, milesBetween, redactContactInfo, ONLINE_WINDOW_MS, PHOTO_LIMITS, effectivePerms, tierFor, photoVisibleTo, RuleError, scoreCandidate, screenMessage, } from './rules'; import type { - AccessStatus, ActivityKind, ActivityList, ActivityPerson, AdminMemberRow, DiscoverCard, Units, Tier, TierPerms, MembershipSettings, Message, MemberEvent, Subscription, + AccessStatus, ActivityKind, ActivityList, ActivityPerson, AdminMemberProfile, AdminMemberRow, 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, ModerationView, MyProfile, Photo, + ConversationView, Gender, GeoPlace, GeoProvider, LocationInput, Member, MemberCard, MemberProfile, MemberStatus, ModerationDecision, ModerationItem, ModerationView, MyProfile, Photo, PhotoKind, PhotoRating, PhotoView, ProfileFieldDef, PublicSite, SearchFilters, SearchResult, Site, SiteSettings, SiteStats, SiteTheme, EventRsvp, EventView, ProfileEvent, RsvpStatus, SiteEvent, } from './types'; @@ -1354,16 +1354,23 @@ 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 === 'profile') { + const about = members.get(i.memberId)?.about ?? ''; + v.profileText = about; + v.contactMatches = findContactInfo(about); + } out.push(v); } return out; } - async adminDecide(admin: AdminUser, siteId: string, itemId: string, decision: 'approve' | 'reject') { + async adminDecide(admin: AdminUser, siteId: string, itemId: string, decision: ModerationDecision, text?: string) { const site = await this.adminSite(admin, siteId); const repo = await this.repo(site); 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 !== 'approve' && decision !== 'reject') throw new RuleError('bad_decision', 'Unknown decision.'); const status = decision === 'approve' ? 'approved' : 'rejected'; if (item.kind === 'photo') { const p = await repo.getPhoto(item.refId); @@ -1390,6 +1397,64 @@ export class Platform { return this.adminModeration(admin, siteId, 'pending'); } + /** Keeps the rest of About me: removes only the contact details (redact), or saves the admin's corrected text (edit). */ + private async adminFixProfileText(admin: AdminUser, site: Site, repo: SiteRepo, item: ModerationItem, decision: 'redact' | 'edit', text?: string) { + if (item.kind !== 'profile') throw new RuleError('bad_decision', 'Only profile text can be edited here.'); + const m = await repo.getMember(item.memberId); + if (!m) throw new RuleError('not_found', 'Member not found.', 404); + let about: string; + if (decision === 'redact') about = redactContactInfo(m.about); + else { + if (typeof text !== 'string') throw new RuleError('bad_text', 'Send the corrected text.'); + about = text.trim(); + // imported profiles can be longer than today's limit; an edit may keep that length but not grow past it + const max = Math.max(ABOUT_MAX, m.about.length); + if (about.length > max) throw new RuleError('about_long', `Keep it under ${max} characters.`); + } + await repo.saveMember({ ...m, about }); + await repo.saveModeration({ ...item, status: 'approved', decidedAt: this.iso(), decidedBy: admin.email }); + await this.audit(admin, `moderation.${decision}`, site.id, item.memberId, item.kind); + this.changed(); + return this.adminModeration(admin, site.id, 'pending'); + } + + /** Imported items were flagged by an older, looser check. Marks them fine when today's check finds no contact details. */ + async adminRecheckModeration(admin: AdminUser, siteId: string): Promise<{ cleared: number; items: ModerationView[] }> { + const site = await this.adminSite(admin, siteId); + const repo = await this.repo(site); + let cleared = 0; + // listModeration returns at most 200, so keep going while a full page still yields clears + for (let round = 0; round < 50; round++) { + const items = (await repo.listModeration('pending')).filter((i) => i.kind === 'profile' && i.reasons.length === 1 && i.reasons[0] === 'contact info in profile'); + const members = new Map((await repo.getMembers(items.map((i) => i.memberId))).map((m) => [m.id, m])); + let now = 0; + for (const i of items) { + const m = members.get(i.memberId); + if (m && findContactInfo(m.about).length) continue; + await repo.saveModeration({ ...i, status: 'approved', decidedAt: this.iso(), decidedBy: `${admin.email} (re-check)` }); + now++; + } + cleared += now; + if (!now) break; + } + if (cleared) await this.audit(admin, 'moderation.recheck', site.id, undefined, `${cleared} cleared`); + this.changed(); + return { cleared, items: await this.adminModeration(admin, siteId, 'pending') }; + } + + /** The member's profile as other members see it, plus every photo (pending, private, rejected) for the admin. + * Nothing is recorded: no profile view, no notification. Contact details stay encrypted and are not included. */ + async adminMemberProfile(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 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 })); + return { profile, photos, status: m.status, profileComplete: m.profileComplete, createdAt: m.createdAt, imported: !!m.imported }; + } + async adminMembers(admin: AdminUser, siteId: string, opts: { search?: string; page?: number }) { const site = await this.adminSite(admin, siteId); const repo = await this.repo(site); diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index c810d23..8aa355f 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -552,12 +552,30 @@ export interface AdminMemberRow { reports: number; } +export interface AdminMemberProfile { + /** Exactly what other members see (approved photos only, private photos locked). */ + profile: MemberProfile; + /** Every photo the member has, with its review status, for the admin. */ + photos: PhotoView[]; + status: MemberStatus; + profileComplete: boolean; + createdAt: string; + imported: boolean; +} + export interface ModerationView extends ModerationItem { memberName: string; photo?: PhotoView; messageBody?: string; + /** Profile items: the member's whole About me as it is now (the summary is cut at 280 characters). */ + profileText?: string; + /** Profile items: where the contact check finds contact details in profileText today. */ + contactMatches?: { start: number; end: number; kind: 'email' | 'url' | 'phone' | 'handle' }[]; } +/** approve/reject as before; redact removes only the contact details; edit saves the admin's corrected text. */ +export type ModerationDecision = 'approve' | 'reject' | 'redact' | 'edit'; + // ---------- Places (worldwide) ---------- export interface GeoPlace { id: string; name: string; region: string; country: string; lat: number; lng: number; postal?: string } export interface GeoCountry { code: string; name: string; postal: boolean; units: Units } diff --git a/packages/core/test/platform.test.ts b/packages/core/test/platform.test.ts index 4cbf075..3fd4ac8 100644 --- a/packages/core/test/platform.test.ts +++ b/packages/core/test/platform.test.ts @@ -630,3 +630,67 @@ test('events: admins create and cancel, members RSVP, profiles show events only assert.equal((await b.event(ev.id)).status, 'cancelled'); assert.ok((await a.events('past')).every((e) => e.past)); }); + +test('contact check ignores ordinary English that used to be flagged', () => { + for (const ok of [ + "A giver at heart. more later\n\nWho I'd like to meet: Tallish, more latter", + "I love to laugh.Me too", "I'm at home. me too", "between 1990-2000 2005 I lived abroad", + "36-24-36 5 10 170", "no mixed signal from me", "snap is fun", "kids ages 12, 15 and 17, born 2008 2010", + ]) assert.equal(findContactInfo(ok).length, 0, ok); + for (const bad of [ + 'jo at gmail', 'bob @ yahoo.com', 'jo [at] mysite [dot] net', '+1 (303) 555-0199', 'Text me 303.555.0199.', + 'my snap is jojo_22', 'snap: johnny', 'visit mysite.com today', 'five five five one two three four five six seven', + ]) assert.ok(findContactInfo(bad).length, bad); + const t = 'Call 303-555-0199 any time'; + const [m] = findContactInfo(t); + assert.equal(t.slice(m.start, m.end), '303-555-0199'); + assert.equal(m.kind, 'phone'); +}); + +test('admin sees full flagged profile text, can redact or edit it, and re-check clears stale flags', async () => { + const { mp, api } = await signIn(); + const me = await api.me(); + const long = 'I love hiking and long dinners. '.repeat(15); + await api.updateMe({ about: `${long}Text me at 303-555-0199 after work.` }); + const admin = createLocalAdminApi(mp.platform); + const st = await admin.start(DEMO_OWNER_EMAIL); + admin.setToken((await admin.verify(st.challengeId, st.devCode!)).token); + const find = async () => (await admin.moderation('site_afterh', 'pending')).find((i) => i.kind === 'profile' && i.memberId === me.member.id); + let item = (await find())!; + assert.ok(item.profileText!.endsWith('after work.'), 'whole text, not cut at 280'); + assert.equal(item.contactMatches!.length, 1); + assert.equal(item.profileText!.slice(item.contactMatches![0].start, item.contactMatches![0].end), '303-555-0199'); + + await admin.decide('site_afterh', item.id, 'redact'); + assert.equal(await find(), undefined); + let mine = await api.me(); + assert.ok(mine.member.about.startsWith(long.trim())); + assert.match(mine.member.about, /Text me at \[contact info removed\] after work\./); + + await api.updateMe({ about: 'Find me on snap: jojo_22 please' }); + item = (await find())!; + await admin.decide('site_afterh', item.id, 'edit', 'Ask me for my snap once we have talked.'); + mine = await api.me(); + assert.equal(mine.member.about, 'Ask me for my snap once we have talked.'); + + // an item flagged by the old, looser rule: no contact info by today's check + const repo = await (mp.platform as any).repo(await (mp.platform as any).adminSite({ role: 'platform' }, 'site_afterh')); + await api.updateMe({ about: 'A giver at heart. more later' }); + await repo.saveModeration({ id: 'mod_stale', kind: 'profile', refId: me.member.id, memberId: me.member.id, summary: 'x', reasons: ['contact info in profile'], status: 'pending', createdAt: new Date().toISOString() }); + const r = await admin.recheckModeration('site_afterh'); + assert.ok(r.cleared >= 1); + assert.ok(!r.items.some((i) => i.id === 'mod_stale')); + assert.equal((await api.me()).member.about, 'A giver at heart. more later', 're-check changes no profile text'); +}); + +test('admin can open a member profile with every photo', async () => { + const { mp, api } = await signIn(); + const me = await api.me(); + await api.addPhoto({ kind: 'private', tone: ['#111111', '#222222'] }); + const admin = createLocalAdminApi(mp.platform); + const st = await admin.start(DEMO_OWNER_EMAIL); + admin.setToken((await admin.verify(st.challengeId, st.devCode!)).token); + 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'); +}); From 284ff12f51df87168c61f5705884924020295000 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:36:07 +0000 Subject: [PATCH 2/2] Admin safety tools: message review (audited), report a message or photo, safety notice on suspend, policy text Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015x8UvSnJ9qFe7pZLH6BupP --- apps/api/scripts/migrate.ts | 4 +- apps/api/src/app.ts | 18 ++- apps/api/src/notify.ts | 16 +- apps/api/src/pg-repo.ts | 4 + apps/member/src/app/(app)/member/[id].tsx | 23 ++- apps/member/src/app/(app)/messages/[id].tsx | 32 +++- apps/member/src/app/admin/index.tsx | 156 +++++++++++++++++++- packages/core/src/api.ts | 16 +- packages/core/src/http-client.ts | 6 +- packages/core/src/index.ts | 1 + packages/core/src/memory-platform.ts | 5 +- packages/core/src/memory-repo.ts | 1 + packages/core/src/repo.ts | 3 + packages/core/src/safety-notice.ts | 46 ++++++ packages/core/src/services.ts | 114 ++++++++++++-- packages/core/src/starter-content.ts | 41 +++++ packages/core/src/types.ts | 25 +++- packages/core/test/platform.test.ts | 87 +++++++++++ 18 files changed, 557 insertions(+), 41 deletions(-) create mode 100644 packages/core/src/safety-notice.ts 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 738bd6c..d914e8f 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) }; } } @@ -229,8 +230,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 26ecd40..2b594c1 100644 --- a/apps/api/src/pg-repo.ts +++ b/apps/api/src/pg-repo.ts @@ -316,6 +316,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 d1734de..fbde434 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 342f744..2318aff 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 Site, type SiteStats, type SiteTheme, TIERS, type Tier, type TierPerms, } from '@whatbox/core'; import { router } from 'expo-router'; @@ -258,6 +259,8 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; 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 [profileId, setProfileId] = useState(null); const load = useCallback(() => { setItems(null); api.moderation(siteId, status).then(setItems); }, [api, siteId, status]); useEffect(() => { load(); }, [load]); const decide = async (id: string, d: ModerationDecision, text?: string) => { await api.decide(siteId, id, d, text); load(); onChange(); }; @@ -316,10 +319,16 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; {i.reasons.map((r) => )} - {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.memberId ? setProfileId(i.memberId)} /> : null} ) : null} @@ -329,6 +338,7 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; ))} setBig(null)} /> + setProfileId(null)} onChanged={load} /> ); } @@ -458,6 +468,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 ( @@ -478,8 +489,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(); } }} /> ))} @@ -492,23 +503,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 ( @@ -541,6 +561,30 @@ function MemberProfilePanel({ api, siteId, memberId, onClose }: { api: AdminApi; Joined {relTime(data.createdAt)} · active {relTime(p.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} About me @@ -580,6 +624,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 38a34d5..26a9741 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; @@ -90,7 +91,10 @@ export interface AdminApi { recheckModeration(siteId: string): Promise<{ cleared: 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; @@ -157,7 +161,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) => { @@ -203,7 +207,9 @@ export function createLocalAdminApi(platform: Platform): AdminApi { recheckModeration: (s) => wrap(async () => platform.adminRecheckModeration(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 0e16b78..44e8c15 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 () => {}; @@ -156,7 +156,9 @@ export function createHttpAdminApi(baseUrl: string): AdminApi { recheckModeration: (id) => req('POST', s(id) + '/moderation-recheck', {}), 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 faea7c8..a303845 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -16,3 +16,4 @@ export * from './zoned-time'; export * from './analytics'; export * from './demo-analytics'; export * from './update-check'; +export * from './safety-notice'; diff --git a/packages/core/src/memory-platform.ts b/packages/core/src/memory-platform.ts index db4c1ad..6bb495b 100644 --- a/packages/core/src/memory-platform.ts +++ b/packages/core/src/memory-platform.ts @@ -15,6 +15,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: { @@ -32,6 +33,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(); @@ -53,6 +55,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({ @@ -67,7 +70,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 1ff0e15..b59bfe4 100644 --- a/packages/core/src/memory-repo.ts +++ b/packages/core/src/memory-repo.ts @@ -264,6 +264,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 08f7063..5eba492 100644 --- a/packages/core/src/services.ts +++ b/packages/core/src/services.ts @@ -14,7 +14,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, @@ -997,16 +997,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(); @@ -1416,6 +1430,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; @@ -1432,6 +1451,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') { @@ -1514,7 +1544,49 @@ 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 })); - return { profile, photos, status: m.status, profileComplete: m.profileComplete, createdAt: m.createdAt, imported: !!m.imported }; + 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 } : {}) }; + }); + return { + profile, photos, status: m.status, profileComplete: m.profileComplete, createdAt: m.createdAt, imported: !!m.imported, + 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 }) { @@ -1534,15 +1606,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 c2d9919..a312527 100644 --- a/packages/core/src/starter-content.ts +++ b/packages/core/src/starter-content.ts @@ -54,6 +54,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.', @@ -65,6 +78,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.', @@ -82,6 +96,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'), @@ -405,6 +420,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 0f31775..81d1ff0 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -132,6 +132,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'; @@ -221,6 +222,8 @@ export interface Member { imported?: { sources: string[]; at: 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'; @@ -285,6 +288,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; @@ -645,6 +651,10 @@ export interface AdminMemberProfile { profileComplete: boolean; createdAt: string; imported: 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; } export interface ModerationView extends ModerationItem { @@ -658,7 +668,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 3fd4ac8..0fb2942 100644 --- a/packages/core/test/platform.test.ts +++ b/packages/core/test/platform.test.ts @@ -694,3 +694,90 @@ test('admin can open a member profile with every photo', async () => { assert.equal(v.profile.id, me.member.id); assert.ok(v.photos.some((p) => p.kind === 'private' && !p.placeholder), 'admin sees private photos unlocked'); }); + +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'); +});