From 34b71c80553f969cfbff96089756ca537eaa8382 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:28:45 +0000 Subject: [PATCH] Possible scammers: confidence buckets with bulk Looks fine / Suspend, random-username and shared sign-up signals, no more false flags from old or relay addresses Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015x8UvPor5y4oThmpSRWg2D --- apps/api/src/app.ts | 10 ++- apps/api/src/import/bundle.ts | 2 + apps/api/src/import/legacy.ts | 23 +++--- apps/api/src/import/load.ts | 47 ++++++----- apps/api/src/import/network.ts | 55 +++++++++++++ apps/api/src/import/skadate.ts | 12 ++- apps/api/src/ipintel.ts | 6 +- apps/api/src/pg-repo.ts | 13 ++- apps/api/test/network.test.ts | 40 ++++++++++ apps/member/src/app/admin/index.tsx | 73 ++++++++++++++++- packages/core/src/api.ts | 10 ++- packages/core/src/demo-analytics.ts | 4 +- packages/core/src/http-client.ts | 4 +- packages/core/src/memory-repo.ts | 12 ++- packages/core/src/network-risk.ts | 100 +++++++++++++++++++++--- packages/core/src/repo.ts | 5 +- packages/core/src/services.ts | 57 ++++++++++++-- packages/core/src/types.ts | 4 +- packages/core/test/network-risk.test.ts | 52 +++++++++++- 19 files changed, 454 insertions(+), 75 deletions(-) create mode 100644 apps/api/test/network.test.ts diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index f553e79..00b8d0a 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -225,8 +225,14 @@ export class AdminController { } // Every site the admin may see (all for WhatBox, their own for an owner). @Get('dashboard') async dashboardAll(@Headers('authorization') a: string, @Query('days') d?: string) { return this.p.adminDashboardAll(await this.admin(a), Number(d)); } - @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); + @Get('sites/:site/moderation') async mod(@Headers('authorization') a: string, @Param('site') s: string, @Query('status') st = 'pending', @Query('kind') kind?: string, @Query('confidence') confidence?: string) { + return this.p.adminModeration(await this.admin(a), s, st as any, { kind: kind || undefined, confidence: confidence || undefined }); + } + @Get('sites/:site/moderation-risk') async riskBuckets(@Headers('authorization') a: string, @Param('site') s: string) { + return this.p.adminRiskBuckets(await this.admin(a), s); + } + @Post('sites/:site/moderation-risk') async bulkRisk(@Headers('authorization') a: string, @Param('site') s: string, @Body() b: { confidence: 'high' | 'medium' | 'low'; decision: 'approve' | 'reject'; expected?: number }) { + return this.p.adminBulkRisk(await this.admin(a), s, b.confidence, b.decision, typeof b.expected === 'number' ? b.expected : undefined); } @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); diff --git a/apps/api/src/import/bundle.ts b/apps/api/src/import/bundle.ts index b310f5f..84f1794 100644 --- a/apps/api/src/import/bundle.ts +++ b/apps/api/src/import/bundle.ts @@ -49,6 +49,8 @@ export interface SrcMember { photos: SrcPhoto[]; /** Countries and VPN/hosting networks the old site logged them signing in from. Derived; never the IPs. */ network?: MemberNetwork; + /** Accounts that signed up from the same address within 30 days (3+ looks like a farm). Count only. */ + sharedSignup?: number; } export type SrcRelation = diff --git a/apps/api/src/import/legacy.ts b/apps/api/src/import/legacy.ts index b4244d1..5d523f0 100644 --- a/apps/api/src/import/legacy.ts +++ b/apps/api/src/import/legacy.ts @@ -7,7 +7,7 @@ import sql from 'mssql'; import { writeFile } from 'node:fs/promises'; import { normalizeImage } from '../photos'; import type { LocalIpIntel } from '../ipintel'; -import { networkFromHistory } from './network'; +import { deriveNetworks, type IpEntry, RECENT_YEARS } from './network'; import { bump, type BundleInfo, type SrcMember, type SrcPhoto, type SrcRelation, photoPath, prepareBundleDir, writeBundle } from './bundle'; import { cleanText, countryCode, isoDate, joinAbout, legacyDrinking, legacyGender, legacyGoal, legacyHeight, legacyKids, @@ -93,18 +93,19 @@ export async function extractLegacy(site: LegacySite, connectionString: string, // Sign-in countries from the old IP log, looked up here; the IPs themselves stay behind. if (opts.ipIntel?.ready) { - const hist = new Map(); + // every account counts for spotting shared addresses and sign-up farms, imported or not + const entries: IpEntry[] = []; for (const r of await q(`SELECT u_username, ipl_ip, MAX(ipl_timestamp) at, COUNT(*) n FROM IPLogs GROUP BY u_username, ipl_ip`)) { - const k = key(r.u_username); - if (byKey.has(k)) (hist.get(k) ?? hist.set(k, []).get(k)!).push({ ip: r.ipl_ip, at: isoDate(r.at), count: r.n }); - } - for (const u of users) { - const k = key(u.u_username); - if (u.u_signup_ip && byKey.has(k)) (hist.get(k) ?? hist.set(k, []).get(k)!).push({ ip: u.u_signup_ip, at: isoDate(u.u_usersince) }); + entries.push({ key: key(r.u_username), ip: r.ipl_ip, at: isoDate(r.at), count: r.n }); } + for (const u of users) if (u.u_signup_ip) entries.push({ key: key(u.u_username), ip: u.u_signup_ip, at: isoDate(u.u_usersince), signup: true }); + const d = deriveNetworks(entries, opts.ipIntel, new Date()); + bump(info.counts, 'addresses ignored as shared (old servers, proxies)', d.sharedAddresses); for (const m of members) { - const n = networkFromHistory(hist.get(m.key) ?? [], opts.ipIntel); - if (n) { m.network = n; bump(info.counts, 'members with sign-in countries'); } else bump(info.counts, 'members with no sign-in IP to check'); + const n = d.networks.get(m.key); + if (n) { m.network = n; bump(info.counts, `members with sign-ins in the last ${RECENT_YEARS} years`); } else bump(info.counts, `members with no sign-in in the last ${RECENT_YEARS} years (not placed)`); + const s = d.sharedSignup.get(m.key); + if (s) { m.sharedSignup = s; bump(info.counts, 'members who signed up from an address shared with 2+ others that month'); } } } else bump(info.skipped, 'sign-in country check (IP database not loaded)'); @@ -150,7 +151,7 @@ export async function extractLegacy(site: LegacySite, connectionString: string, relations.push({ type: 'message', id: 'legacy-' + r.m_id, from: key(r.f), to: key(r.t), at: isoDate(r.m_timestamp)!, body, read: !!r.m_is_read }); } - info.counts = countBundle(members, relations); + info.counts = { ...info.counts, ...countBundle(members, relations) }; // keeps the sign-in check's counts await writeBundle(outDir, info, members, relations); return info; } finally { diff --git a/apps/api/src/import/load.ts b/apps/api/src/import/load.ts index 67e8641..369c27c 100644 --- a/apps/api/src/import/load.ts +++ b/apps/api/src/import/load.ts @@ -11,7 +11,7 @@ import { createHash } from 'node:crypto'; import { readFile } from 'node:fs/promises'; import { - findContactInfo, flagMember, type Gender, memberFlags, type MemberNetwork, type NicheFlag, riskFlags, riskKey, riskReasons, type GeoPlace, type GeoProvider, isGender, type Member, type ModerationItem, type Photo, type PhotoKind, + findContactInfo, flagMember, type Gender, memberFlags, type MemberNetwork, type NicheFlag, riskConfidence, riskFlags, riskKey, riskReasons, type GeoPlace, type GeoProvider, isGender, type Member, type ModerationItem, type Photo, type PhotoKind, type PhotoStore, type ProfileFieldDef, type Site, type SiteCrypto, type SiteRepo, PHOTO_LIMITS, unitsForCountry, } from '@whatbox/core'; import { type Bundle, bump, photoPath, type SrcLocation, type SrcMember, type SrcPhoto } from './bundle'; @@ -63,6 +63,7 @@ export function mergeMembers(bundles: Bundle[]): MergedMember[] { m.lastActiveAt = maxIso(m.lastActiveAt, src.lastActiveAt); m.flags = [...new Set([...m.flags, ...src.flags])].filter((f) => f !== 'dead_signup' || dead); m.network = mergeNetworks(m.network, src.network); + if (src.sharedSignup) m.sharedSignup = Math.max(m.sharedSignup ?? 0, src.sharedSignup); cur.photos.push(...photos); } } @@ -330,36 +331,46 @@ export async function riskCheckImported(bundles: Bundle[], d: Pick f.review); const key = riskKey(view); + const id = 'mod_imp_risk_' + short(m.id); + // an item this check (or a sign-in) raised earlier and still waiting: re-score it with today's rules + const openId = m.risk?.openItemId ?? id; + const open = await d.repo.getModeration(openId); + const waiting = open?.kind === 'risk' && open.status === 'pending' ? open : null; if (!key) { - bump(report.members, riskFlags(view).length ? 'fits their profile (VPN or hosting seen, not queued)' : 'fits their profile'); + if (waiting) { + bump(report.members, 'cleared automatically (only old or proxy addresses behind the flag)'); + if (!d.dryRun) { + await d.repo.saveModeration({ ...waiting, status: 'approved', decidedAt: at, decidedBy: 'automatic re-check' }); + await d.repo.saveMember({ ...m, risk: { ...risk, openItemId: undefined } }); + } + } else bump(report.members, all.length ? 'fits their profile (minor hints only, not queued)' : 'fits their profile'); continue; } - if (key === m.risk?.clearedKey) { bump(report.members, 'already marked fine'); continue; } - const open = m.risk?.openItemId ? await d.repo.getModeration(m.risk.openItemId) : null; - if (open?.status === 'pending') { bump(report.members, 'already in the queue'); continue; } - const id = 'mod_imp_risk_' + short(m.id); - const prior = await d.repo.getModeration(id); - if (prior) { bump(report.members, prior.status === 'pending' ? 'already in the queue' : 'already decided'); continue; } - const all = riskFlags(view), flags = all.filter((f) => f.review); - const reasons = [...riskReasons(all), 'old site sign-ins']; - bump(report.members, 'flagged for review'); - for (const f of flags) bump(report.members, `flagged: ${riskReasons([f])[0]}`); - for (const c of g.m.network?.countries ?? []) if (c.code !== m.country && flags.some((f) => f.code === 'country_mismatch')) report.flaggedFrom[c.code] = (report.flaggedFrom[c.code] ?? 0) + 1; + if (key === m.risk?.clearedKey && !waiting) { bump(report.members, 'already marked fine'); continue; } + if (!waiting && open && open.status !== 'pending') { bump(report.members, 'already decided'); continue; } + const confidence = riskConfidence(all) ?? 'low'; + bump(report.members, `queued: ${confidence} confidence`); + for (const f of flags) bump(report.members, `flag: ${riskReasons([f])[0]}`); + if (flags.some((f) => f.code === 'country_mismatch')) for (const c of g.m.network?.countries ?? []) if (c.code !== m.country) report.flaggedFrom[c.code] = (report.flaggedFrom[c.code] ?? 0) + 1; if (d.dryRun) continue; await d.repo.saveModeration({ - id, kind: 'risk', refId: m.id, memberId: m.id, status: 'pending', createdAt: d.now.toISOString(), reasons, - summary: `On the old site: ${flags.map((f) => f.text).join(' ')}`, + ...(waiting ?? { id, kind: 'risk' as const, refId: m.id, memberId: m.id, status: 'pending' as const, createdAt: at }), + reasons: [...riskReasons(all), 'old site'], confidence, + summary: `From the old site's records: ${flags.map((f) => f.text).join(' ')}`, }); - await d.repo.saveMember({ ...m, risk: { ...m.risk, openItemId: id } }); + await d.repo.saveMember({ ...m, risk: { ...risk, openItemId: waiting?.id ?? id } }); } return report; } diff --git a/apps/api/src/import/network.ts b/apps/api/src/import/network.ts index bec24ec..59fafe3 100644 --- a/apps/api/src/import/network.ts +++ b/apps/api/src/import/network.ts @@ -2,6 +2,7 @@ // The old databases logged member IPs. The extractor looks each one up in the local IP database // (see ../ipintel.ts) and puts only the result in the bundle: countries, how often, when last, and // whether a network was a VPN or hosting provider. No IP address leaves the throwaway runner. +import { isIP } from 'node:net'; import type { MemberNetwork } from '@whatbox/core'; import type { LocalIpIntel } from '../ipintel'; @@ -40,3 +41,57 @@ export function networkFromHistory(rows: { ip: unknown; at?: string | null; coun if (!countries.length && !hosting) return undefined; return hosting ? { countries, hosting } : { countries }; } + +/** Addresses change hands: a 2010 address looked up in today's database often names someone else + * (old AOL and BlackBerry proxies now show up as Canada), so only recent sign-ins are placed. */ +export const RECENT_YEARS = 3; +const DAY = 86_400_000; +const PRIVATE = /^(10\.|127\.|0\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/; + +export interface IpEntry { key: string; ip: unknown; at?: string | null; count?: number; signup?: boolean } + +/** + * Works out, for every member of one old site: + * - network: countries from sign-ins in the last RECENT_YEARS years only. + * - sharedSignup: how many accounts signed up from the same address within 30 days of theirs (3+ looks like a farm). + * Addresses used by 10+ accounts over more than half a year are treated as the old site's own servers, + * a proxy or a big shared network, and ignored for both. The addresses themselves are not returned. + */ +export function deriveNetworks(entries: IpEntry[], intel: LocalIpIntel, now: Date) { + const rows = entries.map((e) => ({ ...e, ip: ipFromLegacy(e.ip) })).filter((e): e is IpEntry & { ip: string } => !!e.ip && isIP(e.ip) > 0 && !PRIVATE.test(e.ip)); + const byIp = new Map; first: string; last: string }>(); + for (const r of rows) { + const at = r.at ?? ''; + const cur = byIp.get(r.ip) ?? { keys: new Set(), first: at || '9', last: at }; + cur.keys.add(r.key); + if (at && at < cur.first) cur.first = at; + if (at > cur.last) cur.last = at; + byIp.set(r.ip, cur); + } + const shared = new Set(); + for (const [ip, v] of byIp) if (v.keys.size >= 10 && Date.parse(v.last) - Date.parse(v.first) > 180 * DAY) shared.add(ip); + + const since = new Date(now.getTime() - RECENT_YEARS * 365 * DAY).toISOString(); + const recent = new Map(); + const keys = new Set(rows.map((r) => r.key)); + for (const r of rows) { + if (shared.has(r.ip) || !r.at || r.at < since) continue; + (recent.get(r.key) ?? recent.set(r.key, []).get(r.key)!).push(r); + } + const networks = new Map(); + for (const [k, list] of recent) { const n = networkFromHistory(list, intel); if (n) networks.set(k, n); } + + // sign-up farms: several accounts made from one address within a month + const signups = new Map(); + for (const r of rows) if (r.signup && r.at && !shared.has(r.ip)) (signups.get(r.ip) ?? signups.set(r.ip, []).get(r.ip)!).push({ key: r.key, t: Date.parse(r.at) }); + const sharedSignup = new Map(); + for (const list of signups.values()) { + if (list.length < 3) continue; + for (const a of list) { + const n = list.filter((b) => Math.abs(b.t - a.t) <= 30 * DAY).length; + if (n >= 3) sharedSignup.set(a.key, Math.max(n, sharedSignup.get(a.key) ?? 0)); + } + } + const withOld = [...keys].filter((k) => !networks.has(k)).length; + return { networks, sharedSignup, sharedAddresses: shared.size, membersOnlyOldOrShared: withOld }; +} diff --git a/apps/api/src/import/skadate.ts b/apps/api/src/import/skadate.ts index 8494910..6cc13dc 100644 --- a/apps/api/src/import/skadate.ts +++ b/apps/api/src/import/skadate.ts @@ -8,7 +8,7 @@ import { readdir, readFile, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { normalizeImage } from '../photos'; import type { LocalIpIntel } from '../ipintel'; -import { networkFromHistory } from './network'; +import { deriveNetworks, RECENT_YEARS } from './network'; import { bump, type BundleInfo, type SrcMember, type SrcPhoto, type SrcRelation, photoPath, prepareBundleDir, writeBundle } from './bundle'; import { countBundle } from './legacy'; import { @@ -125,11 +125,15 @@ export async function extractSkadate(url: string, outDir: string, opts: { photos if (opts.ipIntel?.ready) { let rows: { id: number; joinIp: unknown; joinStamp: number }[] = []; try { rows = await q(`SELECT id, joinIp, joinStamp FROM ow_base_user`); } catch { bump(info.skipped, 'sign-in country check (no joinIp column)'); } + const d = deriveNetworks(rows.map((r) => ({ key: 'skadate:' + r.id, ip: r.joinIp, at: r.joinStamp ? new Date(r.joinStamp * 1000).toISOString() : null, signup: true })), opts.ipIntel, new Date()); + bump(info.counts, 'addresses ignored as shared (old servers, proxies)', d.sharedAddresses); for (const r of rows) { const m = byId.get(Number(r.id)); if (!m) continue; - const n = networkFromHistory([{ ip: r.joinIp, at: r.joinStamp ? new Date(r.joinStamp * 1000).toISOString() : null }], opts.ipIntel); - if (n) { m.network = n; bump(info.counts, 'members with sign-in countries'); } else bump(info.counts, 'members with no sign-in IP to check'); + const n = d.networks.get('skadate:' + r.id); + if (n) { m.network = n; bump(info.counts, `members with sign-ins in the last ${RECENT_YEARS} years`); } else bump(info.counts, `members with no sign-in in the last ${RECENT_YEARS} years (not placed)`); + const s = d.sharedSignup.get('skadate:' + r.id); + if (s) { m.sharedSignup = s; bump(info.counts, 'members who signed up from an address shared with 2+ others that month'); } } } else bump(info.skipped, 'sign-in country check (IP database not loaded)'); @@ -177,7 +181,7 @@ export async function extractSkadate(url: string, outDir: string, opts: { photos relations.push({ type: 'message', id: 'skadate-' + r.id, from: key(r.senderId), to: key(r.recipientId), at: isoDate(Number(r.timeStamp))!, body, read: !!r.recipientRead }); } - info.counts = countBundle(members, relations); + info.counts = { ...info.counts, ...countBundle(members, relations) }; // keeps the sign-in check's counts await writeBundle(outDir, info, members, relations); return info; } finally { diff --git a/apps/api/src/ipintel.ts b/apps/api/src/ipintel.ts index d77b8a3..926ab7b 100644 --- a/apps/api/src/ipintel.ts +++ b/apps/api/src/ipintel.ts @@ -9,7 +9,7 @@ import { gunzipSync } from 'node:zlib'; import { isIP } from 'node:net'; import { Reader, type AsnResponse, type CountryResponse } from 'mmdb-lib'; -import { isHostingNetwork, type IpIntel, type NetworkInfo } from '@whatbox/core'; +import { isHostingNetwork, isRelayNetwork, type IpIntel, type NetworkInfo } from '@whatbox/core'; import { config } from './config'; type CountryRec = CountryResponse; @@ -93,9 +93,11 @@ export class LocalIpIntel implements IpIntel { if (a?.autonomous_system_number) { out.asn = a.autonomous_system_number; out.org = a.autonomous_system_organization?.slice(0, 80); - out.hosting = isHostingNetwork(out.asn, out.org); + if (isRelayNetwork(out.asn, out.org)) out.relay = true; + else out.hosting = isHostingNetwork(out.asn, out.org); } } catch { /* ignore */ } + if (out.relay) delete out.country; // the relay's location, not the member's if (this.tor.has(ip)) out.tor = true; return out.country || out.asn || out.tor ? out : null; } diff --git a/apps/api/src/pg-repo.ts b/apps/api/src/pg-repo.ts index 9c85a50..c6dea53 100644 --- a/apps/api/src/pg-repo.ts +++ b/apps/api/src/pg-repo.ts @@ -395,12 +395,17 @@ export class PgSiteRepo implements SiteRepo { const r = await this.db.query(`SELECT DISTINCT doc->>'memberId' AS member_id, doc->>'kind' AS kind FROM moderation WHERE status='pending' AND coalesce(doc->>'memberId','') <> ''`); return r.rows.map((x: any) => ({ memberId: x.member_id as string, kind: x.kind as string })); } - async listModeration(status: ReviewStatus | 'all') { - const r = status === 'all' - ? await this.db.query('SELECT doc FROM moderation ORDER BY created_at DESC LIMIT 200') - : await this.db.query('SELECT doc FROM moderation WHERE status=$1 ORDER BY created_at DESC LIMIT 200', [status]); + async listModeration(status: ReviewStatus | 'all', opts: { kind?: string; confidence?: string; limit?: number } = {}) { + const r = await this.db.query( + `SELECT doc FROM moderation WHERE ($1::text = 'all' OR status = $1) AND ($2::text IS NULL OR doc->>'kind' = $2) + AND ($3::text IS NULL OR coalesce(doc->>'confidence', '') = $3) ORDER BY created_at DESC LIMIT $4`, + [status, opts.kind ?? null, opts.confidence ?? null, Math.min(Math.max(1, opts.limit ?? 200), 1000)]); return docs(r.rows); } + async countPendingByConfidence(kind: string) { + const r = await this.db.query(`SELECT coalesce(doc->>'confidence', '') c, count(*)::int n FROM moderation WHERE status='pending' AND doc->>'kind'=$1 GROUP BY 1`, [kind]); + return Object.fromEntries(r.rows.map((x: any) => [x.c as string, x.n as number])); + } // ---- events async listEvents() { return docs((await this.db.query('SELECT doc FROM events ORDER BY starts_at')).rows); } diff --git a/apps/api/test/network.test.ts b/apps/api/test/network.test.ts new file mode 100644 index 0000000..8dc0343 --- /dev/null +++ b/apps/api/test/network.test.ts @@ -0,0 +1,40 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { deriveNetworks, ipFromLegacy } from '../src/import/network'; +import type { LocalIpIntel } from '../src/ipintel'; + +const COUNTRY: Record = { '73.0.0.': 'US', '102.89.0.': 'NG', '74.82.64.': 'CA', '9.9.9.': 'US' }; +const intel = { lookup: (ip: string) => { const k = Object.keys(COUNTRY).find((p) => ip.startsWith(p)); return k ? { country: COUNTRY[k] } : null; } } as unknown as LocalIpIntel; +const now = new Date('2026-11-28T00:00:00Z'); + +test('only recent sign-ins are placed; old ones are not, so reassigned addresses cannot flag anyone', () => { + const d = deriveNetworks([ + { key: 'a', ip: '74.82.64.10', at: '2011-05-01T00:00:00Z' }, // an old BlackBerry-era address + { key: 'a', ip: '73.0.0.5', at: '2025-02-01T00:00:00Z' }, + { key: 'b', ip: '74.82.64.11', at: '2012-01-01T00:00:00Z' }, + { key: 'c', ip: '102.89.0.4', at: '2026-10-01T00:00:00Z', count: 3 }, + { key: 'd', ip: '192.168.0.4', at: '2026-10-01T00:00:00Z' }, + ], intel, now); + assert.deepEqual(d.networks.get('a')?.countries.map((c) => c.code), ['US']); + assert.equal(d.networks.get('b'), undefined); + assert.equal(d.networks.get('c')?.countries[0].count, 3); + assert.equal(d.networks.get('d'), undefined); +}); + +test('an address many accounts used over years is ignored; several sign-ups in one month are a cluster', () => { + const entries = []; + for (let i = 0; i < 12; i++) entries.push({ key: 'm' + i, ip: '9.9.9.9', at: new Date(Date.UTC(2024 + (i % 2), i, 1)).toISOString(), signup: true }); + for (const k of ['x', 'y', 'z']) entries.push({ key: k, ip: '73.0.0.77', at: '2026-03-0' + (k === 'x' ? 1 : k === 'y' ? 5 : 9) + 'T00:00:00Z', signup: true }); + entries.push({ key: 'w', ip: '73.0.0.77', at: '2025-01-01T00:00:00Z', signup: true }); // a year earlier: not part of it + const d = deriveNetworks(entries, intel, now); + assert.equal(d.sharedAddresses, 1); + assert.equal(d.networks.get('m0'), undefined); + assert.equal(d.sharedSignup.get('m0'), undefined); + assert.equal(d.sharedSignup.get('x'), 3); + assert.equal(d.sharedSignup.get('w'), undefined); +}); + +test('numeric addresses from MySQL are converted', () => { + assert.equal(ipFromLegacy(1249763329), '74.125.224.1'); + assert.equal(ipFromLegacy(0), null); +}); diff --git a/apps/member/src/app/admin/index.tsx b/apps/member/src/app/admin/index.tsx index 1da9661..329dcff 100644 --- a/apps/member/src/app/admin/index.tsx +++ b/apps/member/src/app/admin/index.tsx @@ -264,7 +264,14 @@ function Moderation({ api, siteId, niche, onChange }: { api: AdminApi; siteId: s const [suspendFor, setSuspendFor] = useState(null); const [nicheRun, setNicheRun] = useState<{ busy: boolean; note?: string }>({ busy: false }); const [openId, setOpenId] = useState(null); - const load = useCallback(() => { setItems(null); api.moderation(siteId, status).then(setItems); }, [api, siteId, status]); + // Possible scammers can run into the hundreds after the old-site check, so they get their own view by confidence + const [bucket, setBucket] = useState<'' | Bucket>(''); + const [buckets, setBuckets] = useState | null>(null); + const load = useCallback(() => { + setItems(null); + api.moderation(siteId, status, bucket ? { kind: 'risk', confidence: bucket } : undefined).then(setItems); + api.riskBuckets(siteId).then(setBuckets, () => setBuckets(null)); + }, [api, siteId, status, bucket]); useEffect(() => { load(); }, [load]); const decide = async (id: string, d: ModerationDecision, text?: string) => { await api.decide(siteId, id, d, text); load(); onChange(); }; const labels: Record = { @@ -299,6 +306,9 @@ function Moderation({ api, siteId, niche, onChange }: { api: AdminApi; siteId: s setStatus('pending')} /> setStatus('all')} /> + {buckets && (buckets.high + buckets.medium + buckets.low + buckets.unsorted) > 0 ? ( + { load(); onChange(); }} /> + ) : null} {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. @@ -330,6 +340,7 @@ function Moderation({ api, siteId, niche, onChange }: { api: AdminApi; siteId: s {labels[i.kind][0]} {i.kind === 'report' || i.kind === 'member' ? 'about' : i.kind === 'email' ? 'for' : 'from'} {i.memberName} ยท {relTime(i.createdAt)} {i.status !== 'pending' ? : null} + {i.kind === 'risk' && i.confidence ? : null} {i.messageBody ? "{i.messageBody}" : null} {i.kind === 'profile' && i.profileText !== undefined @@ -383,8 +394,66 @@ function Moderation({ api, siteId, niche, onChange }: { api: AdminApi; siteId: s ); } +type Bucket = 'high' | 'medium' | 'low'; +const BUCKET_LABEL: Record = { high: 'High', medium: 'Medium', low: 'Low' }; +const BUCKET_HELP: Record = { + high: 'Several signs together, e.g. signs in from another country plus a random username or scam wording.', + medium: 'Two signs, e.g. another country through a VPN, or a shared sign-up address.', + low: 'One sign on its own, e.g. only another country or only a random-looking username. Most likely to be honest members.', +}; + +/** Possible scammers grouped by how sure the scoring is, with one-click decisions for a whole group. */ +function ScamBuckets({ api, siteId, buckets, bucket, setBucket, onDone }: { + api: AdminApi; siteId: string; buckets: Record; bucket: '' | Bucket; setBucket: (b: '' | Bucket) => void; onDone: () => void; +}) { + const [confirm, setConfirm] = useState<'approve' | 'reject' | null>(null); + const [busy, setBusy] = useState(false); + const [note, setNote] = useState<{ tone: 'success' | 'error'; text: string } | null>(null); + useEffect(() => { setConfirm(null); }, [bucket]); + const n = bucket ? buckets[bucket] : 0; + const run = async (d: 'approve' | 'reject') => { + if (!bucket) return; + setBusy(true); setNote(null); + try { + const r = await api.bulkRisk(siteId, bucket, d, n); + setNote({ tone: 'success', text: d === 'approve' ? `Marked ${r.done} as fine.` : `Suspended ${r.done} accounts.` }); + setConfirm(null); onDone(); + } catch (e) { setNote({ tone: 'error', text: e instanceof ApiError ? e.message : 'That did not work.' }); } + setBusy(false); + }; + return ( + + Possible scammers: {buckets.high + buckets.medium + buckets.low + buckets.unsorted} waiting + + setBucket('')} /> + {(['high', 'medium', 'low'] as Bucket[]).map((b) => setBucket(b)} />)} + + {bucket ? ( + <> + {BUCKET_HELP[bucket]} Look through some of them first; the buttons act on all {n}. + {n > 0 ? ( + confirm ? ( + + {confirm === 'approve' ? (n === 1 ? 'Mark this 1 as fine?' : `Mark all ${n} as fine?`) : `${n === 1 ? 'Suspend this 1 account' : `Suspend all ${n} accounts`}? They can't sign in until reinstated.`} + run(confirm)} /> + setConfirm(null)} /> + + ) : ( + + setConfirm('approve')} /> + setConfirm('reject')} /> + + ) + ) : null} + + ) : Pick a group to see only those members and decide them together.} + {note ? {note.text} : null} + + ); +} + const RISK_BADGE: Record = { - country_mismatch: 'Location mismatch', tor: 'Tor', hosting: 'VPN or hosting', dropped_i: 'Dropped "I"', spelling: 'British spelling', scam_phrases: 'Scam wording', + country_mismatch: 'Location mismatch', scam_hub: 'Scam-hub country', shared_signup: 'Shared sign-up address', random_name: 'Random username', tor: 'Tor', hosting: 'VPN or hosting', dropped_i: 'Dropped "I"', spelling: 'British spelling', scam_phrases: 'Scam wording', }; /** Hints from where a member signs in. They are for a person to judge; nothing is blocked automatically. */ diff --git a/packages/core/src/api.ts b/packages/core/src/api.ts index b72c913..89b9fd1 100644 --- a/packages/core/src/api.ts +++ b/packages/core/src/api.ts @@ -90,7 +90,11 @@ export interface AdminApi { dashboard(siteId: string, days: number): Promise; /** The same, added up over every site this admin may see. */ dashboardAll(days: number): Promise; - moderation(siteId: string, status: 'pending' | 'approved' | 'rejected' | 'all'): Promise; + moderation(siteId: string, status: 'pending' | 'approved' | 'rejected' | 'all', opts?: { kind?: string; confidence?: string }): Promise; + /** Waiting possible-scammer items by confidence. */ + riskBuckets(siteId: string): Promise>; + /** Looks fine (approve) or suspend (reject) every waiting possible-scammer item in one bucket. expected = the count the admin saw. */ + bulkRisk(siteId: string, confidence: 'high' | 'medium' | 'low', decision: 'approve' | 'reject', expected: number): Promise<{ done: number; buckets: Record<'high' | 'medium' | 'low' | 'unsorted', number> }>; 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[] }>; @@ -217,7 +221,9 @@ export function createLocalAdminApi(platform: Platform): AdminApi { stats: (s) => wrap(async () => platform.adminStats(await admin(), s)), dashboard: (s, d) => wrap(async () => platform.adminDashboard(await admin(), s, d)), dashboardAll: (d) => wrap(async () => platform.adminDashboardAll(await admin(), d)), - moderation: (s, st) => wrap(async () => platform.adminModeration(await admin(), s, st)), + moderation: (s, st, o) => wrap(async () => platform.adminModeration(await admin(), s, st, o)), + riskBuckets: (s) => wrap(async () => platform.adminRiskBuckets(await admin(), s)), + bulkRisk: (s, c, d, n) => wrap(async () => platform.adminBulkRisk(await admin(), s, c, d, n)), decide: (s, i, d, text) => wrap(async () => platform.adminDecide(await admin(), s, i, d, text)), recheckModeration: (s) => wrap(async () => platform.adminRecheckModeration(await admin(), s)), runNicheChecks: (s) => wrap(async () => platform.adminRunNicheChecks(await admin(), s)), diff --git a/packages/core/src/demo-analytics.ts b/packages/core/src/demo-analytics.ts index 885ef8b..aef242d 100644 --- a/packages/core/src/demo-analytics.ts +++ b/packages/core/src/demo-analytics.ts @@ -2,7 +2,7 @@ import { addDays, utcDay } from './analytics'; import type { SiteRepo } from './repo'; import type { Site } from './types'; -import { riskFlags, riskReasons } from './network-risk'; +import { riskConfidence, riskFlags, riskReasons } from './network-risk'; function rng(seed: number) { let x = seed || 1; @@ -53,5 +53,5 @@ export async function seedDemoRisk(repo: SiteRepo, now: Date, memberId: string | const id = 'mod_demo_risk'; m.risk = { openItemId: id }; await repo.saveMember(m); - await repo.saveModeration({ id, kind: 'risk', refId: m.id, memberId: m.id, summary: flags.map((f) => f.text).join(' '), reasons: riskReasons(all), status: 'pending', createdAt: at }); + await repo.saveModeration({ id, kind: 'risk', refId: m.id, memberId: m.id, summary: flags.map((f) => f.text).join(' '), reasons: riskReasons(all), confidence: riskConfidence(all) ?? 'low', status: 'pending', createdAt: at }); } diff --git a/packages/core/src/http-client.ts b/packages/core/src/http-client.ts index 5420b6a..d05b4e1 100644 --- a/packages/core/src/http-client.ts +++ b/packages/core/src/http-client.ts @@ -153,7 +153,9 @@ export function createHttpAdminApi(baseUrl: string): AdminApi { stats: (id) => req('GET', s(id) + '/stats'), dashboard: (id, days) => req('GET', s(id) + '/dashboard?days=' + days), dashboardAll: (days) => req('GET', '/v1/admin/dashboard?days=' + days), - moderation: (id, status) => req('GET', s(id) + '/moderation?status=' + status), + moderation: (id, status, o) => req('GET', s(id) + '/moderation?status=' + status + (o?.kind ? '&kind=' + encodeURIComponent(o.kind) : '') + (o?.confidence ? '&confidence=' + encodeURIComponent(o.confidence) : '')), + riskBuckets: (id) => req('GET', s(id) + '/moderation-risk'), + bulkRisk: (id, confidence, decision, expected) => req('POST', s(id) + '/moderation-risk', { confidence, decision, expected }), decide: (id, item, decision, text) => req('POST', s(id) + '/moderation/' + item, { decision, text }), recheckModeration: (id) => req('POST', s(id) + '/moderation-recheck', {}), runNicheChecks: (id) => req('POST', s(id) + '/niche-checks', {}), diff --git a/packages/core/src/memory-repo.ts b/packages/core/src/memory-repo.ts index 020f50f..b575858 100644 --- a/packages/core/src/memory-repo.ts +++ b/packages/core/src/memory-repo.ts @@ -311,13 +311,19 @@ export class MemorySiteRepo implements SiteRepo { 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); } - async listModeration(status: ReviewStatus | 'all') { + async listModeration(status: ReviewStatus | 'all', opts: { kind?: string; confidence?: string; limit?: number } = {}) { return clone( this.d.moderation - .filter((m) => status === 'all' || m.status === status) - .sort((a, b) => b.createdAt.localeCompare(a.createdAt)), + .filter((m) => (status === 'all' || m.status === status) && (!opts.kind || m.kind === opts.kind) && (opts.confidence === undefined || (m.confidence ?? '') === opts.confidence)) + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)) + .slice(0, opts.limit ?? 200), ); } + async countPendingByConfidence(kind: string) { + const out: Record = {}; + for (const m of this.d.moderation) if (m.status === 'pending' && m.kind === kind) out[m.confidence ?? ''] = (out[m.confidence ?? ''] ?? 0) + 1; + return out; + } async listEvents() { return clone(this.d.events!); } async getEvent(id: string) { return clone(this.d.events!.find((e) => e.id === id) ?? null); } diff --git a/packages/core/src/network-risk.ts b/packages/core/src/network-risk.ts index acb6e2a..006f064 100644 --- a/packages/core/src/network-risk.ts +++ b/packages/core/src/network-risk.ts @@ -16,6 +16,9 @@ export interface NetworkInfo { org?: string; // network owner, e.g. "Comcast Cable" or "M247 Europe SRL" hosting?: boolean; // a datacenter or VPN provider rather than a home or mobile connection tor?: boolean; // a Tor exit node + /** A relay that hides where someone really is without being a VPN (BlackBerry's and AOL's old proxies, + * iCloud Private Relay, Cloudflare WARP). Its country says nothing about the member, so it is ignored. */ + relay?: boolean; } export interface IpIntel { @@ -32,8 +35,29 @@ export interface MemberNetwork { torAt?: string; } -export type RiskCode = 'country_mismatch' | 'tor' | 'hosting' | 'dropped_i' | 'spelling' | 'scam_phrases'; +export type RiskCode = 'country_mismatch' | 'scam_hub' | 'tor' | 'hosting' | 'shared_signup' | 'random_name' | 'dropped_i' | 'spelling' | 'scam_phrases'; export interface RiskFlag { code: RiskCode; text: string; /** true when it goes to the moderation queue */ review: boolean } +export type RiskConfidence = 'high' | 'medium' | 'low'; + +/** What the scoring looks at. A Member fits; the import adds what it found in the old site's logs. */ +export type RiskInput = Pick & { + about?: string; + displayName?: string; + imported?: { sources: string[] }; + /** Accounts (including this one) that signed up from the same address within a few weeks: a bot-farm sign. */ + risk?: { sharedSignup?: number }; +}; + +/** How much each hint counts. 2 or more goes to the queue; 4+ is high confidence, 3 medium, 2 low. */ +const WEIGHT: Record = { + country_mismatch: 2, scam_hub: 1, tor: 2, shared_signup: 3, random_name: 2, hosting: 1, dropped_i: 1, spelling: 1, scam_phrases: 1, +}; +export const REVIEW_SCORE = 2; +export function riskScore(flags: RiskFlag[]): number { return flags.reduce((n, f) => n + WEIGHT[f.code], 0); } +export function riskConfidence(flags: RiskFlag[]): RiskConfidence | null { + const n = riskScore(flags); + return n >= 4 ? 'high' : n === 3 ? 'medium' : n >= REVIEW_SCORE ? 'low' : null; +} const MAX_COUNTRIES = 5; /** Sign-in history older than this is dropped, so the record doesn't become a travel log. */ @@ -70,6 +94,10 @@ export function pruneNetwork(n: MemberNetwork | undefined, now: Date): MemberNet } const name = (code: string) => countryName(code); +/** Puerto Rico, Guam and the other US territories count as the US. */ +const US_TERRITORIES = new Set(['US', 'PR', 'GU', 'VI', 'AS', 'MP', 'UM']); +/** Countries most romance scams are run from (FBI and FTC reports). Only counted on top of a mismatch. */ +const SCAM_HUBS = new Set(['NG', 'GH', 'TG', 'BJ', 'CI', 'CM', 'SN']); const list = (codes: string[]) => codes.length <= 1 ? codes.map(name).join('') : codes.slice(0, -1).map(name).join(', ') + ' and ' + name(codes[codes.length - 1]); /** @@ -79,25 +107,59 @@ const list = (codes: string[]) => codes.length <= 1 ? codes.map(name).join('') : * - tor: signed in over Tor, which hides where someone is. Goes to review. * - hosting: signed in from a datacenter or VPN network. Shown on the member only, since plenty of honest people use a VPN. */ -export function riskFlags(m: Pick & { about?: string }): RiskFlag[] { - const out: RiskFlag[] = [...networkFlags(m), ...writingFlags(m.about ?? '', m.country)]; - // Scored together: a sign-in mismatch or Tor goes to review on its own; writing hints need a second - // hint (another writing hint, or a VPN/hosting network) before they do. A single one stays a note. - const strong = out.some((f) => f.code === 'country_mismatch' || f.code === 'tor'); - const weak = out.filter((f) => TEXT_CODES.has(f.code) || f.code === 'hosting').length; - for (const f of out) if (TEXT_CODES.has(f.code)) f.review = strong || weak >= 2; +export function riskFlags(m: RiskInput): RiskFlag[] { + const out: RiskFlag[] = [...networkFlags(m), ...nameFlags(m), ...writingFlags(m.about ?? '', m.country)]; + // Scored together (WEIGHT): a mismatch, Tor, a random name or a shared sign-up address goes to review on + // its own; a VPN or a writing hint needs a second hint before it does. Below that they stay notes. + const review = riskScore(out) >= REVIEW_SCORE; + for (const f of out) f.review = review; + return out; +} + +function nameFlags(m: RiskInput): RiskFlag[] { + const out: RiskFlag[] = []; + const n = m.risk?.sharedSignup ?? 0; + if (n >= 3) out.push({ code: 'shared_signup', review: true, text: `Signed up from the same network address as ${n - 1} other accounts within a few weeks, a common sign of a bot or scam farm.` }); + // SkaDate made up random usernames for real members, so its accounts are skipped + if (m.displayName && !m.imported?.sources.includes('skadate')) { + const why = randomName(m.displayName); + if (why) out.push({ code: 'random_name', review: true, text: `Username "${m.displayName}" looks like ${why}, typical of made-up or bot accounts.` }); + } return out; } +const KEY_ROWS = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']; +const SLANG = new Set(['ssbbw', 'bbw', 'bbbw', 'sbbw', 'mstr', 'nyc', 'ltr', 'fwb']); +/** "xkqzjwp", "a8f3k2d9", "asdfgh": random letters and numbers rather than a name or a word. Returns why, or null. */ +export function randomName(name: string): string | null { + const s = name.replace(/[^A-Za-z0-9]/g, ''); + const low = s.toLowerCase(); + if (low.length < 5) return null; + const core = low.replace(/\d+$/, ''); + if ((core.match(/[a-z]\d|\d[a-z]/g) ?? []).length >= 3) return 'random letters and numbers'; + if (/([a-z])\1{4,}/.test(low)) return 'one key held down'; + for (const r of KEY_ROWS) for (let i = 0; i + 4 <= r.length; i++) if (low.includes(r.slice(i, i + 4))) return 'keyboard mashing'; + for (const raw of s.replace(/\d/g, ' ').match(/[A-Z]?[a-z]+|[A-Z]+(?![a-z])/g) ?? []) { + const t = raw.toLowerCase(); + if (SLANG.has(t)) continue; + if (t.length >= 5 && !/[aeiouy]/.test(t)) return 'random letters'; + if (/[bcdfghjklmnpqrstvwxz]{6,}/.test(t)) return 'random letters'; + } + return null; +} + function networkFlags(m: Pick): RiskFlag[] { const n = m.network; if (!n) return []; const out: RiskFlag[] = []; const seen = n.countries.map((c) => c.code); const stated = (m.country ?? '').toUpperCase(); - if (stated && seen.length && !seen.includes(stated)) { + const home = (c: string) => (US_TERRITORIES.has(c) ? 'US' : c); + if (stated && seen.length && !seen.some((c) => home(c) === home(stated))) { const via = n.hosting ? ` (through ${n.hosting.org}, so possibly a VPN)` : ''; out.push({ code: 'country_mismatch', review: true, text: `Signs in from ${list(seen)}${via}, but their profile says ${name(stated)}.` }); + const hubs = seen.filter((c) => SCAM_HUBS.has(c)); + if (hubs.length) out.push({ code: 'scam_hub', review: true, text: `${list(hubs)} ${hubs.length > 1 ? 'are' : 'is'} where many romance scams are run from.` }); } if (n.torAt) out.push({ code: 'tor', review: true, text: 'Signed in over Tor, which hides where they really are.' }); if (n.hosting) out.push({ code: 'hosting', review: false, text: `Signed in from a hosting or VPN network (${n.hosting.org}). Common for bots, but many honest people use a VPN.` }); @@ -107,7 +169,6 @@ function networkFlags(m: Pick): RiskFlag[] { // ---------------- Writing hints (profile text) ---------------- // Jeff's experience from running the old sites: scam profiles written outside the country they claim // give themselves away in small ways. These are hints for a person to judge, never proof. -const TEXT_CODES = new Set(['dropped_i', 'spelling', 'scam_phrases']); /** "Am a caring man", "am from Texas": the "I" dropped at the start of a sentence. "Am I ..." is a question, not this. */ const DROPPED_I = /(?:^|[.!?\n]\s*)am\s+(?!i\b)(a|an|the|from|here|looking|single|simple|honest|new|very|so|just|seeking|caring|loving|kind|easy|god|widow|widowed|divorced|currently|working|living|presently|\w+ing)\b/i; @@ -144,13 +205,13 @@ export function writingFlags(about: string, country?: string): RiskFlag[] { } const REASON: Record = { - country_mismatch: 'country mismatch', tor: 'Tor', hosting: 'VPN or hosting', dropped_i: 'dropped "I"', spelling: 'British spelling', scam_phrases: 'scam wording', + country_mismatch: 'country mismatch', scam_hub: 'scam-hub country', tor: 'Tor', hosting: 'VPN or hosting', shared_signup: 'shared sign-up address', random_name: 'random username', dropped_i: 'dropped "I"', spelling: 'British spelling', scam_phrases: 'scam wording', }; /** Short labels for the moderation queue's reason chips. */ export function riskReasons(flags: RiskFlag[]): string[] { return flags.map((f) => REASON[f.code]); } /** Identifies the set of review flags, so "Looks fine" quiets these and a new kind of flag (or a new country) raises it again. */ -export function riskKey(m: Pick & { about?: string }): string { +export function riskKey(m: RiskInput): string { const f = riskFlags(m).filter((x) => x.review); if (!f.length) return ''; const countries = f.some((x) => x.code === 'country_mismatch') ? (m.network?.countries ?? []).map((c) => c.code).sort().join(',') : ''; @@ -203,7 +264,20 @@ export const HOSTING_ASNS = new Set([ 9370, 2519, // Sakura Internet, Arteria (JP hosting) ]); -const HOSTING_ORG = /\b(hosting|host|server|servers|datacenter|data ?center|data-center|cloud|colo|colocation|vps|dedicated|vpn|proxy|m247|datacamp|cdn77|digitalocean|linode|vultr|choopa|ovh|hetzner|contabo|leaseweb|amazon|aws|azure|google cloud|oracle cloud|alibaba|tencent cloud|scaleway|packethub|tefincom|mullvad|nordvpn|expressvpn|surfshark|private internet access|ipvanish|hide\.me|windscribe|protonvpn|proton ag)\b/i; +const HOSTING_ORG = /\b(hosting|host|server|servers|datacenter|data ?center|data-center|cloud|colo|colocation|vps|dedicated|vpn|proxy|m247|datacamp|cdn77|digitalocean|linode|vultr|choopa|ovh|hetzner|contabo|leaseweb|amazon|aws|azure|google cloud|oracle cloud|alibaba|tencent cloud|scaleway|packethub|tefincom|mullvad|nordvpn|expressvpn|surfshark|private internet access|ipvanish|hide\.me|windscribe|protonvpn|proton ag|oxylabs|bright data|luminati|smartproxy|iproyal)\b/i; + +// Relays: the address belongs to the relay, not to the member's location. +export const RELAY_ASNS = new Set([ + 18705, 13340, // BlackBerry (all BlackBerry phone traffic went through its servers in Canada) + 1668, // AOL (dial-up and AOL browser proxies) + 13335, // Cloudflare (WARP and iCloud Private Relay) + 36183, // Akamai (iCloud Private Relay) +]); +const RELAY_ORG = /\b(blackberry|research in motion|america online|aol)\b|private relay/i; +export function isRelayNetwork(asn: number | undefined, org: string | undefined): boolean { + if (asn && RELAY_ASNS.has(asn)) return true; + return !!org && RELAY_ORG.test(org); +} /** True when the network looks like a datacenter, cloud or VPN provider. */ export function isHostingNetwork(asn: number | undefined, org: string | undefined): boolean { diff --git a/packages/core/src/repo.ts b/packages/core/src/repo.ts index 41c81ee..d693394 100644 --- a/packages/core/src/repo.ts +++ b/packages/core/src/repo.ts @@ -112,7 +112,10 @@ export interface SiteRepo { listReportsAbout(targetId: string): Promise; saveModeration(item: ModerationItem): Promise; getModeration(id: string): Promise; - listModeration(status: ReviewStatus | 'all'): Promise; + /** Newest first, at most 200 (or limit). kind/confidence narrow it to one kind of item or one confidence bucket. */ + listModeration(status: ReviewStatus | 'all', opts?: { kind?: string; confidence?: string; limit?: number }): Promise; + /** Waiting items of one kind, counted by confidence ('' for none). */ + countPendingByConfidence(kind: string): Promise>; // Members with something waiting in the moderation queue (all of them, not just the first page), by kind. pendingModerationMembers(): Promise<{ memberId: string; kind: string }[]>; diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts index 105db60..45c3157 100644 --- a/packages/core/src/services.ts +++ b/packages/core/src/services.ts @@ -3,7 +3,7 @@ import { LocalEventHub } from './events'; import { DevKeyProvider, hmacHex, type KeyProvider, randomCode, randomId, SiteCrypto } from './crypto'; import { builtinGeo, countryName, unitsForCountry } from './geo'; -import { type IpIntel, noteSignIn, riskFlags, riskKey, riskReasons } from './network-risk'; +import { type IpIntel, noteSignIn, riskConfidence, riskFlags, riskKey, riskReasons, type RiskConfidence } from './network-risk'; import { memberFlags, type NicheFlag, outsideNiche, textFlags } from './niche'; import { agesOf, couplesOn, coupleMix, fieldValues, fitsAges, isCouple, seeks } from './couples'; import { @@ -282,12 +282,13 @@ export class Platform { const open = member.risk?.openItemId ? await repo.getModeration(member.risk.openItemId) : null; const reasons = riskReasons(all); const summary = flags.map((f) => f.text).join(' '); + const confidence = riskConfidence(all) ?? 'low'; if (open && open.status === 'pending') { - if (open.summary !== summary) await repo.saveModeration({ ...open, summary, reasons }); + if (open.summary !== summary || open.confidence !== confidence) await repo.saveModeration({ ...open, summary, reasons, confidence }); return; } const id = randomId('mod_'); - await repo.saveModeration({ id, kind: 'risk', refId: member.id, memberId: member.id, summary, reasons, status: 'pending', createdAt: this.iso() }); + await repo.saveModeration({ id, kind: 'risk', refId: member.id, memberId: member.id, summary, reasons, confidence, status: 'pending', createdAt: this.iso() }); member.risk = { ...member.risk, openItemId: id }; } @@ -585,7 +586,7 @@ export class Platform { if (m.displayName && m.city && !missing.length && !partnerMissing && seeksSomeone && (m.kind !== 'couple' || isCouple(m))) m.profileComplete = true; } // Sign-up sets the country after the first sign-in, so compare again whenever it or the profile text changes. - if (patch.location || patch.postal !== undefined || patch.about !== undefined) await this.checkRisk(ctx.site, ctx.repo, m); + if (patch.location || patch.postal !== undefined || patch.about !== undefined || patch.displayName !== undefined) await this.checkRisk(ctx.site, ctx.repo, m); await ctx.repo.saveMember(m); if (nicheCheck && m.profileComplete) { for (const f of memberFlags(ctx.site, m)) await flagMember(ctx.repo, m.id, f, this.iso()); @@ -1596,10 +1597,10 @@ export class Platform { } } - async adminModeration(admin: AdminUser, siteId: string, status: 'pending' | 'approved' | 'rejected' | 'all'): Promise { + async adminModeration(admin: AdminUser, siteId: string, status: 'pending' | 'approved' | 'rejected' | 'all', opts: { kind?: string; confidence?: string } = {}): Promise { const site = await this.adminSite(admin, siteId); const repo = await this.repo(site); - const items = await repo.listModeration(status); + const items = await repo.listModeration(status, { kind: opts.kind || undefined, confidence: opts.confidence || undefined }); const members = new Map((await repo.getMembers(items.map((i) => i.memberId))).map((m) => [m.id, m])); const out: ModerationView[] = []; for (const i of items) { @@ -1620,7 +1621,11 @@ export class Platform { v.profileText = about; v.contactMatches = findContactInfo(about); } - if (i.kind === 'risk') { const m = members.get(i.memberId); v.flags = m ? riskFlags(m) : []; } + if (i.kind === 'risk') { + const m = members.get(i.memberId); + v.flags = m ? riskFlags(m) : []; + v.confidence ??= riskConfidence(v.flags) ?? 'low'; + } out.push(v); } return out; @@ -1683,6 +1688,44 @@ export class Platform { return this.adminModeration(admin, siteId, 'pending'); } + /** Waiting possible-scammer items by confidence, for the bucket chips. */ + async adminRiskBuckets(admin: AdminUser, siteId: string): Promise> { + const site = await this.adminSite(admin, siteId); + const c = await (await this.repo(site)).countPendingByConfidence('risk'); + return { high: c.high ?? 0, medium: c.medium ?? 0, low: c.low ?? 0, unsorted: c[''] ?? 0 }; + } + + /** + * One click for a whole confidence bucket of waiting possible-scammer items, after the admin has looked: + * approve = "Looks fine" for all of them; reject = suspend all of them. Only ever run by an admin's click. + */ + async adminBulkRisk(admin: AdminUser, siteId: string, confidence: RiskConfidence, decision: 'approve' | 'reject', expected?: number) { + const site = await this.adminSite(admin, siteId); + const repo = await this.repo(site); + if (!['high', 'medium', 'low'].includes(confidence)) throw new RuleError('bad_bucket', 'Choose high, medium or low.'); + if (decision !== 'approve' && decision !== 'reject') throw new RuleError('bad_decision', 'Unknown decision.'); + // the admin saw a count; refuse if the bucket grew since, so nobody is suspended unseen + const before = (await repo.countPendingByConfidence('risk'))[confidence] ?? 0; + if (expected === undefined || before > expected) throw new RuleError('bucket_changed', `This group now has ${before} members, not ${expected}. Look again before deciding.`, 409); + let done = 0; + for (let round = 0; round < 100; round++) { + const items = await repo.listModeration('pending', { kind: 'risk', confidence, limit: 500 }); + if (!items.length) break; + for (const item of items) { + const m = await repo.getMember(item.memberId); + if (m) { + const risk = { ...m.risk, openItemId: undefined, ...(decision === 'approve' ? { clearedKey: riskKey(m) } : {}) }; + await repo.saveMember({ ...m, risk, ...(decision === 'reject' && m.status === 'active' ? { status: 'suspended' as const } : {}) }); + } + await repo.saveModeration({ ...item, status: decision === 'approve' ? 'approved' : 'rejected', decidedAt: this.iso(), decidedBy: `${admin.email} (bulk)` }); + done++; + } + } + await this.audit(admin, decision === 'approve' ? 'moderation.bulk_fine' : 'moderation.bulk_suspend', site.id, undefined, `${done} possible-scammer items, ${confidence} confidence`); + this.changed(); + return { done, buckets: await this.adminRiskBuckets(admin, siteId) }; + } + /** 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.'); diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 8c2b37b..1894acc 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -289,7 +289,7 @@ export interface Member { /** Countries and network types seen at sign-in, derived from the IP with a local database. The IP is never kept. */ network?: MemberNetwork; /** Risk review state: the open moderation item, and the flags an admin last marked as fine. */ - risk?: { openItemId?: string; clearedKey?: string }; + risk?: { openItemId?: string; clearedKey?: string; /** accounts that signed up from the same address within weeks (old-site check) */ sharedSignup?: number }; createdAt: string; lastActiveAt: string; /** When contacts were last sent a safety notice about this member (sent once). */ @@ -356,6 +356,8 @@ export interface Report { export type ModerationKind = 'photo' | 'message' | 'report' | 'profile' | 'risk' | 'member' | 'email'; export interface ModerationItem { id: string; + /** Possible-scammer items: how sure the scoring is (see network-risk.ts). */ + confidence?: 'high' | 'medium' | 'low'; kind: ModerationKind; refId: string; memberId: string; // member the item is about diff --git a/packages/core/test/network-risk.test.ts b/packages/core/test/network-risk.test.ts index eb74d29..b194c46 100644 --- a/packages/core/test/network-risk.test.ts +++ b/packages/core/test/network-risk.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { createLocalAdminApi, createLocalMemberApi, createMemoryPlatform, DEMO_OWNER_EMAIL, type IpIntel, type NetworkInfo, - isHostingNetwork, noteSignIn, pruneNetwork, riskFlags, riskKey, + isHostingNetwork, isRelayNetwork, noteSignIn, pruneNetwork, randomName, riskConfidence, riskFlags, riskKey, } from '../src/index'; const NETS: Record = { @@ -38,7 +38,7 @@ test('a US profile signing in from Nigeria is flagged for review; the IP is not const items = (await admin.moderation('site_afterh', 'pending')).filter((i) => i.kind === 'risk'); assert.equal(items.length, 1); assert.match(items[0].summary, /Signs in from Nigeria, but their profile says United States/); - assert.deepEqual(items[0].reasons, ['country mismatch']); + assert.deepEqual(items[0].reasons, ['country mismatch', 'scam-hub country']); assert.equal(items[0].flags?.[0].code, 'country_mismatch'); const me = (await api.me()).member as Record; @@ -141,3 +141,51 @@ test('writing hints: dropped "I", British spelling only for US profiles, scam wo assert.ok(riskFlags(m).every((f) => f.review)); assert.notEqual(riskKey(m), ''); }); + +test('random usernames are spotted; real names, slang and SkaDate accounts are not', () => { + for (const n of ['xkqzjwp', 'a8f3k2d9', 'asdfgh22', 'Hccvvvb', 'mkldnsk']) assert.ok(randomName(n), n); + for (const n of ['mike77', 'Johnny_B', 'CuddlySSBBW585', 'kathryn066', 'sydney_b', 'Rosa', 'tcampf']) assert.equal(randomName(n), null, n); + const flags = (displayName: string, sources = ['aspnetdating']) => riskFlags({ country: 'US', displayName, imported: { sources } }).map((f) => f.code); + assert.deepEqual(flags('xkqzjwp'), ['random_name']); + assert.deepEqual(flags('xkqzjwp', ['skadate']), []); +}); + +test('confidence: one sign is low, two medium, several high; US territories count as the US', () => { + const at = '2026-11-01T00:00:00Z'; + const ng = { countries: [{ code: 'NG', count: 2, lastAt: at }] }; + assert.equal(riskConfidence(riskFlags({ country: 'US', network: { countries: [{ code: 'MX', count: 1, lastAt: at }] } })), 'low'); + assert.equal(riskConfidence(riskFlags({ country: 'US', network: ng })), 'medium'); // mismatch + scam hub + assert.equal(riskConfidence(riskFlags({ country: 'US', network: ng, displayName: 'xkqzjwp' })), 'high'); + assert.equal(riskConfidence(riskFlags({ country: 'US', risk: { sharedSignup: 4 } })), 'medium'); + assert.equal(riskConfidence(riskFlags({ country: 'US', network: { countries: [{ code: 'PR', count: 1, lastAt: at }] } })), null); + assert.equal(riskConfidence(riskFlags({ country: 'US', about: 'Am a nice guy' })), null); // one writing hint stays a note + assert.equal(isRelayNetwork(18705, 'BlackBerry Limited'), true); + assert.equal(isRelayNetwork(7922, 'Comcast Cable Communications, LLC'), false); +}); + +test('bulk decisions act on one confidence bucket only, and refuse if it grew since the admin looked', async () => { + const { mp, signIn, admin, repo } = await setup(); + const mk = async (email: string, ip: string, name: string) => { + const { token } = await signIn(email, ip); + const api = createLocalMemberApi(mp.platform, 'afterh', 'web'); + api.setToken(token); + await api.updateMe({ displayName: name, birthYear: 1985, gender: 'woman', seeking: ['man'], location: { country: 'US', postal: '80202' }, fields: { hsv_status: ['HSV-1'] } }); + }; + await mk('a1@example.com', '41.58.0.1', 'Anna'); // Ghana: mismatch + hub = medium + await mk('a2@example.com', '102.89.0.1', 'Bea'); // Nigeria: medium + await mk('a3@example.com', '193.32.249.1', 'Cleo'); // NL via VPN: mismatch + VPN = medium + await mk('a4@example.com', '102.89.0.1', 'Qzxkvbnm'); // Nigeria + random name = high + const b = await admin.riskBuckets('site_afterh'); + assert.deepEqual([b.high, b.medium, b.low], [1, 3, 0]); + const medium = await admin.moderation('site_afterh', 'pending', { kind: 'risk', confidence: 'medium' }); + assert.equal(medium.length, 3); + await assert.rejects(admin.bulkRisk('site_afterh', 'medium', 'approve', 2), /now has 3/); + const r = await admin.bulkRisk('site_afterh', 'medium', 'approve', 3); + assert.equal(r.done, 3); + assert.deepEqual([r.buckets.high, r.buckets.medium], [1, 0]); + const s = await admin.bulkRisk('site_afterh', 'high', 'reject', 1); + assert.equal(s.done, 1); + const all = (await repo.listAllMembers(500, 0)).rows; + assert.equal(all.find((m) => m.displayName === 'Qzxkvbnm')!.status, 'suspended'); + assert.equal(all.find((m) => m.displayName === 'Bea')!.status, 'active'); +});